diff --git a/examples/AutomatedTest/main.cpp b/examples/AutomatedTest/main.cpp index 8cf9d8aa..88c81ffd 100644 --- a/examples/AutomatedTest/main.cpp +++ b/examples/AutomatedTest/main.cpp @@ -28,14 +28,14 @@ static video::E_DRIVER_TYPE chooseDriver(core::stringc arg_) static inline void check(bool ok, const char *msg) { - if (!ok) - { + if (!ok) { test_fail++; device->getLogger()->log((core::stringc("FAILED TEST: ") + msg).c_str(), ELL_ERROR); } } -void run_unit_tests() { +void run_unit_tests() +{ std::cout << "Running unit tests:" << std::endl; try { test_irr_array(); @@ -72,35 +72,33 @@ int main(int argc, char *argv[]) device->setWindowCaption(L"Hello World!"); device->setResizable(true); - video::IVideoDriver* driver = device->getVideoDriver(); - scene::ISceneManager* smgr = device->getSceneManager(); - gui::IGUIEnvironment* guienv = device->getGUIEnvironment(); + video::IVideoDriver *driver = device->getVideoDriver(); + scene::ISceneManager *smgr = device->getSceneManager(); + gui::IGUIEnvironment *guienv = device->getGUIEnvironment(); - guienv->addStaticText(L"sample text", core::rect(10,10,110,22), false); + guienv->addStaticText(L"sample text", core::rect(10, 10, 110, 22), false); - gui::IGUIButton* button = guienv->addButton( - core::rect(10,30,110,30 + 32), 0, -1, L"sample button", - L"sample tooltip"); + gui::IGUIButton *button = guienv->addButton( + core::rect(10, 30, 110, 30 + 32), 0, -1, L"sample button", + L"sample tooltip"); - gui::IGUIEditBox* editbox = guienv->addEditBox(L"", - core::rect(10,70,60,70 + 16)); + gui::IGUIEditBox *editbox = guienv->addEditBox(L"", + core::rect(10, 70, 60, 70 + 16)); const io::path mediaPath = getExampleMediaPath(); auto mesh_file = device->getFileSystem()->createAndOpenFile(mediaPath + "coolguy_opt.x"); check(mesh_file, "mesh file loading"); - scene::IAnimatedMesh* mesh = smgr->getMesh(mesh_file); + scene::IAnimatedMesh *mesh = smgr->getMesh(mesh_file); check(mesh, "mesh loading"); if (mesh_file) mesh_file->drop(); - if (mesh) - { - video::ITexture* tex = driver->getTexture(mediaPath + "cooltexture.png"); + if (mesh) { + video::ITexture *tex = driver->getTexture(mediaPath + "cooltexture.png"); check(tex, "texture loading"); - scene::IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode(mesh); - if (node) - { - node->forEachMaterial([tex] (video::SMaterial &mat) { + scene::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh); + if (node) { + node->forEachMaterial([tex](video::SMaterial &mat) { mat.Lighting = false; mat.setTexture(0, tex); }); @@ -109,16 +107,14 @@ int main(int argc, char *argv[]) } } - smgr->addCameraSceneNode(0, core::vector3df(0,4,5), core::vector3df(0,2,0)); + smgr->addCameraSceneNode(0, core::vector3df(0, 4, 5), core::vector3df(0, 2, 0)); s32 n = 0; SEvent event; device->getTimer()->start(); - while (device->run()) - { - if (device->getTimer()->getTime() >= 1000) - { + while (device->run()) { + if (device->getTimer()->getTime() >= 1000) { device->getTimer()->setTime(0); ++n; if (n == 1) // Tooltip display @@ -129,8 +125,7 @@ int main(int argc, char *argv[]) event.MouseInput.X = button->getAbsolutePosition().getCenter().X; event.MouseInput.Y = button->getAbsolutePosition().getCenter().Y; device->postEventFromUser(event); - } - else if (n == 2) // Text input focus + } else if (n == 2) // Text input focus guienv->setFocus(editbox); else if (n == 3) // Keypress for Text input { @@ -142,13 +137,12 @@ int main(int argc, char *argv[]) device->postEventFromUser(event); event.KeyInput.PressedDown = false; device->postEventFromUser(event); - } - else + } else device->closeDevice(); } driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, - video::SColor(255,100,100,150)); + video::SColor(255, 100, 100, 150)); smgr->drawAll(); guienv->drawAll(); driver->endScene(); diff --git a/examples/AutomatedTest/test_array.cpp b/examples/AutomatedTest/test_array.cpp index 4c207ffe..7b2d8228 100644 --- a/examples/AutomatedTest/test_array.cpp +++ b/examples/AutomatedTest/test_array.cpp @@ -4,13 +4,14 @@ using namespace irr; using core::array; -static void test_basics() { +static void test_basics() +{ array v; - v.push_back(1); // 1 + v.push_back(1); // 1 v.push_front(2); // 2, 1 - v.insert(4, 0); // 4, 2, 1 - v.insert(3, 1); // 4, 3, 2, 1 - v.insert(0, 4); // 4, 3, 2, 1, 0 + v.insert(4, 0); // 4, 2, 1 + v.insert(3, 1); // 4, 3, 2, 1 + v.insert(0, 4); // 4, 3, 2, 1, 0 UASSERTEQ(v.size(), 5); UASSERTEQ(v[0], 4); UASSERTEQ(v[1], 3); @@ -57,7 +58,8 @@ static void test_basics() { UASSERTEQ(v.size(), 2); } -static void test_linear_searches() { +static void test_linear_searches() +{ // Populate the array with 0, 1, 2, ..., 100, 100, 99, 98, 97, ..., 0 array arr; for (int i = 0; i <= 100; i++) @@ -75,14 +77,15 @@ static void test_linear_searches() { } } -static void test_binary_searches() { - const auto& values = { 3, 5, 1, 2, 5, 10, 19, 9, 7, 1, 2, 5, 8, 15 }; +static void test_binary_searches() +{ + const auto &values = {3, 5, 1, 2, 5, 10, 19, 9, 7, 1, 2, 5, 8, 15}; array arr; for (int value : values) { arr.push_back(value); } // Test the const form first, it uses a linear search without sorting - const array & carr = arr; + const array &carr = arr; UASSERTEQ(carr.binary_search(20), -1); UASSERTEQ(carr.binary_search(0), -1); UASSERTEQ(carr.binary_search(1), 2); diff --git a/examples/AutomatedTest/test_helper.h b/examples/AutomatedTest/test_helper.h index 9774cddb..5229eff2 100644 --- a/examples/AutomatedTest/test_helper.h +++ b/examples/AutomatedTest/test_helper.h @@ -3,28 +3,31 @@ #include #include -class TestFailedException : public std::exception { +class TestFailedException : public std::exception +{ }; // Asserts the comparison specified by CMP is true, or fails the current unit test -#define UASSERTCMP(CMP, actual, expected) do { \ - const auto &a = (actual); \ - const auto &e = (expected); \ - if (!CMP(a, e)) { \ - std::cout \ - << "Test assertion failed: " << #actual << " " << #CMP << " " \ - << #expected << std::endl \ - << " at " << __FILE__ << ":" << __LINE__ << std::endl \ - << " actual: " << a << std::endl << " expected: " \ - << e << std::endl; \ - throw TestFailedException(); \ - } \ -} while (0) +#define UASSERTCMP(CMP, actual, expected) \ + do { \ + const auto &a = (actual); \ + const auto &e = (expected); \ + if (!CMP(a, e)) { \ + std::cout \ + << "Test assertion failed: " << #actual << " " << #CMP << " " \ + << #expected << std::endl \ + << " at " << __FILE__ << ":" << __LINE__ << std::endl \ + << " actual: " << a << std::endl \ + << " expected: " \ + << e << std::endl; \ + throw TestFailedException(); \ + } \ + } while (0) -#define CMPEQ(a, e) (a == e) -#define CMPTRUE(a, e) (a) -#define CMPNE(a, e) (a != e) +#define CMPEQ(a, e) (a == e) +#define CMPTRUE(a, e) (a) +#define CMPNE(a, e) (a != e) -#define UASSERTEQ(actual, expected) UASSERTCMP(CMPEQ, actual, expected) +#define UASSERTEQ(actual, expected) UASSERTCMP(CMPEQ, actual, expected) #define UASSERTNE(actual, nexpected) UASSERTCMP(CMPNE, actual, nexpected) -#define UASSERT(actual) UASSERTCMP(CMPTRUE, actual, true) +#define UASSERT(actual) UASSERTCMP(CMPTRUE, actual, true) diff --git a/examples/AutomatedTest/test_string.cpp b/examples/AutomatedTest/test_string.cpp index 926f6c8f..4d1291f1 100644 --- a/examples/AutomatedTest/test_string.cpp +++ b/examples/AutomatedTest/test_string.cpp @@ -38,7 +38,7 @@ static void test_basics() UASSERTSTR(s, "abcdef"); s = L"abcdef"; UASSERTSTR(s, "abcdef"); - s = static_cast(nullptr); + s = static_cast(nullptr); UASSERTSTR(s, ""); // operator+ s = s + stringc("foo"); @@ -163,7 +163,7 @@ static void test_methods() UASSERTSTR(res[0], "a"); UASSERTSTR(res[2], ""); for (int i = 0; i < 3; i++) - UASSERTSTR(res[2*i+1], ","); + UASSERTSTR(res[2 * i + 1], ","); } static void test_conv() @@ -180,9 +180,9 @@ static void test_conv() wStringToUTF8(out2, L"†††"); UASSERTEQ(out2.size(), 9); for (int i = 0; i < 3; i++) { - UASSERTEQ(static_cast(out2[3*i]), 0xe2); - UASSERTEQ(static_cast(out2[3*i+1]), 0x80); - UASSERTEQ(static_cast(out2[3*i+2]), 0xa0); + UASSERTEQ(static_cast(out2[3 * i]), 0xe2); + UASSERTEQ(static_cast(out2[3 * i + 1]), 0x80); + UASSERTEQ(static_cast(out2[3 * i + 2]), 0xa0); } // locale-dependent diff --git a/include/CMeshBuffer.h b/include/CMeshBuffer.h index 9004af71..8f8158ff 100644 --- a/include/CMeshBuffer.h +++ b/include/CMeshBuffer.h @@ -11,284 +11,264 @@ namespace irr { namespace scene { - //! Template implementation of the IMeshBuffer interface - template - class CMeshBuffer : public IMeshBuffer +//! Template implementation of the IMeshBuffer interface +template +class CMeshBuffer : public IMeshBuffer +{ +public: + //! Default constructor for empty meshbuffer + CMeshBuffer() : + ChangedID_Vertex(1), ChangedID_Index(1), MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER), HWBuffer(NULL), PrimitiveType(EPT_TRIANGLES) { - public: - //! Default constructor for empty meshbuffer - CMeshBuffer() - : ChangedID_Vertex(1), ChangedID_Index(1) - , MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER) - , HWBuffer(NULL) - , PrimitiveType(EPT_TRIANGLES) - { - #ifdef _DEBUG - setDebugName("CMeshBuffer"); - #endif +#ifdef _DEBUG + setDebugName("CMeshBuffer"); +#endif + } + + //! Get material of this meshbuffer + /** \return Material of this buffer */ + const video::SMaterial &getMaterial() const override + { + return Material; + } + + //! Get material of this meshbuffer + /** \return Material of this buffer */ + video::SMaterial &getMaterial() override + { + return Material; + } + + //! Get pointer to vertices + /** \return Pointer to vertices. */ + const void *getVertices() const override + { + return Vertices.const_pointer(); + } + + //! Get pointer to vertices + /** \return Pointer to vertices. */ + void *getVertices() override + { + return Vertices.pointer(); + } + + //! Get number of vertices + /** \return Number of vertices. */ + u32 getVertexCount() const override + { + return Vertices.size(); + } + + //! Get type of index data which is stored in this meshbuffer. + /** \return Index type of this buffer. */ + video::E_INDEX_TYPE getIndexType() const override + { + return video::EIT_16BIT; + } + + //! Get pointer to indices + /** \return Pointer to indices. */ + const u16 *getIndices() const override + { + return Indices.const_pointer(); + } + + //! Get pointer to indices + /** \return Pointer to indices. */ + u16 *getIndices() override + { + return Indices.pointer(); + } + + //! Get number of indices + /** \return Number of indices. */ + u32 getIndexCount() const override + { + return Indices.size(); + } + + //! Get the axis aligned bounding box + /** \return Axis aligned bounding box of this buffer. */ + const core::aabbox3d &getBoundingBox() const override + { + return BoundingBox; + } + + //! Set the axis aligned bounding box + /** \param box New axis aligned bounding box for this buffer. */ + //! set user axis aligned bounding box + void setBoundingBox(const core::aabbox3df &box) override + { + BoundingBox = box; + } + + //! Recalculate the bounding box. + /** should be called if the mesh changed. */ + void recalculateBoundingBox() override + { + if (!Vertices.empty()) { + BoundingBox.reset(Vertices[0].Pos); + const irr::u32 vsize = Vertices.size(); + for (u32 i = 1; i < vsize; ++i) + BoundingBox.addInternalPoint(Vertices[i].Pos); + } else + BoundingBox.reset(0, 0, 0); + } + + //! Get type of vertex data stored in this buffer. + /** \return Type of vertex data. */ + video::E_VERTEX_TYPE getVertexType() const override + { + return T::getType(); + } + + //! returns position of vertex i + const core::vector3df &getPosition(u32 i) const override + { + return Vertices[i].Pos; + } + + //! returns position of vertex i + core::vector3df &getPosition(u32 i) override + { + return Vertices[i].Pos; + } + + //! returns normal of vertex i + const core::vector3df &getNormal(u32 i) const override + { + return Vertices[i].Normal; + } + + //! returns normal of vertex i + core::vector3df &getNormal(u32 i) override + { + return Vertices[i].Normal; + } + + //! returns texture coord of vertex i + const core::vector2df &getTCoords(u32 i) const override + { + return Vertices[i].TCoords; + } + + //! returns texture coord of vertex i + core::vector2df &getTCoords(u32 i) override + { + return Vertices[i].TCoords; + } + + //! Append the vertices and indices to the current buffer + /** Only works for compatible types, i.e. either the same type + or the main buffer is of standard type. Otherwise, behavior is + undefined. + */ + void append(const void *const vertices, u32 numVertices, const u16 *const indices, u32 numIndices) override + { + if (vertices == getVertices()) + return; + + const u32 vertexCount = getVertexCount(); + u32 i; + + Vertices.reallocate(vertexCount + numVertices); + for (i = 0; i < numVertices; ++i) { + Vertices.push_back(static_cast(vertices)[i]); + BoundingBox.addInternalPoint(static_cast(vertices)[i].Pos); } - - //! Get material of this meshbuffer - /** \return Material of this buffer */ - const video::SMaterial& getMaterial() const override - { - return Material; + Indices.reallocate(getIndexCount() + numIndices); + for (i = 0; i < numIndices; ++i) { + Indices.push_back(indices[i] + vertexCount); } + } + //! get the current hardware mapping hint + E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const override + { + return MappingHint_Vertex; + } - //! Get material of this meshbuffer - /** \return Material of this buffer */ - video::SMaterial& getMaterial() override - { - return Material; - } + //! get the current hardware mapping hint + E_HARDWARE_MAPPING getHardwareMappingHint_Index() const override + { + return MappingHint_Index; + } + //! set the hardware mapping hint, for driver + void setHardwareMappingHint(E_HARDWARE_MAPPING NewMappingHint, E_BUFFER_TYPE Buffer = EBT_VERTEX_AND_INDEX) override + { + if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_VERTEX) + MappingHint_Vertex = NewMappingHint; + if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_INDEX) + MappingHint_Index = NewMappingHint; + } - //! Get pointer to vertices - /** \return Pointer to vertices. */ - const void* getVertices() const override - { - return Vertices.const_pointer(); - } + //! Describe what kind of primitive geometry is used by the meshbuffer + void setPrimitiveType(E_PRIMITIVE_TYPE type) override + { + PrimitiveType = type; + } + //! Get the kind of primitive geometry which is used by the meshbuffer + E_PRIMITIVE_TYPE getPrimitiveType() const override + { + return PrimitiveType; + } - //! Get pointer to vertices - /** \return Pointer to vertices. */ - void* getVertices() override - { - return Vertices.pointer(); - } + //! flags the mesh as changed, reloads hardware buffers + void setDirty(E_BUFFER_TYPE Buffer = EBT_VERTEX_AND_INDEX) override + { + if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_VERTEX) + ++ChangedID_Vertex; + if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_INDEX) + ++ChangedID_Index; + } + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + u32 getChangedID_Vertex() const override { return ChangedID_Vertex; } - //! Get number of vertices - /** \return Number of vertices. */ - u32 getVertexCount() const override - { - return Vertices.size(); - } + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + u32 getChangedID_Index() const override { return ChangedID_Index; } - //! Get type of index data which is stored in this meshbuffer. - /** \return Index type of this buffer. */ - video::E_INDEX_TYPE getIndexType() const override - { - return video::EIT_16BIT; - } + void setHWBuffer(void *ptr) const override + { + HWBuffer = ptr; + } - //! Get pointer to indices - /** \return Pointer to indices. */ - const u16* getIndices() const override - { - return Indices.const_pointer(); - } + void *getHWBuffer() const override + { + return HWBuffer; + } + u32 ChangedID_Vertex; + u32 ChangedID_Index; - //! Get pointer to indices - /** \return Pointer to indices. */ - u16* getIndices() override - { - return Indices.pointer(); - } + //! hardware mapping hint + E_HARDWARE_MAPPING MappingHint_Vertex; + E_HARDWARE_MAPPING MappingHint_Index; + mutable void *HWBuffer; + //! Material for this meshbuffer. + video::SMaterial Material; + //! Vertices of this buffer + core::array Vertices; + //! Indices into the vertices of this buffer. + core::array Indices; + //! Bounding box of this meshbuffer. + core::aabbox3d BoundingBox; + //! Primitive type used for rendering (triangles, lines, ...) + E_PRIMITIVE_TYPE PrimitiveType; +}; - //! Get number of indices - /** \return Number of indices. */ - u32 getIndexCount() const override - { - return Indices.size(); - } - - - //! Get the axis aligned bounding box - /** \return Axis aligned bounding box of this buffer. */ - const core::aabbox3d& getBoundingBox() const override - { - return BoundingBox; - } - - - //! Set the axis aligned bounding box - /** \param box New axis aligned bounding box for this buffer. */ - //! set user axis aligned bounding box - void setBoundingBox(const core::aabbox3df& box) override - { - BoundingBox = box; - } - - - //! Recalculate the bounding box. - /** should be called if the mesh changed. */ - void recalculateBoundingBox() override - { - if (!Vertices.empty()) - { - BoundingBox.reset(Vertices[0].Pos); - const irr::u32 vsize = Vertices.size(); - for (u32 i=1; i(vertices)[i]); - BoundingBox.addInternalPoint(static_cast(vertices)[i].Pos); - } - - Indices.reallocate(getIndexCount()+numIndices); - for (i=0; i Vertices; - //! Indices into the vertices of this buffer. - core::array Indices; - //! Bounding box of this meshbuffer. - core::aabbox3d BoundingBox; - //! Primitive type used for rendering (triangles, lines, ...) - E_PRIMITIVE_TYPE PrimitiveType; - }; - - //! Standard meshbuffer - typedef CMeshBuffer SMeshBuffer; - //! Meshbuffer with two texture coords per vertex, e.g. for lightmaps - typedef CMeshBuffer SMeshBufferLightMap; - //! Meshbuffer with vertices having tangents stored, e.g. for normal mapping - typedef CMeshBuffer SMeshBufferTangents; +//! Standard meshbuffer +typedef CMeshBuffer SMeshBuffer; +//! Meshbuffer with two texture coords per vertex, e.g. for lightmaps +typedef CMeshBuffer SMeshBufferLightMap; +//! Meshbuffer with vertices having tangents stored, e.g. for normal mapping +typedef CMeshBuffer SMeshBufferTangents; } // end namespace scene } // end namespace irr diff --git a/include/ECullingTypes.h b/include/ECullingTypes.h index e8d2b069..46dc3c92 100644 --- a/include/ECullingTypes.h +++ b/include/ECullingTypes.h @@ -11,26 +11,25 @@ namespace irr namespace scene { - //! An enumeration for all types of automatic culling for built-in scene nodes - enum E_CULLING_TYPE - { - EAC_OFF = 0, - EAC_BOX = 1, - EAC_FRUSTUM_BOX = 2, - EAC_FRUSTUM_SPHERE = 4, - EAC_OCC_QUERY = 8 - }; +//! An enumeration for all types of automatic culling for built-in scene nodes +enum E_CULLING_TYPE +{ + EAC_OFF = 0, + EAC_BOX = 1, + EAC_FRUSTUM_BOX = 2, + EAC_FRUSTUM_SPHERE = 4, + EAC_OCC_QUERY = 8 +}; - //! Names for culling type - const c8* const AutomaticCullingNames[] = - { - "false", - "box", // camera box against node box - "frustum_box", // camera frustum against node box - "frustum_sphere", // camera frustum against node sphere - "occ_query", // occlusion query - 0 - }; +//! Names for culling type +const c8 *const AutomaticCullingNames[] = + { + "false", + "box", // camera box against node box + "frustum_box", // camera frustum against node box + "frustum_sphere", // camera frustum against node sphere + "occ_query", // occlusion query + 0}; } // end namespace scene } // end namespace irr diff --git a/include/EDebugSceneTypes.h b/include/EDebugSceneTypes.h index 67721b8e..29ca8ad0 100644 --- a/include/EDebugSceneTypes.h +++ b/include/EDebugSceneTypes.h @@ -9,34 +9,33 @@ namespace irr namespace scene { - //! An enumeration for all types of debug data for built-in scene nodes (flags) - enum E_DEBUG_SCENE_TYPE - { - //! No Debug Data ( Default ) - EDS_OFF = 0, +//! An enumeration for all types of debug data for built-in scene nodes (flags) +enum E_DEBUG_SCENE_TYPE +{ + //! No Debug Data ( Default ) + EDS_OFF = 0, - //! Show Bounding Boxes of SceneNode - EDS_BBOX = 1, + //! Show Bounding Boxes of SceneNode + EDS_BBOX = 1, - //! Show Vertex Normals - EDS_NORMALS = 2, + //! Show Vertex Normals + EDS_NORMALS = 2, - //! Shows Skeleton/Tags - EDS_SKELETON = 4, + //! Shows Skeleton/Tags + EDS_SKELETON = 4, - //! Overlays Mesh Wireframe - EDS_MESH_WIRE_OVERLAY = 8, + //! Overlays Mesh Wireframe + EDS_MESH_WIRE_OVERLAY = 8, - //! Show Bounding Boxes of all MeshBuffers - EDS_BBOX_BUFFERS = 32, + //! Show Bounding Boxes of all MeshBuffers + EDS_BBOX_BUFFERS = 32, - //! EDS_BBOX | EDS_BBOX_BUFFERS - EDS_BBOX_ALL = EDS_BBOX | EDS_BBOX_BUFFERS, - - //! Show all debug infos - EDS_FULL = 0xffffffff - }; + //! EDS_BBOX | EDS_BBOX_BUFFERS + EDS_BBOX_ALL = EDS_BBOX | EDS_BBOX_BUFFERS, + //! Show all debug infos + EDS_FULL = 0xffffffff +}; } // end namespace scene } // end namespace irr diff --git a/include/EDeviceTypes.h b/include/EDeviceTypes.h index 617168ca..1eff4f61 100644 --- a/include/EDeviceTypes.h +++ b/include/EDeviceTypes.h @@ -7,40 +7,40 @@ namespace irr { - //! An enum for the different device types supported by the Irrlicht Engine. - enum E_DEVICE_TYPE - { +//! An enum for the different device types supported by the Irrlicht Engine. +enum E_DEVICE_TYPE +{ - //! A device native to Microsoft Windows - /** This device uses the Win32 API and works in all versions of Windows. */ - EIDT_WIN32, + //! A device native to Microsoft Windows + /** This device uses the Win32 API and works in all versions of Windows. */ + EIDT_WIN32, - //! A device native to Unix style operating systems. - /** This device uses the X11 windowing system and works in Linux, Solaris, FreeBSD, OSX and - other operating systems which support X11. */ - EIDT_X11, + //! A device native to Unix style operating systems. + /** This device uses the X11 windowing system and works in Linux, Solaris, FreeBSD, OSX and + other operating systems which support X11. */ + EIDT_X11, - //! A device native to Mac OSX - /** This device uses Apple's Cocoa API and works in Mac OSX 10.2 and above. */ - EIDT_OSX, + //! A device native to Mac OSX + /** This device uses Apple's Cocoa API and works in Mac OSX 10.2 and above. */ + EIDT_OSX, - //! A device which uses Simple DirectMedia Layer - /** The SDL device works under all platforms supported by SDL but first must be compiled - in by setting the USE_SDL2 CMake option to ON */ - EIDT_SDL, + //! A device which uses Simple DirectMedia Layer + /** The SDL device works under all platforms supported by SDL but first must be compiled + in by setting the USE_SDL2 CMake option to ON */ + EIDT_SDL, - //! This selection allows Irrlicht to choose the best device from the ones available. - /** If this selection is chosen then Irrlicht will try to use the IrrlichtDevice native - to your operating system. If this is unavailable then the X11, SDL and then console device - will be tried. This ensures that Irrlicht will run even if your platform is unsupported, - although it may not be able to render anything. */ - EIDT_BEST, + //! This selection allows Irrlicht to choose the best device from the ones available. + /** If this selection is chosen then Irrlicht will try to use the IrrlichtDevice native + to your operating system. If this is unavailable then the X11, SDL and then console device + will be tried. This ensures that Irrlicht will run even if your platform is unsupported, + although it may not be able to render anything. */ + EIDT_BEST, - //! A device for Android platforms - /** Best used with embedded devices and mobile systems. - Does not need X11 or other graphical subsystems. - May support hw-acceleration via OpenGL-ES */ - EIDT_ANDROID, - }; + //! A device for Android platforms + /** Best used with embedded devices and mobile systems. + Does not need X11 or other graphical subsystems. + May support hw-acceleration via OpenGL-ES */ + EIDT_ANDROID, +}; } // end namespace irr diff --git a/include/EDriverFeatures.h b/include/EDriverFeatures.h index 2a2ef5b0..bde2c769 100644 --- a/include/EDriverFeatures.h +++ b/include/EDriverFeatures.h @@ -9,129 +9,129 @@ namespace irr namespace video { - //! enumeration for querying features of the video driver. - enum E_VIDEO_DRIVER_FEATURE - { - //! Is driver able to render to a surface? - EVDF_RENDER_TO_TARGET = 0, +//! enumeration for querying features of the video driver. +enum E_VIDEO_DRIVER_FEATURE +{ + //! Is driver able to render to a surface? + EVDF_RENDER_TO_TARGET = 0, - //! Is hardware transform and lighting supported? - EVDF_HARDWARE_TL, + //! Is hardware transform and lighting supported? + EVDF_HARDWARE_TL, - //! Are multiple textures per material possible? - EVDF_MULTITEXTURE, + //! Are multiple textures per material possible? + EVDF_MULTITEXTURE, - //! Is driver able to render with a bilinear filter applied? - EVDF_BILINEAR_FILTER, + //! Is driver able to render with a bilinear filter applied? + EVDF_BILINEAR_FILTER, - //! Can the driver handle mip maps? - EVDF_MIP_MAP, + //! Can the driver handle mip maps? + EVDF_MIP_MAP, - //! Can the driver update mip maps automatically? - EVDF_MIP_MAP_AUTO_UPDATE, + //! Can the driver update mip maps automatically? + EVDF_MIP_MAP_AUTO_UPDATE, - //! Are stencilbuffers switched on and does the device support stencil buffers? - EVDF_STENCIL_BUFFER, + //! Are stencilbuffers switched on and does the device support stencil buffers? + EVDF_STENCIL_BUFFER, - //! Is Vertex Shader 1.1 supported? - EVDF_VERTEX_SHADER_1_1, + //! Is Vertex Shader 1.1 supported? + EVDF_VERTEX_SHADER_1_1, - //! Is Vertex Shader 2.0 supported? - EVDF_VERTEX_SHADER_2_0, + //! Is Vertex Shader 2.0 supported? + EVDF_VERTEX_SHADER_2_0, - //! Is Vertex Shader 3.0 supported? - EVDF_VERTEX_SHADER_3_0, + //! Is Vertex Shader 3.0 supported? + EVDF_VERTEX_SHADER_3_0, - //! Is Pixel Shader 1.1 supported? - EVDF_PIXEL_SHADER_1_1, + //! Is Pixel Shader 1.1 supported? + EVDF_PIXEL_SHADER_1_1, - //! Is Pixel Shader 1.2 supported? - EVDF_PIXEL_SHADER_1_2, + //! Is Pixel Shader 1.2 supported? + EVDF_PIXEL_SHADER_1_2, - //! Is Pixel Shader 1.3 supported? - EVDF_PIXEL_SHADER_1_3, + //! Is Pixel Shader 1.3 supported? + EVDF_PIXEL_SHADER_1_3, - //! Is Pixel Shader 1.4 supported? - EVDF_PIXEL_SHADER_1_4, + //! Is Pixel Shader 1.4 supported? + EVDF_PIXEL_SHADER_1_4, - //! Is Pixel Shader 2.0 supported? - EVDF_PIXEL_SHADER_2_0, + //! Is Pixel Shader 2.0 supported? + EVDF_PIXEL_SHADER_2_0, - //! Is Pixel Shader 3.0 supported? - EVDF_PIXEL_SHADER_3_0, + //! Is Pixel Shader 3.0 supported? + EVDF_PIXEL_SHADER_3_0, - //! Are ARB vertex programs v1.0 supported? - EVDF_ARB_VERTEX_PROGRAM_1, + //! Are ARB vertex programs v1.0 supported? + EVDF_ARB_VERTEX_PROGRAM_1, - //! Are ARB fragment programs v1.0 supported? - EVDF_ARB_FRAGMENT_PROGRAM_1, + //! Are ARB fragment programs v1.0 supported? + EVDF_ARB_FRAGMENT_PROGRAM_1, - //! Is GLSL supported? - EVDF_ARB_GLSL, + //! Is GLSL supported? + EVDF_ARB_GLSL, - //! Is HLSL supported? - EVDF_HLSL, + //! Is HLSL supported? + EVDF_HLSL, - //! Are non-square textures supported? - EVDF_TEXTURE_NSQUARE, + //! Are non-square textures supported? + EVDF_TEXTURE_NSQUARE, - //! Are non-power-of-two textures supported? - EVDF_TEXTURE_NPOT, + //! Are non-power-of-two textures supported? + EVDF_TEXTURE_NPOT, - //! Are framebuffer objects supported? - EVDF_FRAMEBUFFER_OBJECT, + //! Are framebuffer objects supported? + EVDF_FRAMEBUFFER_OBJECT, - //! Are vertex buffer objects supported? - EVDF_VERTEX_BUFFER_OBJECT, + //! Are vertex buffer objects supported? + EVDF_VERTEX_BUFFER_OBJECT, - //! Supports Alpha To Coverage - EVDF_ALPHA_TO_COVERAGE, + //! Supports Alpha To Coverage + EVDF_ALPHA_TO_COVERAGE, - //! Supports Color masks (disabling color planes in output) - EVDF_COLOR_MASK, + //! Supports Color masks (disabling color planes in output) + EVDF_COLOR_MASK, - //! Supports multiple render targets at once - EVDF_MULTIPLE_RENDER_TARGETS, + //! Supports multiple render targets at once + EVDF_MULTIPLE_RENDER_TARGETS, - //! Supports separate blend settings for multiple render targets - EVDF_MRT_BLEND, + //! Supports separate blend settings for multiple render targets + EVDF_MRT_BLEND, - //! Supports separate color masks for multiple render targets - EVDF_MRT_COLOR_MASK, + //! Supports separate color masks for multiple render targets + EVDF_MRT_COLOR_MASK, - //! Supports separate blend functions for multiple render targets - EVDF_MRT_BLEND_FUNC, + //! Supports separate blend functions for multiple render targets + EVDF_MRT_BLEND_FUNC, - //! Supports geometry shaders - EVDF_GEOMETRY_SHADER, + //! Supports geometry shaders + EVDF_GEOMETRY_SHADER, - //! Supports occlusion queries - EVDF_OCCLUSION_QUERY, + //! Supports occlusion queries + EVDF_OCCLUSION_QUERY, - //! Supports polygon offset/depth bias for avoiding z-fighting - EVDF_POLYGON_OFFSET, + //! Supports polygon offset/depth bias for avoiding z-fighting + EVDF_POLYGON_OFFSET, - //! Support for different blend functions. Without, only ADD is available - EVDF_BLEND_OPERATIONS, + //! Support for different blend functions. Without, only ADD is available + EVDF_BLEND_OPERATIONS, - //! Support for separate blending for RGB and Alpha. - EVDF_BLEND_SEPARATE, + //! Support for separate blending for RGB and Alpha. + EVDF_BLEND_SEPARATE, - //! Support for texture coord transformation via texture matrix - EVDF_TEXTURE_MATRIX, + //! Support for texture coord transformation via texture matrix + EVDF_TEXTURE_MATRIX, - //! Support for cube map textures. - EVDF_TEXTURE_CUBEMAP, + //! Support for cube map textures. + EVDF_TEXTURE_CUBEMAP, - //! Support for filtering across different faces of the cubemap - EVDF_TEXTURE_CUBEMAP_SEAMLESS, + //! Support for filtering across different faces of the cubemap + EVDF_TEXTURE_CUBEMAP_SEAMLESS, - //! Support for clamping vertices beyond far-plane to depth instead of capping them. - EVDF_DEPTH_CLAMP, + //! Support for clamping vertices beyond far-plane to depth instead of capping them. + EVDF_DEPTH_CLAMP, - //! Only used for counting the elements of this enum - EVDF_COUNT - }; + //! Only used for counting the elements of this enum + EVDF_COUNT +}; } // end namespace video } // end namespace irr diff --git a/include/EDriverTypes.h b/include/EDriverTypes.h index f41e42d6..33f98788 100644 --- a/include/EDriverTypes.h +++ b/include/EDriverTypes.h @@ -11,34 +11,34 @@ namespace irr namespace video { - //! An enum for all types of drivers the Irrlicht Engine supports. - enum E_DRIVER_TYPE - { - //! Null driver, useful for applications to run the engine without visualization. - /** The null device is able to load textures, but does not - render and display any graphics. */ - EDT_NULL, +//! An enum for all types of drivers the Irrlicht Engine supports. +enum E_DRIVER_TYPE +{ + //! Null driver, useful for applications to run the engine without visualization. + /** The null device is able to load textures, but does not + render and display any graphics. */ + EDT_NULL, - //! OpenGL device, available on most platforms. - /** Performs hardware accelerated rendering of 3D and 2D - primitives. */ - EDT_OPENGL, + //! OpenGL device, available on most platforms. + /** Performs hardware accelerated rendering of 3D and 2D + primitives. */ + EDT_OPENGL, - //! OpenGL-ES 1.x driver, for embedded and mobile systems - EDT_OGLES1, + //! OpenGL-ES 1.x driver, for embedded and mobile systems + EDT_OGLES1, - //! OpenGL-ES 2.x driver, for embedded and mobile systems - /** Supports shaders etc. */ - EDT_OGLES2, + //! OpenGL-ES 2.x driver, for embedded and mobile systems + /** Supports shaders etc. */ + EDT_OGLES2, - //! WebGL1 friendly subset of OpenGL-ES 2.x driver for Emscripten - EDT_WEBGL1, + //! WebGL1 friendly subset of OpenGL-ES 2.x driver for Emscripten + EDT_WEBGL1, - EDT_OPENGL3, + EDT_OPENGL3, - //! No driver, just for counting the elements - EDT_COUNT - }; + //! No driver, just for counting the elements + EDT_COUNT +}; } // end namespace video } // end namespace irr diff --git a/include/EGUIAlignment.h b/include/EGUIAlignment.h index 4c3c44a0..3935644b 100644 --- a/include/EGUIAlignment.h +++ b/include/EGUIAlignment.h @@ -13,7 +13,7 @@ namespace gui enum EGUI_ALIGNMENT { //! Aligned to parent's top or left side (default) - EGUIA_UPPERLEFT=0, + EGUIA_UPPERLEFT = 0, //! Aligned to parent's bottom or right side EGUIA_LOWERRIGHT, //! Aligned to the center of parent @@ -23,14 +23,13 @@ enum EGUI_ALIGNMENT }; //! Names for alignments -const c8* const GUIAlignmentNames[] = -{ - "upperLeft", - "lowerRight", - "center", - "scale", - 0 -}; +const c8 *const GUIAlignmentNames[] = + { + "upperLeft", + "lowerRight", + "center", + "scale", + 0}; } // namespace gui } // namespace irr diff --git a/include/EGUIElementTypes.h b/include/EGUIElementTypes.h index aea49f47..2452024e 100644 --- a/include/EGUIElementTypes.h +++ b/include/EGUIElementTypes.h @@ -99,36 +99,35 @@ enum EGUI_ELEMENT_TYPE }; //! Names for built-in element types -const c8* const GUIElementTypeNames[] = -{ - "button", - "checkBox", - "comboBox", - "contextMenu", - "menu", - "editBox", - "fileOpenDialog", - "colorSelectDialog", - "inOutFader", - "image", - "listBox", - "meshViewer", - "messageBox", - "modalScreen", - "scrollBar", - "spinBox", - "staticText", - "tab", - "tabControl", - "table", - "toolBar", - "treeview", - "window", - "element", - "root", - "profiler", - 0 -}; +const c8 *const GUIElementTypeNames[] = + { + "button", + "checkBox", + "comboBox", + "contextMenu", + "menu", + "editBox", + "fileOpenDialog", + "colorSelectDialog", + "inOutFader", + "image", + "listBox", + "meshViewer", + "messageBox", + "modalScreen", + "scrollBar", + "spinBox", + "staticText", + "tab", + "tabControl", + "table", + "toolBar", + "treeview", + "window", + "element", + "root", + "profiler", + 0}; } // end namespace gui } // end namespace irr diff --git a/include/EHardwareBufferFlags.h b/include/EHardwareBufferFlags.h index e50d2cff..ae1b602e 100644 --- a/include/EHardwareBufferFlags.h +++ b/include/EHardwareBufferFlags.h @@ -9,32 +9,32 @@ namespace irr namespace scene { - enum E_HARDWARE_MAPPING - { - //! Don't store on the hardware - EHM_NEVER=0, +enum E_HARDWARE_MAPPING +{ + //! Don't store on the hardware + EHM_NEVER = 0, - //! Rarely changed, usually stored completely on the hardware - EHM_STATIC, + //! Rarely changed, usually stored completely on the hardware + EHM_STATIC, - //! Sometimes changed, driver optimized placement - EHM_DYNAMIC, + //! Sometimes changed, driver optimized placement + EHM_DYNAMIC, - //! Always changed, cache optimizing on the GPU - EHM_STREAM - }; + //! Always changed, cache optimizing on the GPU + EHM_STREAM +}; - enum E_BUFFER_TYPE - { - //! Does not change anything - EBT_NONE=0, - //! Change the vertex mapping - EBT_VERTEX, - //! Change the index mapping - EBT_INDEX, - //! Change both vertex and index mapping to the same value - EBT_VERTEX_AND_INDEX - }; +enum E_BUFFER_TYPE +{ + //! Does not change anything + EBT_NONE = 0, + //! Change the vertex mapping + EBT_VERTEX, + //! Change the index mapping + EBT_INDEX, + //! Change both vertex and index mapping to the same value + EBT_VERTEX_AND_INDEX +}; } // end namespace scene } // end namespace irr diff --git a/include/EMaterialProps.h b/include/EMaterialProps.h index 975cd604..6f37c95b 100644 --- a/include/EMaterialProps.h +++ b/include/EMaterialProps.h @@ -9,74 +9,74 @@ namespace irr namespace video { - //! Material properties - enum E_MATERIAL_PROP - { - //! Corresponds to SMaterial::Wireframe. - EMP_WIREFRAME = 0x1, +//! Material properties +enum E_MATERIAL_PROP +{ + //! Corresponds to SMaterial::Wireframe. + EMP_WIREFRAME = 0x1, - //! Corresponds to SMaterial::PointCloud. - EMP_POINTCLOUD = 0x2, + //! Corresponds to SMaterial::PointCloud. + EMP_POINTCLOUD = 0x2, - //! Corresponds to SMaterial::GouraudShading. - EMP_GOURAUD_SHADING = 0x4, + //! Corresponds to SMaterial::GouraudShading. + EMP_GOURAUD_SHADING = 0x4, - //! Corresponds to SMaterial::Lighting. - EMP_LIGHTING = 0x8, + //! Corresponds to SMaterial::Lighting. + EMP_LIGHTING = 0x8, - //! Corresponds to SMaterial::ZBuffer. - EMP_ZBUFFER = 0x10, + //! Corresponds to SMaterial::ZBuffer. + EMP_ZBUFFER = 0x10, - //! Corresponds to SMaterial::ZWriteEnable. - EMP_ZWRITE_ENABLE = 0x20, + //! Corresponds to SMaterial::ZWriteEnable. + EMP_ZWRITE_ENABLE = 0x20, - //! Corresponds to SMaterial::BackfaceCulling. - EMP_BACK_FACE_CULLING = 0x40, + //! Corresponds to SMaterial::BackfaceCulling. + EMP_BACK_FACE_CULLING = 0x40, - //! Corresponds to SMaterial::FrontfaceCulling. - EMP_FRONT_FACE_CULLING = 0x80, + //! Corresponds to SMaterial::FrontfaceCulling. + EMP_FRONT_FACE_CULLING = 0x80, - //! Corresponds to SMaterialLayer::MinFilter. - EMP_MIN_FILTER = 0x100, + //! Corresponds to SMaterialLayer::MinFilter. + EMP_MIN_FILTER = 0x100, - //! Corresponds to SMaterialLayer::MagFilter. - EMP_MAG_FILTER = 0x200, + //! Corresponds to SMaterialLayer::MagFilter. + EMP_MAG_FILTER = 0x200, - //! Corresponds to SMaterialLayer::AnisotropicFilter. - EMP_ANISOTROPIC_FILTER = 0x400, + //! Corresponds to SMaterialLayer::AnisotropicFilter. + EMP_ANISOTROPIC_FILTER = 0x400, - //! Corresponds to SMaterial::FogEnable. - EMP_FOG_ENABLE = 0x800, + //! Corresponds to SMaterial::FogEnable. + EMP_FOG_ENABLE = 0x800, - //! Corresponds to SMaterial::NormalizeNormals. - EMP_NORMALIZE_NORMALS = 0x1000, + //! Corresponds to SMaterial::NormalizeNormals. + EMP_NORMALIZE_NORMALS = 0x1000, - //! Corresponds to SMaterialLayer::TextureWrapU, TextureWrapV and - //! TextureWrapW. - EMP_TEXTURE_WRAP = 0x2000, + //! Corresponds to SMaterialLayer::TextureWrapU, TextureWrapV and + //! TextureWrapW. + EMP_TEXTURE_WRAP = 0x2000, - //! Corresponds to SMaterial::AntiAliasing. - EMP_ANTI_ALIASING = 0x4000, + //! Corresponds to SMaterial::AntiAliasing. + EMP_ANTI_ALIASING = 0x4000, - //! Corresponds to SMaterial::ColorMask. - EMP_COLOR_MASK = 0x8000, + //! Corresponds to SMaterial::ColorMask. + EMP_COLOR_MASK = 0x8000, - //! Corresponds to SMaterial::ColorMaterial. - EMP_COLOR_MATERIAL = 0x10000, + //! Corresponds to SMaterial::ColorMaterial. + EMP_COLOR_MATERIAL = 0x10000, - //! Corresponds to SMaterial::UseMipMaps. - EMP_USE_MIP_MAPS = 0x20000, + //! Corresponds to SMaterial::UseMipMaps. + EMP_USE_MIP_MAPS = 0x20000, - //! Corresponds to SMaterial::BlendOperation. - EMP_BLEND_OPERATION = 0x40000, + //! Corresponds to SMaterial::BlendOperation. + EMP_BLEND_OPERATION = 0x40000, - //! Corresponds to SMaterial::PolygonOffsetFactor, PolygonOffsetDirection, - //! PolygonOffsetDepthBias and PolygonOffsetSlopeScale. - EMP_POLYGON_OFFSET = 0x80000, + //! Corresponds to SMaterial::PolygonOffsetFactor, PolygonOffsetDirection, + //! PolygonOffsetDepthBias and PolygonOffsetSlopeScale. + EMP_POLYGON_OFFSET = 0x80000, - //! Corresponds to SMaterial::BlendFactor. - EMP_BLEND_FACTOR = 0x100000, - }; + //! Corresponds to SMaterial::BlendFactor. + EMP_BLEND_FACTOR = 0x100000, +}; } // end namespace video } // end namespace irr diff --git a/include/EMaterialTypes.h b/include/EMaterialTypes.h index 7bfe3dc2..ba15245c 100644 --- a/include/EMaterialTypes.h +++ b/include/EMaterialTypes.h @@ -11,65 +11,64 @@ namespace irr namespace video { - //! Abstracted and easy to use fixed function/programmable pipeline material modes. - enum E_MATERIAL_TYPE - { - //! Standard solid material. - /** Only first texture is used, which is supposed to be the - diffuse material. */ - EMT_SOLID = 0, +//! Abstracted and easy to use fixed function/programmable pipeline material modes. +enum E_MATERIAL_TYPE +{ + //! Standard solid material. + /** Only first texture is used, which is supposed to be the + diffuse material. */ + EMT_SOLID = 0, - //! Makes the material transparent based on the texture alpha channel. - /** The final color is blended together from the destination - color and the texture color, using the alpha channel value as - blend factor. Only first texture is used. If you are using - this material with small textures, it is a good idea to load - the texture in 32 bit mode - (video::IVideoDriver::setTextureCreationFlag()). Also, an alpha - ref is used, which can be manipulated using - SMaterial::MaterialTypeParam. This value controls how sharp the - edges become when going from a transparent to a solid spot on - the texture. */ - EMT_TRANSPARENT_ALPHA_CHANNEL, + //! Makes the material transparent based on the texture alpha channel. + /** The final color is blended together from the destination + color and the texture color, using the alpha channel value as + blend factor. Only first texture is used. If you are using + this material with small textures, it is a good idea to load + the texture in 32 bit mode + (video::IVideoDriver::setTextureCreationFlag()). Also, an alpha + ref is used, which can be manipulated using + SMaterial::MaterialTypeParam. This value controls how sharp the + edges become when going from a transparent to a solid spot on + the texture. */ + EMT_TRANSPARENT_ALPHA_CHANNEL, - //! Makes the material transparent based on the texture alpha channel. - /** If the alpha channel value is greater than 127, a - pixel is written to the target, otherwise not. This - material does not use alpha blending and is a lot faster - than EMT_TRANSPARENT_ALPHA_CHANNEL. It is ideal for drawing - stuff like leaves of plants, because the borders are not - blurry but sharp. Only first texture is used. If you are - using this material with small textures and 3d object, it - is a good idea to load the texture in 32 bit mode - (video::IVideoDriver::setTextureCreationFlag()). */ - EMT_TRANSPARENT_ALPHA_CHANNEL_REF, + //! Makes the material transparent based on the texture alpha channel. + /** If the alpha channel value is greater than 127, a + pixel is written to the target, otherwise not. This + material does not use alpha blending and is a lot faster + than EMT_TRANSPARENT_ALPHA_CHANNEL. It is ideal for drawing + stuff like leaves of plants, because the borders are not + blurry but sharp. Only first texture is used. If you are + using this material with small textures and 3d object, it + is a good idea to load the texture in 32 bit mode + (video::IVideoDriver::setTextureCreationFlag()). */ + EMT_TRANSPARENT_ALPHA_CHANNEL_REF, - //! Makes the material transparent based on the vertex alpha value. - EMT_TRANSPARENT_VERTEX_ALPHA, + //! Makes the material transparent based on the vertex alpha value. + EMT_TRANSPARENT_VERTEX_ALPHA, - //! BlendFunc = source * sourceFactor + dest * destFactor ( E_BLEND_FUNC ) - /** Using only first texture. Generic blending method. - The blend function is set to SMaterial::MaterialTypeParam with - pack_textureBlendFunc (for 2D) or pack_textureBlendFuncSeparate (for 3D). */ - EMT_ONETEXTURE_BLEND, + //! BlendFunc = source * sourceFactor + dest * destFactor ( E_BLEND_FUNC ) + /** Using only first texture. Generic blending method. + The blend function is set to SMaterial::MaterialTypeParam with + pack_textureBlendFunc (for 2D) or pack_textureBlendFuncSeparate (for 3D). */ + EMT_ONETEXTURE_BLEND, - //! This value is not used. It only forces this enumeration to compile to 32 bit. - EMT_FORCE_32BIT = 0x7fffffff - }; + //! This value is not used. It only forces this enumeration to compile to 32 bit. + EMT_FORCE_32BIT = 0x7fffffff +}; - //! Array holding the built in material type names - const char* const sBuiltInMaterialTypeNames[] = - { - "solid", - "trans_alphach", - "trans_alphach_ref", - "trans_vertex_alpha", - "onetexture_blend", - 0 - }; +//! Array holding the built in material type names +const char *const sBuiltInMaterialTypeNames[] = + { + "solid", + "trans_alphach", + "trans_alphach_ref", + "trans_vertex_alpha", + "onetexture_blend", + 0}; - constexpr u32 numBuiltInMaterials = - sizeof(sBuiltInMaterialTypeNames) / sizeof(char*) - 1; +constexpr u32 numBuiltInMaterials = + sizeof(sBuiltInMaterialTypeNames) / sizeof(char *) - 1; } // end namespace video } // end namespace irr diff --git a/include/EPrimitiveTypes.h b/include/EPrimitiveTypes.h index c2830d07..d4e5f73f 100644 --- a/include/EPrimitiveTypes.h +++ b/include/EPrimitiveTypes.h @@ -9,35 +9,35 @@ namespace irr namespace scene { - //! Enumeration for all primitive types there are. - enum E_PRIMITIVE_TYPE - { - //! All vertices are non-connected points. - EPT_POINTS=0, +//! Enumeration for all primitive types there are. +enum E_PRIMITIVE_TYPE +{ + //! All vertices are non-connected points. + EPT_POINTS = 0, - //! All vertices form a single connected line. - EPT_LINE_STRIP, + //! All vertices form a single connected line. + EPT_LINE_STRIP, - //! Just as LINE_STRIP, but the last and the first vertex is also connected. - EPT_LINE_LOOP, + //! Just as LINE_STRIP, but the last and the first vertex is also connected. + EPT_LINE_LOOP, - //! Every two vertices are connected creating n/2 lines. - EPT_LINES, + //! Every two vertices are connected creating n/2 lines. + EPT_LINES, - //! After the first two vertices each vertex defines a new triangle. - //! Always the two last and the new one form a new triangle. - EPT_TRIANGLE_STRIP, + //! After the first two vertices each vertex defines a new triangle. + //! Always the two last and the new one form a new triangle. + EPT_TRIANGLE_STRIP, - //! After the first two vertices each vertex defines a new triangle. - //! All around the common first vertex. - EPT_TRIANGLE_FAN, + //! After the first two vertices each vertex defines a new triangle. + //! All around the common first vertex. + EPT_TRIANGLE_FAN, - //! Explicitly set all vertices for each triangle. - EPT_TRIANGLES, + //! Explicitly set all vertices for each triangle. + EPT_TRIANGLES, - //! The single vertices are expanded to quad billboards on the GPU. - EPT_POINT_SPRITES - }; + //! The single vertices are expanded to quad billboards on the GPU. + EPT_POINT_SPRITES +}; } // end namespace scene } // end namespace irr diff --git a/include/EReadFileType.h b/include/EReadFileType.h index 0e00eaf4..2241b70b 100644 --- a/include/EReadFileType.h +++ b/include/EReadFileType.h @@ -11,20 +11,20 @@ namespace irr namespace io { - //! An enumeration for different class types implementing IReadFile - enum EREAD_FILE_TYPE - { - //! CReadFile - ERFT_READ_FILE = MAKE_IRR_ID('r','e','a','d'), +//! An enumeration for different class types implementing IReadFile +enum EREAD_FILE_TYPE +{ + //! CReadFile + ERFT_READ_FILE = MAKE_IRR_ID('r', 'e', 'a', 'd'), - //! CMemoryReadFile - ERFT_MEMORY_READ_FILE = MAKE_IRR_ID('r','m','e','m'), + //! CMemoryReadFile + ERFT_MEMORY_READ_FILE = MAKE_IRR_ID('r', 'm', 'e', 'm'), - //! CLimitReadFile - ERFT_LIMIT_READ_FILE = MAKE_IRR_ID('r','l','i','m'), + //! CLimitReadFile + ERFT_LIMIT_READ_FILE = MAKE_IRR_ID('r', 'l', 'i', 'm'), - //! Unknown type - EFIT_UNKNOWN = MAKE_IRR_ID('u','n','k','n') - }; + //! Unknown type + EFIT_UNKNOWN = MAKE_IRR_ID('u', 'n', 'k', 'n') +}; } // end namespace io } // end namespace irr diff --git a/include/ESceneNodeTypes.h b/include/ESceneNodeTypes.h index e1e6c76e..b8251d96 100644 --- a/include/ESceneNodeTypes.h +++ b/include/ESceneNodeTypes.h @@ -11,41 +11,39 @@ namespace irr namespace scene { - //! An enumeration for all types of built-in scene nodes - /** A scene node type is represented by a four character code - such as 'cube' or 'mesh' instead of simple numbers, to avoid - name clashes with external scene nodes.*/ - enum ESCENE_NODE_TYPE - { - //! of type CSceneManager (note that ISceneManager is not(!) an ISceneNode) - ESNT_SCENE_MANAGER = MAKE_IRR_ID('s','m','n','g'), +//! An enumeration for all types of built-in scene nodes +/** A scene node type is represented by a four character code +such as 'cube' or 'mesh' instead of simple numbers, to avoid +name clashes with external scene nodes.*/ +enum ESCENE_NODE_TYPE +{ + //! of type CSceneManager (note that ISceneManager is not(!) an ISceneNode) + ESNT_SCENE_MANAGER = MAKE_IRR_ID('s', 'm', 'n', 'g'), - //! Mesh Scene Node - ESNT_MESH = MAKE_IRR_ID('m','e','s','h'), + //! Mesh Scene Node + ESNT_MESH = MAKE_IRR_ID('m', 'e', 's', 'h'), - //! Empty Scene Node - ESNT_EMPTY = MAKE_IRR_ID('e','m','t','y'), + //! Empty Scene Node + ESNT_EMPTY = MAKE_IRR_ID('e', 'm', 't', 'y'), - //! Dummy Transformation Scene Node - ESNT_DUMMY_TRANSFORMATION = MAKE_IRR_ID('d','m','m','y'), + //! Dummy Transformation Scene Node + ESNT_DUMMY_TRANSFORMATION = MAKE_IRR_ID('d', 'm', 'm', 'y'), - //! Camera Scene Node - ESNT_CAMERA = MAKE_IRR_ID('c','a','m','_'), + //! Camera Scene Node + ESNT_CAMERA = MAKE_IRR_ID('c', 'a', 'm', '_'), - //! Billboard Scene Node - ESNT_BILLBOARD = MAKE_IRR_ID('b','i','l','l'), + //! Billboard Scene Node + ESNT_BILLBOARD = MAKE_IRR_ID('b', 'i', 'l', 'l'), - //! Animated Mesh Scene Node - ESNT_ANIMATED_MESH = MAKE_IRR_ID('a','m','s','h'), - - //! Unknown scene node - ESNT_UNKNOWN = MAKE_IRR_ID('u','n','k','n'), - - //! Will match with any scene node when checking types - ESNT_ANY = MAKE_IRR_ID('a','n','y','_') - }; + //! Animated Mesh Scene Node + ESNT_ANIMATED_MESH = MAKE_IRR_ID('a', 'm', 's', 'h'), + //! Unknown scene node + ESNT_UNKNOWN = MAKE_IRR_ID('u', 'n', 'k', 'n'), + //! Will match with any scene node when checking types + ESNT_ANY = MAKE_IRR_ID('a', 'n', 'y', '_') +}; } // end namespace scene } // end namespace irr diff --git a/include/EShaderTypes.h b/include/EShaderTypes.h index f5f87a7a..8d0b3a5e 100644 --- a/include/EShaderTypes.h +++ b/include/EShaderTypes.h @@ -23,15 +23,15 @@ enum E_VERTEX_SHADER_TYPE }; //! Names for all vertex shader types, each entry corresponds to a E_VERTEX_SHADER_TYPE entry. -const c8* const VERTEX_SHADER_TYPE_NAMES[] = { - "vs_1_1", - "vs_2_0", - "vs_2_a", - "vs_3_0", - "vs_4_0", - "vs_4_1", - "vs_5_0", - 0 }; +const c8 *const VERTEX_SHADER_TYPE_NAMES[] = { + "vs_1_1", + "vs_2_0", + "vs_2_a", + "vs_3_0", + "vs_4_0", + "vs_4_1", + "vs_5_0", + 0}; //! Compile target enumeration for the addHighLevelShaderMaterial() method. enum E_PIXEL_SHADER_TYPE @@ -53,19 +53,19 @@ enum E_PIXEL_SHADER_TYPE }; //! Names for all pixel shader types, each entry corresponds to a E_PIXEL_SHADER_TYPE entry. -const c8* const PIXEL_SHADER_TYPE_NAMES[] = { - "ps_1_1", - "ps_1_2", - "ps_1_3", - "ps_1_4", - "ps_2_0", - "ps_2_a", - "ps_2_b", - "ps_3_0", - "ps_4_0", - "ps_4_1", - "ps_5_0", - 0 }; +const c8 *const PIXEL_SHADER_TYPE_NAMES[] = { + "ps_1_1", + "ps_1_2", + "ps_1_3", + "ps_1_4", + "ps_2_0", + "ps_2_a", + "ps_2_b", + "ps_3_0", + "ps_4_0", + "ps_4_1", + "ps_5_0", + 0}; //! Enum for supported geometry shader types enum E_GEOMETRY_SHADER_TYPE @@ -77,10 +77,9 @@ enum E_GEOMETRY_SHADER_TYPE }; //! String names for supported geometry shader types -const c8* const GEOMETRY_SHADER_TYPE_NAMES[] = { - "gs_4_0", - 0 }; - +const c8 *const GEOMETRY_SHADER_TYPE_NAMES[] = { + "gs_4_0", + 0}; } // end namespace video } // end namespace irr diff --git a/include/EVertexAttributes.h b/include/EVertexAttributes.h index 67461c4a..40b05a6d 100644 --- a/include/EVertexAttributes.h +++ b/include/EVertexAttributes.h @@ -19,17 +19,16 @@ enum E_VERTEX_ATTRIBUTES }; //! Array holding the built in vertex attribute names -const char* const sBuiltInVertexAttributeNames[] = -{ - "inVertexPosition", - "inVertexNormal", - "inVertexColor", - "inTexCoord0", - "inTexCoord1", - "inVertexTangent", - "inVertexBinormal", - 0 -}; +const char *const sBuiltInVertexAttributeNames[] = + { + "inVertexPosition", + "inVertexNormal", + "inVertexColor", + "inTexCoord0", + "inTexCoord1", + "inVertexTangent", + "inVertexBinormal", + 0}; } // end namespace video } // end namespace irr diff --git a/include/IAnimatedMesh.h b/include/IAnimatedMesh.h index f5ad6fe3..80b3bc3c 100644 --- a/include/IAnimatedMesh.h +++ b/include/IAnimatedMesh.h @@ -11,60 +11,59 @@ namespace irr { namespace scene { - //! Interface for an animated mesh. - /** There are already simple implementations of this interface available so - you don't have to implement this interface on your own if you need to: - You might want to use irr::scene::SAnimatedMesh, irr::scene::SMesh, - irr::scene::SMeshBuffer etc. */ - class IAnimatedMesh : public IMesh +//! Interface for an animated mesh. +/** There are already simple implementations of this interface available so +you don't have to implement this interface on your own if you need to: +You might want to use irr::scene::SAnimatedMesh, irr::scene::SMesh, +irr::scene::SMeshBuffer etc. */ +class IAnimatedMesh : public IMesh +{ +public: + //! Gets the frame count of the animated mesh. + /** Note that the play-time is usually getFrameCount()-1 as it stops as soon as the last frame-key is reached. + \return The amount of frames. If the amount is 1, + it is a static, non animated mesh. */ + virtual u32 getFrameCount() const = 0; + + //! Gets the animation speed of the animated mesh. + /** \return The number of frames per second to play the + animation with by default. If the amount is 0, + it is a static, non animated mesh. */ + virtual f32 getAnimationSpeed() const = 0; + + //! Sets the animation speed of the animated mesh. + /** \param fps Number of frames per second to play the + animation with by default. If the amount is 0, + it is not animated. The actual speed is set in the + scene node the mesh is instantiated in.*/ + virtual void setAnimationSpeed(f32 fps) = 0; + + //! Returns the IMesh interface for a frame. + /** \param frame: Frame number as zero based index. The maximum + frame number is getFrameCount() - 1; + \param detailLevel: Level of detail. 0 is the lowest, 255 the + highest level of detail. Most meshes will ignore the detail level. + \param startFrameLoop: Because some animated meshes (.MD2) are + blended between 2 static frames, and maybe animated in a loop, + the startFrameLoop and the endFrameLoop have to be defined, to + prevent the animation to be blended between frames which are + outside of this loop. + If startFrameLoop and endFrameLoop are both -1, they are ignored. + \param endFrameLoop: see startFrameLoop. + \return Returns the animated mesh based on a detail level. */ + virtual IMesh *getMesh(s32 frame, s32 detailLevel = 255, s32 startFrameLoop = -1, s32 endFrameLoop = -1) = 0; + + //! Returns the type of the animated mesh. + /** In most cases it is not necessary to use this method. + This is useful for making a safe downcast. For example, + if getMeshType() returns EAMT_MD2 it's safe to cast the + IAnimatedMesh to IAnimatedMeshMD2. + \returns Type of the mesh. */ + E_ANIMATED_MESH_TYPE getMeshType() const override { - public: - - //! Gets the frame count of the animated mesh. - /** Note that the play-time is usually getFrameCount()-1 as it stops as soon as the last frame-key is reached. - \return The amount of frames. If the amount is 1, - it is a static, non animated mesh. */ - virtual u32 getFrameCount() const = 0; - - //! Gets the animation speed of the animated mesh. - /** \return The number of frames per second to play the - animation with by default. If the amount is 0, - it is a static, non animated mesh. */ - virtual f32 getAnimationSpeed() const = 0; - - //! Sets the animation speed of the animated mesh. - /** \param fps Number of frames per second to play the - animation with by default. If the amount is 0, - it is not animated. The actual speed is set in the - scene node the mesh is instantiated in.*/ - virtual void setAnimationSpeed(f32 fps) =0; - - //! Returns the IMesh interface for a frame. - /** \param frame: Frame number as zero based index. The maximum - frame number is getFrameCount() - 1; - \param detailLevel: Level of detail. 0 is the lowest, 255 the - highest level of detail. Most meshes will ignore the detail level. - \param startFrameLoop: Because some animated meshes (.MD2) are - blended between 2 static frames, and maybe animated in a loop, - the startFrameLoop and the endFrameLoop have to be defined, to - prevent the animation to be blended between frames which are - outside of this loop. - If startFrameLoop and endFrameLoop are both -1, they are ignored. - \param endFrameLoop: see startFrameLoop. - \return Returns the animated mesh based on a detail level. */ - virtual IMesh* getMesh(s32 frame, s32 detailLevel=255, s32 startFrameLoop=-1, s32 endFrameLoop=-1) = 0; - - //! Returns the type of the animated mesh. - /** In most cases it is not necessary to use this method. - This is useful for making a safe downcast. For example, - if getMeshType() returns EAMT_MD2 it's safe to cast the - IAnimatedMesh to IAnimatedMeshMD2. - \returns Type of the mesh. */ - E_ANIMATED_MESH_TYPE getMeshType() const override - { - return EAMT_UNKNOWN; - } - }; + return EAMT_UNKNOWN; + } +}; } // end namespace scene } // end namespace irr diff --git a/include/IAnimatedMeshSceneNode.h b/include/IAnimatedMeshSceneNode.h index c15caabf..65fdaaad 100644 --- a/include/IAnimatedMeshSceneNode.h +++ b/include/IAnimatedMeshSceneNode.h @@ -12,162 +12,158 @@ namespace irr { namespace scene { - enum E_JOINT_UPDATE_ON_RENDER - { - //! do nothing - EJUOR_NONE = 0, +enum E_JOINT_UPDATE_ON_RENDER +{ + //! do nothing + EJUOR_NONE = 0, - //! get joints positions from the mesh (for attached nodes, etc) - EJUOR_READ, + //! get joints positions from the mesh (for attached nodes, etc) + EJUOR_READ, - //! control joint positions in the mesh (eg. ragdolls, or set the animation from animateJoints() ) - EJUOR_CONTROL - }; + //! control joint positions in the mesh (eg. ragdolls, or set the animation from animateJoints() ) + EJUOR_CONTROL +}; +class IAnimatedMeshSceneNode; - class IAnimatedMeshSceneNode; +//! Callback interface for catching events of ended animations. +/** Implement this interface and use +IAnimatedMeshSceneNode::setAnimationEndCallback to be able to +be notified if an animation playback has ended. +**/ +class IAnimationEndCallBack : public virtual IReferenceCounted +{ +public: + //! Will be called when the animation playback has ended. + /** See IAnimatedMeshSceneNode::setAnimationEndCallback for + more information. + \param node: Node of which the animation has ended. */ + virtual void OnAnimationEnd(IAnimatedMeshSceneNode *node) = 0; +}; - //! Callback interface for catching events of ended animations. - /** Implement this interface and use - IAnimatedMeshSceneNode::setAnimationEndCallback to be able to - be notified if an animation playback has ended. - **/ - class IAnimationEndCallBack : public virtual IReferenceCounted - { - public: +//! Scene node capable of displaying an animated mesh. +class IAnimatedMeshSceneNode : public ISceneNode +{ +public: + //! Constructor + IAnimatedMeshSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f)) : + ISceneNode(parent, mgr, id, position, rotation, scale) {} - //! Will be called when the animation playback has ended. - /** See IAnimatedMeshSceneNode::setAnimationEndCallback for - more information. - \param node: Node of which the animation has ended. */ - virtual void OnAnimationEnd(IAnimatedMeshSceneNode* node) = 0; - }; + //! Destructor + virtual ~IAnimatedMeshSceneNode() {} - //! Scene node capable of displaying an animated mesh. - class IAnimatedMeshSceneNode : public ISceneNode - { - public: + //! Sets the current frame number. + /** From now on the animation is played from this frame. + \param frame: Number of the frame to let the animation be started from. + The frame number must be a valid frame number of the IMesh used by this + scene node. Set IAnimatedMesh::getMesh() for details. */ + virtual void setCurrentFrame(f32 frame) = 0; - //! Constructor - IAnimatedMeshSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)) - : ISceneNode(parent, mgr, id, position, rotation, scale) {} + //! Sets the frame numbers between the animation is looped. + /** The default is 0 to getFrameCount()-1 of the mesh. + Number of played frames is end-start. + It interpolates toward the last frame but stops when it is reached. + It does not interpolate back to start even when looping. + Looping animations should ensure last and first frame-key are identical. + \param begin: Start frame number of the loop. + \param end: End frame number of the loop. + \return True if successful, false if not. */ + virtual bool setFrameLoop(s32 begin, s32 end) = 0; - //! Destructor - virtual ~IAnimatedMeshSceneNode() {} + //! Sets the speed with which the animation is played. + /** \param framesPerSecond: Frames per second played. */ + virtual void setAnimationSpeed(f32 framesPerSecond) = 0; - //! Sets the current frame number. - /** From now on the animation is played from this frame. - \param frame: Number of the frame to let the animation be started from. - The frame number must be a valid frame number of the IMesh used by this - scene node. Set IAnimatedMesh::getMesh() for details. */ - virtual void setCurrentFrame(f32 frame) = 0; + //! Gets the speed with which the animation is played. + /** \return Frames per second played. */ + virtual f32 getAnimationSpeed() const = 0; - //! Sets the frame numbers between the animation is looped. - /** The default is 0 to getFrameCount()-1 of the mesh. - Number of played frames is end-start. - It interpolates toward the last frame but stops when it is reached. - It does not interpolate back to start even when looping. - Looping animations should ensure last and first frame-key are identical. - \param begin: Start frame number of the loop. - \param end: End frame number of the loop. - \return True if successful, false if not. */ - virtual bool setFrameLoop(s32 begin, s32 end) = 0; + //! Get a pointer to a joint in the mesh (if the mesh is a bone based mesh). + /** With this method it is possible to attach scene nodes to + joints for example possible to attach a weapon to the left hand + of an animated model. This example shows how: + \code + ISceneNode* hand = + yourAnimatedMeshSceneNode->getJointNode("LeftHand"); + hand->addChild(weaponSceneNode); + \endcode + Please note that the joint returned by this method may not exist + before this call and the joints in the node were created by it. + \param jointName: Name of the joint. + \return Pointer to the scene node which represents the joint + with the specified name. Returns 0 if the contained mesh is not + an skinned mesh or the name of the joint could not be found. */ + virtual IBoneSceneNode *getJointNode(const c8 *jointName) = 0; - //! Sets the speed with which the animation is played. - /** \param framesPerSecond: Frames per second played. */ - virtual void setAnimationSpeed(f32 framesPerSecond) = 0; + //! same as getJointNode(const c8* jointName), but based on id + virtual IBoneSceneNode *getJointNode(u32 jointID) = 0; - //! Gets the speed with which the animation is played. - /** \return Frames per second played. */ - virtual f32 getAnimationSpeed() const =0; + //! Gets joint count. + /** \return Amount of joints in the mesh. */ + virtual u32 getJointCount() const = 0; - //! Get a pointer to a joint in the mesh (if the mesh is a bone based mesh). - /** With this method it is possible to attach scene nodes to - joints for example possible to attach a weapon to the left hand - of an animated model. This example shows how: - \code - ISceneNode* hand = - yourAnimatedMeshSceneNode->getJointNode("LeftHand"); - hand->addChild(weaponSceneNode); - \endcode - Please note that the joint returned by this method may not exist - before this call and the joints in the node were created by it. - \param jointName: Name of the joint. - \return Pointer to the scene node which represents the joint - with the specified name. Returns 0 if the contained mesh is not - an skinned mesh or the name of the joint could not be found. */ - virtual IBoneSceneNode* getJointNode(const c8* jointName)=0; + //! Returns the currently displayed frame number. + virtual f32 getFrameNr() const = 0; + //! Returns the current start frame number. + virtual s32 getStartFrame() const = 0; + //! Returns the current end frame number. + virtual s32 getEndFrame() const = 0; - //! same as getJointNode(const c8* jointName), but based on id - virtual IBoneSceneNode* getJointNode(u32 jointID) = 0; + //! Sets looping mode which is on by default. + /** If set to false, animations will not be played looped. */ + virtual void setLoopMode(bool playAnimationLooped) = 0; - //! Gets joint count. - /** \return Amount of joints in the mesh. */ - virtual u32 getJointCount() const = 0; + //! returns the current loop mode + /** When true the animations are played looped */ + virtual bool getLoopMode() const = 0; - //! Returns the currently displayed frame number. - virtual f32 getFrameNr() const = 0; - //! Returns the current start frame number. - virtual s32 getStartFrame() const = 0; - //! Returns the current end frame number. - virtual s32 getEndFrame() const = 0; + //! Sets a callback interface which will be called if an animation playback has ended. + /** Set this to 0 to disable the callback again. + Please note that this will only be called when in non looped + mode, see IAnimatedMeshSceneNode::setLoopMode(). */ + virtual void setAnimationEndCallback(IAnimationEndCallBack *callback = 0) = 0; - //! Sets looping mode which is on by default. - /** If set to false, animations will not be played looped. */ - virtual void setLoopMode(bool playAnimationLooped) = 0; + //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. + /** In this way it is possible to change the materials a mesh + causing all mesh scene nodes referencing this mesh to change + too. */ + virtual void setReadOnlyMaterials(bool readonly) = 0; - //! returns the current loop mode - /** When true the animations are played looped */ - virtual bool getLoopMode() const = 0; + //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style + virtual bool isReadOnlyMaterials() const = 0; - //! Sets a callback interface which will be called if an animation playback has ended. - /** Set this to 0 to disable the callback again. - Please note that this will only be called when in non looped - mode, see IAnimatedMeshSceneNode::setLoopMode(). */ - virtual void setAnimationEndCallback(IAnimationEndCallBack* callback=0) = 0; + //! Sets a new mesh + virtual void setMesh(IAnimatedMesh *mesh) = 0; - //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. - /** In this way it is possible to change the materials a mesh - causing all mesh scene nodes referencing this mesh to change - too. */ - virtual void setReadOnlyMaterials(bool readonly) = 0; + //! Returns the current mesh + virtual IAnimatedMesh *getMesh(void) = 0; - //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style - virtual bool isReadOnlyMaterials() const = 0; + //! Set how the joints should be updated on render + virtual void setJointMode(E_JOINT_UPDATE_ON_RENDER mode) = 0; - //! Sets a new mesh - virtual void setMesh(IAnimatedMesh* mesh) = 0; + //! Sets the transition time in seconds + /** Note: This needs to enable joints, and setJointmode set to + EJUOR_CONTROL. You must call animateJoints(), or the mesh will + not animate. */ + virtual void setTransitionTime(f32 Time) = 0; - //! Returns the current mesh - virtual IAnimatedMesh* getMesh(void) = 0; + //! animates the joints in the mesh based on the current frame. + /** Also takes in to account transitions. */ + virtual void animateJoints(bool CalculateAbsolutePositions = true) = 0; - //! Set how the joints should be updated on render - virtual void setJointMode(E_JOINT_UPDATE_ON_RENDER mode)=0; + //! render mesh ignoring its transformation. + /** Culling is unaffected. */ + virtual void setRenderFromIdentity(bool On) = 0; - //! Sets the transition time in seconds - /** Note: This needs to enable joints, and setJointmode set to - EJUOR_CONTROL. You must call animateJoints(), or the mesh will - not animate. */ - virtual void setTransitionTime(f32 Time) =0; - - //! animates the joints in the mesh based on the current frame. - /** Also takes in to account transitions. */ - virtual void animateJoints(bool CalculateAbsolutePositions=true) = 0; - - //! render mesh ignoring its transformation. - /** Culling is unaffected. */ - virtual void setRenderFromIdentity( bool On )=0; - - //! Creates a clone of this scene node and its children. - /** \param newParent An optional new parent. - \param newManager An optional new scene manager. - \return The newly created clone of this node. */ - virtual ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) = 0; - - }; + //! Creates a clone of this scene node and its children. + /** \param newParent An optional new parent. + \param newManager An optional new scene manager. + \return The newly created clone of this node. */ + virtual ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/IAttributes.h b/include/IAttributes.h index 5b8b1ba9..906d334a 100644 --- a/include/IAttributes.h +++ b/include/IAttributes.h @@ -14,7 +14,7 @@ namespace irr { namespace video { - class ITexture; +class ITexture; } // end namespace video namespace io { @@ -23,32 +23,30 @@ namespace io class IAttributes : public virtual IReferenceCounted { public: - //! Returns amount of attributes in this collection of attributes. virtual u32 getAttributeCount() const = 0; //! Returns attribute name by index. //! \param index: Index value, must be between 0 and getAttributeCount()-1. - virtual const c8* getAttributeName(s32 index) const = 0; + virtual const c8 *getAttributeName(s32 index) const = 0; //! Returns the type of an attribute //! \param attributeName: Name for the attribute - virtual E_ATTRIBUTE_TYPE getAttributeType(const c8* attributeName) const = 0; + virtual E_ATTRIBUTE_TYPE getAttributeType(const c8 *attributeName) const = 0; //! Returns attribute type by index. //! \param index: Index value, must be between 0 and getAttributeCount()-1. virtual E_ATTRIBUTE_TYPE getAttributeType(s32 index) const = 0; //! Returns if an attribute with a name exists - virtual bool existsAttribute(const c8* attributeName) const = 0; + virtual bool existsAttribute(const c8 *attributeName) const = 0; //! Returns attribute index from name, -1 if not found - virtual s32 findAttribute(const c8* attributeName) const = 0; + virtual s32 findAttribute(const c8 *attributeName) const = 0; //! Removes all attributes virtual void clear() = 0; - /* Integer Attribute @@ -56,16 +54,16 @@ public: */ //! Adds an attribute as integer - virtual void addInt(const c8* attributeName, s32 value) = 0; + virtual void addInt(const c8 *attributeName, s32 value) = 0; //! Sets an attribute as integer value - virtual void setAttribute(const c8* attributeName, s32 value) = 0; + virtual void setAttribute(const c8 *attributeName, s32 value) = 0; //! Gets an attribute as integer value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - virtual s32 getAttributeAsInt(const c8* attributeName, irr::s32 defaultNotFound=0) const = 0; + virtual s32 getAttributeAsInt(const c8 *attributeName, irr::s32 defaultNotFound = 0) const = 0; //! Gets an attribute as integer value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -81,16 +79,16 @@ public: */ //! Adds an attribute as float - virtual void addFloat(const c8* attributeName, f32 value) = 0; + virtual void addFloat(const c8 *attributeName, f32 value) = 0; //! Sets a attribute as float value - virtual void setAttribute(const c8* attributeName, f32 value) = 0; + virtual void setAttribute(const c8 *attributeName, f32 value) = 0; //! Gets an attribute as float value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - virtual f32 getAttributeAsFloat(const c8* attributeName, irr::f32 defaultNotFound=0.f) const = 0; + virtual f32 getAttributeAsFloat(const c8 *attributeName, irr::f32 defaultNotFound = 0.f) const = 0; //! Gets an attribute as float value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -99,22 +97,21 @@ public: //! Sets an attribute as float value virtual void setAttribute(s32 index, f32 value) = 0; - /* Bool Attribute */ //! Adds an attribute as bool - virtual void addBool(const c8* attributeName, bool value) = 0; + virtual void addBool(const c8 *attributeName, bool value) = 0; //! Sets an attribute as boolean value - virtual void setAttribute(const c8* attributeName, bool value) = 0; + virtual void setAttribute(const c8 *attributeName, bool value) = 0; //! Gets an attribute as boolean value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - virtual bool getAttributeAsBool(const c8* attributeName, bool defaultNotFound=false) const = 0; + virtual bool getAttributeAsBool(const c8 *attributeName, bool defaultNotFound = false) const = 0; //! Gets an attribute as boolean value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -122,7 +119,6 @@ public: //! Sets an attribute as boolean value virtual void setAttribute(s32 index, bool value) = 0; - }; } // end namespace io diff --git a/include/IBillboardSceneNode.h b/include/IBillboardSceneNode.h index a05c949a..3e7026ac 100644 --- a/include/IBillboardSceneNode.h +++ b/include/IBillboardSceneNode.h @@ -10,8 +10,8 @@ namespace irr { namespace scene { - class ICameraSceneNode; - class IMeshBuffer; +class ICameraSceneNode; +class IMeshBuffer; //! A billboard scene node. /** A billboard is like a 3d sprite: A 2d element, @@ -21,14 +21,13 @@ lensflares, particles and things like that. class IBillboardSceneNode : public ISceneNode { public: - //! Constructor - IBillboardSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0)) - : ISceneNode(parent, mgr, id, position) {} + IBillboardSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0)) : + ISceneNode(parent, mgr, id, position) {} //! Sets the size of the billboard, making it rectangular. - virtual void setSize(const core::dimension2d& size) = 0; + virtual void setSize(const core::dimension2d &size) = 0; //! Sets the size of the billboard with independent widths of the bottom and top edges. /** \param[in] height The height of the billboard. @@ -42,38 +41,38 @@ public: Use getWidths() to retrieve the bottom and top edges independently. \return Size of the billboard. */ - virtual const core::dimension2d& getSize() const = 0; + virtual const core::dimension2d &getSize() const = 0; //! Gets the size of the the billboard and handles independent top and bottom edge widths correctly. /** \param[out] height The height of the billboard. \param[out] bottomEdgeWidth The width of the bottom edge of the billboard. \param[out] topEdgeWidth The width of the top edge of the billboard. */ - virtual void getSize(f32& height, f32& bottomEdgeWidth, f32& topEdgeWidth) const =0; + virtual void getSize(f32 &height, f32 &bottomEdgeWidth, f32 &topEdgeWidth) const = 0; //! Set the color of all vertices of the billboard /** \param[in] overallColor Color to set */ - virtual void setColor(const video::SColor& overallColor) = 0; + virtual void setColor(const video::SColor &overallColor) = 0; //! Set the color of the top and bottom vertices of the billboard /** \param[in] topColor Color to set the top vertices \param[in] bottomColor Color to set the bottom vertices */ - virtual void setColor(const video::SColor& topColor, - const video::SColor& bottomColor) = 0; + virtual void setColor(const video::SColor &topColor, + const video::SColor &bottomColor) = 0; //! Gets the color of the top and bottom vertices of the billboard /** \param[out] topColor Stores the color of the top vertices \param[out] bottomColor Stores the color of the bottom vertices */ - virtual void getColor(video::SColor& topColor, - video::SColor& bottomColor) const = 0; + virtual void getColor(video::SColor &topColor, + video::SColor &bottomColor) const = 0; //! Get the real boundingbox used by the billboard, which can depend on the active camera. /** The boundingbox returned will use absolute coordinates. The billboard orients itself toward the camera and some only update in render(). - So we don't know the real boundingboxes before that. Which would be too late for culling. - That is why the usual getBoundingBox will return a "safe" boundingbox which is guaranteed - to contain the billboard. While this function can return the real one. */ - virtual const core::aabbox3d& getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode* camera) = 0; + So we don't know the real boundingboxes before that. Which would be too late for culling. + That is why the usual getBoundingBox will return a "safe" boundingbox which is guaranteed + to contain the billboard. While this function can return the real one. */ + virtual const core::aabbox3d &getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode *camera) = 0; //! Get the amount of mesh buffers. /** \return Amount of mesh buffers (IMeshBuffer) in this mesh. */ @@ -84,7 +83,7 @@ public: So this is mainly useful to access/modify the uv-coordinates. \param nr: Zero based index of the mesh buffer. \return Pointer to the mesh buffer or 0 if there is no such mesh buffer. */ - virtual IMeshBuffer* getMeshBuffer(u32 nr) const = 0; + virtual IMeshBuffer *getMeshBuffer(u32 nr) const = 0; }; } // end namespace scene diff --git a/include/IBoneSceneNode.h b/include/IBoneSceneNode.h index f57b902c..d242ef8f 100644 --- a/include/IBoneSceneNode.h +++ b/include/IBoneSceneNode.h @@ -11,90 +11,87 @@ namespace irr namespace scene { - //! Enumeration for different bone animation modes - enum E_BONE_ANIMATION_MODE - { - //! The bone is usually animated, unless it's parent is not animated - EBAM_AUTOMATIC=0, +//! Enumeration for different bone animation modes +enum E_BONE_ANIMATION_MODE +{ + //! The bone is usually animated, unless it's parent is not animated + EBAM_AUTOMATIC = 0, - //! The bone is animated by the skin, if it's parent is not animated then animation will resume from this bone onward - EBAM_ANIMATED, + //! The bone is animated by the skin, if it's parent is not animated then animation will resume from this bone onward + EBAM_ANIMATED, - //! The bone is not animated by the skin - EBAM_UNANIMATED, + //! The bone is not animated by the skin + EBAM_UNANIMATED, - //! Not an animation mode, just here to count the available modes - EBAM_COUNT + //! Not an animation mode, just here to count the available modes + EBAM_COUNT - }; +}; - enum E_BONE_SKINNING_SPACE - { - //! local skinning, standard - EBSS_LOCAL=0, +enum E_BONE_SKINNING_SPACE +{ + //! local skinning, standard + EBSS_LOCAL = 0, - //! global skinning - EBSS_GLOBAL, + //! global skinning + EBSS_GLOBAL, - EBSS_COUNT - }; + EBSS_COUNT +}; - //! Names for bone animation modes - const c8* const BoneAnimationModeNames[] = - { - "automatic", - "animated", - "unanimated", - 0, - }; +//! Names for bone animation modes +const c8 *const BoneAnimationModeNames[] = + { + "automatic", + "animated", + "unanimated", + 0, +}; +//! Interface for bones used for skeletal animation. +/** Used with ISkinnedMesh and IAnimatedMeshSceneNode. */ +class IBoneSceneNode : public ISceneNode +{ +public: + IBoneSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id = -1) : + ISceneNode(parent, mgr, id), positionHint(-1), scaleHint(-1), rotationHint(-1) {} - //! Interface for bones used for skeletal animation. - /** Used with ISkinnedMesh and IAnimatedMeshSceneNode. */ - class IBoneSceneNode : public ISceneNode - { - public: + //! Get the index of the bone + virtual u32 getBoneIndex() const = 0; - IBoneSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id=-1) : - ISceneNode(parent, mgr, id),positionHint(-1),scaleHint(-1),rotationHint(-1) { } + //! Sets the animation mode of the bone. + /** \return True if successful. (Unused) */ + virtual bool setAnimationMode(E_BONE_ANIMATION_MODE mode) = 0; - //! Get the index of the bone - virtual u32 getBoneIndex() const = 0; + //! Gets the current animation mode of the bone + virtual E_BONE_ANIMATION_MODE getAnimationMode() const = 0; - //! Sets the animation mode of the bone. - /** \return True if successful. (Unused) */ - virtual bool setAnimationMode(E_BONE_ANIMATION_MODE mode) = 0; + //! Get the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override = 0; - //! Gets the current animation mode of the bone - virtual E_BONE_ANIMATION_MODE getAnimationMode() const = 0; + //! Returns the relative transformation of the scene node. + // virtual core::matrix4 getRelativeTransformation() const = 0; - //! Get the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override = 0; + //! The animation method. + void OnAnimate(u32 timeMs) override = 0; - //! Returns the relative transformation of the scene node. - //virtual core::matrix4 getRelativeTransformation() const = 0; + //! The render method. + /** Does nothing as bones are not visible. */ + void render() override {} - //! The animation method. - void OnAnimate(u32 timeMs) override =0; + //! How the relative transformation of the bone is used + virtual void setSkinningSpace(E_BONE_SKINNING_SPACE space) = 0; - //! The render method. - /** Does nothing as bones are not visible. */ - void render() override { } + //! How the relative transformation of the bone is used + virtual E_BONE_SKINNING_SPACE getSkinningSpace() const = 0; - //! How the relative transformation of the bone is used - virtual void setSkinningSpace( E_BONE_SKINNING_SPACE space ) =0; - - //! How the relative transformation of the bone is used - virtual E_BONE_SKINNING_SPACE getSkinningSpace() const =0; - - //! Updates the absolute position based on the relative and the parents position - virtual void updateAbsolutePositionOfAllChildren()=0; - - s32 positionHint; - s32 scaleHint; - s32 rotationHint; - }; + //! Updates the absolute position based on the relative and the parents position + virtual void updateAbsolutePositionOfAllChildren() = 0; + s32 positionHint; + s32 scaleHint; + s32 rotationHint; +}; } // end namespace scene } // end namespace irr diff --git a/include/ICameraSceneNode.h b/include/ICameraSceneNode.h index acc7e5d2..a7c72428 100644 --- a/include/ICameraSceneNode.h +++ b/include/ICameraSceneNode.h @@ -11,175 +11,174 @@ namespace irr { namespace scene { - struct SViewFrustum; +struct SViewFrustum; - //! Scene Node which is a (controllable) camera. - /** The whole scene will be rendered from the cameras point of view. - Because the ICameraSceneNode is a SceneNode, it can be attached to any - other scene node, and will follow its parents movement, rotation and so - on. +//! Scene Node which is a (controllable) camera. +/** The whole scene will be rendered from the cameras point of view. +Because the ICameraSceneNode is a SceneNode, it can be attached to any +other scene node, and will follow its parents movement, rotation and so +on. +*/ +class ICameraSceneNode : public ISceneNode, public IEventReceiver +{ +public: + //! Constructor + ICameraSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f)) : + ISceneNode(parent, mgr, id, position, rotation, scale), + IsOrthogonal(false) {} + + //! Sets the projection matrix of the camera. + /** The core::matrix4 class has some methods to build a + projection matrix. e.g: + core::matrix4::buildProjectionMatrixPerspectiveFovLH. + Note that the matrix will only stay as set by this method until + one of the following Methods are called: setNearValue, + setFarValue, setAspectRatio, setFOV. + NOTE: The frustum is not updated before render() is called + unless you explicitly call updateMatrices() + \param projection The new projection matrix of the camera. + \param isOrthogonal Set this to true if the matrix is an + orthogonal one (e.g. from matrix4::buildProjectionMatrixOrtho). */ - class ICameraSceneNode : public ISceneNode, public IEventReceiver + virtual void setProjectionMatrix(const core::matrix4 &projection, bool isOrthogonal = false) = 0; + + //! Gets the current projection matrix of the camera. + /** \return The current projection matrix of the camera. */ + virtual const core::matrix4 &getProjectionMatrix() const = 0; + + //! Gets the current view matrix of the camera. + /** \return The current view matrix of the camera. */ + virtual const core::matrix4 &getViewMatrix() const = 0; + + //! Sets a custom view matrix affector. + /** The matrix passed here, will be multiplied with the view + matrix when it gets updated. This allows for custom camera + setups like, for example, a reflection camera. + \param affector The affector matrix. */ + virtual void setViewMatrixAffector(const core::matrix4 &affector) = 0; + + //! Get the custom view matrix affector. + /** \return The affector matrix. */ + virtual const core::matrix4 &getViewMatrixAffector() const = 0; + + //! It is possible to send mouse and key events to the camera. + /** Most cameras may ignore this input, but camera scene nodes + which are created for example with + ISceneManager::addCameraSceneNodeMaya or + ISceneManager::addCameraSceneNodeFPS, may want to get + this input for changing their position, look at target or + whatever. */ + bool OnEvent(const SEvent &event) override = 0; + + //! Sets the look at target of the camera + /** If the camera's target and rotation are bound ( @see + bindTargetAndRotation() ) then calling this will also change + the camera's scene node rotation to match the target. + Note that setTarget uses the current absolute position + internally, so if you changed setPosition since last rendering you must + call updateAbsolutePosition before using this function. + \param pos Look at target of the camera, in world co-ordinates. */ + virtual void setTarget(const core::vector3df &pos) = 0; + + //! Sets the rotation of the node. + /** This only modifies the relative rotation of the node. + If the camera's target and rotation are bound ( @see + bindTargetAndRotation() ) then calling this will also change + the camera's target to match the rotation. + \param rotation New rotation of the node in degrees. */ + void setRotation(const core::vector3df &rotation) override = 0; + + //! Gets the current look at target of the camera + /** \return The current look at target of the camera, in world co-ordinates */ + virtual const core::vector3df &getTarget() const = 0; + + //! Sets the up vector of the camera. + /** \param pos: New upvector of the camera. */ + virtual void setUpVector(const core::vector3df &pos) = 0; + + //! Gets the up vector of the camera. + /** \return The up vector of the camera, in world space. */ + virtual const core::vector3df &getUpVector() const = 0; + + //! Gets the value of the near plane of the camera. + /** \return The value of the near plane of the camera. */ + virtual f32 getNearValue() const = 0; + + //! Gets the value of the far plane of the camera. + /** \return The value of the far plane of the camera. */ + virtual f32 getFarValue() const = 0; + + //! Gets the aspect ratio of the camera. + /** \return The aspect ratio of the camera. */ + virtual f32 getAspectRatio() const = 0; + + //! Gets the field of view of the camera. + /** \return The field of view of the camera in radians. */ + virtual f32 getFOV() const = 0; + + //! Sets the value of the near clipping plane. (default: 1.0f) + /** \param zn: New z near value. */ + virtual void setNearValue(f32 zn) = 0; + + //! Sets the value of the far clipping plane (default: 2000.0f) + /** \param zf: New z far value. */ + virtual void setFarValue(f32 zf) = 0; + + //! Sets the aspect ratio (default: 4.0f / 3.0f) + /** \param aspect: New aspect ratio. */ + virtual void setAspectRatio(f32 aspect) = 0; + + //! Sets the field of view (Default: PI / 2.5f) + /** \param fovy: New field of view in radians. */ + virtual void setFOV(f32 fovy) = 0; + + //! Get the view frustum. + /** \return The current view frustum. */ + virtual const SViewFrustum *getViewFrustum() const = 0; + + //! Disables or enables the camera to get key or mouse inputs. + /** If this is set to true, the camera will respond to key + inputs otherwise not. */ + virtual void setInputReceiverEnabled(bool enabled) = 0; + + //! Checks if the input receiver of the camera is currently enabled. + virtual bool isInputReceiverEnabled() const = 0; + + //! Checks if a camera is orthogonal. + virtual bool isOrthogonal() const { - public: + return IsOrthogonal; + } - //! Constructor - ICameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f,1.0f,1.0f)) - : ISceneNode(parent, mgr, id, position, rotation, scale), IsOrthogonal(false) {} + //! Binds the camera scene node's rotation to its target position and vice versa, or unbinds them. + /** When bound, calling setRotation() will update the camera's + target position to be along its +Z axis, and likewise calling + setTarget() will update its rotation so that its +Z axis will + point at the target point. FPS camera use this binding by + default; other cameras do not. + \param bound True to bind the camera's scene node rotation + and targeting, false to unbind them. + @see getTargetAndRotationBinding() */ + virtual void bindTargetAndRotation(bool bound) = 0; - //! Sets the projection matrix of the camera. - /** The core::matrix4 class has some methods to build a - projection matrix. e.g: - core::matrix4::buildProjectionMatrixPerspectiveFovLH. - Note that the matrix will only stay as set by this method until - one of the following Methods are called: setNearValue, - setFarValue, setAspectRatio, setFOV. - NOTE: The frustum is not updated before render() is called - unless you explicitly call updateMatrices() - \param projection The new projection matrix of the camera. - \param isOrthogonal Set this to true if the matrix is an - orthogonal one (e.g. from matrix4::buildProjectionMatrixOrtho). - */ - virtual void setProjectionMatrix(const core::matrix4& projection, bool isOrthogonal=false) =0; + //! Updates the matrices without uploading them to the driver + virtual void updateMatrices() = 0; - //! Gets the current projection matrix of the camera. - /** \return The current projection matrix of the camera. */ - virtual const core::matrix4& getProjectionMatrix() const =0; + //! Queries if the camera scene node's rotation and its target position are bound together. + /** @see bindTargetAndRotation() */ + virtual bool getTargetAndRotationBinding(void) const = 0; - //! Gets the current view matrix of the camera. - /** \return The current view matrix of the camera. */ - virtual const core::matrix4& getViewMatrix() const =0; +protected: + void cloneMembers(const ICameraSceneNode *toCopyFrom) + { + IsOrthogonal = toCopyFrom->IsOrthogonal; + } - //! Sets a custom view matrix affector. - /** The matrix passed here, will be multiplied with the view - matrix when it gets updated. This allows for custom camera - setups like, for example, a reflection camera. - \param affector The affector matrix. */ - virtual void setViewMatrixAffector(const core::matrix4& affector) =0; - - //! Get the custom view matrix affector. - /** \return The affector matrix. */ - virtual const core::matrix4& getViewMatrixAffector() const =0; - - //! It is possible to send mouse and key events to the camera. - /** Most cameras may ignore this input, but camera scene nodes - which are created for example with - ISceneManager::addCameraSceneNodeMaya or - ISceneManager::addCameraSceneNodeFPS, may want to get - this input for changing their position, look at target or - whatever. */ - bool OnEvent(const SEvent& event) override =0; - - //! Sets the look at target of the camera - /** If the camera's target and rotation are bound ( @see - bindTargetAndRotation() ) then calling this will also change - the camera's scene node rotation to match the target. - Note that setTarget uses the current absolute position - internally, so if you changed setPosition since last rendering you must - call updateAbsolutePosition before using this function. - \param pos Look at target of the camera, in world co-ordinates. */ - virtual void setTarget(const core::vector3df& pos) =0; - - //! Sets the rotation of the node. - /** This only modifies the relative rotation of the node. - If the camera's target and rotation are bound ( @see - bindTargetAndRotation() ) then calling this will also change - the camera's target to match the rotation. - \param rotation New rotation of the node in degrees. */ - void setRotation(const core::vector3df& rotation) override =0; - - //! Gets the current look at target of the camera - /** \return The current look at target of the camera, in world co-ordinates */ - virtual const core::vector3df& getTarget() const =0; - - //! Sets the up vector of the camera. - /** \param pos: New upvector of the camera. */ - virtual void setUpVector(const core::vector3df& pos) =0; - - //! Gets the up vector of the camera. - /** \return The up vector of the camera, in world space. */ - virtual const core::vector3df& getUpVector() const =0; - - //! Gets the value of the near plane of the camera. - /** \return The value of the near plane of the camera. */ - virtual f32 getNearValue() const =0; - - //! Gets the value of the far plane of the camera. - /** \return The value of the far plane of the camera. */ - virtual f32 getFarValue() const =0; - - //! Gets the aspect ratio of the camera. - /** \return The aspect ratio of the camera. */ - virtual f32 getAspectRatio() const =0; - - //! Gets the field of view of the camera. - /** \return The field of view of the camera in radians. */ - virtual f32 getFOV() const =0; - - //! Sets the value of the near clipping plane. (default: 1.0f) - /** \param zn: New z near value. */ - virtual void setNearValue(f32 zn) =0; - - //! Sets the value of the far clipping plane (default: 2000.0f) - /** \param zf: New z far value. */ - virtual void setFarValue(f32 zf) =0; - - //! Sets the aspect ratio (default: 4.0f / 3.0f) - /** \param aspect: New aspect ratio. */ - virtual void setAspectRatio(f32 aspect) =0; - - //! Sets the field of view (Default: PI / 2.5f) - /** \param fovy: New field of view in radians. */ - virtual void setFOV(f32 fovy) =0; - - //! Get the view frustum. - /** \return The current view frustum. */ - virtual const SViewFrustum* getViewFrustum() const =0; - - //! Disables or enables the camera to get key or mouse inputs. - /** If this is set to true, the camera will respond to key - inputs otherwise not. */ - virtual void setInputReceiverEnabled(bool enabled) =0; - - //! Checks if the input receiver of the camera is currently enabled. - virtual bool isInputReceiverEnabled() const =0; - - //! Checks if a camera is orthogonal. - virtual bool isOrthogonal() const - { - return IsOrthogonal; - } - - //! Binds the camera scene node's rotation to its target position and vice versa, or unbinds them. - /** When bound, calling setRotation() will update the camera's - target position to be along its +Z axis, and likewise calling - setTarget() will update its rotation so that its +Z axis will - point at the target point. FPS camera use this binding by - default; other cameras do not. - \param bound True to bind the camera's scene node rotation - and targeting, false to unbind them. - @see getTargetAndRotationBinding() */ - virtual void bindTargetAndRotation(bool bound) =0; - - //! Updates the matrices without uploading them to the driver - virtual void updateMatrices() = 0; - - //! Queries if the camera scene node's rotation and its target position are bound together. - /** @see bindTargetAndRotation() */ - virtual bool getTargetAndRotationBinding(void) const =0; - - protected: - - void cloneMembers(const ICameraSceneNode* toCopyFrom) - { - IsOrthogonal = toCopyFrom->IsOrthogonal; - } - - bool IsOrthogonal; - }; + bool IsOrthogonal; +}; } // end namespace scene } // end namespace irr diff --git a/include/IContextManager.h b/include/IContextManager.h index 1b8e5bb5..85177dc4 100644 --- a/include/IContextManager.h +++ b/include/IContextManager.h @@ -12,50 +12,48 @@ namespace irr { namespace video { - // For system specific window contexts (used for OpenGL) - class IContextManager : public virtual IReferenceCounted - { - public: - //! Initialize manager with device creation parameters and device window (passed as exposed video data) - virtual bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) =0; +// For system specific window contexts (used for OpenGL) +class IContextManager : public virtual IReferenceCounted +{ +public: + //! Initialize manager with device creation parameters and device window (passed as exposed video data) + virtual bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) = 0; - //! Terminate manager, any cleanup that is left over. Manager needs a new initialize to be usable again - virtual void terminate() =0; + //! Terminate manager, any cleanup that is left over. Manager needs a new initialize to be usable again + virtual void terminate() = 0; - //! Create surface based on current window set - virtual bool generateSurface() =0; + //! Create surface based on current window set + virtual bool generateSurface() = 0; - //! Destroy current surface - virtual void destroySurface() =0; + //! Destroy current surface + virtual void destroySurface() = 0; - //! Create context based on current surface - virtual bool generateContext() =0; + //! Create context based on current surface + virtual bool generateContext() = 0; - //! Destroy current context - virtual void destroyContext() =0; + //! Destroy current context + virtual void destroyContext() = 0; - //! Get current context - virtual const SExposedVideoData& getContext() const =0; + //! Get current context + virtual const SExposedVideoData &getContext() const = 0; - //! Change render context, disable old and activate new defined by videoData - //\param restorePrimaryOnZero When true: restore original driver context when videoData is set to 0 values. - // When false: resets the context when videoData is set to 0 values. - /** This is mostly used internally by IVideoDriver::beginScene(). - But if you want to switch threads which access your OpenGL driver you will have to - call this function as follows: - Old thread gives up context with: activateContext(irr::video::SExposedVideoData()); - New thread takes over context with: activateContext(videoDriver->getExposedVideoData()); - Note that only 1 thread at a time may access an OpenGL context. */ - virtual bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero=false) =0; + //! Change render context, disable old and activate new defined by videoData + //\param restorePrimaryOnZero When true: restore original driver context when videoData is set to 0 values. + // When false: resets the context when videoData is set to 0 values. + /** This is mostly used internally by IVideoDriver::beginScene(). + But if you want to switch threads which access your OpenGL driver you will have to + call this function as follows: + Old thread gives up context with: activateContext(irr::video::SExposedVideoData()); + New thread takes over context with: activateContext(videoDriver->getExposedVideoData()); + Note that only 1 thread at a time may access an OpenGL context. */ + virtual bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero = false) = 0; - //! Get the address of any OpenGL procedure (including core procedures). - virtual void* getProcAddress(const std::string &procName) =0; + //! Get the address of any OpenGL procedure (including core procedures). + virtual void *getProcAddress(const std::string &procName) = 0; - //! Swap buffers. - virtual bool swapBuffers() =0; - }; + //! Swap buffers. + virtual bool swapBuffers() = 0; +}; } // end namespace video } // end namespace irr - - diff --git a/include/ICursorControl.h b/include/ICursorControl.h index 2b7a4dca..8f75e523 100644 --- a/include/ICursorControl.h +++ b/include/ICursorControl.h @@ -13,186 +13,183 @@ namespace irr namespace gui { - class IGUISpriteBank; +class IGUISpriteBank; - //! Default icons for cursors - enum ECURSOR_ICON - { - // Following cursors might be system specific, or might use an Irrlicht icon-set. No guarantees so far. - ECI_NORMAL, // arrow - ECI_CROSS, // Crosshair - ECI_HAND, // Hand - ECI_HELP, // Arrow and question mark - ECI_IBEAM, // typical text-selection cursor - ECI_NO, // should not click icon - ECI_WAIT, // hourglass - ECI_SIZEALL, // arrow in all directions - ECI_SIZENESW, // resizes in direction north-east or south-west - ECI_SIZENWSE, // resizes in direction north-west or south-east - ECI_SIZENS, // resizes in direction north or south - ECI_SIZEWE, // resizes in direction west or east - ECI_UP, // up-arrow +//! Default icons for cursors +enum ECURSOR_ICON +{ + // Following cursors might be system specific, or might use an Irrlicht icon-set. No guarantees so far. + ECI_NORMAL, // arrow + ECI_CROSS, // Crosshair + ECI_HAND, // Hand + ECI_HELP, // Arrow and question mark + ECI_IBEAM, // typical text-selection cursor + ECI_NO, // should not click icon + ECI_WAIT, // hourglass + ECI_SIZEALL, // arrow in all directions + ECI_SIZENESW, // resizes in direction north-east or south-west + ECI_SIZENWSE, // resizes in direction north-west or south-east + ECI_SIZENS, // resizes in direction north or south + ECI_SIZEWE, // resizes in direction west or east + ECI_UP, // up-arrow - // Implementer note: Should we add system specific cursors, which use guaranteed the system icons, - // then I would recommend using a naming scheme like ECI_W32_CROSS, ECI_X11_CROSSHAIR and adding those - // additionally. + // Implementer note: Should we add system specific cursors, which use guaranteed the system icons, + // then I would recommend using a naming scheme like ECI_W32_CROSS, ECI_X11_CROSSHAIR and adding those + // additionally. - ECI_COUNT // maximal of defined cursors. Note that higher values can be created at runtime - }; + ECI_COUNT // maximal of defined cursors. Note that higher values can be created at runtime +}; - //! Names for ECURSOR_ICON - const c8* const GUICursorIconNames[ECI_COUNT+1] = - { - "normal", - "cross", - "hand", - "help", - "ibeam", - "no", - "wait", - "sizeall", - "sizenesw", - "sizenwse", - "sizens", - "sizewe", - "sizeup", - 0 - }; - - //! structure used to set sprites as cursors. - struct SCursorSprite - { - SCursorSprite() - : SpriteBank(0), SpriteId(-1) +//! Names for ECURSOR_ICON +const c8 *const GUICursorIconNames[ECI_COUNT + 1] = { - } + "normal", + "cross", + "hand", + "help", + "ibeam", + "no", + "wait", + "sizeall", + "sizenesw", + "sizenwse", + "sizens", + "sizewe", + "sizeup", + 0}; - SCursorSprite( gui::IGUISpriteBank * spriteBank, s32 spriteId, const core::position2d &hotspot=(core::position2d(0,0)) ) - : SpriteBank(spriteBank), SpriteId(spriteId), HotSpot(hotspot) - { - } - - IGUISpriteBank * SpriteBank; - s32 SpriteId; - core::position2d HotSpot; - }; - - //! platform specific behavior flags for the cursor - enum ECURSOR_PLATFORM_BEHAVIOR +//! structure used to set sprites as cursors. +struct SCursorSprite +{ + SCursorSprite() : + SpriteBank(0), SpriteId(-1) { - //! default - no platform specific behavior - ECPB_NONE = 0, + } - //! On X11 try caching cursor updates as XQueryPointer calls can be expensive. - /** Update cursor positions only when the irrlicht timer has been updated or the timer is stopped. - This means you usually get one cursor update per device->run() which will be fine in most cases. - See this forum-thread for a more detailed explanation: - http://irrlicht.sourceforge.net/forum/viewtopic.php?f=7&t=45525 - */ - ECPB_X11_CACHE_UPDATES = 1 - }; - - //! Interface to manipulate the mouse cursor. - class ICursorControl : public virtual IReferenceCounted + SCursorSprite(gui::IGUISpriteBank *spriteBank, s32 spriteId, const core::position2d &hotspot = (core::position2d(0, 0))) : + SpriteBank(spriteBank), SpriteId(spriteId), HotSpot(hotspot) { - public: + } - //! Changes the visible state of the mouse cursor. - /** \param visible: The new visible state. If true, the cursor will be visible, - if false, it will be invisible. */ - virtual void setVisible(bool visible) = 0; + IGUISpriteBank *SpriteBank; + s32 SpriteId; + core::position2d HotSpot; +}; - //! Returns if the cursor is currently visible. - /** \return True if the cursor flag is set to visible, false if not. */ - virtual bool isVisible() const = 0; +//! platform specific behavior flags for the cursor +enum ECURSOR_PLATFORM_BEHAVIOR +{ + //! default - no platform specific behavior + ECPB_NONE = 0, - //! Sets the new position of the cursor. - /** The position must be - between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is - the top left corner and (1.0f, 1.0f) is the bottom right corner of the - render window. - \param pos New position of the cursor. */ - virtual void setPosition(const core::position2d &pos) = 0; + //! On X11 try caching cursor updates as XQueryPointer calls can be expensive. + /** Update cursor positions only when the irrlicht timer has been updated or the timer is stopped. + This means you usually get one cursor update per device->run() which will be fine in most cases. + See this forum-thread for a more detailed explanation: + http://irrlicht.sourceforge.net/forum/viewtopic.php?f=7&t=45525 + */ + ECPB_X11_CACHE_UPDATES = 1 +}; - //! Sets the new position of the cursor. - /** The position must be - between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is - the top left corner and (1.0f, 1.0f) is the bottom right corner of the - render window. - \param x New x-coord of the cursor. - \param y New x-coord of the cursor. */ - virtual void setPosition(f32 x, f32 y) = 0; +//! Interface to manipulate the mouse cursor. +class ICursorControl : public virtual IReferenceCounted +{ +public: + //! Changes the visible state of the mouse cursor. + /** \param visible: The new visible state. If true, the cursor will be visible, + if false, it will be invisible. */ + virtual void setVisible(bool visible) = 0; - //! Sets the new position of the cursor. - /** \param pos: New position of the cursor. The coordinates are pixel units. */ - virtual void setPosition(const core::position2d &pos) = 0; + //! Returns if the cursor is currently visible. + /** \return True if the cursor flag is set to visible, false if not. */ + virtual bool isVisible() const = 0; - //! Sets the new position of the cursor. - /** \param x New x-coord of the cursor. The coordinates are pixel units. - \param y New y-coord of the cursor. The coordinates are pixel units. */ - virtual void setPosition(s32 x, s32 y) = 0; + //! Sets the new position of the cursor. + /** The position must be + between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is + the top left corner and (1.0f, 1.0f) is the bottom right corner of the + render window. + \param pos New position of the cursor. */ + virtual void setPosition(const core::position2d &pos) = 0; - //! Returns the current position of the mouse cursor. - /** \param updateCursor When true ask system/OS for current cursor position. - When false return the last known (buffered) position ( this is useful to - check what has become of a setPosition call with float numbers). - \return Returns the current position of the cursor. The returned position - is the position of the mouse cursor in pixel units. */ - virtual const core::position2d& getPosition(bool updateCursor=true) = 0; + //! Sets the new position of the cursor. + /** The position must be + between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is + the top left corner and (1.0f, 1.0f) is the bottom right corner of the + render window. + \param x New x-coord of the cursor. + \param y New x-coord of the cursor. */ + virtual void setPosition(f32 x, f32 y) = 0; - //! Returns the current position of the mouse cursor. - /** \param updateCursor When true ask system/OS for current cursor position. - When false return the last known (buffered) position (this is - useful to check what has become of a setPosition call with float numbers - and is often different from the values you passed in setPosition). - \return Returns the current position of the cursor. The returned position - is a value between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is - the top left corner and (1.0f, 1.0f) is the bottom right corner of the - render window. */ - virtual core::position2d getRelativePosition(bool updateCursor=true) = 0; + //! Sets the new position of the cursor. + /** \param pos: New position of the cursor. The coordinates are pixel units. */ + virtual void setPosition(const core::position2d &pos) = 0; - //! Sets an absolute reference rect for setting and retrieving the cursor position. - /** If this rect is set, the cursor position is not being calculated relative to - the rendering window but to this rect. You can set the rect pointer to 0 to disable - this feature again. This feature is useful when rendering into parts of foreign windows - for example in an editor. - \param rect: A pointer to an reference rectangle or 0 to disable the reference rectangle.*/ - virtual void setReferenceRect(core::rect* rect=0) = 0; + //! Sets the new position of the cursor. + /** \param x New x-coord of the cursor. The coordinates are pixel units. + \param y New y-coord of the cursor. The coordinates are pixel units. */ + virtual void setPosition(s32 x, s32 y) = 0; - //! Internally fixes the mouse position, and reports relative mouse movement compared to the old position - /** Specific to SDL */ - virtual void setRelativeMode(bool relative) {}; + //! Returns the current position of the mouse cursor. + /** \param updateCursor When true ask system/OS for current cursor position. + When false return the last known (buffered) position ( this is useful to + check what has become of a setPosition call with float numbers). + \return Returns the current position of the cursor. The returned position + is the position of the mouse cursor in pixel units. */ + virtual const core::position2d &getPosition(bool updateCursor = true) = 0; - //! Sets the active cursor icon - /** Setting cursor icons is so far only supported on Win32 and Linux */ - virtual void setActiveIcon(ECURSOR_ICON iconId) {} + //! Returns the current position of the mouse cursor. + /** \param updateCursor When true ask system/OS for current cursor position. + When false return the last known (buffered) position (this is + useful to check what has become of a setPosition call with float numbers + and is often different from the values you passed in setPosition). + \return Returns the current position of the cursor. The returned position + is a value between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is + the top left corner and (1.0f, 1.0f) is the bottom right corner of the + render window. */ + virtual core::position2d getRelativePosition(bool updateCursor = true) = 0; - //! Gets the currently active icon - virtual ECURSOR_ICON getActiveIcon() const { return gui::ECI_NORMAL; } + //! Sets an absolute reference rect for setting and retrieving the cursor position. + /** If this rect is set, the cursor position is not being calculated relative to + the rendering window but to this rect. You can set the rect pointer to 0 to disable + this feature again. This feature is useful when rendering into parts of foreign windows + for example in an editor. + \param rect: A pointer to an reference rectangle or 0 to disable the reference rectangle.*/ + virtual void setReferenceRect(core::rect *rect = 0) = 0; - //! Add a custom sprite as cursor icon. - /** \return Identification for the icon */ - virtual ECURSOR_ICON addIcon(const gui::SCursorSprite& icon) { return gui::ECI_NORMAL; } + //! Internally fixes the mouse position, and reports relative mouse movement compared to the old position + /** Specific to SDL */ + virtual void setRelativeMode(bool relative){}; - //! replace a cursor icon. - /** Changing cursor icons is so far only supported on Win32 and Linux - Note that this only changes the icons within your application, system cursors outside your - application will not be affected. - */ - virtual void changeIcon(ECURSOR_ICON iconId, const gui::SCursorSprite& sprite) {} + //! Sets the active cursor icon + /** Setting cursor icons is so far only supported on Win32 and Linux */ + virtual void setActiveIcon(ECURSOR_ICON iconId) {} - //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. - virtual core::dimension2di getSupportedIconSize() const { return core::dimension2di(0,0); } + //! Gets the currently active icon + virtual ECURSOR_ICON getActiveIcon() const { return gui::ECI_NORMAL; } - //! Set platform specific behavior flags. - virtual void setPlatformBehavior(ECURSOR_PLATFORM_BEHAVIOR behavior) {} + //! Add a custom sprite as cursor icon. + /** \return Identification for the icon */ + virtual ECURSOR_ICON addIcon(const gui::SCursorSprite &icon) { return gui::ECI_NORMAL; } - //! Return platform specific behavior. - /** \return Behavior set by setPlatformBehavior or ECPB_NONE for platforms not implementing specific behaviors. - */ - virtual ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const { return ECPB_NONE; } - }; + //! replace a cursor icon. + /** Changing cursor icons is so far only supported on Win32 and Linux + Note that this only changes the icons within your application, system cursors outside your + application will not be affected. + */ + virtual void changeIcon(ECURSOR_ICON iconId, const gui::SCursorSprite &sprite) {} + //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. + virtual core::dimension2di getSupportedIconSize() const { return core::dimension2di(0, 0); } + + //! Set platform specific behavior flags. + virtual void setPlatformBehavior(ECURSOR_PLATFORM_BEHAVIOR behavior) {} + + //! Return platform specific behavior. + /** \return Behavior set by setPlatformBehavior or ECPB_NONE for platforms not implementing specific behaviors. + */ + virtual ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const { return ECPB_NONE; } +}; } // end namespace gui } // end namespace irr diff --git a/include/IDummyTransformationSceneNode.h b/include/IDummyTransformationSceneNode.h index fb823eae..88bc37c7 100644 --- a/include/IDummyTransformationSceneNode.h +++ b/include/IDummyTransformationSceneNode.h @@ -22,15 +22,14 @@ joint scene nodes when playing skeletal animations. class IDummyTransformationSceneNode : public ISceneNode { public: - //! Constructor - IDummyTransformationSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id) - : ISceneNode(parent, mgr, id) {} + IDummyTransformationSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id) : + ISceneNode(parent, mgr, id) {} //! Returns a reference to the current relative transformation matrix. /** This is the matrix, this scene node uses instead of scale, translation and rotation. */ - virtual core::matrix4& getRelativeTransformationMatrix() = 0; + virtual core::matrix4 &getRelativeTransformationMatrix() = 0; }; } // end namespace scene diff --git a/include/IEventReceiver.h b/include/IEventReceiver.h index 8cea6e38..38961e4d 100644 --- a/include/IEventReceiver.h +++ b/include/IEventReceiver.h @@ -10,304 +10,303 @@ namespace irr { - //! Enumeration for all event types there are. - enum EEVENT_TYPE - { - //! An event of the graphical user interface. - /** GUI events are created by the GUI environment or the GUI elements in response - to mouse or keyboard events. When a GUI element receives an event it will either - process it and return true, or pass the event to its parent. If an event is not absorbed - before it reaches the root element then it will then be passed to the user receiver. */ - EET_GUI_EVENT = 0, - - //! A mouse input event. - /** Mouse events are created by the device and passed to IrrlichtDevice::postEventFromUser - in response to mouse input received from the operating system. - Mouse events are first passed to the user receiver, then to the GUI environment and its elements, - then finally the input receiving scene manager where it is passed to the active camera. - */ - EET_MOUSE_INPUT_EVENT, - - //! A key input event. - /** Like mouse events, keyboard events are created by the device and passed to - IrrlichtDevice::postEventFromUser. They take the same path as mouse events. */ - EET_KEY_INPUT_EVENT, - - //! A string input event. - /** This event is created when multiple characters are sent at a time (e.g. using an IME). */ - EET_STRING_INPUT_EVENT, - - //! A touch input event. - EET_TOUCH_INPUT_EVENT, - - //! A accelerometer event. - EET_ACCELEROMETER_EVENT, - - //! A gyroscope event. - EET_GYROSCOPE_EVENT, - - //! A device motion event. - EET_DEVICE_MOTION_EVENT, - - //! A joystick (joypad, gamepad) input event. - /** Joystick events are created by polling all connected joysticks once per - device run() and then passing the events to IrrlichtDevice::postEventFromUser. - They take the same path as mouse events. - Windows, SDL: Implemented. - Linux: Implemented, with POV hat issues. - MacOS / Other: Not yet implemented. - */ - EET_JOYSTICK_INPUT_EVENT, - - //! A log event - /** Log events are only passed to the user receiver if there is one. If they are absorbed by the - user receiver then no text will be sent to the console. */ - EET_LOG_TEXT_EVENT, - - //! A user event with user data. - /** This is not used by Irrlicht and can be used to send user - specific data though the system. The Irrlicht 'window handle' - can be obtained from IrrlichtDevice::getExposedVideoData() - The usage and behavior depends on the operating system: - Windows: send a WM_USER message to the Irrlicht Window; the - wParam and lParam will be used to populate the - UserData1 and UserData2 members of the SUserEvent. - Linux: send a ClientMessage via XSendEvent to the Irrlicht - Window; the data.l[0] and data.l[1] members will be - cast to s32 and used as UserData1 and UserData2. - MacOS: Not yet implemented - */ - EET_USER_EVENT, - - //! Pass on raw events from the OS - EET_SYSTEM_EVENT, - - //! Application state events like a resume, pause etc. - EET_APPLICATION_EVENT, - - //! This enum is never used, it only forces the compiler to - //! compile these enumeration values to 32 bit. - EGUIET_FORCE_32_BIT = 0x7fffffff - - }; - - //! Enumeration for all mouse input events - enum EMOUSE_INPUT_EVENT - { - //! Left mouse button was pressed down. - EMIE_LMOUSE_PRESSED_DOWN = 0, - - //! Right mouse button was pressed down. - EMIE_RMOUSE_PRESSED_DOWN, - - //! Middle mouse button was pressed down. - EMIE_MMOUSE_PRESSED_DOWN, - - //! Left mouse button was left up. - EMIE_LMOUSE_LEFT_UP, - - //! Right mouse button was left up. - EMIE_RMOUSE_LEFT_UP, - - //! Middle mouse button was left up. - EMIE_MMOUSE_LEFT_UP, - - //! The mouse cursor changed its position. - EMIE_MOUSE_MOVED, - - //! The mouse wheel was moved. Use Wheel value in event data to find out - //! in what direction and how fast. - EMIE_MOUSE_WHEEL, - - //! Left mouse button double click. - //! This event is generated after the second EMIE_LMOUSE_PRESSED_DOWN event. - EMIE_LMOUSE_DOUBLE_CLICK, - - //! Right mouse button double click. - //! This event is generated after the second EMIE_RMOUSE_PRESSED_DOWN event. - EMIE_RMOUSE_DOUBLE_CLICK, +//! Enumeration for all event types there are. +enum EEVENT_TYPE +{ + //! An event of the graphical user interface. + /** GUI events are created by the GUI environment or the GUI elements in response + to mouse or keyboard events. When a GUI element receives an event it will either + process it and return true, or pass the event to its parent. If an event is not absorbed + before it reaches the root element then it will then be passed to the user receiver. */ + EET_GUI_EVENT = 0, + + //! A mouse input event. + /** Mouse events are created by the device and passed to IrrlichtDevice::postEventFromUser + in response to mouse input received from the operating system. + Mouse events are first passed to the user receiver, then to the GUI environment and its elements, + then finally the input receiving scene manager where it is passed to the active camera. + */ + EET_MOUSE_INPUT_EVENT, + + //! A key input event. + /** Like mouse events, keyboard events are created by the device and passed to + IrrlichtDevice::postEventFromUser. They take the same path as mouse events. */ + EET_KEY_INPUT_EVENT, + + //! A string input event. + /** This event is created when multiple characters are sent at a time (e.g. using an IME). */ + EET_STRING_INPUT_EVENT, + + //! A touch input event. + EET_TOUCH_INPUT_EVENT, + + //! A accelerometer event. + EET_ACCELEROMETER_EVENT, + + //! A gyroscope event. + EET_GYROSCOPE_EVENT, + + //! A device motion event. + EET_DEVICE_MOTION_EVENT, + + //! A joystick (joypad, gamepad) input event. + /** Joystick events are created by polling all connected joysticks once per + device run() and then passing the events to IrrlichtDevice::postEventFromUser. + They take the same path as mouse events. + Windows, SDL: Implemented. + Linux: Implemented, with POV hat issues. + MacOS / Other: Not yet implemented. + */ + EET_JOYSTICK_INPUT_EVENT, + + //! A log event + /** Log events are only passed to the user receiver if there is one. If they are absorbed by the + user receiver then no text will be sent to the console. */ + EET_LOG_TEXT_EVENT, + + //! A user event with user data. + /** This is not used by Irrlicht and can be used to send user + specific data though the system. The Irrlicht 'window handle' + can be obtained from IrrlichtDevice::getExposedVideoData() + The usage and behavior depends on the operating system: + Windows: send a WM_USER message to the Irrlicht Window; the + wParam and lParam will be used to populate the + UserData1 and UserData2 members of the SUserEvent. + Linux: send a ClientMessage via XSendEvent to the Irrlicht + Window; the data.l[0] and data.l[1] members will be + cast to s32 and used as UserData1 and UserData2. + MacOS: Not yet implemented + */ + EET_USER_EVENT, + + //! Pass on raw events from the OS + EET_SYSTEM_EVENT, + + //! Application state events like a resume, pause etc. + EET_APPLICATION_EVENT, + + //! This enum is never used, it only forces the compiler to + //! compile these enumeration values to 32 bit. + EGUIET_FORCE_32_BIT = 0x7fffffff + +}; + +//! Enumeration for all mouse input events +enum EMOUSE_INPUT_EVENT +{ + //! Left mouse button was pressed down. + EMIE_LMOUSE_PRESSED_DOWN = 0, + + //! Right mouse button was pressed down. + EMIE_RMOUSE_PRESSED_DOWN, + + //! Middle mouse button was pressed down. + EMIE_MMOUSE_PRESSED_DOWN, + + //! Left mouse button was left up. + EMIE_LMOUSE_LEFT_UP, + + //! Right mouse button was left up. + EMIE_RMOUSE_LEFT_UP, + + //! Middle mouse button was left up. + EMIE_MMOUSE_LEFT_UP, + + //! The mouse cursor changed its position. + EMIE_MOUSE_MOVED, + + //! The mouse wheel was moved. Use Wheel value in event data to find out + //! in what direction and how fast. + EMIE_MOUSE_WHEEL, + + //! Left mouse button double click. + //! This event is generated after the second EMIE_LMOUSE_PRESSED_DOWN event. + EMIE_LMOUSE_DOUBLE_CLICK, + + //! Right mouse button double click. + //! This event is generated after the second EMIE_RMOUSE_PRESSED_DOWN event. + EMIE_RMOUSE_DOUBLE_CLICK, - //! Middle mouse button double click. - //! This event is generated after the second EMIE_MMOUSE_PRESSED_DOWN event. - EMIE_MMOUSE_DOUBLE_CLICK, + //! Middle mouse button double click. + //! This event is generated after the second EMIE_MMOUSE_PRESSED_DOWN event. + EMIE_MMOUSE_DOUBLE_CLICK, - //! Left mouse button triple click. - //! This event is generated after the third EMIE_LMOUSE_PRESSED_DOWN event. - EMIE_LMOUSE_TRIPLE_CLICK, - - //! Right mouse button triple click. - //! This event is generated after the third EMIE_RMOUSE_PRESSED_DOWN event. - EMIE_RMOUSE_TRIPLE_CLICK, - - //! Middle mouse button triple click. - //! This event is generated after the third EMIE_MMOUSE_PRESSED_DOWN event. - EMIE_MMOUSE_TRIPLE_CLICK, - - //! Mouse enters canvas used for rendering. - //! Only generated on emscripten - EMIE_MOUSE_ENTER_CANVAS, - - //! Mouse leaves canvas used for rendering. - //! Only generated on emscripten - EMIE_MOUSE_LEAVE_CANVAS, - - //! No real event. Just for convenience to get number of events - EMIE_COUNT - }; - - //! Masks for mouse button states - enum E_MOUSE_BUTTON_STATE_MASK - { - EMBSM_LEFT = 0x01, - EMBSM_RIGHT = 0x02, - EMBSM_MIDDLE = 0x04, + //! Left mouse button triple click. + //! This event is generated after the third EMIE_LMOUSE_PRESSED_DOWN event. + EMIE_LMOUSE_TRIPLE_CLICK, + + //! Right mouse button triple click. + //! This event is generated after the third EMIE_RMOUSE_PRESSED_DOWN event. + EMIE_RMOUSE_TRIPLE_CLICK, + + //! Middle mouse button triple click. + //! This event is generated after the third EMIE_MMOUSE_PRESSED_DOWN event. + EMIE_MMOUSE_TRIPLE_CLICK, + + //! Mouse enters canvas used for rendering. + //! Only generated on emscripten + EMIE_MOUSE_ENTER_CANVAS, + + //! Mouse leaves canvas used for rendering. + //! Only generated on emscripten + EMIE_MOUSE_LEAVE_CANVAS, + + //! No real event. Just for convenience to get number of events + EMIE_COUNT +}; + +//! Masks for mouse button states +enum E_MOUSE_BUTTON_STATE_MASK +{ + EMBSM_LEFT = 0x01, + EMBSM_RIGHT = 0x02, + EMBSM_MIDDLE = 0x04, - //! currently only on windows - EMBSM_EXTRA1 = 0x08, + //! currently only on windows + EMBSM_EXTRA1 = 0x08, - //! currently only on windows - EMBSM_EXTRA2 = 0x10, + //! currently only on windows + EMBSM_EXTRA2 = 0x10, - EMBSM_FORCE_32_BIT = 0x7fffffff - }; + EMBSM_FORCE_32_BIT = 0x7fffffff +}; - //! Enumeration for all touch input events - enum ETOUCH_INPUT_EVENT - { - //! Touch was pressed down. - ETIE_PRESSED_DOWN = 0, +//! Enumeration for all touch input events +enum ETOUCH_INPUT_EVENT +{ + //! Touch was pressed down. + ETIE_PRESSED_DOWN = 0, - //! Touch was left up. - ETIE_LEFT_UP, + //! Touch was left up. + ETIE_LEFT_UP, - //! The touch changed its position. - ETIE_MOVED, + //! The touch changed its position. + ETIE_MOVED, - //! No real event. Just for convenience to get number of events - ETIE_COUNT - }; + //! No real event. Just for convenience to get number of events + ETIE_COUNT +}; - enum ESYSTEM_EVENT_TYPE - { - //! From Android command handler for native activity messages - ESET_ANDROID_CMD = 0, +enum ESYSTEM_EVENT_TYPE +{ + //! From Android command handler for native activity messages + ESET_ANDROID_CMD = 0, - // TODO: for example ESET_WINDOWS_MESSAGE for win32 message loop events + // TODO: for example ESET_WINDOWS_MESSAGE for win32 message loop events - //! No real event, but to get number of event types - ESET_COUNT - }; + //! No real event, but to get number of event types + ESET_COUNT +}; - //! Enumeration for a commonly used application state events (it's useful mainly for mobile devices) - enum EAPPLICATION_EVENT_TYPE - { - //! The application will be resumed. - EAET_WILL_RESUME = 0, +//! Enumeration for a commonly used application state events (it's useful mainly for mobile devices) +enum EAPPLICATION_EVENT_TYPE +{ + //! The application will be resumed. + EAET_WILL_RESUME = 0, - //! The application has been resumed. - EAET_DID_RESUME, + //! The application has been resumed. + EAET_DID_RESUME, - //! The application will be paused. - EAET_WILL_PAUSE, + //! The application will be paused. + EAET_WILL_PAUSE, - //! The application has been paused. - EAET_DID_PAUSE, + //! The application has been paused. + EAET_DID_PAUSE, - //! The application will be terminated. - EAET_WILL_TERMINATE, + //! The application will be terminated. + EAET_WILL_TERMINATE, - //! The application received a memory warning. - EAET_MEMORY_WARNING, + //! The application received a memory warning. + EAET_MEMORY_WARNING, - //! No real event, but to get number of event types. - EAET_COUNT - }; + //! No real event, but to get number of event types. + EAET_COUNT +}; - namespace gui - { +namespace gui +{ - class IGUIElement; +class IGUIElement; - //! Enumeration for all events which are sendable by the gui system - enum EGUI_EVENT_TYPE - { - //! A gui element has lost its focus. - /** GUIEvent.Caller is losing the focus to GUIEvent.Element. - If the event is absorbed then the focus will not be changed. */ - EGET_ELEMENT_FOCUS_LOST = 0, +//! Enumeration for all events which are sendable by the gui system +enum EGUI_EVENT_TYPE +{ + //! A gui element has lost its focus. + /** GUIEvent.Caller is losing the focus to GUIEvent.Element. + If the event is absorbed then the focus will not be changed. */ + EGET_ELEMENT_FOCUS_LOST = 0, - //! A gui element has got the focus. - /** If the event is absorbed then the focus will not be changed. */ - EGET_ELEMENT_FOCUSED, + //! A gui element has got the focus. + /** If the event is absorbed then the focus will not be changed. */ + EGET_ELEMENT_FOCUSED, - //! The mouse cursor hovered over a gui element. - /** If an element has sub-elements you also get this message for the subelements */ - EGET_ELEMENT_HOVERED, + //! The mouse cursor hovered over a gui element. + /** If an element has sub-elements you also get this message for the subelements */ + EGET_ELEMENT_HOVERED, - //! The mouse cursor left the hovered element. - /** If an element has sub-elements you also get this message for the subelements */ - EGET_ELEMENT_LEFT, + //! The mouse cursor left the hovered element. + /** If an element has sub-elements you also get this message for the subelements */ + EGET_ELEMENT_LEFT, - //! An element would like to close. - /** Windows and context menus use this event when they would like to close, - this can be canceled by absorbing the event. */ - EGET_ELEMENT_CLOSED, + //! An element would like to close. + /** Windows and context menus use this event when they would like to close, + this can be canceled by absorbing the event. */ + EGET_ELEMENT_CLOSED, - //! A button was clicked. - EGET_BUTTON_CLICKED, + //! A button was clicked. + EGET_BUTTON_CLICKED, - //! A scrollbar has changed its position. - EGET_SCROLL_BAR_CHANGED, + //! A scrollbar has changed its position. + EGET_SCROLL_BAR_CHANGED, - //! A checkbox has changed its check state. - EGET_CHECKBOX_CHANGED, + //! A checkbox has changed its check state. + EGET_CHECKBOX_CHANGED, - //! A listbox would like to open. - /** You can prevent the listbox from opening by absorbing the event. */ - EGET_LISTBOX_OPENED, + //! A listbox would like to open. + /** You can prevent the listbox from opening by absorbing the event. */ + EGET_LISTBOX_OPENED, - //! A new item in a listbox was selected. - /** NOTE: You also get this event currently when the same item was clicked again after more than 500 ms. */ - EGET_LISTBOX_CHANGED, + //! A new item in a listbox was selected. + /** NOTE: You also get this event currently when the same item was clicked again after more than 500 ms. */ + EGET_LISTBOX_CHANGED, - //! An item in the listbox was selected, which was already selected. - /** NOTE: You get the event currently only if the item was clicked again within 500 ms or selected by "enter" or "space". */ - EGET_LISTBOX_SELECTED_AGAIN, + //! An item in the listbox was selected, which was already selected. + /** NOTE: You get the event currently only if the item was clicked again within 500 ms or selected by "enter" or "space". */ + EGET_LISTBOX_SELECTED_AGAIN, - //! A file has been selected in the file dialog - EGET_FILE_SELECTED, + //! A file has been selected in the file dialog + EGET_FILE_SELECTED, - //! A directory has been selected in the file dialog - EGET_DIRECTORY_SELECTED, + //! A directory has been selected in the file dialog + EGET_DIRECTORY_SELECTED, - //! A file open dialog has been closed without choosing a file - EGET_FILE_CHOOSE_DIALOG_CANCELLED, + //! A file open dialog has been closed without choosing a file + EGET_FILE_CHOOSE_DIALOG_CANCELLED, - //! In an editbox 'ENTER' was pressed - EGET_EDITBOX_ENTER, + //! In an editbox 'ENTER' was pressed + EGET_EDITBOX_ENTER, - //! The text in an editbox was changed. This does not include automatic changes in text-breaking. - EGET_EDITBOX_CHANGED, + //! The text in an editbox was changed. This does not include automatic changes in text-breaking. + EGET_EDITBOX_CHANGED, - //! The marked area in an editbox was changed. - EGET_EDITBOX_MARKING_CHANGED, + //! The marked area in an editbox was changed. + EGET_EDITBOX_MARKING_CHANGED, - //! The tab was changed in an tab control - EGET_TAB_CHANGED, + //! The tab was changed in an tab control + EGET_TAB_CHANGED, - //! The selection in a combo box has been changed - EGET_COMBO_BOX_CHANGED, + //! The selection in a combo box has been changed + EGET_COMBO_BOX_CHANGED, - //! A table has changed - EGET_TABLE_CHANGED, - EGET_TABLE_HEADER_CHANGED, - EGET_TABLE_SELECTED_AGAIN, - - //! No real event. Just for convenience to get number of events - EGET_COUNT - }; - } // end namespace gui + //! A table has changed + EGET_TABLE_CHANGED, + EGET_TABLE_HEADER_CHANGED, + EGET_TABLE_SELECTED_AGAIN, + //! No real event. Just for convenience to get number of events + EGET_COUNT +}; +} // end namespace gui //! SEvents hold information about an event. See irr::IEventReceiver for details on event handling. struct SEvent @@ -316,14 +315,13 @@ struct SEvent struct SGUIEvent { //! IGUIElement who called the event - gui::IGUIElement* Caller; + gui::IGUIElement *Caller; //! If the event has something to do with another element, it will be held here. - gui::IGUIElement* Element; + gui::IGUIElement *Element; //! Type of GUI Event gui::EGUI_EVENT_TYPE EventType; - }; //! Any kind of mouse event. @@ -340,10 +338,10 @@ struct SEvent f32 Wheel; //! True if shift was also pressed - bool Shift:1; + bool Shift : 1; //! True if ctrl was also pressed - bool Control:1; + bool Control : 1; //! A bitmap of button states. You can use isButtonPressed() to determine //! if a button is pressed or not. @@ -351,13 +349,13 @@ struct SEvent u32 ButtonStates; //! Is the left button pressed down? - bool isLeftPressed() const { return 0 != ( ButtonStates & EMBSM_LEFT ); } + bool isLeftPressed() const { return 0 != (ButtonStates & EMBSM_LEFT); } //! Is the right button pressed down? - bool isRightPressed() const { return 0 != ( ButtonStates & EMBSM_RIGHT ); } + bool isRightPressed() const { return 0 != (ButtonStates & EMBSM_RIGHT); } //! Is the middle button pressed down? - bool isMiddlePressed() const { return 0 != ( ButtonStates & EMBSM_MIDDLE ); } + bool isMiddlePressed() const { return 0 != (ButtonStates & EMBSM_MIDDLE); } //! Type of mouse event EMOUSE_INPUT_EVENT Event; @@ -377,13 +375,13 @@ struct SEvent u32 SystemKeyCode; //! If not true, then the key was left up - bool PressedDown:1; + bool PressedDown : 1; //! True if shift was also pressed - bool Shift:1; + bool Shift : 1; //! True if ctrl was also pressed - bool Control:1; + bool Control : 1; }; //! String input event. @@ -425,7 +423,7 @@ struct SEvent f64 Z; }; - //! Any kind of gyroscope event. + //! Any kind of gyroscope event. struct SGyroscopeEvent { // X rotation. @@ -465,13 +463,13 @@ struct SEvent { NUMBER_OF_BUTTONS = 32, - AXIS_X = 0, // e.g. analog stick 1 left to right + AXIS_X = 0, // e.g. analog stick 1 left to right AXIS_Y, // e.g. analog stick 1 top to bottom AXIS_Z, // e.g. throttle, or analog 2 stick 2 left to right AXIS_R, // e.g. rudder, or analog 2 stick 2 top to bottom AXIS_U, AXIS_V, - NUMBER_OF_AXES=18 // (please tell Irrlicht maintainers if you absolutely need more axes) + NUMBER_OF_AXES = 18 // (please tell Irrlicht maintainers if you absolutely need more axes) }; /** A bitmap of button states. You can use IsButtonPressed() to @@ -503,7 +501,7 @@ struct SEvent //! A helper function to check if a button is pressed. bool IsButtonPressed(u32 button) const { - if(button >= (u32)NUMBER_OF_BUTTONS) + if (button >= (u32)NUMBER_OF_BUTTONS) return false; return (ButtonStates & (1 << button)) ? true : false; @@ -514,7 +512,7 @@ struct SEvent struct SLogEvent { //! Pointer to text which has been logged - const c8* Text; + const c8 *Text; //! Log level in which the text has been logged ELOG_LEVEL Level; @@ -572,7 +570,6 @@ struct SEvent struct SSystemEvent SystemEvent; struct SApplicationEvent ApplicationEvent; }; - }; //! Interface of an object which can receive events. @@ -584,7 +581,6 @@ path it takes through the system. */ class IEventReceiver { public: - //! Destructor virtual ~IEventReceiver() {} @@ -594,10 +590,9 @@ public: * Therefore your return value for all unprocessed events should be 'false'. \return True if the event was processed. */ - virtual bool OnEvent(const SEvent& event) = 0; + virtual bool OnEvent(const SEvent &event) = 0; }; - //! Information on a joystick, returned from @ref irr::IrrlichtDevice::activateJoysticks() struct SJoystickInfo { @@ -634,5 +629,4 @@ struct SJoystickInfo } PovHat; }; // struct SJoystickInfo - } // end namespace irr diff --git a/include/IFileArchive.h b/include/IFileArchive.h index c62a7f5e..a2bb4534 100644 --- a/include/IFileArchive.h +++ b/include/IFileArchive.h @@ -16,54 +16,53 @@ namespace io //! FileSystemType: which filesystem should be used for e.g. browsing enum EFileSystemType { - FILESYSTEM_NATIVE = 0, // Native OS FileSystem - FILESYSTEM_VIRTUAL // Virtual FileSystem + FILESYSTEM_NATIVE = 0, // Native OS FileSystem + FILESYSTEM_VIRTUAL // Virtual FileSystem }; //! Contains the different types of archives enum E_FILE_ARCHIVE_TYPE { //! A PKZIP archive - EFAT_ZIP = MAKE_IRR_ID('Z','I','P', 0), + EFAT_ZIP = MAKE_IRR_ID('Z', 'I', 'P', 0), //! A gzip archive - EFAT_GZIP = MAKE_IRR_ID('g','z','i','p'), + EFAT_GZIP = MAKE_IRR_ID('g', 'z', 'i', 'p'), - //! An Android asset file archive - EFAT_ANDROID_ASSET = MAKE_IRR_ID('A','S','S','E'), + //! An Android asset file archive + EFAT_ANDROID_ASSET = MAKE_IRR_ID('A', 'S', 'S', 'E'), //! The type of this archive is unknown - EFAT_UNKNOWN = MAKE_IRR_ID('u','n','k','n') + EFAT_UNKNOWN = MAKE_IRR_ID('u', 'n', 'k', 'n') }; //! The FileArchive manages archives and provides access to files inside them. class IFileArchive : public virtual IReferenceCounted { public: - //! Opens a file based on its name /** Creates and returns a new IReadFile for a file in the archive. \param filename The file to open \return Returns A pointer to the created file on success, or 0 on failure. */ - virtual IReadFile* createAndOpenFile(const path& filename) =0; + virtual IReadFile *createAndOpenFile(const path &filename) = 0; //! Opens a file based on its position in the file list. /** Creates and returns \param index The zero based index of the file. \return Returns a pointer to the created file on success, or 0 on failure. */ - virtual IReadFile* createAndOpenFile(u32 index) =0; + virtual IReadFile *createAndOpenFile(u32 index) = 0; //! Returns the complete file tree /** \return Returns the complete directory tree for the archive, including all files and folders */ - virtual const IFileList* getFileList() const =0; + virtual const IFileList *getFileList() const = 0; //! get the archive type virtual E_FILE_ARCHIVE_TYPE getType() const { return EFAT_UNKNOWN; } //! return the name (id) of the file Archive - virtual const io::path& getArchiveName() const =0; + virtual const io::path &getArchiveName() const = 0; //! Add a directory in the archive and all it's files to the FileList /** Only needed for file-archives which have no information about their own @@ -95,35 +94,34 @@ public: /** Check based on the file extension (e.g. ".zip") \param filename Name of file to check. \return True if file seems to be loadable. */ - virtual bool isALoadableFileFormat(const path& filename) const =0; + virtual bool isALoadableFileFormat(const path &filename) const = 0; //! Check if the file might be loaded by this class /** This check may look into the file. \param file File handle to check. \return True if file seems to be loadable. */ - virtual bool isALoadableFileFormat(io::IReadFile* file) const =0; + virtual bool isALoadableFileFormat(io::IReadFile *file) const = 0; //! Check to see if the loader can create archives of this type. /** Check based on the archive type. \param fileType The archive type to check. \return True if the archive loader supports this type, false if not */ - virtual bool isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const =0; + virtual bool isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const = 0; //! Creates an archive from the filename /** \param filename File to use. \param ignoreCase Searching is performed without regarding the case \param ignorePaths Files are searched for without checking for the directories \return Pointer to newly created archive, or 0 upon error. */ - virtual IFileArchive* createArchive(const path& filename, bool ignoreCase, bool ignorePaths) const =0; + virtual IFileArchive *createArchive(const path &filename, bool ignoreCase, bool ignorePaths) const = 0; //! Creates an archive from the file /** \param file File handle to use. \param ignoreCase Searching is performed without regarding the case \param ignorePaths Files are searched for without checking for the directories \return Pointer to newly created archive, or 0 upon error. */ - virtual IFileArchive* createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const =0; + virtual IFileArchive *createArchive(io::IReadFile *file, bool ignoreCase, bool ignorePaths) const = 0; }; - } // end namespace io } // end namespace irr diff --git a/include/IFileList.h b/include/IFileList.h index cdef3e67..f33b1628 100644 --- a/include/IFileList.h +++ b/include/IFileList.h @@ -27,13 +27,13 @@ public: \param index is the zero based index of the file which name should be returned. The index must be less than the amount getFileCount() returns. \return File name of the file. Returns 0, if an error occurred. */ - virtual const io::path& getFileName(u32 index) const = 0; + virtual const io::path &getFileName(u32 index) const = 0; //! Gets the full name of a file in the list including the path, based on an index. /** \param index is the zero based index of the file which name should be returned. The index must be less than the amount getFileCount() returns. \return File name of the file. Returns 0 if an error occurred. */ - virtual const io::path& getFullFileName(u32 index) const = 0; + virtual const io::path &getFullFileName(u32 index) const = 0; //! Returns the size of a file in the file list, based on an index. /** \param index is the zero based index of the file which should be returned. @@ -68,10 +68,10 @@ public: \param isFolder True if you are searching for a directory path, false if you are searching for a file \return Returns the index of the file in the file list, or -1 if no matching name name was found. */ - virtual s32 findFile(const io::path& filename, bool isFolder=false) const = 0; + virtual s32 findFile(const io::path &filename, bool isFolder = false) const = 0; //! Returns the base path of the file list - virtual const io::path& getPath() const = 0; + virtual const io::path &getPath() const = 0; //! Add as a file or folder to the list /** \param fullPath The file name including path, from the root of the file list. @@ -79,7 +79,7 @@ public: \param offset The file offset inside an archive \param size The size of the file in bytes. \param id The ID of the file in the archive which owns it */ - virtual u32 addItem(const io::path& fullPath, u32 offset, u32 size, bool isDirectory, u32 id=0) = 0; + virtual u32 addItem(const io::path &fullPath, u32 offset, u32 size, bool isDirectory, u32 id = 0) = 0; //! Sorts the file list. You should call this after adding any items to the file list virtual void sort() = 0; diff --git a/include/IFileSystem.h b/include/IFileSystem.h index 635c7975..1fe9fe6f 100644 --- a/include/IFileSystem.h +++ b/include/IFileSystem.h @@ -11,7 +11,7 @@ namespace irr { namespace video { - class IVideoDriver; +class IVideoDriver; } // end namespace video namespace io { @@ -21,7 +21,6 @@ class IWriteFile; class IFileList; class IAttributes; - //! The FileSystem manages files and archives and provides access to them. /** It manages where files are, so that modules which use the the IO do not need to know where every file is located. A file could be in a .zip-Archive or @@ -29,13 +28,12 @@ as file on disk, using the IFileSystem makes no difference to this. */ class IFileSystem : public virtual IReferenceCounted { public: - //! Opens a file for read access. /** \param filename: Name of file to open. \return Pointer to the created file interface. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ - virtual IReadFile* createAndOpenFile(const path& filename) =0; + virtual IReadFile *createAndOpenFile(const path &filename) = 0; //! Creates an IReadFile interface for accessing memory like a file. /** This allows you to use a pointer to memory where an IReadFile is requested. @@ -48,7 +46,7 @@ public: The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ - virtual IReadFile* createMemoryReadFile(const void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0; + virtual IReadFile *createMemoryReadFile(const void *memory, s32 len, const path &fileName, bool deleteMemoryWhenDropped = false) = 0; //! Creates an IReadFile interface for accessing files inside files. /** This is useful e.g. for archives. @@ -60,8 +58,8 @@ public: The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ - virtual IReadFile* createLimitReadFile(const path& fileName, - IReadFile* alreadyOpenedFile, long pos, long areaSize) =0; + virtual IReadFile *createLimitReadFile(const path &fileName, + IReadFile *alreadyOpenedFile, long pos, long areaSize) = 0; //! Creates an IWriteFile interface for accessing memory like a file. /** This allows you to use a pointer to memory where an IWriteFile is requested. @@ -75,8 +73,7 @@ public: The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ - virtual IWriteFile* createMemoryWriteFile(void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0; - + virtual IWriteFile *createMemoryWriteFile(void *memory, s32 len, const path &fileName, bool deleteMemoryWhenDropped = false) = 0; //! Opens a file for write access. /** \param filename: Name of file to open. @@ -86,7 +83,7 @@ public: file could not created or opened for writing. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ - virtual IWriteFile* createAndWriteFile(const path& filename, bool append=false) =0; + virtual IWriteFile *createAndWriteFile(const path &filename, bool append = false) = 0; //! Adds an archive to the file system. /** After calling this, the Irrlicht Engine will also search and open @@ -110,11 +107,11 @@ public: \param password An optional password, which is used in case of encrypted archives. \param retArchive A pointer that will be set to the archive that is added. \return True if the archive was added successfully, false if not. */ - virtual bool addFileArchive(const path& filename, bool ignoreCase=true, - bool ignorePaths=true, - E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN, - const core::stringc& password="", - IFileArchive** retArchive=0) =0; + virtual bool addFileArchive(const path &filename, bool ignoreCase = true, + bool ignorePaths = true, + E_FILE_ARCHIVE_TYPE archiveType = EFAT_UNKNOWN, + const core::stringc &password = "", + IFileArchive **retArchive = 0) = 0; //! Adds an archive to the file system. /** After calling this, the Irrlicht Engine will also search and open @@ -142,19 +139,19 @@ public: \param password An optional password, which is used in case of encrypted archives. \param retArchive A pointer that will be set to the archive that is added. \return True if the archive was added successfully, false if not. */ - virtual bool addFileArchive(IReadFile* file, bool ignoreCase=true, - bool ignorePaths=true, - E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN, - const core::stringc& password="", - IFileArchive** retArchive=0) =0; + virtual bool addFileArchive(IReadFile *file, bool ignoreCase = true, + bool ignorePaths = true, + E_FILE_ARCHIVE_TYPE archiveType = EFAT_UNKNOWN, + const core::stringc &password = "", + IFileArchive **retArchive = 0) = 0; //! Adds an archive to the file system. /** \param archive: The archive to add to the file system. \return True if the archive was added successfully, false if not. */ - virtual bool addFileArchive(IFileArchive* archive) =0; + virtual bool addFileArchive(IFileArchive *archive) = 0; //! Get the number of archives currently attached to the file system - virtual u32 getFileArchiveCount() const =0; + virtual u32 getFileArchiveCount() const = 0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not @@ -162,7 +159,7 @@ public: example textures and meshes. \param index: The index of the archive to remove \return True on success, false on failure */ - virtual bool removeFileArchive(u32 index) =0; + virtual bool removeFileArchive(u32 index) = 0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not @@ -176,7 +173,7 @@ public: locating the archive to work with. \param filename The archive pointed to by the name will be removed \return True on success, false on failure */ - virtual bool removeFileArchive(const path& filename) =0; + virtual bool removeFileArchive(const path &filename) = 0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not @@ -184,21 +181,21 @@ public: example textures and meshes. \param archive The archive to remove. \return True on success, false on failure */ - virtual bool removeFileArchive(const IFileArchive* archive) =0; + virtual bool removeFileArchive(const IFileArchive *archive) = 0; //! Changes the search order of attached archives. /** \param sourceIndex: The index of the archive to change \param relative: The relative change in position, archives with a lower index are searched first */ - virtual bool moveFileArchive(u32 sourceIndex, s32 relative) =0; + virtual bool moveFileArchive(u32 sourceIndex, s32 relative) = 0; //! Get the archive at a given index. - virtual IFileArchive* getFileArchive(u32 index) =0; + virtual IFileArchive *getFileArchive(u32 index) = 0; //! Adds an external archive loader to the engine. /** Use this function to add support for new archive types to the engine, for example proprietary or encrypted file storage. */ - virtual void addArchiveLoader(IArchiveLoader* loader) =0; + virtual void addArchiveLoader(IArchiveLoader *loader) = 0; //! Gets the number of archive loaders currently added virtual u32 getArchiveLoaderCount() const = 0; @@ -207,63 +204,62 @@ public: /** \param index The index of the loader to retrieve. This parameter is an 0-based array index. \return A pointer to the specified loader, 0 if the index is incorrect. */ - virtual IArchiveLoader* getArchiveLoader(u32 index) const = 0; + virtual IArchiveLoader *getArchiveLoader(u32 index) const = 0; //! Get the current working directory. /** \return Current working directory as a string. */ - virtual const path& getWorkingDirectory() =0; + virtual const path &getWorkingDirectory() = 0; //! Changes the current working directory. /** \param newDirectory: A string specifying the new working directory. The string is operating system dependent. Under Windows it has the form ":\\\<..>". An example would be: "C:\Windows\" \return True if successful, otherwise false. */ - virtual bool changeWorkingDirectoryTo(const path& newDirectory) =0; + virtual bool changeWorkingDirectoryTo(const path &newDirectory) = 0; //! Converts a relative path to an absolute (unique) path, resolving symbolic links if required /** \param filename Possibly relative file or directory name to query. \result Absolute filename which points to the same file. */ - virtual path getAbsolutePath(const path& filename) const =0; + virtual path getAbsolutePath(const path &filename) const = 0; //! Get the directory a file is located in. /** \param filename: The file to get the directory from. \return String containing the directory of the file. */ - virtual path getFileDir(const path& filename) const =0; + virtual path getFileDir(const path &filename) const = 0; //! Get the base part of a filename, i.e. the name without the directory part. /** If no directory is prefixed, the full name is returned. \param filename: The file to get the basename from \param keepExtension True if filename with extension is returned otherwise everything after the final '.' is removed as well. */ - virtual path getFileBasename(const path& filename, bool keepExtension=true) const =0; + virtual path getFileBasename(const path &filename, bool keepExtension = true) const = 0; //! flatten a path and file name for example: "/you/me/../." becomes "/you" - virtual path& flattenFilename(path& directory, const path& root="/") const =0; + virtual path &flattenFilename(path &directory, const path &root = "/") const = 0; //! Get the relative filename, relative to the given directory - virtual path getRelativeFilename(const path& filename, const path& directory) const =0; + virtual path getRelativeFilename(const path &filename, const path &directory) const = 0; //! Creates a list of files and directories in the current working directory and returns it. /** \return a Pointer to the created IFileList is returned. After the list has been used it has to be deleted using its IFileList::drop() method. See IReferenceCounted::drop() for more information. */ - virtual IFileList* createFileList() =0; + virtual IFileList *createFileList() = 0; //! Creates an empty filelist /** \return a Pointer to the created IFileList is returned. After the list has been used it has to be deleted using its IFileList::drop() method. See IReferenceCounted::drop() for more information. */ - virtual IFileList* createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) =0; + virtual IFileList *createEmptyFileList(const io::path &path, bool ignoreCase, bool ignorePaths) = 0; //! Set the active type of file system. - virtual EFileSystemType setFileListSystem(EFileSystemType listType) =0; + virtual EFileSystemType setFileListSystem(EFileSystemType listType) = 0; //! Determines if a file exists and could be opened. /** \param filename is the string identifying the file which should be tested for existence. \return True if file exists, and false if it does not exist or an error occurred. */ - virtual bool existFile(const path& filename) const =0; + virtual bool existFile(const path &filename) const = 0; }; - } // end namespace io } // end namespace irr diff --git a/include/IGPUProgrammingServices.h b/include/IGPUProgrammingServices.h index 470e26af..de24a912 100644 --- a/include/IGPUProgrammingServices.h +++ b/include/IGPUProgrammingServices.h @@ -14,7 +14,7 @@ namespace irr namespace io { - class IReadFile; +class IReadFile; } // end namespace io namespace video @@ -27,7 +27,6 @@ class IShaderConstantSetCallBack; class IGPUProgrammingServices { public: - //! Destructor virtual ~IGPUProgrammingServices() {} @@ -73,41 +72,41 @@ public: target is not reachable. The error strings are then printed to the error log and can be caught with a custom event receiver. */ virtual s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) = 0; + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) = 0; //! convenience function for use without geometry shaders s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName="main", - E_VERTEX_SHADER_TYPE vsCompileTarget=EVST_VS_1_1, - const c8* pixelShaderProgram=0, - const c8* pixelShaderEntryPointName="main", - E_PIXEL_SHADER_TYPE psCompileTarget=EPST_PS_1_1, - IShaderConstantSetCallBack* callback=0, - E_MATERIAL_TYPE baseMaterial=video::EMT_SOLID, - s32 userData=0) + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName = "main", + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const c8 *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = "main", + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterial( - vertexShaderProgram, vertexShaderEntryPointName, - vsCompileTarget, pixelShaderProgram, - pixelShaderEntryPointName, psCompileTarget, - 0, "main", EGST_GS_4_0, - scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, - callback, baseMaterial, userData); + vertexShaderProgram, vertexShaderEntryPointName, + vsCompileTarget, pixelShaderProgram, + pixelShaderEntryPointName, psCompileTarget, + 0, "main", EGST_GS_4_0, + scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, + callback, baseMaterial, userData); } //! convenience function for use with many defaults, without geometry shader @@ -115,19 +114,19 @@ public: type 1.1. */ s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* pixelShaderProgram=0, - IShaderConstantSetCallBack* callback=0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData=0) + const c8 *vertexShaderProgram, + const c8 *pixelShaderProgram = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterial( - vertexShaderProgram, "main", - EVST_VS_1_1, pixelShaderProgram, - "main", EPST_PS_1_1, - 0, "main", EGST_GS_4_0, - scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, - callback, baseMaterial, userData); + vertexShaderProgram, "main", + EVST_VS_1_1, pixelShaderProgram, + "main", EPST_PS_1_1, + 0, "main", EGST_GS_4_0, + scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, + callback, baseMaterial, userData); } //! convenience function for use with many defaults, with geometry shader @@ -135,23 +134,23 @@ public: type 1.1 and geometry shader 4.0. */ s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* pixelShaderProgram = 0, - const c8* geometryShaderProgram = 0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0 ) + const c8 *vertexShaderProgram, + const c8 *pixelShaderProgram = 0, + const c8 *geometryShaderProgram = 0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterial( - vertexShaderProgram, "main", - EVST_VS_1_1, pixelShaderProgram, - "main", EPST_PS_1_1, - geometryShaderProgram, "main", EGST_GS_4_0, - inType, outType, verticesOut, - callback, baseMaterial, userData); + vertexShaderProgram, "main", + EVST_VS_1_1, pixelShaderProgram, + "main", EPST_PS_1_1, + geometryShaderProgram, "main", EGST_GS_4_0, + inType, outType, verticesOut, + callback, baseMaterial, userData); } //! Like addHighLevelShaderMaterial(), but loads from files. @@ -197,41 +196,41 @@ public: target is not reachable. The error strings are then printed to the error log and can be caught with a custom event receiver. */ virtual s32 addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFileName, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const io::path& pixelShaderProgramFileName, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const io::path& geometryShaderProgramFileName, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) = 0; + const io::path &vertexShaderProgramFileName, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const io::path &pixelShaderProgramFileName, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const io::path &geometryShaderProgramFileName, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) = 0; //! convenience function for use without geometry shaders s32 addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFileName, - const c8* vertexShaderEntryPointName = "main", - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - const io::path& pixelShaderProgramFileName = "", - const c8* pixelShaderEntryPointName = "main", - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) + const io::path &vertexShaderProgramFileName, + const c8 *vertexShaderEntryPointName = "main", + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const io::path &pixelShaderProgramFileName = "", + const c8 *pixelShaderEntryPointName = "main", + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterialFromFiles( - vertexShaderProgramFileName, vertexShaderEntryPointName, - vsCompileTarget, pixelShaderProgramFileName, - pixelShaderEntryPointName, psCompileTarget, - "", "main", EGST_GS_4_0, - scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, - callback, baseMaterial, userData); + vertexShaderProgramFileName, vertexShaderEntryPointName, + vsCompileTarget, pixelShaderProgramFileName, + pixelShaderEntryPointName, psCompileTarget, + "", "main", EGST_GS_4_0, + scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, + callback, baseMaterial, userData); } //! convenience function for use with many defaults, without geometry shader @@ -239,19 +238,19 @@ public: type 1.1. */ s32 addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFileName, - const io::path& pixelShaderProgramFileName = "", - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0 ) + const io::path &vertexShaderProgramFileName, + const io::path &pixelShaderProgramFileName = "", + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterialFromFiles( - vertexShaderProgramFileName, "main", - EVST_VS_1_1, pixelShaderProgramFileName, - "main", EPST_PS_1_1, - "", "main", EGST_GS_4_0, - scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, - callback, baseMaterial, userData); + vertexShaderProgramFileName, "main", + EVST_VS_1_1, pixelShaderProgramFileName, + "main", EPST_PS_1_1, + "", "main", EGST_GS_4_0, + scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, + callback, baseMaterial, userData); } //! convenience function for use with many defaults, with geometry shader @@ -259,23 +258,23 @@ public: type 1.1 and geometry shader 4.0. */ s32 addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFileName, - const io::path& pixelShaderProgramFileName = "", - const io::path& geometryShaderProgramFileName = "", - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0 ) + const io::path &vertexShaderProgramFileName, + const io::path &pixelShaderProgramFileName = "", + const io::path &geometryShaderProgramFileName = "", + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterialFromFiles( - vertexShaderProgramFileName, "main", - EVST_VS_1_1, pixelShaderProgramFileName, - "main", EPST_PS_1_1, - geometryShaderProgramFileName, "main", EGST_GS_4_0, - inType, outType, verticesOut, - callback, baseMaterial, userData); + vertexShaderProgramFileName, "main", + EVST_VS_1_1, pixelShaderProgramFileName, + "main", EPST_PS_1_1, + geometryShaderProgramFileName, "main", EGST_GS_4_0, + inType, outType, verticesOut, + callback, baseMaterial, userData); } //! Like addHighLevelShaderMaterial(), but loads from files. @@ -319,41 +318,41 @@ public: compile target is not reachable. The error strings are then printed to the error log and can be caught with a custom event receiver. */ virtual s32 addHighLevelShaderMaterialFromFiles( - io::IReadFile* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - io::IReadFile* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - io::IReadFile* geometryShaderProgram, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) = 0; + io::IReadFile *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + io::IReadFile *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + io::IReadFile *geometryShaderProgram, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) = 0; //! convenience function for use without geometry shaders s32 addHighLevelShaderMaterialFromFiles( - io::IReadFile* vertexShaderProgram, - const c8* vertexShaderEntryPointName = "main", - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - io::IReadFile* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = "main", - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) + io::IReadFile *vertexShaderProgram, + const c8 *vertexShaderEntryPointName = "main", + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + io::IReadFile *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = "main", + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) { return addHighLevelShaderMaterialFromFiles( - vertexShaderProgram, vertexShaderEntryPointName, - vsCompileTarget, pixelShaderProgram, - pixelShaderEntryPointName, psCompileTarget, - 0, "main", EGST_GS_4_0, - scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, - callback, baseMaterial, userData); + vertexShaderProgram, vertexShaderEntryPointName, + vsCompileTarget, pixelShaderProgram, + pixelShaderEntryPointName, psCompileTarget, + 0, "main", EGST_GS_4_0, + scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, + callback, baseMaterial, userData); } //! Delete a shader material and associated data. @@ -366,6 +365,5 @@ public: virtual void deleteShaderMaterial(s32 material) = 0; }; - } // end namespace video } // end namespace irr diff --git a/include/IGUIButton.h b/include/IGUIButton.h index a146e728..ee6ec2ee 100644 --- a/include/IGUIButton.h +++ b/include/IGUIButton.h @@ -11,254 +11,251 @@ namespace irr namespace video { - class ITexture; +class ITexture; } // end namespace video namespace gui { - class IGUIFont; - class IGUISpriteBank; +class IGUIFont; +class IGUISpriteBank; - //! Current state of buttons used for drawing sprites. - //! Note that up to 3 states can be active at the same time: - //! EGBS_BUTTON_UP or EGBS_BUTTON_DOWN - //! EGBS_BUTTON_MOUSE_OVER or EGBS_BUTTON_MOUSE_OFF - //! EGBS_BUTTON_FOCUSED or EGBS_BUTTON_NOT_FOCUSED - enum EGUI_BUTTON_STATE - { - //! The button is not pressed. - EGBS_BUTTON_UP=0, - //! The button is currently pressed down. - EGBS_BUTTON_DOWN, - //! The mouse cursor is over the button - EGBS_BUTTON_MOUSE_OVER, - //! The mouse cursor is not over the button - EGBS_BUTTON_MOUSE_OFF, - //! The button has the focus - EGBS_BUTTON_FOCUSED, - //! The button doesn't have the focus - EGBS_BUTTON_NOT_FOCUSED, - //! The button is disabled All other states are ignored in that case. - EGBS_BUTTON_DISABLED, - //! not used, counts the number of enumerated items - EGBS_COUNT - }; +//! Current state of buttons used for drawing sprites. +//! Note that up to 3 states can be active at the same time: +//! EGBS_BUTTON_UP or EGBS_BUTTON_DOWN +//! EGBS_BUTTON_MOUSE_OVER or EGBS_BUTTON_MOUSE_OFF +//! EGBS_BUTTON_FOCUSED or EGBS_BUTTON_NOT_FOCUSED +enum EGUI_BUTTON_STATE +{ + //! The button is not pressed. + EGBS_BUTTON_UP = 0, + //! The button is currently pressed down. + EGBS_BUTTON_DOWN, + //! The mouse cursor is over the button + EGBS_BUTTON_MOUSE_OVER, + //! The mouse cursor is not over the button + EGBS_BUTTON_MOUSE_OFF, + //! The button has the focus + EGBS_BUTTON_FOCUSED, + //! The button doesn't have the focus + EGBS_BUTTON_NOT_FOCUSED, + //! The button is disabled All other states are ignored in that case. + EGBS_BUTTON_DISABLED, + //! not used, counts the number of enumerated items + EGBS_COUNT +}; - //! Names for gui button state icons - const c8* const GUIButtonStateNames[EGBS_COUNT+1] = - { - "buttonUp", - "buttonDown", - "buttonMouseOver", - "buttonMouseOff", - "buttonFocused", - "buttonNotFocused", - "buttonDisabled", - 0 // count - }; +//! Names for gui button state icons +const c8 *const GUIButtonStateNames[EGBS_COUNT + 1] = + { + "buttonUp", + "buttonDown", + "buttonMouseOver", + "buttonMouseOff", + "buttonFocused", + "buttonNotFocused", + "buttonDisabled", + 0 // count +}; - //! State of buttons used for drawing texture images. - //! Note that only a single state is active at a time - //! Also when no image is defined for a state it will use images from another state - //! and if that state is not set from the replacement for that,etc. - //! So in many cases setting EGBIS_IMAGE_UP and EGBIS_IMAGE_DOWN is sufficient. - enum EGUI_BUTTON_IMAGE_STATE - { - //! When no other states have images they will all use this one. - EGBIS_IMAGE_UP, - //! When not set EGBIS_IMAGE_UP is used. - EGBIS_IMAGE_UP_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP_MOUSEOVER is used. - EGBIS_IMAGE_UP_FOCUSED, - //! When not set EGBIS_IMAGE_UP_FOCUSED is used. - EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP is used. - EGBIS_IMAGE_DOWN, - //! When not set EGBIS_IMAGE_DOWN is used. - EGBIS_IMAGE_DOWN_MOUSEOVER, - //! When not set EGBIS_IMAGE_DOWN_MOUSEOVER is used. - EGBIS_IMAGE_DOWN_FOCUSED, - //! When not set EGBIS_IMAGE_DOWN_FOCUSED is used. - EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP or EGBIS_IMAGE_DOWN are used (depending on button state). - EGBIS_IMAGE_DISABLED, - //! not used, counts the number of enumerated items - EGBIS_COUNT - }; +//! State of buttons used for drawing texture images. +//! Note that only a single state is active at a time +//! Also when no image is defined for a state it will use images from another state +//! and if that state is not set from the replacement for that,etc. +//! So in many cases setting EGBIS_IMAGE_UP and EGBIS_IMAGE_DOWN is sufficient. +enum EGUI_BUTTON_IMAGE_STATE +{ + //! When no other states have images they will all use this one. + EGBIS_IMAGE_UP, + //! When not set EGBIS_IMAGE_UP is used. + EGBIS_IMAGE_UP_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP_MOUSEOVER is used. + EGBIS_IMAGE_UP_FOCUSED, + //! When not set EGBIS_IMAGE_UP_FOCUSED is used. + EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP is used. + EGBIS_IMAGE_DOWN, + //! When not set EGBIS_IMAGE_DOWN is used. + EGBIS_IMAGE_DOWN_MOUSEOVER, + //! When not set EGBIS_IMAGE_DOWN_MOUSEOVER is used. + EGBIS_IMAGE_DOWN_FOCUSED, + //! When not set EGBIS_IMAGE_DOWN_FOCUSED is used. + EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP or EGBIS_IMAGE_DOWN are used (depending on button state). + EGBIS_IMAGE_DISABLED, + //! not used, counts the number of enumerated items + EGBIS_COUNT +}; - //! Names for gui button image states - const c8* const GUIButtonImageStateNames[EGBIS_COUNT+1] = - { - "Image", // not "ImageUp" as it otherwise breaks serialization of old files - "ImageUpOver", - "ImageUpFocused", - "ImageUpFocusedOver", - "PressedImage", // not "ImageDown" as it otherwise breaks serialization of old files - "ImageDownOver", - "ImageDownFocused", - "ImageDownFocusedOver", - "ImageDisabled", - 0 // count - }; +//! Names for gui button image states +const c8 *const GUIButtonImageStateNames[EGBIS_COUNT + 1] = + { + "Image", // not "ImageUp" as it otherwise breaks serialization of old files + "ImageUpOver", + "ImageUpFocused", + "ImageUpFocusedOver", + "PressedImage", // not "ImageDown" as it otherwise breaks serialization of old files + "ImageDownOver", + "ImageDownFocused", + "ImageDownFocusedOver", + "ImageDisabled", + 0 // count +}; - //! GUI Button interface. - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_BUTTON_CLICKED - */ - class IGUIButton : public IGUIElement - { - public: +//! GUI Button interface. +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_BUTTON_CLICKED +*/ +class IGUIButton : public IGUIElement +{ +public: + //! constructor + IGUIButton(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_BUTTON, environment, parent, id, rectangle) {} - //! constructor - IGUIButton(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_BUTTON, environment, parent, id, rectangle) {} + //! Sets another skin independent font. + /** If this is set to zero, the button uses the font of the skin. + \param font: New font to set. */ + virtual void setOverrideFont(IGUIFont *font = 0) = 0; - //! Sets another skin independent font. - /** If this is set to zero, the button uses the font of the skin. - \param font: New font to set. */ - virtual void setOverrideFont(IGUIFont* font=0) = 0; + //! Gets the override font (if any) + /** \return The override font (may be 0) */ + virtual IGUIFont *getOverrideFont(void) const = 0; - //! Gets the override font (if any) - /** \return The override font (may be 0) */ - virtual IGUIFont* getOverrideFont(void) const = 0; + //! Get the font which is used right now for drawing + /** Currently this is the override font when one is set and the + font of the active skin otherwise */ + virtual IGUIFont *getActiveFont() const = 0; - //! Get the font which is used right now for drawing - /** Currently this is the override font when one is set and the - font of the active skin otherwise */ - virtual IGUIFont* getActiveFont() const = 0; + //! Sets another color for the button text. + /** When set, this color is used instead of EGDC_BUTTON_TEXT/EGDC_GRAY_TEXT. + You don't need to call enableOverrideColor(true), that's done by this function. + If you want the the color of the skin back, call enableOverrideColor(false); + \param color: New color of the text. */ + virtual void setOverrideColor(video::SColor color) = 0; - //! Sets another color for the button text. - /** When set, this color is used instead of EGDC_BUTTON_TEXT/EGDC_GRAY_TEXT. - You don't need to call enableOverrideColor(true), that's done by this function. - If you want the the color of the skin back, call enableOverrideColor(false); - \param color: New color of the text. */ - virtual void setOverrideColor(video::SColor color) = 0; + //! Gets the override color + /** \return: The override color */ + virtual video::SColor getOverrideColor(void) const = 0; - //! Gets the override color - /** \return: The override color */ - virtual video::SColor getOverrideColor(void) const = 0; + //! Gets the currently used text color + /** Either a skin-color for the current state or the override color */ + virtual video::SColor getActiveColor() const = 0; - //! Gets the currently used text color - /** Either a skin-color for the current state or the override color */ - virtual video::SColor getActiveColor() const = 0; + //! Sets if the button text should use the override color or the color in the gui skin. + /** \param enable: If set to true, the override color, which can be set + with IGUIStaticText::setOverrideColor is used, otherwise the + EGDC_BUTTON_TEXT or EGDC_GRAY_TEXT color of the skin. */ + virtual void enableOverrideColor(bool enable) = 0; - //! Sets if the button text should use the override color or the color in the gui skin. - /** \param enable: If set to true, the override color, which can be set - with IGUIStaticText::setOverrideColor is used, otherwise the - EGDC_BUTTON_TEXT or EGDC_GRAY_TEXT color of the skin. */ - virtual void enableOverrideColor(bool enable) = 0; + //! Checks if an override color is enabled + /** \return true if the override color is enabled, false otherwise */ + virtual bool isOverrideColorEnabled(void) const = 0; - //! Checks if an override color is enabled - /** \return true if the override color is enabled, false otherwise */ - virtual bool isOverrideColorEnabled(void) const = 0; + //! Sets an image which should be displayed on the button when it is in the given state. + /** Only one image-state can be active at a time. Images are drawn below sprites. + If a state is without image it will try to use images from other states as described + in ::EGUI_BUTTON_IMAGE_STATE. + Images are a little less flexible than sprites, but easier to use. + \param state: One of ::EGUI_BUTTON_IMAGE_STATE + \param image: Image to be displayed or NULL to remove the image + \param sourceRect: Source rectangle on the image texture. When width or height are 0 then the full texture-size is used (default). */ + virtual void setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture *image = 0, const core::rect &sourceRect = core::rect(0, 0, 0, 0)) = 0; - //! Sets an image which should be displayed on the button when it is in the given state. - /** Only one image-state can be active at a time. Images are drawn below sprites. - If a state is without image it will try to use images from other states as described - in ::EGUI_BUTTON_IMAGE_STATE. - Images are a little less flexible than sprites, but easier to use. - \param state: One of ::EGUI_BUTTON_IMAGE_STATE - \param image: Image to be displayed or NULL to remove the image - \param sourceRect: Source rectangle on the image texture. When width or height are 0 then the full texture-size is used (default). */ - virtual void setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture* image=0, const core::rect& sourceRect=core::rect(0,0,0,0)) = 0; + //! Sets an image which should be displayed on the button when it is in normal state. + /** This is identical to calling setImage(EGBIS_IMAGE_UP, image); and might be deprecated in future revisions. + \param image: Image to be displayed */ + virtual void setImage(video::ITexture *image = 0) = 0; - //! Sets an image which should be displayed on the button when it is in normal state. - /** This is identical to calling setImage(EGBIS_IMAGE_UP, image); and might be deprecated in future revisions. - \param image: Image to be displayed */ - virtual void setImage(video::ITexture* image=0) = 0; + //! Sets a background image for the button when it is in normal state. + /** This is identical to calling setImage(EGBIS_IMAGE_UP, image, sourceRect); and might be deprecated in future revisions. + \param image: Texture containing the image to be displayed + \param sourceRect: Position in the texture, where the image is located. + When width or height are 0 then the full texture-size is used */ + virtual void setImage(video::ITexture *image, const core::rect &sourceRect) = 0; - //! Sets a background image for the button when it is in normal state. - /** This is identical to calling setImage(EGBIS_IMAGE_UP, image, sourceRect); and might be deprecated in future revisions. - \param image: Texture containing the image to be displayed - \param sourceRect: Position in the texture, where the image is located. - When width or height are 0 then the full texture-size is used */ - virtual void setImage(video::ITexture* image, const core::rect& sourceRect) = 0; + //! Sets a background image for the button when it is in pressed state. + /** This is identical to calling setImage(EGBIS_IMAGE_DOWN, image); and might be deprecated in future revisions. + If no images is specified for the pressed state via + setPressedImage(), this image is also drawn in pressed state. + \param image: Image to be displayed */ + virtual void setPressedImage(video::ITexture *image = 0) = 0; - //! Sets a background image for the button when it is in pressed state. - /** This is identical to calling setImage(EGBIS_IMAGE_DOWN, image); and might be deprecated in future revisions. - If no images is specified for the pressed state via - setPressedImage(), this image is also drawn in pressed state. - \param image: Image to be displayed */ - virtual void setPressedImage(video::ITexture* image=0) = 0; + //! Sets an image which should be displayed on the button when it is in pressed state. + /** This is identical to calling setImage(EGBIS_IMAGE_DOWN, image, sourceRect); and might be deprecated in future revisions. + \param image: Texture containing the image to be displayed + \param sourceRect: Position in the texture, where the image is located */ + virtual void setPressedImage(video::ITexture *image, const core::rect &sourceRect) = 0; - //! Sets an image which should be displayed on the button when it is in pressed state. - /** This is identical to calling setImage(EGBIS_IMAGE_DOWN, image, sourceRect); and might be deprecated in future revisions. - \param image: Texture containing the image to be displayed - \param sourceRect: Position in the texture, where the image is located */ - virtual void setPressedImage(video::ITexture* image, const core::rect& sourceRect) = 0; + //! Sets the sprite bank used by the button + /** NOTE: The spritebank itself is _not_ serialized so far. The sprites are serialized. + Which means after loading the gui you still have to set the spritebank manually. */ + virtual void setSpriteBank(IGUISpriteBank *bank = 0) = 0; + //! Sets the animated sprite for a specific button state + /** Several sprites can be drawn at the same time. + Sprites can be animated. + Sprites are drawn above the images. + \param index: Number of the sprite within the sprite bank, use -1 for no sprite + \param state: State of the button to set the sprite for + \param index: The sprite number from the current sprite bank + \param color: The color of the sprite + \param loop: True if the animation should loop, false if not + \param scale: True if the sprite should scale to button size, false if not */ + virtual void setSprite(EGUI_BUTTON_STATE state, s32 index, + video::SColor color = video::SColor(255, 255, 255, 255), bool loop = false, bool scale = false) = 0; - //! Sets the sprite bank used by the button - /** NOTE: The spritebank itself is _not_ serialized so far. The sprites are serialized. - Which means after loading the gui you still have to set the spritebank manually. */ - virtual void setSpriteBank(IGUISpriteBank* bank=0) = 0; + //! Get the sprite-index for the given state or -1 when no sprite is set + virtual s32 getSpriteIndex(EGUI_BUTTON_STATE state) const = 0; - //! Sets the animated sprite for a specific button state - /** Several sprites can be drawn at the same time. - Sprites can be animated. - Sprites are drawn above the images. - \param index: Number of the sprite within the sprite bank, use -1 for no sprite - \param state: State of the button to set the sprite for - \param index: The sprite number from the current sprite bank - \param color: The color of the sprite - \param loop: True if the animation should loop, false if not - \param scale: True if the sprite should scale to button size, false if not */ - virtual void setSprite(EGUI_BUTTON_STATE state, s32 index, - video::SColor color=video::SColor(255,255,255,255), bool loop=false, bool scale=false) = 0; + //! Get the sprite color for the given state. Color is only used when a sprite is set. + virtual video::SColor getSpriteColor(EGUI_BUTTON_STATE state) const = 0; - //! Get the sprite-index for the given state or -1 when no sprite is set - virtual s32 getSpriteIndex(EGUI_BUTTON_STATE state) const = 0; + //! Returns if the sprite in the given state does loop + virtual bool getSpriteLoop(EGUI_BUTTON_STATE state) const = 0; - //! Get the sprite color for the given state. Color is only used when a sprite is set. - virtual video::SColor getSpriteColor(EGUI_BUTTON_STATE state) const = 0; + //! Returns if the sprite in the given state is scaled + virtual bool getSpriteScale(EGUI_BUTTON_STATE state) const = 0; - //! Returns if the sprite in the given state does loop - virtual bool getSpriteLoop(EGUI_BUTTON_STATE state) const = 0; + //! Sets if the button should behave like a push button. + /** Which means it can be in two states: Normal or Pressed. With a click on the button, + the user can change the state of the button. */ + virtual void setIsPushButton(bool isPushButton = true) = 0; - //! Returns if the sprite in the given state is scaled - virtual bool getSpriteScale(EGUI_BUTTON_STATE state) const = 0; + //! Sets the pressed state of the button if this is a pushbutton + virtual void setPressed(bool pressed = true) = 0; - //! Sets if the button should behave like a push button. - /** Which means it can be in two states: Normal or Pressed. With a click on the button, - the user can change the state of the button. */ - virtual void setIsPushButton(bool isPushButton=true) = 0; + //! Returns if the button is currently pressed + virtual bool isPressed() const = 0; - //! Sets the pressed state of the button if this is a pushbutton - virtual void setPressed(bool pressed=true) = 0; + //! Sets if the alpha channel should be used for drawing background images on the button (default is false) + virtual void setUseAlphaChannel(bool useAlphaChannel = true) = 0; - //! Returns if the button is currently pressed - virtual bool isPressed() const = 0; + //! Returns if the alpha channel should be used for drawing background images on the button + virtual bool isAlphaChannelUsed() const = 0; - //! Sets if the alpha channel should be used for drawing background images on the button (default is false) - virtual void setUseAlphaChannel(bool useAlphaChannel=true) = 0; + //! Returns whether the button is a push button + virtual bool isPushButton() const = 0; - //! Returns if the alpha channel should be used for drawing background images on the button - virtual bool isAlphaChannelUsed() const = 0; + //! Sets if the button should use the skin to draw its border and button face (default is true) + virtual void setDrawBorder(bool border = true) = 0; - //! Returns whether the button is a push button - virtual bool isPushButton() const = 0; + //! Returns if the border and button face are being drawn using the skin + virtual bool isDrawingBorder() const = 0; - //! Sets if the button should use the skin to draw its border and button face (default is true) - virtual void setDrawBorder(bool border=true) = 0; + //! Sets if the button should scale the button images to fit + virtual void setScaleImage(bool scaleImage = true) = 0; - //! Returns if the border and button face are being drawn using the skin - virtual bool isDrawingBorder() const = 0; + //! Checks whether the button scales the used images + virtual bool isScalingImage() const = 0; - //! Sets if the button should scale the button images to fit - virtual void setScaleImage(bool scaleImage=true) = 0; - - //! Checks whether the button scales the used images - virtual bool isScalingImage() const = 0; - - //! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event - /** Generated together with event, so info is available in the event-receiver. */ - virtual bool getClickShiftState() const = 0; - - //! Get if the control key was pressed in last EGET_BUTTON_CLICKED event - /** Generated together with event, so info is available in the event-receiver. */ - virtual bool getClickControlState() const = 0; - }; + //! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event + /** Generated together with event, so info is available in the event-receiver. */ + virtual bool getClickShiftState() const = 0; + //! Get if the control key was pressed in last EGET_BUTTON_CLICKED event + /** Generated together with event, so info is available in the event-receiver. */ + virtual bool getClickControlState() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUICheckBox.h b/include/IGUICheckBox.h index d3a0f3a2..0e71510b 100644 --- a/include/IGUICheckBox.h +++ b/include/IGUICheckBox.h @@ -11,39 +11,37 @@ namespace irr namespace gui { - //! GUI Check box interface. - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_CHECKBOX_CHANGED - */ - class IGUICheckBox : public IGUIElement - { - public: +//! GUI Check box interface. +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_CHECKBOX_CHANGED +*/ +class IGUICheckBox : public IGUIElement +{ +public: + //! constructor + IGUICheckBox(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_CHECK_BOX, environment, parent, id, rectangle) {} - //! constructor - IGUICheckBox(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_CHECK_BOX, environment, parent, id, rectangle) {} + //! Set if box is checked. + virtual void setChecked(bool checked) = 0; - //! Set if box is checked. - virtual void setChecked(bool checked) = 0; + //! Returns true if box is checked. + virtual bool isChecked() const = 0; - //! Returns true if box is checked. - virtual bool isChecked() const = 0; + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw) = 0; - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw) = 0; + //! Checks if background drawing is enabled + /** \return true if background drawing is enabled, false otherwise */ + virtual bool isDrawBackgroundEnabled() const = 0; - //! Checks if background drawing is enabled - /** \return true if background drawing is enabled, false otherwise */ - virtual bool isDrawBackgroundEnabled() const = 0; + //! Sets whether to draw the border + virtual void setDrawBorder(bool draw) = 0; - //! Sets whether to draw the border - virtual void setDrawBorder(bool draw) = 0; - - //! Checks if border drawing is enabled - /** \return true if border drawing is enabled, false otherwise */ - virtual bool isDrawBorderEnabled() const = 0; - - }; + //! Checks if border drawing is enabled + /** \return true if border drawing is enabled, false otherwise */ + virtual bool isDrawBorderEnabled() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIComboBox.h b/include/IGUIComboBox.h index e63fee82..deeaad2b 100644 --- a/include/IGUIComboBox.h +++ b/include/IGUIComboBox.h @@ -11,64 +11,62 @@ namespace irr namespace gui { - //! Combobox widget - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_COMBO_BOX_CHANGED - */ - class IGUIComboBox : public IGUIElement - { - public: +//! Combobox widget +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_COMBO_BOX_CHANGED +*/ +class IGUIComboBox : public IGUIElement +{ +public: + //! constructor + IGUIComboBox(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_COMBO_BOX, environment, parent, id, rectangle) {} - //! constructor - IGUIComboBox(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_COMBO_BOX, environment, parent, id, rectangle) {} + //! Returns amount of items in box + virtual u32 getItemCount() const = 0; - //! Returns amount of items in box - virtual u32 getItemCount() const = 0; + //! Returns string of an item. the idx may be a value from 0 to itemCount-1 + virtual const wchar_t *getItem(u32 idx) const = 0; - //! Returns string of an item. the idx may be a value from 0 to itemCount-1 - virtual const wchar_t* getItem(u32 idx) const = 0; + //! Returns item data of an item. the idx may be a value from 0 to itemCount-1 + virtual u32 getItemData(u32 idx) const = 0; - //! Returns item data of an item. the idx may be a value from 0 to itemCount-1 - virtual u32 getItemData(u32 idx) const = 0; + //! Returns index based on item data + virtual s32 getIndexForItemData(u32 data) const = 0; - //! Returns index based on item data - virtual s32 getIndexForItemData(u32 data ) const = 0; + //! Adds an item and returns the index of it + virtual u32 addItem(const wchar_t *text, u32 data = 0) = 0; - //! Adds an item and returns the index of it - virtual u32 addItem(const wchar_t* text, u32 data = 0) = 0; + //! Removes an item from the combo box. + /** Warning. This will change the index of all following items */ + virtual void removeItem(u32 idx) = 0; - //! Removes an item from the combo box. - /** Warning. This will change the index of all following items */ - virtual void removeItem(u32 idx) = 0; + //! Deletes all items in the combo box + virtual void clear() = 0; - //! Deletes all items in the combo box - virtual void clear() = 0; + //! Returns id of selected item. returns -1 if no item is selected. + virtual s32 getSelected() const = 0; - //! Returns id of selected item. returns -1 if no item is selected. - virtual s32 getSelected() const = 0; + //! Sets the selected item. Set this to -1 if no item should be selected + virtual void setSelected(s32 idx) = 0; - //! Sets the selected item. Set this to -1 if no item should be selected - virtual void setSelected(s32 idx) = 0; + //! Sets the selected item and emits a change event. + /** Set this to -1 if no item should be selected */ + virtual void setAndSendSelected(s32 idx) = 0; - //! Sets the selected item and emits a change event. - /** Set this to -1 if no item should be selected */ - virtual void setAndSendSelected(s32 idx) = 0; + //! Sets text justification of the text area + /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), + EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. + \param vertical: EGUIA_UPPERLEFT to align with top edge, + EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text (default). */ + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; - //! Sets text justification of the text area - /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), - EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. - \param vertical: EGUIA_UPPERLEFT to align with top edge, - EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text (default). */ - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; - - //! Set the maximal number of rows for the selection listbox - virtual void setMaxSelectionRows(u32 max) = 0; - - //! Get the maximal number of rows for the selection listbox - virtual u32 getMaxSelectionRows() const = 0; - }; + //! Set the maximal number of rows for the selection listbox + virtual void setMaxSelectionRows(u32 max) = 0; + //! Get the maximal number of rows for the selection listbox + virtual u32 getMaxSelectionRows() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIEditBox.h b/include/IGUIEditBox.h index 67ca5a1e..c63a905d 100644 --- a/include/IGUIEditBox.h +++ b/include/IGUIEditBox.h @@ -11,143 +11,141 @@ namespace irr { namespace gui { - class IGUIFont; +class IGUIFont; - //! Single line edit box for editing simple text. - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_EDITBOX_ENTER - \li EGET_EDITBOX_CHANGED - \li EGET_EDITBOX_MARKING_CHANGED - */ - class IGUIEditBox : public IGUIElement - { - public: +//! Single line edit box for editing simple text. +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_EDITBOX_ENTER +\li EGET_EDITBOX_CHANGED +\li EGET_EDITBOX_MARKING_CHANGED +*/ +class IGUIEditBox : public IGUIElement +{ +public: + //! constructor + IGUIEditBox(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_EDIT_BOX, environment, parent, id, rectangle) {} - //! constructor - IGUIEditBox(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_EDIT_BOX, environment, parent, id, rectangle) {} + //! Sets another skin independent font. + /** If this is set to zero, the button uses the font of the skin. + \param font: New font to set. */ + virtual void setOverrideFont(IGUIFont *font = 0) = 0; - //! Sets another skin independent font. - /** If this is set to zero, the button uses the font of the skin. - \param font: New font to set. */ - virtual void setOverrideFont(IGUIFont* font=0) = 0; + //! Gets the override font (if any) + /** \return The override font (may be 0) */ + virtual IGUIFont *getOverrideFont() const = 0; - //! Gets the override font (if any) - /** \return The override font (may be 0) */ - virtual IGUIFont* getOverrideFont() const = 0; + //! Get the font which is used right now for drawing + /** Currently this is the override font when one is set and the + font of the active skin otherwise */ + virtual IGUIFont *getActiveFont() const = 0; - //! Get the font which is used right now for drawing - /** Currently this is the override font when one is set and the - font of the active skin otherwise */ - virtual IGUIFont* getActiveFont() const = 0; + //! Sets another color for the text. + /** If set, the edit box does not use the EGDC_BUTTON_TEXT color defined + in the skin, but the set color instead. You don't need to call + IGUIEditBox::enableOverrrideColor(true) after this, this is done + by this function. + If you set a color, and you want the text displayed with the color + of the skin again, call IGUIEditBox::enableOverrideColor(false); + \param color: New color of the text. */ + virtual void setOverrideColor(video::SColor color) = 0; - //! Sets another color for the text. - /** If set, the edit box does not use the EGDC_BUTTON_TEXT color defined - in the skin, but the set color instead. You don't need to call - IGUIEditBox::enableOverrrideColor(true) after this, this is done - by this function. - If you set a color, and you want the text displayed with the color - of the skin again, call IGUIEditBox::enableOverrideColor(false); - \param color: New color of the text. */ - virtual void setOverrideColor(video::SColor color) = 0; + //! Gets the override color + virtual video::SColor getOverrideColor() const = 0; - //! Gets the override color - virtual video::SColor getOverrideColor() const = 0; + //! Sets if the text should use the override color or the color in the gui skin. + /** \param enable: If set to true, the override color, which can be set + with IGUIEditBox::setOverrideColor is used, otherwise the + EGDC_BUTTON_TEXT color of the skin. */ + virtual void enableOverrideColor(bool enable) = 0; - //! Sets if the text should use the override color or the color in the gui skin. - /** \param enable: If set to true, the override color, which can be set - with IGUIEditBox::setOverrideColor is used, otherwise the - EGDC_BUTTON_TEXT color of the skin. */ - virtual void enableOverrideColor(bool enable) = 0; + //! Checks if an override color is enabled + /** \return true if the override color is enabled, false otherwise */ + virtual bool isOverrideColorEnabled(void) const = 0; - //! Checks if an override color is enabled - /** \return true if the override color is enabled, false otherwise */ - virtual bool isOverrideColorEnabled(void) const = 0; + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw) = 0; - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw) = 0; + //! Checks if background drawing is enabled + /** \return true if background drawing is enabled, false otherwise */ + virtual bool isDrawBackgroundEnabled() const = 0; - //! Checks if background drawing is enabled - /** \return true if background drawing is enabled, false otherwise */ - virtual bool isDrawBackgroundEnabled() const = 0; + //! Turns the border on or off + /** \param border: true if you want the border to be drawn, false if not */ + virtual void setDrawBorder(bool border) = 0; - //! Turns the border on or off - /** \param border: true if you want the border to be drawn, false if not */ - virtual void setDrawBorder(bool border) = 0; + //! Checks if border drawing is enabled + /** \return true if border drawing is enabled, false otherwise */ + virtual bool isDrawBorderEnabled() const = 0; - //! Checks if border drawing is enabled - /** \return true if border drawing is enabled, false otherwise */ - virtual bool isDrawBorderEnabled() const = 0; + //! Sets text justification mode + /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), + EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. + \param vertical: EGUIA_UPPERLEFT to align with top edge, + EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text (default). */ + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; - //! Sets text justification mode - /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), - EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. - \param vertical: EGUIA_UPPERLEFT to align with top edge, - EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text (default). */ - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; + //! Enables or disables word wrap. + /** \param enable: If set to true, words going over one line are + broken to the next line. */ + virtual void setWordWrap(bool enable) = 0; - //! Enables or disables word wrap. - /** \param enable: If set to true, words going over one line are - broken to the next line. */ - virtual void setWordWrap(bool enable) = 0; + //! Checks if word wrap is enabled + /** \return true if word wrap is enabled, false otherwise */ + virtual bool isWordWrapEnabled() const = 0; - //! Checks if word wrap is enabled - /** \return true if word wrap is enabled, false otherwise */ - virtual bool isWordWrapEnabled() const = 0; + //! Enables or disables newlines. + /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, + instead a newline character will be inserted. */ + virtual void setMultiLine(bool enable) = 0; - //! Enables or disables newlines. - /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, - instead a newline character will be inserted. */ - virtual void setMultiLine(bool enable) = 0; + //! Checks if multi line editing is enabled + /** \return true if multi-line is enabled, false otherwise */ + virtual bool isMultiLineEnabled() const = 0; - //! Checks if multi line editing is enabled - /** \return true if multi-line is enabled, false otherwise */ - virtual bool isMultiLineEnabled() const = 0; + //! Enables or disables automatic scrolling with cursor position + /** \param enable: If set to true, the text will move around with the cursor position */ + virtual void setAutoScroll(bool enable) = 0; - //! Enables or disables automatic scrolling with cursor position - /** \param enable: If set to true, the text will move around with the cursor position */ - virtual void setAutoScroll(bool enable) = 0; + //! Checks to see if automatic scrolling is enabled + /** \return true if automatic scrolling is enabled, false if not */ + virtual bool isAutoScrollEnabled() const = 0; - //! Checks to see if automatic scrolling is enabled - /** \return true if automatic scrolling is enabled, false if not */ - virtual bool isAutoScrollEnabled() const = 0; + //! Sets whether the edit box is a password box. Setting this to true will + /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x + \param passwordBox: true to enable password, false to disable + \param passwordChar: the character that is displayed instead of letters */ + virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*') = 0; - //! Sets whether the edit box is a password box. Setting this to true will - /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x - \param passwordBox: true to enable password, false to disable - \param passwordChar: the character that is displayed instead of letters */ - virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*') = 0; + //! Returns true if the edit box is currently a password box. + virtual bool isPasswordBox() const = 0; - //! Returns true if the edit box is currently a password box. - virtual bool isPasswordBox() const = 0; + //! Gets the size area of the text in the edit box + /** \return The size in pixels of the text */ + virtual core::dimension2du getTextDimension() = 0; - //! Gets the size area of the text in the edit box - /** \return The size in pixels of the text */ - virtual core::dimension2du getTextDimension() = 0; + //! Sets the maximum amount of characters which may be entered in the box. + /** \param max: Maximum amount of characters. If 0, the character amount is + infinity. */ + virtual void setMax(u32 max) = 0; - //! Sets the maximum amount of characters which may be entered in the box. - /** \param max: Maximum amount of characters. If 0, the character amount is - infinity. */ - virtual void setMax(u32 max) = 0; + //! Returns maximum amount of characters, previously set by setMax(); + virtual u32 getMax() const = 0; - //! Returns maximum amount of characters, previously set by setMax(); - virtual u32 getMax() const = 0; + //! Set the character used for the cursor. + /** By default it's "_" */ + virtual void setCursorChar(const wchar_t cursorChar) = 0; - //! Set the character used for the cursor. - /** By default it's "_" */ - virtual void setCursorChar(const wchar_t cursorChar) = 0; + //! Get the character used for the cursor. + virtual wchar_t getCursorChar() const = 0; - //! Get the character used for the cursor. - virtual wchar_t getCursorChar() const = 0; - - //! Set the blinktime for the cursor. 2x blinktime is one full cycle. - //** \param timeMs Blinktime in milliseconds. When set to 0 the cursor is constantly on without blinking */ - virtual void setCursorBlinkTime(irr::u32 timeMs) = 0; - - //! Get the cursor blinktime - virtual irr::u32 getCursorBlinkTime() const = 0; - }; + //! Set the blinktime for the cursor. 2x blinktime is one full cycle. + //** \param timeMs Blinktime in milliseconds. When set to 0 the cursor is constantly on without blinking */ + virtual void setCursorBlinkTime(irr::u32 timeMs) = 0; + //! Get the cursor blinktime + virtual irr::u32 getCursorBlinkTime() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIElement.h b/include/IGUIElement.h index 552ccf15..6c5de88e 100644 --- a/include/IGUIElement.h +++ b/include/IGUIElement.h @@ -25,30 +25,28 @@ namespace gui class IGUIElement : virtual public IReferenceCounted, public IEventReceiver { public: - //! Constructor - IGUIElement(EGUI_ELEMENT_TYPE type, IGUIEnvironment* environment, IGUIElement* parent, - s32 id, const core::rect& rectangle) - : Parent(0), RelativeRect(rectangle), AbsoluteRect(rectangle), - AbsoluteClippingRect(rectangle), DesiredRect(rectangle), - MaxSize(0,0), MinSize(1,1), IsVisible(true), IsEnabled(true), - IsSubElement(false), NoClip(false), ID(id), IsTabStop(false), TabOrder(-1), IsTabGroup(false), - AlignLeft(EGUIA_UPPERLEFT), AlignRight(EGUIA_UPPERLEFT), AlignTop(EGUIA_UPPERLEFT), AlignBottom(EGUIA_UPPERLEFT), - Environment(environment), Type(type) + IGUIElement(EGUI_ELEMENT_TYPE type, IGUIEnvironment *environment, IGUIElement *parent, + s32 id, const core::rect &rectangle) : + Parent(0), + RelativeRect(rectangle), AbsoluteRect(rectangle), + AbsoluteClippingRect(rectangle), DesiredRect(rectangle), + MaxSize(0, 0), MinSize(1, 1), IsVisible(true), IsEnabled(true), + IsSubElement(false), NoClip(false), ID(id), IsTabStop(false), TabOrder(-1), IsTabGroup(false), + AlignLeft(EGUIA_UPPERLEFT), AlignRight(EGUIA_UPPERLEFT), AlignTop(EGUIA_UPPERLEFT), AlignBottom(EGUIA_UPPERLEFT), + Environment(environment), Type(type) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("IGUIElement"); - #endif +#endif // if we were given a parent to attach to - if (parent) - { + if (parent) { parent->addChildToEnd(this); recalculateAbsolutePosition(true); } } - //! Destructor virtual ~IGUIElement() { @@ -58,9 +56,8 @@ public: } } - //! Returns parent of this element. - IGUIElement* getParent() const + IGUIElement *getParent() const { return Parent; } @@ -71,22 +68,20 @@ public: return RelativeRect; } - //! Sets the relative rectangle of this element. /** \param r The absolute position to set */ - void setRelativePosition(const core::rect& r) + void setRelativePosition(const core::rect &r) { - if (Parent) - { - const core::rect& r2 = Parent->getAbsolutePosition(); + if (Parent) { + const core::rect &r2 = Parent->getAbsolutePosition(); core::dimension2df d((f32)(r2.getSize().Width), (f32)(r2.getSize().Height)); - if (AlignLeft == EGUIA_SCALE) + if (AlignLeft == EGUIA_SCALE) ScaleRect.UpperLeftCorner.X = (f32)r.UpperLeftCorner.X / d.Width; - if (AlignRight == EGUIA_SCALE) + if (AlignRight == EGUIA_SCALE) ScaleRect.LowerRightCorner.X = (f32)r.LowerRightCorner.X / d.Width; - if (AlignTop == EGUIA_SCALE) + if (AlignTop == EGUIA_SCALE) ScaleRect.UpperLeftCorner.Y = (f32)r.UpperLeftCorner.Y / d.Height; if (AlignBottom == EGUIA_SCALE) ScaleRect.LowerRightCorner.Y = (f32)r.LowerRightCorner.Y / d.Height; @@ -98,53 +93,49 @@ public: //! Sets the relative rectangle of this element, maintaining its current width and height /** \param position The new relative position to set. Width and height will not be changed. */ - void setRelativePosition(const core::position2di & position) + void setRelativePosition(const core::position2di &position) { const core::dimension2di mySize = RelativeRect.getSize(); const core::rect rectangle(position.X, position.Y, - position.X + mySize.Width, position.Y + mySize.Height); + position.X + mySize.Width, position.Y + mySize.Height); setRelativePosition(rectangle); } - //! Sets the relative rectangle of this element as a proportion of its parent's area. /** \note This method used to be 'void setRelativePosition(const core::rect& r)' \param r The rectangle to set, interpreted as a proportion of the parent's area. Meaningful values are in the range [0...1], unless you intend this element to spill outside its parent. */ - void setRelativePositionProportional(const core::rect& r) + void setRelativePositionProportional(const core::rect &r) { if (!Parent) return; - const core::dimension2di& d = Parent->getAbsolutePosition().getSize(); + const core::dimension2di &d = Parent->getAbsolutePosition().getSize(); DesiredRect = core::rect( - core::floor32((f32)d.Width * r.UpperLeftCorner.X), - core::floor32((f32)d.Height * r.UpperLeftCorner.Y), - core::floor32((f32)d.Width * r.LowerRightCorner.X), - core::floor32((f32)d.Height * r.LowerRightCorner.Y)); + core::floor32((f32)d.Width * r.UpperLeftCorner.X), + core::floor32((f32)d.Height * r.UpperLeftCorner.Y), + core::floor32((f32)d.Width * r.LowerRightCorner.X), + core::floor32((f32)d.Height * r.LowerRightCorner.Y)); ScaleRect = r; updateAbsolutePosition(); } - //! Gets the absolute rectangle of this element core::rect getAbsolutePosition() const { return AbsoluteRect; } - //! Returns the visible area of the element. core::rect getAbsoluteClippingRect() const { return AbsoluteClippingRect; } - //! Sets whether the element will ignore its parent's clipping rectangle /** \param noClip If true, the element will not be clipped by its parent's clipping rectangle. */ void setNotClipped(bool noClip) @@ -153,7 +144,6 @@ public: updateAbsolutePosition(); } - //! Gets whether the element will ignore its parent's clipping rectangle /** \return true if the element is not clipped by its parent's clipping rectangle. */ bool isNotClipped() const @@ -161,7 +151,6 @@ public: return NoClip; } - //! Sets the maximum size allowed for this element /** If set to 0,0, there is no maximum size */ void setMaxSize(core::dimension2du size) @@ -170,7 +159,6 @@ public: updateAbsolutePosition(); } - //! Sets the minimum size allowed for this element void setMinSize(core::dimension2du size) { @@ -182,7 +170,6 @@ public: updateAbsolutePosition(); } - //! The alignment defines how the borders of this element will be positioned when the parent element is resized. void setAlignment(EGUI_ALIGNMENT left, EGUI_ALIGNMENT right, EGUI_ALIGNMENT top, EGUI_ALIGNMENT bottom) { @@ -191,17 +178,16 @@ public: AlignTop = top; AlignBottom = bottom; - if (Parent) - { + if (Parent) { core::rect r(Parent->getAbsolutePosition()); core::dimension2df d((f32)r.getSize().Width, (f32)r.getSize().Height); - if (AlignLeft == EGUIA_SCALE) + if (AlignLeft == EGUIA_SCALE) ScaleRect.UpperLeftCorner.X = (f32)DesiredRect.UpperLeftCorner.X / d.Width; - if (AlignRight == EGUIA_SCALE) + if (AlignRight == EGUIA_SCALE) ScaleRect.LowerRightCorner.X = (f32)DesiredRect.LowerRightCorner.X / d.Width; - if (AlignTop == EGUIA_SCALE) + if (AlignTop == EGUIA_SCALE) ScaleRect.UpperLeftCorner.Y = (f32)DesiredRect.UpperLeftCorner.Y / d.Height; if (AlignBottom == EGUIA_SCALE) ScaleRect.LowerRightCorner.Y = (f32)DesiredRect.LowerRightCorner.Y / d.Height; @@ -238,13 +224,11 @@ public: recalculateAbsolutePosition(false); // update all children - for (auto child : Children) - { + for (auto child : Children) { child->updateAbsolutePosition(); } } - //! Returns the topmost GUI element at the specific position. /** This will check this GUI element and all of its descendants, so it @@ -257,18 +241,16 @@ public: \return The topmost GUI element at that point, or 0 if there are no candidate elements at this point. */ - virtual IGUIElement* getElementFromPoint(const core::position2d& point) + virtual IGUIElement *getElementFromPoint(const core::position2d &point) { - IGUIElement* target = 0; + IGUIElement *target = 0; - if (isVisible()) - { + if (isVisible()) { // we have to search from back to front, because later children // might be drawn over the top of earlier ones. auto it = Children.rbegin(); auto ie = Children.rend(); - while (it != ie) - { + while (it != ie) { target = (*it)->getElementFromPoint(point); if (target) return target; @@ -283,27 +265,24 @@ public: return target; } - //! Returns true if a point is within this element. /** Elements with a shape other than a rectangle should override this method */ - virtual bool isPointInside(const core::position2d& point) const + virtual bool isPointInside(const core::position2d &point) const { return AbsoluteClippingRect.isPointInside(point); } - //! Adds a GUI element as new child of this element. - virtual void addChild(IGUIElement* child) + virtual void addChild(IGUIElement *child) { - if ( child && child != this ) - { + if (child && child != this) { addChildToEnd(child); child->updateAbsolutePosition(); } } //! Removes a child. - virtual void removeChild(IGUIElement* child) + virtual void removeChild(IGUIElement *child) { assert(child->Parent == this); Children.erase(child->ParentPos); @@ -312,7 +291,8 @@ public: } //! Removes all children. - virtual void removeAllChildren() { + virtual void removeAllChildren() + { while (!Children.empty()) { auto child = Children.back(); child->remove(); @@ -326,36 +306,30 @@ public: Parent->removeChild(this); } - //! Draws the element and its children. virtual void draw() { - if ( isVisible() ) - { + if (isVisible()) { for (auto child : Children) child->draw(); } } - //! animate the element and its children. virtual void OnPostRender(u32 timeMs) { - if ( isVisible() ) - { + if (isVisible()) { for (auto child : Children) - child->OnPostRender( timeMs ); + child->OnPostRender(timeMs); } } - //! Moves this element. virtual void move(core::position2d absoluteMovement) { setRelativePosition(DesiredRect + absoluteMovement); } - //! Returns true if element is visible. virtual bool isVisible() const { @@ -367,10 +341,10 @@ public: false if this or any parent element is invisible. */ virtual bool isTrulyVisible() const { - if(!IsVisible) + if (!IsVisible) return false; - if(!Parent) + if (!Parent) return true; return Parent->isTrulyVisible(); @@ -382,14 +356,12 @@ public: IsVisible = visible; } - //! Returns true if this element was created as part of its parent control virtual bool isSubElement() const { return IsSubElement; } - //! Sets whether this control was created as part of its parent. /** For example, it is true when a scrollbar is part of a listbox. SubElements are not saved to disk when calling guiEnvironment->saveGUI() */ @@ -398,7 +370,6 @@ public: IsSubElement = subElement; } - //! If set to true, the focus will visit this element when using the tab key to cycle through elements. /** If this element is a tab group (see isTabGroup/setTabGroup) then ctrl+tab will be used instead. */ @@ -407,51 +378,43 @@ public: IsTabStop = enable; } - //! Returns true if this element can be focused by navigating with the tab key bool isTabStop() const { return IsTabStop; } - //! Sets the priority of focus when using the tab key to navigate between a group of elements. /** See setTabGroup, isTabGroup and getTabGroup for information on tab groups. Elements with a lower number are focused first */ void setTabOrder(s32 index) { // negative = autonumber - if (index < 0) - { + if (index < 0) { TabOrder = 0; IGUIElement *el = getTabGroup(); while (IsTabGroup && el && el->Parent) el = el->Parent; - IGUIElement *first=0, *closest=0; - if (el) - { + IGUIElement *first = 0, *closest = 0; + if (el) { // find the highest element number el->getNextElement(-1, true, IsTabGroup, first, closest, true, true); - if (first) - { + if (first) { TabOrder = first->getTabOrder() + 1; } } - } - else + } else TabOrder = index; } - //! Returns the number in the tab order sequence s32 getTabOrder() const { return TabOrder; } - //! Sets whether this element is a container for a group of elements which can be navigated using the tab key. /** For example, windows are tab groups. Groups can be navigated using ctrl+tab, providing isTabStop is true. */ @@ -460,18 +423,16 @@ public: IsTabGroup = isGroup; } - //! Returns true if this element is a tab group. bool isTabGroup() const { return IsTabGroup; } - //! Returns the container element which holds all elements in this element's tab group. - IGUIElement* getTabGroup() + IGUIElement *getTabGroup() { - IGUIElement *ret=this; + IGUIElement *ret = this; while (ret && !ret->isTabGroup()) ret = ret->getParent(); @@ -479,7 +440,6 @@ public: return ret; } - //! Returns true if element is enabled /** Currently elements do _not_ care about parent-states. So if you want to affect children you have to enable/disable them all. @@ -487,72 +447,63 @@ public: */ virtual bool isEnabled() const { - if ( isSubElement() && IsEnabled && getParent() ) + if (isSubElement() && IsEnabled && getParent()) return getParent()->isEnabled(); return IsEnabled; } - //! Sets the enabled state of this element. virtual void setEnabled(bool enabled) { IsEnabled = enabled; } - //! Sets the new caption of this element. - virtual void setText(const wchar_t* text) + virtual void setText(const wchar_t *text) { Text = text; } - //! Returns caption of this element. - virtual const wchar_t* getText() const + virtual const wchar_t *getText() const { return Text.c_str(); } - //! Sets the new caption of this element. - virtual void setToolTipText(const wchar_t* text) + virtual void setToolTipText(const wchar_t *text) { ToolTipText = text; } - //! Returns caption of this element. - virtual const core::stringw& getToolTipText() const + virtual const core::stringw &getToolTipText() const { return ToolTipText; } - //! Returns id. Can be used to identify the element. virtual s32 getID() const { return ID; } - //! Sets the id of this element virtual void setID(s32 id) { ID = id; } - //! Called if an event happened. - bool OnEvent(const SEvent& event) override + bool OnEvent(const SEvent &event) override { return Parent ? Parent->OnEvent(event) : false; } - //! Brings a child to front /** \return True if successful, false if not. */ - virtual bool bringToFront(IGUIElement* child) + virtual bool bringToFront(IGUIElement *child) { if (child->Parent != this) return false; @@ -563,10 +514,9 @@ public: return true; } - //! Moves a child to the back, so it's siblings are drawn on top of it /** \return True if successful, false if not. */ - virtual bool sendToBack(IGUIElement* child) + virtual bool sendToBack(IGUIElement *child) { if (child->Parent != this) return false; @@ -578,12 +528,11 @@ public: } //! Returns list with children of this element - virtual const std::list& getChildren() const + virtual const std::list &getChildren() const { return Children; } - //! Finds the first element with the given id. /** \param id: Id to search for. \param searchchildren: Set this to true, if also children of this @@ -591,12 +540,11 @@ public: should be searched too. \return Returns the first element with the given id. If no element with this id was found, 0 is returned. */ - virtual IGUIElement* getElementFromId(s32 id, bool searchchildren=false) const + virtual IGUIElement *getElementFromId(s32 id, bool searchchildren = false) const { - IGUIElement* e = 0; + IGUIElement *e = 0; - for (auto child : Children) - { + for (auto child : Children) { if (child->getID() == id) return child; @@ -610,25 +558,21 @@ public: return e; } - //! returns true if the given element is a child of this one. //! \param child: The child element to check - bool isMyChild(IGUIElement* child) const + bool isMyChild(IGUIElement *child) const { if (!child) return false; - do - { + do { if (child->Parent) child = child->Parent; } while (child->Parent && child != this); - return child == this; } - //! searches elements to find the closest next element to tab to /** \param startOrder: The TabOrder of the current element, -1 if none \param reverse: true if searching for a lower number @@ -639,74 +583,58 @@ public: \param includeDisabled: includes disabled elements in the search (default=false) \return true if successfully found an element, false to continue searching/fail */ bool getNextElement(s32 startOrder, bool reverse, bool group, - IGUIElement*& first, IGUIElement*& closest, bool includeInvisible=false, - bool includeDisabled=false) const + IGUIElement *&first, IGUIElement *&closest, bool includeInvisible = false, + bool includeDisabled = false) const { // we'll stop searching if we find this number - s32 wanted = startOrder + ( reverse ? -1 : 1 ); - if (wanted==-2) + s32 wanted = startOrder + (reverse ? -1 : 1); + if (wanted == -2) wanted = 1073741824; // maximum s32 auto it = Children.begin(); s32 closestOrder, currentOrder; - while(it != Children.end()) - { + while (it != Children.end()) { // ignore invisible elements and their children - if ( ( (*it)->isVisible() || includeInvisible ) && - (group == true || (*it)->isTabGroup() == false) ) - { + if (((*it)->isVisible() || includeInvisible) && + (group == true || (*it)->isTabGroup() == false)) { // ignore disabled, but children are checked (disabled is currently per element ignoring parent states) - if ( (*it)->isEnabled() || includeDisabled ) - { + if ((*it)->isEnabled() || includeDisabled) { // only check tab stops and those with the same group status - if ((*it)->isTabStop() && ((*it)->isTabGroup() == group)) - { + if ((*it)->isTabStop() && ((*it)->isTabGroup() == group)) { currentOrder = (*it)->getTabOrder(); // is this what we're looking for? - if (currentOrder == wanted) - { + if (currentOrder == wanted) { closest = *it; return true; } // is it closer than the current closest? - if (closest) - { + if (closest) { closestOrder = closest->getTabOrder(); - if ( ( reverse && currentOrder > closestOrder && currentOrder < startOrder) - ||(!reverse && currentOrder < closestOrder && currentOrder > startOrder)) - { + if ((reverse && currentOrder > closestOrder && currentOrder < startOrder) || (!reverse && currentOrder < closestOrder && currentOrder > startOrder)) { closest = *it; } - } - else - if ( (reverse && currentOrder < startOrder) || (!reverse && currentOrder > startOrder) ) - { + } else if ((reverse && currentOrder < startOrder) || (!reverse && currentOrder > startOrder)) { closest = *it; } // is it before the current first? - if (first) - { + if (first) { closestOrder = first->getTabOrder(); - if ( (reverse && closestOrder < currentOrder) || (!reverse && closestOrder > currentOrder) ) - { + if ((reverse && closestOrder < currentOrder) || (!reverse && closestOrder > currentOrder)) { first = *it; } - } - else - { + } else { first = *it; } } } // search within children - if ((*it)->getNextElement(startOrder, reverse, group, first, closest, includeInvisible, includeDisabled)) - { + if ((*it)->getNextElement(startOrder, reverse, group, first, closest, includeInvisible, includeDisabled)) { return true; } } @@ -715,7 +643,6 @@ public: return false; } - //! Returns the type of the gui element. /** This is needed for the .NET wrapper but will be used later for serializing and deserializing. @@ -740,52 +667,46 @@ public: return type == Type; } - //! Returns the type name of the gui element. /** This is needed serializing elements. */ - virtual const c8* getTypeName() const + virtual const c8 *getTypeName() const { return GUIElementTypeNames[Type]; } //! Returns the name of the element. /** \return Name as character string. */ - virtual const c8* getName() const + virtual const c8 *getName() const { return Name.c_str(); } - //! Sets the name of the element. /** \param name New name of the gui element. */ - virtual void setName(const c8* name) + virtual void setName(const c8 *name) { Name = name; } - //! Sets the name of the element. /** \param name New name of the gui element. */ - virtual void setName(const core::stringc& name) + virtual void setName(const core::stringc &name) { Name = name; } - //! Returns whether the element takes input from the IME virtual bool acceptsIME() { return false; } - protected: // not virtual because needed in constructor - void addChildToEnd(IGUIElement* child) + void addChildToEnd(IGUIElement *child) { - if (child) - { - child->grab(); // prevent destruction when removed + if (child) { + child->grab(); // prevent destruction when removed child->remove(); // remove from old parent child->LastParentRect = getAbsolutePosition(); child->Parent = this; @@ -794,8 +715,9 @@ protected: } #ifndef NDEBUG - template - static size_t _fastSetChecksum(Iterator begin, Iterator end) { + template + static size_t _fastSetChecksum(Iterator begin, Iterator end) + { std::hash hasher; size_t checksum = 0; for (Iterator it = begin; it != end; ++it) { @@ -808,13 +730,12 @@ protected: // Reorder children [from, to) to the order given by `neworder` void reorderChildren( - std::list::iterator from, - std::list::iterator to, - const std::vector &neworder) + std::list::iterator from, + std::list::iterator to, + const std::vector &neworder) { assert(_fastSetChecksum(from, to) == _fastSetChecksum(neworder.begin(), neworder.end())); - for (auto e : neworder) - { + for (auto e : neworder) { *from = e; e->ParentPos = from; ++from; @@ -822,26 +743,22 @@ protected: assert(from == to); } - // not virtual because needed in constructor void recalculateAbsolutePosition(bool recursive) { - core::rect parentAbsolute(0,0,0,0); + core::rect parentAbsolute(0, 0, 0, 0); core::rect parentAbsoluteClip; - f32 fw=0.f, fh=0.f; + f32 fw = 0.f, fh = 0.f; - if (Parent) - { + if (Parent) { parentAbsolute = Parent->AbsoluteRect; - if (NoClip) - { - IGUIElement* p=this; + if (NoClip) { + IGUIElement *p = this; while (p->Parent) p = p->Parent; parentAbsoluteClip = p->AbsoluteClippingRect; - } - else + } else parentAbsoluteClip = Parent->AbsoluteClippingRect; } @@ -854,64 +771,60 @@ protected: if (AlignTop == EGUIA_SCALE || AlignBottom == EGUIA_SCALE) fh = (f32)parentAbsolute.getHeight(); - switch (AlignLeft) - { - case EGUIA_UPPERLEFT: - break; - case EGUIA_LOWERRIGHT: - DesiredRect.UpperLeftCorner.X += diffx; - break; - case EGUIA_CENTER: - DesiredRect.UpperLeftCorner.X += diffx/2; - break; - case EGUIA_SCALE: - DesiredRect.UpperLeftCorner.X = core::round32(ScaleRect.UpperLeftCorner.X * fw); - break; + switch (AlignLeft) { + case EGUIA_UPPERLEFT: + break; + case EGUIA_LOWERRIGHT: + DesiredRect.UpperLeftCorner.X += diffx; + break; + case EGUIA_CENTER: + DesiredRect.UpperLeftCorner.X += diffx / 2; + break; + case EGUIA_SCALE: + DesiredRect.UpperLeftCorner.X = core::round32(ScaleRect.UpperLeftCorner.X * fw); + break; } - switch (AlignRight) - { - case EGUIA_UPPERLEFT: - break; - case EGUIA_LOWERRIGHT: - DesiredRect.LowerRightCorner.X += diffx; - break; - case EGUIA_CENTER: - DesiredRect.LowerRightCorner.X += diffx/2; - break; - case EGUIA_SCALE: - DesiredRect.LowerRightCorner.X = core::round32(ScaleRect.LowerRightCorner.X * fw); - break; + switch (AlignRight) { + case EGUIA_UPPERLEFT: + break; + case EGUIA_LOWERRIGHT: + DesiredRect.LowerRightCorner.X += diffx; + break; + case EGUIA_CENTER: + DesiredRect.LowerRightCorner.X += diffx / 2; + break; + case EGUIA_SCALE: + DesiredRect.LowerRightCorner.X = core::round32(ScaleRect.LowerRightCorner.X * fw); + break; } - switch (AlignTop) - { - case EGUIA_UPPERLEFT: - break; - case EGUIA_LOWERRIGHT: - DesiredRect.UpperLeftCorner.Y += diffy; - break; - case EGUIA_CENTER: - DesiredRect.UpperLeftCorner.Y += diffy/2; - break; - case EGUIA_SCALE: - DesiredRect.UpperLeftCorner.Y = core::round32(ScaleRect.UpperLeftCorner.Y * fh); - break; + switch (AlignTop) { + case EGUIA_UPPERLEFT: + break; + case EGUIA_LOWERRIGHT: + DesiredRect.UpperLeftCorner.Y += diffy; + break; + case EGUIA_CENTER: + DesiredRect.UpperLeftCorner.Y += diffy / 2; + break; + case EGUIA_SCALE: + DesiredRect.UpperLeftCorner.Y = core::round32(ScaleRect.UpperLeftCorner.Y * fh); + break; } - switch (AlignBottom) - { - case EGUIA_UPPERLEFT: - break; - case EGUIA_LOWERRIGHT: - DesiredRect.LowerRightCorner.Y += diffy; - break; - case EGUIA_CENTER: - DesiredRect.LowerRightCorner.Y += diffy/2; - break; - case EGUIA_SCALE: - DesiredRect.LowerRightCorner.Y = core::round32(ScaleRect.LowerRightCorner.Y * fh); - break; + switch (AlignBottom) { + case EGUIA_UPPERLEFT: + break; + case EGUIA_LOWERRIGHT: + DesiredRect.LowerRightCorner.Y += diffy; + break; + case EGUIA_CENTER: + DesiredRect.LowerRightCorner.Y += diffy / 2; + break; + case EGUIA_SCALE: + DesiredRect.LowerRightCorner.Y = core::round32(ScaleRect.LowerRightCorner.Y * fh); + break; } RelativeRect = DesiredRect; @@ -941,26 +854,23 @@ protected: LastParentRect = parentAbsolute; - if ( recursive ) - { + if (recursive) { // update all children - for (auto child : Children) - { + for (auto child : Children) { child->recalculateAbsolutePosition(recursive); } } } protected: - //! List of all children of this element - std::list Children; + std::list Children; //! Pointer to the parent - IGUIElement* Parent; + IGUIElement *Parent; //! Our position in the parent list. Only valid when Parent != nullptr - std::list::iterator ParentPos; + std::list::iterator ParentPos; //! relative rect of element core::rect RelativeRect; @@ -1021,12 +931,11 @@ protected: EGUI_ALIGNMENT AlignLeft, AlignRight, AlignTop, AlignBottom; //! GUI Environment - IGUIEnvironment* Environment; + IGUIEnvironment *Environment; //! type of element EGUI_ELEMENT_TYPE Type; }; - } // end namespace gui } // end namespace irr diff --git a/include/IGUIEnvironment.h b/include/IGUIEnvironment.h index 833d00ff..b9905252 100644 --- a/include/IGUIEnvironment.h +++ b/include/IGUIEnvironment.h @@ -13,20 +13,20 @@ namespace irr { - class IOSOperator; - class IEventReceiver; +class IOSOperator; +class IEventReceiver; - namespace io - { - class IReadFile; - class IWriteFile; - class IFileSystem; - } // end namespace io - namespace video - { - class IVideoDriver; - class ITexture; - } // end namespace video +namespace io +{ +class IReadFile; +class IWriteFile; +class IFileSystem; +} // end namespace io +namespace video +{ +class IVideoDriver; +class ITexture; +} // end namespace video namespace gui { @@ -58,11 +58,10 @@ class IGUIWindow; class IGUIEnvironment : public virtual IReferenceCounted { public: - //! Draws all gui elements by traversing the GUI environment starting at the root node. /** \param When true ensure the GuiEnvironment (aka the RootGUIElement) has the same size as the current driver screensize. - Can be set to false to control that size yourself, p.E when not the full size should be used for UI. */ - virtual void drawAll(bool useScreenSize=true) = 0; + Can be set to false to control that size yourself, p.E when not the full size should be used for UI. */ + virtual void drawAll(bool useScreenSize = true) = 0; //! Sets the focus to an element. /** Causes a EGET_ELEMENT_FOCUS_LOST event followed by a @@ -70,11 +69,11 @@ public: then the focus will not be changed. \param element Pointer to the element which shall get the focus. \return True on success, false on failure */ - virtual bool setFocus(IGUIElement* element) = 0; + virtual bool setFocus(IGUIElement *element) = 0; //! Returns the element which holds the focus. /** \return Pointer to the element with focus. */ - virtual IGUIElement* getFocus() const = 0; + virtual IGUIElement *getFocus() const = 0; //! Returns the element which was last under the mouse cursor /** NOTE: This information is updated _after_ the user-eventreceiver @@ -82,32 +81,32 @@ public: mouse events you have to use instead: IGUIEnvironment::getRootGUIElement()->getElementFromPoint(mousePos); \return Pointer to the element under the mouse. */ - virtual IGUIElement* getHovered() const = 0; + virtual IGUIElement *getHovered() const = 0; //! Removes the focus from an element. /** Causes a EGET_ELEMENT_FOCUS_LOST event. If the event is absorbed then the focus will not be changed. \param element Pointer to the element which shall lose the focus. \return True on success, false on failure */ - virtual bool removeFocus(IGUIElement* element) = 0; + virtual bool removeFocus(IGUIElement *element) = 0; //! Returns whether the element has focus /** \param element Pointer to the element which is tested. \param checkSubElements When true and focus is on a sub-element of element then it will still count as focused and return true \return True if the element has focus, else false. */ - virtual bool hasFocus(const IGUIElement* element, bool checkSubElements=false) const = 0; + virtual bool hasFocus(const IGUIElement *element, bool checkSubElements = false) const = 0; //! Returns the current video driver. /** \return Pointer to the video driver. */ - virtual video::IVideoDriver* getVideoDriver() const = 0; + virtual video::IVideoDriver *getVideoDriver() const = 0; //! Returns the file system. /** \return Pointer to the file system. */ - virtual io::IFileSystem* getFileSystem() const = 0; + virtual io::IFileSystem *getFileSystem() const = 0; //! returns a pointer to the OS operator /** \return Pointer to the OS operator. */ - virtual IOSOperator* getOSOperator() const = 0; + virtual IOSOperator *getOSOperator() const = 0; //! Removes all elements from the environment. virtual void clear() = 0; @@ -117,17 +116,17 @@ public: use this method, it is used by the engine internally. \param event The event to post. \return True if succeeded, else false. */ - virtual bool postEventFromUser(const SEvent& event) = 0; + virtual bool postEventFromUser(const SEvent &event) = 0; //! This sets a new event receiver for gui events. /** Usually you do not have to use this method, it is used by the engine internally. \param evr Pointer to the new receiver. */ - virtual void setUserEventReceiver(IEventReceiver* evr) = 0; + virtual void setUserEventReceiver(IEventReceiver *evr) = 0; //! Returns pointer to the current gui skin. /** \return Pointer to the GUI skin. */ - virtual IGUISkin* getSkin() const = 0; + virtual IGUISkin *getSkin() const = 0; //! Sets a new GUI Skin /** You can use this to change the appearance of the whole GUI @@ -142,7 +141,7 @@ public: \endcode \param skin New skin to use. */ - virtual void setSkin(IGUISkin* skin) = 0; + virtual void setSkin(IGUISkin *skin) = 0; //! Creates a new GUI Skin based on a template. /** Use setSkin() to set the created skin. @@ -150,8 +149,7 @@ public: \return Pointer to the created skin. If you no longer need it, you should call IGUISkin::drop(). See IReferenceCounted::drop() for more information. */ - virtual IGUISkin* createSkin(EGUI_SKIN_TYPE type) = 0; - + virtual IGUISkin *createSkin(EGUI_SKIN_TYPE type) = 0; //! Creates the image list from the given texture. /** \param texture Texture to split into images @@ -160,9 +158,9 @@ public: \return Pointer to the font. Returns 0 if the font could not be loaded. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIImageList* createImageList( video::ITexture* texture, - core::dimension2d imageSize, - bool useAlphaChannel ) = 0; + virtual IGUIImageList *createImageList(video::ITexture *texture, + core::dimension2d imageSize, + bool useAlphaChannel) = 0; //! Returns pointer to the font with the specified filename. /** Loads the font if it was not loaded before. @@ -170,7 +168,7 @@ public: \return Pointer to the font. Returns 0 if the font could not be loaded. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIFont* getFont(const io::path& filename) = 0; + virtual IGUIFont *getFont(const io::path &filename) = 0; //! Adds an externally loaded font to the font list. /** This method allows to attach an already loaded font to the list of @@ -178,29 +176,29 @@ public: \param name Name the font should be stored as. \param font Pointer to font to add. \return Pointer to the font stored. This can differ from given parameter if the name previously existed. */ - virtual IGUIFont* addFont(const io::path& name, IGUIFont* font) = 0; + virtual IGUIFont *addFont(const io::path &name, IGUIFont *font) = 0; //! remove loaded font - virtual void removeFont(IGUIFont* font) = 0; + virtual void removeFont(IGUIFont *font) = 0; //! Returns the default built-in font. /** \return Pointer to the default built-in font. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIFont* getBuiltInFont() const = 0; + virtual IGUIFont *getBuiltInFont() const = 0; //! Returns pointer to the sprite bank which was added with addEmptySpriteBank /** TODO: This should load files in the future, but not implemented so far. \param filename Name of a spritebank added with addEmptySpriteBank \return Pointer to the sprite bank. Returns 0 if it could not be loaded. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUISpriteBank* getSpriteBank(const io::path& filename) = 0; + virtual IGUISpriteBank *getSpriteBank(const io::path &filename) = 0; //! Adds an empty sprite bank to the manager /** \param name Name of the new sprite bank. \return Pointer to the sprite bank. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUISpriteBank* addEmptySpriteBank(const io::path& name) = 0; + virtual IGUISpriteBank *addEmptySpriteBank(const io::path &name) = 0; //! Returns the root gui element. /** This is the first gui element, the (direct or indirect) parent of all @@ -209,7 +207,7 @@ public: \return Pointer to the root element of the GUI. The returned pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIElement* getRootGUIElement() = 0; + virtual IGUIElement *getRootGUIElement() = 0; //! Adds a button element. /** \param rectangle Rectangle specifying the borders of the button. @@ -220,8 +218,8 @@ public: \return Pointer to the created button. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIButton* addButton(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0, const wchar_t* tooltiptext = 0) = 0; + virtual IGUIButton *addButton(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0, const wchar_t *tooltiptext = 0) = 0; //! Adds a scrollbar. /** \param horizontal Specifies if the scroll bar is drawn horizontal @@ -232,8 +230,8 @@ public: \return Pointer to the created scrollbar. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIScrollBar* addScrollBar(bool horizontal, const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) = 0; + virtual IGUIScrollBar *addScrollBar(bool horizontal, const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) = 0; //! Adds an image element. /** \param image Image to be displayed. @@ -247,8 +245,8 @@ public: \return Pointer to the created image element. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIImage* addImage(video::ITexture* image, core::position2d pos, - bool useAlphaChannel=true, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0) = 0; + virtual IGUIImage *addImage(video::ITexture *image, core::position2d pos, + bool useAlphaChannel = true, IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0) = 0; //! Adds an image element. /** Use IGUIImage::setImage later to set the image to be displayed. @@ -261,8 +259,8 @@ public: \return Pointer to the created image element. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIImage* addImage(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0, bool useAlphaChannel=true) = 0; + virtual IGUIImage *addImage(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0, bool useAlphaChannel = true) = 0; //! Adds a checkbox element. /** \param checked Define the initial state of the check box. @@ -273,8 +271,8 @@ public: \return Pointer to the created check box. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUICheckBox* addCheckBox(bool checked, const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0) = 0; + virtual IGUICheckBox *addCheckBox(bool checked, const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0) = 0; //! Adds a list box element. /** \param rectangle Rectangle specifying the borders of the list box. @@ -284,8 +282,8 @@ public: \return Pointer to the created list box. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIListBox* addListBox(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, bool drawBackground=false) = 0; + virtual IGUIListBox *addListBox(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, bool drawBackground = false) = 0; //! Adds a file open dialog. /** \param title Text to be displayed as the title of the dialog. @@ -301,9 +299,9 @@ public: \return Pointer to the created file open dialog. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIFileOpenDialog* addFileOpenDialog(const wchar_t* title=0, - bool modal=true, IGUIElement* parent=0, s32 id=-1, - bool restoreCWD=false, io::path::char_type* startDir=0) = 0; + virtual IGUIFileOpenDialog *addFileOpenDialog(const wchar_t *title = 0, + bool modal = true, IGUIElement *parent = 0, s32 id = -1, + bool restoreCWD = false, io::path::char_type *startDir = 0) = 0; //! Adds a static text. /** \param text Text to be displayed. Can be altered after creation by SetText(). @@ -317,9 +315,9 @@ public: \return Pointer to the created static text. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIStaticText* addStaticText(const wchar_t* text, const core::rect& rectangle, - bool border=false, bool wordWrap=true, IGUIElement* parent=0, s32 id=-1, - bool fillBackground = false) = 0; + virtual IGUIStaticText *addStaticText(const wchar_t *text, const core::rect &rectangle, + bool border = false, bool wordWrap = true, IGUIElement *parent = 0, s32 id = -1, + bool fillBackground = false) = 0; //! Adds an edit box. /** Supports Unicode input from every keyboard around the world, @@ -336,8 +334,8 @@ public: \return Pointer to the created edit box. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIEditBox* addEditBox(const wchar_t* text, const core::rect& rectangle, - bool border=true, IGUIElement* parent=0, s32 id=-1) = 0; + virtual IGUIEditBox *addEditBox(const wchar_t *text, const core::rect &rectangle, + bool border = true, IGUIElement *parent = 0, s32 id = -1) = 0; //! Adds a tab control to the environment. /** \param rectangle Rectangle specifying the borders of the tab control. @@ -352,9 +350,9 @@ public: \return Pointer to the created tab control element. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUITabControl* addTabControl(const core::rect& rectangle, - IGUIElement* parent=0, bool fillbackground=false, - bool border=true, s32 id=-1) = 0; + virtual IGUITabControl *addTabControl(const core::rect &rectangle, + IGUIElement *parent = 0, bool fillbackground = false, + bool border = true, s32 id = -1) = 0; //! Adds tab to the environment. /** You can use this element to group other elements. This is not used @@ -367,8 +365,8 @@ public: \return Pointer to the created tab. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUITab* addTab(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) = 0; + virtual IGUITab *addTab(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) = 0; //! Adds a combo box to the environment. /** \param rectangle Rectangle specifying the borders of the combo box. @@ -378,8 +376,8 @@ public: \return Pointer to the created combo box. Returns 0 if an error occurred. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IGUIComboBox* addComboBox(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) = 0; + virtual IGUIComboBox *addComboBox(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) = 0; //! Find the next element which would be selected when pressing the tab-key /** If you set the focus for the result you can manually force focus-changes like they @@ -387,7 +385,7 @@ public: \param reverse When true it will search backward (toward lower TabOrder numbers, like shift+tab) \param group When true it will search for the next tab-group (like ctrl+tab) */ - virtual IGUIElement* getNextElement(bool reverse=false, bool group=false) = 0; + virtual IGUIElement *getNextElement(bool reverse = false, bool group = false) = 0; //! Set the way the gui will handle automatic focus changes /** The default is (EFF_SET_ON_LMOUSE_DOWN | EFF_SET_ON_TAB). @@ -409,9 +407,8 @@ public: Note that in general just calling IGUIElement::remove() is enough. Unless you create your own GUI elements removing themselves you won't need it. \param element: Element to remove */ - virtual void addToDeletionQueue(IGUIElement* element) = 0; + virtual void addToDeletionQueue(IGUIElement *element) = 0; }; - } // end namespace gui } // end namespace irr diff --git a/include/IGUIFileOpenDialog.h b/include/IGUIFileOpenDialog.h index ec8e1a6c..04a51ccb 100644 --- a/include/IGUIFileOpenDialog.h +++ b/include/IGUIFileOpenDialog.h @@ -12,35 +12,33 @@ namespace irr namespace gui { - //! Standard file chooser dialog. - /** \warning When the user selects a folder this does change the current working directory +//! Standard file chooser dialog. +/** \warning When the user selects a folder this does change the current working directory - \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_DIRECTORY_SELECTED - \li EGET_FILE_SELECTED - \li EGET_FILE_CHOOSE_DIALOG_CANCELLED - */ - class IGUIFileOpenDialog : public IGUIElement - { - public: +\par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_DIRECTORY_SELECTED +\li EGET_FILE_SELECTED +\li EGET_FILE_CHOOSE_DIALOG_CANCELLED +*/ +class IGUIFileOpenDialog : public IGUIElement +{ +public: + //! constructor + IGUIFileOpenDialog(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_FILE_OPEN_DIALOG, environment, parent, id, rectangle) {} - //! constructor - IGUIFileOpenDialog(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_FILE_OPEN_DIALOG, environment, parent, id, rectangle) {} + //! Returns the filename of the selected file converted to wide characters. Returns NULL if no file was selected. + virtual const wchar_t *getFileName() const = 0; - //! Returns the filename of the selected file converted to wide characters. Returns NULL if no file was selected. - virtual const wchar_t* getFileName() const = 0; + //! Returns the filename of the selected file. Is empty if no file was selected. + virtual const io::path &getFileNameP() const = 0; - //! Returns the filename of the selected file. Is empty if no file was selected. - virtual const io::path& getFileNameP() const = 0; - - //! Returns the directory of the selected file. Empty if no directory was selected. - virtual const io::path& getDirectoryName() const = 0; - - //! Returns the directory of the selected file converted to wide characters. Returns NULL if no directory was selected. - virtual const wchar_t* getDirectoryNameW() const = 0; - }; + //! Returns the directory of the selected file. Empty if no directory was selected. + virtual const io::path &getDirectoryName() const = 0; + //! Returns the directory of the selected file converted to wide characters. Returns NULL if no directory was selected. + virtual const wchar_t *getDirectoryNameW() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIFont.h b/include/IGUIFont.h index 49641ec3..c18354c7 100644 --- a/include/IGUIFont.h +++ b/include/IGUIFont.h @@ -38,7 +38,6 @@ enum EGUI_FONT_TYPE class IGUIFont : public virtual IReferenceCounted { public: - //! Draws some text and clips it to the specified rectangle if wanted. /** \param text: Text to draw \param position: Rectangle specifying position where to draw the text. @@ -47,30 +46,30 @@ public: \param vcenter: Specifies if the text should be centered vertically into the rectangle. \param clip: Optional pointer to a rectangle against which the text will be clipped. If the pointer is null, no clipping will be done. */ - virtual void draw(const core::stringw& text, const core::rect& position, - video::SColor color, bool hcenter=false, bool vcenter=false, - const core::rect* clip=0) = 0; + virtual void draw(const core::stringw &text, const core::rect &position, + video::SColor color, bool hcenter = false, bool vcenter = false, + const core::rect *clip = 0) = 0; //! Calculates the width and height of a given string of text. /** \return Returns width and height of the area covered by the text if it would be drawn. */ - virtual core::dimension2d getDimension(const wchar_t* text) const = 0; + virtual core::dimension2d getDimension(const wchar_t *text) const = 0; //! Calculates the index of the character in the text which is on a specific position. /** \param text: Text string. \param pixel_x: X pixel position of which the index of the character will be returned. \return Returns zero based index of the character in the text, and -1 if no no character is on this position. (=the text is too short). */ - virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const = 0; + virtual s32 getCharacterFromPos(const wchar_t *text, s32 pixel_x) const = 0; //! Returns the type of this font virtual EGUI_FONT_TYPE getType() const { return EGFT_CUSTOM; } //! Sets global kerning width for the font. - virtual void setKerningWidth (s32 kerning) = 0; + virtual void setKerningWidth(s32 kerning) = 0; //! Sets global kerning height for the font. - virtual void setKerningHeight (s32 kerning) = 0; + virtual void setKerningHeight(s32 kerning) = 0; //! Gets kerning values (distance between letters) for the font. If no parameters are provided, /** the global kerning distance is returned. @@ -83,7 +82,7 @@ public: which supports kerning pairs a string such as 'Wo' may have the 'o' tucked neatly under the 'W'. */ - virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const = 0; + virtual s32 getKerningWidth(const wchar_t *thisLetter = 0, const wchar_t *previousLetter = 0) const = 0; //! Returns the distance between letters virtual s32 getKerningHeight() const = 0; @@ -93,7 +92,7 @@ public: most fonts. \param s String of symbols which are not send down to the videodriver */ - virtual void setInvisibleCharacters( const wchar_t *s ) = 0; + virtual void setInvisibleCharacters(const wchar_t *s) = 0; }; } // end namespace gui diff --git a/include/IGUIFontBitmap.h b/include/IGUIFontBitmap.h index 029ca11d..b86dbe2b 100644 --- a/include/IGUIFontBitmap.h +++ b/include/IGUIFontBitmap.h @@ -10,18 +10,17 @@ namespace irr { namespace gui { - class IGUISpriteBank; +class IGUISpriteBank; //! Font interface. class IGUIFontBitmap : public IGUIFont { public: - //! Returns the type of this font EGUI_FONT_TYPE getType() const override { return EGFT_BITMAP; } //! returns the parsed Symbol Information - virtual IGUISpriteBank* getSpriteBank() const = 0; + virtual IGUISpriteBank *getSpriteBank() const = 0; //! returns the sprite number from a given character virtual u32 getSpriteNoFromChar(const wchar_t *c) const = 0; @@ -35,7 +34,7 @@ public: kerning value. For example, EGFT_BITMAP will add the right kerning value of previousLetter to the left side kerning value of thisLetter, then add the global value. */ - s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const override = 0; + s32 getKerningWidth(const wchar_t *thisLetter = 0, const wchar_t *previousLetter = 0) const override = 0; }; } // end namespace gui diff --git a/include/IGUIImage.h b/include/IGUIImage.h index 77aca5c4..33453a3c 100644 --- a/include/IGUIImage.h +++ b/include/IGUIImage.h @@ -10,75 +10,73 @@ namespace irr { namespace video { - class ITexture; +class ITexture; } namespace gui { - //! GUI element displaying an image. - class IGUIImage : public IGUIElement - { - public: +//! GUI element displaying an image. +class IGUIImage : public IGUIElement +{ +public: + //! constructor + IGUIImage(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_IMAGE, environment, parent, id, rectangle) {} - //! constructor - IGUIImage(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_IMAGE, environment, parent, id, rectangle) {} + //! Sets an image texture + virtual void setImage(video::ITexture *image) = 0; - //! Sets an image texture - virtual void setImage(video::ITexture* image) = 0; + //! Gets the image texture + virtual video::ITexture *getImage() const = 0; - //! Gets the image texture - virtual video::ITexture* getImage() const = 0; + //! Sets the color of the image + /** \param color Color with which the image is drawn. If the color + equals Color(255,255,255,255) it is ignored. */ + virtual void setColor(video::SColor color) = 0; - //! Sets the color of the image - /** \param color Color with which the image is drawn. If the color - equals Color(255,255,255,255) it is ignored. */ - virtual void setColor(video::SColor color) = 0; + //! Sets if the image should scale to fit the element + virtual void setScaleImage(bool scale) = 0; - //! Sets if the image should scale to fit the element - virtual void setScaleImage(bool scale) = 0; + //! Sets if the image should use its alpha channel to draw itself + virtual void setUseAlphaChannel(bool use) = 0; - //! Sets if the image should use its alpha channel to draw itself - virtual void setUseAlphaChannel(bool use) = 0; + //! Gets the color of the image + virtual video::SColor getColor() const = 0; - //! Gets the color of the image - virtual video::SColor getColor() const = 0; + //! Returns true if the image is scaled to fit, false if not + virtual bool isImageScaled() const = 0; - //! Returns true if the image is scaled to fit, false if not - virtual bool isImageScaled() const = 0; + //! Returns true if the image is using the alpha channel, false if not + virtual bool isAlphaChannelUsed() const = 0; - //! Returns true if the image is using the alpha channel, false if not - virtual bool isAlphaChannelUsed() const = 0; + //! Sets the source rectangle of the image. By default the full image is used. + /** \param sourceRect coordinates inside the image or an area with size 0 for using the full image (default). */ + virtual void setSourceRect(const core::rect &sourceRect) = 0; - //! Sets the source rectangle of the image. By default the full image is used. - /** \param sourceRect coordinates inside the image or an area with size 0 for using the full image (default). */ - virtual void setSourceRect(const core::rect& sourceRect) = 0; + //! Returns the customized source rectangle of the image to be used. + /** By default an empty rectangle of width and height 0 is returned which means the full image is used. */ + virtual core::rect getSourceRect() const = 0; - //! Returns the customized source rectangle of the image to be used. - /** By default an empty rectangle of width and height 0 is returned which means the full image is used. */ - virtual core::rect getSourceRect() const = 0; + //! Restrict drawing-area. + /** This allows for example to use the image as a progress bar. + Base for area is the image, which means: + - The original clipping area when the texture is scaled or there is no texture. + - The source-rect for an unscaled texture (but still restricted afterward by the clipping area) + Unlike normal clipping this does not affect the gui-children. + \param drawBoundUVs: Coordinates between 0 and 1 where 0 are for left+top and 1 for right+bottom + */ + virtual void setDrawBounds(const core::rect &drawBoundUVs = core::rect(0.f, 0.f, 1.f, 1.f)) = 0; - //! Restrict drawing-area. - /** This allows for example to use the image as a progress bar. - Base for area is the image, which means: - - The original clipping area when the texture is scaled or there is no texture. - - The source-rect for an unscaled texture (but still restricted afterward by the clipping area) - Unlike normal clipping this does not affect the gui-children. - \param drawBoundUVs: Coordinates between 0 and 1 where 0 are for left+top and 1 for right+bottom - */ - virtual void setDrawBounds(const core::rect& drawBoundUVs = core::rect(0.f, 0.f, 1.f, 1.f)) = 0; + //! Get drawing-area restrictions. + virtual core::rect getDrawBounds() const = 0; - //! Get drawing-area restrictions. - virtual core::rect getDrawBounds() const = 0; - - //! Sets whether to draw a background color (EGDC_3D_DARK_SHADOW) when no texture is set - /** By default it's enabled */ - virtual void setDrawBackground(bool draw) = 0; - - //! Checks if a background is drawn when no texture is set - /** \return true if background drawing is enabled, false otherwise */ - virtual bool isDrawBackgroundEnabled() const = 0; - }; + //! Sets whether to draw a background color (EGDC_3D_DARK_SHADOW) when no texture is set + /** By default it's enabled */ + virtual void setDrawBackground(bool draw) = 0; + //! Checks if a background is drawn when no texture is set + /** \return true if background drawing is enabled, false otherwise */ + virtual bool isDrawBackgroundEnabled() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIImageList.h b/include/IGUIImageList.h index fd34296e..6b23c546 100644 --- a/include/IGUIImageList.h +++ b/include/IGUIImageList.h @@ -16,17 +16,16 @@ namespace gui class IGUIImageList : public virtual IReferenceCounted { public: - //! Destructor - virtual ~IGUIImageList() {}; + virtual ~IGUIImageList(){}; //! Draws an image and clips it to the specified rectangle if wanted //! \param index: Index of the image //! \param destPos: Position of the image to draw //! \param clip: Optional pointer to a rectangle against which the text will be clipped. //! If the pointer is null, no clipping will be done. - virtual void draw(s32 index, const core::position2d& destPos, - const core::rect* clip = 0) = 0; + virtual void draw(s32 index, const core::position2d &destPos, + const core::rect *clip = 0) = 0; //! Returns the count of Images in the list. //! \return Returns the count of Images in the list. diff --git a/include/IGUIListBox.h b/include/IGUIListBox.h index fe16f088..6271eb56 100644 --- a/include/IGUIListBox.h +++ b/include/IGUIListBox.h @@ -11,128 +11,126 @@ namespace irr { namespace gui { - class IGUISpriteBank; - class IGUIScrollBar; +class IGUISpriteBank; +class IGUIScrollBar; - //! Enumeration for listbox colors - enum EGUI_LISTBOX_COLOR - { - //! Color of text - EGUI_LBC_TEXT=0, - //! Color of selected text - EGUI_LBC_TEXT_HIGHLIGHT, - //! Color of icon - EGUI_LBC_ICON, - //! Color of selected icon - EGUI_LBC_ICON_HIGHLIGHT, - //! Not used, just counts the number of available colors - EGUI_LBC_COUNT - }; - - - //! Default list box GUI element. - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_LISTBOX_CHANGED - \li EGET_LISTBOX_SELECTED_AGAIN - */ - class IGUIListBox : public IGUIElement - { - public: - //! constructor - IGUIListBox(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_LIST_BOX, environment, parent, id, rectangle) {} - - //! returns amount of list items - virtual u32 getItemCount() const = 0; - - //! returns string of a list item. the may id be a value from 0 to itemCount-1 - virtual const wchar_t* getListItem(u32 id) const = 0; - - //! adds an list item, returns id of item - virtual u32 addItem(const wchar_t* text) = 0; - - //! adds an list item with an icon - /** \param text Text of list entry - \param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon - \return The id of the new created item */ - virtual u32 addItem(const wchar_t* text, s32 icon) = 0; - - //! Removes an item from the list - virtual void removeItem(u32 index) = 0; - - //! get the the id of the item at the given absolute coordinates - /** \return The id of the list item or -1 when no item is at those coordinates*/ - virtual s32 getItemAt(s32 xpos, s32 ypos) const = 0; - - //! Returns the icon of an item - virtual s32 getIcon(u32 index) const = 0; - - //! Sets the sprite bank which should be used to draw list icons. - /** This font is set to the sprite bank of the built-in-font by - default. A sprite can be displayed in front of every list item. - An icon is an index within the icon sprite bank. Several - default icons are available in the skin through getIcon. */ - virtual void setSpriteBank(IGUISpriteBank* bank) = 0; - - //! clears the list, deletes all items in the listbox - virtual void clear() = 0; - - //! returns id of selected item. returns -1 if no item is selected. - virtual s32 getSelected() const = 0; - - //! sets the selected item. Set this to -1 if no item should be selected - virtual void setSelected(s32 index) = 0; - - //! sets the selected item. Set this to 0 if no item should be selected - virtual void setSelected(const wchar_t *item) = 0; - - //! set whether the listbox should scroll to newly selected items - virtual void setAutoScrollEnabled(bool scroll) = 0; - - //! returns true if automatic scrolling is enabled, false if not. - virtual bool isAutoScrollEnabled() const = 0; - - //! set all item colors at given index to color - virtual void setItemOverrideColor(u32 index, video::SColor color) = 0; - - //! set all item colors of specified type at given index to color - virtual void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, video::SColor color) = 0; - - //! clear all item colors at index - virtual void clearItemOverrideColor(u32 index) = 0; - - //! clear item color at index for given colortype - virtual void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) = 0; - - //! has the item at index its color overwritten? - virtual bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0; - - //! return the overwrite color at given item index. - virtual video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0; - - //! return the default color which is used for the given colorType - virtual video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const = 0; - - //! set the item at the given index - virtual void setItem(u32 index, const wchar_t* text, s32 icon) = 0; - - //! Insert the item at the given index - /** \return The index on success or -1 on failure. */ - virtual s32 insertItem(u32 index, const wchar_t* text, s32 icon) = 0; - - //! Swap the items at the given indices - virtual void swapItems(u32 index1, u32 index2) = 0; - - //! set global itemHeight - virtual void setItemHeight( s32 height ) = 0; - - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw) = 0; - - //! Access the vertical scrollbar - virtual IGUIScrollBar* getVerticalScrollBar() const = 0; +//! Enumeration for listbox colors +enum EGUI_LISTBOX_COLOR +{ + //! Color of text + EGUI_LBC_TEXT = 0, + //! Color of selected text + EGUI_LBC_TEXT_HIGHLIGHT, + //! Color of icon + EGUI_LBC_ICON, + //! Color of selected icon + EGUI_LBC_ICON_HIGHLIGHT, + //! Not used, just counts the number of available colors + EGUI_LBC_COUNT }; +//! Default list box GUI element. +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_LISTBOX_CHANGED +\li EGET_LISTBOX_SELECTED_AGAIN +*/ +class IGUIListBox : public IGUIElement +{ +public: + //! constructor + IGUIListBox(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_LIST_BOX, environment, parent, id, rectangle) {} + + //! returns amount of list items + virtual u32 getItemCount() const = 0; + + //! returns string of a list item. the may id be a value from 0 to itemCount-1 + virtual const wchar_t *getListItem(u32 id) const = 0; + + //! adds an list item, returns id of item + virtual u32 addItem(const wchar_t *text) = 0; + + //! adds an list item with an icon + /** \param text Text of list entry + \param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon + \return The id of the new created item */ + virtual u32 addItem(const wchar_t *text, s32 icon) = 0; + + //! Removes an item from the list + virtual void removeItem(u32 index) = 0; + + //! get the the id of the item at the given absolute coordinates + /** \return The id of the list item or -1 when no item is at those coordinates*/ + virtual s32 getItemAt(s32 xpos, s32 ypos) const = 0; + + //! Returns the icon of an item + virtual s32 getIcon(u32 index) const = 0; + + //! Sets the sprite bank which should be used to draw list icons. + /** This font is set to the sprite bank of the built-in-font by + default. A sprite can be displayed in front of every list item. + An icon is an index within the icon sprite bank. Several + default icons are available in the skin through getIcon. */ + virtual void setSpriteBank(IGUISpriteBank *bank) = 0; + + //! clears the list, deletes all items in the listbox + virtual void clear() = 0; + + //! returns id of selected item. returns -1 if no item is selected. + virtual s32 getSelected() const = 0; + + //! sets the selected item. Set this to -1 if no item should be selected + virtual void setSelected(s32 index) = 0; + + //! sets the selected item. Set this to 0 if no item should be selected + virtual void setSelected(const wchar_t *item) = 0; + + //! set whether the listbox should scroll to newly selected items + virtual void setAutoScrollEnabled(bool scroll) = 0; + + //! returns true if automatic scrolling is enabled, false if not. + virtual bool isAutoScrollEnabled() const = 0; + + //! set all item colors at given index to color + virtual void setItemOverrideColor(u32 index, video::SColor color) = 0; + + //! set all item colors of specified type at given index to color + virtual void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, video::SColor color) = 0; + + //! clear all item colors at index + virtual void clearItemOverrideColor(u32 index) = 0; + + //! clear item color at index for given colortype + virtual void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) = 0; + + //! has the item at index its color overwritten? + virtual bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0; + + //! return the overwrite color at given item index. + virtual video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const = 0; + + //! return the default color which is used for the given colorType + virtual video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const = 0; + + //! set the item at the given index + virtual void setItem(u32 index, const wchar_t *text, s32 icon) = 0; + + //! Insert the item at the given index + /** \return The index on success or -1 on failure. */ + virtual s32 insertItem(u32 index, const wchar_t *text, s32 icon) = 0; + + //! Swap the items at the given indices + virtual void swapItems(u32 index1, u32 index2) = 0; + + //! set global itemHeight + virtual void setItemHeight(s32 height) = 0; + + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw) = 0; + + //! Access the vertical scrollbar + virtual IGUIScrollBar *getVerticalScrollBar() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIScrollBar.h b/include/IGUIScrollBar.h index c8855625..c7eb4b1b 100644 --- a/include/IGUIScrollBar.h +++ b/include/IGUIScrollBar.h @@ -11,51 +11,49 @@ namespace irr namespace gui { - //! Default scroll bar GUI element. - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_SCROLL_BAR_CHANGED - */ - class IGUIScrollBar : public IGUIElement - { - public: +//! Default scroll bar GUI element. +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_SCROLL_BAR_CHANGED +*/ +class IGUIScrollBar : public IGUIElement +{ +public: + //! constructor + IGUIScrollBar(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_SCROLL_BAR, environment, parent, id, rectangle) {} - //! constructor - IGUIScrollBar(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_SCROLL_BAR, environment, parent, id, rectangle) {} + //! sets the maximum value of the scrollbar. + virtual void setMax(s32 max) = 0; + //! gets the maximum value of the scrollbar. + virtual s32 getMax() const = 0; - //! sets the maximum value of the scrollbar. - virtual void setMax(s32 max) = 0; - //! gets the maximum value of the scrollbar. - virtual s32 getMax() const = 0; + //! sets the minimum value of the scrollbar. + virtual void setMin(s32 min) = 0; + //! gets the minimum value of the scrollbar. + virtual s32 getMin() const = 0; - //! sets the minimum value of the scrollbar. - virtual void setMin(s32 min) = 0; - //! gets the minimum value of the scrollbar. - virtual s32 getMin() const = 0; + //! gets the small step value + virtual s32 getSmallStep() const = 0; - //! gets the small step value - virtual s32 getSmallStep() const = 0; + //! Sets the small step + /** That is the amount that the value changes by when clicking + on the buttons or using the cursor keys. */ + virtual void setSmallStep(s32 step) = 0; - //! Sets the small step - /** That is the amount that the value changes by when clicking - on the buttons or using the cursor keys. */ - virtual void setSmallStep(s32 step) = 0; + //! gets the large step value + virtual s32 getLargeStep() const = 0; - //! gets the large step value - virtual s32 getLargeStep() const = 0; + //! Sets the large step + /** That is the amount that the value changes by when clicking + in the tray, or using the page up and page down keys. */ + virtual void setLargeStep(s32 step) = 0; - //! Sets the large step - /** That is the amount that the value changes by when clicking - in the tray, or using the page up and page down keys. */ - virtual void setLargeStep(s32 step) = 0; - - //! gets the current position of the scrollbar - virtual s32 getPos() const = 0; - - //! sets the current position of the scrollbar - virtual void setPos(s32 pos) = 0; - }; + //! gets the current position of the scrollbar + virtual s32 getPos() const = 0; + //! sets the current position of the scrollbar + virtual void setPos(s32 pos) = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUISkin.h b/include/IGUISkin.h index 595f4251..b209eef6 100644 --- a/include/IGUISkin.h +++ b/include/IGUISkin.h @@ -13,564 +13,555 @@ namespace irr { namespace gui { - class IGUIFont; - class IGUISpriteBank; - class IGUIElement; +class IGUIFont; +class IGUISpriteBank; +class IGUIElement; - //! Enumeration of available default skins. - /** To set one of the skins, use the following code, for example to set - the Windows classic skin: - \code - gui::IGUISkin* newskin = environment->createSkin(gui::EGST_WINDOWS_CLASSIC); - environment->setSkin(newskin); - newskin->drop(); - \endcode - */ - enum EGUI_SKIN_TYPE - { - //! Default windows look and feel - EGST_WINDOWS_CLASSIC=0, +//! Enumeration of available default skins. +/** To set one of the skins, use the following code, for example to set +the Windows classic skin: +\code +gui::IGUISkin* newskin = environment->createSkin(gui::EGST_WINDOWS_CLASSIC); +environment->setSkin(newskin); +newskin->drop(); +\endcode +*/ +enum EGUI_SKIN_TYPE +{ + //! Default windows look and feel + EGST_WINDOWS_CLASSIC = 0, - //! Like EGST_WINDOWS_CLASSIC, but with metallic shaded windows and buttons - EGST_WINDOWS_METALLIC, + //! Like EGST_WINDOWS_CLASSIC, but with metallic shaded windows and buttons + EGST_WINDOWS_METALLIC, - //! Burning's skin - EGST_BURNING_SKIN, + //! Burning's skin + EGST_BURNING_SKIN, - //! An unknown skin, not serializable at present - EGST_UNKNOWN, + //! An unknown skin, not serializable at present + EGST_UNKNOWN, - //! this value is not used, it only specifies the number of skin types - EGST_COUNT - }; + //! this value is not used, it only specifies the number of skin types + EGST_COUNT +}; - //! Names for gui element types - const c8* const GUISkinTypeNames[EGST_COUNT+1] = - { - "windowsClassic", - "windowsMetallic", - "burning", - "unknown", - 0, - }; +//! Names for gui element types +const c8 *const GUISkinTypeNames[EGST_COUNT + 1] = + { + "windowsClassic", + "windowsMetallic", + "burning", + "unknown", + 0, +}; +//! Enumeration for skin colors +enum EGUI_DEFAULT_COLOR +{ + //! Dark shadow for three-dimensional display elements. + EGDC_3D_DARK_SHADOW = 0, + //! Shadow color for three-dimensional display elements (for edges facing away from the light source). + EGDC_3D_SHADOW, + //! Face color for three-dimensional display elements and for dialog box backgrounds. + EGDC_3D_FACE, + //! Highlight color for three-dimensional display elements (for edges facing the light source.) + EGDC_3D_HIGH_LIGHT, + //! Light color for three-dimensional display elements (for edges facing the light source.) + EGDC_3D_LIGHT, + //! Active window border. + EGDC_ACTIVE_BORDER, + //! Active window title bar text. + EGDC_ACTIVE_CAPTION, + //! Background color of multiple document interface (MDI) applications. + EGDC_APP_WORKSPACE, + //! Text on a button + EGDC_BUTTON_TEXT, + //! Grayed (disabled) text. + EGDC_GRAY_TEXT, + //! Item(s) selected in a control. + EGDC_HIGH_LIGHT, + //! Text of item(s) selected in a control. + EGDC_HIGH_LIGHT_TEXT, + //! Inactive window border. + EGDC_INACTIVE_BORDER, + //! Inactive window caption. + EGDC_INACTIVE_CAPTION, + //! Tool tip text color + EGDC_TOOLTIP, + //! Tool tip background color + EGDC_TOOLTIP_BACKGROUND, + //! Scrollbar gray area + EGDC_SCROLLBAR, + //! Window background + EGDC_WINDOW, + //! Window symbols like on close buttons, scroll bars and check boxes + EGDC_WINDOW_SYMBOL, + //! Icons in a list or tree + EGDC_ICON, + //! Selected icons in a list or tree + EGDC_ICON_HIGH_LIGHT, + //! Grayed (disabled) window symbols like on close buttons, scroll bars and check boxes + EGDC_GRAY_WINDOW_SYMBOL, + //! Window background for editable field (editbox, checkbox-field) + EGDC_EDITABLE, + //! Grayed (disabled) window background for editable field (editbox, checkbox-field) + EGDC_GRAY_EDITABLE, + //! Show focus of window background for editable field (editbox or when checkbox-field is pressed) + EGDC_FOCUSED_EDITABLE, - //! Enumeration for skin colors - enum EGUI_DEFAULT_COLOR - { - //! Dark shadow for three-dimensional display elements. - EGDC_3D_DARK_SHADOW = 0, - //! Shadow color for three-dimensional display elements (for edges facing away from the light source). - EGDC_3D_SHADOW, - //! Face color for three-dimensional display elements and for dialog box backgrounds. - EGDC_3D_FACE, - //! Highlight color for three-dimensional display elements (for edges facing the light source.) - EGDC_3D_HIGH_LIGHT, - //! Light color for three-dimensional display elements (for edges facing the light source.) - EGDC_3D_LIGHT, - //! Active window border. - EGDC_ACTIVE_BORDER, - //! Active window title bar text. - EGDC_ACTIVE_CAPTION, - //! Background color of multiple document interface (MDI) applications. - EGDC_APP_WORKSPACE, - //! Text on a button - EGDC_BUTTON_TEXT, - //! Grayed (disabled) text. - EGDC_GRAY_TEXT, - //! Item(s) selected in a control. - EGDC_HIGH_LIGHT, - //! Text of item(s) selected in a control. - EGDC_HIGH_LIGHT_TEXT, - //! Inactive window border. - EGDC_INACTIVE_BORDER, - //! Inactive window caption. - EGDC_INACTIVE_CAPTION, - //! Tool tip text color - EGDC_TOOLTIP, - //! Tool tip background color - EGDC_TOOLTIP_BACKGROUND, - //! Scrollbar gray area - EGDC_SCROLLBAR, - //! Window background - EGDC_WINDOW, - //! Window symbols like on close buttons, scroll bars and check boxes - EGDC_WINDOW_SYMBOL, - //! Icons in a list or tree - EGDC_ICON, - //! Selected icons in a list or tree - EGDC_ICON_HIGH_LIGHT, - //! Grayed (disabled) window symbols like on close buttons, scroll bars and check boxes - EGDC_GRAY_WINDOW_SYMBOL, - //! Window background for editable field (editbox, checkbox-field) - EGDC_EDITABLE, - //! Grayed (disabled) window background for editable field (editbox, checkbox-field) - EGDC_GRAY_EDITABLE, - //! Show focus of window background for editable field (editbox or when checkbox-field is pressed) - EGDC_FOCUSED_EDITABLE, + //! this value is not used, it only specifies the amount of default colors + //! available. + EGDC_COUNT +}; - //! this value is not used, it only specifies the amount of default colors - //! available. - EGDC_COUNT - }; +//! Names for default skin colors +const c8 *const GUISkinColorNames[EGDC_COUNT + 1] = + { + "3DDarkShadow", + "3DShadow", + "3DFace", + "3DHighlight", + "3DLight", + "ActiveBorder", + "ActiveCaption", + "AppWorkspace", + "ButtonText", + "GrayText", + "Highlight", + "HighlightText", + "InactiveBorder", + "InactiveCaption", + "ToolTip", + "ToolTipBackground", + "ScrollBar", + "Window", + "WindowSymbol", + "Icon", + "IconHighlight", + "GrayWindowSymbol", + "Editable", + "GrayEditable", + "FocusedEditable", + 0, +}; - //! Names for default skin colors - const c8* const GUISkinColorNames[EGDC_COUNT+1] = - { - "3DDarkShadow", - "3DShadow", - "3DFace", - "3DHighlight", - "3DLight", - "ActiveBorder", - "ActiveCaption", - "AppWorkspace", - "ButtonText", - "GrayText", - "Highlight", - "HighlightText", - "InactiveBorder", - "InactiveCaption", - "ToolTip", - "ToolTipBackground", - "ScrollBar", - "Window", - "WindowSymbol", - "Icon", - "IconHighlight", - "GrayWindowSymbol", - "Editable", - "GrayEditable", - "FocusedEditable", - 0, - }; +//! Enumeration for default sizes. +enum EGUI_DEFAULT_SIZE +{ + //! default with / height of scrollbar. Also width of drop-down button in comboboxes. + EGDS_SCROLLBAR_SIZE = 0, + //! height of menu + EGDS_MENU_HEIGHT, + //! width and height of a window titlebar button (like minimize/maximize/close buttons). The titlebar height is also calculated from that. + EGDS_WINDOW_BUTTON_WIDTH, + //! width of a checkbox check + EGDS_CHECK_BOX_WIDTH, + //! \deprecated This may be removed by Irrlicht 1.9 + EGDS_MESSAGE_BOX_WIDTH, + //! \deprecated This may be removed by Irrlicht 1.9 + EGDS_MESSAGE_BOX_HEIGHT, + //! width of a default button + EGDS_BUTTON_WIDTH, + //! height of a default button (OK and cancel buttons) + EGDS_BUTTON_HEIGHT, + //! distance for text from background + EGDS_TEXT_DISTANCE_X, + //! distance for text from background + EGDS_TEXT_DISTANCE_Y, + //! distance for text in the title bar, from the left of the window rect + EGDS_TITLEBARTEXT_DISTANCE_X, + //! distance for text in the title bar, from the top of the window rect + EGDS_TITLEBARTEXT_DISTANCE_Y, + //! free space in a messagebox between borders and contents on all sides + EGDS_MESSAGE_BOX_GAP_SPACE, + //! minimal space to reserve for messagebox text-width + EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH, + //! maximal space to reserve for messagebox text-width + EGDS_MESSAGE_BOX_MAX_TEXT_WIDTH, + //! minimal space to reserve for messagebox text-height + EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT, + //! maximal space to reserve for messagebox text-height + EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT, + //! pixels to move an unscaled button image to the right when a button is pressed and the unpressed image looks identical + EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X, + //! pixels to move an unscaled button image down when a button is pressed and the unpressed image looks identical + EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y, + //! pixels to move the button text to the right when a button is pressed + EGDS_BUTTON_PRESSED_TEXT_OFFSET_X, + //! pixels to move the button text down when a button is pressed + EGDS_BUTTON_PRESSED_TEXT_OFFSET_Y, + //! pixels to move an unscaled button sprite to the right when a button is pressed + EGDS_BUTTON_PRESSED_SPRITE_OFFSET_X, + //! pixels to move an unscaled button sprite down when a button is pressed + EGDS_BUTTON_PRESSED_SPRITE_OFFSET_Y, - //! Enumeration for default sizes. - enum EGUI_DEFAULT_SIZE - { - //! default with / height of scrollbar. Also width of drop-down button in comboboxes. - EGDS_SCROLLBAR_SIZE = 0, - //! height of menu - EGDS_MENU_HEIGHT, - //! width and height of a window titlebar button (like minimize/maximize/close buttons). The titlebar height is also calculated from that. - EGDS_WINDOW_BUTTON_WIDTH, - //! width of a checkbox check - EGDS_CHECK_BOX_WIDTH, - //! \deprecated This may be removed by Irrlicht 1.9 - EGDS_MESSAGE_BOX_WIDTH, - //! \deprecated This may be removed by Irrlicht 1.9 - EGDS_MESSAGE_BOX_HEIGHT, - //! width of a default button - EGDS_BUTTON_WIDTH, - //! height of a default button (OK and cancel buttons) - EGDS_BUTTON_HEIGHT, - //! distance for text from background - EGDS_TEXT_DISTANCE_X, - //! distance for text from background - EGDS_TEXT_DISTANCE_Y, - //! distance for text in the title bar, from the left of the window rect - EGDS_TITLEBARTEXT_DISTANCE_X, - //! distance for text in the title bar, from the top of the window rect - EGDS_TITLEBARTEXT_DISTANCE_Y, - //! free space in a messagebox between borders and contents on all sides - EGDS_MESSAGE_BOX_GAP_SPACE, - //! minimal space to reserve for messagebox text-width - EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH, - //! maximal space to reserve for messagebox text-width - EGDS_MESSAGE_BOX_MAX_TEXT_WIDTH, - //! minimal space to reserve for messagebox text-height - EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT, - //! maximal space to reserve for messagebox text-height - EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT, - //! pixels to move an unscaled button image to the right when a button is pressed and the unpressed image looks identical - EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X, - //! pixels to move an unscaled button image down when a button is pressed and the unpressed image looks identical - EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y, - //! pixels to move the button text to the right when a button is pressed - EGDS_BUTTON_PRESSED_TEXT_OFFSET_X, - //! pixels to move the button text down when a button is pressed - EGDS_BUTTON_PRESSED_TEXT_OFFSET_Y, - //! pixels to move an unscaled button sprite to the right when a button is pressed - EGDS_BUTTON_PRESSED_SPRITE_OFFSET_X, - //! pixels to move an unscaled button sprite down when a button is pressed - EGDS_BUTTON_PRESSED_SPRITE_OFFSET_Y, + //! this value is not used, it only specifies the amount of default sizes + //! available. + EGDS_COUNT +}; - //! this value is not used, it only specifies the amount of default sizes - //! available. - EGDS_COUNT - }; +//! Names for default skin sizes +const c8 *const GUISkinSizeNames[EGDS_COUNT + 1] = + { + "ScrollBarSize", + "MenuHeight", + "WindowButtonWidth", + "CheckBoxWidth", + "MessageBoxWidth", + "MessageBoxHeight", + "ButtonWidth", + "ButtonHeight", + "TextDistanceX", + "TextDistanceY", + "TitleBarTextX", + "TitleBarTextY", + "MessageBoxGapSpace", + "MessageBoxMinTextWidth", + "MessageBoxMaxTextWidth", + "MessageBoxMinTextHeight", + "MessageBoxMaxTextHeight", + "ButtonPressedImageOffsetX", + "ButtonPressedImageOffsetY", + "ButtonPressedTextOffsetX", + "ButtonPressedTextOffsetY", + "ButtonPressedSpriteOffsetX", + "ButtonPressedSpriteOffsetY", + 0}; +enum EGUI_DEFAULT_TEXT +{ + //! Text for the OK button on a message box + EGDT_MSG_BOX_OK = 0, + //! Text for the Cancel button on a message box + EGDT_MSG_BOX_CANCEL, + //! Text for the Yes button on a message box + EGDT_MSG_BOX_YES, + //! Text for the No button on a message box + EGDT_MSG_BOX_NO, + //! Tooltip text for window close button + EGDT_WINDOW_CLOSE, + //! Tooltip text for window maximize button + EGDT_WINDOW_MAXIMIZE, + //! Tooltip text for window minimize button + EGDT_WINDOW_MINIMIZE, + //! Tooltip text for window restore button + EGDT_WINDOW_RESTORE, - //! Names for default skin sizes - const c8* const GUISkinSizeNames[EGDS_COUNT+1] = - { - "ScrollBarSize", - "MenuHeight", - "WindowButtonWidth", - "CheckBoxWidth", - "MessageBoxWidth", - "MessageBoxHeight", - "ButtonWidth", - "ButtonHeight", - "TextDistanceX", - "TextDistanceY", - "TitleBarTextX", - "TitleBarTextY", - "MessageBoxGapSpace", - "MessageBoxMinTextWidth", - "MessageBoxMaxTextWidth", - "MessageBoxMinTextHeight", - "MessageBoxMaxTextHeight", - "ButtonPressedImageOffsetX", - "ButtonPressedImageOffsetY", - "ButtonPressedTextOffsetX", - "ButtonPressedTextOffsetY", - "ButtonPressedSpriteOffsetX", - "ButtonPressedSpriteOffsetY", - 0 - }; + //! this value is not used, it only specifies the number of default texts + EGDT_COUNT +}; +//! Names for default skin sizes +const c8 *const GUISkinTextNames[EGDT_COUNT + 1] = + { + "MessageBoxOkay", + "MessageBoxCancel", + "MessageBoxYes", + "MessageBoxNo", + "WindowButtonClose", + "WindowButtonMaximize", + "WindowButtonMinimize", + "WindowButtonRestore", + 0}; - enum EGUI_DEFAULT_TEXT - { - //! Text for the OK button on a message box - EGDT_MSG_BOX_OK = 0, - //! Text for the Cancel button on a message box - EGDT_MSG_BOX_CANCEL, - //! Text for the Yes button on a message box - EGDT_MSG_BOX_YES, - //! Text for the No button on a message box - EGDT_MSG_BOX_NO, - //! Tooltip text for window close button - EGDT_WINDOW_CLOSE, - //! Tooltip text for window maximize button - EGDT_WINDOW_MAXIMIZE, - //! Tooltip text for window minimize button - EGDT_WINDOW_MINIMIZE, - //! Tooltip text for window restore button - EGDT_WINDOW_RESTORE, +//! Customizable symbols for GUI +enum EGUI_DEFAULT_ICON +{ + //! maximize window button + EGDI_WINDOW_MAXIMIZE = 0, + //! restore window button + EGDI_WINDOW_RESTORE, + //! close window button + EGDI_WINDOW_CLOSE, + //! minimize window button + EGDI_WINDOW_MINIMIZE, + //! resize icon for bottom right corner of a window + EGDI_WINDOW_RESIZE, + //! scroll bar up button + EGDI_CURSOR_UP, + //! scroll bar down button + EGDI_CURSOR_DOWN, + //! scroll bar left button + EGDI_CURSOR_LEFT, + //! scroll bar right button + EGDI_CURSOR_RIGHT, + //! icon for menu children + EGDI_MENU_MORE, + //! tick for checkbox + EGDI_CHECK_BOX_CHECKED, + //! down arrow for dropdown menus + EGDI_DROP_DOWN, + //! smaller up arrow + EGDI_SMALL_CURSOR_UP, + //! smaller down arrow + EGDI_SMALL_CURSOR_DOWN, + //! selection dot in a radio button + EGDI_RADIO_BUTTON_CHECKED, + //! << icon indicating there is more content to the left + EGDI_MORE_LEFT, + //! >> icon indicating that there is more content to the right + EGDI_MORE_RIGHT, + //! icon indicating that there is more content above + EGDI_MORE_UP, + //! icon indicating that there is more content below + EGDI_MORE_DOWN, + //! plus icon for trees + EGDI_EXPAND, - //! this value is not used, it only specifies the number of default texts - EGDT_COUNT - }; + //! minus icon for trees + EGDI_COLLAPSE, + //! file icon for file selection + EGDI_FILE, + //! folder icon for file selection + EGDI_DIRECTORY, - //! Names for default skin sizes - const c8* const GUISkinTextNames[EGDT_COUNT+1] = - { - "MessageBoxOkay", - "MessageBoxCancel", - "MessageBoxYes", - "MessageBoxNo", - "WindowButtonClose", - "WindowButtonMaximize", - "WindowButtonMinimize", - "WindowButtonRestore", - 0 - }; + //! value not used, it only specifies the number of icons + EGDI_COUNT +}; - //! Customizable symbols for GUI - enum EGUI_DEFAULT_ICON - { - //! maximize window button - EGDI_WINDOW_MAXIMIZE = 0, - //! restore window button - EGDI_WINDOW_RESTORE, - //! close window button - EGDI_WINDOW_CLOSE, - //! minimize window button - EGDI_WINDOW_MINIMIZE, - //! resize icon for bottom right corner of a window - EGDI_WINDOW_RESIZE, - //! scroll bar up button - EGDI_CURSOR_UP, - //! scroll bar down button - EGDI_CURSOR_DOWN, - //! scroll bar left button - EGDI_CURSOR_LEFT, - //! scroll bar right button - EGDI_CURSOR_RIGHT, - //! icon for menu children - EGDI_MENU_MORE, - //! tick for checkbox - EGDI_CHECK_BOX_CHECKED, - //! down arrow for dropdown menus - EGDI_DROP_DOWN, - //! smaller up arrow - EGDI_SMALL_CURSOR_UP, - //! smaller down arrow - EGDI_SMALL_CURSOR_DOWN, - //! selection dot in a radio button - EGDI_RADIO_BUTTON_CHECKED, - //! << icon indicating there is more content to the left - EGDI_MORE_LEFT, - //! >> icon indicating that there is more content to the right - EGDI_MORE_RIGHT, - //! icon indicating that there is more content above - EGDI_MORE_UP, - //! icon indicating that there is more content below - EGDI_MORE_DOWN, - //! plus icon for trees - EGDI_EXPAND, +const c8 *const GUISkinIconNames[EGDI_COUNT + 1] = + { + "windowMaximize", + "windowRestore", + "windowClose", + "windowMinimize", + "windowResize", + "cursorUp", + "cursorDown", + "cursorLeft", + "cursorRight", + "menuMore", + "checkBoxChecked", + "dropDown", + "smallCursorUp", + "smallCursorDown", + "radioButtonChecked", + "moreLeft", + "moreRight", + "moreUp", + "moreDown", + "expand", + "collapse", + "file", + "directory", + 0}; - //! minus icon for trees - EGDI_COLLAPSE, - //! file icon for file selection - EGDI_FILE, - //! folder icon for file selection - EGDI_DIRECTORY, +// Customizable fonts +enum EGUI_DEFAULT_FONT +{ + //! For static text, edit boxes, lists and most other places + EGDF_DEFAULT = 0, + //! Font for buttons + EGDF_BUTTON, + //! Font for window title bars + EGDF_WINDOW, + //! Font for menu items + EGDF_MENU, + //! Font for tooltips + EGDF_TOOLTIP, + //! this value is not used, it only specifies the amount of default fonts + //! available. + EGDF_COUNT +}; - //! value not used, it only specifies the number of icons - EGDI_COUNT - }; +const c8 *const GUISkinFontNames[EGDF_COUNT + 1] = + { + "defaultFont", + "buttonFont", + "windowFont", + "menuFont", + "tooltipFont", + 0}; - const c8* const GUISkinIconNames[EGDI_COUNT+1] = - { - "windowMaximize", - "windowRestore", - "windowClose", - "windowMinimize", - "windowResize", - "cursorUp", - "cursorDown", - "cursorLeft", - "cursorRight", - "menuMore", - "checkBoxChecked", - "dropDown", - "smallCursorUp", - "smallCursorDown", - "radioButtonChecked", - "moreLeft", - "moreRight", - "moreUp", - "moreDown", - "expand", - "collapse", - "file", - "directory", - 0 - }; +//! A skin modifies the look of the GUI elements. +class IGUISkin : virtual public IReferenceCounted +{ +public: + //! returns default color + virtual video::SColor getColor(EGUI_DEFAULT_COLOR color) const = 0; - // Customizable fonts - enum EGUI_DEFAULT_FONT - { - //! For static text, edit boxes, lists and most other places - EGDF_DEFAULT=0, - //! Font for buttons - EGDF_BUTTON, - //! Font for window title bars - EGDF_WINDOW, - //! Font for menu items - EGDF_MENU, - //! Font for tooltips - EGDF_TOOLTIP, - //! this value is not used, it only specifies the amount of default fonts - //! available. - EGDF_COUNT - }; + //! sets a default color + virtual void setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) = 0; - const c8* const GUISkinFontNames[EGDF_COUNT+1] = - { - "defaultFont", - "buttonFont", - "windowFont", - "menuFont", - "tooltipFont", - 0 - }; + //! returns size for the given size type + virtual s32 getSize(EGUI_DEFAULT_SIZE size) const = 0; - //! A skin modifies the look of the GUI elements. - class IGUISkin : virtual public IReferenceCounted - { - public: + //! Returns a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + virtual const wchar_t *getDefaultText(EGUI_DEFAULT_TEXT text) const = 0; - //! returns default color - virtual video::SColor getColor(EGUI_DEFAULT_COLOR color) const = 0; + //! Sets a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + virtual void setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t *newText) = 0; - //! sets a default color - virtual void setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) = 0; + //! sets a default size + virtual void setSize(EGUI_DEFAULT_SIZE which, s32 size) = 0; - //! returns size for the given size type - virtual s32 getSize(EGUI_DEFAULT_SIZE size) const = 0; + //! returns the default font + virtual IGUIFont *getFont(EGUI_DEFAULT_FONT which = EGDF_DEFAULT) const = 0; - //! Returns a default text. - /** For example for Message box button captions: - "OK", "Cancel", "Yes", "No" and so on. */ - virtual const wchar_t* getDefaultText(EGUI_DEFAULT_TEXT text) const = 0; + //! sets a default font + virtual void setFont(IGUIFont *font, EGUI_DEFAULT_FONT which = EGDF_DEFAULT) = 0; - //! Sets a default text. - /** For example for Message box button captions: - "OK", "Cancel", "Yes", "No" and so on. */ - virtual void setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText) = 0; + //! returns the sprite bank + virtual IGUISpriteBank *getSpriteBank() const = 0; - //! sets a default size - virtual void setSize(EGUI_DEFAULT_SIZE which, s32 size) = 0; + //! sets the sprite bank + virtual void setSpriteBank(IGUISpriteBank *bank) = 0; - //! returns the default font - virtual IGUIFont* getFont(EGUI_DEFAULT_FONT which=EGDF_DEFAULT) const = 0; + //! Returns a default icon + /** Returns the sprite index within the sprite bank */ + virtual u32 getIcon(EGUI_DEFAULT_ICON icon) const = 0; - //! sets a default font - virtual void setFont(IGUIFont* font, EGUI_DEFAULT_FONT which=EGDF_DEFAULT) = 0; + //! Sets a default icon + /** Sets the sprite index used for drawing icons like arrows, + close buttons and ticks in checkboxes + \param icon: Enum specifying which icon to change + \param index: The sprite index used to draw this icon */ + virtual void setIcon(EGUI_DEFAULT_ICON icon, u32 index) = 0; - //! returns the sprite bank - virtual IGUISpriteBank* getSpriteBank() const = 0; + //! draws a standard 3d button pane + /** Used for drawing for example buttons in normal state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DButtonPaneStandard(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) = 0; - //! sets the sprite bank - virtual void setSpriteBank(IGUISpriteBank* bank) = 0; + //! draws a pressed 3d button pane + /** Used for drawing for example buttons in pressed state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DButtonPanePressed(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) = 0; - //! Returns a default icon - /** Returns the sprite index within the sprite bank */ - virtual u32 getIcon(EGUI_DEFAULT_ICON icon) const = 0; - - //! Sets a default icon - /** Sets the sprite index used for drawing icons like arrows, - close buttons and ticks in checkboxes - \param icon: Enum specifying which icon to change - \param index: The sprite index used to draw this icon */ - virtual void setIcon(EGUI_DEFAULT_ICON icon, u32 index) = 0; - - //! draws a standard 3d button pane - /** Used for drawing for example buttons in normal state. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DButtonPaneStandard(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) = 0; - - //! draws a pressed 3d button pane - /** Used for drawing for example buttons in pressed state. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DButtonPanePressed(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) = 0; - - //! draws a sunken 3d pane - /** Used for drawing the background of edit, combo or check boxes. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param bgcolor: Background color. - \param flat: Specifies if the sunken pane should be flat or displayed as sunken - deep into the ground. - \param fillBackGround: Specifies if the background should be filled with the background - color or not be drawn at all. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DSunkenPane(IGUIElement* element, + //! draws a sunken 3d pane + /** Used for drawing the background of edit, combo or check boxes. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param bgcolor: Background color. + \param flat: Specifies if the sunken pane should be flat or displayed as sunken + deep into the ground. + \param fillBackGround: Specifies if the background should be filled with the background + color or not be drawn at all. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DSunkenPane(IGUIElement *element, video::SColor bgcolor, bool flat, bool fillBackGround, - const core::rect& rect, - const core::rect* clip=0) = 0; + const core::rect &rect, + const core::rect *clip = 0) = 0; - //! draws a window background - /** Used for drawing the background of dialogs and windows. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param titleBarColor: Title color. - \param drawTitleBar: True to enable title drawing. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param checkClientArea: When set to non-null the function will not draw anything, - but will instead return the clientArea which can be used for drawing by the calling window. - That is the area without borders and without titlebar. - \return Returns rect where it would be good to draw title bar text. This will - work even when checkClientArea is set to a non-null value.*/ - virtual core::rect draw3DWindowBackground(IGUIElement* element, + //! draws a window background + /** Used for drawing the background of dialogs and windows. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param titleBarColor: Title color. + \param drawTitleBar: True to enable title drawing. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param checkClientArea: When set to non-null the function will not draw anything, + but will instead return the clientArea which can be used for drawing by the calling window. + That is the area without borders and without titlebar. + \return Returns rect where it would be good to draw title bar text. This will + work even when checkClientArea is set to a non-null value.*/ + virtual core::rect draw3DWindowBackground(IGUIElement *element, bool drawTitleBar, video::SColor titleBarColor, - const core::rect& rect, - const core::rect* clip=0, - core::rect* checkClientArea=0) = 0; + const core::rect &rect, + const core::rect *clip = 0, + core::rect *checkClientArea = 0) = 0; - //! draws a standard 3d menu pane - /** Used for drawing for menus and context menus. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DMenuPane(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) = 0; + //! draws a standard 3d menu pane + /** Used for drawing for menus and context menus. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DMenuPane(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) = 0; - //! draws a standard 3d tool bar - /** Used for drawing for toolbars and menus. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DToolBar(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) = 0; + //! draws a standard 3d tool bar + /** Used for drawing for toolbars and menus. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DToolBar(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) = 0; - //! draws a tab button - /** Used for drawing for tab buttons on top of tabs. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param active: Specifies if the tab is currently active. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param alignment Alignment of GUI element. */ - virtual void draw3DTabButton(IGUIElement* element, bool active, - const core::rect& rect, const core::rect* clip=0, gui::EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT) = 0; + //! draws a tab button + /** Used for drawing for tab buttons on top of tabs. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param active: Specifies if the tab is currently active. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param alignment Alignment of GUI element. */ + virtual void draw3DTabButton(IGUIElement *element, bool active, + const core::rect &rect, const core::rect *clip = 0, gui::EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) = 0; - //! draws a tab control body - /** \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by IGUISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param border: Specifies if the border should be drawn. - \param background: Specifies if the background should be drawn. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param tabHeight Height of tab. - \param alignment Alignment of GUI element. */ - virtual void draw3DTabBody(IGUIElement* element, bool border, bool background, - const core::rect& rect, const core::rect* clip=0, s32 tabHeight=-1, gui::EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT ) = 0; + //! draws a tab control body + /** \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by IGUISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param border: Specifies if the border should be drawn. + \param background: Specifies if the background should be drawn. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param tabHeight Height of tab. + \param alignment Alignment of GUI element. */ + virtual void draw3DTabBody(IGUIElement *element, bool border, bool background, + const core::rect &rect, const core::rect *clip = 0, s32 tabHeight = -1, gui::EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) = 0; - //! draws an icon, usually from the skin's sprite bank - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param icon: Specifies the icon to be drawn. - \param position: The position to draw the icon - \param starttime: The time at the start of the animation - \param currenttime: The present time, used to calculate the frame number - \param loop: Whether the animation should loop or not - \param clip: Clip area. */ - virtual void drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, - const core::position2di position, u32 starttime=0, u32 currenttime=0, - bool loop=false, const core::rect* clip=0) = 0; + //! draws an icon, usually from the skin's sprite bank + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param icon: Specifies the icon to be drawn. + \param position: The position to draw the icon + \param starttime: The time at the start of the animation + \param currenttime: The present time, used to calculate the frame number + \param loop: Whether the animation should loop or not + \param clip: Clip area. */ + virtual void drawIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, + const core::position2di position, u32 starttime = 0, u32 currenttime = 0, + bool loop = false, const core::rect *clip = 0) = 0; - //! draws a 2d rectangle. - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param color: Color of the rectangle to draw. The alpha component specifies how - transparent the rectangle will be. - \param pos: Position of the rectangle. - \param clip: Pointer to rectangle against which the rectangle will be clipped. - If the pointer is null, no clipping will be performed. */ - virtual void draw2DRectangle(IGUIElement* element, const video::SColor &color, - const core::rect& pos, const core::rect* clip = 0) = 0; - - //! get the type of this skin - virtual EGUI_SKIN_TYPE getType() const { return EGST_UNKNOWN; } - }; + //! draws a 2d rectangle. + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param color: Color of the rectangle to draw. The alpha component specifies how + transparent the rectangle will be. + \param pos: Position of the rectangle. + \param clip: Pointer to rectangle against which the rectangle will be clipped. + If the pointer is null, no clipping will be performed. */ + virtual void draw2DRectangle(IGUIElement *element, const video::SColor &color, + const core::rect &pos, const core::rect *clip = 0) = 0; + //! get the type of this skin + virtual EGUI_SKIN_TYPE getType() const { return EGST_UNKNOWN; } +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUISpriteBank.h b/include/IGUISpriteBank.h index 0242e1b1..70d8fd1b 100644 --- a/include/IGUISpriteBank.h +++ b/include/IGUISpriteBank.h @@ -14,7 +14,7 @@ namespace irr namespace video { - class ITexture; +class ITexture; } // end namespace video namespace gui @@ -24,12 +24,13 @@ namespace gui // Note for implementer: Can't fix variable names to uppercase as this is a public interface used since a while struct SGUISpriteFrame { - SGUISpriteFrame() : textureNumber(0), rectNumber(0) + SGUISpriteFrame() : + textureNumber(0), rectNumber(0) { } - SGUISpriteFrame(u32 textureIndex, u32 positionIndex) - : textureNumber(textureIndex), rectNumber(positionIndex) + SGUISpriteFrame(u32 textureIndex, u32 positionIndex) : + textureNumber(textureIndex), rectNumber(positionIndex) { } @@ -44,8 +45,10 @@ struct SGUISpriteFrame // Note for implementer: Can't fix variable names to uppercase as this is a public interface used since a while struct SGUISprite { - SGUISprite() : frameTime(0) {} - SGUISprite(const SGUISpriteFrame& firstFrame) : frameTime(0) + SGUISprite() : + frameTime(0) {} + SGUISprite(const SGUISpriteFrame &firstFrame) : + frameTime(0) { Frames.push_back(firstFrame); } @@ -54,37 +57,35 @@ struct SGUISprite u32 frameTime; }; - //! Sprite bank interface. /** See http://http://irrlicht.sourceforge.net/forum//viewtopic.php?f=9&t=25742 -* for more information how to use the spritebank. -*/ + * for more information how to use the spritebank. + */ class IGUISpriteBank : public virtual IReferenceCounted { public: - //! Returns the list of rectangles held by the sprite bank - virtual core::array< core::rect >& getPositions() = 0; + virtual core::array> &getPositions() = 0; //! Returns the array of animated sprites within the sprite bank - virtual core::array< SGUISprite >& getSprites() = 0; + virtual core::array &getSprites() = 0; //! Returns the number of textures held by the sprite bank virtual u32 getTextureCount() const = 0; //! Gets the texture with the specified index - virtual video::ITexture* getTexture(u32 index) const = 0; + virtual video::ITexture *getTexture(u32 index) const = 0; //! Adds a texture to the sprite bank - virtual void addTexture(video::ITexture* texture) = 0; + virtual void addTexture(video::ITexture *texture) = 0; //! Changes one of the textures in the sprite bank - virtual void setTexture(u32 index, video::ITexture* texture) = 0; + virtual void setTexture(u32 index, video::ITexture *texture) = 0; //! Add the texture and use it for a single non-animated sprite. /** The texture and the corresponding rectangle and sprite will all be added to the end of each array. \returns The index of the sprite or -1 on failure */ - virtual s32 addTextureAsSprite(video::ITexture* texture) = 0; + virtual s32 addTextureAsSprite(video::ITexture *texture) = 0; //! Clears sprites, rectangles and textures virtual void clear() = 0; @@ -102,11 +103,11 @@ public: \param loop When true animations are looped \param center When true pivot is set to the sprite-center. So it affects pos. */ - virtual void draw2DSprite(u32 index, const core::position2di& pos, - const core::rect* clip=0, - const video::SColor& color= video::SColor(255,255,255,255), - u32 starttime=0, u32 currenttime=0, - bool loop=true, bool center=false) = 0; + virtual void draw2DSprite(u32 index, const core::position2di &pos, + const core::rect *clip = 0, + const video::SColor &color = video::SColor(255, 255, 255, 255), + u32 starttime = 0, u32 currenttime = 0, + bool loop = true, bool center = false) = 0; //! Draws a sprite in 2d with destination rectangle and colors /** @@ -119,20 +120,19 @@ public: (same as currenttime-starttime in other draw2DSprite function) \param loop When true animations are looped */ - virtual void draw2DSprite(u32 index, const core::rect& destRect, - const core::rect* clip=0, - const video::SColor * const colors=0, + virtual void draw2DSprite(u32 index, const core::rect &destRect, + const core::rect *clip = 0, + const video::SColor *const colors = 0, u32 timeTicks = 0, - bool loop=true) = 0; + bool loop = true) = 0; //! Draws a sprite batch in 2d using an array of positions and a color - virtual void draw2DSpriteBatch(const core::array& indices, const core::array& pos, - const core::rect* clip=0, - const video::SColor& color= video::SColor(255,255,255,255), - u32 starttime=0, u32 currenttime=0, - bool loop=true, bool center=false) = 0; + virtual void draw2DSpriteBatch(const core::array &indices, const core::array &pos, + const core::rect *clip = 0, + const video::SColor &color = video::SColor(255, 255, 255, 255), + u32 starttime = 0, u32 currenttime = 0, + bool loop = true, bool center = false) = 0; }; - } // end namespace gui } // end namespace irr diff --git a/include/IGUIStaticText.h b/include/IGUIStaticText.h index be72171c..02af9b57 100644 --- a/include/IGUIStaticText.h +++ b/include/IGUIStaticText.h @@ -11,125 +11,123 @@ namespace irr { namespace gui { - class IGUIFont; +class IGUIFont; - //! Multi or single line text label. - class IGUIStaticText : public IGUIElement - { - public: +//! Multi or single line text label. +class IGUIStaticText : public IGUIElement +{ +public: + //! constructor + IGUIStaticText(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_STATIC_TEXT, environment, parent, id, rectangle) {} - //! constructor - IGUIStaticText(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_STATIC_TEXT, environment, parent, id, rectangle) {} + //! Sets another skin independent font. + /** If this is set to zero, the button uses the font of the skin. + \param font: New font to set. */ + virtual void setOverrideFont(IGUIFont *font = 0) = 0; - //! Sets another skin independent font. - /** If this is set to zero, the button uses the font of the skin. - \param font: New font to set. */ - virtual void setOverrideFont(IGUIFont* font=0) = 0; + //! Gets the override font (if any) + /** \return The override font (may be 0) */ + virtual IGUIFont *getOverrideFont(void) const = 0; - //! Gets the override font (if any) - /** \return The override font (may be 0) */ - virtual IGUIFont* getOverrideFont(void) const = 0; + //! Get the font which is used right now for drawing + /** Currently this is the override font when one is set and the + font of the active skin otherwise */ + virtual IGUIFont *getActiveFont() const = 0; - //! Get the font which is used right now for drawing - /** Currently this is the override font when one is set and the - font of the active skin otherwise */ - virtual IGUIFont* getActiveFont() const = 0; + //! Sets another color for the text. + /** If set, the static text does not use the EGDC_BUTTON_TEXT color defined + in the skin, but the set color instead. You don't need to call + IGUIStaticText::enableOverrrideColor(true) after this, this is done + by this function. + If you set a color, and you want the text displayed with the color + of the skin again, call IGUIStaticText::enableOverrideColor(false); + \param color: New color of the text. */ + virtual void setOverrideColor(video::SColor color) = 0; - //! Sets another color for the text. - /** If set, the static text does not use the EGDC_BUTTON_TEXT color defined - in the skin, but the set color instead. You don't need to call - IGUIStaticText::enableOverrrideColor(true) after this, this is done - by this function. - If you set a color, and you want the text displayed with the color - of the skin again, call IGUIStaticText::enableOverrideColor(false); - \param color: New color of the text. */ - virtual void setOverrideColor(video::SColor color) = 0; + //! Gets the override color + /** \return: The override color */ + virtual video::SColor getOverrideColor(void) const = 0; - //! Gets the override color - /** \return: The override color */ - virtual video::SColor getOverrideColor(void) const = 0; + //! Gets the currently used text color + /** Either a skin-color for the current state or the override color */ + virtual video::SColor getActiveColor() const = 0; - //! Gets the currently used text color - /** Either a skin-color for the current state or the override color */ - virtual video::SColor getActiveColor() const = 0; + //! Sets if the static text should use the override color or the color in the gui skin. + /** \param enable: If set to true, the override color, which can be set + with IGUIStaticText::setOverrideColor is used, otherwise the + EGDC_BUTTON_TEXT color of the skin. */ + virtual void enableOverrideColor(bool enable) = 0; - //! Sets if the static text should use the override color or the color in the gui skin. - /** \param enable: If set to true, the override color, which can be set - with IGUIStaticText::setOverrideColor is used, otherwise the - EGDC_BUTTON_TEXT color of the skin. */ - virtual void enableOverrideColor(bool enable) = 0; + //! Checks if an override color is enabled + /** \return true if the override color is enabled, false otherwise */ + virtual bool isOverrideColorEnabled(void) const = 0; - //! Checks if an override color is enabled - /** \return true if the override color is enabled, false otherwise */ - virtual bool isOverrideColorEnabled(void) const = 0; + //! Sets another color for the background. + virtual void setBackgroundColor(video::SColor color) = 0; - //! Sets another color for the background. - virtual void setBackgroundColor(video::SColor color) = 0; + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw) = 0; - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw) = 0; + //! Checks if background drawing is enabled + /** \return true if background drawing is enabled, false otherwise */ + virtual bool isDrawBackgroundEnabled() const = 0; - //! Checks if background drawing is enabled - /** \return true if background drawing is enabled, false otherwise */ - virtual bool isDrawBackgroundEnabled() const = 0; + //! Gets the background color + /** \return: The background color */ + virtual video::SColor getBackgroundColor() const = 0; - //! Gets the background color - /** \return: The background color */ - virtual video::SColor getBackgroundColor() const = 0; + //! Sets whether to draw the border + virtual void setDrawBorder(bool draw) = 0; - //! Sets whether to draw the border - virtual void setDrawBorder(bool draw) = 0; + //! Checks if border drawing is enabled + /** \return true if border drawing is enabled, false otherwise */ + virtual bool isDrawBorderEnabled() const = 0; - //! Checks if border drawing is enabled - /** \return true if border drawing is enabled, false otherwise */ - virtual bool isDrawBorderEnabled() const = 0; + //! Sets text justification mode + /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), + EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. + \param vertical: EGUIA_UPPERLEFT to align with top edge (default), + EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text. */ + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; - //! Sets text justification mode - /** \param horizontal: EGUIA_UPPERLEFT for left justified (default), - EGUIA_LOWERRIGHT for right justified, or EGUIA_CENTER for centered text. - \param vertical: EGUIA_UPPERLEFT to align with top edge (default), - EGUIA_LOWERRIGHT for bottom edge, or EGUIA_CENTER for centered text. */ - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) = 0; + //! Enables or disables word wrap for using the static text as multiline text control. + /** \param enable: If set to true, words going over one line are + broken on to the next line. */ + virtual void setWordWrap(bool enable) = 0; - //! Enables or disables word wrap for using the static text as multiline text control. - /** \param enable: If set to true, words going over one line are - broken on to the next line. */ - virtual void setWordWrap(bool enable) = 0; + //! Checks if word wrap is enabled + /** \return true if word wrap is enabled, false otherwise */ + virtual bool isWordWrapEnabled(void) const = 0; - //! Checks if word wrap is enabled - /** \return true if word wrap is enabled, false otherwise */ - virtual bool isWordWrapEnabled(void) const = 0; + //! Returns the height of the text in pixels when it is drawn. + /** This is useful for adjusting the layout of gui elements based on the height + of the multiline text in this element. + \return Height of text in pixels. */ + virtual s32 getTextHeight() const = 0; - //! Returns the height of the text in pixels when it is drawn. - /** This is useful for adjusting the layout of gui elements based on the height - of the multiline text in this element. - \return Height of text in pixels. */ - virtual s32 getTextHeight() const = 0; + //! Returns the width of the current text, in the current font + /** If the text is broken, this returns the width of the widest line + \return The width of the text, or the widest broken line. */ + virtual s32 getTextWidth(void) const = 0; - //! Returns the width of the current text, in the current font - /** If the text is broken, this returns the width of the widest line - \return The width of the text, or the widest broken line. */ - virtual s32 getTextWidth(void) const = 0; + //! Set whether the text in this label should be clipped if it goes outside bounds + virtual void setTextRestrainedInside(bool restrainedInside) = 0; - //! Set whether the text in this label should be clipped if it goes outside bounds - virtual void setTextRestrainedInside(bool restrainedInside) = 0; + //! Checks if the text in this label should be clipped if it goes outside bounds + virtual bool isTextRestrainedInside() const = 0; - //! Checks if the text in this label should be clipped if it goes outside bounds - virtual bool isTextRestrainedInside() const = 0; - - //! Set whether the string should be interpreted as right-to-left (RTL) text - /** \note This component does not implement the Unicode bidi standard, the - text of the component should be already RTL if you call this. The - main difference when RTL is enabled is that the linebreaks for multiline - elements are performed starting from the end. - */ - virtual void setRightToLeft(bool rtl) = 0; - - //! Checks whether the text in this element should be interpreted as right-to-left - virtual bool isRightToLeft() const = 0; - }; + //! Set whether the string should be interpreted as right-to-left (RTL) text + /** \note This component does not implement the Unicode bidi standard, the + text of the component should be already RTL if you call this. The + main difference when RTL is enabled is that the linebreaks for multiline + elements are performed starting from the end. + */ + virtual void setRightToLeft(bool rtl) = 0; + //! Checks whether the text in this element should be interpreted as right-to-left + virtual bool isRightToLeft() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUITabControl.h b/include/IGUITabControl.h index 5b042d27..f1d2183a 100644 --- a/include/IGUITabControl.h +++ b/include/IGUITabControl.h @@ -12,140 +12,138 @@ namespace irr { namespace gui { - class IGUITab; +class IGUITab; - //! A standard tab control - /** \par This element can create the following events of type EGUI_EVENT_TYPE: - \li EGET_TAB_CHANGED - */ - class IGUITabControl : public IGUIElement - { - public: +//! A standard tab control +/** \par This element can create the following events of type EGUI_EVENT_TYPE: +\li EGET_TAB_CHANGED +*/ +class IGUITabControl : public IGUIElement +{ +public: + //! constructor + IGUITabControl(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_TAB_CONTROL, environment, parent, id, rectangle) {} - //! constructor - IGUITabControl(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_TAB_CONTROL, environment, parent, id, rectangle) {} + //! Adds a tab + virtual IGUITab *addTab(const wchar_t *caption, s32 id = -1) = 0; - //! Adds a tab - virtual IGUITab* addTab(const wchar_t* caption, s32 id=-1) = 0; + //! Adds an existing tab + /** Note that it will also add the tab as a child of this TabControl. + \return Index of added tab or -1 for failure*/ + virtual s32 addTab(IGUITab *tab) = 0; - //! Adds an existing tab - /** Note that it will also add the tab as a child of this TabControl. - \return Index of added tab or -1 for failure*/ - virtual s32 addTab(IGUITab* tab) = 0; + //! Insert the tab at the given index + /** \return The tab on success or NULL on failure. */ + virtual IGUITab *insertTab(s32 idx, const wchar_t *caption, s32 id = -1) = 0; - //! Insert the tab at the given index - /** \return The tab on success or NULL on failure. */ - virtual IGUITab* insertTab(s32 idx, const wchar_t* caption, s32 id=-1) = 0; + //! Insert an existing tab + /** Note that it will also add the tab as a child of this TabControl. + \param idx Index at which tab will be inserted. Later tabs will be moved. + Previous active tab will stay active unless this is the first + element to be inserted in which case it becomes active. + \param tab New tab to insert. + \param serializationMode Internally used for serialization. You should not need this. + When true it reserves space for the index, doesn't move but replaces tabs + and it doesn't change the active tab. + \return Index of added tab (should be same as the one passed) or -1 for failure*/ + virtual s32 insertTab(s32 idx, IGUITab *tab, bool serializationMode = false) = 0; - //! Insert an existing tab - /** Note that it will also add the tab as a child of this TabControl. - \param idx Index at which tab will be inserted. Later tabs will be moved. - Previous active tab will stay active unless this is the first - element to be inserted in which case it becomes active. - \param tab New tab to insert. - \param serializationMode Internally used for serialization. You should not need this. - When true it reserves space for the index, doesn't move but replaces tabs - and it doesn't change the active tab. - \return Index of added tab (should be same as the one passed) or -1 for failure*/ - virtual s32 insertTab(s32 idx, IGUITab* tab, bool serializationMode=false) = 0; + //! Removes a tab from the tabcontrol + virtual void removeTab(s32 idx) = 0; - //! Removes a tab from the tabcontrol - virtual void removeTab(s32 idx) = 0; + //! Clears the tabcontrol removing all tabs + virtual void clear() = 0; - //! Clears the tabcontrol removing all tabs - virtual void clear() = 0; + //! Returns amount of tabs in the tabcontrol + virtual s32 getTabCount() const = 0; - //! Returns amount of tabs in the tabcontrol - virtual s32 getTabCount() const = 0; + //! Returns a tab based on zero based index + /** \param idx: zero based index of tab. Is a value between 0 and getTabcount()-1; + \return Returns pointer to the Tab. Returns 0 if no tab + is corresponding to this tab. */ + virtual IGUITab *getTab(s32 idx) const = 0; - //! Returns a tab based on zero based index - /** \param idx: zero based index of tab. Is a value between 0 and getTabcount()-1; - \return Returns pointer to the Tab. Returns 0 if no tab - is corresponding to this tab. */ - virtual IGUITab* getTab(s32 idx) const = 0; + //! For given element find if it's a tab and return it's zero-based index (or -1 for not found) + /** \param tab Tab for which we are looking (usually you will look for an IGUITab* type as only + those can be tabs, but we allow looking for any kind of IGUIElement* as there are some + use-cases for that even if it just returns 0. For example this way you can check for + all children of this gui-element if they are tabs or some non-tab children.*/ + virtual s32 getTabIndex(const IGUIElement *tab) const = 0; - //! For given element find if it's a tab and return it's zero-based index (or -1 for not found) - /** \param tab Tab for which we are looking (usually you will look for an IGUITab* type as only - those can be tabs, but we allow looking for any kind of IGUIElement* as there are some - use-cases for that even if it just returns 0. For example this way you can check for - all children of this gui-element if they are tabs or some non-tab children.*/ - virtual s32 getTabIndex(const IGUIElement *tab) const = 0; + //! Brings a tab to front. + /** \param idx: number of the tab. + \return Returns true if successful. */ + virtual bool setActiveTab(s32 idx) = 0; - //! Brings a tab to front. - /** \param idx: number of the tab. - \return Returns true if successful. */ - virtual bool setActiveTab(s32 idx) = 0; + //! Brings a tab to front. + /** \param tab: pointer to the tab. + \return Returns true if successful. */ + virtual bool setActiveTab(IGUITab *tab) = 0; - //! Brings a tab to front. - /** \param tab: pointer to the tab. - \return Returns true if successful. */ - virtual bool setActiveTab(IGUITab *tab) = 0; + //! Returns which tab is currently active + virtual s32 getActiveTab() const = 0; - //! Returns which tab is currently active - virtual s32 getActiveTab() const = 0; + //! get the the id of the tab at the given absolute coordinates + /** \return The id of the tab or -1 when no tab is at those coordinates*/ + virtual s32 getTabAt(s32 xpos, s32 ypos) const = 0; - //! get the the id of the tab at the given absolute coordinates - /** \return The id of the tab or -1 when no tab is at those coordinates*/ - virtual s32 getTabAt(s32 xpos, s32 ypos) const = 0; + //! Set the height of the tabs + virtual void setTabHeight(s32 height) = 0; - //! Set the height of the tabs - virtual void setTabHeight( s32 height ) = 0; + //! Get the height of the tabs + /** return Returns the height of the tabs */ + virtual s32 getTabHeight() const = 0; - //! Get the height of the tabs - /** return Returns the height of the tabs */ - virtual s32 getTabHeight() const = 0; + //! set the maximal width of a tab. Per default width is 0 which means "no width restriction". + virtual void setTabMaxWidth(s32 width) = 0; - //! set the maximal width of a tab. Per default width is 0 which means "no width restriction". - virtual void setTabMaxWidth(s32 width ) = 0; + //! get the maximal width of a tab + virtual s32 getTabMaxWidth() const = 0; - //! get the maximal width of a tab - virtual s32 getTabMaxWidth() const = 0; + //! Set the alignment of the tabs + /** Use EGUIA_UPPERLEFT or EGUIA_LOWERRIGHT */ + virtual void setTabVerticalAlignment(gui::EGUI_ALIGNMENT alignment) = 0; - //! Set the alignment of the tabs - /** Use EGUIA_UPPERLEFT or EGUIA_LOWERRIGHT */ - virtual void setTabVerticalAlignment( gui::EGUI_ALIGNMENT alignment ) = 0; + //! Get the alignment of the tabs + /** return Returns the alignment of the tabs */ + virtual gui::EGUI_ALIGNMENT getTabVerticalAlignment() const = 0; - //! Get the alignment of the tabs - /** return Returns the alignment of the tabs */ - virtual gui::EGUI_ALIGNMENT getTabVerticalAlignment() const = 0; + //! Set the extra width added to tabs on each side of the text + virtual void setTabExtraWidth(s32 extraWidth) = 0; - //! Set the extra width added to tabs on each side of the text - virtual void setTabExtraWidth( s32 extraWidth ) = 0; + //! Get the extra width added to tabs on each side of the text + /** return Returns the extra width of the tabs */ + virtual s32 getTabExtraWidth() const = 0; +}; - //! Get the extra width added to tabs on each side of the text - /** return Returns the extra width of the tabs */ - virtual s32 getTabExtraWidth() const = 0; - }; +//! A tab-page, onto which other gui elements could be added. +/** IGUITab refers mostly to the page itself, but also carries some data about the tab in the tabbar of an IGUITabControl. */ +class IGUITab : public IGUIElement +{ +public: + //! constructor + IGUITab(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_TAB, environment, parent, id, rectangle) {} - //! A tab-page, onto which other gui elements could be added. - /** IGUITab refers mostly to the page itself, but also carries some data about the tab in the tabbar of an IGUITabControl. */ - class IGUITab : public IGUIElement - { - public: + //! sets if the tab should draw its background + virtual void setDrawBackground(bool draw = true) = 0; - //! constructor - IGUITab(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_TAB, environment, parent, id, rectangle) {} + //! sets the color of the background, if it should be drawn. + virtual void setBackgroundColor(video::SColor c) = 0; - //! sets if the tab should draw its background - virtual void setDrawBackground(bool draw=true) = 0; + //! returns true if the tab is drawing its background, false if not + virtual bool isDrawingBackground() const = 0; - //! sets the color of the background, if it should be drawn. - virtual void setBackgroundColor(video::SColor c) = 0; + //! returns the color of the background + virtual video::SColor getBackgroundColor() const = 0; - //! returns true if the tab is drawing its background, false if not - virtual bool isDrawingBackground() const = 0; + //! sets the color of it's text in the tab-bar + virtual void setTextColor(video::SColor c) = 0; - //! returns the color of the background - virtual video::SColor getBackgroundColor() const = 0; - - //! sets the color of it's text in the tab-bar - virtual void setTextColor(video::SColor c) = 0; - - //! gets the color of the text - virtual video::SColor getTextColor() const = 0; - }; + //! gets the color of the text + virtual video::SColor getTextColor() const = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IGUIToolbar.h b/include/IGUIToolbar.h index 75736855..2011f09a 100644 --- a/include/IGUIToolbar.h +++ b/include/IGUIToolbar.h @@ -10,27 +10,25 @@ namespace irr { namespace video { - class ITexture; +class ITexture; } // end namespace video namespace gui { - class IGUIButton; +class IGUIButton; - //! Stays at the top of its parent like the menu bar and contains tool buttons - class IGUIToolBar : public IGUIElement - { - public: - - //! constructor - IGUIToolBar(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) - : IGUIElement(EGUIET_TOOL_BAR, environment, parent, id, rectangle) {} - - //! Adds a button to the tool bar - virtual IGUIButton* addButton(s32 id=-1, const wchar_t* text=0,const wchar_t* tooltiptext=0, - video::ITexture* img=0, video::ITexture* pressedimg=0, - bool isPushButton=false, bool useAlphaChannel=false) = 0; - }; +//! Stays at the top of its parent like the menu bar and contains tool buttons +class IGUIToolBar : public IGUIElement +{ +public: + //! constructor + IGUIToolBar(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIElement(EGUIET_TOOL_BAR, environment, parent, id, rectangle) {} + //! Adds a button to the tool bar + virtual IGUIButton *addButton(s32 id = -1, const wchar_t *text = 0, const wchar_t *tooltiptext = 0, + video::ITexture *img = 0, video::ITexture *pressedimg = 0, + bool isPushButton = false, bool useAlphaChannel = false) = 0; +}; } // end namespace gui } // end namespace irr diff --git a/include/IImage.h b/include/IImage.h index 3fc7000c..f3c29b71 100644 --- a/include/IImage.h +++ b/include/IImage.h @@ -23,10 +23,9 @@ NOTE: Floating point formats are not well supported yet. Basically only getData( class IImage : public virtual IReferenceCounted { public: - //! constructor - IImage(ECOLOR_FORMAT format, const core::dimension2d& size, bool deleteMemory) : - Format(format), Size(size), Data(0), MipMapsData(0), BytesPerPixel(0), Pitch(0), DeleteMemory(deleteMemory), DeleteMipMapsMemory(false) + IImage(ECOLOR_FORMAT format, const core::dimension2d &size, bool deleteMemory) : + Format(format), Size(size), Data(0), MipMapsData(0), BytesPerPixel(0), Pitch(0), DeleteMemory(deleteMemory), DeleteMipMapsMemory(false) { BytesPerPixel = getBitsPerPixelFromFormat(Format) / 8; Pitch = BytesPerPixel * Size.Width; @@ -49,7 +48,7 @@ public: } //! Returns width and height of image data. - const core::dimension2d& getDimension() const + const core::dimension2d &getDimension() const { return Size; } @@ -88,8 +87,7 @@ public: //! Returns mask for red value of a pixel u32 getRedMask() const { - switch (Format) - { + switch (Format) { case ECF_A1R5G5B5: return 0x1F << 10; case ECF_R5G6B5: @@ -106,8 +104,7 @@ public: //! Returns mask for green value of a pixel u32 getGreenMask() const { - switch (Format) - { + switch (Format) { case ECF_A1R5G5B5: return 0x1F << 5; case ECF_R5G6B5: @@ -124,8 +121,7 @@ public: //! Returns mask for blue value of a pixel u32 getBlueMask() const { - switch (Format) - { + switch (Format) { case ECF_A1R5G5B5: return 0x1F; case ECF_R5G6B5: @@ -142,8 +138,7 @@ public: //! Returns mask for alpha value of a pixel u32 getAlphaMask() const { - switch (Format) - { + switch (Format) { case ECF_A1R5G5B5: return 0x1 << 15; case ECF_R5G6B5: @@ -162,7 +157,7 @@ public: \return Pointer to the image data. What type of data is pointed to depends on the color format of the image. For example if the color format is ECF_A8R8G8B8, it is of u32. */ - void* getData() const + void *getData() const { return Data; } @@ -175,43 +170,38 @@ public: return getMipMapsSize(Size, mipmapLevel); } - //! Calculate mipmap size for a certain level /** level 0 will be full image size. Every further level is half the size. */ - static core::dimension2du getMipMapsSize(const core::dimension2du& sizeLevel0, u32 mipmapLevel) + static core::dimension2du getMipMapsSize(const core::dimension2du &sizeLevel0, u32 mipmapLevel) { core::dimension2du result(sizeLevel0); - u32 i=0; - while (i != mipmapLevel) - { - if (result.Width>1) + u32 i = 0; + while (i != mipmapLevel) { + if (result.Width > 1) result.Width >>= 1; - if (result.Height>1) - result.Height>>=1; + if (result.Height > 1) + result.Height >>= 1; ++i; - if ( result.Width == 1 && result.Height == 1 && i < mipmapLevel ) - return core::dimension2du(0,0); + if (result.Width == 1 && result.Height == 1 && i < mipmapLevel) + return core::dimension2du(0, 0); } return result; } - //! Get mipmaps data. /** Note that different mip levels are just behind each other in memory block. So if you just get level 1 you also have the data for all other levels. There is no level 0 - use getData to get the original image data. */ - void* getMipMapsData(irr::u32 mipLevel=1) const + void *getMipMapsData(irr::u32 mipLevel = 1) const { - if ( MipMapsData && mipLevel > 0) - { + if (MipMapsData && mipLevel > 0) { size_t dataSize = 0; core::dimension2du mipSize(Size); - u32 i = 1; // We want the start of data for this level, not end. + u32 i = 1; // We want the start of data for this level, not end. - while (i != mipLevel) - { + while (i != mipLevel) { if (mipSize.Width > 1) mipSize.Width >>= 1; @@ -221,7 +211,7 @@ public: dataSize += getDataSizeFromFormat(Format, mipSize.Width, mipSize.Height); ++i; - if ( mipSize.Width == 1 && mipSize.Height == 1 && i < mipLevel) + if (mipSize.Width == 1 && mipSize.Height == 1 && i < mipLevel) return 0; } @@ -240,33 +230,26 @@ public: will by copied internally. \param deleteMemory Whether the memory is deallocated upon destruction. */ - void setMipMapsData(void* data, bool ownForeignMemory) + void setMipMapsData(void *data, bool ownForeignMemory) { - if (data != MipMapsData) - { - if (DeleteMipMapsMemory) - { + if (data != MipMapsData) { + if (DeleteMipMapsMemory) { delete[] MipMapsData; DeleteMipMapsMemory = false; } - if (data) - { - if (ownForeignMemory) - { - MipMapsData = static_cast(data); + if (data) { + if (ownForeignMemory) { + MipMapsData = static_cast(data); DeleteMipMapsMemory = false; - } - else - { + } else { u32 dataSize = 0; u32 width = Size.Width; u32 height = Size.Height; - do - { + do { if (width > 1) width >>= 1; @@ -281,9 +264,7 @@ public: DeleteMipMapsMemory = true; } - } - else - { + } else { MipMapsData = 0; } } @@ -293,51 +274,50 @@ public: virtual SColor getPixel(u32 x, u32 y) const = 0; //! Sets a pixel - virtual void setPixel(u32 x, u32 y, const SColor &color, bool blend = false ) = 0; + virtual void setPixel(u32 x, u32 y, const SColor &color, bool blend = false) = 0; //! Copies this surface into another, if it has the exact same size and format. /** NOTE: mipmaps are ignored \return True if it was copied, false otherwise. */ - virtual bool copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format=ECF_A8R8G8B8, u32 pitch=0) const = 0; + virtual bool copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format = ECF_A8R8G8B8, u32 pitch = 0) const = 0; //! Copies the image into the target, scaling the image to fit /** NOTE: mipmaps are ignored */ - virtual void copyToScaling(void* target, u32 width, u32 height, ECOLOR_FORMAT format=ECF_A8R8G8B8, u32 pitch=0) =0; + virtual void copyToScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format = ECF_A8R8G8B8, u32 pitch = 0) = 0; //! Copies the image into the target, scaling the image to fit /** NOTE: mipmaps are ignored */ - virtual void copyToScaling(IImage* target) =0; + virtual void copyToScaling(IImage *target) = 0; //! copies this surface into another /** NOTE: mipmaps are ignored */ - virtual void copyTo(IImage* target, const core::position2d& pos=core::position2d(0,0)) =0; + virtual void copyTo(IImage *target, const core::position2d &pos = core::position2d(0, 0)) = 0; //! copies this surface into another /** NOTE: mipmaps are ignored */ - virtual void copyTo(IImage* target, const core::position2d& pos, const core::rect& sourceRect, const core::rect* clipRect=0) =0; + virtual void copyTo(IImage *target, const core::position2d &pos, const core::rect &sourceRect, const core::rect *clipRect = 0) = 0; //! copies this surface into another, using the alpha mask and cliprect and a color to add with /** NOTE: mipmaps are ignored \param combineAlpha - When true then combine alpha channels. When false replace target image alpha with source image alpha. */ - virtual void copyToWithAlpha(IImage* target, const core::position2d& pos, - const core::rect& sourceRect, const SColor &color, - const core::rect* clipRect = 0, - bool combineAlpha=false) =0; + virtual void copyToWithAlpha(IImage *target, const core::position2d &pos, + const core::rect &sourceRect, const SColor &color, + const core::rect *clipRect = 0, + bool combineAlpha = false) = 0; //! copies this surface into another, scaling it to fit, applying a box filter /** NOTE: mipmaps are ignored */ - virtual void copyToScalingBoxFilter(IImage* target, s32 bias = 0, bool blend = false) = 0; + virtual void copyToScalingBoxFilter(IImage *target, s32 bias = 0, bool blend = false) = 0; //! fills the surface with given color - virtual void fill(const SColor &color) =0; + virtual void fill(const SColor &color) = 0; //! get the amount of Bits per Pixel of the given color format static u32 getBitsPerPixelFromFormat(const ECOLOR_FORMAT format) { - switch(format) - { + switch (format) { case ECF_A1R5G5B5: return 16; case ECF_R5G6B5: @@ -396,14 +376,13 @@ public: //! check if the color format is only viable for depth/stencil textures static bool isDepthFormat(const ECOLOR_FORMAT format) { - switch(format) - { - case ECF_D16: - case ECF_D32: - case ECF_D24S8: - return true; - default: - return false; + switch (format) { + case ECF_D16: + case ECF_D32: + case ECF_D24S8: + return true; + default: + return false; } } @@ -413,8 +392,7 @@ public: if (isCompressedFormat(format)) return false; - switch(format) - { + switch (format) { case ECF_R16F: case ECF_G16R16F: case ECF_A16B16G16R16F: @@ -432,8 +410,8 @@ protected: ECOLOR_FORMAT Format; core::dimension2d Size; - u8* Data; - u8* MipMapsData; + u8 *Data; + u8 *MipMapsData; u32 BytesPerPixel; u32 Pitch; @@ -442,6 +420,5 @@ protected: bool DeleteMipMapsMemory; }; - } // end namespace video } // end namespace irr diff --git a/include/IImageLoader.h b/include/IImageLoader.h index 12623c69..a521be15 100644 --- a/include/IImageLoader.h +++ b/include/IImageLoader.h @@ -14,7 +14,7 @@ namespace irr { namespace io { - class IReadFile; +class IReadFile; } // end namespace io namespace video { @@ -27,25 +27,23 @@ IVideoDriver::addExternalImageLoader() to the engine. */ class IImageLoader : public virtual IReferenceCounted { public: - //! Check if the file might be loaded by this class /** Check is based on the file extension (e.g. ".tga") \param filename Name of file to check. \return True if file seems to be loadable. */ - virtual bool isALoadableFileExtension(const io::path& filename) const = 0; + virtual bool isALoadableFileExtension(const io::path &filename) const = 0; //! Check if the file might be loaded by this class /** Check might look into the file. \param file File handle to check. \return True if file seems to be loadable. */ - virtual bool isALoadableFileFormat(io::IReadFile* file) const = 0; + virtual bool isALoadableFileFormat(io::IReadFile *file) const = 0; //! Creates a surface from the file /** \param file File handle to check. \return Pointer to newly created image, or 0 upon error. */ - virtual IImage* loadImage(io::IReadFile* file) const = 0; + virtual IImage *loadImage(io::IReadFile *file) const = 0; }; - } // end namespace video } // end namespace irr diff --git a/include/IImageWriter.h b/include/IImageWriter.h index 632d8b5d..b8defc75 100644 --- a/include/IImageWriter.h +++ b/include/IImageWriter.h @@ -12,13 +12,12 @@ namespace irr { namespace io { - class IWriteFile; +class IWriteFile; } // end namespace io namespace video { - class IImage; - +class IImage; //! Interface for writing software image data. class IImageWriter : public IReferenceCounted @@ -27,7 +26,7 @@ public: //! Check if this writer can write a file with the given extension /** \param filename Name of the file to check. \return True if file extension specifies a writable type. */ - virtual bool isAWriteableFileExtension(const io::path& filename) const = 0; + virtual bool isAWriteableFileExtension(const io::path &filename) const = 0; //! Write image to file /** \param file File handle to write to. diff --git a/include/IIndexBuffer.h b/include/IIndexBuffer.h index c1a35f52..3d5b8e76 100644 --- a/include/IIndexBuffer.h +++ b/include/IIndexBuffer.h @@ -20,42 +20,40 @@ namespace video namespace scene { - class IIndexBuffer : public virtual IReferenceCounted - { - public: +class IIndexBuffer : public virtual IReferenceCounted +{ +public: + virtual void *getData() = 0; - virtual void* getData() =0; + virtual video::E_INDEX_TYPE getType() const = 0; + virtual void setType(video::E_INDEX_TYPE IndexType) = 0; - virtual video::E_INDEX_TYPE getType() const =0; - virtual void setType(video::E_INDEX_TYPE IndexType) =0; + virtual u32 stride() const = 0; - virtual u32 stride() const =0; + virtual u32 size() const = 0; + virtual void push_back(const u32 &element) = 0; + virtual u32 operator[](u32 index) const = 0; + virtual u32 getLast() = 0; + virtual void setValue(u32 index, u32 value) = 0; + virtual void set_used(u32 usedNow) = 0; + virtual void reallocate(u32 new_size) = 0; + virtual u32 allocated_size() const = 0; - virtual u32 size() const =0; - virtual void push_back (const u32 &element) =0; - virtual u32 operator [](u32 index) const =0; - virtual u32 getLast() =0; - virtual void setValue(u32 index, u32 value) =0; - virtual void set_used(u32 usedNow) =0; - virtual void reallocate(u32 new_size) =0; - virtual u32 allocated_size() const=0; + virtual void *pointer() = 0; - virtual void* pointer() =0; + //! get the current hardware mapping hint + virtual E_HARDWARE_MAPPING getHardwareMappingHint() const = 0; - //! get the current hardware mapping hint - virtual E_HARDWARE_MAPPING getHardwareMappingHint() const =0; + //! set the hardware mapping hint, for driver + virtual void setHardwareMappingHint(E_HARDWARE_MAPPING NewMappingHint) = 0; - //! set the hardware mapping hint, for driver - virtual void setHardwareMappingHint( E_HARDWARE_MAPPING NewMappingHint ) =0; - - //! flags the meshbuffer as changed, reloads hardware buffers - virtual void setDirty() = 0; - - //! Get the currently used ID for identification of changes. - /** This shouldn't be used for anything outside the VideoDriver. */ - virtual u32 getChangedID() const = 0; - }; + //! flags the meshbuffer as changed, reloads hardware buffers + virtual void setDirty() = 0; + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + virtual u32 getChangedID() const = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/ILogger.h b/include/ILogger.h index 48dfc5f4..2642f339 100644 --- a/include/ILogger.h +++ b/include/ILogger.h @@ -32,12 +32,10 @@ enum ELOG_LEVEL ELL_NONE }; - //! Interface for logging messages, warnings and errors class ILogger : public virtual IReferenceCounted { public: - //! Destructor virtual ~ILogger() {} @@ -60,7 +58,7 @@ public: is just an informational text, set it to ELL_INFORMATION. Texts are filtered with these levels. If you want to be a text displayed, independent on what level filter is set, use ELL_NONE. */ - virtual void log(const c8* text, ELOG_LEVEL ll=ELL_INFORMATION) = 0; + virtual void log(const c8 *text, ELOG_LEVEL ll = ELL_INFORMATION) = 0; //! Prints out a text into the log /** \param text: Text to print out. @@ -71,7 +69,7 @@ public: is just an informational text, set it to ELL_INFORMATION. Texts are filtered with these levels. If you want to be a text displayed, independent on what level filter is set, use ELL_NONE. */ - virtual void log(const c8* text, const c8* hint, ELOG_LEVEL ll=ELL_INFORMATION) = 0; + virtual void log(const c8 *text, const c8 *hint, ELOG_LEVEL ll = ELL_INFORMATION) = 0; }; } // end namespace diff --git a/include/IMaterialRenderer.h b/include/IMaterialRenderer.h index b959a493..ba9c4b74 100644 --- a/include/IMaterialRenderer.h +++ b/include/IMaterialRenderer.h @@ -24,7 +24,6 @@ engine with new materials. */ class IMaterialRenderer : public virtual IReferenceCounted { public: - //! Called by the IVideoDriver implementation the let the renderer set its needed render states. /** This is called during the IVideoDriver::setMaterial() call. When overriding this, you can set some renderstates or for example a @@ -47,8 +46,8 @@ public: fogenable. \param services: Interface providing some methods for changing advanced, internal states of a IVideoDriver. */ - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) {} + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) {} //! Called every time before a new bunch of geometry is being drawn using this material with for example drawIndexedTriangleList() call. /** OnSetMaterial should normally only be called if the renderer decides @@ -68,7 +67,7 @@ public: example if he doesn't support the specified vertex type. This is actually done in D3D9 when using a normal mapped material with a vertex type other than EVT_TANGENTS. */ - virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) { return true; } + virtual bool OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype) { return true; } //! Called by the IVideoDriver to unset this material. /** Called during the IVideoDriver::setMaterial() call before the new @@ -95,9 +94,8 @@ public: //! Access the callback provided by the users when creating shader materials /** \returns Returns either the users provided callback or 0 when no such callback exists. Non-shader materials will always return 0. */ - virtual IShaderConstantSetCallBack* getShaderConstantSetCallBack() const { return 0; } + virtual IShaderConstantSetCallBack *getShaderConstantSetCallBack() const { return 0; } }; - } // end namespace video } // end namespace irr diff --git a/include/IMaterialRendererServices.h b/include/IMaterialRendererServices.h index 2eb13a77..81a195d8 100644 --- a/include/IMaterialRendererServices.h +++ b/include/IMaterialRendererServices.h @@ -14,12 +14,10 @@ namespace video class IVideoDriver; - //! Interface providing some methods for changing advanced, internal states of a IVideoDriver. class IMaterialRendererServices { public: - //! Destructor virtual ~IMaterialRendererServices() {} @@ -33,12 +31,12 @@ public: \param lastMaterial The material used until now. \param resetAllRenderstates Set to true if all renderstates should be set, regardless of their current state. */ - virtual void setBasicRenderStates(const SMaterial& material, - const SMaterial& lastMaterial, - bool resetAllRenderstates) = 0; + virtual void setBasicRenderStates(const SMaterial &material, + const SMaterial &lastMaterial, + bool resetAllRenderstates) = 0; //! Return an index constant for the vertex shader based on a uniform variable name. - virtual s32 getVertexShaderConstantID(const c8* name) = 0; + virtual s32 getVertexShaderConstantID(const c8 *name) = 0; //! Sets a value for a vertex shader uniform variable. /** \param index Index of the variable (as received from getVertexShaderConstantID) @@ -46,16 +44,16 @@ public: \param count Amount of floats in array. \return True if successful. */ - virtual bool setVertexShaderConstant(s32 index, const f32* floats, int count) = 0; + virtual bool setVertexShaderConstant(s32 index, const f32 *floats, int count) = 0; //! Int interface for the above. - virtual bool setVertexShaderConstant(s32 index, const s32* ints, int count) = 0; + virtual bool setVertexShaderConstant(s32 index, const s32 *ints, int count) = 0; //! Uint interface for the above. - virtual bool setVertexShaderConstant(s32 index, const u32* ints, int count) = 0; + virtual bool setVertexShaderConstant(s32 index, const u32 *ints, int count) = 0; //! Return an index constant for the pixel shader for the given uniform variable name - virtual s32 getPixelShaderConstantID(const c8* name) = 0; + virtual s32 getPixelShaderConstantID(const c8 *name) = 0; //! Sets a value for the given pixel shader uniform variable /** This can be used if you used a high level shader language like GLSL @@ -65,17 +63,17 @@ public: \param floats Pointer to array of floats \param count Amount of floats in array. \return True if successful. */ - virtual bool setPixelShaderConstant(s32 index, const f32* floats, int count) = 0; + virtual bool setPixelShaderConstant(s32 index, const f32 *floats, int count) = 0; //! Int interface for the above. - virtual bool setPixelShaderConstant(s32 index, const s32* ints, int count) = 0; + virtual bool setPixelShaderConstant(s32 index, const s32 *ints, int count) = 0; //! Uint interface for the above. - virtual bool setPixelShaderConstant(s32 index, const u32* ints, int count) = 0; + virtual bool setPixelShaderConstant(s32 index, const u32 *ints, int count) = 0; //! Get pointer to the IVideoDriver interface /** \return Pointer to the IVideoDriver interface */ - virtual IVideoDriver* getVideoDriver() = 0; + virtual IVideoDriver *getVideoDriver() = 0; }; } // end namespace video diff --git a/include/IMemoryReadFile.h b/include/IMemoryReadFile.h index 7b18d53c..982b09af 100644 --- a/include/IMemoryReadFile.h +++ b/include/IMemoryReadFile.h @@ -11,17 +11,17 @@ namespace irr namespace io { - //! Interface providing read access to a memory read file. - class IMemoryReadFile : public IReadFile - { - public: - //! Get direct access to internal buffer of memory block used as file. - /** It's usually better to use the IReadFile functions to access - the file content. But as that buffer exist over the full life-time - of a CMemoryReadFile, it's sometimes nice to avoid the additional - data-copy which read() needs. - */ - virtual const void *getBuffer() const = 0; - }; +//! Interface providing read access to a memory read file. +class IMemoryReadFile : public IReadFile +{ +public: + //! Get direct access to internal buffer of memory block used as file. + /** It's usually better to use the IReadFile functions to access + the file content. But as that buffer exist over the full life-time + of a CMemoryReadFile, it's sometimes nice to avoid the additional + data-copy which read() needs. + */ + virtual const void *getBuffer() const = 0; +}; } // end namespace io } // end namespace irr diff --git a/include/IMesh.h b/include/IMesh.h index 2884d74a..6d06eb76 100644 --- a/include/IMesh.h +++ b/include/IMesh.h @@ -12,114 +12,112 @@ namespace irr { namespace scene { - //! Possible types of meshes. - // Note: Was previously only used in IAnimatedMesh so it still has the "animated" in the name. - // But can now be used for all mesh-types as we need those casts as well. - enum E_ANIMATED_MESH_TYPE +//! Possible types of meshes. +// Note: Was previously only used in IAnimatedMesh so it still has the "animated" in the name. +// But can now be used for all mesh-types as we need those casts as well. +enum E_ANIMATED_MESH_TYPE +{ + //! Unknown animated mesh type. + EAMT_UNKNOWN = 0, + + //! Quake 2 MD2 model file + EAMT_MD2, + + //! Quake 3 MD3 model file + EAMT_MD3, + + //! Maya .obj static model + EAMT_OBJ, + + //! Quake 3 .bsp static Map + EAMT_BSP, + + //! 3D Studio .3ds file + EAMT_3DS, + + //! My3D Mesh, the file format by Zhuck Dimitry + EAMT_MY3D, + + //! Pulsar LMTools .lmts file. This Irrlicht loader was written by Jonas Petersen + EAMT_LMTS, + + //! Cartography Shop .csm file. This loader was created by Saurav Mohapatra. + EAMT_CSM, + + //! .oct file for Paul Nette's FSRad or from Murphy McCauley's Blender .oct exporter. + /** The oct file format contains 3D geometry and lightmaps and + can be loaded directly by Irrlicht */ + EAMT_OCT, + + //! Halflife MDL model file + EAMT_MDL_HALFLIFE, + + //! generic skinned mesh + EAMT_SKINNED, + + //! generic non-animated mesh + EAMT_STATIC +}; + +class IMeshBuffer; + +//! Class which holds the geometry of an object. +/** An IMesh is nothing more than a collection of some mesh buffers +(IMeshBuffer). SMesh is a simple implementation of an IMesh. +A mesh is usually added to an IMeshSceneNode in order to be rendered. +*/ +class IMesh : public virtual IReferenceCounted +{ +public: + //! Get the amount of mesh buffers. + /** \return Amount of mesh buffers (IMeshBuffer) in this mesh. */ + virtual u32 getMeshBufferCount() const = 0; + + //! Get pointer to a mesh buffer. + /** \param nr: Zero based index of the mesh buffer. The maximum value is + getMeshBufferCount() - 1; + \return Pointer to the mesh buffer or 0 if there is no such + mesh buffer. */ + virtual IMeshBuffer *getMeshBuffer(u32 nr) const = 0; + + //! Get pointer to a mesh buffer which fits a material + /** \param material: material to search for + \return Pointer to the mesh buffer or 0 if there is no such + mesh buffer. */ + virtual IMeshBuffer *getMeshBuffer(const video::SMaterial &material) const = 0; + + //! Get an axis aligned bounding box of the mesh. + /** \return Bounding box of this mesh. */ + virtual const core::aabbox3d &getBoundingBox() const = 0; + + //! Set user-defined axis aligned bounding box + /** \param box New bounding box to use for the mesh. */ + virtual void setBoundingBox(const core::aabbox3df &box) = 0; + + //! Set the hardware mapping hint + /** This methods allows to define optimization hints for the + hardware. This enables, e.g., the use of hardware buffers on + platforms that support this feature. This can lead to noticeable + performance gains. */ + virtual void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) = 0; + + //! Flag the meshbuffer as changed, reloads hardware buffers + /** This method has to be called every time the vertices or + indices have changed. Otherwise, changes won't be updated + on the GPU in the next render cycle. */ + virtual void setDirty(E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) = 0; + + //! Returns the type of the meshes. + /** This is useful for making a safe downcast. For example, + if getMeshType() returns EAMT_MD2 it's safe to cast the + IMesh to IAnimatedMeshMD2. + Note: It's no longer just about animated meshes, that name has just historical reasons. + \returns Type of the mesh */ + virtual E_ANIMATED_MESH_TYPE getMeshType() const { - //! Unknown animated mesh type. - EAMT_UNKNOWN = 0, - - //! Quake 2 MD2 model file - EAMT_MD2, - - //! Quake 3 MD3 model file - EAMT_MD3, - - //! Maya .obj static model - EAMT_OBJ, - - //! Quake 3 .bsp static Map - EAMT_BSP, - - //! 3D Studio .3ds file - EAMT_3DS, - - //! My3D Mesh, the file format by Zhuck Dimitry - EAMT_MY3D, - - //! Pulsar LMTools .lmts file. This Irrlicht loader was written by Jonas Petersen - EAMT_LMTS, - - //! Cartography Shop .csm file. This loader was created by Saurav Mohapatra. - EAMT_CSM, - - //! .oct file for Paul Nette's FSRad or from Murphy McCauley's Blender .oct exporter. - /** The oct file format contains 3D geometry and lightmaps and - can be loaded directly by Irrlicht */ - EAMT_OCT, - - //! Halflife MDL model file - EAMT_MDL_HALFLIFE, - - //! generic skinned mesh - EAMT_SKINNED, - - //! generic non-animated mesh - EAMT_STATIC - }; - - - class IMeshBuffer; - - //! Class which holds the geometry of an object. - /** An IMesh is nothing more than a collection of some mesh buffers - (IMeshBuffer). SMesh is a simple implementation of an IMesh. - A mesh is usually added to an IMeshSceneNode in order to be rendered. - */ - class IMesh : public virtual IReferenceCounted - { - public: - - //! Get the amount of mesh buffers. - /** \return Amount of mesh buffers (IMeshBuffer) in this mesh. */ - virtual u32 getMeshBufferCount() const = 0; - - //! Get pointer to a mesh buffer. - /** \param nr: Zero based index of the mesh buffer. The maximum value is - getMeshBufferCount() - 1; - \return Pointer to the mesh buffer or 0 if there is no such - mesh buffer. */ - virtual IMeshBuffer* getMeshBuffer(u32 nr) const = 0; - - //! Get pointer to a mesh buffer which fits a material - /** \param material: material to search for - \return Pointer to the mesh buffer or 0 if there is no such - mesh buffer. */ - virtual IMeshBuffer* getMeshBuffer( const video::SMaterial &material) const = 0; - - //! Get an axis aligned bounding box of the mesh. - /** \return Bounding box of this mesh. */ - virtual const core::aabbox3d& getBoundingBox() const = 0; - - //! Set user-defined axis aligned bounding box - /** \param box New bounding box to use for the mesh. */ - virtual void setBoundingBox( const core::aabbox3df& box) = 0; - - //! Set the hardware mapping hint - /** This methods allows to define optimization hints for the - hardware. This enables, e.g., the use of hardware buffers on - platforms that support this feature. This can lead to noticeable - performance gains. */ - virtual void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) = 0; - - //! Flag the meshbuffer as changed, reloads hardware buffers - /** This method has to be called every time the vertices or - indices have changed. Otherwise, changes won't be updated - on the GPU in the next render cycle. */ - virtual void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) = 0; - - //! Returns the type of the meshes. - /** This is useful for making a safe downcast. For example, - if getMeshType() returns EAMT_MD2 it's safe to cast the - IMesh to IAnimatedMeshMD2. - Note: It's no longer just about animated meshes, that name has just historical reasons. - \returns Type of the mesh */ - virtual E_ANIMATED_MESH_TYPE getMeshType() const - { - return EAMT_STATIC; - } - }; + return EAMT_STATIC; + } +}; } // end namespace scene } // end namespace irr diff --git a/include/IMeshBuffer.h b/include/IMeshBuffer.h index 8b32ac12..3e2e3d74 100644 --- a/include/IMeshBuffer.h +++ b/include/IMeshBuffer.h @@ -16,162 +16,167 @@ namespace irr { namespace scene { - //! Struct for holding a mesh with a single material. - /** A part of an IMesh which has the same material on each face of that - group. Logical groups of an IMesh need not be put into separate mesh - buffers, but can be. Separately animated parts of the mesh must be put - into separate mesh buffers. - Some mesh buffer implementations have limitations on the number of - vertices the buffer can hold. In that case, logical grouping can help. - Moreover, the number of vertices should be optimized for the GPU upload, - which often depends on the type of gfx card. Typical figures are - 1000-10000 vertices per buffer. - SMeshBuffer is a simple implementation of a MeshBuffer, which supports - up to 65535 vertices. +//! Struct for holding a mesh with a single material. +/** A part of an IMesh which has the same material on each face of that +group. Logical groups of an IMesh need not be put into separate mesh +buffers, but can be. Separately animated parts of the mesh must be put +into separate mesh buffers. +Some mesh buffer implementations have limitations on the number of +vertices the buffer can hold. In that case, logical grouping can help. +Moreover, the number of vertices should be optimized for the GPU upload, +which often depends on the type of gfx card. Typical figures are +1000-10000 vertices per buffer. +SMeshBuffer is a simple implementation of a MeshBuffer, which supports +up to 65535 vertices. - Since meshbuffers are used for drawing, and hence will be exposed - to the driver, chances are high that they are grab()'ed from somewhere. - It's therefore required to dynamically allocate meshbuffers which are - passed to a video driver and only drop the buffer once it's not used in - the current code block anymore. - */ - class IMeshBuffer : public virtual IReferenceCounted +Since meshbuffers are used for drawing, and hence will be exposed +to the driver, chances are high that they are grab()'ed from somewhere. +It's therefore required to dynamically allocate meshbuffers which are +passed to a video driver and only drop the buffer once it's not used in +the current code block anymore. +*/ +class IMeshBuffer : public virtual IReferenceCounted +{ +public: + //! Get the material of this meshbuffer + /** \return Material of this buffer. */ + virtual video::SMaterial &getMaterial() = 0; + + //! Get the material of this meshbuffer + /** \return Material of this buffer. */ + virtual const video::SMaterial &getMaterial() const = 0; + + //! Get type of vertex data which is stored in this meshbuffer. + /** \return Vertex type of this buffer. */ + virtual video::E_VERTEX_TYPE getVertexType() const = 0; + + //! Get access to vertex data. The data is an array of vertices. + /** Which vertex type is used can be determined by getVertexType(). + \return Pointer to array of vertices. */ + virtual const void *getVertices() const = 0; + + //! Get access to vertex data. The data is an array of vertices. + /** Which vertex type is used can be determined by getVertexType(). + \return Pointer to array of vertices. */ + virtual void *getVertices() = 0; + + //! Get amount of vertices in meshbuffer. + /** \return Number of vertices in this buffer. */ + virtual u32 getVertexCount() const = 0; + + //! Get type of index data which is stored in this meshbuffer. + /** \return Index type of this buffer. */ + virtual video::E_INDEX_TYPE getIndexType() const = 0; + + //! Get access to indices. + /** \return Pointer to indices array. */ + virtual const u16 *getIndices() const = 0; + + //! Get access to indices. + /** \return Pointer to indices array. */ + virtual u16 *getIndices() = 0; + + //! Get amount of indices in this meshbuffer. + /** \return Number of indices in this buffer. */ + virtual u32 getIndexCount() const = 0; + + //! Get the axis aligned bounding box of this meshbuffer. + /** \return Axis aligned bounding box of this buffer. */ + virtual const core::aabbox3df &getBoundingBox() const = 0; + + //! Set axis aligned bounding box + /** \param box User defined axis aligned bounding box to use + for this buffer. */ + virtual void setBoundingBox(const core::aabbox3df &box) = 0; + + //! Recalculates the bounding box. Should be called if the mesh changed. + virtual void recalculateBoundingBox() = 0; + + //! returns position of vertex i + virtual const core::vector3df &getPosition(u32 i) const = 0; + + //! returns position of vertex i + virtual core::vector3df &getPosition(u32 i) = 0; + + //! returns normal of vertex i + virtual const core::vector3df &getNormal(u32 i) const = 0; + + //! returns normal of vertex i + virtual core::vector3df &getNormal(u32 i) = 0; + + //! returns texture coord of vertex i + virtual const core::vector2df &getTCoords(u32 i) const = 0; + + //! returns texture coord of vertex i + virtual core::vector2df &getTCoords(u32 i) = 0; + + //! Append the vertices and indices to the current buffer + /** Only works for compatible vertex types. + \param vertices Pointer to a vertex array. + \param numVertices Number of vertices in the array. + \param indices Pointer to index array. + \param numIndices Number of indices in array. */ + virtual void append(const void *const vertices, u32 numVertices, const u16 *const indices, u32 numIndices) = 0; + + //! get the current hardware mapping hint + virtual E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const = 0; + + //! get the current hardware mapping hint + virtual E_HARDWARE_MAPPING getHardwareMappingHint_Index() const = 0; + + //! set the hardware mapping hint, for driver + virtual void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) = 0; + + //! flags the meshbuffer as changed, reloads hardware buffers + virtual void setDirty(E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) = 0; + + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + virtual u32 getChangedID_Vertex() const = 0; + + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + virtual u32 getChangedID_Index() const = 0; + + //! Used by the VideoDriver to remember the buffer link. + virtual void setHWBuffer(void *ptr) const = 0; + virtual void *getHWBuffer() const = 0; + + //! Describe what kind of primitive geometry is used by the meshbuffer + /** Note: Default is EPT_TRIANGLES. Using other types is fine for rendering. + But meshbuffer manipulation functions might expect type EPT_TRIANGLES + to work correctly. Also mesh writers will generally fail (badly!) with other + types than EPT_TRIANGLES. */ + virtual void setPrimitiveType(E_PRIMITIVE_TYPE type) = 0; + + //! Get the kind of primitive geometry which is used by the meshbuffer + virtual E_PRIMITIVE_TYPE getPrimitiveType() const = 0; + + //! Calculate how many geometric primitives are used by this meshbuffer + virtual u32 getPrimitiveCount() const { - public: - - //! Get the material of this meshbuffer - /** \return Material of this buffer. */ - virtual video::SMaterial& getMaterial() = 0; - - //! Get the material of this meshbuffer - /** \return Material of this buffer. */ - virtual const video::SMaterial& getMaterial() const = 0; - - //! Get type of vertex data which is stored in this meshbuffer. - /** \return Vertex type of this buffer. */ - virtual video::E_VERTEX_TYPE getVertexType() const = 0; - - //! Get access to vertex data. The data is an array of vertices. - /** Which vertex type is used can be determined by getVertexType(). - \return Pointer to array of vertices. */ - virtual const void* getVertices() const = 0; - - //! Get access to vertex data. The data is an array of vertices. - /** Which vertex type is used can be determined by getVertexType(). - \return Pointer to array of vertices. */ - virtual void* getVertices() = 0; - - //! Get amount of vertices in meshbuffer. - /** \return Number of vertices in this buffer. */ - virtual u32 getVertexCount() const = 0; - - //! Get type of index data which is stored in this meshbuffer. - /** \return Index type of this buffer. */ - virtual video::E_INDEX_TYPE getIndexType() const =0; - - //! Get access to indices. - /** \return Pointer to indices array. */ - virtual const u16* getIndices() const = 0; - - //! Get access to indices. - /** \return Pointer to indices array. */ - virtual u16* getIndices() = 0; - - //! Get amount of indices in this meshbuffer. - /** \return Number of indices in this buffer. */ - virtual u32 getIndexCount() const = 0; - - //! Get the axis aligned bounding box of this meshbuffer. - /** \return Axis aligned bounding box of this buffer. */ - virtual const core::aabbox3df& getBoundingBox() const = 0; - - //! Set axis aligned bounding box - /** \param box User defined axis aligned bounding box to use - for this buffer. */ - virtual void setBoundingBox(const core::aabbox3df& box) = 0; - - //! Recalculates the bounding box. Should be called if the mesh changed. - virtual void recalculateBoundingBox() = 0; - - //! returns position of vertex i - virtual const core::vector3df& getPosition(u32 i) const = 0; - - //! returns position of vertex i - virtual core::vector3df& getPosition(u32 i) = 0; - - //! returns normal of vertex i - virtual const core::vector3df& getNormal(u32 i) const = 0; - - //! returns normal of vertex i - virtual core::vector3df& getNormal(u32 i) = 0; - - //! returns texture coord of vertex i - virtual const core::vector2df& getTCoords(u32 i) const = 0; - - //! returns texture coord of vertex i - virtual core::vector2df& getTCoords(u32 i) = 0; - - //! Append the vertices and indices to the current buffer - /** Only works for compatible vertex types. - \param vertices Pointer to a vertex array. - \param numVertices Number of vertices in the array. - \param indices Pointer to index array. - \param numIndices Number of indices in array. */ - virtual void append(const void* const vertices, u32 numVertices, const u16* const indices, u32 numIndices) = 0; - - //! get the current hardware mapping hint - virtual E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const = 0; - - //! get the current hardware mapping hint - virtual E_HARDWARE_MAPPING getHardwareMappingHint_Index() const = 0; - - //! set the hardware mapping hint, for driver - virtual void setHardwareMappingHint( E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX ) = 0; - - //! flags the meshbuffer as changed, reloads hardware buffers - virtual void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) = 0; - - //! Get the currently used ID for identification of changes. - /** This shouldn't be used for anything outside the VideoDriver. */ - virtual u32 getChangedID_Vertex() const = 0; - - //! Get the currently used ID for identification of changes. - /** This shouldn't be used for anything outside the VideoDriver. */ - virtual u32 getChangedID_Index() const = 0; - - //! Used by the VideoDriver to remember the buffer link. - virtual void setHWBuffer(void *ptr) const = 0; - virtual void *getHWBuffer() const = 0; - - //! Describe what kind of primitive geometry is used by the meshbuffer - /** Note: Default is EPT_TRIANGLES. Using other types is fine for rendering. - But meshbuffer manipulation functions might expect type EPT_TRIANGLES - to work correctly. Also mesh writers will generally fail (badly!) with other - types than EPT_TRIANGLES. */ - virtual void setPrimitiveType(E_PRIMITIVE_TYPE type) = 0; - - //! Get the kind of primitive geometry which is used by the meshbuffer - virtual E_PRIMITIVE_TYPE getPrimitiveType() const = 0; - - //! Calculate how many geometric primitives are used by this meshbuffer - virtual u32 getPrimitiveCount() const - { - const u32 indexCount = getIndexCount(); - switch (getPrimitiveType()) - { - case scene::EPT_POINTS: return indexCount; - case scene::EPT_LINE_STRIP: return indexCount-1; - case scene::EPT_LINE_LOOP: return indexCount; - case scene::EPT_LINES: return indexCount/2; - case scene::EPT_TRIANGLE_STRIP: return (indexCount-2); - case scene::EPT_TRIANGLE_FAN: return (indexCount-2); - case scene::EPT_TRIANGLES: return indexCount/3; - case scene::EPT_POINT_SPRITES: return indexCount; - } - return 0; + const u32 indexCount = getIndexCount(); + switch (getPrimitiveType()) { + case scene::EPT_POINTS: + return indexCount; + case scene::EPT_LINE_STRIP: + return indexCount - 1; + case scene::EPT_LINE_LOOP: + return indexCount; + case scene::EPT_LINES: + return indexCount / 2; + case scene::EPT_TRIANGLE_STRIP: + return (indexCount - 2); + case scene::EPT_TRIANGLE_FAN: + return (indexCount - 2); + case scene::EPT_TRIANGLES: + return indexCount / 3; + case scene::EPT_POINT_SPRITES: + return indexCount; } - - }; + return 0; + } +}; } // end namespace scene } // end namespace irr diff --git a/include/IMeshCache.h b/include/IMeshCache.h index 1c2782b8..66052bfa 100644 --- a/include/IMeshCache.h +++ b/include/IMeshCache.h @@ -12,122 +12,120 @@ namespace irr namespace scene { - class IMesh; - class IAnimatedMesh; - class IAnimatedMeshSceneNode; - class IMeshLoader; +class IMesh; +class IAnimatedMesh; +class IAnimatedMeshSceneNode; +class IMeshLoader; - //! The mesh cache stores already loaded meshes and provides an interface to them. - /** You can access it using ISceneManager::getMeshCache(). All existing - scene managers will return a pointer to the same mesh cache, because it - is shared between them. With this interface, it is possible to manually - add new loaded meshes (if ISceneManager::getMesh() is not sufficient), - to remove them and to iterate through already loaded meshes. */ - class IMeshCache : public virtual IReferenceCounted - { - public: +//! The mesh cache stores already loaded meshes and provides an interface to them. +/** You can access it using ISceneManager::getMeshCache(). All existing +scene managers will return a pointer to the same mesh cache, because it +is shared between them. With this interface, it is possible to manually +add new loaded meshes (if ISceneManager::getMesh() is not sufficient), +to remove them and to iterate through already loaded meshes. */ +class IMeshCache : public virtual IReferenceCounted +{ +public: + //! Destructor + virtual ~IMeshCache() {} - //! Destructor - virtual ~IMeshCache() {} + //! Adds a mesh to the internal list of loaded meshes. + /** Usually, ISceneManager::getMesh() is called to load a mesh + from a file. That method searches the list of loaded meshes if + a mesh has already been loaded and returns a pointer to if it + is in that list and already in memory. Otherwise it loads the + mesh. With IMeshCache::addMesh(), it is possible to pretend + that a mesh already has been loaded. This method can be used + for example by mesh loaders who need to load more than one mesh + with one call. They can add additional meshes with this method + to the scene manager. The COLLADA loader for example uses this + method. + \param name Name of the mesh. When calling + ISceneManager::getMesh() with this name it will return the mesh + set by this method. + \param mesh Pointer to a mesh which will now be referenced by + this name. */ + virtual void addMesh(const io::path &name, IAnimatedMesh *mesh) = 0; - //! Adds a mesh to the internal list of loaded meshes. - /** Usually, ISceneManager::getMesh() is called to load a mesh - from a file. That method searches the list of loaded meshes if - a mesh has already been loaded and returns a pointer to if it - is in that list and already in memory. Otherwise it loads the - mesh. With IMeshCache::addMesh(), it is possible to pretend - that a mesh already has been loaded. This method can be used - for example by mesh loaders who need to load more than one mesh - with one call. They can add additional meshes with this method - to the scene manager. The COLLADA loader for example uses this - method. - \param name Name of the mesh. When calling - ISceneManager::getMesh() with this name it will return the mesh - set by this method. - \param mesh Pointer to a mesh which will now be referenced by - this name. */ - virtual void addMesh(const io::path& name, IAnimatedMesh* mesh) = 0; + //! Removes the mesh from the cache. + /** After loading a mesh with getMesh(), the mesh can be + removed from the cache using this method, freeing a lot of + memory. + \param mesh Pointer to the mesh which shall be removed. */ + virtual void removeMesh(const IMesh *const mesh) = 0; - //! Removes the mesh from the cache. - /** After loading a mesh with getMesh(), the mesh can be - removed from the cache using this method, freeing a lot of - memory. - \param mesh Pointer to the mesh which shall be removed. */ - virtual void removeMesh(const IMesh* const mesh) = 0; + //! Returns amount of loaded meshes in the cache. + /** You can load new meshes into the cache using getMesh() and + addMesh(). If you ever need to access the internal mesh cache, + you can do this using removeMesh(), getMeshNumber(), + getMeshByIndex() and getMeshName(). + \return Number of meshes in cache. */ + virtual u32 getMeshCount() const = 0; - //! Returns amount of loaded meshes in the cache. - /** You can load new meshes into the cache using getMesh() and - addMesh(). If you ever need to access the internal mesh cache, - you can do this using removeMesh(), getMeshNumber(), - getMeshByIndex() and getMeshName(). - \return Number of meshes in cache. */ - virtual u32 getMeshCount() const = 0; + //! Returns current index number of the mesh or -1 when not found. + /** \param mesh Pointer to the mesh to search for. + \return Index of the mesh in the cache, or -1 if not found. */ + virtual s32 getMeshIndex(const IMesh *const mesh) const = 0; - //! Returns current index number of the mesh or -1 when not found. - /** \param mesh Pointer to the mesh to search for. - \return Index of the mesh in the cache, or -1 if not found. */ - virtual s32 getMeshIndex(const IMesh* const mesh) const = 0; + //! Returns a mesh based on its index number. + /** \param index: Index of the mesh, number between 0 and + getMeshCount()-1. + Note that this number is only valid until a new mesh is loaded + or removed. + \return Pointer to the mesh or 0 if there is none with this + number. */ + virtual IAnimatedMesh *getMeshByIndex(u32 index) = 0; - //! Returns a mesh based on its index number. - /** \param index: Index of the mesh, number between 0 and - getMeshCount()-1. - Note that this number is only valid until a new mesh is loaded - or removed. - \return Pointer to the mesh or 0 if there is none with this - number. */ - virtual IAnimatedMesh* getMeshByIndex(u32 index) = 0; + //! Returns a mesh based on its name. + /** \param name Name of the mesh. Usually a filename. + \return Pointer to the mesh or 0 if there is none with this number. */ + virtual IAnimatedMesh *getMeshByName(const io::path &name) = 0; - //! Returns a mesh based on its name. - /** \param name Name of the mesh. Usually a filename. - \return Pointer to the mesh or 0 if there is none with this number. */ - virtual IAnimatedMesh* getMeshByName(const io::path& name) = 0; + //! Get the name of a loaded mesh, based on its index. + /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. + \return The name if mesh was found and has a name, else the path is empty. */ + virtual const io::SNamedPath &getMeshName(u32 index) const = 0; - //! Get the name of a loaded mesh, based on its index. - /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. - \return The name if mesh was found and has a name, else the path is empty. */ - virtual const io::SNamedPath& getMeshName(u32 index) const = 0; + //! Get the name of the loaded mesh if there is any. + /** \param mesh Pointer to mesh to query. + \return The name if mesh was found and has a name, else the path is empty. */ + virtual const io::SNamedPath &getMeshName(const IMesh *const mesh) const = 0; - //! Get the name of the loaded mesh if there is any. - /** \param mesh Pointer to mesh to query. - \return The name if mesh was found and has a name, else the path is empty. */ - virtual const io::SNamedPath& getMeshName(const IMesh* const mesh) const = 0; + //! Renames a loaded mesh. + /** Note that renaming meshes might change the ordering of the + meshes, and so the index of the meshes as returned by + getMeshIndex() or taken by some methods will change. + \param index The index of the mesh in the cache. + \param name New name for the mesh. + \return True if mesh was renamed. */ + virtual bool renameMesh(u32 index, const io::path &name) = 0; - //! Renames a loaded mesh. - /** Note that renaming meshes might change the ordering of the - meshes, and so the index of the meshes as returned by - getMeshIndex() or taken by some methods will change. - \param index The index of the mesh in the cache. - \param name New name for the mesh. - \return True if mesh was renamed. */ - virtual bool renameMesh(u32 index, const io::path& name) = 0; + //! Renames the loaded mesh + /** Note that renaming meshes might change the ordering of the + meshes, and so the index of the meshes as returned by + getMeshIndex() or taken by some methods will change. + \param mesh Mesh to be renamed. + \param name New name for the mesh. + \return True if mesh was renamed. */ + virtual bool renameMesh(const IMesh *const mesh, const io::path &name) = 0; - //! Renames the loaded mesh - /** Note that renaming meshes might change the ordering of the - meshes, and so the index of the meshes as returned by - getMeshIndex() or taken by some methods will change. - \param mesh Mesh to be renamed. - \param name New name for the mesh. - \return True if mesh was renamed. */ - virtual bool renameMesh(const IMesh* const mesh, const io::path& name) = 0; + //! Check if a mesh was already loaded. + /** \param name Name of the mesh. Usually a filename. + \return True if the mesh has been loaded, else false. */ + virtual bool isMeshLoaded(const io::path &name) = 0; - //! Check if a mesh was already loaded. - /** \param name Name of the mesh. Usually a filename. - \return True if the mesh has been loaded, else false. */ - virtual bool isMeshLoaded(const io::path& name) = 0; - - //! Clears the whole mesh cache, removing all meshes. - /** All meshes will be reloaded completely when using ISceneManager::getMesh() - after calling this method. - Warning: If you have pointers to meshes that were loaded with ISceneManager::getMesh() - and you did not grab them, then they may become invalid. */ - virtual void clear() = 0; - - //! Clears all meshes that are held in the mesh cache but not used anywhere else. - /** Warning: If you have pointers to meshes that were loaded with ISceneManager::getMesh() - and you did not grab them, then they may become invalid. */ - virtual void clearUnusedMeshes() = 0; - }; + //! Clears the whole mesh cache, removing all meshes. + /** All meshes will be reloaded completely when using ISceneManager::getMesh() + after calling this method. + Warning: If you have pointers to meshes that were loaded with ISceneManager::getMesh() + and you did not grab them, then they may become invalid. */ + virtual void clear() = 0; + //! Clears all meshes that are held in the mesh cache but not used anywhere else. + /** Warning: If you have pointers to meshes that were loaded with ISceneManager::getMesh() + and you did not grab them, then they may become invalid. */ + virtual void clearUnusedMeshes() = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/IMeshLoader.h b/include/IMeshLoader.h index 6162fb46..d1f2675e 100644 --- a/include/IMeshLoader.h +++ b/include/IMeshLoader.h @@ -11,11 +11,11 @@ namespace irr { namespace io { - class IReadFile; +class IReadFile; } // end namespace io namespace scene { - class IAnimatedMesh; +class IAnimatedMesh; //! Class which is able to load an animated mesh from a file. /** If you want Irrlicht be able to load meshes of @@ -25,7 +25,6 @@ ISceneManager::addExternalMeshLoader() to the engine. */ class IMeshLoader : public virtual IReferenceCounted { public: - //! Constructor IMeshLoader() {} @@ -37,16 +36,15 @@ public: only. \param filename Name of the file to test. \return True if the file might be loaded by this class. */ - virtual bool isALoadableFileExtension(const io::path& filename) const = 0; + virtual bool isALoadableFileExtension(const io::path &filename) const = 0; //! Creates/loads an animated mesh from the file. /** \param file File handler to load the file from. \return Pointer to the created mesh. Returns 0 if loading failed. If you no longer need the mesh, you should call IAnimatedMesh::drop(). See IReferenceCounted::drop() for more information. */ - virtual IAnimatedMesh* createMesh(io::IReadFile* file) = 0; + virtual IAnimatedMesh *createMesh(io::IReadFile *file) = 0; }; - } // end namespace scene } // end namespace irr diff --git a/include/IMeshManipulator.h b/include/IMeshManipulator.h index fe0d8e90..de3d8441 100644 --- a/include/IMeshManipulator.h +++ b/include/IMeshManipulator.h @@ -17,166 +17,153 @@ namespace irr namespace scene { - struct SMesh; +struct SMesh; - //! An interface for easy manipulation of meshes. - /** Scale, set alpha value, flip surfaces, and so on. This exists for - fixing problems with wrong imported or exported meshes quickly after - loading. It is not intended for doing mesh modifications and/or - animations during runtime. - */ - class IMeshManipulator : public virtual IReferenceCounted +//! An interface for easy manipulation of meshes. +/** Scale, set alpha value, flip surfaces, and so on. This exists for +fixing problems with wrong imported or exported meshes quickly after +loading. It is not intended for doing mesh modifications and/or +animations during runtime. +*/ +class IMeshManipulator : public virtual IReferenceCounted +{ +public: + //! Recalculates all normals of the mesh. + /** \param mesh: Mesh on which the operation is performed. + \param smooth: If the normals shall be smoothed. + \param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */ + virtual void recalculateNormals(IMesh *mesh, bool smooth = false, + bool angleWeighted = false) const = 0; + + //! Recalculates all normals of the mesh buffer. + /** \param buffer: Mesh buffer on which the operation is performed. + \param smooth: If the normals shall be smoothed. + \param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */ + virtual void recalculateNormals(IMeshBuffer *buffer, + bool smooth = false, bool angleWeighted = false) const = 0; + + //! Scales the actual mesh, not a scene node. + /** \param mesh Mesh on which the operation is performed. + \param factor Scale factor for each axis. */ + void scale(IMesh *mesh, const core::vector3df &factor) const { - public: + apply(SVertexPositionScaleManipulator(factor), mesh, true); + } - //! Recalculates all normals of the mesh. - /** \param mesh: Mesh on which the operation is performed. - \param smooth: If the normals shall be smoothed. - \param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */ - virtual void recalculateNormals(IMesh* mesh, bool smooth = false, - bool angleWeighted = false) const=0; + //! Scales the actual meshbuffer, not a scene node. + /** \param buffer Meshbuffer on which the operation is performed. + \param factor Scale factor for each axis. */ + void scale(IMeshBuffer *buffer, const core::vector3df &factor) const + { + apply(SVertexPositionScaleManipulator(factor), buffer, true); + } - //! Recalculates all normals of the mesh buffer. - /** \param buffer: Mesh buffer on which the operation is performed. - \param smooth: If the normals shall be smoothed. - \param angleWeighted: If the normals shall be smoothed in relation to their angles. More expensive, but also higher precision. */ - virtual void recalculateNormals(IMeshBuffer* buffer, - bool smooth = false, bool angleWeighted = false) const=0; + //! Clones a static IMesh into a modifiable SMesh. + /** All meshbuffers in the returned SMesh + are of type SMeshBuffer or SMeshBufferLightMap. + \param mesh Mesh to copy. + \return Cloned mesh. If you no longer need the + cloned mesh, you should call SMesh::drop(). See + IReferenceCounted::drop() for more information. */ + virtual SMesh *createMeshCopy(IMesh *mesh) const = 0; - //! Scales the actual mesh, not a scene node. - /** \param mesh Mesh on which the operation is performed. - \param factor Scale factor for each axis. */ - void scale(IMesh* mesh, const core::vector3df& factor) const - { - apply(SVertexPositionScaleManipulator(factor), mesh, true); - } + //! Get amount of polygons in mesh. + /** \param mesh Input mesh + \return Number of polygons in mesh. */ + virtual s32 getPolyCount(IMesh *mesh) const = 0; - //! Scales the actual meshbuffer, not a scene node. - /** \param buffer Meshbuffer on which the operation is performed. - \param factor Scale factor for each axis. */ - void scale(IMeshBuffer* buffer, const core::vector3df& factor) const - { - apply(SVertexPositionScaleManipulator(factor), buffer, true); - } + //! Get amount of polygons in mesh. + /** \param mesh Input mesh + \return Number of polygons in mesh. */ + virtual s32 getPolyCount(IAnimatedMesh *mesh) const = 0; - //! Clones a static IMesh into a modifiable SMesh. - /** All meshbuffers in the returned SMesh - are of type SMeshBuffer or SMeshBufferLightMap. - \param mesh Mesh to copy. - \return Cloned mesh. If you no longer need the - cloned mesh, you should call SMesh::drop(). See - IReferenceCounted::drop() for more information. */ - virtual SMesh* createMeshCopy(IMesh* mesh) const = 0; - - //! Get amount of polygons in mesh. - /** \param mesh Input mesh - \return Number of polygons in mesh. */ - virtual s32 getPolyCount(IMesh* mesh) const = 0; - - //! Get amount of polygons in mesh. - /** \param mesh Input mesh - \return Number of polygons in mesh. */ - virtual s32 getPolyCount(IAnimatedMesh* mesh) const = 0; - - //! Create a new AnimatedMesh and adds the mesh to it - /** \param mesh Input mesh - \param type The type of the animated mesh to create. - \return Newly created animated mesh with mesh as its only - content. When you don't need the animated mesh anymore, you - should call IAnimatedMesh::drop(). See - IReferenceCounted::drop() for more information. */ - virtual IAnimatedMesh * createAnimatedMesh(IMesh* mesh, + //! Create a new AnimatedMesh and adds the mesh to it + /** \param mesh Input mesh + \param type The type of the animated mesh to create. + \return Newly created animated mesh with mesh as its only + content. When you don't need the animated mesh anymore, you + should call IAnimatedMesh::drop(). See + IReferenceCounted::drop() for more information. */ + virtual IAnimatedMesh *createAnimatedMesh(IMesh *mesh, scene::E_ANIMATED_MESH_TYPE type = scene::EAMT_UNKNOWN) const = 0; - //! Apply a manipulator on the Meshbuffer - /** \param func A functor defining the mesh manipulation. - \param buffer The Meshbuffer to apply the manipulator to. - \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. - \return True if the functor was successfully applied, else false. */ - template - bool apply(const Functor& func, IMeshBuffer* buffer, bool boundingBoxUpdate=false) const - { - return apply_(func, buffer, boundingBoxUpdate, func); - } + //! Apply a manipulator on the Meshbuffer + /** \param func A functor defining the mesh manipulation. + \param buffer The Meshbuffer to apply the manipulator to. + \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. + \return True if the functor was successfully applied, else false. */ + template + bool apply(const Functor &func, IMeshBuffer *buffer, bool boundingBoxUpdate = false) const + { + return apply_(func, buffer, boundingBoxUpdate, func); + } - - //! Apply a manipulator on the Mesh - /** \param func A functor defining the mesh manipulation. - \param mesh The Mesh to apply the manipulator to. - \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. - \return True if the functor was successfully applied, else false. */ - template - bool apply(const Functor& func, IMesh* mesh, bool boundingBoxUpdate=false) const - { - if (!mesh) - return true; - bool result = true; - core::aabbox3df bufferbox; - for (u32 i=0; igetMeshBufferCount(); ++i) - { - result &= apply(func, mesh->getMeshBuffer(i), boundingBoxUpdate); - if (boundingBoxUpdate) - { - if (0==i) - bufferbox.reset(mesh->getMeshBuffer(i)->getBoundingBox()); - else - bufferbox.addInternalBox(mesh->getMeshBuffer(i)->getBoundingBox()); - } + //! Apply a manipulator on the Mesh + /** \param func A functor defining the mesh manipulation. + \param mesh The Mesh to apply the manipulator to. + \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. + \return True if the functor was successfully applied, else false. */ + template + bool apply(const Functor &func, IMesh *mesh, bool boundingBoxUpdate = false) const + { + if (!mesh) + return true; + bool result = true; + core::aabbox3df bufferbox; + for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) { + result &= apply(func, mesh->getMeshBuffer(i), boundingBoxUpdate); + if (boundingBoxUpdate) { + if (0 == i) + bufferbox.reset(mesh->getMeshBuffer(i)->getBoundingBox()); + else + bufferbox.addInternalBox(mesh->getMeshBuffer(i)->getBoundingBox()); } - if (boundingBoxUpdate) - mesh->setBoundingBox(bufferbox); - return result; } + if (boundingBoxUpdate) + mesh->setBoundingBox(bufferbox); + return result; + } protected: - //! Apply a manipulator based on the type of the functor - /** \param func A functor defining the mesh manipulation. - \param buffer The Meshbuffer to apply the manipulator to. - \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. - \param typeTest Unused parameter, which handles the proper call selection based on the type of the Functor which is passed in two times. - \return True if the functor was successfully applied, else false. */ - template - bool apply_(const Functor& func, IMeshBuffer* buffer, bool boundingBoxUpdate, const IVertexManipulator& typeTest) const - { - if (!buffer) - return true; - - core::aabbox3df bufferbox; - for (u32 i=0; igetVertexCount(); ++i) - { - switch (buffer->getVertexType()) - { - case video::EVT_STANDARD: - { - video::S3DVertex* verts = (video::S3DVertex*)buffer->getVertices(); - func(verts[i]); - } - break; - case video::EVT_2TCOORDS: - { - video::S3DVertex2TCoords* verts = (video::S3DVertex2TCoords*)buffer->getVertices(); - func(verts[i]); - } - break; - case video::EVT_TANGENTS: - { - video::S3DVertexTangents* verts = (video::S3DVertexTangents*)buffer->getVertices(); - func(verts[i]); - } - break; - } - if (boundingBoxUpdate) - { - if (0==i) - bufferbox.reset(buffer->getPosition(0)); - else - bufferbox.addInternalPoint(buffer->getPosition(i)); - } - } - if (boundingBoxUpdate) - buffer->setBoundingBox(bufferbox); + //! Apply a manipulator based on the type of the functor + /** \param func A functor defining the mesh manipulation. + \param buffer The Meshbuffer to apply the manipulator to. + \param boundingBoxUpdate Specifies if the bounding box should be updated during manipulation. + \param typeTest Unused parameter, which handles the proper call selection based on the type of the Functor which is passed in two times. + \return True if the functor was successfully applied, else false. */ + template + bool apply_(const Functor &func, IMeshBuffer *buffer, bool boundingBoxUpdate, const IVertexManipulator &typeTest) const + { + if (!buffer) return true; + + core::aabbox3df bufferbox; + for (u32 i = 0; i < buffer->getVertexCount(); ++i) { + switch (buffer->getVertexType()) { + case video::EVT_STANDARD: { + video::S3DVertex *verts = (video::S3DVertex *)buffer->getVertices(); + func(verts[i]); + } break; + case video::EVT_2TCOORDS: { + video::S3DVertex2TCoords *verts = (video::S3DVertex2TCoords *)buffer->getVertices(); + func(verts[i]); + } break; + case video::EVT_TANGENTS: { + video::S3DVertexTangents *verts = (video::S3DVertexTangents *)buffer->getVertices(); + func(verts[i]); + } break; + } + if (boundingBoxUpdate) { + if (0 == i) + bufferbox.reset(buffer->getPosition(0)); + else + bufferbox.addInternalPoint(buffer->getPosition(i)); + } } + if (boundingBoxUpdate) + buffer->setBoundingBox(bufferbox); + return true; + } }; } // end namespace scene diff --git a/include/IMeshSceneNode.h b/include/IMeshSceneNode.h index f31b4238..89b26dce 100644 --- a/include/IMeshSceneNode.h +++ b/include/IMeshSceneNode.h @@ -13,28 +13,26 @@ namespace scene class IMesh; - //! A scene node displaying a static mesh class IMeshSceneNode : public ISceneNode { public: - //! Constructor /** Use setMesh() to set the mesh to display. - */ - IMeshSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1,1,1)) - : ISceneNode(parent, mgr, id, position, rotation, scale) {} + */ + IMeshSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1, 1, 1)) : + ISceneNode(parent, mgr, id, position, rotation, scale) {} //! Sets a new mesh to display /** \param mesh Mesh to display. */ - virtual void setMesh(IMesh* mesh) = 0; + virtual void setMesh(IMesh *mesh) = 0; //! Get the currently defined mesh for display. /** \return Pointer to mesh which is displayed by this node. */ - virtual IMesh* getMesh(void) = 0; + virtual IMesh *getMesh(void) = 0; //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. /** In this way it is possible to change the materials of a mesh diff --git a/include/IOSOperator.h b/include/IOSOperator.h index 9f7d09b5..6164af5c 100644 --- a/include/IOSOperator.h +++ b/include/IOSOperator.h @@ -15,32 +15,31 @@ class IOSOperator : public virtual IReferenceCounted { public: //! Get the current OS version as string. - virtual const core::stringc& getOperatingSystemVersion() const = 0; + virtual const core::stringc &getOperatingSystemVersion() const = 0; //! Copies text to the clipboard //! \param text: text in utf-8 - virtual void copyToClipboard(const c8* text) const = 0; + virtual void copyToClipboard(const c8 *text) const = 0; //! Copies text to the primary selection //! This is a no-op on some platforms. //! \param text: text in utf-8 - virtual void copyToPrimarySelection(const c8* text) const = 0; + virtual void copyToPrimarySelection(const c8 *text) const = 0; //! Get text from the clipboard //! \return Returns 0 if no string is in there, otherwise an utf-8 string. - virtual const c8* getTextFromClipboard() const = 0; + virtual const c8 *getTextFromClipboard() const = 0; //! Get text from the primary selection //! This is a no-op on some platforms. //! \return Returns 0 if no string is in there, otherwise an utf-8 string. - virtual const c8* getTextFromPrimarySelection() const = 0; + virtual const c8 *getTextFromPrimarySelection() const = 0; //! Get the total and available system RAM /** \param totalBytes: will contain the total system memory in Kilobytes (1024 B) \param availableBytes: will contain the available memory in Kilobytes (1024 B) \return True if successful, false if not */ - virtual bool getSystemMemory(u32* totalBytes, u32* availableBytes) const = 0; - + virtual bool getSystemMemory(u32 *totalBytes, u32 *availableBytes) const = 0; }; } // end namespace diff --git a/include/IReadFile.h b/include/IReadFile.h index 3dab3b87..d3d97306 100644 --- a/include/IReadFile.h +++ b/include/IReadFile.h @@ -13,45 +13,45 @@ namespace irr namespace io { - //! Interface providing read access to a file. - class IReadFile : public virtual IReferenceCounted +//! Interface providing read access to a file. +class IReadFile : public virtual IReferenceCounted +{ +public: + //! Reads an amount of bytes from the file. + /** \param buffer Pointer to buffer where read bytes are written to. + \param sizeToRead Amount of bytes to read from the file. + \return How many bytes were read. */ + virtual size_t read(void *buffer, size_t sizeToRead) = 0; + + //! Changes position in file + /** \param finalPos Destination position in the file. + \param relativeMovement If set to true, the position in the file is + changed relative to current position. Otherwise the position is changed + from beginning of file. + \return True if successful, otherwise false. */ + virtual bool seek(long finalPos, bool relativeMovement = false) = 0; + + //! Get size of file. + /** \return Size of the file in bytes. */ + virtual long getSize() const = 0; + + //! Get the current position in the file. + /** \return Current position in the file in bytes on success or -1L on failure. */ + virtual long getPos() const = 0; + + //! Get name of file. + /** \return File name as zero terminated character string. */ + virtual const io::path &getFileName() const = 0; + + //! Get the type of the class implementing this interface + virtual EREAD_FILE_TYPE getType() const { - public: - //! Reads an amount of bytes from the file. - /** \param buffer Pointer to buffer where read bytes are written to. - \param sizeToRead Amount of bytes to read from the file. - \return How many bytes were read. */ - virtual size_t read(void* buffer, size_t sizeToRead) = 0; + return EFIT_UNKNOWN; + } +}; - //! Changes position in file - /** \param finalPos Destination position in the file. - \param relativeMovement If set to true, the position in the file is - changed relative to current position. Otherwise the position is changed - from beginning of file. - \return True if successful, otherwise false. */ - virtual bool seek(long finalPos, bool relativeMovement = false) = 0; - - //! Get size of file. - /** \return Size of the file in bytes. */ - virtual long getSize() const = 0; - - //! Get the current position in the file. - /** \return Current position in the file in bytes on success or -1L on failure. */ - virtual long getPos() const = 0; - - //! Get name of file. - /** \return File name as zero terminated character string. */ - virtual const io::path& getFileName() const = 0; - - //! Get the type of the class implementing this interface - virtual EREAD_FILE_TYPE getType() const - { - return EFIT_UNKNOWN; - } - }; - - //! Internal function, please do not use. - IReadFile* createLimitReadFile(const io::path& fileName, IReadFile* alreadyOpenedFile, long pos, long areaSize); +//! Internal function, please do not use. +IReadFile *createLimitReadFile(const io::path &fileName, IReadFile *alreadyOpenedFile, long pos, long areaSize); } // end namespace io } // end namespace irr diff --git a/include/IReferenceCounted.h b/include/IReferenceCounted.h index 3de94fa1..6f85bb90 100644 --- a/include/IReferenceCounted.h +++ b/include/IReferenceCounted.h @@ -9,158 +9,154 @@ namespace irr { - //! Base class of most objects of the Irrlicht Engine. - /** This class provides reference counting through the methods grab() and drop(). - It also is able to store a debug string for every instance of an object. - Most objects of the Irrlicht - Engine are derived from IReferenceCounted, and so they are reference counted. +//! Base class of most objects of the Irrlicht Engine. +/** This class provides reference counting through the methods grab() and drop(). +It also is able to store a debug string for every instance of an object. +Most objects of the Irrlicht +Engine are derived from IReferenceCounted, and so they are reference counted. - When you create an object in the Irrlicht engine, calling a method - which starts with 'create', an object is created, and you get a pointer - to the new object. If you no longer need the object, you have - to call drop(). This will destroy the object, if grab() was not called - in another part of you program, because this part still needs the object. - Note, that you only need to call drop() to the object, if you created it, - and the method had a 'create' in it. +When you create an object in the Irrlicht engine, calling a method +which starts with 'create', an object is created, and you get a pointer +to the new object. If you no longer need the object, you have +to call drop(). This will destroy the object, if grab() was not called +in another part of you program, because this part still needs the object. +Note, that you only need to call drop() to the object, if you created it, +and the method had a 'create' in it. + +A simple example: + +If you want to create a texture, you may want to call an imaginable method +IDriver::createTexture. You call +ITexture* texture = driver->createTexture(dimension2d(128, 128)); +If you no longer need the texture, call texture->drop(). + +If you want to load a texture, you may want to call imaginable method +IDriver::loadTexture. You do this like +ITexture* texture = driver->loadTexture("example.jpg"); +You will not have to drop the pointer to the loaded texture, because +the name of the method does not start with 'create'. The texture +is stored somewhere by the driver. +*/ +class IReferenceCounted +{ +public: + //! Constructor. + IReferenceCounted() : + DebugName(0), ReferenceCounter(1) + { + } + + //! Destructor. + virtual ~IReferenceCounted() + { + } + + //! Grabs the object. Increments the reference counter by one. + /** Someone who calls grab() to an object, should later also + call drop() to it. If an object never gets as much drop() as + grab() calls, it will never be destroyed. The + IReferenceCounted class provides a basic reference counting + mechanism with its methods grab() and drop(). Most objects of + the Irrlicht Engine are derived from IReferenceCounted, and so + they are reference counted. + + When you create an object in the Irrlicht engine, calling a + method which starts with 'create', an object is created, and + you get a pointer to the new object. If you no longer need the + object, you have to call drop(). This will destroy the object, + if grab() was not called in another part of you program, + because this part still needs the object. Note, that you only + need to call drop() to the object, if you created it, and the + method had a 'create' in it. A simple example: - If you want to create a texture, you may want to call an imaginable method - IDriver::createTexture. You call + If you want to create a texture, you may want to call an + imaginable method IDriver::createTexture. You call ITexture* texture = driver->createTexture(dimension2d(128, 128)); If you no longer need the texture, call texture->drop(). - - If you want to load a texture, you may want to call imaginable method - IDriver::loadTexture. You do this like + If you want to load a texture, you may want to call imaginable + method IDriver::loadTexture. You do this like ITexture* texture = driver->loadTexture("example.jpg"); - You will not have to drop the pointer to the loaded texture, because - the name of the method does not start with 'create'. The texture - is stored somewhere by the driver. - */ - class IReferenceCounted + You will not have to drop the pointer to the loaded texture, + because the name of the method does not start with 'create'. + The texture is stored somewhere by the driver. */ + void grab() const { ++ReferenceCounter; } + + //! Drops the object. Decrements the reference counter by one. + /** The IReferenceCounted class provides a basic reference + counting mechanism with its methods grab() and drop(). Most + objects of the Irrlicht Engine are derived from + IReferenceCounted, and so they are reference counted. + + When you create an object in the Irrlicht engine, calling a + method which starts with 'create', an object is created, and + you get a pointer to the new object. If you no longer need the + object, you have to call drop(). This will destroy the object, + if grab() was not called in another part of you program, + because this part still needs the object. Note, that you only + need to call drop() to the object, if you created it, and the + method had a 'create' in it. + + A simple example: + + If you want to create a texture, you may want to call an + imaginable method IDriver::createTexture. You call + ITexture* texture = driver->createTexture(dimension2d(128, 128)); + If you no longer need the texture, call texture->drop(). + If you want to load a texture, you may want to call imaginable + method IDriver::loadTexture. You do this like + ITexture* texture = driver->loadTexture("example.jpg"); + You will not have to drop the pointer to the loaded texture, + because the name of the method does not start with 'create'. + The texture is stored somewhere by the driver. + \return True, if the object was deleted. */ + bool drop() const { - public: + // someone is doing bad reference counting. + _IRR_DEBUG_BREAK_IF(ReferenceCounter <= 0) - //! Constructor. - IReferenceCounted() - : DebugName(0), ReferenceCounter(1) - { + --ReferenceCounter; + if (!ReferenceCounter) { + delete this; + return true; } - //! Destructor. - virtual ~IReferenceCounted() - { - } + return false; + } - //! Grabs the object. Increments the reference counter by one. - /** Someone who calls grab() to an object, should later also - call drop() to it. If an object never gets as much drop() as - grab() calls, it will never be destroyed. The - IReferenceCounted class provides a basic reference counting - mechanism with its methods grab() and drop(). Most objects of - the Irrlicht Engine are derived from IReferenceCounted, and so - they are reference counted. + //! Get the reference count. + /** \return Current value of the reference counter. */ + s32 getReferenceCount() const + { + return ReferenceCounter; + } - When you create an object in the Irrlicht engine, calling a - method which starts with 'create', an object is created, and - you get a pointer to the new object. If you no longer need the - object, you have to call drop(). This will destroy the object, - if grab() was not called in another part of you program, - because this part still needs the object. Note, that you only - need to call drop() to the object, if you created it, and the - method had a 'create' in it. + //! Returns the debug name of the object. + /** The Debugname may only be set and changed by the object + itself. This method should only be used in Debug mode. + \return Returns a string, previously set by setDebugName(); */ + const c8 *getDebugName() const + { + return DebugName; + } - A simple example: +protected: + //! Sets the debug name of the object. + /** The Debugname may only be set and changed by the object + itself. This method should only be used in Debug mode. + \param newName: New debug name to set. */ + void setDebugName(const c8 *newName) + { + DebugName = newName; + } - If you want to create a texture, you may want to call an - imaginable method IDriver::createTexture. You call - ITexture* texture = driver->createTexture(dimension2d(128, 128)); - If you no longer need the texture, call texture->drop(). - If you want to load a texture, you may want to call imaginable - method IDriver::loadTexture. You do this like - ITexture* texture = driver->loadTexture("example.jpg"); - You will not have to drop the pointer to the loaded texture, - because the name of the method does not start with 'create'. - The texture is stored somewhere by the driver. */ - void grab() const { ++ReferenceCounter; } +private: + //! The debug name. + const c8 *DebugName; - //! Drops the object. Decrements the reference counter by one. - /** The IReferenceCounted class provides a basic reference - counting mechanism with its methods grab() and drop(). Most - objects of the Irrlicht Engine are derived from - IReferenceCounted, and so they are reference counted. - - When you create an object in the Irrlicht engine, calling a - method which starts with 'create', an object is created, and - you get a pointer to the new object. If you no longer need the - object, you have to call drop(). This will destroy the object, - if grab() was not called in another part of you program, - because this part still needs the object. Note, that you only - need to call drop() to the object, if you created it, and the - method had a 'create' in it. - - A simple example: - - If you want to create a texture, you may want to call an - imaginable method IDriver::createTexture. You call - ITexture* texture = driver->createTexture(dimension2d(128, 128)); - If you no longer need the texture, call texture->drop(). - If you want to load a texture, you may want to call imaginable - method IDriver::loadTexture. You do this like - ITexture* texture = driver->loadTexture("example.jpg"); - You will not have to drop the pointer to the loaded texture, - because the name of the method does not start with 'create'. - The texture is stored somewhere by the driver. - \return True, if the object was deleted. */ - bool drop() const - { - // someone is doing bad reference counting. - _IRR_DEBUG_BREAK_IF(ReferenceCounter <= 0) - - --ReferenceCounter; - if (!ReferenceCounter) - { - delete this; - return true; - } - - return false; - } - - //! Get the reference count. - /** \return Current value of the reference counter. */ - s32 getReferenceCount() const - { - return ReferenceCounter; - } - - //! Returns the debug name of the object. - /** The Debugname may only be set and changed by the object - itself. This method should only be used in Debug mode. - \return Returns a string, previously set by setDebugName(); */ - const c8* getDebugName() const - { - return DebugName; - } - - protected: - - //! Sets the debug name of the object. - /** The Debugname may only be set and changed by the object - itself. This method should only be used in Debug mode. - \param newName: New debug name to set. */ - void setDebugName(const c8* newName) - { - DebugName = newName; - } - - private: - - //! The debug name. - const c8* DebugName; - - //! The reference counter. Mutable to do reference counting on const objects. - mutable s32 ReferenceCounter; - }; + //! The reference counter. Mutable to do reference counting on const objects. + mutable s32 ReferenceCounter; +}; } // end namespace irr diff --git a/include/IRenderTarget.h b/include/IRenderTarget.h index c0fb1bbe..1e70c1e0 100644 --- a/include/IRenderTarget.h +++ b/include/IRenderTarget.h @@ -12,115 +12,108 @@ namespace irr { namespace video { - class ITexture; +class ITexture; - //! Enumeration of cube texture surfaces - enum E_CUBE_SURFACE +//! Enumeration of cube texture surfaces +enum E_CUBE_SURFACE +{ + ECS_POSX = 0, + ECS_NEGX, + ECS_POSY, + ECS_NEGY, + ECS_POSZ, + ECS_NEGZ +}; + +//! Interface of a Render Target. +class IRenderTarget : public virtual IReferenceCounted +{ +public: + //! constructor + IRenderTarget() : + DepthStencil(0), DriverType(EDT_NULL) { - ECS_POSX = 0, - ECS_NEGX, - ECS_POSY, - ECS_NEGY, - ECS_POSZ, - ECS_NEGZ - }; + } - //! Interface of a Render Target. - class IRenderTarget : public virtual IReferenceCounted + //! Returns an array of previously set textures. + const core::array &getTexture() const { - public: + return Textures; + } - //! constructor - IRenderTarget() : DepthStencil(0), DriverType(EDT_NULL) - { + //! Returns a of previously set depth / depth-stencil texture. + ITexture *getDepthStencil() const + { + return DepthStencil; + } + + //! Returns an array of active surface for cube textures + const core::array &getCubeSurfaces() const + { + return CubeSurfaces; + } + + //! Set multiple textures. + /** Set multiple textures for the render target. + \param texture Array of texture objects. These textures are used for a color outputs. + \param depthStencil Depth or packed depth-stencil texture. This texture is used as depth + or depth-stencil buffer. You can pass getDepthStencil() if you don't want to change it. + \param cubeSurfaces When rendering to cube textures, set the surface to be used for each texture. Can be empty otherwise. + */ + void setTexture(const core::array &texture, ITexture *depthStencil, const core::array &cubeSurfaces = core::array()) + { + setTextures(texture.const_pointer(), texture.size(), depthStencil, cubeSurfaces.const_pointer(), cubeSurfaces.size()); + } + + //! Sets one texture + depthStencil + //! You can pass getDepthStencil() for depthStencil if you don't want to change that one + void setTexture(ITexture *texture, ITexture *depthStencil) + { + if (texture) { + setTextures(&texture, 1, depthStencil); + } else { + setTextures(0, 0, depthStencil); } + } - //! Returns an array of previously set textures. - const core::array& getTexture() const - { - return Textures; + //! Set one cube surface texture. + void setTexture(ITexture *texture, ITexture *depthStencil, E_CUBE_SURFACE cubeSurface) + { + if (texture) { + setTextures(&texture, 1, depthStencil, &cubeSurface, 1); + } else { + setTextures(0, 0, depthStencil, &cubeSurface, 1); } + } - //! Returns a of previously set depth / depth-stencil texture. - ITexture* getDepthStencil() const - { - return DepthStencil; - } + //! Get driver type of render target. + E_DRIVER_TYPE getDriverType() const + { + return DriverType; + } - //! Returns an array of active surface for cube textures - const core::array& getCubeSurfaces() const - { - return CubeSurfaces; - } +protected: + //! Set multiple textures. + // NOTE: working with pointers instead of arrays to avoid unnecessary memory allocations for the single textures case + virtual void setTextures(ITexture *const *textures, u32 numTextures, ITexture *depthStencil, const E_CUBE_SURFACE *cubeSurfaces = 0, u32 numCubeSurfaces = 0) = 0; - //! Set multiple textures. - /** Set multiple textures for the render target. - \param texture Array of texture objects. These textures are used for a color outputs. - \param depthStencil Depth or packed depth-stencil texture. This texture is used as depth - or depth-stencil buffer. You can pass getDepthStencil() if you don't want to change it. - \param cubeSurfaces When rendering to cube textures, set the surface to be used for each texture. Can be empty otherwise. - */ - void setTexture(const core::array& texture, ITexture* depthStencil, const core::array& cubeSurfaces = core::array()) - { - setTextures(texture.const_pointer(), texture.size(), depthStencil, cubeSurfaces.const_pointer(), cubeSurfaces.size()); - } + //! Textures assigned to render target. + core::array Textures; - //! Sets one texture + depthStencil - //! You can pass getDepthStencil() for depthStencil if you don't want to change that one - void setTexture(ITexture* texture, ITexture* depthStencil) - { - if ( texture ) - { - setTextures(&texture, 1, depthStencil); - } - else - { - setTextures(0, 0, depthStencil); - } - } + //! Depth or packed depth-stencil texture assigned to render target. + ITexture *DepthStencil; - //! Set one cube surface texture. - void setTexture(ITexture* texture, ITexture* depthStencil, E_CUBE_SURFACE cubeSurface) - { - if ( texture ) - { - setTextures(&texture, 1, depthStencil, &cubeSurface, 1); - } - else - { - setTextures(0, 0, depthStencil, &cubeSurface, 1); - } - } + //! Active surface of cube textures + core::array CubeSurfaces; - //! Get driver type of render target. - E_DRIVER_TYPE getDriverType() const - { - return DriverType; - } + //! Driver type of render target. + E_DRIVER_TYPE DriverType; - protected: - - //! Set multiple textures. - // NOTE: working with pointers instead of arrays to avoid unnecessary memory allocations for the single textures case - virtual void setTextures(ITexture* const * textures, u32 numTextures, ITexture* depthStencil, const E_CUBE_SURFACE* cubeSurfaces=0, u32 numCubeSurfaces=0) = 0; - - //! Textures assigned to render target. - core::array Textures; - - //! Depth or packed depth-stencil texture assigned to render target. - ITexture* DepthStencil; - - //! Active surface of cube textures - core::array CubeSurfaces; - - //! Driver type of render target. - E_DRIVER_TYPE DriverType; - - private: - // no copying (IReferenceCounted still allows that for reasons which take some time to work around) - IRenderTarget(const IRenderTarget&); - IRenderTarget& operator=(const IRenderTarget&); - }; +private: + // no copying (IReferenceCounted still allows that for reasons which take some time to work around) + IRenderTarget(const IRenderTarget &); + IRenderTarget &operator=(const IRenderTarget &); +}; } } diff --git a/include/ISceneCollisionManager.h b/include/ISceneCollisionManager.h index 200e8c08..3307dc6b 100644 --- a/include/ISceneCollisionManager.h +++ b/include/ISceneCollisionManager.h @@ -13,23 +13,21 @@ namespace irr namespace scene { - class ICameraSceneNode; +class ICameraSceneNode; - class ISceneCollisionManager : public virtual IReferenceCounted - { - public: - - //! Returns a 3d ray which would go through the 2d screen coordinates. - /** \param pos: Screen coordinates in pixels. - \param camera: Camera from which the ray starts. If null, the - active camera is used. - \return Ray starting from the position of the camera and ending - at a length of the far value of the camera at a position which - would be behind the 2d screen coordinates. */ - virtual core::line3d getRayFromScreenCoordinates( - const core::position2d& pos, const ICameraSceneNode* camera = 0) = 0; - - }; +class ISceneCollisionManager : public virtual IReferenceCounted +{ +public: + //! Returns a 3d ray which would go through the 2d screen coordinates. + /** \param pos: Screen coordinates in pixels. + \param camera: Camera from which the ray starts. If null, the + active camera is used. + \return Ray starting from the position of the camera and ending + at a length of the far value of the camera at a position which + would be behind the 2d screen coordinates. */ + virtual core::line3d getRayFromScreenCoordinates( + const core::position2d &pos, const ICameraSceneNode *camera = 0) = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/ISceneManager.h b/include/ISceneManager.h index 46102c10..c247c4b9 100644 --- a/include/ISceneManager.h +++ b/include/ISceneManager.h @@ -17,618 +17,616 @@ namespace irr { - struct SKeyMap; - struct SEvent; +struct SKeyMap; +struct SEvent; namespace io { - class IReadFile; - class IAttributes; - class IWriteFile; - class IFileSystem; +class IReadFile; +class IAttributes; +class IWriteFile; +class IFileSystem; } // end namespace io namespace gui { - class IGUIFont; - class IGUIEnvironment; +class IGUIFont; +class IGUIEnvironment; } // end namespace gui namespace video { - class IVideoDriver; - class SMaterial; - class IImage; - class ITexture; +class IVideoDriver; +class SMaterial; +class IImage; +class ITexture; } // end namespace video namespace scene { - //! Enumeration for render passes. - /** A parameter passed to the registerNodeForRendering() method of the ISceneManager, - specifying when the node wants to be drawn in relation to the other nodes. - Note: Despite the numbering this is not used as bit-field. - */ - enum E_SCENE_NODE_RENDER_PASS - { - //! No pass currently active - ESNRP_NONE =0, +//! Enumeration for render passes. +/** A parameter passed to the registerNodeForRendering() method of the ISceneManager, +specifying when the node wants to be drawn in relation to the other nodes. +Note: Despite the numbering this is not used as bit-field. +*/ +enum E_SCENE_NODE_RENDER_PASS +{ + //! No pass currently active + ESNRP_NONE = 0, - //! Camera pass. The active view is set up here. The very first pass. - ESNRP_CAMERA =1, + //! Camera pass. The active view is set up here. The very first pass. + ESNRP_CAMERA = 1, - //! In this pass, lights are transformed into camera space and added to the driver - ESNRP_LIGHT =2, + //! In this pass, lights are transformed into camera space and added to the driver + ESNRP_LIGHT = 2, - //! This is used for sky boxes. - ESNRP_SKY_BOX =4, + //! This is used for sky boxes. + ESNRP_SKY_BOX = 4, - //! All normal objects can use this for registering themselves. - /** This value will never be returned by - ISceneManager::getSceneNodeRenderPass(). The scene manager - will determine by itself if an object is transparent or solid - and register the object as ESNRT_TRANSPARENT or ESNRP_SOLID - automatically if you call registerNodeForRendering with this - value (which is default). Note that it will register the node - only as ONE type. If your scene node has both solid and - transparent material types register it twice (one time as - ESNRP_SOLID, the other time as ESNRT_TRANSPARENT) and in the - render() method call getSceneNodeRenderPass() to find out the - current render pass and render only the corresponding parts of - the node. */ - ESNRP_AUTOMATIC =24, + //! All normal objects can use this for registering themselves. + /** This value will never be returned by + ISceneManager::getSceneNodeRenderPass(). The scene manager + will determine by itself if an object is transparent or solid + and register the object as ESNRT_TRANSPARENT or ESNRP_SOLID + automatically if you call registerNodeForRendering with this + value (which is default). Note that it will register the node + only as ONE type. If your scene node has both solid and + transparent material types register it twice (one time as + ESNRP_SOLID, the other time as ESNRT_TRANSPARENT) and in the + render() method call getSceneNodeRenderPass() to find out the + current render pass and render only the corresponding parts of + the node. */ + ESNRP_AUTOMATIC = 24, - //! Solid scene nodes or special scene nodes without materials. - ESNRP_SOLID =8, + //! Solid scene nodes or special scene nodes without materials. + ESNRP_SOLID = 8, - //! Transparent scene nodes, drawn after solid nodes. They are sorted from back to front and drawn in that order. - ESNRP_TRANSPARENT =16, + //! Transparent scene nodes, drawn after solid nodes. They are sorted from back to front and drawn in that order. + ESNRP_TRANSPARENT = 16, - //! Transparent effect scene nodes, drawn after Transparent nodes. They are sorted from back to front and drawn in that order. - ESNRP_TRANSPARENT_EFFECT =32, + //! Transparent effect scene nodes, drawn after Transparent nodes. They are sorted from back to front and drawn in that order. + ESNRP_TRANSPARENT_EFFECT = 32, - //! Drawn after the solid nodes, before the transparent nodes, the time for drawing shadow volumes - ESNRP_SHADOW =64, + //! Drawn after the solid nodes, before the transparent nodes, the time for drawing shadow volumes + ESNRP_SHADOW = 64, - //! Drawn after transparent effect nodes. For custom gui's. Unsorted (in order nodes registered themselves). - ESNRP_GUI = 128 + //! Drawn after transparent effect nodes. For custom gui's. Unsorted (in order nodes registered themselves). + ESNRP_GUI = 128 - }; +}; - class IAnimatedMesh; - class IAnimatedMeshSceneNode; - class IBillboardSceneNode; - class ICameraSceneNode; - class IDummyTransformationSceneNode; - class IMesh; - class IMeshBuffer; - class IMeshCache; - class ISceneCollisionManager; - class IMeshLoader; - class IMeshManipulator; - class IMeshSceneNode; - class ISceneNode; - class ISceneNodeFactory; +class IAnimatedMesh; +class IAnimatedMeshSceneNode; +class IBillboardSceneNode; +class ICameraSceneNode; +class IDummyTransformationSceneNode; +class IMesh; +class IMeshBuffer; +class IMeshCache; +class ISceneCollisionManager; +class IMeshLoader; +class IMeshManipulator; +class IMeshSceneNode; +class ISceneNode; +class ISceneNodeFactory; - //! The Scene Manager manages scene nodes, mesh resources, cameras and all the other stuff. - /** All Scene nodes can be created only here. - A scene node is a node in the hierarchical scene graph. Every scene node - may have children, which are other scene nodes. Children move relative - the their parents position. If the parent of a node is not visible, its - children won't be visible, too. In this way, it is for example easily - possible to attach a light to a moving car or to place a walking - character on a moving platform on a moving ship. - The SceneManager is also able to load 3d mesh files of different - formats. Take a look at getMesh() to find out what formats are - supported. If these formats are not enough, use - addExternalMeshLoader() to add new formats to the engine. - */ - class ISceneManager : public virtual IReferenceCounted - { - public: +//! The Scene Manager manages scene nodes, mesh resources, cameras and all the other stuff. +/** All Scene nodes can be created only here. +A scene node is a node in the hierarchical scene graph. Every scene node +may have children, which are other scene nodes. Children move relative +the their parents position. If the parent of a node is not visible, its +children won't be visible, too. In this way, it is for example easily +possible to attach a light to a moving car or to place a walking +character on a moving platform on a moving ship. +The SceneManager is also able to load 3d mesh files of different +formats. Take a look at getMesh() to find out what formats are +supported. If these formats are not enough, use +addExternalMeshLoader() to add new formats to the engine. +*/ +class ISceneManager : public virtual IReferenceCounted +{ +public: + //! Get pointer to an animatable mesh. Loads the file if not loaded already. + /** + * If you want to remove a loaded mesh from the cache again, use removeMesh(). + * Currently there are the following mesh formats supported: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
FormatDescription
3D Studio (.3ds)Loader for 3D-Studio files which lots of 3D packages + * are able to export. Only static meshes are currently + * supported by this importer.
3D World Studio (.smf)Loader for Leadwerks SMF mesh files, a simple mesh format + * containing static geometry for games. The proprietary .STF texture format + * is not supported yet. This loader was originally written by Joseph Ellis.
Bliz Basic B3D (.b3d)Loader for blitz basic files, developed by Mark + * Sibly. This is the ideal animated mesh format for game + * characters as it is both rigidly defined and widely + * supported by modeling and animation software. + * As this format supports skeletal animations, an + * ISkinnedMesh will be returned by this importer.
Cartography shop 4 (.csm)Cartography Shop is a modeling program for creating + * architecture and calculating lighting. Irrlicht can + * directly import .csm files thanks to the IrrCSM library + * created by Saurav Mohapatra which is now integrated + * directly in Irrlicht. + *
Delgine DeleD (.dmf)DeleD (delgine.com) is a 3D editor and level-editor + * combined into one and is specifically designed for 3D + * game-development. With this loader, it is possible to + * directly load all geometry is as well as textures and + * lightmaps from .dmf files. To set texture and + * material paths, see scene::DMF_USE_MATERIALS_DIRS. + * It is also possible to flip the alpha texture by setting + * scene::DMF_FLIP_ALPHA_TEXTURES to true and to set the + * material transparent reference value by setting + * scene::DMF_ALPHA_CHANNEL_REF to a float between 0 and + * 1. The loader is based on Salvatore Russo's .dmf + * loader, I just changed some parts of it. Thanks to + * Salvatore for his work and for allowing me to use his + * code in Irrlicht and put it under Irrlicht's license. + * For newer and more enhanced versions of the loader, + * take a look at delgine.com. + *
DirectX (.x)Platform independent importer (so not D3D-only) for + * .x files. Most 3D packages can export these natively + * and there are several tools for them available, e.g. + * the Maya exporter included in the DX SDK. + * .x files can include skeletal animations and Irrlicht + * is able to play and display them, users can manipulate + * the joints via the ISkinnedMesh interface. Currently, + * Irrlicht only supports uncompressed .x files.
Half-Life model (.mdl)This loader opens Half-life 1 models, it was contributed + * by Fabio Concas and adapted by Thomas Alten.
LightWave (.lwo)Native to NewTek's LightWave 3D, the LWO format is well + * known and supported by many exporters. This loader will + * import LWO2 models including lightmaps, bumpmaps and + * reflection textures.
Maya (.obj)Most 3D software can create .obj files which contain + * static geometry without material data. The material + * files .mtl are also supported. This importer for + * Irrlicht can load them directly.
Milkshape (.ms3d).MS3D files contain models and sometimes skeletal + * animations from the Milkshape 3D modeling and animation + * software. Like the other skeletal mesh loaders, joints + * are exposed via the ISkinnedMesh animated mesh type.
My3D (.my3d).my3D is a flexible 3D file format. The My3DTools + * contains plug-ins to export .my3D files from several + * 3D packages. With this built-in importer, Irrlicht + * can read and display those files directly. This + * loader was written by Zhuck Dimitry who also created + * the whole My3DTools package. + *
OCT (.oct)The oct file format contains 3D geometry and + * lightmaps and can be loaded directly by Irrlicht. OCT + * files
can be created by FSRad, Paul Nette's + * radiosity processor or exported from Blender using + * OCTTools which can be found in the exporters/OCTTools + * directory of the SDK. Thanks to Murphy McCauley for + * creating all this.
OGRE Meshes (.mesh)Ogre .mesh files contain 3D data for the OGRE 3D + * engine. Irrlicht can read and display them directly + * with this importer. To define materials for the mesh, + * copy a .material file named like the corresponding + * .mesh file where the .mesh file is. (For example + * ogrehead.material for ogrehead.mesh). Thanks to + * Christian Stehno who wrote and contributed this + * loader.
Pulsar LMTools (.lmts)LMTools is a set of tools (Windows & Linux) for + * creating lightmaps. Irrlicht can directly read .lmts + * files thanks to
the importer created by Jonas + * Petersen. + * Notes for
this version of the loader:
+ * - It does not recognize/support user data in the + * *.lmts files.
+ * - The TGAs generated by LMTools don't work in + * Irrlicht for some reason (the textures are upside + * down). Opening and resaving them in a graphics app + * will solve the problem.
Quake 3 levels (.bsp)Quake 3 is a popular game by IDSoftware, and .pk3 + * files contain .bsp files and textures/lightmaps + * describing huge prelighted levels. Irrlicht can read + * .pk3 and .bsp files directly and thus render Quake 3 + * levels directly. Written by Nikolaus Gebhardt + * enhanced by Dean P. Macri with the curved surfaces + * feature.
Quake 2 models (.md2)Quake 2 models are characters with morph target + * animation. Irrlicht can read, display and animate + * them directly with this importer.
Quake 3 models (.md3)Quake 3 models are characters with morph target + * animation, they contain mount points for weapons and body + * parts and are typically made of several sections which are + * manually joined together.
Stanford Triangle (.ply)Invented by Stanford University and known as the native + * format of the infamous "Stanford Bunny" model, this is a + * popular static mesh format used by 3D scanning hardware + * and software. This loader supports extremely large models + * in both ASCII and binary format, but only has rudimentary + * material support in the form of vertex colors and texture + * coordinates.
Stereolithography (.stl)The STL format is used for rapid prototyping and + * computer-aided manufacturing, thus has no support for + * materials.
+ * + * To load and display a mesh quickly, just do this: + * \code + * SceneManager->addAnimatedMeshSceneNode( + * SceneManager->getMesh("yourmesh.3ds")); + * \endcode + * If you would like to implement and add your own file format loader to Irrlicht, + * see addExternalMeshLoader(). + * \param file File handle of the mesh to load. + * \return Null if failed, otherwise pointer to the mesh. + * This pointer should not be dropped. See IReferenceCounted::drop() for more information. + **/ + virtual IAnimatedMesh *getMesh(io::IReadFile *file) = 0; - //! Get pointer to an animatable mesh. Loads the file if not loaded already. - /** - * If you want to remove a loaded mesh from the cache again, use removeMesh(). - * Currently there are the following mesh formats supported: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
FormatDescription
3D Studio (.3ds)Loader for 3D-Studio files which lots of 3D packages - * are able to export. Only static meshes are currently - * supported by this importer.
3D World Studio (.smf)Loader for Leadwerks SMF mesh files, a simple mesh format - * containing static geometry for games. The proprietary .STF texture format - * is not supported yet. This loader was originally written by Joseph Ellis.
Bliz Basic B3D (.b3d)Loader for blitz basic files, developed by Mark - * Sibly. This is the ideal animated mesh format for game - * characters as it is both rigidly defined and widely - * supported by modeling and animation software. - * As this format supports skeletal animations, an - * ISkinnedMesh will be returned by this importer.
Cartography shop 4 (.csm)Cartography Shop is a modeling program for creating - * architecture and calculating lighting. Irrlicht can - * directly import .csm files thanks to the IrrCSM library - * created by Saurav Mohapatra which is now integrated - * directly in Irrlicht. - *
Delgine DeleD (.dmf)DeleD (delgine.com) is a 3D editor and level-editor - * combined into one and is specifically designed for 3D - * game-development. With this loader, it is possible to - * directly load all geometry is as well as textures and - * lightmaps from .dmf files. To set texture and - * material paths, see scene::DMF_USE_MATERIALS_DIRS. - * It is also possible to flip the alpha texture by setting - * scene::DMF_FLIP_ALPHA_TEXTURES to true and to set the - * material transparent reference value by setting - * scene::DMF_ALPHA_CHANNEL_REF to a float between 0 and - * 1. The loader is based on Salvatore Russo's .dmf - * loader, I just changed some parts of it. Thanks to - * Salvatore for his work and for allowing me to use his - * code in Irrlicht and put it under Irrlicht's license. - * For newer and more enhanced versions of the loader, - * take a look at delgine.com. - *
DirectX (.x)Platform independent importer (so not D3D-only) for - * .x files. Most 3D packages can export these natively - * and there are several tools for them available, e.g. - * the Maya exporter included in the DX SDK. - * .x files can include skeletal animations and Irrlicht - * is able to play and display them, users can manipulate - * the joints via the ISkinnedMesh interface. Currently, - * Irrlicht only supports uncompressed .x files.
Half-Life model (.mdl)This loader opens Half-life 1 models, it was contributed - * by Fabio Concas and adapted by Thomas Alten.
LightWave (.lwo)Native to NewTek's LightWave 3D, the LWO format is well - * known and supported by many exporters. This loader will - * import LWO2 models including lightmaps, bumpmaps and - * reflection textures.
Maya (.obj)Most 3D software can create .obj files which contain - * static geometry without material data. The material - * files .mtl are also supported. This importer for - * Irrlicht can load them directly.
Milkshape (.ms3d).MS3D files contain models and sometimes skeletal - * animations from the Milkshape 3D modeling and animation - * software. Like the other skeletal mesh loaders, joints - * are exposed via the ISkinnedMesh animated mesh type.
My3D (.my3d).my3D is a flexible 3D file format. The My3DTools - * contains plug-ins to export .my3D files from several - * 3D packages. With this built-in importer, Irrlicht - * can read and display those files directly. This - * loader was written by Zhuck Dimitry who also created - * the whole My3DTools package. - *
OCT (.oct)The oct file format contains 3D geometry and - * lightmaps and can be loaded directly by Irrlicht. OCT - * files
can be created by FSRad, Paul Nette's - * radiosity processor or exported from Blender using - * OCTTools which can be found in the exporters/OCTTools - * directory of the SDK. Thanks to Murphy McCauley for - * creating all this.
OGRE Meshes (.mesh)Ogre .mesh files contain 3D data for the OGRE 3D - * engine. Irrlicht can read and display them directly - * with this importer. To define materials for the mesh, - * copy a .material file named like the corresponding - * .mesh file where the .mesh file is. (For example - * ogrehead.material for ogrehead.mesh). Thanks to - * Christian Stehno who wrote and contributed this - * loader.
Pulsar LMTools (.lmts)LMTools is a set of tools (Windows & Linux) for - * creating lightmaps. Irrlicht can directly read .lmts - * files thanks to
the importer created by Jonas - * Petersen. - * Notes for
this version of the loader:
- * - It does not recognize/support user data in the - * *.lmts files.
- * - The TGAs generated by LMTools don't work in - * Irrlicht for some reason (the textures are upside - * down). Opening and resaving them in a graphics app - * will solve the problem.
Quake 3 levels (.bsp)Quake 3 is a popular game by IDSoftware, and .pk3 - * files contain .bsp files and textures/lightmaps - * describing huge prelighted levels. Irrlicht can read - * .pk3 and .bsp files directly and thus render Quake 3 - * levels directly. Written by Nikolaus Gebhardt - * enhanced by Dean P. Macri with the curved surfaces - * feature.
Quake 2 models (.md2)Quake 2 models are characters with morph target - * animation. Irrlicht can read, display and animate - * them directly with this importer.
Quake 3 models (.md3)Quake 3 models are characters with morph target - * animation, they contain mount points for weapons and body - * parts and are typically made of several sections which are - * manually joined together.
Stanford Triangle (.ply)Invented by Stanford University and known as the native - * format of the infamous "Stanford Bunny" model, this is a - * popular static mesh format used by 3D scanning hardware - * and software. This loader supports extremely large models - * in both ASCII and binary format, but only has rudimentary - * material support in the form of vertex colors and texture - * coordinates.
Stereolithography (.stl)The STL format is used for rapid prototyping and - * computer-aided manufacturing, thus has no support for - * materials.
- * - * To load and display a mesh quickly, just do this: - * \code - * SceneManager->addAnimatedMeshSceneNode( - * SceneManager->getMesh("yourmesh.3ds")); - * \endcode - * If you would like to implement and add your own file format loader to Irrlicht, - * see addExternalMeshLoader(). - * \param file File handle of the mesh to load. - * \return Null if failed, otherwise pointer to the mesh. - * This pointer should not be dropped. See IReferenceCounted::drop() for more information. - **/ - virtual IAnimatedMesh* getMesh(io::IReadFile* file) = 0; + //! Get interface to the mesh cache which is shared between all existing scene managers. + /** With this interface, it is possible to manually add new loaded + meshes (if ISceneManager::getMesh() is not sufficient), to remove them and to iterate + through already loaded meshes. */ + virtual IMeshCache *getMeshCache() = 0; - //! Get interface to the mesh cache which is shared between all existing scene managers. - /** With this interface, it is possible to manually add new loaded - meshes (if ISceneManager::getMesh() is not sufficient), to remove them and to iterate - through already loaded meshes. */ - virtual IMeshCache* getMeshCache() = 0; + //! Get the video driver. + /** \return Pointer to the video Driver. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual video::IVideoDriver *getVideoDriver() = 0; - //! Get the video driver. - /** \return Pointer to the video Driver. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual video::IVideoDriver* getVideoDriver() = 0; + //! Adds a scene node for rendering an animated mesh model. + /** \param mesh: Pointer to the loaded animated mesh to be displayed. + \param parent: Parent of the scene node. Can be NULL if no parent. + \param id: Id of the node. This id can be used to identify the scene node. + \param position: Position of the space relative to its parent where the + scene node will be placed. + \param rotation: Initial rotation of the scene node. + \param scale: Initial scale of the scene node. + \param alsoAddIfMeshPointerZero: Add the scene node even if a 0 pointer is passed. + \return Pointer to the created scene node. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual IAnimatedMeshSceneNode *addAnimatedMeshSceneNode(IAnimatedMesh *mesh, + ISceneNode *parent = 0, s32 id = -1, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f), + bool alsoAddIfMeshPointerZero = false) = 0; - //! Adds a scene node for rendering an animated mesh model. - /** \param mesh: Pointer to the loaded animated mesh to be displayed. - \param parent: Parent of the scene node. Can be NULL if no parent. - \param id: Id of the node. This id can be used to identify the scene node. - \param position: Position of the space relative to its parent where the - scene node will be placed. - \param rotation: Initial rotation of the scene node. - \param scale: Initial scale of the scene node. - \param alsoAddIfMeshPointerZero: Add the scene node even if a 0 pointer is passed. - \return Pointer to the created scene node. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IAnimatedMeshSceneNode* addAnimatedMeshSceneNode(IAnimatedMesh* mesh, - ISceneNode* parent=0, s32 id=-1, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f), - bool alsoAddIfMeshPointerZero=false) = 0; + //! Adds a scene node for rendering a static mesh. + /** \param mesh: Pointer to the loaded static mesh to be displayed. + \param parent: Parent of the scene node. Can be NULL if no parent. + \param id: Id of the node. This id can be used to identify the scene node. + \param position: Position of the space relative to its parent where the + scene node will be placed. + \param rotation: Initial rotation of the scene node. + \param scale: Initial scale of the scene node. + \param alsoAddIfMeshPointerZero: Add the scene node even if a 0 pointer is passed. + \return Pointer to the created scene node. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual IMeshSceneNode *addMeshSceneNode(IMesh *mesh, ISceneNode *parent = 0, s32 id = -1, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f), + bool alsoAddIfMeshPointerZero = false) = 0; - //! Adds a scene node for rendering a static mesh. - /** \param mesh: Pointer to the loaded static mesh to be displayed. - \param parent: Parent of the scene node. Can be NULL if no parent. - \param id: Id of the node. This id can be used to identify the scene node. - \param position: Position of the space relative to its parent where the - scene node will be placed. - \param rotation: Initial rotation of the scene node. - \param scale: Initial scale of the scene node. - \param alsoAddIfMeshPointerZero: Add the scene node even if a 0 pointer is passed. - \return Pointer to the created scene node. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IMeshSceneNode* addMeshSceneNode(IMesh* mesh, ISceneNode* parent=0, s32 id=-1, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f), - bool alsoAddIfMeshPointerZero=false) = 0; + //! Adds a camera scene node to the scene graph and sets it as active camera. + /** This camera does not react on user input. + If you want to move or animate it, use ISceneNode::setPosition(), + ICameraSceneNode::setTarget() etc methods. + By default, a camera's look at position (set with setTarget()) and its scene node + rotation (set with setRotation()) are independent. If you want to be able to + control the direction that the camera looks by using setRotation() then call + ICameraSceneNode::bindTargetAndRotation(true) on it. + \param position: Position of the space relative to its parent where the camera will be placed. + \param lookat: Position where the camera will look at. Also known as target. + \param parent: Parent scene node of the camera. Can be null. If the parent moves, + the camera will move too. + \param id: id of the camera. This id can be used to identify the camera. + \param makeActive Flag whether this camera should become the active one. + Make sure you always have one active camera. + \return Pointer to interface to camera if successful, otherwise 0. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ICameraSceneNode *addCameraSceneNode(ISceneNode *parent = 0, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &lookat = core::vector3df(0, 0, 100), + s32 id = -1, bool makeActive = true) = 0; - //! Adds a camera scene node to the scene graph and sets it as active camera. - /** This camera does not react on user input. - If you want to move or animate it, use ISceneNode::setPosition(), - ICameraSceneNode::setTarget() etc methods. - By default, a camera's look at position (set with setTarget()) and its scene node - rotation (set with setRotation()) are independent. If you want to be able to - control the direction that the camera looks by using setRotation() then call - ICameraSceneNode::bindTargetAndRotation(true) on it. - \param position: Position of the space relative to its parent where the camera will be placed. - \param lookat: Position where the camera will look at. Also known as target. - \param parent: Parent scene node of the camera. Can be null. If the parent moves, - the camera will move too. - \param id: id of the camera. This id can be used to identify the camera. - \param makeActive Flag whether this camera should become the active one. - Make sure you always have one active camera. - \return Pointer to interface to camera if successful, otherwise 0. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ICameraSceneNode* addCameraSceneNode(ISceneNode* parent = 0, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& lookat = core::vector3df(0,0,100), - s32 id=-1, bool makeActive=true) = 0; - - //! Adds a billboard scene node to the scene graph. - /** A billboard is like a 3d sprite: A 2d element, - which always looks to the camera. It is usually used for things - like explosions, fire, lensflares and things like that. - \param parent Parent scene node of the billboard. Can be null. - If the parent moves, the billboard will move too. - \param size Size of the billboard. This size is 2 dimensional - because a billboard only has width and height. - \param position Position of the space relative to its parent - where the billboard will be placed. - \param id An id of the node. This id can be used to identify - the node. - \param colorTop The color of the vertices at the top of the - billboard (default: white). - \param colorBottom The color of the vertices at the bottom of - the billboard (default: white). - \return Pointer to the billboard if successful, otherwise NULL. - This pointer should not be dropped. See - IReferenceCounted::drop() for more information. */ - virtual IBillboardSceneNode* addBillboardSceneNode(ISceneNode* parent = 0, - const core::dimension2d& size = core::dimension2d(10.0f, 10.0f), - const core::vector3df& position = core::vector3df(0,0,0), s32 id=-1, + //! Adds a billboard scene node to the scene graph. + /** A billboard is like a 3d sprite: A 2d element, + which always looks to the camera. It is usually used for things + like explosions, fire, lensflares and things like that. + \param parent Parent scene node of the billboard. Can be null. + If the parent moves, the billboard will move too. + \param size Size of the billboard. This size is 2 dimensional + because a billboard only has width and height. + \param position Position of the space relative to its parent + where the billboard will be placed. + \param id An id of the node. This id can be used to identify + the node. + \param colorTop The color of the vertices at the top of the + billboard (default: white). + \param colorBottom The color of the vertices at the bottom of + the billboard (default: white). + \return Pointer to the billboard if successful, otherwise NULL. + This pointer should not be dropped. See + IReferenceCounted::drop() for more information. */ + virtual IBillboardSceneNode *addBillboardSceneNode(ISceneNode *parent = 0, + const core::dimension2d &size = core::dimension2d(10.0f, 10.0f), + const core::vector3df &position = core::vector3df(0, 0, 0), s32 id = -1, video::SColor colorTop = 0xFFFFFFFF, video::SColor colorBottom = 0xFFFFFFFF) = 0; - //! Adds an empty scene node to the scene graph. - /** Can be used for doing advanced transformations - or structuring the scene graph. - \return Pointer to the created scene node. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneNode* addEmptySceneNode(ISceneNode* parent=0, s32 id=-1) = 0; + //! Adds an empty scene node to the scene graph. + /** Can be used for doing advanced transformations + or structuring the scene graph. + \return Pointer to the created scene node. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneNode *addEmptySceneNode(ISceneNode *parent = 0, s32 id = -1) = 0; - //! Adds a dummy transformation scene node to the scene graph. - /** This scene node does not render itself, and does not respond to set/getPosition, - set/getRotation and set/getScale. Its just a simple scene node that takes a - matrix as relative transformation, making it possible to insert any transformation - anywhere into the scene graph. - \return Pointer to the created scene node. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IDummyTransformationSceneNode* addDummyTransformationSceneNode( - ISceneNode* parent=0, s32 id=-1) = 0; + //! Adds a dummy transformation scene node to the scene graph. + /** This scene node does not render itself, and does not respond to set/getPosition, + set/getRotation and set/getScale. Its just a simple scene node that takes a + matrix as relative transformation, making it possible to insert any transformation + anywhere into the scene graph. + \return Pointer to the created scene node. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual IDummyTransformationSceneNode *addDummyTransformationSceneNode( + ISceneNode *parent = 0, s32 id = -1) = 0; - //! Gets the root scene node. - /** This is the scene node which is parent - of all scene nodes. The root scene node is a special scene node which - only exists to manage all scene nodes. It will not be rendered and cannot - be removed from the scene. - \return Pointer to the root scene node. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneNode* getRootSceneNode() = 0; + //! Gets the root scene node. + /** This is the scene node which is parent + of all scene nodes. The root scene node is a special scene node which + only exists to manage all scene nodes. It will not be rendered and cannot + be removed from the scene. + \return Pointer to the root scene node. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneNode *getRootSceneNode() = 0; - //! Get the first scene node with the specified id. - /** \param id: The id to search for - \param start: Scene node to start from. All children of this scene - node are searched. If null is specified, the root scene node is - taken. - \return Pointer to the first scene node with this id, - and null if no scene node could be found. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneNode* getSceneNodeFromId(s32 id, ISceneNode* start=0) = 0; + //! Get the first scene node with the specified id. + /** \param id: The id to search for + \param start: Scene node to start from. All children of this scene + node are searched. If null is specified, the root scene node is + taken. + \return Pointer to the first scene node with this id, + and null if no scene node could be found. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneNode *getSceneNodeFromId(s32 id, ISceneNode *start = 0) = 0; - //! Get the first scene node with the specified name. - /** \param name: The name to search for - \param start: Scene node to start from. All children of this scene - node are searched. If null is specified, the root scene node is - taken. - \return Pointer to the first scene node with this id, - and null if no scene node could be found. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneNode* getSceneNodeFromName(const c8* name, ISceneNode* start=0) = 0; + //! Get the first scene node with the specified name. + /** \param name: The name to search for + \param start: Scene node to start from. All children of this scene + node are searched. If null is specified, the root scene node is + taken. + \return Pointer to the first scene node with this id, + and null if no scene node could be found. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneNode *getSceneNodeFromName(const c8 *name, ISceneNode *start = 0) = 0; - //! Get the first scene node with the specified type. - /** \param type: The type to search for - \param start: Scene node to start from. All children of this scene - node are searched. If null is specified, the root scene node is - taken. - \return Pointer to the first scene node with this type, - and null if no scene node could be found. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneNode* getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode* start=0) = 0; + //! Get the first scene node with the specified type. + /** \param type: The type to search for + \param start: Scene node to start from. All children of this scene + node are searched. If null is specified, the root scene node is + taken. + \return Pointer to the first scene node with this type, + and null if no scene node could be found. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneNode *getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode *start = 0) = 0; - //! Get scene nodes by type. - /** \param type: Type of scene node to find (ESNT_ANY will return all child nodes). - \param outNodes: results will be added to this array (outNodes is not cleared). - \param start: Scene node to start from. This node and all children of this scene - node are checked (recursively, so also children of children, etc). If null is specified, - the root scene node is taken as start-node. */ - virtual void getSceneNodesFromType(ESCENE_NODE_TYPE type, - core::array& outNodes, - ISceneNode* start=0) = 0; + //! Get scene nodes by type. + /** \param type: Type of scene node to find (ESNT_ANY will return all child nodes). + \param outNodes: results will be added to this array (outNodes is not cleared). + \param start: Scene node to start from. This node and all children of this scene + node are checked (recursively, so also children of children, etc). If null is specified, + the root scene node is taken as start-node. */ + virtual void getSceneNodesFromType(ESCENE_NODE_TYPE type, + core::array &outNodes, + ISceneNode *start = 0) = 0; - //! Get the current active camera. - /** \return The active camera is returned. Note that this can - be NULL, if there was no camera created yet. - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ICameraSceneNode* getActiveCamera() const =0; + //! Get the current active camera. + /** \return The active camera is returned. Note that this can + be NULL, if there was no camera created yet. + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ICameraSceneNode *getActiveCamera() const = 0; - //! Sets the currently active camera. - /** The previous active camera will be deactivated. - \param camera: The new camera which should be active. */ - virtual void setActiveCamera(ICameraSceneNode* camera) = 0; + //! Sets the currently active camera. + /** The previous active camera will be deactivated. + \param camera: The new camera which should be active. */ + virtual void setActiveCamera(ICameraSceneNode *camera) = 0; - //! Registers a node for rendering it at a specific time. - /** This method should only be used by SceneNodes when they get a - ISceneNode::OnRegisterSceneNode() call. - \param node: Node to register for drawing. Usually scene nodes would set 'this' - as parameter here because they want to be drawn. - \param pass: Specifies when the node wants to be drawn in relation to the other nodes. - For example, if the node is a shadow, it usually wants to be drawn after all other nodes - and will use ESNRP_SHADOW for this. See scene::E_SCENE_NODE_RENDER_PASS for details. - Note: This is _not_ a bitfield. If you want to register a note for several render passes, then - call this function once for each pass. - \return scene will be rendered ( passed culling ) */ - virtual u32 registerNodeForRendering(ISceneNode* node, + //! Registers a node for rendering it at a specific time. + /** This method should only be used by SceneNodes when they get a + ISceneNode::OnRegisterSceneNode() call. + \param node: Node to register for drawing. Usually scene nodes would set 'this' + as parameter here because they want to be drawn. + \param pass: Specifies when the node wants to be drawn in relation to the other nodes. + For example, if the node is a shadow, it usually wants to be drawn after all other nodes + and will use ESNRP_SHADOW for this. See scene::E_SCENE_NODE_RENDER_PASS for details. + Note: This is _not_ a bitfield. If you want to register a note for several render passes, then + call this function once for each pass. + \return scene will be rendered ( passed culling ) */ + virtual u32 registerNodeForRendering(ISceneNode *node, E_SCENE_NODE_RENDER_PASS pass = ESNRP_AUTOMATIC) = 0; - //! Clear all nodes which are currently registered for rendering - /** Usually you don't have to care about this as drawAll will clear nodes - after rendering them. But sometimes you might have to manually reset this. - For example when you deleted nodes between registering and rendering. */ - virtual void clearAllRegisteredNodesForRendering() = 0; + //! Clear all nodes which are currently registered for rendering + /** Usually you don't have to care about this as drawAll will clear nodes + after rendering them. But sometimes you might have to manually reset this. + For example when you deleted nodes between registering and rendering. */ + virtual void clearAllRegisteredNodesForRendering() = 0; - //! Draws all the scene nodes. - /** This can only be invoked between - IVideoDriver::beginScene() and IVideoDriver::endScene(). Please note that - the scene is not only drawn when calling this, but also animated - by existing scene node animators, culling of scene nodes is done, etc. */ - virtual void drawAll() = 0; + //! Draws all the scene nodes. + /** This can only be invoked between + IVideoDriver::beginScene() and IVideoDriver::endScene(). Please note that + the scene is not only drawn when calling this, but also animated + by existing scene node animators, culling of scene nodes is done, etc. */ + virtual void drawAll() = 0; - //! Adds an external mesh loader for extending the engine with new file formats. - /** If you want the engine to be extended with - file formats it currently is not able to load (e.g. .cob), just implement - the IMeshLoader interface in your loading class and add it with this method. - Using this method it is also possible to override built-in mesh loaders with - newer or updated versions without the need to recompile the engine. - \param externalLoader: Implementation of a new mesh loader. */ - virtual void addExternalMeshLoader(IMeshLoader* externalLoader) = 0; + //! Adds an external mesh loader for extending the engine with new file formats. + /** If you want the engine to be extended with + file formats it currently is not able to load (e.g. .cob), just implement + the IMeshLoader interface in your loading class and add it with this method. + Using this method it is also possible to override built-in mesh loaders with + newer or updated versions without the need to recompile the engine. + \param externalLoader: Implementation of a new mesh loader. */ + virtual void addExternalMeshLoader(IMeshLoader *externalLoader) = 0; - //! Returns the number of mesh loaders supported by Irrlicht at this time - virtual u32 getMeshLoaderCount() const = 0; + //! Returns the number of mesh loaders supported by Irrlicht at this time + virtual u32 getMeshLoaderCount() const = 0; - //! Retrieve the given mesh loader - /** \param index The index of the loader to retrieve. This parameter is an 0-based - array index. - \return A pointer to the specified loader, 0 if the index is incorrect. */ - virtual IMeshLoader* getMeshLoader(u32 index) const = 0; + //! Retrieve the given mesh loader + /** \param index The index of the loader to retrieve. This parameter is an 0-based + array index. + \return A pointer to the specified loader, 0 if the index is incorrect. */ + virtual IMeshLoader *getMeshLoader(u32 index) const = 0; - //! Get pointer to the scene collision manager. - /** \return Pointer to the collision manager - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ISceneCollisionManager* getSceneCollisionManager() = 0; + //! Get pointer to the scene collision manager. + /** \return Pointer to the collision manager + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ISceneCollisionManager *getSceneCollisionManager() = 0; - //! Get pointer to the mesh manipulator. - /** \return Pointer to the mesh manipulator - This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual IMeshManipulator* getMeshManipulator() = 0; + //! Get pointer to the mesh manipulator. + /** \return Pointer to the mesh manipulator + This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual IMeshManipulator *getMeshManipulator() = 0; - //! Adds a scene node to the deletion queue. - /** The scene node is immediately - deleted when it's secure. Which means when the scene node does not - execute animators and things like that. This method is for example - used for deleting scene nodes by their scene node animators. In - most other cases, a ISceneNode::remove() call is enough, using this - deletion queue is not necessary. - See ISceneManager::createDeleteAnimator() for details. - \param node: Node to delete. */ - virtual void addToDeletionQueue(ISceneNode* node) = 0; + //! Adds a scene node to the deletion queue. + /** The scene node is immediately + deleted when it's secure. Which means when the scene node does not + execute animators and things like that. This method is for example + used for deleting scene nodes by their scene node animators. In + most other cases, a ISceneNode::remove() call is enough, using this + deletion queue is not necessary. + See ISceneManager::createDeleteAnimator() for details. + \param node: Node to delete. */ + virtual void addToDeletionQueue(ISceneNode *node) = 0; - //! Posts an input event to the environment. - /** Usually you do not have to - use this method, it is used by the internal engine. */ - virtual bool postEventFromUser(const SEvent& event) = 0; + //! Posts an input event to the environment. + /** Usually you do not have to + use this method, it is used by the internal engine. */ + virtual bool postEventFromUser(const SEvent &event) = 0; - //! Clears the whole scene. - /** All scene nodes are removed. */ - virtual void clear() = 0; + //! Clears the whole scene. + /** All scene nodes are removed. */ + virtual void clear() = 0; - //! Get interface to the parameters set in this scene. - /** String parameters can be used by plugins and mesh loaders. - See COLLADA_CREATE_SCENE_INSTANCES and DMF_USE_MATERIALS_DIRS */ - virtual io::IAttributes* getParameters() = 0; + //! Get interface to the parameters set in this scene. + /** String parameters can be used by plugins and mesh loaders. + See COLLADA_CREATE_SCENE_INSTANCES and DMF_USE_MATERIALS_DIRS */ + virtual io::IAttributes *getParameters() = 0; - //! Get current render pass. - /** All scene nodes are being rendered in a specific order. - First lights, cameras, sky boxes, solid geometry, and then transparent - stuff. During the rendering process, scene nodes may want to know what the scene - manager is rendering currently, because for example they registered for rendering - twice, once for transparent geometry and once for solid. When knowing what rendering - pass currently is active they can render the correct part of their geometry. */ - virtual E_SCENE_NODE_RENDER_PASS getSceneNodeRenderPass() const = 0; + //! Get current render pass. + /** All scene nodes are being rendered in a specific order. + First lights, cameras, sky boxes, solid geometry, and then transparent + stuff. During the rendering process, scene nodes may want to know what the scene + manager is rendering currently, because for example they registered for rendering + twice, once for transparent geometry and once for solid. When knowing what rendering + pass currently is active they can render the correct part of their geometry. */ + virtual E_SCENE_NODE_RENDER_PASS getSceneNodeRenderPass() const = 0; - //! Creates a new scene manager. - /** This can be used to easily draw and/or store two - independent scenes at the same time. The mesh cache will be - shared between all existing scene managers, which means if you - load a mesh in the original scene manager using for example - getMesh(), the mesh will be available in all other scene - managers too, without loading. - The original/main scene manager will still be there and - accessible via IrrlichtDevice::getSceneManager(). If you need - input event in this new scene manager, for example for FPS - cameras, you'll need to forward input to this manually: Just - implement an IEventReceiver and call - yourNewSceneManager->postEventFromUser(), and return true so - that the original scene manager doesn't get the event. - Otherwise, all input will go to the main scene manager - automatically. - If you no longer need the new scene manager, you should call - ISceneManager::drop(). - See IReferenceCounted::drop() for more information. */ - virtual ISceneManager* createNewSceneManager(bool cloneContent=false) = 0; + //! Creates a new scene manager. + /** This can be used to easily draw and/or store two + independent scenes at the same time. The mesh cache will be + shared between all existing scene managers, which means if you + load a mesh in the original scene manager using for example + getMesh(), the mesh will be available in all other scene + managers too, without loading. + The original/main scene manager will still be there and + accessible via IrrlichtDevice::getSceneManager(). If you need + input event in this new scene manager, for example for FPS + cameras, you'll need to forward input to this manually: Just + implement an IEventReceiver and call + yourNewSceneManager->postEventFromUser(), and return true so + that the original scene manager doesn't get the event. + Otherwise, all input will go to the main scene manager + automatically. + If you no longer need the new scene manager, you should call + ISceneManager::drop(). + See IReferenceCounted::drop() for more information. */ + virtual ISceneManager *createNewSceneManager(bool cloneContent = false) = 0; - //! Get a skinned mesh, which is not available as header-only code - /** Note: You need to drop() the pointer after use again, see IReferenceCounted::drop() - for details. */ - virtual ISkinnedMesh* createSkinnedMesh() = 0; + //! Get a skinned mesh, which is not available as header-only code + /** Note: You need to drop() the pointer after use again, see IReferenceCounted::drop() + for details. */ + virtual ISkinnedMesh *createSkinnedMesh() = 0; - //! Sets ambient color of the scene - virtual void setAmbientLight(const video::SColorf &ambientColor) = 0; + //! Sets ambient color of the scene + virtual void setAmbientLight(const video::SColorf &ambientColor) = 0; - //! Get ambient color of the scene - virtual const video::SColorf& getAmbientLight() const = 0; + //! Get ambient color of the scene + virtual const video::SColorf &getAmbientLight() const = 0; - //! Get current render pass. - virtual E_SCENE_NODE_RENDER_PASS getCurrentRenderPass() const =0; + //! Get current render pass. + virtual E_SCENE_NODE_RENDER_PASS getCurrentRenderPass() const = 0; - //! Set current render pass. - virtual void setCurrentRenderPass(E_SCENE_NODE_RENDER_PASS nextPass) =0; - - //! Check if node is culled in current view frustum - /** Please note that depending on the used culling method this - check can be rather coarse, or slow. A positive result is - correct, though, i.e. if this method returns true the node is - positively not visible. The node might still be invisible even - if this method returns false. - \param node The scene node which is checked for culling. - \return True if node is not visible in the current scene, else - false. */ - virtual bool isCulled(const ISceneNode* node) const =0; - }; + //! Set current render pass. + virtual void setCurrentRenderPass(E_SCENE_NODE_RENDER_PASS nextPass) = 0; + //! Check if node is culled in current view frustum + /** Please note that depending on the used culling method this + check can be rather coarse, or slow. A positive result is + correct, though, i.e. if this method returns true the node is + positively not visible. The node might still be invisible even + if this method returns false. + \param node The scene node which is checked for culling. + \return True if node is not visible in the current scene, else + false. */ + virtual bool isCulled(const ISceneNode *node) const = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/ISceneNode.h b/include/ISceneNode.h index 9cc38f9d..7a03a225 100644 --- a/include/ISceneNode.h +++ b/include/ISceneNode.h @@ -21,619 +21,577 @@ namespace irr { namespace scene { - class ISceneNode; - class ISceneManager; +class ISceneNode; +class ISceneManager; - //! Typedef for list of scene nodes - typedef std::list ISceneNodeList; +//! Typedef for list of scene nodes +typedef std::list ISceneNodeList; - //! Scene node interface. - /** A scene node is a node in the hierarchical scene graph. Every scene - node may have children, which are also scene nodes. Children move - relative to their parent's position. If the parent of a node is not - visible, its children won't be visible either. In this way, it is for - example easily possible to attach a light to a moving car, or to place - a walking character on a moving platform on a moving ship. - */ - class ISceneNode : virtual public IReferenceCounted +//! Scene node interface. +/** A scene node is a node in the hierarchical scene graph. Every scene +node may have children, which are also scene nodes. Children move +relative to their parent's position. If the parent of a node is not +visible, its children won't be visible either. In this way, it is for +example easily possible to attach a light to a moving car, or to place +a walking character on a moving platform on a moving ship. +*/ +class ISceneNode : virtual public IReferenceCounted +{ +public: + //! Constructor + ISceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id = -1, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f)) : + RelativeTranslation(position), + RelativeRotation(rotation), RelativeScale(scale), + Parent(0), SceneManager(mgr), ID(id), + AutomaticCullingState(EAC_BOX), DebugDataVisible(EDS_OFF), + IsVisible(true), IsDebugObject(false) { - public: + if (parent) + parent->addChild(this); - //! Constructor - ISceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id=-1, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)) - : RelativeTranslation(position), RelativeRotation(rotation), RelativeScale(scale), - Parent(0), SceneManager(mgr), ID(id), - AutomaticCullingState(EAC_BOX), DebugDataVisible(EDS_OFF), - IsVisible(true), IsDebugObject(false) - { - if (parent) - parent->addChild(this); + updateAbsolutePosition(); + } + //! Destructor + virtual ~ISceneNode() + { + // delete all children + removeAll(); + } + + //! This method is called just before the rendering process of the whole scene. + /** Nodes may register themselves in the render pipeline during this call, + precalculate the geometry which should be rendered, and prevent their + children from being able to register themselves if they are clipped by simply + not calling their OnRegisterSceneNode method. + If you are implementing your own scene node, you should overwrite this method + with an implementation code looking like this: + \code + if (IsVisible) + SceneManager->registerNodeForRendering(this); + + ISceneNode::OnRegisterSceneNode(); + \endcode + */ + virtual void OnRegisterSceneNode() + { + if (IsVisible) { + ISceneNodeList::iterator it = Children.begin(); + for (; it != Children.end(); ++it) + (*it)->OnRegisterSceneNode(); + } + } + + //! OnAnimate() is called just before rendering the whole scene. + /** Nodes may calculate or store animations here, and may do other useful things, + depending on what they are. Also, OnAnimate() should be called for all + child scene nodes here. This method will be called once per frame, independent + of whether the scene node is visible or not. + \param timeMs Current time in milliseconds. */ + virtual void OnAnimate(u32 timeMs) + { + if (IsVisible) { + // update absolute position updateAbsolutePosition(); - } - - //! Destructor - virtual ~ISceneNode() - { - // delete all children - removeAll(); - } - - - //! This method is called just before the rendering process of the whole scene. - /** Nodes may register themselves in the render pipeline during this call, - precalculate the geometry which should be rendered, and prevent their - children from being able to register themselves if they are clipped by simply - not calling their OnRegisterSceneNode method. - If you are implementing your own scene node, you should overwrite this method - with an implementation code looking like this: - \code - if (IsVisible) - SceneManager->registerNodeForRendering(this); - - ISceneNode::OnRegisterSceneNode(); - \endcode - */ - virtual void OnRegisterSceneNode() - { - if (IsVisible) - { - ISceneNodeList::iterator it = Children.begin(); - for (; it != Children.end(); ++it) - (*it)->OnRegisterSceneNode(); - } - } - - - //! OnAnimate() is called just before rendering the whole scene. - /** Nodes may calculate or store animations here, and may do other useful things, - depending on what they are. Also, OnAnimate() should be called for all - child scene nodes here. This method will be called once per frame, independent - of whether the scene node is visible or not. - \param timeMs Current time in milliseconds. */ - virtual void OnAnimate(u32 timeMs) - { - if (IsVisible) - { - // update absolute position - updateAbsolutePosition(); - - // perform the post render process on all children - - ISceneNodeList::iterator it = Children.begin(); - for (; it != Children.end(); ++it) - (*it)->OnAnimate(timeMs); - } - } - - - //! Renders the node. - virtual void render() = 0; - - - //! Returns the name of the node. - /** \return Name as character string. */ - virtual const std::optional &getName() const - { - return Name; - } - - //! Sets the name of the node. - /** \param name New name of the scene node. */ - virtual void setName(const std::optional &name) - { - Name = name; - } - - - //! Get the axis aligned, not transformed bounding box of this node. - /** This means that if this node is an animated 3d character, - moving in a room, the bounding box will always be around the - origin. To get the box in real world coordinates, just - transform it with the matrix you receive with - getAbsoluteTransformation() or simply use - getTransformedBoundingBox(), which does the same. - \return The non-transformed bounding box. */ - virtual const core::aabbox3d& getBoundingBox() const = 0; - - - //! Get the axis aligned, transformed and animated absolute bounding box of this node. - /** Note: The result is still an axis-aligned bounding box, so it's size - changes with rotation. - \return The transformed bounding box. */ - virtual const core::aabbox3d getTransformedBoundingBox() const - { - core::aabbox3d box = getBoundingBox(); - AbsoluteTransformation.transformBoxEx(box); - return box; - } - - //! Get a the 8 corners of the original bounding box transformed and - //! animated by the absolute transformation. - /** Note: The result is _not_ identical to getTransformedBoundingBox().getEdges(), - but getting an aabbox3d of these edges would then be identical. - \param edges Receives an array with the transformed edges */ - virtual void getTransformedBoundingBoxEdges(core::array< core::vector3d >& edges) const - { - edges.set_used(8); - getBoundingBox().getEdges( edges.pointer() ); - for ( u32 i=0; i<8; ++i ) - AbsoluteTransformation.transformVect( edges[i] ); - } - - //! Get the absolute transformation of the node. Is recalculated every OnAnimate()-call. - /** NOTE: For speed reasons the absolute transformation is not - automatically recalculated on each change of the relative - transformation or by a transformation change of an parent. Instead the - update usually happens once per frame in OnAnimate. You can enforce - an update with updateAbsolutePosition(). - \return The absolute transformation matrix. */ - virtual const core::matrix4& getAbsoluteTransformation() const - { - return AbsoluteTransformation; - } - - - //! Returns the relative transformation of the scene node. - /** The relative transformation is stored internally as 3 - vectors: translation, rotation and scale. To get the relative - transformation matrix, it is calculated from these values. - \return The relative transformation matrix. */ - virtual core::matrix4 getRelativeTransformation() const - { - core::matrix4 mat; - mat.setRotationDegrees(RelativeRotation); - mat.setTranslation(RelativeTranslation); - - if (RelativeScale != core::vector3df(1.f,1.f,1.f)) - { - core::matrix4 smat; - smat.setScale(RelativeScale); - mat *= smat; - } - - return mat; - } - - - //! Returns whether the node should be visible (if all of its parents are visible). - /** This is only an option set by the user, but has nothing to - do with geometry culling - \return The requested visibility of the node, true means - visible (if all parents are also visible). */ - virtual bool isVisible() const - { - return IsVisible; - } - - //! Check whether the node is truly visible, taking into accounts its parents' visibility - /** \return true if the node and all its parents are visible, - false if this or any parent node is invisible. */ - virtual bool isTrulyVisible() const - { - if(!IsVisible) - return false; - - if(!Parent) - return true; - - return Parent->isTrulyVisible(); - } - - //! Sets if the node should be visible or not. - /** All children of this node won't be visible either, when set - to false. Invisible nodes are not valid candidates for selection by - collision manager bounding box methods. - \param isVisible If the node shall be visible. */ - virtual void setVisible(bool isVisible) - { - IsVisible = isVisible; - } - - - //! Get the id of the scene node. - /** This id can be used to identify the node. - \return The id. */ - virtual s32 getID() const - { - return ID; - } - - - //! Sets the id of the scene node. - /** This id can be used to identify the node. - \param id The new id. */ - virtual void setID(s32 id) - { - ID = id; - } - - - //! Adds a child to this scene node. - /** If the scene node already has a parent it is first removed - from the other parent. - \param child A pointer to the new child. */ - virtual void addChild(ISceneNode* child) - { - if (child && (child != this)) - { - // Change scene manager? - if (SceneManager != child->SceneManager) - child->setSceneManager(SceneManager); - - child->grab(); - child->remove(); // remove from old parent - // Note: This iterator is not invalidated until we erase it. - child->ThisIterator = Children.insert(Children.end(), child); - child->Parent = this; - } - } - - - //! Removes a child from this scene node. - /** - \param child A pointer to the child which shall be removed. - \return True if the child was removed, and false if not, - e.g. because it belongs to a different parent or no parent. */ - virtual bool removeChild(ISceneNode* child) - { - if (child->Parent != this) - return false; - - // The iterator must be set since the parent is not null. - _IRR_DEBUG_BREAK_IF(!child->ThisIterator.has_value()); - auto it = *child->ThisIterator; - child->ThisIterator = std::nullopt; - child->Parent = nullptr; - child->drop(); - Children.erase(it); - return true; - } - - - //! Removes all children of this scene node - /** The scene nodes found in the children list are also dropped - and might be deleted if no other grab exists on them. - */ - virtual void removeAll() - { - for (auto &child : Children) { - child->Parent = nullptr; - child->ThisIterator = std::nullopt; - child->drop(); - } - Children.clear(); - } - - - //! Removes this scene node from the scene - /** If no other grab exists for this node, it will be deleted. - */ - virtual void remove() - { - if (Parent) - Parent->removeChild(this); - } - - - //! Returns the material based on the zero based index i. - /** To get the amount of materials used by this scene node, use - getMaterialCount(). This function is needed for inserting the - node into the scene hierarchy at an optimal position for - minimizing renderstate changes, but can also be used to - directly modify the material of a scene node. - \param num Zero based index. The maximal value is getMaterialCount() - 1. - \return The material at that index. */ - virtual video::SMaterial& getMaterial(u32 num) - { - return video::IdentityMaterial; - } - - - //! Get amount of materials used by this scene node. - /** \return Current amount of materials of this scene node. */ - virtual u32 getMaterialCount() const - { - return 0; - } - - - //! Execute a function on all materials of this scene node. - /** Useful for setting material properties, e.g. if you want the whole - mesh to be affected by light. */ - template - void forEachMaterial(F &&fn) { - for (u32 i = 0; i < getMaterialCount(); i++) { - fn(getMaterial(i)); - } - } - - - //! Gets the scale of the scene node relative to its parent. - /** This is the scale of this node relative to its parent. - If you want the absolute scale, use - getAbsoluteTransformation().getScale() - \return The scale of the scene node. */ - virtual const core::vector3df& getScale() const - { - return RelativeScale; - } - - - //! Sets the relative scale of the scene node. - /** \param scale New scale of the node, relative to its parent. */ - virtual void setScale(const core::vector3df& scale) - { - RelativeScale = scale; - } - - - //! Gets the rotation of the node relative to its parent. - /** Note that this is the relative rotation of the node. - If you want the absolute rotation, use - getAbsoluteTransformation().getRotation() - \return Current relative rotation of the scene node. */ - virtual const core::vector3df& getRotation() const - { - return RelativeRotation; - } - - - //! Sets the rotation of the node relative to its parent. - /** This only modifies the relative rotation of the node. - \param rotation New rotation of the node in degrees. */ - virtual void setRotation(const core::vector3df& rotation) - { - RelativeRotation = rotation; - } - - - //! Gets the position of the node relative to its parent. - /** Note that the position is relative to the parent. If you want - the position in world coordinates, use getAbsolutePosition() instead. - \return The current position of the node relative to the parent. */ - virtual const core::vector3df& getPosition() const - { - return RelativeTranslation; - } - - - //! Sets the position of the node relative to its parent. - /** Note that the position is relative to the parent. - \param newpos New relative position of the scene node. */ - virtual void setPosition(const core::vector3df& newpos) - { - RelativeTranslation = newpos; - } - - - //! Gets the absolute position of the node in world coordinates. - /** If you want the position of the node relative to its parent, - use getPosition() instead. - NOTE: For speed reasons the absolute position is not - automatically recalculated on each change of the relative - position or by a position change of an parent. Instead the - update usually happens once per frame in OnAnimate. You can enforce - an update with updateAbsolutePosition(). - \return The current absolute position of the scene node (updated on last call of updateAbsolutePosition). */ - virtual core::vector3df getAbsolutePosition() const - { - return AbsoluteTransformation.getTranslation(); - } - - - //! Set a culling style or disable culling completely. - /** Box cullling (EAC_BOX) is set by default. Note that not - all SceneNodes support culling and that some nodes always cull - their geometry because it is their only reason for existence, - for example the OctreeSceneNode. - \param state The culling state to be used. Check E_CULLING_TYPE for possible values.*/ - void setAutomaticCulling( u32 state) - { - AutomaticCullingState = state; - } - - - //! Gets the automatic culling state. - /** \return The automatic culling state. */ - u32 getAutomaticCulling() const - { - return AutomaticCullingState; - } - - - //! Sets if debug data like bounding boxes should be drawn. - /** A bitwise OR of the types from @ref irr::scene::E_DEBUG_SCENE_TYPE. - Please note that not all scene nodes support all debug data types. - \param state The debug data visibility state to be used. */ - virtual void setDebugDataVisible(u32 state) - { - DebugDataVisible = state; - } - - //! Returns if debug data like bounding boxes are drawn. - /** \return A bitwise OR of the debug data values from - @ref irr::scene::E_DEBUG_SCENE_TYPE that are currently visible. */ - u32 isDebugDataVisible() const - { - return DebugDataVisible; - } - - - //! Sets if this scene node is a debug object. - /** Debug objects have some special properties, for example they can be easily - excluded from collision detection or from serialization, etc. */ - void setIsDebugObject(bool debugObject) - { - IsDebugObject = debugObject; - } - - - //! Returns if this scene node is a debug object. - /** Debug objects have some special properties, for example they can be easily - excluded from collision detection or from serialization, etc. - \return If this node is a debug object, true is returned. */ - bool isDebugObject() const - { - return IsDebugObject; - } - - - //! Returns a const reference to the list of all children. - /** \return The list of all children of this node. */ - const std::list& getChildren() const - { - return Children; - } - - - //! Changes the parent of the scene node. - /** \param newParent The new parent to be used. */ - virtual void setParent(ISceneNode* newParent) - { - grab(); - remove(); - - if (newParent) - newParent->addChild(this); - - drop(); - } - - - //! Updates the absolute position based on the relative and the parents position - /** Note: This does not recursively update the parents absolute positions, so if you have a deeper - hierarchy you might want to update the parents first.*/ - virtual void updateAbsolutePosition() - { - if (Parent) - { - AbsoluteTransformation = - Parent->getAbsoluteTransformation() * getRelativeTransformation(); - } - else - AbsoluteTransformation = getRelativeTransformation(); - } - - - //! Returns the parent of this scene node - /** \return A pointer to the parent. */ - scene::ISceneNode* getParent() const - { - return Parent; - } - - - //! Returns type of the scene node - /** \return The type of this node. */ - virtual ESCENE_NODE_TYPE getType() const - { - return ESNT_UNKNOWN; - } - - //! Creates a clone of this scene node and its children. - /** \param newParent An optional new parent. - \param newManager An optional new scene manager. - \return The newly created clone of this node. */ - virtual ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) - { - return 0; // to be implemented by derived classes - } - - //! Retrieve the scene manager for this node. - /** \return The node's scene manager. */ - virtual ISceneManager* getSceneManager(void) const { return SceneManager; } - - protected: - - //! A clone function for the ISceneNode members. - /** This method can be used by clone() implementations of - derived classes - \param toCopyFrom The node from which the values are copied - \param newManager The new scene manager. */ - void cloneMembers(ISceneNode* toCopyFrom, ISceneManager* newManager) - { - Name = toCopyFrom->Name; - AbsoluteTransformation = toCopyFrom->AbsoluteTransformation; - RelativeTranslation = toCopyFrom->RelativeTranslation; - RelativeRotation = toCopyFrom->RelativeRotation; - RelativeScale = toCopyFrom->RelativeScale; - ID = toCopyFrom->ID; - AutomaticCullingState = toCopyFrom->AutomaticCullingState; - DebugDataVisible = toCopyFrom->DebugDataVisible; - IsVisible = toCopyFrom->IsVisible; - IsDebugObject = toCopyFrom->IsDebugObject; - - if (newManager) - SceneManager = newManager; - else - SceneManager = toCopyFrom->SceneManager; - - // clone children - - ISceneNodeList::iterator it = toCopyFrom->Children.begin(); - for (; it != toCopyFrom->Children.end(); ++it) - (*it)->clone(this, newManager); - } - - //! Sets the new scene manager for this node and all children. - //! Called by addChild when moving nodes between scene managers - void setSceneManager(ISceneManager* newManager) - { - SceneManager = newManager; + // perform the post render process on all children ISceneNodeList::iterator it = Children.begin(); for (; it != Children.end(); ++it) - (*it)->setSceneManager(newManager); + (*it)->OnAnimate(timeMs); + } + } + + //! Renders the node. + virtual void render() = 0; + + //! Returns the name of the node. + /** \return Name as character string. */ + virtual const std::optional &getName() const + { + return Name; + } + + //! Sets the name of the node. + /** \param name New name of the scene node. */ + virtual void setName(const std::optional &name) + { + Name = name; + } + + //! Get the axis aligned, not transformed bounding box of this node. + /** This means that if this node is an animated 3d character, + moving in a room, the bounding box will always be around the + origin. To get the box in real world coordinates, just + transform it with the matrix you receive with + getAbsoluteTransformation() or simply use + getTransformedBoundingBox(), which does the same. + \return The non-transformed bounding box. */ + virtual const core::aabbox3d &getBoundingBox() const = 0; + + //! Get the axis aligned, transformed and animated absolute bounding box of this node. + /** Note: The result is still an axis-aligned bounding box, so it's size + changes with rotation. + \return The transformed bounding box. */ + virtual const core::aabbox3d getTransformedBoundingBox() const + { + core::aabbox3d box = getBoundingBox(); + AbsoluteTransformation.transformBoxEx(box); + return box; + } + + //! Get a the 8 corners of the original bounding box transformed and + //! animated by the absolute transformation. + /** Note: The result is _not_ identical to getTransformedBoundingBox().getEdges(), + but getting an aabbox3d of these edges would then be identical. + \param edges Receives an array with the transformed edges */ + virtual void getTransformedBoundingBoxEdges(core::array> &edges) const + { + edges.set_used(8); + getBoundingBox().getEdges(edges.pointer()); + for (u32 i = 0; i < 8; ++i) + AbsoluteTransformation.transformVect(edges[i]); + } + + //! Get the absolute transformation of the node. Is recalculated every OnAnimate()-call. + /** NOTE: For speed reasons the absolute transformation is not + automatically recalculated on each change of the relative + transformation or by a transformation change of an parent. Instead the + update usually happens once per frame in OnAnimate. You can enforce + an update with updateAbsolutePosition(). + \return The absolute transformation matrix. */ + virtual const core::matrix4 &getAbsoluteTransformation() const + { + return AbsoluteTransformation; + } + + //! Returns the relative transformation of the scene node. + /** The relative transformation is stored internally as 3 + vectors: translation, rotation and scale. To get the relative + transformation matrix, it is calculated from these values. + \return The relative transformation matrix. */ + virtual core::matrix4 getRelativeTransformation() const + { + core::matrix4 mat; + mat.setRotationDegrees(RelativeRotation); + mat.setTranslation(RelativeTranslation); + + if (RelativeScale != core::vector3df(1.f, 1.f, 1.f)) { + core::matrix4 smat; + smat.setScale(RelativeScale); + mat *= smat; } - //! Name of the scene node. - std::optional Name; + return mat; + } - //! Absolute transformation of the node. - core::matrix4 AbsoluteTransformation; + //! Returns whether the node should be visible (if all of its parents are visible). + /** This is only an option set by the user, but has nothing to + do with geometry culling + \return The requested visibility of the node, true means + visible (if all parents are also visible). */ + virtual bool isVisible() const + { + return IsVisible; + } - //! Relative translation of the scene node. - core::vector3df RelativeTranslation; + //! Check whether the node is truly visible, taking into accounts its parents' visibility + /** \return true if the node and all its parents are visible, + false if this or any parent node is invisible. */ + virtual bool isTrulyVisible() const + { + if (!IsVisible) + return false; - //! Relative rotation of the scene node. - core::vector3df RelativeRotation; + if (!Parent) + return true; - //! Relative scale of the scene node. - core::vector3df RelativeScale; + return Parent->isTrulyVisible(); + } - //! List of all children of this node - std::list Children; + //! Sets if the node should be visible or not. + /** All children of this node won't be visible either, when set + to false. Invisible nodes are not valid candidates for selection by + collision manager bounding box methods. + \param isVisible If the node shall be visible. */ + virtual void setVisible(bool isVisible) + { + IsVisible = isVisible; + } - //! Iterator pointing to this node in the parent's child list. - std::optional ThisIterator; + //! Get the id of the scene node. + /** This id can be used to identify the node. + \return The id. */ + virtual s32 getID() const + { + return ID; + } - //! Pointer to the parent - ISceneNode* Parent; + //! Sets the id of the scene node. + /** This id can be used to identify the node. + \param id The new id. */ + virtual void setID(s32 id) + { + ID = id; + } - //! Pointer to the scene manager - ISceneManager* SceneManager; + //! Adds a child to this scene node. + /** If the scene node already has a parent it is first removed + from the other parent. + \param child A pointer to the new child. */ + virtual void addChild(ISceneNode *child) + { + if (child && (child != this)) { + // Change scene manager? + if (SceneManager != child->SceneManager) + child->setSceneManager(SceneManager); - //! ID of the node. - s32 ID; + child->grab(); + child->remove(); // remove from old parent + // Note: This iterator is not invalidated until we erase it. + child->ThisIterator = Children.insert(Children.end(), child); + child->Parent = this; + } + } - //! Automatic culling state - u32 AutomaticCullingState; + //! Removes a child from this scene node. + /** + \param child A pointer to the child which shall be removed. + \return True if the child was removed, and false if not, + e.g. because it belongs to a different parent or no parent. */ + virtual bool removeChild(ISceneNode *child) + { + if (child->Parent != this) + return false; - //! Flag if debug data should be drawn, such as Bounding Boxes. - u32 DebugDataVisible; + // The iterator must be set since the parent is not null. + _IRR_DEBUG_BREAK_IF(!child->ThisIterator.has_value()); + auto it = *child->ThisIterator; + child->ThisIterator = std::nullopt; + child->Parent = nullptr; + child->drop(); + Children.erase(it); + return true; + } - //! Is the node visible? - bool IsVisible; + //! Removes all children of this scene node + /** The scene nodes found in the children list are also dropped + and might be deleted if no other grab exists on them. + */ + virtual void removeAll() + { + for (auto &child : Children) { + child->Parent = nullptr; + child->ThisIterator = std::nullopt; + child->drop(); + } + Children.clear(); + } - //! Is debug object? - bool IsDebugObject; - }; + //! Removes this scene node from the scene + /** If no other grab exists for this node, it will be deleted. + */ + virtual void remove() + { + if (Parent) + Parent->removeChild(this); + } + //! Returns the material based on the zero based index i. + /** To get the amount of materials used by this scene node, use + getMaterialCount(). This function is needed for inserting the + node into the scene hierarchy at an optimal position for + minimizing renderstate changes, but can also be used to + directly modify the material of a scene node. + \param num Zero based index. The maximal value is getMaterialCount() - 1. + \return The material at that index. */ + virtual video::SMaterial &getMaterial(u32 num) + { + return video::IdentityMaterial; + } + + //! Get amount of materials used by this scene node. + /** \return Current amount of materials of this scene node. */ + virtual u32 getMaterialCount() const + { + return 0; + } + + //! Execute a function on all materials of this scene node. + /** Useful for setting material properties, e.g. if you want the whole + mesh to be affected by light. */ + template + void forEachMaterial(F &&fn) + { + for (u32 i = 0; i < getMaterialCount(); i++) { + fn(getMaterial(i)); + } + } + + //! Gets the scale of the scene node relative to its parent. + /** This is the scale of this node relative to its parent. + If you want the absolute scale, use + getAbsoluteTransformation().getScale() + \return The scale of the scene node. */ + virtual const core::vector3df &getScale() const + { + return RelativeScale; + } + + //! Sets the relative scale of the scene node. + /** \param scale New scale of the node, relative to its parent. */ + virtual void setScale(const core::vector3df &scale) + { + RelativeScale = scale; + } + + //! Gets the rotation of the node relative to its parent. + /** Note that this is the relative rotation of the node. + If you want the absolute rotation, use + getAbsoluteTransformation().getRotation() + \return Current relative rotation of the scene node. */ + virtual const core::vector3df &getRotation() const + { + return RelativeRotation; + } + + //! Sets the rotation of the node relative to its parent. + /** This only modifies the relative rotation of the node. + \param rotation New rotation of the node in degrees. */ + virtual void setRotation(const core::vector3df &rotation) + { + RelativeRotation = rotation; + } + + //! Gets the position of the node relative to its parent. + /** Note that the position is relative to the parent. If you want + the position in world coordinates, use getAbsolutePosition() instead. + \return The current position of the node relative to the parent. */ + virtual const core::vector3df &getPosition() const + { + return RelativeTranslation; + } + + //! Sets the position of the node relative to its parent. + /** Note that the position is relative to the parent. + \param newpos New relative position of the scene node. */ + virtual void setPosition(const core::vector3df &newpos) + { + RelativeTranslation = newpos; + } + + //! Gets the absolute position of the node in world coordinates. + /** If you want the position of the node relative to its parent, + use getPosition() instead. + NOTE: For speed reasons the absolute position is not + automatically recalculated on each change of the relative + position or by a position change of an parent. Instead the + update usually happens once per frame in OnAnimate. You can enforce + an update with updateAbsolutePosition(). + \return The current absolute position of the scene node (updated on last call of updateAbsolutePosition). */ + virtual core::vector3df getAbsolutePosition() const + { + return AbsoluteTransformation.getTranslation(); + } + + //! Set a culling style or disable culling completely. + /** Box cullling (EAC_BOX) is set by default. Note that not + all SceneNodes support culling and that some nodes always cull + their geometry because it is their only reason for existence, + for example the OctreeSceneNode. + \param state The culling state to be used. Check E_CULLING_TYPE for possible values.*/ + void setAutomaticCulling(u32 state) + { + AutomaticCullingState = state; + } + + //! Gets the automatic culling state. + /** \return The automatic culling state. */ + u32 getAutomaticCulling() const + { + return AutomaticCullingState; + } + + //! Sets if debug data like bounding boxes should be drawn. + /** A bitwise OR of the types from @ref irr::scene::E_DEBUG_SCENE_TYPE. + Please note that not all scene nodes support all debug data types. + \param state The debug data visibility state to be used. */ + virtual void setDebugDataVisible(u32 state) + { + DebugDataVisible = state; + } + + //! Returns if debug data like bounding boxes are drawn. + /** \return A bitwise OR of the debug data values from + @ref irr::scene::E_DEBUG_SCENE_TYPE that are currently visible. */ + u32 isDebugDataVisible() const + { + return DebugDataVisible; + } + + //! Sets if this scene node is a debug object. + /** Debug objects have some special properties, for example they can be easily + excluded from collision detection or from serialization, etc. */ + void setIsDebugObject(bool debugObject) + { + IsDebugObject = debugObject; + } + + //! Returns if this scene node is a debug object. + /** Debug objects have some special properties, for example they can be easily + excluded from collision detection or from serialization, etc. + \return If this node is a debug object, true is returned. */ + bool isDebugObject() const + { + return IsDebugObject; + } + + //! Returns a const reference to the list of all children. + /** \return The list of all children of this node. */ + const std::list &getChildren() const + { + return Children; + } + + //! Changes the parent of the scene node. + /** \param newParent The new parent to be used. */ + virtual void setParent(ISceneNode *newParent) + { + grab(); + remove(); + + if (newParent) + newParent->addChild(this); + + drop(); + } + + //! Updates the absolute position based on the relative and the parents position + /** Note: This does not recursively update the parents absolute positions, so if you have a deeper + hierarchy you might want to update the parents first.*/ + virtual void updateAbsolutePosition() + { + if (Parent) { + AbsoluteTransformation = + Parent->getAbsoluteTransformation() * getRelativeTransformation(); + } else + AbsoluteTransformation = getRelativeTransformation(); + } + + //! Returns the parent of this scene node + /** \return A pointer to the parent. */ + scene::ISceneNode *getParent() const + { + return Parent; + } + + //! Returns type of the scene node + /** \return The type of this node. */ + virtual ESCENE_NODE_TYPE getType() const + { + return ESNT_UNKNOWN; + } + + //! Creates a clone of this scene node and its children. + /** \param newParent An optional new parent. + \param newManager An optional new scene manager. + \return The newly created clone of this node. */ + virtual ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) + { + return 0; // to be implemented by derived classes + } + + //! Retrieve the scene manager for this node. + /** \return The node's scene manager. */ + virtual ISceneManager *getSceneManager(void) const { return SceneManager; } + +protected: + //! A clone function for the ISceneNode members. + /** This method can be used by clone() implementations of + derived classes + \param toCopyFrom The node from which the values are copied + \param newManager The new scene manager. */ + void cloneMembers(ISceneNode *toCopyFrom, ISceneManager *newManager) + { + Name = toCopyFrom->Name; + AbsoluteTransformation = toCopyFrom->AbsoluteTransformation; + RelativeTranslation = toCopyFrom->RelativeTranslation; + RelativeRotation = toCopyFrom->RelativeRotation; + RelativeScale = toCopyFrom->RelativeScale; + ID = toCopyFrom->ID; + AutomaticCullingState = toCopyFrom->AutomaticCullingState; + DebugDataVisible = toCopyFrom->DebugDataVisible; + IsVisible = toCopyFrom->IsVisible; + IsDebugObject = toCopyFrom->IsDebugObject; + + if (newManager) + SceneManager = newManager; + else + SceneManager = toCopyFrom->SceneManager; + + // clone children + + ISceneNodeList::iterator it = toCopyFrom->Children.begin(); + for (; it != toCopyFrom->Children.end(); ++it) + (*it)->clone(this, newManager); + } + + //! Sets the new scene manager for this node and all children. + //! Called by addChild when moving nodes between scene managers + void setSceneManager(ISceneManager *newManager) + { + SceneManager = newManager; + + ISceneNodeList::iterator it = Children.begin(); + for (; it != Children.end(); ++it) + (*it)->setSceneManager(newManager); + } + + //! Name of the scene node. + std::optional Name; + + //! Absolute transformation of the node. + core::matrix4 AbsoluteTransformation; + + //! Relative translation of the scene node. + core::vector3df RelativeTranslation; + + //! Relative rotation of the scene node. + core::vector3df RelativeRotation; + + //! Relative scale of the scene node. + core::vector3df RelativeScale; + + //! List of all children of this node + std::list Children; + + //! Iterator pointing to this node in the parent's child list. + std::optional ThisIterator; + + //! Pointer to the parent + ISceneNode *Parent; + + //! Pointer to the scene manager + ISceneManager *SceneManager; + + //! ID of the node. + s32 ID; + + //! Automatic culling state + u32 AutomaticCullingState; + + //! Flag if debug data should be drawn, such as Bounding Boxes. + u32 DebugDataVisible; + + //! Is the node visible? + bool IsVisible; + + //! Is debug object? + bool IsDebugObject; +}; } // end namespace scene } // end namespace irr diff --git a/include/IShaderConstantSetCallBack.h b/include/IShaderConstantSetCallBack.h index 1bc7e4ae..2e37a34a 100644 --- a/include/IShaderConstantSetCallBack.h +++ b/include/IShaderConstantSetCallBack.h @@ -10,8 +10,8 @@ namespace irr { namespace video { - class IMaterialRendererServices; - class SMaterial; +class IMaterialRendererServices; +class SMaterial; //! Interface making it possible to set constants for gpu programs every frame. /** Implement this interface in an own class and pass a pointer to it to one of @@ -20,7 +20,6 @@ OnSetConstants method will be called every frame now. */ class IShaderConstantSetCallBack : public virtual IReferenceCounted { public: - //! Called to let the callBack know the used material (optional method) /** \code @@ -40,7 +39,7 @@ public: } \endcode */ - virtual void OnSetMaterial(const SMaterial& material) { } + virtual void OnSetMaterial(const SMaterial &material) {} //! Called by the engine when the vertex and/or pixel shader constants for an material renderer should be set. /** @@ -73,9 +72,8 @@ public: \param services: Pointer to an interface providing methods to set the constants for the shader. \param userData: Userdata int which can be specified when creating the shader. */ - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData) = 0; + virtual void OnSetConstants(IMaterialRendererServices *services, s32 userData) = 0; }; - } // end namespace video } // end namespace irr diff --git a/include/ISkinnedMesh.h b/include/ISkinnedMesh.h index a8bc2625..9cc7469c 100644 --- a/include/ISkinnedMesh.h +++ b/include/ISkinnedMesh.h @@ -16,208 +16,205 @@ namespace irr namespace scene { - enum E_INTERPOLATION_MODE +enum E_INTERPOLATION_MODE +{ + // constant does use the current key-values without interpolation + EIM_CONSTANT = 0, + + // linear interpolation + EIM_LINEAR, + + //! count of all available interpolation modes + EIM_COUNT +}; + +//! Interface for using some special functions of Skinned meshes +class ISkinnedMesh : public IAnimatedMesh +{ +public: + //! Gets joint count. + /** \return Amount of joints in the skeletal animated mesh. */ + virtual u32 getJointCount() const = 0; + + //! Gets the name of a joint. + /** \param number: Zero based index of joint. The last joint + has the number getJointCount()-1; + \return Name of joint and null if an error happened. */ + virtual const std::optional &getJointName(u32 number) const = 0; + + //! Gets a joint number from its name + /** \param name: Name of the joint. + \return Number of the joint or std::nullopt if not found. */ + virtual std::optional getJointNumber(const std::string &name) const = 0; + + //! Use animation from another mesh + /** The animation is linked (not copied) based on joint names + so make sure they are unique. + \return True if all joints in this mesh were + matched up (empty names will not be matched, and it's case + sensitive). Unmatched joints will not be animated. */ + virtual bool useAnimationFrom(const ISkinnedMesh *mesh) = 0; + + //! Update Normals when Animating + /** \param on If false don't animate, which is faster. + Else update normals, which allows for proper lighting of + animated meshes. */ + virtual void updateNormalsWhenAnimating(bool on) = 0; + + //! Sets Interpolation Mode + virtual void setInterpolationMode(E_INTERPOLATION_MODE mode) = 0; + + //! Animates this mesh's joints based on frame input + virtual void animateMesh(f32 frame, f32 blend) = 0; + + //! Preforms a software skin on this mesh based of joint positions + virtual void skinMesh() = 0; + + //! converts the vertex type of all meshbuffers to tangents. + /** E.g. used for bump mapping. */ + virtual void convertMeshToTangents() = 0; + + //! Allows to enable hardware skinning. + /* This feature is not implemented in Irrlicht yet */ + virtual bool setHardwareSkinning(bool on) = 0; + + //! Refreshes vertex data cached in joints such as positions and normals + virtual void refreshJointCache() = 0; + + //! Moves the mesh into static position. + virtual void resetAnimation() = 0; + + //! A vertex weight + struct SWeight { - // constant does use the current key-values without interpolation - EIM_CONSTANT = 0, + //! Index of the mesh buffer + u16 buffer_id; // I doubt 32bits is needed - // linear interpolation - EIM_LINEAR, + //! Index of the vertex + u32 vertex_id; // Store global ID here - //! count of all available interpolation modes - EIM_COUNT + //! Weight Strength/Percentage (0-1) + f32 strength; + + private: + //! Internal members used by CSkinnedMesh + friend class CSkinnedMesh; + char *Moved; + core::vector3df StaticPos; + core::vector3df StaticNormal; }; - - //! Interface for using some special functions of Skinned meshes - class ISkinnedMesh : public IAnimatedMesh + //! Animation keyframe which describes a new position + struct SPositionKey { - public: - - //! Gets joint count. - /** \return Amount of joints in the skeletal animated mesh. */ - virtual u32 getJointCount() const = 0; - - //! Gets the name of a joint. - /** \param number: Zero based index of joint. The last joint - has the number getJointCount()-1; - \return Name of joint and null if an error happened. */ - virtual const std::optional &getJointName(u32 number) const = 0; - - //! Gets a joint number from its name - /** \param name: Name of the joint. - \return Number of the joint or std::nullopt if not found. */ - virtual std::optional getJointNumber(const std::string &name) const = 0; - - //! Use animation from another mesh - /** The animation is linked (not copied) based on joint names - so make sure they are unique. - \return True if all joints in this mesh were - matched up (empty names will not be matched, and it's case - sensitive). Unmatched joints will not be animated. */ - virtual bool useAnimationFrom(const ISkinnedMesh *mesh) = 0; - - //! Update Normals when Animating - /** \param on If false don't animate, which is faster. - Else update normals, which allows for proper lighting of - animated meshes. */ - virtual void updateNormalsWhenAnimating(bool on) = 0; - - //! Sets Interpolation Mode - virtual void setInterpolationMode(E_INTERPOLATION_MODE mode) = 0; - - //! Animates this mesh's joints based on frame input - virtual void animateMesh(f32 frame, f32 blend)=0; - - //! Preforms a software skin on this mesh based of joint positions - virtual void skinMesh() = 0; - - //! converts the vertex type of all meshbuffers to tangents. - /** E.g. used for bump mapping. */ - virtual void convertMeshToTangents() = 0; - - //! Allows to enable hardware skinning. - /* This feature is not implemented in Irrlicht yet */ - virtual bool setHardwareSkinning(bool on) = 0; - - //! Refreshes vertex data cached in joints such as positions and normals - virtual void refreshJointCache() = 0; - - //! Moves the mesh into static position. - virtual void resetAnimation() = 0; - - //! A vertex weight - struct SWeight - { - //! Index of the mesh buffer - u16 buffer_id; //I doubt 32bits is needed - - //! Index of the vertex - u32 vertex_id; //Store global ID here - - //! Weight Strength/Percentage (0-1) - f32 strength; - - private: - //! Internal members used by CSkinnedMesh - friend class CSkinnedMesh; - char *Moved; - core::vector3df StaticPos; - core::vector3df StaticNormal; - }; - - - //! Animation keyframe which describes a new position - struct SPositionKey - { - f32 frame; - core::vector3df position; - }; - - //! Animation keyframe which describes a new scale - struct SScaleKey - { - f32 frame; - core::vector3df scale; - }; - - //! Animation keyframe which describes a new rotation - struct SRotationKey - { - f32 frame; - core::quaternion rotation; - }; - - //! Joints - struct SJoint - { - SJoint() : UseAnimationFrom(0), GlobalSkinningSpace(false), - positionHint(-1),scaleHint(-1),rotationHint(-1) - { - } - - //! The name of this joint - std::optional Name; - - //! Local matrix of this joint - core::matrix4 LocalMatrix; - - //! List of child joints - core::array Children; - - //! List of attached meshes - core::array AttachedMeshes; - - //! Animation keys causing translation change - core::array PositionKeys; - - //! Animation keys causing scale change - core::array ScaleKeys; - - //! Animation keys causing rotation change - core::array RotationKeys; - - //! Skin weights - core::array Weights; - - //! Unnecessary for loaders, will be overwritten on finalize - core::matrix4 GlobalMatrix; - core::matrix4 GlobalAnimatedMatrix; - core::matrix4 LocalAnimatedMatrix; - core::vector3df Animatedposition; - core::vector3df Animatedscale; - core::quaternion Animatedrotation; - - core::matrix4 GlobalInversedMatrix; //the x format pre-calculates this - - private: - //! Internal members used by CSkinnedMesh - friend class CSkinnedMesh; - - SJoint *UseAnimationFrom; - bool GlobalSkinningSpace; - - s32 positionHint; - s32 scaleHint; - s32 rotationHint; - }; - - - //Interface for the mesh loaders (finalize should lock these functions, and they should have some prefix like loader_ - - //these functions will use the needed arrays, set values, etc to help the loaders - - //! exposed for loaders: to add mesh buffers - virtual core::array& getMeshBuffers() = 0; - - //! exposed for loaders: joints list - virtual core::array& getAllJoints() = 0; - - //! exposed for loaders: joints list - virtual const core::array& getAllJoints() const = 0; - - //! loaders should call this after populating the mesh - virtual void finalize() = 0; - - //! Adds a new meshbuffer to the mesh, access it as last one - virtual SSkinMeshBuffer* addMeshBuffer() = 0; - - //! Adds a new joint to the mesh, access it as last one - virtual SJoint* addJoint(SJoint *parent=0) = 0; - - //! Adds a new weight to the mesh, access it as last one - virtual SWeight* addWeight(SJoint *joint) = 0; - - //! Adds a new position key to the mesh, access it as last one - virtual SPositionKey* addPositionKey(SJoint *joint) = 0; - //! Adds a new scale key to the mesh, access it as last one - virtual SScaleKey* addScaleKey(SJoint *joint) = 0; - //! Adds a new rotation key to the mesh, access it as last one - virtual SRotationKey* addRotationKey(SJoint *joint) = 0; - - //! Check if the mesh is non-animated - virtual bool isStatic()=0; + f32 frame; + core::vector3df position; }; + //! Animation keyframe which describes a new scale + struct SScaleKey + { + f32 frame; + core::vector3df scale; + }; + + //! Animation keyframe which describes a new rotation + struct SRotationKey + { + f32 frame; + core::quaternion rotation; + }; + + //! Joints + struct SJoint + { + SJoint() : + UseAnimationFrom(0), GlobalSkinningSpace(false), + positionHint(-1), scaleHint(-1), rotationHint(-1) + { + } + + //! The name of this joint + std::optional Name; + + //! Local matrix of this joint + core::matrix4 LocalMatrix; + + //! List of child joints + core::array Children; + + //! List of attached meshes + core::array AttachedMeshes; + + //! Animation keys causing translation change + core::array PositionKeys; + + //! Animation keys causing scale change + core::array ScaleKeys; + + //! Animation keys causing rotation change + core::array RotationKeys; + + //! Skin weights + core::array Weights; + + //! Unnecessary for loaders, will be overwritten on finalize + core::matrix4 GlobalMatrix; + core::matrix4 GlobalAnimatedMatrix; + core::matrix4 LocalAnimatedMatrix; + core::vector3df Animatedposition; + core::vector3df Animatedscale; + core::quaternion Animatedrotation; + + core::matrix4 GlobalInversedMatrix; // the x format pre-calculates this + + private: + //! Internal members used by CSkinnedMesh + friend class CSkinnedMesh; + + SJoint *UseAnimationFrom; + bool GlobalSkinningSpace; + + s32 positionHint; + s32 scaleHint; + s32 rotationHint; + }; + + // Interface for the mesh loaders (finalize should lock these functions, and they should have some prefix like loader_ + + // these functions will use the needed arrays, set values, etc to help the loaders + + //! exposed for loaders: to add mesh buffers + virtual core::array &getMeshBuffers() = 0; + + //! exposed for loaders: joints list + virtual core::array &getAllJoints() = 0; + + //! exposed for loaders: joints list + virtual const core::array &getAllJoints() const = 0; + + //! loaders should call this after populating the mesh + virtual void finalize() = 0; + + //! Adds a new meshbuffer to the mesh, access it as last one + virtual SSkinMeshBuffer *addMeshBuffer() = 0; + + //! Adds a new joint to the mesh, access it as last one + virtual SJoint *addJoint(SJoint *parent = 0) = 0; + + //! Adds a new weight to the mesh, access it as last one + virtual SWeight *addWeight(SJoint *joint) = 0; + + //! Adds a new position key to the mesh, access it as last one + virtual SPositionKey *addPositionKey(SJoint *joint) = 0; + //! Adds a new scale key to the mesh, access it as last one + virtual SScaleKey *addScaleKey(SJoint *joint) = 0; + //! Adds a new rotation key to the mesh, access it as last one + virtual SRotationKey *addRotationKey(SJoint *joint) = 0; + + //! Check if the mesh is non-animated + virtual bool isStatic() = 0; +}; + } // end namespace scene } // end namespace irr diff --git a/include/ITexture.h b/include/ITexture.h index 8724e209..adca90e7 100644 --- a/include/ITexture.h +++ b/include/ITexture.h @@ -16,7 +16,6 @@ namespace irr namespace video { - //! Enumeration flags used to tell the video driver with setTextureCreationFlag in which format textures should be created. enum E_TEXTURE_CREATION_FLAG { @@ -66,7 +65,7 @@ enum E_TEXTURE_CREATION_FLAG /** Discard any alpha layer and use non-alpha color format. Warning: This may lead to getting 24-bit texture formats which - are often badly supported by drivers. So it's generally + are often badly supported by drivers. So it's generally not recommended to enable this flag. */ ETCF_NO_ALPHA_CHANNEL = 0x00000020, @@ -176,10 +175,10 @@ and write a warning or an error message to the output buffer. class ITexture : public virtual IReferenceCounted { public: - //! constructor - ITexture(const io::path& name, E_TEXTURE_TYPE type) : NamedPath(name), DriverType(EDT_NULL), OriginalColorFormat(ECF_UNKNOWN), - ColorFormat(ECF_UNKNOWN), Pitch(0), HasMipMaps(false), IsRenderTarget(false), Source(ETS_UNKNOWN), Type(type) + ITexture(const io::path &name, E_TEXTURE_TYPE type) : + NamedPath(name), DriverType(EDT_NULL), OriginalColorFormat(ECF_UNKNOWN), + ColorFormat(ECF_UNKNOWN), Pitch(0), HasMipMaps(false), IsRenderTarget(false), Source(ETS_UNKNOWN), Type(type) { } @@ -206,7 +205,7 @@ public: \return Returns a pointer to the pixel data. The format of the pixel can be determined by using getColorFormat(). 0 is returned, if the texture cannot be locked. */ - virtual void* lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel=0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) = 0; + virtual void *lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel = 0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) = 0; //! Unlock function. Must be called after a lock() to the texture. /** One should avoid to call unlock more than once before another lock. @@ -223,7 +222,7 @@ public: level. At least one pixel will be always kept. \param layer It informs a texture about which cubemap or texture array layer needs mipmap regeneration. */ - virtual void regenerateMipMapLevels(void* data = 0, u32 layer = 0) = 0; + virtual void regenerateMipMapLevels(void *data = 0, u32 layer = 0) = 0; //! Get original size of the texture. /** The texture is usually scaled, if it was created with an unoptimal @@ -233,11 +232,11 @@ public: exact size of the original texture. Use ITexture::getSize() if you want to know the real size it has now stored in the system. \return The original size of the texture. */ - const core::dimension2d& getOriginalSize() const { return OriginalSize; }; + const core::dimension2d &getOriginalSize() const { return OriginalSize; }; //! Get dimension (=size) of the texture. /** \return The size of the texture. */ - const core::dimension2d& getSize() const { return Size; }; + const core::dimension2d &getSize() const { return Size; }; //! Get driver type of texture. /** This is the driver, which created the texture. This method is used @@ -274,7 +273,7 @@ public: bool isRenderTarget() const { return IsRenderTarget; } //! Get name of texture (in most cases this is the filename) - const io::SNamedPath& getName() const { return NamedPath; } + const io::SNamedPath &getName() const { return NamedPath; } //! Check where the last IVideoDriver::getTexture found this texture E_TEXTURE_SOURCE getSource() const { return Source; } @@ -287,8 +286,7 @@ public: { bool status = false; - switch (ColorFormat) - { + switch (ColorFormat) { case ECF_A8R8G8B8: case ECF_A1R5G5B5: case ECF_A16B16G16R16F: @@ -306,7 +304,6 @@ public: E_TEXTURE_TYPE getType() const { return Type; } protected: - //! Helper function, helps to get the desired texture creation format from the flags. /** \return Either ETCF_ALWAYS_32_BIT, ETCF_ALWAYS_16_BIT, ETCF_OPTIMIZED_FOR_QUALITY, or ETCF_OPTIMIZED_FOR_SPEED. */ @@ -336,6 +333,5 @@ protected: E_TEXTURE_TYPE Type; }; - } // end namespace video } // end namespace irr diff --git a/include/IVertexBuffer.h b/include/IVertexBuffer.h index 883cae58..a4ec5efd 100644 --- a/include/IVertexBuffer.h +++ b/include/IVertexBuffer.h @@ -14,36 +14,35 @@ namespace irr namespace scene { - class IVertexBuffer : public virtual IReferenceCounted - { - public: - virtual void* getData() =0; - virtual video::E_VERTEX_TYPE getType() const =0; - virtual void setType(video::E_VERTEX_TYPE vertexType) =0; - virtual u32 stride() const =0; - virtual u32 size() const =0; - virtual void push_back(const video::S3DVertex &element) =0; - virtual video::S3DVertex& operator [](const u32 index) const =0; - virtual video::S3DVertex& getLast() =0; - virtual void set_used(u32 usedNow) =0; - virtual void reallocate(u32 new_size) =0; - virtual u32 allocated_size() const =0; - virtual video::S3DVertex* pointer() =0; +class IVertexBuffer : public virtual IReferenceCounted +{ +public: + virtual void *getData() = 0; + virtual video::E_VERTEX_TYPE getType() const = 0; + virtual void setType(video::E_VERTEX_TYPE vertexType) = 0; + virtual u32 stride() const = 0; + virtual u32 size() const = 0; + virtual void push_back(const video::S3DVertex &element) = 0; + virtual video::S3DVertex &operator[](const u32 index) const = 0; + virtual video::S3DVertex &getLast() = 0; + virtual void set_used(u32 usedNow) = 0; + virtual void reallocate(u32 new_size) = 0; + virtual u32 allocated_size() const = 0; + virtual video::S3DVertex *pointer() = 0; - //! get the current hardware mapping hint - virtual E_HARDWARE_MAPPING getHardwareMappingHint() const =0; + //! get the current hardware mapping hint + virtual E_HARDWARE_MAPPING getHardwareMappingHint() const = 0; - //! set the hardware mapping hint, for driver - virtual void setHardwareMappingHint( E_HARDWARE_MAPPING NewMappingHint ) =0; + //! set the hardware mapping hint, for driver + virtual void setHardwareMappingHint(E_HARDWARE_MAPPING NewMappingHint) = 0; - //! flags the meshbuffer as changed, reloads hardware buffers - virtual void setDirty() =0; - - //! Get the currently used ID for identification of changes. - /** This shouldn't be used for anything outside the VideoDriver. */ - virtual u32 getChangedID() const = 0; - }; + //! flags the meshbuffer as changed, reloads hardware buffers + virtual void setDirty() = 0; + //! Get the currently used ID for identification of changes. + /** This shouldn't be used for anything outside the VideoDriver. */ + virtual u32 getChangedID() const = 0; +}; } // end namespace scene } // end namespace irr diff --git a/include/IVideoDriver.h b/include/IVideoDriver.h index e2b2d58f..3b8dcd09 100644 --- a/include/IVideoDriver.h +++ b/include/IVideoDriver.h @@ -22,1190 +22,1186 @@ namespace irr { namespace io { - class IAttributes; - class IReadFile; - class IWriteFile; +class IAttributes; +class IReadFile; +class IWriteFile; } // end namespace io namespace scene { - class IMeshBuffer; - class IMesh; - class IMeshManipulator; - class ISceneNode; +class IMeshBuffer; +class IMesh; +class IMeshManipulator; +class ISceneNode; } // end namespace scene namespace video { - struct S3DVertex; - struct S3DVertex2TCoords; - struct S3DVertexTangents; - class IImageLoader; - class IImageWriter; - class IMaterialRenderer; - class IGPUProgrammingServices; - class IRenderTarget; +struct S3DVertex; +struct S3DVertex2TCoords; +struct S3DVertexTangents; +class IImageLoader; +class IImageWriter; +class IMaterialRenderer; +class IGPUProgrammingServices; +class IRenderTarget; - //! enumeration for geometry transformation states - enum E_TRANSFORMATION_STATE +//! enumeration for geometry transformation states +enum E_TRANSFORMATION_STATE +{ + //! View transformation + ETS_VIEW = 0, + //! World transformation + ETS_WORLD, + //! Projection transformation + ETS_PROJECTION, + //! Texture 0 transformation + //! Use E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + texture_number) to access other texture transformations + ETS_TEXTURE_0, + //! Only used internally + ETS_COUNT = ETS_TEXTURE_0 + MATERIAL_MAX_TEXTURES +}; + +//! Special render targets, which usually map to dedicated hardware +/** These render targets (besides 0 and 1) need not be supported by gfx cards */ +enum E_RENDER_TARGET +{ + //! Render target is the main color frame buffer + ERT_FRAME_BUFFER = 0, + //! Render target is a render texture + ERT_RENDER_TEXTURE, + //! Multi-Render target textures + ERT_MULTI_RENDER_TEXTURES, + //! Render target is the main color frame buffer + ERT_STEREO_LEFT_BUFFER, + //! Render target is the right color buffer (left is the main buffer) + ERT_STEREO_RIGHT_BUFFER, + //! Render to both stereo buffers at once + ERT_STEREO_BOTH_BUFFERS, + //! Auxiliary buffer 0 + ERT_AUX_BUFFER0, + //! Auxiliary buffer 1 + ERT_AUX_BUFFER1, + //! Auxiliary buffer 2 + ERT_AUX_BUFFER2, + //! Auxiliary buffer 3 + ERT_AUX_BUFFER3, + //! Auxiliary buffer 4 + ERT_AUX_BUFFER4 +}; + +//! Enum for the flags of clear buffer +enum E_CLEAR_BUFFER_FLAG +{ + ECBF_NONE = 0, + ECBF_COLOR = 1, + ECBF_DEPTH = 2, + ECBF_STENCIL = 4, + ECBF_ALL = ECBF_COLOR | ECBF_DEPTH | ECBF_STENCIL +}; + +//! Enum for the types of fog distributions to choose from +enum E_FOG_TYPE +{ + EFT_FOG_EXP = 0, + EFT_FOG_LINEAR, + EFT_FOG_EXP2 +}; + +const c8 *const FogTypeNames[] = + { + "FogExp", + "FogLinear", + "FogExp2", + 0}; + +//! Interface to driver which is able to perform 2d and 3d graphics functions. +/** This interface is one of the most important interfaces of +the Irrlicht Engine: All rendering and texture manipulation is done with +this interface. You are able to use the Irrlicht Engine by only +invoking methods of this interface if you like to, although the +irr::scene::ISceneManager interface provides a lot of powerful classes +and methods to make the programmer's life easier. +*/ +class IVideoDriver : public virtual IReferenceCounted +{ +public: + //! Applications must call this method before performing any rendering. + /** This method can clear the back- and the z-buffer. + \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. + \param clearColor The clear color for the color buffer. + \param clearDepth The clear value for the depth buffer. + \param clearStencil The clear value for the stencil buffer. + \param videoData Handle of another window, if you want the + bitmap to be displayed on another window. If this is an empty + element, everything will be displayed in the default window. + Note: This feature is not fully implemented for all devices. + \param sourceRect Pointer to a rectangle defining the source + rectangle of the area to be presented. Set to null to present + everything. Note: not implemented in all devices. + \return False if failed. */ + virtual bool beginScene(u16 clearFlag = (u16)(ECBF_COLOR | ECBF_DEPTH), SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) = 0; + + //! Alternative beginScene implementation. Can't clear stencil buffer, but otherwise identical to other beginScene + bool beginScene(bool backBuffer, bool zBuffer, SColor color = SColor(255, 0, 0, 0), + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) { - //! View transformation - ETS_VIEW = 0, - //! World transformation - ETS_WORLD, - //! Projection transformation - ETS_PROJECTION, - //! Texture 0 transformation - //! Use E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + texture_number) to access other texture transformations - ETS_TEXTURE_0, - //! Only used internally - ETS_COUNT = ETS_TEXTURE_0 + MATERIAL_MAX_TEXTURES - }; + u16 flag = 0; - //! Special render targets, which usually map to dedicated hardware - /** These render targets (besides 0 and 1) need not be supported by gfx cards */ - enum E_RENDER_TARGET - { - //! Render target is the main color frame buffer - ERT_FRAME_BUFFER=0, - //! Render target is a render texture - ERT_RENDER_TEXTURE, - //! Multi-Render target textures - ERT_MULTI_RENDER_TEXTURES, - //! Render target is the main color frame buffer - ERT_STEREO_LEFT_BUFFER, - //! Render target is the right color buffer (left is the main buffer) - ERT_STEREO_RIGHT_BUFFER, - //! Render to both stereo buffers at once - ERT_STEREO_BOTH_BUFFERS, - //! Auxiliary buffer 0 - ERT_AUX_BUFFER0, - //! Auxiliary buffer 1 - ERT_AUX_BUFFER1, - //! Auxiliary buffer 2 - ERT_AUX_BUFFER2, - //! Auxiliary buffer 3 - ERT_AUX_BUFFER3, - //! Auxiliary buffer 4 - ERT_AUX_BUFFER4 - }; + if (backBuffer) + flag |= ECBF_COLOR; - //! Enum for the flags of clear buffer - enum E_CLEAR_BUFFER_FLAG - { - ECBF_NONE = 0, - ECBF_COLOR = 1, - ECBF_DEPTH = 2, - ECBF_STENCIL = 4, - ECBF_ALL = ECBF_COLOR|ECBF_DEPTH|ECBF_STENCIL - }; + if (zBuffer) + flag |= ECBF_DEPTH; - //! Enum for the types of fog distributions to choose from - enum E_FOG_TYPE - { - EFT_FOG_EXP=0, - EFT_FOG_LINEAR, - EFT_FOG_EXP2 - }; + return beginScene(flag, color, 1.f, 0, videoData, sourceRect); + } - const c8* const FogTypeNames[] = - { - "FogExp", - "FogLinear", - "FogExp2", - 0 - }; + //! Presents the rendered image to the screen. + /** Applications must call this method after performing any + rendering. + \return False if failed and true if succeeded. */ + virtual bool endScene() = 0; - //! Interface to driver which is able to perform 2d and 3d graphics functions. - /** This interface is one of the most important interfaces of - the Irrlicht Engine: All rendering and texture manipulation is done with - this interface. You are able to use the Irrlicht Engine by only - invoking methods of this interface if you like to, although the - irr::scene::ISceneManager interface provides a lot of powerful classes - and methods to make the programmer's life easier. + //! Queries the features of the driver. + /** Returns true if a feature is available + \param feature Feature to query. + \return True if the feature is available, false if not. */ + virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const = 0; + + //! Disable a feature of the driver. + /** Can also be used to enable the features again. It is not + possible to enable unsupported features this way, though. + \param feature Feature to disable. + \param flag When true the feature is disabled, otherwise it is enabled. */ + virtual void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag = true) = 0; + + //! Get attributes of the actual video driver + /** The following names can be queried for the given types: + MaxTextures (int) The maximum number of simultaneous textures supported by the driver. This can be less than the supported number of textures of the driver. Use _IRR_MATERIAL_MAX_TEXTURES_ to adapt the number. + MaxSupportedTextures (int) The maximum number of simultaneous textures supported by the fixed function pipeline of the (hw) driver. The actual supported number of textures supported by the engine can be lower. + MaxLights (int) Number of hardware lights supported in the fixed function pipeline of the driver, typically 6-8. Use light manager or deferred shading for more. + MaxAnisotropy (int) Number of anisotropy levels supported for filtering. At least 1, max is typically at 16 or 32. + MaxUserClipPlanes (int) Number of additional clip planes, which can be set by the user via dedicated driver methods. + MaxAuxBuffers (int) Special render buffers, which are currently not really usable inside Irrlicht. Only supported by OpenGL + MaxMultipleRenderTargets (int) Number of render targets which can be bound simultaneously. Rendering to MRTs is done via shaders. + MaxIndices (int) Number of indices which can be used in one render call (i.e. one mesh buffer). + MaxTextureSize (int) Dimension that a texture may have, both in width and height. + MaxGeometryVerticesOut (int) Number of vertices the geometry shader can output in one pass. Only OpenGL so far. + MaxTextureLODBias (float) Maximum value for LOD bias. Is usually at around 16, but can be lower on some systems. + Version (int) Version of the driver. Should be Major*100+Minor + ShaderLanguageVersion (int) Version of the high level shader language. Should be Major*100+Minor. + AntiAlias (int) Number of Samples the driver uses for each pixel. 0 and 1 means anti aliasing is off, typical values are 2,4,8,16,32 */ - class IVideoDriver : public virtual IReferenceCounted + virtual const io::IAttributes &getDriverAttributes() const = 0; + + //! Check if the driver was recently reset. + /** For d3d devices you will need to recreate the RTTs if the + driver was reset. Should be queried right after beginScene(). + */ + virtual bool checkDriverReset() = 0; + + //! Sets transformation matrices. + /** \param state Transformation type to be set, e.g. view, + world, or projection. + \param mat Matrix describing the transformation. */ + virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) = 0; + + //! Returns the transformation set by setTransform + /** \param state Transformation type to query + \return Matrix describing the transformation. */ + virtual const core::matrix4 &getTransform(E_TRANSFORMATION_STATE state) const = 0; + + //! Retrieve the number of image loaders + /** \return Number of image loaders */ + virtual u32 getImageLoaderCount() const = 0; + + //! Retrieve the given image loader + /** \param n The index of the loader to retrieve. This parameter is an 0-based + array index. + \return A pointer to the specified loader, 0 if the index is incorrect. */ + virtual IImageLoader *getImageLoader(u32 n) = 0; + + //! Retrieve the number of image writers + /** \return Number of image writers */ + virtual u32 getImageWriterCount() const = 0; + + //! Retrieve the given image writer + /** \param n The index of the writer to retrieve. This parameter is an 0-based + array index. + \return A pointer to the specified writer, 0 if the index is incorrect. */ + virtual IImageWriter *getImageWriter(u32 n) = 0; + + //! Sets a material. + /** All 3d drawing functions will draw geometry using this material thereafter. + \param material: Material to be used from now on. */ + virtual void setMaterial(const SMaterial &material) = 0; + + //! Get access to a named texture. + /** Loads the texture from disk if it is not + already loaded and generates mipmap levels if desired. + Texture loading can be influenced using the + setTextureCreationFlag() method. The texture can be in several + imageformats, such as BMP, JPG, TGA, PCX, PNG, and PSD. + \param filename Filename of the texture to be loaded. + \return Pointer to the texture, or 0 if the texture + could not be loaded. This pointer should not be dropped. See + IReferenceCounted::drop() for more information. */ + virtual ITexture *getTexture(const io::path &filename) = 0; + + //! Get access to a named texture. + /** Loads the texture from disk if it is not + already loaded and generates mipmap levels if desired. + Texture loading can be influenced using the + setTextureCreationFlag() method. The texture can be in several + imageformats, such as BMP, JPG, TGA, PCX, PNG, and PSD. + \param file Pointer to an already opened file. + \return Pointer to the texture, or 0 if the texture + could not be loaded. This pointer should not be dropped. See + IReferenceCounted::drop() for more information. */ + virtual ITexture *getTexture(io::IReadFile *file) = 0; + + //! Returns amount of textures currently loaded + /** \return Amount of textures currently loaded */ + virtual u32 getTextureCount() const = 0; + + //! Creates an empty texture of specified size. + /** \param size: Size of the texture. + \param name A name for the texture. Later calls to + getTexture() with this name will return this texture. + The name can _not_ be empty. + \param format Desired color format of the texture. Please note + that the driver may choose to create the texture in another + color format. + \return Pointer to the newly created texture. This pointer + should not be dropped. See IReferenceCounted::drop() for more + information. */ + virtual ITexture *addTexture(const core::dimension2d &size, + const io::path &name, ECOLOR_FORMAT format = ECF_A8R8G8B8) = 0; + + //! Creates a texture from an IImage. + /** \param name A name for the texture. Later calls of + getTexture() with this name will return this texture. + The name can _not_ be empty. + \param image Image the texture is created from. + \return Pointer to the newly created texture. This pointer + should not be dropped. See IReferenceCounted::drop() for more + information. */ + virtual ITexture *addTexture(const io::path &name, IImage *image) = 0; + + //! Creates a cubemap texture from loaded IImages. + /** \param name A name for the texture. Later calls of getTexture() with this name will return this texture. + The name can _not_ be empty. + \param imagePosX Image (positive X) the texture is created from. + \param imageNegX Image (negative X) the texture is created from. + \param imagePosY Image (positive Y) the texture is created from. + \param imageNegY Image (negative Y) the texture is created from. + \param imagePosZ Image (positive Z) the texture is created from. + \param imageNegZ Image (negative Z) the texture is created from. + \return Pointer to the newly created texture. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ + virtual ITexture *addTextureCubemap(const io::path &name, IImage *imagePosX, IImage *imageNegX, IImage *imagePosY, + IImage *imageNegY, IImage *imagePosZ, IImage *imageNegZ) = 0; + + //! Creates an empty cubemap texture of specified size. + /** \param sideLen diameter of one side of the cube + \param name A name for the texture. Later calls of + getTexture() with this name will return this texture. + The name can _not_ be empty. + \param format Desired color format of the texture. Please note + that the driver may choose to create the texture in another + color format. + \return Pointer to the newly created texture. */ + virtual ITexture *addTextureCubemap(const irr::u32 sideLen, const io::path &name, ECOLOR_FORMAT format = ECF_A8R8G8B8) = 0; + + //! Adds a new render target texture to the texture cache. + /** \param size Size of the texture, in pixels. Width and + height should be a power of two (e.g. 64, 128, 256, 512, ...) + and it should not be bigger than the backbuffer, because it + shares the zbuffer with the screen buffer. + \param name A name for the texture. Later calls of getTexture() with this name will return this texture. + The name can _not_ be empty. + \param format The color format of the render target. Floating point formats are supported. + \return Pointer to the created texture or 0 if the texture + could not be created. This pointer should not be dropped. See + IReferenceCounted::drop() for more information. + You may want to remove it from driver texture cache with removeTexture if you no longer need it. + */ + virtual ITexture *addRenderTargetTexture(const core::dimension2d &size, + const io::path &name = "rt", const ECOLOR_FORMAT format = ECF_UNKNOWN) = 0; + + //! Adds a new render target texture with 6 sides for a cubemap map to the texture cache. + /** \param sideLen Length of one cubemap side. + \param name A name for the texture. Later calls of getTexture() with this name will return this texture. + The name can _not_ be empty. + \param format The color format of the render target. Floating point formats are supported. + \return Pointer to the created texture or 0 if the texture + could not be created. This pointer should not be dropped. See + IReferenceCounted::drop() for more information. */ + virtual ITexture *addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name = "rt", const ECOLOR_FORMAT format = ECF_UNKNOWN) = 0; + + //! Removes a texture from the texture cache and deletes it. + /** This method can free a lot of memory! + Please note that after calling this, the pointer to the + ITexture may no longer be valid, if it was not grabbed before + by other parts of the engine for storing it longer. So it is a + good idea to set all materials which are using this texture to + 0 or another texture first. + \param texture Texture to delete from the engine cache. */ + virtual void removeTexture(ITexture *texture) = 0; + + //! Removes all textures from the texture cache and deletes them. + /** This method can free a lot of memory! + Please note that after calling this, the pointer to the + ITexture may no longer be valid, if it was not grabbed before + by other parts of the engine for storing it longer. So it is a + good idea to set all materials which are using this texture to + 0 or another texture first. */ + virtual void removeAllTextures() = 0; + + //! Remove hardware buffer + virtual void removeHardwareBuffer(const scene::IMeshBuffer *mb) = 0; + + //! Remove all hardware buffers + virtual void removeAllHardwareBuffers() = 0; + + //! Create occlusion query. + /** Use node for identification and mesh for occlusion test. */ + virtual void addOcclusionQuery(scene::ISceneNode *node, + const scene::IMesh *mesh = 0) = 0; + + //! Remove occlusion query. + virtual void removeOcclusionQuery(scene::ISceneNode *node) = 0; + + //! Remove all occlusion queries. + virtual void removeAllOcclusionQueries() = 0; + + //! Run occlusion query. Draws mesh stored in query. + /** If the mesh shall not be rendered visible, use + overrideMaterial to disable the color and depth buffer. */ + virtual void runOcclusionQuery(scene::ISceneNode *node, bool visible = false) = 0; + + //! Run all occlusion queries. Draws all meshes stored in queries. + /** If the meshes shall not be rendered visible, use + overrideMaterial to disable the color and depth buffer. */ + virtual void runAllOcclusionQueries(bool visible = false) = 0; + + //! Update occlusion query. Retrieves results from GPU. + /** If the query shall not block, set the flag to false. + Update might not occur in this case, though */ + virtual void updateOcclusionQuery(scene::ISceneNode *node, bool block = true) = 0; + + //! Update all occlusion queries. Retrieves results from GPU. + /** If the query shall not block, set the flag to false. + Update might not occur in this case, though */ + virtual void updateAllOcclusionQueries(bool block = true) = 0; + + //! Return query result. + /** Return value is the number of visible pixels/fragments. + The value is a safe approximation, i.e. can be larger than the + actual value of pixels. */ + virtual u32 getOcclusionQueryResult(scene::ISceneNode *node) const = 0; + + //! Create render target. + virtual IRenderTarget *addRenderTarget() = 0; + + //! Remove render target. + virtual void removeRenderTarget(IRenderTarget *renderTarget) = 0; + + //! Remove all render targets. + virtual void removeAllRenderTargets() = 0; + + //! Sets a boolean alpha channel on the texture based on a color key. + /** This makes the texture fully transparent at the texels where + this color key can be found when using for example draw2DImage + with useAlphachannel==true. The alpha of other texels is not modified. + \param texture Texture whose alpha channel is modified. + \param color Color key color. Every texel with this color will + become fully transparent as described above. Please note that the + colors of a texture may be converted when loading it, so the + color values may not be exactly the same in the engine and for + example in picture edit programs. To avoid this problem, you + could use the makeColorKeyTexture method, which takes the + position of a pixel instead a color value. */ + virtual void makeColorKeyTexture(video::ITexture *texture, + video::SColor color) const = 0; + + //! Sets a boolean alpha channel on the texture based on the color at a position. + /** This makes the texture fully transparent at the texels where + the color key can be found when using for example draw2DImage + with useAlphachannel==true. The alpha of other texels is not modified. + \param texture Texture whose alpha channel is modified. + \param colorKeyPixelPos Position of a pixel with the color key + color. Every texel with this color will become fully transparent as + described above. */ + virtual void makeColorKeyTexture(video::ITexture *texture, + core::position2d colorKeyPixelPos) const = 0; + + //! Set a render target. + /** This will only work if the driver supports the + EVDF_RENDER_TO_TARGET feature, which can be queried with + queryFeature(). Please note that you cannot render 3D or 2D + geometry with a render target as texture on it when you are rendering + the scene into this render target at the same time. It is usually only + possible to render into a texture between the + IVideoDriver::beginScene() and endScene() method calls. If you need the + best performance use this method instead of setRenderTarget. + \param target Render target object. If set to nullptr, it makes the + window the current render target. + \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. + \param clearColor The clear color for the color buffer. + \param clearDepth The clear value for the depth buffer. + \param clearStencil The clear value for the stencil buffer. + \return True if successful and false if not. */ + virtual bool setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), + f32 clearDepth = 1.f, u8 clearStencil = 0) = 0; + + //! Sets a new render target. + /** This will only work if the driver supports the + EVDF_RENDER_TO_TARGET feature, which can be queried with + queryFeature(). Usually, rendering to textures is done in this + way: + \code + // create render target + ITexture* target = driver->addRenderTargetTexture(core::dimension2d(128,128), "rtt1"); + + // ... + + driver->setRenderTarget(target); // set render target + // .. draw stuff here + driver->setRenderTarget(0); // set previous render target + \endcode + Please note that you cannot render 3D or 2D geometry with a + render target as texture on it when you are rendering the scene + into this render target at the same time. It is usually only + possible to render into a texture between the + IVideoDriver::beginScene() and endScene() method calls. + \param texture New render target. Must be a texture created with + IVideoDriver::addRenderTargetTexture(). If set to nullptr, it makes + the window the current render target. + \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. + \param clearColor The clear color for the color buffer. + \param clearDepth The clear value for the depth buffer. + \param clearStencil The clear value for the stencil buffer. + \return True if successful and false if not. */ + virtual bool setRenderTarget(ITexture *texture, u16 clearFlag = ECBF_COLOR | ECBF_DEPTH, SColor clearColor = SColor(255, 0, 0, 0), + f32 clearDepth = 1.f, u8 clearStencil = 0) = 0; + + //! Sets a new render target. + //! Prefer to use the setRenderTarget function taking flags as parameter as this one can't clear the stencil buffer. + //! It's still offered for backward compatibility. + bool setRenderTarget(ITexture *texture, bool clearBackBuffer, bool clearZBuffer, SColor color = SColor(255, 0, 0, 0)) { - public: - - //! Applications must call this method before performing any rendering. - /** This method can clear the back- and the z-buffer. - \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. - \param clearColor The clear color for the color buffer. - \param clearDepth The clear value for the depth buffer. - \param clearStencil The clear value for the stencil buffer. - \param videoData Handle of another window, if you want the - bitmap to be displayed on another window. If this is an empty - element, everything will be displayed in the default window. - Note: This feature is not fully implemented for all devices. - \param sourceRect Pointer to a rectangle defining the source - rectangle of the area to be presented. Set to null to present - everything. Note: not implemented in all devices. - \return False if failed. */ - virtual bool beginScene(u16 clearFlag=(u16)(ECBF_COLOR|ECBF_DEPTH), SColor clearColor = SColor(255,0,0,0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData=SExposedVideoData(), core::rect* sourceRect = 0) = 0; - - //! Alternative beginScene implementation. Can't clear stencil buffer, but otherwise identical to other beginScene - bool beginScene(bool backBuffer, bool zBuffer, SColor color = SColor(255,0,0,0), - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) - { - u16 flag = 0; - - if (backBuffer) - flag |= ECBF_COLOR; - - if (zBuffer) - flag |= ECBF_DEPTH; - - return beginScene(flag, color, 1.f, 0, videoData, sourceRect); - } - - //! Presents the rendered image to the screen. - /** Applications must call this method after performing any - rendering. - \return False if failed and true if succeeded. */ - virtual bool endScene() = 0; - - //! Queries the features of the driver. - /** Returns true if a feature is available - \param feature Feature to query. - \return True if the feature is available, false if not. */ - virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const =0; - - //! Disable a feature of the driver. - /** Can also be used to enable the features again. It is not - possible to enable unsupported features this way, though. - \param feature Feature to disable. - \param flag When true the feature is disabled, otherwise it is enabled. */ - virtual void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag=true) =0; - - //! Get attributes of the actual video driver - /** The following names can be queried for the given types: - MaxTextures (int) The maximum number of simultaneous textures supported by the driver. This can be less than the supported number of textures of the driver. Use _IRR_MATERIAL_MAX_TEXTURES_ to adapt the number. - MaxSupportedTextures (int) The maximum number of simultaneous textures supported by the fixed function pipeline of the (hw) driver. The actual supported number of textures supported by the engine can be lower. - MaxLights (int) Number of hardware lights supported in the fixed function pipeline of the driver, typically 6-8. Use light manager or deferred shading for more. - MaxAnisotropy (int) Number of anisotropy levels supported for filtering. At least 1, max is typically at 16 or 32. - MaxUserClipPlanes (int) Number of additional clip planes, which can be set by the user via dedicated driver methods. - MaxAuxBuffers (int) Special render buffers, which are currently not really usable inside Irrlicht. Only supported by OpenGL - MaxMultipleRenderTargets (int) Number of render targets which can be bound simultaneously. Rendering to MRTs is done via shaders. - MaxIndices (int) Number of indices which can be used in one render call (i.e. one mesh buffer). - MaxTextureSize (int) Dimension that a texture may have, both in width and height. - MaxGeometryVerticesOut (int) Number of vertices the geometry shader can output in one pass. Only OpenGL so far. - MaxTextureLODBias (float) Maximum value for LOD bias. Is usually at around 16, but can be lower on some systems. - Version (int) Version of the driver. Should be Major*100+Minor - ShaderLanguageVersion (int) Version of the high level shader language. Should be Major*100+Minor. - AntiAlias (int) Number of Samples the driver uses for each pixel. 0 and 1 means anti aliasing is off, typical values are 2,4,8,16,32 - */ - virtual const io::IAttributes& getDriverAttributes() const=0; - - //! Check if the driver was recently reset. - /** For d3d devices you will need to recreate the RTTs if the - driver was reset. Should be queried right after beginScene(). - */ - virtual bool checkDriverReset() =0; - - //! Sets transformation matrices. - /** \param state Transformation type to be set, e.g. view, - world, or projection. - \param mat Matrix describing the transformation. */ - virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) =0; - - //! Returns the transformation set by setTransform - /** \param state Transformation type to query - \return Matrix describing the transformation. */ - virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const =0; - - //! Retrieve the number of image loaders - /** \return Number of image loaders */ - virtual u32 getImageLoaderCount() const = 0; - - //! Retrieve the given image loader - /** \param n The index of the loader to retrieve. This parameter is an 0-based - array index. - \return A pointer to the specified loader, 0 if the index is incorrect. */ - virtual IImageLoader* getImageLoader(u32 n) = 0; - - //! Retrieve the number of image writers - /** \return Number of image writers */ - virtual u32 getImageWriterCount() const = 0; - - //! Retrieve the given image writer - /** \param n The index of the writer to retrieve. This parameter is an 0-based - array index. - \return A pointer to the specified writer, 0 if the index is incorrect. */ - virtual IImageWriter* getImageWriter(u32 n) = 0; - - //! Sets a material. - /** All 3d drawing functions will draw geometry using this material thereafter. - \param material: Material to be used from now on. */ - virtual void setMaterial(const SMaterial& material) =0; - - //! Get access to a named texture. - /** Loads the texture from disk if it is not - already loaded and generates mipmap levels if desired. - Texture loading can be influenced using the - setTextureCreationFlag() method. The texture can be in several - imageformats, such as BMP, JPG, TGA, PCX, PNG, and PSD. - \param filename Filename of the texture to be loaded. - \return Pointer to the texture, or 0 if the texture - could not be loaded. This pointer should not be dropped. See - IReferenceCounted::drop() for more information. */ - virtual ITexture* getTexture(const io::path& filename) = 0; - - //! Get access to a named texture. - /** Loads the texture from disk if it is not - already loaded and generates mipmap levels if desired. - Texture loading can be influenced using the - setTextureCreationFlag() method. The texture can be in several - imageformats, such as BMP, JPG, TGA, PCX, PNG, and PSD. - \param file Pointer to an already opened file. - \return Pointer to the texture, or 0 if the texture - could not be loaded. This pointer should not be dropped. See - IReferenceCounted::drop() for more information. */ - virtual ITexture* getTexture(io::IReadFile* file) =0; - - //! Returns amount of textures currently loaded - /** \return Amount of textures currently loaded */ - virtual u32 getTextureCount() const = 0; - - //! Creates an empty texture of specified size. - /** \param size: Size of the texture. - \param name A name for the texture. Later calls to - getTexture() with this name will return this texture. - The name can _not_ be empty. - \param format Desired color format of the texture. Please note - that the driver may choose to create the texture in another - color format. - \return Pointer to the newly created texture. This pointer - should not be dropped. See IReferenceCounted::drop() for more - information. */ - virtual ITexture* addTexture(const core::dimension2d& size, - const io::path& name, ECOLOR_FORMAT format = ECF_A8R8G8B8) = 0; - - //! Creates a texture from an IImage. - /** \param name A name for the texture. Later calls of - getTexture() with this name will return this texture. - The name can _not_ be empty. - \param image Image the texture is created from. - \return Pointer to the newly created texture. This pointer - should not be dropped. See IReferenceCounted::drop() for more - information. */ - virtual ITexture* addTexture(const io::path& name, IImage* image) = 0; - - //! Creates a cubemap texture from loaded IImages. - /** \param name A name for the texture. Later calls of getTexture() with this name will return this texture. - The name can _not_ be empty. - \param imagePosX Image (positive X) the texture is created from. - \param imageNegX Image (negative X) the texture is created from. - \param imagePosY Image (positive Y) the texture is created from. - \param imageNegY Image (negative Y) the texture is created from. - \param imagePosZ Image (positive Z) the texture is created from. - \param imageNegZ Image (negative Z) the texture is created from. - \return Pointer to the newly created texture. This pointer should not be dropped. See IReferenceCounted::drop() for more information. */ - virtual ITexture* addTextureCubemap(const io::path& name, IImage* imagePosX, IImage* imageNegX, IImage* imagePosY, - IImage* imageNegY, IImage* imagePosZ, IImage* imageNegZ) = 0; - - //! Creates an empty cubemap texture of specified size. - /** \param sideLen diameter of one side of the cube - \param name A name for the texture. Later calls of - getTexture() with this name will return this texture. - The name can _not_ be empty. - \param format Desired color format of the texture. Please note - that the driver may choose to create the texture in another - color format. - \return Pointer to the newly created texture. */ - virtual ITexture* addTextureCubemap(const irr::u32 sideLen, const io::path& name, ECOLOR_FORMAT format = ECF_A8R8G8B8) = 0; - - //! Adds a new render target texture to the texture cache. - /** \param size Size of the texture, in pixels. Width and - height should be a power of two (e.g. 64, 128, 256, 512, ...) - and it should not be bigger than the backbuffer, because it - shares the zbuffer with the screen buffer. - \param name A name for the texture. Later calls of getTexture() with this name will return this texture. - The name can _not_ be empty. - \param format The color format of the render target. Floating point formats are supported. - \return Pointer to the created texture or 0 if the texture - could not be created. This pointer should not be dropped. See - IReferenceCounted::drop() for more information. - You may want to remove it from driver texture cache with removeTexture if you no longer need it. - */ - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name = "rt", const ECOLOR_FORMAT format = ECF_UNKNOWN) =0; - - //! Adds a new render target texture with 6 sides for a cubemap map to the texture cache. - /** \param sideLen Length of one cubemap side. - \param name A name for the texture. Later calls of getTexture() with this name will return this texture. - The name can _not_ be empty. - \param format The color format of the render target. Floating point formats are supported. - \return Pointer to the created texture or 0 if the texture - could not be created. This pointer should not be dropped. See - IReferenceCounted::drop() for more information. */ - virtual ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name = "rt", const ECOLOR_FORMAT format = ECF_UNKNOWN) =0; - - //! Removes a texture from the texture cache and deletes it. - /** This method can free a lot of memory! - Please note that after calling this, the pointer to the - ITexture may no longer be valid, if it was not grabbed before - by other parts of the engine for storing it longer. So it is a - good idea to set all materials which are using this texture to - 0 or another texture first. - \param texture Texture to delete from the engine cache. */ - virtual void removeTexture(ITexture* texture) =0; - - //! Removes all textures from the texture cache and deletes them. - /** This method can free a lot of memory! - Please note that after calling this, the pointer to the - ITexture may no longer be valid, if it was not grabbed before - by other parts of the engine for storing it longer. So it is a - good idea to set all materials which are using this texture to - 0 or another texture first. */ - virtual void removeAllTextures() =0; - - //! Remove hardware buffer - virtual void removeHardwareBuffer(const scene::IMeshBuffer* mb) =0; - - //! Remove all hardware buffers - virtual void removeAllHardwareBuffers() =0; - - //! Create occlusion query. - /** Use node for identification and mesh for occlusion test. */ - virtual void addOcclusionQuery(scene::ISceneNode* node, - const scene::IMesh* mesh=0) =0; - - //! Remove occlusion query. - virtual void removeOcclusionQuery(scene::ISceneNode* node) =0; - - //! Remove all occlusion queries. - virtual void removeAllOcclusionQueries() =0; - - //! Run occlusion query. Draws mesh stored in query. - /** If the mesh shall not be rendered visible, use - overrideMaterial to disable the color and depth buffer. */ - virtual void runOcclusionQuery(scene::ISceneNode* node, bool visible=false) =0; - - //! Run all occlusion queries. Draws all meshes stored in queries. - /** If the meshes shall not be rendered visible, use - overrideMaterial to disable the color and depth buffer. */ - virtual void runAllOcclusionQueries(bool visible=false) =0; - - //! Update occlusion query. Retrieves results from GPU. - /** If the query shall not block, set the flag to false. - Update might not occur in this case, though */ - virtual void updateOcclusionQuery(scene::ISceneNode* node, bool block=true) =0; - - //! Update all occlusion queries. Retrieves results from GPU. - /** If the query shall not block, set the flag to false. - Update might not occur in this case, though */ - virtual void updateAllOcclusionQueries(bool block=true) =0; - - //! Return query result. - /** Return value is the number of visible pixels/fragments. - The value is a safe approximation, i.e. can be larger than the - actual value of pixels. */ - virtual u32 getOcclusionQueryResult(scene::ISceneNode* node) const =0; - - //! Create render target. - virtual IRenderTarget* addRenderTarget() = 0; - - //! Remove render target. - virtual void removeRenderTarget(IRenderTarget* renderTarget) = 0; - - //! Remove all render targets. - virtual void removeAllRenderTargets() = 0; - - //! Sets a boolean alpha channel on the texture based on a color key. - /** This makes the texture fully transparent at the texels where - this color key can be found when using for example draw2DImage - with useAlphachannel==true. The alpha of other texels is not modified. - \param texture Texture whose alpha channel is modified. - \param color Color key color. Every texel with this color will - become fully transparent as described above. Please note that the - colors of a texture may be converted when loading it, so the - color values may not be exactly the same in the engine and for - example in picture edit programs. To avoid this problem, you - could use the makeColorKeyTexture method, which takes the - position of a pixel instead a color value. */ - virtual void makeColorKeyTexture(video::ITexture* texture, - video::SColor color) const =0; - - //! Sets a boolean alpha channel on the texture based on the color at a position. - /** This makes the texture fully transparent at the texels where - the color key can be found when using for example draw2DImage - with useAlphachannel==true. The alpha of other texels is not modified. - \param texture Texture whose alpha channel is modified. - \param colorKeyPixelPos Position of a pixel with the color key - color. Every texel with this color will become fully transparent as - described above. */ - virtual void makeColorKeyTexture(video::ITexture* texture, - core::position2d colorKeyPixelPos) const =0; - - //! Set a render target. - /** This will only work if the driver supports the - EVDF_RENDER_TO_TARGET feature, which can be queried with - queryFeature(). Please note that you cannot render 3D or 2D - geometry with a render target as texture on it when you are rendering - the scene into this render target at the same time. It is usually only - possible to render into a texture between the - IVideoDriver::beginScene() and endScene() method calls. If you need the - best performance use this method instead of setRenderTarget. - \param target Render target object. If set to nullptr, it makes the - window the current render target. - \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. - \param clearColor The clear color for the color buffer. - \param clearDepth The clear value for the depth buffer. - \param clearStencil The clear value for the stencil buffer. - \return True if successful and false if not. */ - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255,0,0,0), - f32 clearDepth = 1.f, u8 clearStencil = 0) = 0; - - //! Sets a new render target. - /** This will only work if the driver supports the - EVDF_RENDER_TO_TARGET feature, which can be queried with - queryFeature(). Usually, rendering to textures is done in this - way: - \code - // create render target - ITexture* target = driver->addRenderTargetTexture(core::dimension2d(128,128), "rtt1"); - - // ... - - driver->setRenderTarget(target); // set render target - // .. draw stuff here - driver->setRenderTarget(0); // set previous render target - \endcode - Please note that you cannot render 3D or 2D geometry with a - render target as texture on it when you are rendering the scene - into this render target at the same time. It is usually only - possible to render into a texture between the - IVideoDriver::beginScene() and endScene() method calls. - \param texture New render target. Must be a texture created with - IVideoDriver::addRenderTargetTexture(). If set to nullptr, it makes - the window the current render target. - \param clearFlag A combination of the E_CLEAR_BUFFER_FLAG bit-flags. - \param clearColor The clear color for the color buffer. - \param clearDepth The clear value for the depth buffer. - \param clearStencil The clear value for the stencil buffer. - \return True if successful and false if not. */ - virtual bool setRenderTarget(ITexture* texture, u16 clearFlag=ECBF_COLOR|ECBF_DEPTH, SColor clearColor = SColor(255,0,0,0), - f32 clearDepth = 1.f, u8 clearStencil = 0) = 0; - - //! Sets a new render target. - //! Prefer to use the setRenderTarget function taking flags as parameter as this one can't clear the stencil buffer. - //! It's still offered for backward compatibility. - bool setRenderTarget(ITexture* texture, bool clearBackBuffer, bool clearZBuffer, SColor color = SColor(255,0,0,0)) - { - u16 flag = 0; - - if (clearBackBuffer) - flag |= ECBF_COLOR; - - if (clearZBuffer) - flag |= ECBF_DEPTH; - - return setRenderTarget(texture, flag, color); - } - - //! Sets a new viewport. - /** Every rendering operation is done into this new area. - \param area: Rectangle defining the new area of rendering - operations. */ - virtual void setViewPort(const core::rect& area) =0; - - //! Gets the area of the current viewport. - /** \return Rectangle of the current viewport. */ - virtual const core::rect& getViewPort() const =0; - - //! Draws a vertex primitive list - /** Note that, depending on the index type, some vertices might be not - accessible through the index list. The limit is at 65535 vertices for 16bit - indices. Please note that currently not all primitives are available for - all drivers, and some might be emulated via triangle renders. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. These define the vertices used - for each primitive. Depending on the pType, indices are interpreted as single - objects (for point like primitives), pairs (for lines), triplets (for - triangles), or quads. - \param primCount Amount of Primitives - \param vType Vertex type, e.g. video::EVT_STANDARD for S3DVertex. - \param pType Primitive type, e.g. scene::EPT_TRIANGLE_FAN for a triangle fan. - \param iType Index type, e.g. video::EIT_16BIT for 16bit indices. */ - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primCount, - E_VERTEX_TYPE vType=EVT_STANDARD, - scene::E_PRIMITIVE_TYPE pType=scene::EPT_TRIANGLES, - E_INDEX_TYPE iType=EIT_16BIT) =0; - - //! Draws a vertex primitive list in 2d - /** Compared to the general (3d) version of this method, this - one sets up a 2d render mode, and uses only x and y of vectors. - Note that, depending on the index type, some vertices might be - not accessible through the index list. The limit is at 65535 - vertices for 16bit indices. Please note that currently not all - primitives are available for all drivers, and some might be - emulated via triangle renders. This function is not available - for the sw drivers. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. These define the - vertices used for each primitive. Depending on the pType, - indices are interpreted as single objects (for point like - primitives), pairs (for lines), triplets (for triangles), or - quads. - \param primCount Amount of Primitives - \param vType Vertex type, e.g. video::EVT_STANDARD for S3DVertex. - \param pType Primitive type, e.g. scene::EPT_TRIANGLE_FAN for a triangle fan. - \param iType Index type, e.g. video::EIT_16BIT for 16bit indices. */ - virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primCount, - E_VERTEX_TYPE vType=EVT_STANDARD, - scene::E_PRIMITIVE_TYPE pType=scene::EPT_TRIANGLES, - E_INDEX_TYPE iType=EIT_16BIT) =0; - - //! Draws an indexed triangle list. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ - void drawIndexedTriangleList(const S3DVertex* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT); - } - - //! Draws an indexed triangle list. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ - void drawIndexedTriangleList(const S3DVertex2TCoords* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_2TCOORDS, scene::EPT_TRIANGLES, EIT_16BIT); - } - - //! Draws an indexed triangle list. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ - void drawIndexedTriangleList(const S3DVertexTangents* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_TANGENTS, scene::EPT_TRIANGLES, EIT_16BIT); - } - - //! Draws an indexed triangle fan. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ - void drawIndexedTriangleFan(const S3DVertex* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT); - } - - //! Draws an indexed triangle fan. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ - void drawIndexedTriangleFan(const S3DVertex2TCoords* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_2TCOORDS, scene::EPT_TRIANGLE_FAN, EIT_16BIT); - } - - //! Draws an indexed triangle fan. - /** Note that there may be at maximum 65536 vertices, because - the index list is an array of 16 bit values each with a maximum - value of 65536. If there are more than 65536 vertices in the - list, results of this operation are not defined. - \param vertices Pointer to array of vertices. - \param vertexCount Amount of vertices in the array. - \param indexList Pointer to array of indices. - \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ - void drawIndexedTriangleFan(const S3DVertexTangents* vertices, - u32 vertexCount, const u16* indexList, u32 triangleCount) - { - drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_TANGENTS, scene::EPT_TRIANGLE_FAN, EIT_16BIT); - } - - //! Draws a 3d line. - /** For some implementations, this method simply calls - drawVertexPrimitiveList for some triangles. - Note that the line is drawn using the current transformation - matrix and material. So if you need to draw the 3D line - independently of the current transformation, use - \code - driver->setMaterial(someMaterial); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - \endcode - for some properly set up material before drawing the line. - Some drivers support line thickness set in the material. - \param start Start of the 3d line. - \param end End of the 3d line. - \param color Color of the line. */ - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color = SColor(255,255,255,255)) =0; - - //! Draws a 3d axis aligned box. - /** This method simply calls draw3DLine for the edges of the - box. Note that the box is drawn using the current transformation - matrix and material. So if you need to draw it independently of - the current transformation, use - \code - driver->setMaterial(someMaterial); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - \endcode - for some properly set up material before drawing the box. - \param box The axis aligned box to draw - \param color Color to use while drawing the box. */ - virtual void draw3DBox(const core::aabbox3d& box, - SColor color = SColor(255,255,255,255)) =0; - - //! Draws a 2d image without any special effects - /** \param texture Pointer to texture to use. - \param destPos Upper left 2d destination position where the - image will be drawn. - \param useAlphaChannelOfTexture: If true, the alpha channel of - the texture is used to draw the image.*/ - virtual void draw2DImage(const video::ITexture* texture, - const core::position2d& destPos, bool useAlphaChannelOfTexture=false) =0; - - //! Draws a 2d image using a color - /** (if color is other than - Color(255,255,255,255)) and the alpha channel of the texture. - \param texture Texture to be drawn. - \param destPos Upper left 2d destination position where the - image will be drawn. - \param sourceRect Source rectangle in the texture (based on it's OriginalSize) - \param clipRect Pointer to rectangle on the screen where the - image is clipped to. - If this pointer is NULL the image is not clipped. - \param color Color with which the image is drawn. If the color - equals Color(255,255,255,255) it is ignored. Note that the - alpha component is used: If alpha is other than 255, the image - will be transparent. - \param useAlphaChannelOfTexture: If true, the alpha channel of - the texture is used to draw the image.*/ - virtual void draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect =0, - SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false) =0; - - //! Draws a set of 2d images, using a color and the alpha channel of the texture. - /** All drawings are clipped against clipRect (if != 0). - The subtextures are defined by the array of sourceRects and are - positioned using the array of positions. - \param texture Texture to be drawn. - \param positions Array of upper left 2d destinations where the - images will be drawn. - \param sourceRects Source rectangles of the texture (based on it's OriginalSize) - \param clipRect Pointer to rectangle on the screen where the - images are clipped to. - If this pointer is 0 then the image is not clipped. - \param color Color with which the image is drawn. - Note that the alpha component is used. If alpha is other than - 255, the image will be transparent. - \param useAlphaChannelOfTexture: If true, the alpha channel of - the texture is used to draw the image. */ - virtual void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect=0, - SColor color=SColor(255,255,255,255), - bool useAlphaChannelOfTexture=false) =0; - - //! Draws a part of the texture into the rectangle. Note that colors must be an array of 4 colors if used. - /** Suggested and first implemented by zola. - \param texture The texture to draw from - \param destRect The rectangle to draw into - \param sourceRect The rectangle denoting a part of the texture (based on it's OriginalSize) - \param clipRect Clips the destination rectangle (may be 0) - \param colors Array of 4 colors denoting the color values of - the corners of the destRect - \param useAlphaChannelOfTexture True if alpha channel will be - blended. */ - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect =0, - const video::SColor * const colors=0, bool useAlphaChannelOfTexture=false) =0; - - //! Draws a 2d rectangle. - /** \param color Color of the rectangle to draw. The alpha - component will not be ignored and specifies how transparent the - rectangle will be. - \param pos Position of the rectangle. - \param clip Pointer to rectangle against which the rectangle - will be clipped. If the pointer is null, no clipping will be - performed. */ - virtual void draw2DRectangle(SColor color, const core::rect& pos, - const core::rect* clip =0) =0; - - //! Draws a 2d rectangle with a gradient. - /** \param colorLeftUp Color of the upper left corner to draw. - The alpha component will not be ignored and specifies how - transparent the rectangle will be. - \param colorRightUp Color of the upper right corner to draw. - The alpha component will not be ignored and specifies how - transparent the rectangle will be. - \param colorLeftDown Color of the lower left corner to draw. - The alpha component will not be ignored and specifies how - transparent the rectangle will be. - \param colorRightDown Color of the lower right corner to draw. - The alpha component will not be ignored and specifies how - transparent the rectangle will be. - \param pos Position of the rectangle. - \param clip Pointer to rectangle against which the rectangle - will be clipped. If the pointer is null, no clipping will be - performed. */ - virtual void draw2DRectangle(const core::rect& pos, - SColor colorLeftUp, SColor colorRightUp, - SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip =0) =0; - - //! Draws a 2d line. - /** In theory both start and end will be included in coloring. - BUG: Currently d3d ignores the last pixel - (it uses the so called "diamond exit rule" for drawing lines). - \param start Screen coordinates of the start of the line - in pixels. - \param end Screen coordinates of the start of the line in - pixels. - \param color Color of the line to draw. */ - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color=SColor(255,255,255,255)) =0; - - //! Draws a mesh buffer - /** \param mb Buffer to draw */ - virtual void drawMeshBuffer(const scene::IMeshBuffer* mb) =0; - - //! Draws normals of a mesh buffer - /** \param mb Buffer to draw the normals of - \param length length scale factor of the normals - \param color Color the normals are rendered with - */ - virtual void drawMeshBufferNormals(const scene::IMeshBuffer* mb, f32 length=10.f, SColor color=0xffffffff) =0; - - //! Sets the fog mode. - /** These are global values attached to each 3d object rendered, - which has the fog flag enabled in its material. - \param color Color of the fog - \param fogType Type of fog used - \param start Only used in linear fog mode (linearFog=true). - Specifies where fog starts. - \param end Only used in linear fog mode (linearFog=true). - Specifies where fog ends. - \param density Only used in exponential fog mode - (linearFog=false). Must be a value between 0 and 1. - \param pixelFog Set this to false for vertex fog, and true if - you want per-pixel fog. - \param rangeFog Set this to true to enable range-based vertex - fog. The distance from the viewer is used to compute the fog, - not the z-coordinate. This is better, but slower. This might not - be available with all drivers and fog settings. */ - virtual void setFog(SColor color=SColor(0,255,255,255), - E_FOG_TYPE fogType=EFT_FOG_LINEAR, - f32 start=50.0f, f32 end=100.0f, f32 density=0.01f, - bool pixelFog=false, bool rangeFog=false) =0; - - //! Gets the fog mode. - virtual void getFog(SColor& color, E_FOG_TYPE& fogType, - f32& start, f32& end, f32& density, - bool& pixelFog, bool& rangeFog) = 0; - - //! Get the current color format of the color buffer - /** \return Color format of the color buffer. */ - virtual ECOLOR_FORMAT getColorFormat() const =0; - - //! Get the size of the screen or render window. - /** \return Size of screen or render window. */ - virtual const core::dimension2d& getScreenSize() const =0; - - //! Get the size of the current render target - /** This method will return the screen size if the driver - doesn't support render to texture, or if the current render - target is the screen. - \return Size of render target or screen/window */ - virtual const core::dimension2d& getCurrentRenderTargetSize() const =0; - - //! Returns current frames per second value. - /** This value is updated approximately every 1.5 seconds and - is only intended to provide a rough guide to the average frame - rate. It is not suitable for use in performing timing - calculations or framerate independent movement. - \return Approximate amount of frames per second drawn. */ - virtual s32 getFPS() const =0; - - //! Returns amount of primitives (mostly triangles) which were drawn in the last frame. - /** Together with getFPS() very useful method for statistics. - \param mode Defines if the primitives drawn are accumulated or - counted per frame. - \return Amount of primitives drawn in the last frame. */ - virtual u32 getPrimitiveCountDrawn( u32 mode =0 ) const =0; - - //! Gets name of this video driver. - /** \return Returns the name of the video driver, e.g. in case - of the Direct3D8 driver, it would return "Direct3D 8.1". */ - virtual const char* getName() const =0; - - //! Adds an external image loader to the engine. - /** This is useful if the Irrlicht Engine should be able to load - textures of currently unsupported file formats (e.g. gif). The - IImageLoader only needs to be implemented for loading this file - format. A pointer to the implementation can be passed to the - engine using this method. - \param loader Pointer to the external loader created. */ - virtual void addExternalImageLoader(IImageLoader* loader) =0; - - //! Adds an external image writer to the engine. - /** This is useful if the Irrlicht Engine should be able to - write textures of currently unsupported file formats (e.g - .gif). The IImageWriter only needs to be implemented for - writing this file format. A pointer to the implementation can - be passed to the engine using this method. - \param writer: Pointer to the external writer created. */ - virtual void addExternalImageWriter(IImageWriter* writer) =0; - - //! Returns the maximum amount of primitives - /** (mostly vertices) which the device is able to render with - one drawVertexPrimitiveList call. - \return Maximum amount of primitives. */ - virtual u32 getMaximalPrimitiveCount() const =0; - - //! Enables or disables a texture creation flag. - /** These flags define how textures should be created. By - changing this value, you can influence for example the speed of - rendering a lot. But please note that the video drivers take - this value only as recommendation. It could happen that you - enable the ETCF_ALWAYS_16_BIT mode, but the driver still creates - 32 bit textures. - \param flag Texture creation flag. - \param enabled Specifies if the given flag should be enabled or - disabled. */ - virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled=true) =0; - - //! Returns if a texture creation flag is enabled or disabled. - /** You can change this value using setTextureCreationFlag(). - \param flag Texture creation flag. - \return The current texture creation flag enabled mode. */ - virtual bool getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const =0; - - //! Creates a software image from a file. - /** No hardware texture will be created for this image. This - method is useful for example if you want to read a heightmap - for a terrain renderer. - \param filename Name of the file from which the image is - created. - \return The created image. - If you no longer need the image, you should call IImage::drop(). - See IReferenceCounted::drop() for more information. */ - virtual IImage* createImageFromFile(const io::path& filename) = 0; - - //! Creates a software image from a file. - /** No hardware texture will be created for this image. This - method is useful for example if you want to read a heightmap - for a terrain renderer. - \param file File from which the image is created. - \return The created image. - If you no longer need the image, you should call IImage::drop(). - See IReferenceCounted::drop() for more information. */ - virtual IImage* createImageFromFile(io::IReadFile* file) = 0; - - //! Writes the provided image to a file. - /** Requires that there is a suitable image writer registered - for writing the image. - \param image Image to write. - \param filename Name of the file to write. - \param param Control parameter for the backend (e.g. compression - level). - \return True on successful write. */ - virtual bool writeImageToFile(IImage* image, const io::path& filename, u32 param = 0) = 0; - - //! Writes the provided image to a file. - /** Requires that there is a suitable image writer registered - for writing the image. - \param image Image to write. - \param file An already open io::IWriteFile object. The name - will be used to determine the appropriate image writer to use. - \param param Control parameter for the backend (e.g. compression - level). - \return True on successful write. */ - virtual bool writeImageToFile(IImage* image, io::IWriteFile* file, u32 param =0) =0; - - //! Creates a software image from a byte array. - /** No hardware texture will be created for this image. This - method is useful for example if you want to read a heightmap - for a terrain renderer. - \param format Desired color format of the texture - \param size Desired size of the image - \param data A byte array with pixel color information - \param ownForeignMemory If true, the image will use the data - pointer directly and own it afterward. If false, the memory - will by copied internally. - WARNING: Setting this to 'true' will not work across dll boundaries. - So unless you link Irrlicht statically you should keep this to 'false'. - The parameter is mainly for internal usage. - \param deleteMemory Whether the memory is deallocated upon - destruction. - \return The created image. - If you no longer need the image, you should call IImage::drop(). - See IReferenceCounted::drop() for more information. */ - virtual IImage* createImageFromData(ECOLOR_FORMAT format, - const core::dimension2d& size, void *data, bool ownForeignMemory = false, + u16 flag = 0; + + if (clearBackBuffer) + flag |= ECBF_COLOR; + + if (clearZBuffer) + flag |= ECBF_DEPTH; + + return setRenderTarget(texture, flag, color); + } + + //! Sets a new viewport. + /** Every rendering operation is done into this new area. + \param area: Rectangle defining the new area of rendering + operations. */ + virtual void setViewPort(const core::rect &area) = 0; + + //! Gets the area of the current viewport. + /** \return Rectangle of the current viewport. */ + virtual const core::rect &getViewPort() const = 0; + + //! Draws a vertex primitive list + /** Note that, depending on the index type, some vertices might be not + accessible through the index list. The limit is at 65535 vertices for 16bit + indices. Please note that currently not all primitives are available for + all drivers, and some might be emulated via triangle renders. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. These define the vertices used + for each primitive. Depending on the pType, indices are interpreted as single + objects (for point like primitives), pairs (for lines), triplets (for + triangles), or quads. + \param primCount Amount of Primitives + \param vType Vertex type, e.g. video::EVT_STANDARD for S3DVertex. + \param pType Primitive type, e.g. scene::EPT_TRIANGLE_FAN for a triangle fan. + \param iType Index type, e.g. video::EIT_16BIT for 16bit indices. */ + virtual void drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primCount, + E_VERTEX_TYPE vType = EVT_STANDARD, + scene::E_PRIMITIVE_TYPE pType = scene::EPT_TRIANGLES, + E_INDEX_TYPE iType = EIT_16BIT) = 0; + + //! Draws a vertex primitive list in 2d + /** Compared to the general (3d) version of this method, this + one sets up a 2d render mode, and uses only x and y of vectors. + Note that, depending on the index type, some vertices might be + not accessible through the index list. The limit is at 65535 + vertices for 16bit indices. Please note that currently not all + primitives are available for all drivers, and some might be + emulated via triangle renders. This function is not available + for the sw drivers. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. These define the + vertices used for each primitive. Depending on the pType, + indices are interpreted as single objects (for point like + primitives), pairs (for lines), triplets (for triangles), or + quads. + \param primCount Amount of Primitives + \param vType Vertex type, e.g. video::EVT_STANDARD for S3DVertex. + \param pType Primitive type, e.g. scene::EPT_TRIANGLE_FAN for a triangle fan. + \param iType Index type, e.g. video::EIT_16BIT for 16bit indices. */ + virtual void draw2DVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primCount, + E_VERTEX_TYPE vType = EVT_STANDARD, + scene::E_PRIMITIVE_TYPE pType = scene::EPT_TRIANGLES, + E_INDEX_TYPE iType = EIT_16BIT) = 0; + + //! Draws an indexed triangle list. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ + void drawIndexedTriangleList(const S3DVertex *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT); + } + + //! Draws an indexed triangle list. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ + void drawIndexedTriangleList(const S3DVertex2TCoords *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_2TCOORDS, scene::EPT_TRIANGLES, EIT_16BIT); + } + + //! Draws an indexed triangle list. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices / 3. */ + void drawIndexedTriangleList(const S3DVertexTangents *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_TANGENTS, scene::EPT_TRIANGLES, EIT_16BIT); + } + + //! Draws an indexed triangle fan. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ + void drawIndexedTriangleFan(const S3DVertex *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT); + } + + //! Draws an indexed triangle fan. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ + void drawIndexedTriangleFan(const S3DVertex2TCoords *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_2TCOORDS, scene::EPT_TRIANGLE_FAN, EIT_16BIT); + } + + //! Draws an indexed triangle fan. + /** Note that there may be at maximum 65536 vertices, because + the index list is an array of 16 bit values each with a maximum + value of 65536. If there are more than 65536 vertices in the + list, results of this operation are not defined. + \param vertices Pointer to array of vertices. + \param vertexCount Amount of vertices in the array. + \param indexList Pointer to array of indices. + \param triangleCount Amount of Triangles. Usually amount of indices - 2. */ + void drawIndexedTriangleFan(const S3DVertexTangents *vertices, + u32 vertexCount, const u16 *indexList, u32 triangleCount) + { + drawVertexPrimitiveList(vertices, vertexCount, indexList, triangleCount, EVT_TANGENTS, scene::EPT_TRIANGLE_FAN, EIT_16BIT); + } + + //! Draws a 3d line. + /** For some implementations, this method simply calls + drawVertexPrimitiveList for some triangles. + Note that the line is drawn using the current transformation + matrix and material. So if you need to draw the 3D line + independently of the current transformation, use + \code + driver->setMaterial(someMaterial); + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); + \endcode + for some properly set up material before drawing the line. + Some drivers support line thickness set in the material. + \param start Start of the 3d line. + \param end End of the 3d line. + \param color Color of the line. */ + virtual void draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color = SColor(255, 255, 255, 255)) = 0; + + //! Draws a 3d axis aligned box. + /** This method simply calls draw3DLine for the edges of the + box. Note that the box is drawn using the current transformation + matrix and material. So if you need to draw it independently of + the current transformation, use + \code + driver->setMaterial(someMaterial); + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); + \endcode + for some properly set up material before drawing the box. + \param box The axis aligned box to draw + \param color Color to use while drawing the box. */ + virtual void draw3DBox(const core::aabbox3d &box, + SColor color = SColor(255, 255, 255, 255)) = 0; + + //! Draws a 2d image without any special effects + /** \param texture Pointer to texture to use. + \param destPos Upper left 2d destination position where the + image will be drawn. + \param useAlphaChannelOfTexture: If true, the alpha channel of + the texture is used to draw the image.*/ + virtual void draw2DImage(const video::ITexture *texture, + const core::position2d &destPos, bool useAlphaChannelOfTexture = false) = 0; + + //! Draws a 2d image using a color + /** (if color is other than + Color(255,255,255,255)) and the alpha channel of the texture. + \param texture Texture to be drawn. + \param destPos Upper left 2d destination position where the + image will be drawn. + \param sourceRect Source rectangle in the texture (based on it's OriginalSize) + \param clipRect Pointer to rectangle on the screen where the + image is clipped to. + If this pointer is NULL the image is not clipped. + \param color Color with which the image is drawn. If the color + equals Color(255,255,255,255) it is ignored. Note that the + alpha component is used: If alpha is other than 255, the image + will be transparent. + \param useAlphaChannelOfTexture: If true, the alpha channel of + the texture is used to draw the image.*/ + virtual void draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) = 0; + + //! Draws a set of 2d images, using a color and the alpha channel of the texture. + /** All drawings are clipped against clipRect (if != 0). + The subtextures are defined by the array of sourceRects and are + positioned using the array of positions. + \param texture Texture to be drawn. + \param positions Array of upper left 2d destinations where the + images will be drawn. + \param sourceRects Source rectangles of the texture (based on it's OriginalSize) + \param clipRect Pointer to rectangle on the screen where the + images are clipped to. + If this pointer is 0 then the image is not clipped. + \param color Color with which the image is drawn. + Note that the alpha component is used. If alpha is other than + 255, the image will be transparent. + \param useAlphaChannelOfTexture: If true, the alpha channel of + the texture is used to draw the image. */ + virtual void draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), + bool useAlphaChannelOfTexture = false) = 0; + + //! Draws a part of the texture into the rectangle. Note that colors must be an array of 4 colors if used. + /** Suggested and first implemented by zola. + \param texture The texture to draw from + \param destRect The rectangle to draw into + \param sourceRect The rectangle denoting a part of the texture (based on it's OriginalSize) + \param clipRect Clips the destination rectangle (may be 0) + \param colors Array of 4 colors denoting the color values of + the corners of the destRect + \param useAlphaChannelOfTexture True if alpha channel will be + blended. */ + virtual void draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect = 0, + const video::SColor *const colors = 0, bool useAlphaChannelOfTexture = false) = 0; + + //! Draws a 2d rectangle. + /** \param color Color of the rectangle to draw. The alpha + component will not be ignored and specifies how transparent the + rectangle will be. + \param pos Position of the rectangle. + \param clip Pointer to rectangle against which the rectangle + will be clipped. If the pointer is null, no clipping will be + performed. */ + virtual void draw2DRectangle(SColor color, const core::rect &pos, + const core::rect *clip = 0) = 0; + + //! Draws a 2d rectangle with a gradient. + /** \param colorLeftUp Color of the upper left corner to draw. + The alpha component will not be ignored and specifies how + transparent the rectangle will be. + \param colorRightUp Color of the upper right corner to draw. + The alpha component will not be ignored and specifies how + transparent the rectangle will be. + \param colorLeftDown Color of the lower left corner to draw. + The alpha component will not be ignored and specifies how + transparent the rectangle will be. + \param colorRightDown Color of the lower right corner to draw. + The alpha component will not be ignored and specifies how + transparent the rectangle will be. + \param pos Position of the rectangle. + \param clip Pointer to rectangle against which the rectangle + will be clipped. If the pointer is null, no clipping will be + performed. */ + virtual void draw2DRectangle(const core::rect &pos, + SColor colorLeftUp, SColor colorRightUp, + SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip = 0) = 0; + + //! Draws a 2d line. + /** In theory both start and end will be included in coloring. + BUG: Currently d3d ignores the last pixel + (it uses the so called "diamond exit rule" for drawing lines). + \param start Screen coordinates of the start of the line + in pixels. + \param end Screen coordinates of the start of the line in + pixels. + \param color Color of the line to draw. */ + virtual void draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color = SColor(255, 255, 255, 255)) = 0; + + //! Draws a mesh buffer + /** \param mb Buffer to draw */ + virtual void drawMeshBuffer(const scene::IMeshBuffer *mb) = 0; + + //! Draws normals of a mesh buffer + /** \param mb Buffer to draw the normals of + \param length length scale factor of the normals + \param color Color the normals are rendered with + */ + virtual void drawMeshBufferNormals(const scene::IMeshBuffer *mb, f32 length = 10.f, SColor color = 0xffffffff) = 0; + + //! Sets the fog mode. + /** These are global values attached to each 3d object rendered, + which has the fog flag enabled in its material. + \param color Color of the fog + \param fogType Type of fog used + \param start Only used in linear fog mode (linearFog=true). + Specifies where fog starts. + \param end Only used in linear fog mode (linearFog=true). + Specifies where fog ends. + \param density Only used in exponential fog mode + (linearFog=false). Must be a value between 0 and 1. + \param pixelFog Set this to false for vertex fog, and true if + you want per-pixel fog. + \param rangeFog Set this to true to enable range-based vertex + fog. The distance from the viewer is used to compute the fog, + not the z-coordinate. This is better, but slower. This might not + be available with all drivers and fog settings. */ + virtual void setFog(SColor color = SColor(0, 255, 255, 255), + E_FOG_TYPE fogType = EFT_FOG_LINEAR, + f32 start = 50.0f, f32 end = 100.0f, f32 density = 0.01f, + bool pixelFog = false, bool rangeFog = false) = 0; + + //! Gets the fog mode. + virtual void getFog(SColor &color, E_FOG_TYPE &fogType, + f32 &start, f32 &end, f32 &density, + bool &pixelFog, bool &rangeFog) = 0; + + //! Get the current color format of the color buffer + /** \return Color format of the color buffer. */ + virtual ECOLOR_FORMAT getColorFormat() const = 0; + + //! Get the size of the screen or render window. + /** \return Size of screen or render window. */ + virtual const core::dimension2d &getScreenSize() const = 0; + + //! Get the size of the current render target + /** This method will return the screen size if the driver + doesn't support render to texture, or if the current render + target is the screen. + \return Size of render target or screen/window */ + virtual const core::dimension2d &getCurrentRenderTargetSize() const = 0; + + //! Returns current frames per second value. + /** This value is updated approximately every 1.5 seconds and + is only intended to provide a rough guide to the average frame + rate. It is not suitable for use in performing timing + calculations or framerate independent movement. + \return Approximate amount of frames per second drawn. */ + virtual s32 getFPS() const = 0; + + //! Returns amount of primitives (mostly triangles) which were drawn in the last frame. + /** Together with getFPS() very useful method for statistics. + \param mode Defines if the primitives drawn are accumulated or + counted per frame. + \return Amount of primitives drawn in the last frame. */ + virtual u32 getPrimitiveCountDrawn(u32 mode = 0) const = 0; + + //! Gets name of this video driver. + /** \return Returns the name of the video driver, e.g. in case + of the Direct3D8 driver, it would return "Direct3D 8.1". */ + virtual const char *getName() const = 0; + + //! Adds an external image loader to the engine. + /** This is useful if the Irrlicht Engine should be able to load + textures of currently unsupported file formats (e.g. gif). The + IImageLoader only needs to be implemented for loading this file + format. A pointer to the implementation can be passed to the + engine using this method. + \param loader Pointer to the external loader created. */ + virtual void addExternalImageLoader(IImageLoader *loader) = 0; + + //! Adds an external image writer to the engine. + /** This is useful if the Irrlicht Engine should be able to + write textures of currently unsupported file formats (e.g + .gif). The IImageWriter only needs to be implemented for + writing this file format. A pointer to the implementation can + be passed to the engine using this method. + \param writer: Pointer to the external writer created. */ + virtual void addExternalImageWriter(IImageWriter *writer) = 0; + + //! Returns the maximum amount of primitives + /** (mostly vertices) which the device is able to render with + one drawVertexPrimitiveList call. + \return Maximum amount of primitives. */ + virtual u32 getMaximalPrimitiveCount() const = 0; + + //! Enables or disables a texture creation flag. + /** These flags define how textures should be created. By + changing this value, you can influence for example the speed of + rendering a lot. But please note that the video drivers take + this value only as recommendation. It could happen that you + enable the ETCF_ALWAYS_16_BIT mode, but the driver still creates + 32 bit textures. + \param flag Texture creation flag. + \param enabled Specifies if the given flag should be enabled or + disabled. */ + virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled = true) = 0; + + //! Returns if a texture creation flag is enabled or disabled. + /** You can change this value using setTextureCreationFlag(). + \param flag Texture creation flag. + \return The current texture creation flag enabled mode. */ + virtual bool getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const = 0; + + //! Creates a software image from a file. + /** No hardware texture will be created for this image. This + method is useful for example if you want to read a heightmap + for a terrain renderer. + \param filename Name of the file from which the image is + created. + \return The created image. + If you no longer need the image, you should call IImage::drop(). + See IReferenceCounted::drop() for more information. */ + virtual IImage *createImageFromFile(const io::path &filename) = 0; + + //! Creates a software image from a file. + /** No hardware texture will be created for this image. This + method is useful for example if you want to read a heightmap + for a terrain renderer. + \param file File from which the image is created. + \return The created image. + If you no longer need the image, you should call IImage::drop(). + See IReferenceCounted::drop() for more information. */ + virtual IImage *createImageFromFile(io::IReadFile *file) = 0; + + //! Writes the provided image to a file. + /** Requires that there is a suitable image writer registered + for writing the image. + \param image Image to write. + \param filename Name of the file to write. + \param param Control parameter for the backend (e.g. compression + level). + \return True on successful write. */ + virtual bool writeImageToFile(IImage *image, const io::path &filename, u32 param = 0) = 0; + + //! Writes the provided image to a file. + /** Requires that there is a suitable image writer registered + for writing the image. + \param image Image to write. + \param file An already open io::IWriteFile object. The name + will be used to determine the appropriate image writer to use. + \param param Control parameter for the backend (e.g. compression + level). + \return True on successful write. */ + virtual bool writeImageToFile(IImage *image, io::IWriteFile *file, u32 param = 0) = 0; + + //! Creates a software image from a byte array. + /** No hardware texture will be created for this image. This + method is useful for example if you want to read a heightmap + for a terrain renderer. + \param format Desired color format of the texture + \param size Desired size of the image + \param data A byte array with pixel color information + \param ownForeignMemory If true, the image will use the data + pointer directly and own it afterward. If false, the memory + will by copied internally. + WARNING: Setting this to 'true' will not work across dll boundaries. + So unless you link Irrlicht statically you should keep this to 'false'. + The parameter is mainly for internal usage. + \param deleteMemory Whether the memory is deallocated upon + destruction. + \return The created image. + If you no longer need the image, you should call IImage::drop(). + See IReferenceCounted::drop() for more information. */ + virtual IImage *createImageFromData(ECOLOR_FORMAT format, + const core::dimension2d &size, void *data, bool ownForeignMemory = false, bool deleteMemory = true) = 0; - //! Creates an empty software image. - /** - \param format Desired color format of the image. - \param size Size of the image to create. - \return The created image. - If you no longer need the image, you should call IImage::drop(). - See IReferenceCounted::drop() for more information. */ - virtual IImage* createImage(ECOLOR_FORMAT format, const core::dimension2d& size) =0; + //! Creates an empty software image. + /** + \param format Desired color format of the image. + \param size Size of the image to create. + \return The created image. + If you no longer need the image, you should call IImage::drop(). + See IReferenceCounted::drop() for more information. */ + virtual IImage *createImage(ECOLOR_FORMAT format, const core::dimension2d &size) = 0; - //! Creates a software image from a part of a texture. - /** - \param texture Texture to copy to the new image in part. - \param pos Position of rectangle to copy. - \param size Extents of rectangle to copy. - \return The created image. - If you no longer need the image, you should call IImage::drop(). - See IReferenceCounted::drop() for more information. */ - virtual IImage* createImage(ITexture* texture, - const core::position2d& pos, - const core::dimension2d& size) =0; + //! Creates a software image from a part of a texture. + /** + \param texture Texture to copy to the new image in part. + \param pos Position of rectangle to copy. + \param size Extents of rectangle to copy. + \return The created image. + If you no longer need the image, you should call IImage::drop(). + See IReferenceCounted::drop() for more information. */ + virtual IImage *createImage(ITexture *texture, + const core::position2d &pos, + const core::dimension2d &size) = 0; - //! Event handler for resize events. Only used by the engine internally. - /** Used to notify the driver that the window was resized. - Usually, there is no need to call this method. */ - virtual void OnResize(const core::dimension2d& size) =0; + //! Event handler for resize events. Only used by the engine internally. + /** Used to notify the driver that the window was resized. + Usually, there is no need to call this method. */ + virtual void OnResize(const core::dimension2d &size) = 0; - //! Adds a new material renderer to the video device. - /** Use this method to extend the VideoDriver with new material - types. To extend the engine using this method do the following: - Derive a class from IMaterialRenderer and override the methods - you need. For setting the right renderstates, you can try to - get a pointer to the real rendering device using - IVideoDriver::getExposedVideoData(). Add your class with - IVideoDriver::addMaterialRenderer(). To use an object being - displayed with your new material, set the MaterialType member of - the SMaterial struct to the value returned by this method. - If you simply want to create a new material using vertex and/or - pixel shaders it would be easier to use the - video::IGPUProgrammingServices interface which you can get - using the getGPUProgrammingServices() method. - \param renderer A pointer to the new renderer. - \param name Optional name for the material renderer entry. - \return The number of the material type which can be set in - SMaterial::MaterialType to use the renderer. -1 is returned if - an error occurred. For example if you tried to add an material - renderer to the software renderer or the null device, which do - not accept material renderers. */ - virtual s32 addMaterialRenderer(IMaterialRenderer* renderer, const c8* name =0) =0; + //! Adds a new material renderer to the video device. + /** Use this method to extend the VideoDriver with new material + types. To extend the engine using this method do the following: + Derive a class from IMaterialRenderer and override the methods + you need. For setting the right renderstates, you can try to + get a pointer to the real rendering device using + IVideoDriver::getExposedVideoData(). Add your class with + IVideoDriver::addMaterialRenderer(). To use an object being + displayed with your new material, set the MaterialType member of + the SMaterial struct to the value returned by this method. + If you simply want to create a new material using vertex and/or + pixel shaders it would be easier to use the + video::IGPUProgrammingServices interface which you can get + using the getGPUProgrammingServices() method. + \param renderer A pointer to the new renderer. + \param name Optional name for the material renderer entry. + \return The number of the material type which can be set in + SMaterial::MaterialType to use the renderer. -1 is returned if + an error occurred. For example if you tried to add an material + renderer to the software renderer or the null device, which do + not accept material renderers. */ + virtual s32 addMaterialRenderer(IMaterialRenderer *renderer, const c8 *name = 0) = 0; - //! Get access to a material renderer by index. - /** \param idx Id of the material renderer. Can be a value of - the E_MATERIAL_TYPE enum or a value which was returned by - addMaterialRenderer(). - \return Pointer to material renderer or null if not existing. */ - virtual IMaterialRenderer* getMaterialRenderer(u32 idx) const = 0; + //! Get access to a material renderer by index. + /** \param idx Id of the material renderer. Can be a value of + the E_MATERIAL_TYPE enum or a value which was returned by + addMaterialRenderer(). + \return Pointer to material renderer or null if not existing. */ + virtual IMaterialRenderer *getMaterialRenderer(u32 idx) const = 0; - //! Get amount of currently available material renderers. - /** \return Amount of currently available material renderers. */ - virtual u32 getMaterialRendererCount() const =0; + //! Get amount of currently available material renderers. + /** \return Amount of currently available material renderers. */ + virtual u32 getMaterialRendererCount() const = 0; - //! Get name of a material renderer - /** This string can, e.g., be used to test if a specific - renderer already has been registered/created, or use this - string to store data about materials: This returned name will - be also used when serializing materials. - \param idx Id of the material renderer. Can be a value of the - E_MATERIAL_TYPE enum or a value which was returned by - addMaterialRenderer(). - \return String with the name of the renderer, or 0 if not - existing */ - virtual const c8* getMaterialRendererName(u32 idx) const =0; + //! Get name of a material renderer + /** This string can, e.g., be used to test if a specific + renderer already has been registered/created, or use this + string to store data about materials: This returned name will + be also used when serializing materials. + \param idx Id of the material renderer. Can be a value of the + E_MATERIAL_TYPE enum or a value which was returned by + addMaterialRenderer(). + \return String with the name of the renderer, or 0 if not + existing */ + virtual const c8 *getMaterialRendererName(u32 idx) const = 0; - //! Sets the name of a material renderer. - /** Will have no effect on built-in material renderers. - \param idx: Id of the material renderer. Can be a value of the - E_MATERIAL_TYPE enum or a value which was returned by - addMaterialRenderer(). - \param name: New name of the material renderer. */ - virtual void setMaterialRendererName(u32 idx, const c8* name) =0; + //! Sets the name of a material renderer. + /** Will have no effect on built-in material renderers. + \param idx: Id of the material renderer. Can be a value of the + E_MATERIAL_TYPE enum or a value which was returned by + addMaterialRenderer(). + \param name: New name of the material renderer. */ + virtual void setMaterialRendererName(u32 idx, const c8 *name) = 0; - //! Swap the material renderers used for certain id's - /** Swap the IMaterialRenderers responsible for rendering specific - material-id's. This means every SMaterial using a MaterialType - with one of the indices involved here will now render differently. - \param idx1 First material index to swap. It must already exist or nothing happens. - \param idx2 Second material index to swap. It must already exist or nothing happens. - \param swapNames When true the renderer names also swap - When false the names will stay at the original index */ - virtual void swapMaterialRenderers(u32 idx1, u32 idx2, bool swapNames=true) = 0; + //! Swap the material renderers used for certain id's + /** Swap the IMaterialRenderers responsible for rendering specific + material-id's. This means every SMaterial using a MaterialType + with one of the indices involved here will now render differently. + \param idx1 First material index to swap. It must already exist or nothing happens. + \param idx2 Second material index to swap. It must already exist or nothing happens. + \param swapNames When true the renderer names also swap + When false the names will stay at the original index */ + virtual void swapMaterialRenderers(u32 idx1, u32 idx2, bool swapNames = true) = 0; - //! Returns driver and operating system specific data about the IVideoDriver. - /** This method should only be used if the engine should be - extended without having to modify the source of the engine. - \return Collection of device dependent pointers. */ - virtual const SExposedVideoData& getExposedVideoData() =0; + //! Returns driver and operating system specific data about the IVideoDriver. + /** This method should only be used if the engine should be + extended without having to modify the source of the engine. + \return Collection of device dependent pointers. */ + virtual const SExposedVideoData &getExposedVideoData() = 0; - //! Get type of video driver - /** \return Type of driver. */ - virtual E_DRIVER_TYPE getDriverType() const =0; + //! Get type of video driver + /** \return Type of driver. */ + virtual E_DRIVER_TYPE getDriverType() const = 0; - //! Gets the IGPUProgrammingServices interface. - /** \return Pointer to the IGPUProgrammingServices. Returns 0 - if the video driver does not support this. For example the - Software driver and the Null driver will always return 0. */ - virtual IGPUProgrammingServices* getGPUProgrammingServices() =0; + //! Gets the IGPUProgrammingServices interface. + /** \return Pointer to the IGPUProgrammingServices. Returns 0 + if the video driver does not support this. For example the + Software driver and the Null driver will always return 0. */ + virtual IGPUProgrammingServices *getGPUProgrammingServices() = 0; - //! Returns a pointer to the mesh manipulator. - virtual scene::IMeshManipulator* getMeshManipulator() =0; + //! Returns a pointer to the mesh manipulator. + virtual scene::IMeshManipulator *getMeshManipulator() = 0; - //! Clear the color, depth and/or stencil buffers. - virtual void clearBuffers(u16 flag, SColor color = SColor(255,0,0,0), f32 depth = 1.f, u8 stencil = 0) = 0; + //! Clear the color, depth and/or stencil buffers. + virtual void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) = 0; - //! Clears the ZBuffer. - /** Note that you usually need not to call this method, as it - is automatically done in IVideoDriver::beginScene() or - IVideoDriver::setRenderTarget() if you enable zBuffer. But if - you have to render some special things, you can clear the - zbuffer during the rendering process with this method any time. - */ - void clearZBuffer() - { - clearBuffers(ECBF_DEPTH, SColor(255,0,0,0), 1.f, 0); - } + //! Clears the ZBuffer. + /** Note that you usually need not to call this method, as it + is automatically done in IVideoDriver::beginScene() or + IVideoDriver::setRenderTarget() if you enable zBuffer. But if + you have to render some special things, you can clear the + zbuffer during the rendering process with this method any time. + */ + void clearZBuffer() + { + clearBuffers(ECBF_DEPTH, SColor(255, 0, 0, 0), 1.f, 0); + } - //! Make a screenshot of the last rendered frame. - /** \return An image created from the last rendered frame. */ - virtual IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) =0; + //! Make a screenshot of the last rendered frame. + /** \return An image created from the last rendered frame. */ + virtual IImage *createScreenShot(video::ECOLOR_FORMAT format = video::ECF_UNKNOWN, video::E_RENDER_TARGET target = video::ERT_FRAME_BUFFER) = 0; - //! Check if the image is already loaded. - /** Works similar to getTexture(), but does not load the texture - if it is not currently loaded. - \param filename Name of the texture. - \return Pointer to loaded texture, or 0 if not found. */ - virtual video::ITexture* findTexture(const io::path& filename) = 0; + //! Check if the image is already loaded. + /** Works similar to getTexture(), but does not load the texture + if it is not currently loaded. + \param filename Name of the texture. + \return Pointer to loaded texture, or 0 if not found. */ + virtual video::ITexture *findTexture(const io::path &filename) = 0; - //! Set or unset a clipping plane. - /** There are at least 6 clipping planes available for the user - to set at will. - \param index The plane index. Must be between 0 and - MaxUserClipPlanes. - \param plane The plane itself. - \param enable If true, enable the clipping plane else disable - it. - \return True if the clipping plane is usable. */ - virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false) =0; + //! Set or unset a clipping plane. + /** There are at least 6 clipping planes available for the user + to set at will. + \param index The plane index. Must be between 0 and + MaxUserClipPlanes. + \param plane The plane itself. + \param enable If true, enable the clipping plane else disable + it. + \return True if the clipping plane is usable. */ + virtual bool setClipPlane(u32 index, const core::plane3df &plane, bool enable = false) = 0; - //! Enable or disable a clipping plane. - /** There are at least 6 clipping planes available for the user - to set at will. - \param index The plane index. Must be between 0 and - MaxUserClipPlanes. - \param enable If true, enable the clipping plane else disable - it. */ - virtual void enableClipPlane(u32 index, bool enable) =0; + //! Enable or disable a clipping plane. + /** There are at least 6 clipping planes available for the user + to set at will. + \param index The plane index. Must be between 0 and + MaxUserClipPlanes. + \param enable If true, enable the clipping plane else disable + it. */ + virtual void enableClipPlane(u32 index, bool enable) = 0; - //! Set the minimum number of vertices for which a hw buffer will be created - /** \param count Number of vertices to set as minimum. */ - virtual void setMinHardwareBufferVertexCount(u32 count) =0; + //! Set the minimum number of vertices for which a hw buffer will be created + /** \param count Number of vertices to set as minimum. */ + virtual void setMinHardwareBufferVertexCount(u32 count) = 0; - //! Get the global Material, which might override local materials. - /** Depending on the enable flags, values from this Material - are used to override those of local materials of some - meshbuffer being rendered. - \return Reference to the Override Material. */ - virtual SOverrideMaterial& getOverrideMaterial() =0; + //! Get the global Material, which might override local materials. + /** Depending on the enable flags, values from this Material + are used to override those of local materials of some + meshbuffer being rendered. + \return Reference to the Override Material. */ + virtual SOverrideMaterial &getOverrideMaterial() = 0; - //! Get the 2d override material for altering its values - /** The 2d override material allows to alter certain render - states of the 2d methods. Not all members of SMaterial are - honored, especially not MaterialType and Textures. Moreover, - the zbuffer is always ignored, and lighting is always off. All - other flags can be changed, though some might have to effect - in most cases. - Please note that you have to enable/disable this effect with - enableMaterial2D(). This effect is costly, as it increases - the number of state changes considerably. Always reset the - values when done. - \return Material reference which should be altered to reflect - the new settings. - */ - virtual SMaterial& getMaterial2D() =0; + //! Get the 2d override material for altering its values + /** The 2d override material allows to alter certain render + states of the 2d methods. Not all members of SMaterial are + honored, especially not MaterialType and Textures. Moreover, + the zbuffer is always ignored, and lighting is always off. All + other flags can be changed, though some might have to effect + in most cases. + Please note that you have to enable/disable this effect with + enableMaterial2D(). This effect is costly, as it increases + the number of state changes considerably. Always reset the + values when done. + \return Material reference which should be altered to reflect + the new settings. + */ + virtual SMaterial &getMaterial2D() = 0; - //! Enable the 2d override material - /** \param enable Flag which tells whether the material shall be - enabled or disabled. */ - virtual void enableMaterial2D(bool enable=true) =0; + //! Enable the 2d override material + /** \param enable Flag which tells whether the material shall be + enabled or disabled. */ + virtual void enableMaterial2D(bool enable = true) = 0; - //! Get the graphics card vendor name. - virtual core::stringc getVendorInfo() =0; + //! Get the graphics card vendor name. + virtual core::stringc getVendorInfo() = 0; - //! Only used by the engine internally. - /** The ambient color is set in the scene manager, see - scene::ISceneManager::setAmbientLight(). - \param color New color of the ambient light. */ - virtual void setAmbientLight(const SColorf& color) =0; + //! Only used by the engine internally. + /** The ambient color is set in the scene manager, see + scene::ISceneManager::setAmbientLight(). + \param color New color of the ambient light. */ + virtual void setAmbientLight(const SColorf &color) = 0; - //! Get the global ambient light currently used by the driver - virtual const SColorf& getAmbientLight() const = 0; + //! Get the global ambient light currently used by the driver + virtual const SColorf &getAmbientLight() const = 0; - //! Only used by the engine internally. - /** Passes the global material flag AllowZWriteOnTransparent. - Use the SceneManager attribute to set this value from your app. - \param flag Default behavior is to disable ZWrite, i.e. false. */ - virtual void setAllowZWriteOnTransparent(bool flag) =0; + //! Only used by the engine internally. + /** Passes the global material flag AllowZWriteOnTransparent. + Use the SceneManager attribute to set this value from your app. + \param flag Default behavior is to disable ZWrite, i.e. false. */ + virtual void setAllowZWriteOnTransparent(bool flag) = 0; - //! Get the maximum texture size supported. - virtual core::dimension2du getMaxTextureSize() const =0; + //! Get the maximum texture size supported. + virtual core::dimension2du getMaxTextureSize() const = 0; - //! Color conversion convenience function - /** Convert an image (as array of pixels) from source to destination - array, thereby converting the color format. The pixel size is - determined by the color formats. - \param sP Pointer to source - \param sF Color format of source - \param sN Number of pixels to convert, both array must be large enough - \param dP Pointer to destination - \param dF Color format of destination - */ - virtual void convertColor(const void* sP, ECOLOR_FORMAT sF, s32 sN, - void* dP, ECOLOR_FORMAT dF) const =0; + //! Color conversion convenience function + /** Convert an image (as array of pixels) from source to destination + array, thereby converting the color format. The pixel size is + determined by the color formats. + \param sP Pointer to source + \param sF Color format of source + \param sN Number of pixels to convert, both array must be large enough + \param dP Pointer to destination + \param dF Color format of destination + */ + virtual void convertColor(const void *sP, ECOLOR_FORMAT sF, s32 sN, + void *dP, ECOLOR_FORMAT dF) const = 0; - //! Check if the driver supports creating textures with the given color format - /** \return True if the format is available, false if not. */ - virtual bool queryTextureFormat(ECOLOR_FORMAT format) const = 0; + //! Check if the driver supports creating textures with the given color format + /** \return True if the format is available, false if not. */ + virtual bool queryTextureFormat(ECOLOR_FORMAT format) const = 0; - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - virtual bool needsTransparentRenderPass(const irr::video::SMaterial& material) const = 0; - }; + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + virtual bool needsTransparentRenderPass(const irr::video::SMaterial &material) const = 0; +}; } // end namespace video } // end namespace irr - - diff --git a/include/IWriteFile.h b/include/IWriteFile.h index c07c540a..cc27e590 100644 --- a/include/IWriteFile.h +++ b/include/IWriteFile.h @@ -12,36 +12,36 @@ namespace irr namespace io { - //! Interface providing write access to a file. - class IWriteFile : public virtual IReferenceCounted - { - public: - //! Writes an amount of bytes to the file. - /** \param buffer Pointer to buffer of bytes to write. - \param sizeToWrite Amount of bytes to write to the file. - \return How much bytes were written. */ - virtual size_t write(const void* buffer, size_t sizeToWrite) = 0; +//! Interface providing write access to a file. +class IWriteFile : public virtual IReferenceCounted +{ +public: + //! Writes an amount of bytes to the file. + /** \param buffer Pointer to buffer of bytes to write. + \param sizeToWrite Amount of bytes to write to the file. + \return How much bytes were written. */ + virtual size_t write(const void *buffer, size_t sizeToWrite) = 0; - //! Changes position in file - /** \param finalPos Destination position in the file. - \param relativeMovement If set to true, the position in the file is - changed relative to current position. Otherwise the position is changed - from begin of file. - \return True if successful, otherwise false. */ - virtual bool seek(long finalPos, bool relativeMovement = false) = 0; + //! Changes position in file + /** \param finalPos Destination position in the file. + \param relativeMovement If set to true, the position in the file is + changed relative to current position. Otherwise the position is changed + from begin of file. + \return True if successful, otherwise false. */ + virtual bool seek(long finalPos, bool relativeMovement = false) = 0; - //! Get the current position in the file. - /** \return Current position in the file in bytes on success or -1L on failure */ - virtual long getPos() const = 0; + //! Get the current position in the file. + /** \return Current position in the file in bytes on success or -1L on failure */ + virtual long getPos() const = 0; - //! Get name of file. - /** \return File name as zero terminated character string. */ - virtual const path& getFileName() const = 0; + //! Get name of file. + /** \return File name as zero terminated character string. */ + virtual const path &getFileName() const = 0; - //! Flush the content of the buffer in the file - /** \return True if successful, otherwise false. */ - virtual bool flush() = 0; - }; + //! Flush the content of the buffer in the file + /** \return True if successful, otherwise false. */ + virtual bool flush() = 0; +}; } // end namespace io } // end namespace irr diff --git a/include/IrrlichtDevice.h b/include/IrrlichtDevice.h index bdaa102c..8f4105a4 100644 --- a/include/IrrlichtDevice.h +++ b/include/IrrlichtDevice.h @@ -17,322 +17,325 @@ namespace irr { - class ILogger; - class IEventReceiver; +class ILogger; +class IEventReceiver; - namespace io { - class IFileSystem; - } // end namespace io +namespace io +{ +class IFileSystem; +} // end namespace io - namespace gui { - class IGUIEnvironment; - } // end namespace gui +namespace gui +{ +class IGUIEnvironment; +} // end namespace gui - namespace scene { - class ISceneManager; - } // end namespace scene +namespace scene +{ +class ISceneManager; +} // end namespace scene - namespace video { - class IContextManager; - extern "C" IRRLICHT_API bool IRRCALLCONV isDriverSupported(E_DRIVER_TYPE driver); - } // end namespace video +namespace video +{ +class IContextManager; +extern "C" IRRLICHT_API bool IRRCALLCONV isDriverSupported(E_DRIVER_TYPE driver); +} // end namespace video - //! The Irrlicht device. You can create it with createDevice() or createDeviceEx(). - /** This is the most important class of the Irrlicht Engine. You can - access everything in the engine if you have a pointer to an instance of - this class. There should be only one instance of this class at any - time. - */ - class IrrlichtDevice : public virtual IReferenceCounted +//! The Irrlicht device. You can create it with createDevice() or createDeviceEx(). +/** This is the most important class of the Irrlicht Engine. You can +access everything in the engine if you have a pointer to an instance of +this class. There should be only one instance of this class at any +time. +*/ +class IrrlichtDevice : public virtual IReferenceCounted +{ +public: + //! Runs the device. + /** Also increments the virtual timer by calling + ITimer::tick();. You can prevent this + by calling ITimer::stop(); before and ITimer::start() after + calling IrrlichtDevice::run(). Returns false if device wants + to be deleted. Use it in this way: + \code + while(device->run()) { - public: + // draw everything here + } + \endcode + If you want the device to do nothing if the window is inactive + (recommended), use the slightly enhanced code shown at isWindowActive(). - //! Runs the device. - /** Also increments the virtual timer by calling - ITimer::tick();. You can prevent this - by calling ITimer::stop(); before and ITimer::start() after - calling IrrlichtDevice::run(). Returns false if device wants - to be deleted. Use it in this way: - \code - while(device->run()) + Note if you are running Irrlicht inside an external, custom + created window: Calling Device->run() will cause Irrlicht to + dispatch windows messages internally. + If you are running Irrlicht in your own custom window, you can + also simply use your own message loop using GetMessage, + DispatchMessage and whatever and simply don't use this method. + But note that Irrlicht will not be able to fetch user input + then. See irr::SIrrlichtCreationParameters::WindowId for more + information and example code. + */ + virtual bool run() = 0; + + //! Cause the device to temporarily pause execution and let other processes run. + /** This should bring down processor usage without major performance loss for Irrlicht. + But this is system dependent, so there's a chance your thread won't get control back quickly. + */ + virtual void yield() = 0; + + //! Pause execution and let other processes to run for a specified amount of time. + /** It may not wait the full given time, as sleep may be interrupted and also may wait longer on some OS. + \param timeMs: Time to sleep for in milliseconds. Note that the OS can round up this number. + On Windows you usually get at least 15ms sleep time minium for any value > 0. + So if you call this in your main loop you can't get more than 65 FPS anymore in your game. + On most Linux systems it's relatively exact, but also no guarantee. + \param pauseTimer: If true, pauses the device timer while sleeping + */ + virtual void sleep(u32 timeMs, bool pauseTimer = false) = 0; + + //! Provides access to the video driver for drawing 3d and 2d geometry. + /** \return Pointer the video driver. */ + virtual video::IVideoDriver *getVideoDriver() = 0; + + //! Provides access to the virtual file system. + /** \return Pointer to the file system. */ + virtual io::IFileSystem *getFileSystem() = 0; + + //! Provides access to the 2d user interface environment. + /** \return Pointer to the gui environment. */ + virtual gui::IGUIEnvironment *getGUIEnvironment() = 0; + + //! Provides access to the scene manager. + /** \return Pointer to the scene manager. */ + virtual scene::ISceneManager *getSceneManager() = 0; + + //! Provides access to the cursor control. + /** \return Pointer to the mouse cursor control interface. */ + virtual gui::ICursorControl *getCursorControl() = 0; + + //! Provides access to the message logger. + /** \return Pointer to the logger. */ + virtual ILogger *getLogger() = 0; + + //! Get context manager + virtual video::IContextManager *getContextManager() = 0; + + //! Provides access to the operation system operator object. + /** The OS operator provides methods for + getting system specific information and doing system + specific operations, such as exchanging data with the clipboard + or reading the operation system version. + \return Pointer to the OS operator. */ + virtual IOSOperator *getOSOperator() = 0; + + //! Provides access to the engine's timer. + /** The system time can be retrieved by it as + well as the virtual time, which also can be manipulated. + \return Pointer to the ITimer object. */ + virtual ITimer *getTimer() = 0; + + //! Sets the caption of the window. + /** \param text: New text of the window caption. */ + virtual void setWindowCaption(const wchar_t *text) = 0; + + //! Sets the window icon. + /** \param img The icon texture. + \return False if no icon was set. */ + virtual bool setWindowIcon(const video::IImage *img) = 0; + + //! Returns if the window is active. + /** If the window is inactive, + nothing needs to be drawn. So if you don't want to draw anything + when the window is inactive, create your drawing loop this way: + \code + while(device->run()) + { + if (device->isWindowActive()) { // draw everything here } - \endcode - If you want the device to do nothing if the window is inactive - (recommended), use the slightly enhanced code shown at isWindowActive(). + else + device->yield(); + } + \endcode + \return True if window is active. */ + virtual bool isWindowActive() const = 0; - Note if you are running Irrlicht inside an external, custom - created window: Calling Device->run() will cause Irrlicht to - dispatch windows messages internally. - If you are running Irrlicht in your own custom window, you can - also simply use your own message loop using GetMessage, - DispatchMessage and whatever and simply don't use this method. - But note that Irrlicht will not be able to fetch user input - then. See irr::SIrrlichtCreationParameters::WindowId for more - information and example code. - */ - virtual bool run() = 0; + //! Checks if the Irrlicht window has the input focus + /** \return True if window has focus. */ + virtual bool isWindowFocused() const = 0; - //! Cause the device to temporarily pause execution and let other processes run. - /** This should bring down processor usage without major performance loss for Irrlicht. - But this is system dependent, so there's a chance your thread won't get control back quickly. - */ - virtual void yield() = 0; + //! Checks if the Irrlicht window is minimized + /** \return True if window is minimized. */ + virtual bool isWindowMinimized() const = 0; - //! Pause execution and let other processes to run for a specified amount of time. - /** It may not wait the full given time, as sleep may be interrupted and also may wait longer on some OS. - \param timeMs: Time to sleep for in milliseconds. Note that the OS can round up this number. - On Windows you usually get at least 15ms sleep time minium for any value > 0. - So if you call this in your main loop you can't get more than 65 FPS anymore in your game. - On most Linux systems it's relatively exact, but also no guarantee. - \param pauseTimer: If true, pauses the device timer while sleeping - */ - virtual void sleep(u32 timeMs, bool pauseTimer=false) = 0; + //! Checks if the Irrlicht window is maximized + //! Only fully works on SDL. Returns false, or the last value set via + //! maximizeWindow() and restoreWindow(), on other backends. + /** \return True if window is maximized. */ + virtual bool isWindowMaximized() const = 0; - //! Provides access to the video driver for drawing 3d and 2d geometry. - /** \return Pointer the video driver. */ - virtual video::IVideoDriver* getVideoDriver() = 0; + //! Checks if the Irrlicht window is running in fullscreen mode + /** \return True if window is fullscreen. */ + virtual bool isFullscreen() const = 0; - //! Provides access to the virtual file system. - /** \return Pointer to the file system. */ - virtual io::IFileSystem* getFileSystem() = 0; + //! Checks if the window could possibly be visible. + //! Currently, this only returns false when the activity is stopped on + //! Android. Note that for Android activities, "stopped" means something + //! different than you might expect (and also something different than + //! "paused"). Read the Android lifecycle documentation. + virtual bool isWindowVisible() const { return true; }; - //! Provides access to the 2d user interface environment. - /** \return Pointer to the gui environment. */ - virtual gui::IGUIEnvironment* getGUIEnvironment() = 0; + //! Get the current color format of the window + /** \return Color format of the window. */ + virtual video::ECOLOR_FORMAT getColorFormat() const = 0; - //! Provides access to the scene manager. - /** \return Pointer to the scene manager. */ - virtual scene::ISceneManager* getSceneManager() = 0; + //! Notifies the device that it should close itself. + /** IrrlichtDevice::run() will always return false after closeDevice() was called. */ + virtual void closeDevice() = 0; - //! Provides access to the cursor control. - /** \return Pointer to the mouse cursor control interface. */ - virtual gui::ICursorControl* getCursorControl() = 0; + //! Get the version of the engine. + /** The returned string + will look like this: "1.2.3" or this: "1.2". + \return String which contains the version. */ + virtual const c8 *getVersion() const = 0; - //! Provides access to the message logger. - /** \return Pointer to the logger. */ - virtual ILogger* getLogger() = 0; + //! Sets a new user event receiver which will receive events from the engine. + /** Return true in IEventReceiver::OnEvent to prevent the event from continuing along + the chain of event receivers. The path that an event takes through the system depends + on its type. See irr::EEVENT_TYPE for details. + \param receiver New receiver to be used. */ + virtual void setEventReceiver(IEventReceiver *receiver) = 0; - //! Get context manager - virtual video::IContextManager* getContextManager() = 0; + //! Provides access to the current event receiver. + /** \return Pointer to the current event receiver. Returns 0 if there is none. */ + virtual IEventReceiver *getEventReceiver() = 0; - //! Provides access to the operation system operator object. - /** The OS operator provides methods for - getting system specific information and doing system - specific operations, such as exchanging data with the clipboard - or reading the operation system version. - \return Pointer to the OS operator. */ - virtual IOSOperator* getOSOperator() = 0; + //! Sends a user created event to the engine. + /** Is is usually not necessary to use this. However, if you + are using an own input library for example for doing joystick + input, you can use this to post key or mouse input events to + the engine. Internally, this method only delegates the events + further to the scene manager and the GUI environment. */ + virtual bool postEventFromUser(const SEvent &event) = 0; - //! Provides access to the engine's timer. - /** The system time can be retrieved by it as - well as the virtual time, which also can be manipulated. - \return Pointer to the ITimer object. */ - virtual ITimer* getTimer() = 0; + //! Sets the input receiving scene manager. + /** If set to null, the main scene manager (returned by + GetSceneManager()) will receive the input + \param sceneManager New scene manager to be used. */ + virtual void setInputReceivingSceneManager(scene::ISceneManager *sceneManager) = 0; - //! Sets the caption of the window. - /** \param text: New text of the window caption. */ - virtual void setWindowCaption(const wchar_t* text) = 0; + //! Sets if the window should be resizable in windowed mode. + /** The default is false. This method only works in windowed + mode. + \param resize Flag whether the window should be resizable. */ + virtual void setResizable(bool resize = false) = 0; - //! Sets the window icon. - /** \param img The icon texture. - \return False if no icon was set. */ - virtual bool setWindowIcon(const video::IImage *img) = 0; + //! Resize the render window. + /** This will only work in windowed mode and is not yet supported on all systems. + It does set the drawing/clientDC size of the window, the window decorations are added to that. + You get the current window size with IVideoDriver::getScreenSize() (might be unified in future) + */ + virtual void setWindowSize(const irr::core::dimension2d &size) = 0; - //! Returns if the window is active. - /** If the window is inactive, - nothing needs to be drawn. So if you don't want to draw anything - when the window is inactive, create your drawing loop this way: - \code - while(device->run()) - { - if (device->isWindowActive()) - { - // draw everything here - } - else - device->yield(); - } - \endcode - \return True if window is active. */ - virtual bool isWindowActive() const = 0; + //! Minimizes the window if possible. + virtual void minimizeWindow() = 0; - //! Checks if the Irrlicht window has the input focus - /** \return True if window has focus. */ - virtual bool isWindowFocused() const = 0; + //! Maximizes the window if possible. + virtual void maximizeWindow() = 0; - //! Checks if the Irrlicht window is minimized - /** \return True if window is minimized. */ - virtual bool isWindowMinimized() const = 0; + //! Restore the window to normal size if possible. + virtual void restoreWindow() = 0; - //! Checks if the Irrlicht window is maximized - //! Only fully works on SDL. Returns false, or the last value set via - //! maximizeWindow() and restoreWindow(), on other backends. - /** \return True if window is maximized. */ - virtual bool isWindowMaximized() const = 0; + //! Get the position of the frame on-screen + virtual core::position2di getWindowPosition() = 0; - //! Checks if the Irrlicht window is running in fullscreen mode - /** \return True if window is fullscreen. */ - virtual bool isFullscreen() const = 0; + //! Activate any joysticks, and generate events for them. + /** Irrlicht contains support for joysticks, but does not generate joystick events by default, + as this would consume joystick info that 3rd party libraries might rely on. Call this method to + activate joystick support in Irrlicht and to receive irr::SJoystickEvent events. + \param joystickInfo On return, this will contain an array of each joystick that was found and activated. + \return true if joysticks are supported on this device, false if joysticks are not + supported or support is compiled out. + */ + virtual bool activateJoysticks(core::array &joystickInfo) = 0; - //! Checks if the window could possibly be visible. - //! Currently, this only returns false when the activity is stopped on - //! Android. Note that for Android activities, "stopped" means something - //! different than you might expect (and also something different than - //! "paused"). Read the Android lifecycle documentation. - virtual bool isWindowVisible() const { return true; }; + //! Activate accelerometer. + virtual bool activateAccelerometer(float updateInterval = 0.016666f) = 0; - //! Get the current color format of the window - /** \return Color format of the window. */ - virtual video::ECOLOR_FORMAT getColorFormat() const = 0; + //! Deactivate accelerometer. + virtual bool deactivateAccelerometer() = 0; - //! Notifies the device that it should close itself. - /** IrrlichtDevice::run() will always return false after closeDevice() was called. */ - virtual void closeDevice() = 0; + //! Is accelerometer active. + virtual bool isAccelerometerActive() = 0; - //! Get the version of the engine. - /** The returned string - will look like this: "1.2.3" or this: "1.2". - \return String which contains the version. */ - virtual const c8* getVersion() const = 0; + //! Is accelerometer available. + virtual bool isAccelerometerAvailable() = 0; - //! Sets a new user event receiver which will receive events from the engine. - /** Return true in IEventReceiver::OnEvent to prevent the event from continuing along - the chain of event receivers. The path that an event takes through the system depends - on its type. See irr::EEVENT_TYPE for details. - \param receiver New receiver to be used. */ - virtual void setEventReceiver(IEventReceiver* receiver) = 0; + //! Activate gyroscope. + virtual bool activateGyroscope(float updateInterval = 0.016666f) = 0; - //! Provides access to the current event receiver. - /** \return Pointer to the current event receiver. Returns 0 if there is none. */ - virtual IEventReceiver* getEventReceiver() = 0; + //! Deactivate gyroscope. + virtual bool deactivateGyroscope() = 0; - //! Sends a user created event to the engine. - /** Is is usually not necessary to use this. However, if you - are using an own input library for example for doing joystick - input, you can use this to post key or mouse input events to - the engine. Internally, this method only delegates the events - further to the scene manager and the GUI environment. */ - virtual bool postEventFromUser(const SEvent& event) = 0; + //! Is gyroscope active. + virtual bool isGyroscopeActive() = 0; - //! Sets the input receiving scene manager. - /** If set to null, the main scene manager (returned by - GetSceneManager()) will receive the input - \param sceneManager New scene manager to be used. */ - virtual void setInputReceivingSceneManager(scene::ISceneManager* sceneManager) = 0; + //! Is gyroscope available. + virtual bool isGyroscopeAvailable() = 0; - //! Sets if the window should be resizable in windowed mode. - /** The default is false. This method only works in windowed - mode. - \param resize Flag whether the window should be resizable. */ - virtual void setResizable(bool resize=false) = 0; + //! Activate device motion. + virtual bool activateDeviceMotion(float updateInterval = 0.016666f) = 0; - //! Resize the render window. - /** This will only work in windowed mode and is not yet supported on all systems. - It does set the drawing/clientDC size of the window, the window decorations are added to that. - You get the current window size with IVideoDriver::getScreenSize() (might be unified in future) - */ - virtual void setWindowSize(const irr::core::dimension2d& size) = 0; + //! Deactivate device motion. + virtual bool deactivateDeviceMotion() = 0; - //! Minimizes the window if possible. - virtual void minimizeWindow() =0; + //! Is device motion active. + virtual bool isDeviceMotionActive() = 0; - //! Maximizes the window if possible. - virtual void maximizeWindow() =0; + //! Is device motion available. + virtual bool isDeviceMotionAvailable() = 0; - //! Restore the window to normal size if possible. - virtual void restoreWindow() =0; + //! Set the maximal elapsed time between 2 clicks to generate doubleclicks for the mouse. It also affects tripleclick behavior. + /** When set to 0 no double- and tripleclicks will be generated. + \param timeMs maximal time in milliseconds for two consecutive clicks to be recognized as double click + */ + virtual void setDoubleClickTime(u32 timeMs) = 0; - //! Get the position of the frame on-screen - virtual core::position2di getWindowPosition() = 0; + //! Get the maximal elapsed time between 2 clicks to generate double- and tripleclicks for the mouse. + /** When return value is 0 no double- and tripleclicks will be generated. + \return maximal time in milliseconds for two consecutive clicks to be recognized as double click + */ + virtual u32 getDoubleClickTime() const = 0; - //! Activate any joysticks, and generate events for them. - /** Irrlicht contains support for joysticks, but does not generate joystick events by default, - as this would consume joystick info that 3rd party libraries might rely on. Call this method to - activate joystick support in Irrlicht and to receive irr::SJoystickEvent events. - \param joystickInfo On return, this will contain an array of each joystick that was found and activated. - \return true if joysticks are supported on this device, false if joysticks are not - supported or support is compiled out. - */ - virtual bool activateJoysticks(core::array& joystickInfo) =0; + //! Remove messages pending in the system message loop + /** This function is usually used after messages have been buffered for a longer time, for example + when loading a large scene. Clearing the message loop prevents that mouse- or buttonclicks which users + have pressed in the meantime will now trigger unexpected actions in the gui.
+ So far the following messages are cleared:
+ Win32: All keyboard and mouse messages
+ Linux: All keyboard and mouse messages
+ All other devices are not yet supported here.
+ The function is still somewhat experimental, as the kind of messages we clear is based on just a few use-cases. + If you think further messages should be cleared, or some messages should not be cleared here, then please tell us. */ + virtual void clearSystemMessages() = 0; - //! Activate accelerometer. - virtual bool activateAccelerometer(float updateInterval = 0.016666f) = 0; + //! Get the type of the device. + /** This allows the user to check which windowing system is currently being + used. */ + virtual E_DEVICE_TYPE getType() const = 0; - //! Deactivate accelerometer. - virtual bool deactivateAccelerometer() = 0; + //! Get the display density in dots per inch. + //! Returns 0.0f on failure. + virtual float getDisplayDensity() const = 0; - //! Is accelerometer active. - virtual bool isAccelerometerActive() = 0; - - //! Is accelerometer available. - virtual bool isAccelerometerAvailable() = 0; - - //! Activate gyroscope. - virtual bool activateGyroscope(float updateInterval = 0.016666f) = 0; - - //! Deactivate gyroscope. - virtual bool deactivateGyroscope() = 0; - - //! Is gyroscope active. - virtual bool isGyroscopeActive() = 0; - - //! Is gyroscope available. - virtual bool isGyroscopeAvailable() = 0; - - //! Activate device motion. - virtual bool activateDeviceMotion(float updateInterval = 0.016666f) = 0; - - //! Deactivate device motion. - virtual bool deactivateDeviceMotion() = 0; - - //! Is device motion active. - virtual bool isDeviceMotionActive() = 0; - - //! Is device motion available. - virtual bool isDeviceMotionAvailable() = 0; - - //! Set the maximal elapsed time between 2 clicks to generate doubleclicks for the mouse. It also affects tripleclick behavior. - /** When set to 0 no double- and tripleclicks will be generated. - \param timeMs maximal time in milliseconds for two consecutive clicks to be recognized as double click - */ - virtual void setDoubleClickTime(u32 timeMs) =0; - - //! Get the maximal elapsed time between 2 clicks to generate double- and tripleclicks for the mouse. - /** When return value is 0 no double- and tripleclicks will be generated. - \return maximal time in milliseconds for two consecutive clicks to be recognized as double click - */ - virtual u32 getDoubleClickTime() const =0; - - //! Remove messages pending in the system message loop - /** This function is usually used after messages have been buffered for a longer time, for example - when loading a large scene. Clearing the message loop prevents that mouse- or buttonclicks which users - have pressed in the meantime will now trigger unexpected actions in the gui.
- So far the following messages are cleared:
- Win32: All keyboard and mouse messages
- Linux: All keyboard and mouse messages
- All other devices are not yet supported here.
- The function is still somewhat experimental, as the kind of messages we clear is based on just a few use-cases. - If you think further messages should be cleared, or some messages should not be cleared here, then please tell us. */ - virtual void clearSystemMessages() = 0; - - //! Get the type of the device. - /** This allows the user to check which windowing system is currently being - used. */ - virtual E_DEVICE_TYPE getType() const = 0; - - //! Get the display density in dots per inch. - //! Returns 0.0f on failure. - virtual float getDisplayDensity() const = 0; - - //! Check if a driver type is supported by the engine. - /** Even if true is returned the driver may not be available - for a configuration requested when creating the device. */ - static bool isDriverSupported(video::E_DRIVER_TYPE driver) - { - return video::isDriverSupported(driver); - } - }; + //! Check if a driver type is supported by the engine. + /** Even if true is returned the driver may not be available + for a configuration requested when creating the device. */ + static bool isDriverSupported(video::E_DRIVER_TYPE driver) + { + return video::isDriverSupported(driver); + } +}; } // end namespace irr diff --git a/include/Keycodes.h b/include/Keycodes.h index 3379ed7e..cdda9d0c 100644 --- a/include/Keycodes.h +++ b/include/Keycodes.h @@ -7,181 +7,179 @@ namespace irr { - enum EKEY_CODE - { - KEY_UNKNOWN = 0x0, - KEY_LBUTTON = 0x01, // Left mouse button - KEY_RBUTTON = 0x02, // Right mouse button - KEY_CANCEL = 0x03, // Control-break processing - KEY_MBUTTON = 0x04, // Middle mouse button (three-button mouse) - KEY_XBUTTON1 = 0x05, // Windows 2000/XP: X1 mouse button - KEY_XBUTTON2 = 0x06, // Windows 2000/XP: X2 mouse button - KEY_BACK = 0x08, // BACKSPACE key - KEY_TAB = 0x09, // TAB key - KEY_CLEAR = 0x0C, // CLEAR key - KEY_RETURN = 0x0D, // ENTER key - KEY_SHIFT = 0x10, // SHIFT key - KEY_CONTROL = 0x11, // CTRL key - KEY_MENU = 0x12, // ALT key - KEY_PAUSE = 0x13, // PAUSE key - KEY_CAPITAL = 0x14, // CAPS LOCK key - KEY_KANA = 0x15, // IME Kana mode - KEY_HANGUEL = 0x15, // IME Hanguel mode (maintained for compatibility use KEY_HANGUL) - KEY_HANGUL = 0x15, // IME Hangul mode - KEY_JUNJA = 0x17, // IME Junja mode - KEY_FINAL = 0x18, // IME final mode - KEY_HANJA = 0x19, // IME Hanja mode - KEY_KANJI = 0x19, // IME Kanji mode - KEY_ESCAPE = 0x1B, // ESC key - KEY_CONVERT = 0x1C, // IME convert - KEY_NONCONVERT = 0x1D, // IME nonconvert - KEY_ACCEPT = 0x1E, // IME accept - KEY_MODECHANGE = 0x1F, // IME mode change request - KEY_SPACE = 0x20, // SPACEBAR - KEY_PRIOR = 0x21, // PAGE UP key - KEY_NEXT = 0x22, // PAGE DOWN key - KEY_END = 0x23, // END key - KEY_HOME = 0x24, // HOME key - KEY_LEFT = 0x25, // LEFT ARROW key - KEY_UP = 0x26, // UP ARROW key - KEY_RIGHT = 0x27, // RIGHT ARROW key - KEY_DOWN = 0x28, // DOWN ARROW key - KEY_SELECT = 0x29, // SELECT key - KEY_PRINT = 0x2A, // PRINT key - KEY_EXECUT = 0x2B, // EXECUTE key - KEY_SNAPSHOT = 0x2C, // PRINT SCREEN key - KEY_INSERT = 0x2D, // INS key - KEY_DELETE = 0x2E, // DEL key - KEY_HELP = 0x2F, // HELP key - KEY_KEY_0 = 0x30, // 0 key - KEY_KEY_1 = 0x31, // 1 key - KEY_KEY_2 = 0x32, // 2 key - KEY_KEY_3 = 0x33, // 3 key - KEY_KEY_4 = 0x34, // 4 key - KEY_KEY_5 = 0x35, // 5 key - KEY_KEY_6 = 0x36, // 6 key - KEY_KEY_7 = 0x37, // 7 key - KEY_KEY_8 = 0x38, // 8 key - KEY_KEY_9 = 0x39, // 9 key - KEY_KEY_A = 0x41, // A key - KEY_KEY_B = 0x42, // B key - KEY_KEY_C = 0x43, // C key - KEY_KEY_D = 0x44, // D key - KEY_KEY_E = 0x45, // E key - KEY_KEY_F = 0x46, // F key - KEY_KEY_G = 0x47, // G key - KEY_KEY_H = 0x48, // H key - KEY_KEY_I = 0x49, // I key - KEY_KEY_J = 0x4A, // J key - KEY_KEY_K = 0x4B, // K key - KEY_KEY_L = 0x4C, // L key - KEY_KEY_M = 0x4D, // M key - KEY_KEY_N = 0x4E, // N key - KEY_KEY_O = 0x4F, // O key - KEY_KEY_P = 0x50, // P key - KEY_KEY_Q = 0x51, // Q key - KEY_KEY_R = 0x52, // R key - KEY_KEY_S = 0x53, // S key - KEY_KEY_T = 0x54, // T key - KEY_KEY_U = 0x55, // U key - KEY_KEY_V = 0x56, // V key - KEY_KEY_W = 0x57, // W key - KEY_KEY_X = 0x58, // X key - KEY_KEY_Y = 0x59, // Y key - KEY_KEY_Z = 0x5A, // Z key - KEY_LWIN = 0x5B, // Left Windows key (Microsoft Natural keyboard) - KEY_RWIN = 0x5C, // Right Windows key (Natural keyboard) - KEY_APPS = 0x5D, // Applications key (Natural keyboard) - KEY_SLEEP = 0x5F, // Computer Sleep key - KEY_NUMPAD0 = 0x60, // Numeric keypad 0 key - KEY_NUMPAD1 = 0x61, // Numeric keypad 1 key - KEY_NUMPAD2 = 0x62, // Numeric keypad 2 key - KEY_NUMPAD3 = 0x63, // Numeric keypad 3 key - KEY_NUMPAD4 = 0x64, // Numeric keypad 4 key - KEY_NUMPAD5 = 0x65, // Numeric keypad 5 key - KEY_NUMPAD6 = 0x66, // Numeric keypad 6 key - KEY_NUMPAD7 = 0x67, // Numeric keypad 7 key - KEY_NUMPAD8 = 0x68, // Numeric keypad 8 key - KEY_NUMPAD9 = 0x69, // Numeric keypad 9 key - KEY_MULTIPLY = 0x6A, // Multiply key - KEY_ADD = 0x6B, // Add key - KEY_SEPARATOR = 0x6C, // Separator key - KEY_SUBTRACT = 0x6D, // Subtract key - KEY_DECIMAL = 0x6E, // Decimal key - KEY_DIVIDE = 0x6F, // Divide key - KEY_F1 = 0x70, // F1 key - KEY_F2 = 0x71, // F2 key - KEY_F3 = 0x72, // F3 key - KEY_F4 = 0x73, // F4 key - KEY_F5 = 0x74, // F5 key - KEY_F6 = 0x75, // F6 key - KEY_F7 = 0x76, // F7 key - KEY_F8 = 0x77, // F8 key - KEY_F9 = 0x78, // F9 key - KEY_F10 = 0x79, // F10 key - KEY_F11 = 0x7A, // F11 key - KEY_F12 = 0x7B, // F12 key - KEY_F13 = 0x7C, // F13 key - KEY_F14 = 0x7D, // F14 key - KEY_F15 = 0x7E, // F15 key - KEY_F16 = 0x7F, // F16 key - KEY_F17 = 0x80, // F17 key - KEY_F18 = 0x81, // F18 key - KEY_F19 = 0x82, // F19 key - KEY_F20 = 0x83, // F20 key - KEY_F21 = 0x84, // F21 key - KEY_F22 = 0x85, // F22 key - KEY_F23 = 0x86, // F23 key - KEY_F24 = 0x87, // F24 key - KEY_NUMLOCK = 0x90, // NUM LOCK key - KEY_SCROLL = 0x91, // SCROLL LOCK key - KEY_LSHIFT = 0xA0, // Left SHIFT key - KEY_RSHIFT = 0xA1, // Right SHIFT key - KEY_LCONTROL = 0xA2, // Left CONTROL key - KEY_RCONTROL = 0xA3, // Right CONTROL key - KEY_LMENU = 0xA4, // Left MENU key - KEY_RMENU = 0xA5, // Right MENU key - KEY_BROWSER_BACK = 0xA6, // Browser Back key - KEY_BROWSER_FORWARD = 0xA7, // Browser Forward key - KEY_BROWSER_REFRESH = 0xA8, // Browser Refresh key - KEY_BROWSER_STOP = 0xA9, // Browser Stop key - KEY_BROWSER_SEARCH = 0xAA, // Browser Search key - KEY_BROWSER_FAVORITES =0xAB, // Browser Favorites key - KEY_BROWSER_HOME = 0xAC, // Browser Start and Home key - KEY_VOLUME_MUTE = 0xAD, // Volume Mute key - KEY_VOLUME_DOWN = 0xAE, // Volume Down key - KEY_VOLUME_UP = 0xAF, // Volume Up key - KEY_MEDIA_NEXT_TRACK = 0xB0, // Next Track key - KEY_MEDIA_PREV_TRACK = 0xB1, // Previous Track key - KEY_MEDIA_STOP = 0xB2, // Stop Media key - KEY_MEDIA_PLAY_PAUSE = 0xB3, // Play/Pause Media key - KEY_OEM_1 = 0xBA, // for US ";:" - KEY_PLUS = 0xBB, // Plus Key "+" - KEY_COMMA = 0xBC, // Comma Key "," - KEY_MINUS = 0xBD, // Minus Key "-" - KEY_PERIOD = 0xBE, // Period Key "." - KEY_OEM_2 = 0xBF, // for US "/?" - KEY_OEM_3 = 0xC0, // for US "`~" - KEY_OEM_4 = 0xDB, // for US "[{" - KEY_OEM_5 = 0xDC, // for US "\|" - KEY_OEM_6 = 0xDD, // for US "]}" - KEY_OEM_7 = 0xDE, // for US "'"" - KEY_OEM_8 = 0xDF, // None - KEY_OEM_AX = 0xE1, // for Japan "AX" - KEY_OEM_102 = 0xE2, // "<>" or "\|" - KEY_ATTN = 0xF6, // Attn key - KEY_CRSEL = 0xF7, // CrSel key - KEY_EXSEL = 0xF8, // ExSel key - KEY_EREOF = 0xF9, // Erase EOF key - KEY_PLAY = 0xFA, // Play key - KEY_ZOOM = 0xFB, // Zoom key - KEY_PA1 = 0xFD, // PA1 key - KEY_OEM_CLEAR = 0xFE, // Clear key - KEY_NONE = 0xFF, // usually no key mapping, but some laptops use it for fn key +enum EKEY_CODE +{ + KEY_UNKNOWN = 0x0, + KEY_LBUTTON = 0x01, // Left mouse button + KEY_RBUTTON = 0x02, // Right mouse button + KEY_CANCEL = 0x03, // Control-break processing + KEY_MBUTTON = 0x04, // Middle mouse button (three-button mouse) + KEY_XBUTTON1 = 0x05, // Windows 2000/XP: X1 mouse button + KEY_XBUTTON2 = 0x06, // Windows 2000/XP: X2 mouse button + KEY_BACK = 0x08, // BACKSPACE key + KEY_TAB = 0x09, // TAB key + KEY_CLEAR = 0x0C, // CLEAR key + KEY_RETURN = 0x0D, // ENTER key + KEY_SHIFT = 0x10, // SHIFT key + KEY_CONTROL = 0x11, // CTRL key + KEY_MENU = 0x12, // ALT key + KEY_PAUSE = 0x13, // PAUSE key + KEY_CAPITAL = 0x14, // CAPS LOCK key + KEY_KANA = 0x15, // IME Kana mode + KEY_HANGUEL = 0x15, // IME Hanguel mode (maintained for compatibility use KEY_HANGUL) + KEY_HANGUL = 0x15, // IME Hangul mode + KEY_JUNJA = 0x17, // IME Junja mode + KEY_FINAL = 0x18, // IME final mode + KEY_HANJA = 0x19, // IME Hanja mode + KEY_KANJI = 0x19, // IME Kanji mode + KEY_ESCAPE = 0x1B, // ESC key + KEY_CONVERT = 0x1C, // IME convert + KEY_NONCONVERT = 0x1D, // IME nonconvert + KEY_ACCEPT = 0x1E, // IME accept + KEY_MODECHANGE = 0x1F, // IME mode change request + KEY_SPACE = 0x20, // SPACEBAR + KEY_PRIOR = 0x21, // PAGE UP key + KEY_NEXT = 0x22, // PAGE DOWN key + KEY_END = 0x23, // END key + KEY_HOME = 0x24, // HOME key + KEY_LEFT = 0x25, // LEFT ARROW key + KEY_UP = 0x26, // UP ARROW key + KEY_RIGHT = 0x27, // RIGHT ARROW key + KEY_DOWN = 0x28, // DOWN ARROW key + KEY_SELECT = 0x29, // SELECT key + KEY_PRINT = 0x2A, // PRINT key + KEY_EXECUT = 0x2B, // EXECUTE key + KEY_SNAPSHOT = 0x2C, // PRINT SCREEN key + KEY_INSERT = 0x2D, // INS key + KEY_DELETE = 0x2E, // DEL key + KEY_HELP = 0x2F, // HELP key + KEY_KEY_0 = 0x30, // 0 key + KEY_KEY_1 = 0x31, // 1 key + KEY_KEY_2 = 0x32, // 2 key + KEY_KEY_3 = 0x33, // 3 key + KEY_KEY_4 = 0x34, // 4 key + KEY_KEY_5 = 0x35, // 5 key + KEY_KEY_6 = 0x36, // 6 key + KEY_KEY_7 = 0x37, // 7 key + KEY_KEY_8 = 0x38, // 8 key + KEY_KEY_9 = 0x39, // 9 key + KEY_KEY_A = 0x41, // A key + KEY_KEY_B = 0x42, // B key + KEY_KEY_C = 0x43, // C key + KEY_KEY_D = 0x44, // D key + KEY_KEY_E = 0x45, // E key + KEY_KEY_F = 0x46, // F key + KEY_KEY_G = 0x47, // G key + KEY_KEY_H = 0x48, // H key + KEY_KEY_I = 0x49, // I key + KEY_KEY_J = 0x4A, // J key + KEY_KEY_K = 0x4B, // K key + KEY_KEY_L = 0x4C, // L key + KEY_KEY_M = 0x4D, // M key + KEY_KEY_N = 0x4E, // N key + KEY_KEY_O = 0x4F, // O key + KEY_KEY_P = 0x50, // P key + KEY_KEY_Q = 0x51, // Q key + KEY_KEY_R = 0x52, // R key + KEY_KEY_S = 0x53, // S key + KEY_KEY_T = 0x54, // T key + KEY_KEY_U = 0x55, // U key + KEY_KEY_V = 0x56, // V key + KEY_KEY_W = 0x57, // W key + KEY_KEY_X = 0x58, // X key + KEY_KEY_Y = 0x59, // Y key + KEY_KEY_Z = 0x5A, // Z key + KEY_LWIN = 0x5B, // Left Windows key (Microsoft Natural keyboard) + KEY_RWIN = 0x5C, // Right Windows key (Natural keyboard) + KEY_APPS = 0x5D, // Applications key (Natural keyboard) + KEY_SLEEP = 0x5F, // Computer Sleep key + KEY_NUMPAD0 = 0x60, // Numeric keypad 0 key + KEY_NUMPAD1 = 0x61, // Numeric keypad 1 key + KEY_NUMPAD2 = 0x62, // Numeric keypad 2 key + KEY_NUMPAD3 = 0x63, // Numeric keypad 3 key + KEY_NUMPAD4 = 0x64, // Numeric keypad 4 key + KEY_NUMPAD5 = 0x65, // Numeric keypad 5 key + KEY_NUMPAD6 = 0x66, // Numeric keypad 6 key + KEY_NUMPAD7 = 0x67, // Numeric keypad 7 key + KEY_NUMPAD8 = 0x68, // Numeric keypad 8 key + KEY_NUMPAD9 = 0x69, // Numeric keypad 9 key + KEY_MULTIPLY = 0x6A, // Multiply key + KEY_ADD = 0x6B, // Add key + KEY_SEPARATOR = 0x6C, // Separator key + KEY_SUBTRACT = 0x6D, // Subtract key + KEY_DECIMAL = 0x6E, // Decimal key + KEY_DIVIDE = 0x6F, // Divide key + KEY_F1 = 0x70, // F1 key + KEY_F2 = 0x71, // F2 key + KEY_F3 = 0x72, // F3 key + KEY_F4 = 0x73, // F4 key + KEY_F5 = 0x74, // F5 key + KEY_F6 = 0x75, // F6 key + KEY_F7 = 0x76, // F7 key + KEY_F8 = 0x77, // F8 key + KEY_F9 = 0x78, // F9 key + KEY_F10 = 0x79, // F10 key + KEY_F11 = 0x7A, // F11 key + KEY_F12 = 0x7B, // F12 key + KEY_F13 = 0x7C, // F13 key + KEY_F14 = 0x7D, // F14 key + KEY_F15 = 0x7E, // F15 key + KEY_F16 = 0x7F, // F16 key + KEY_F17 = 0x80, // F17 key + KEY_F18 = 0x81, // F18 key + KEY_F19 = 0x82, // F19 key + KEY_F20 = 0x83, // F20 key + KEY_F21 = 0x84, // F21 key + KEY_F22 = 0x85, // F22 key + KEY_F23 = 0x86, // F23 key + KEY_F24 = 0x87, // F24 key + KEY_NUMLOCK = 0x90, // NUM LOCK key + KEY_SCROLL = 0x91, // SCROLL LOCK key + KEY_LSHIFT = 0xA0, // Left SHIFT key + KEY_RSHIFT = 0xA1, // Right SHIFT key + KEY_LCONTROL = 0xA2, // Left CONTROL key + KEY_RCONTROL = 0xA3, // Right CONTROL key + KEY_LMENU = 0xA4, // Left MENU key + KEY_RMENU = 0xA5, // Right MENU key + KEY_BROWSER_BACK = 0xA6, // Browser Back key + KEY_BROWSER_FORWARD = 0xA7, // Browser Forward key + KEY_BROWSER_REFRESH = 0xA8, // Browser Refresh key + KEY_BROWSER_STOP = 0xA9, // Browser Stop key + KEY_BROWSER_SEARCH = 0xAA, // Browser Search key + KEY_BROWSER_FAVORITES = 0xAB, // Browser Favorites key + KEY_BROWSER_HOME = 0xAC, // Browser Start and Home key + KEY_VOLUME_MUTE = 0xAD, // Volume Mute key + KEY_VOLUME_DOWN = 0xAE, // Volume Down key + KEY_VOLUME_UP = 0xAF, // Volume Up key + KEY_MEDIA_NEXT_TRACK = 0xB0, // Next Track key + KEY_MEDIA_PREV_TRACK = 0xB1, // Previous Track key + KEY_MEDIA_STOP = 0xB2, // Stop Media key + KEY_MEDIA_PLAY_PAUSE = 0xB3, // Play/Pause Media key + KEY_OEM_1 = 0xBA, // for US ";:" + KEY_PLUS = 0xBB, // Plus Key "+" + KEY_COMMA = 0xBC, // Comma Key "," + KEY_MINUS = 0xBD, // Minus Key "-" + KEY_PERIOD = 0xBE, // Period Key "." + KEY_OEM_2 = 0xBF, // for US "/?" + KEY_OEM_3 = 0xC0, // for US "`~" + KEY_OEM_4 = 0xDB, // for US "[{" + KEY_OEM_5 = 0xDC, // for US "\|" + KEY_OEM_6 = 0xDD, // for US "]}" + KEY_OEM_7 = 0xDE, // for US "'"" + KEY_OEM_8 = 0xDF, // None + KEY_OEM_AX = 0xE1, // for Japan "AX" + KEY_OEM_102 = 0xE2, // "<>" or "\|" + KEY_ATTN = 0xF6, // Attn key + KEY_CRSEL = 0xF7, // CrSel key + KEY_EXSEL = 0xF8, // ExSel key + KEY_EREOF = 0xF9, // Erase EOF key + KEY_PLAY = 0xFA, // Play key + KEY_ZOOM = 0xFB, // Zoom key + KEY_PA1 = 0xFD, // PA1 key + KEY_OEM_CLEAR = 0xFE, // Clear key + KEY_NONE = 0xFF, // usually no key mapping, but some laptops use it for fn key - KEY_KEY_CODES_COUNT = 0x100 // this is not a key, but the amount of keycodes there are. - }; + KEY_KEY_CODES_COUNT = 0x100 // this is not a key, but the amount of keycodes there are. +}; } // end namespace irr - - diff --git a/include/S3DVertex.h b/include/S3DVertex.h index b4953154..fa99f173 100644 --- a/include/S3DVertex.h +++ b/include/S3DVertex.h @@ -31,28 +31,29 @@ enum E_VERTEX_TYPE }; //! Array holding the built in vertex type names -const char* const sBuiltInVertexTypeNames[] = -{ - "standard", - "2tcoords", - "tangents", - 0 -}; +const char *const sBuiltInVertexTypeNames[] = + { + "standard", + "2tcoords", + "tangents", + 0}; //! standard vertex used by the Irrlicht engine. struct S3DVertex { //! default constructor - constexpr S3DVertex() : Color(0xffffffff) {} + constexpr S3DVertex() : + Color(0xffffffff) {} //! constructor - constexpr S3DVertex(f32 x, f32 y, f32 z, f32 nx, f32 ny, f32 nz, SColor c, f32 tu, f32 tv) - : Pos(x,y,z), Normal(nx,ny,nz), Color(c), TCoords(tu,tv) {} + constexpr S3DVertex(f32 x, f32 y, f32 z, f32 nx, f32 ny, f32 nz, SColor c, f32 tu, f32 tv) : + Pos(x, y, z), Normal(nx, ny, nz), Color(c), TCoords(tu, tv) {} //! constructor - constexpr S3DVertex(const core::vector3df& pos, const core::vector3df& normal, - SColor color, const core::vector2df& tcoords) - : Pos(pos), Normal(normal), Color(color), TCoords(tcoords) {} + constexpr S3DVertex(const core::vector3df &pos, const core::vector3df &normal, + SColor color, const core::vector2df &tcoords) : + Pos(pos), + Normal(normal), Color(color), TCoords(tcoords) {} //! Position core::vector3df Pos; @@ -66,19 +67,19 @@ struct S3DVertex //! Texture coordinates core::vector2df TCoords; - constexpr bool operator==(const S3DVertex& other) const + constexpr bool operator==(const S3DVertex &other) const { return ((Pos == other.Pos) && (Normal == other.Normal) && - (Color == other.Color) && (TCoords == other.TCoords)); + (Color == other.Color) && (TCoords == other.TCoords)); } - constexpr bool operator!=(const S3DVertex& other) const + constexpr bool operator!=(const S3DVertex &other) const { return ((Pos != other.Pos) || (Normal != other.Normal) || - (Color != other.Color) || (TCoords != other.TCoords)); + (Color != other.Color) || (TCoords != other.TCoords)); } - constexpr bool operator<(const S3DVertex& other) const + constexpr bool operator<(const S3DVertex &other) const { return ((Pos < other.Pos) || ((Pos == other.Pos) && (Normal < other.Normal)) || @@ -93,7 +94,7 @@ struct S3DVertex } //\param d d=0 returns other, d=1 returns this, values between interpolate. - S3DVertex getInterpolated(const S3DVertex& other, f32 d) + S3DVertex getInterpolated(const S3DVertex &other, f32 d) { d = core::clamp(d, 0.0f, 1.0f); return S3DVertex(Pos.getInterpolated(other.Pos, d), @@ -103,7 +104,6 @@ struct S3DVertex } }; - //! Vertex with two texture coordinates. /** Usually used for geometry with lightmaps or other special materials. @@ -111,61 +111,68 @@ or other special materials. struct S3DVertex2TCoords : public S3DVertex { //! default constructor - constexpr S3DVertex2TCoords() : S3DVertex() {} + constexpr S3DVertex2TCoords() : + S3DVertex() {} //! constructor with two different texture coords, but no normal - constexpr S3DVertex2TCoords(f32 x, f32 y, f32 z, SColor c, f32 tu, f32 tv, f32 tu2, f32 tv2) - : S3DVertex(x,y,z, 0.0f, 0.0f, 0.0f, c, tu,tv), TCoords2(tu2,tv2) {} + constexpr S3DVertex2TCoords(f32 x, f32 y, f32 z, SColor c, f32 tu, f32 tv, f32 tu2, f32 tv2) : + S3DVertex(x, y, z, 0.0f, 0.0f, 0.0f, c, tu, tv), TCoords2(tu2, tv2) {} //! constructor with two different texture coords, but no normal - constexpr S3DVertex2TCoords(const core::vector3df& pos, SColor color, - const core::vector2df& tcoords, const core::vector2df& tcoords2) - : S3DVertex(pos, core::vector3df(), color, tcoords), TCoords2(tcoords2) {} + constexpr S3DVertex2TCoords(const core::vector3df &pos, SColor color, + const core::vector2df &tcoords, const core::vector2df &tcoords2) : + S3DVertex(pos, core::vector3df(), color, tcoords), + TCoords2(tcoords2) {} //! constructor with all values - constexpr S3DVertex2TCoords(const core::vector3df& pos, const core::vector3df& normal, const SColor& color, - const core::vector2df& tcoords, const core::vector2df& tcoords2) - : S3DVertex(pos, normal, color, tcoords), TCoords2(tcoords2) {} + constexpr S3DVertex2TCoords(const core::vector3df &pos, const core::vector3df &normal, const SColor &color, + const core::vector2df &tcoords, const core::vector2df &tcoords2) : + S3DVertex(pos, normal, color, tcoords), + TCoords2(tcoords2) {} //! constructor with all values constexpr S3DVertex2TCoords(f32 x, f32 y, f32 z, f32 nx, f32 ny, f32 nz, - SColor c, f32 tu, f32 tv, f32 tu2, f32 tv2) - : S3DVertex(x,y,z, nx,ny,nz, c, tu,tv), TCoords2(tu2,tv2) {} + SColor c, f32 tu, f32 tv, f32 tu2, f32 tv2) : + S3DVertex(x, y, z, nx, ny, nz, c, tu, tv), + TCoords2(tu2, tv2) {} //! constructor with the same texture coords and normal constexpr S3DVertex2TCoords(f32 x, f32 y, f32 z, f32 nx, f32 ny, f32 nz, - SColor c, f32 tu, f32 tv) - : S3DVertex(x,y,z, nx,ny,nz, c, tu,tv), TCoords2(tu,tv) {} + SColor c, f32 tu, f32 tv) : + S3DVertex(x, y, z, nx, ny, nz, c, tu, tv), + TCoords2(tu, tv) {} //! constructor with the same texture coords and normal - constexpr S3DVertex2TCoords(const core::vector3df& pos, const core::vector3df& normal, - SColor color, const core::vector2df& tcoords) - : S3DVertex(pos, normal, color, tcoords), TCoords2(tcoords) {} + constexpr S3DVertex2TCoords(const core::vector3df &pos, const core::vector3df &normal, + SColor color, const core::vector2df &tcoords) : + S3DVertex(pos, normal, color, tcoords), + TCoords2(tcoords) {} //! constructor from S3DVertex - constexpr S3DVertex2TCoords(const S3DVertex& o) : S3DVertex(o) {} + constexpr S3DVertex2TCoords(const S3DVertex &o) : + S3DVertex(o) {} //! Second set of texture coordinates core::vector2df TCoords2; //! Equality operator - constexpr bool operator==(const S3DVertex2TCoords& other) const + constexpr bool operator==(const S3DVertex2TCoords &other) const { - return ((static_cast(*this)==static_cast(other)) && - (TCoords2 == other.TCoords2)); + return ((static_cast(*this) == static_cast(other)) && + (TCoords2 == other.TCoords2)); } //! Inequality operator - constexpr bool operator!=(const S3DVertex2TCoords& other) const + constexpr bool operator!=(const S3DVertex2TCoords &other) const { - return ((static_cast(*this)!=static_cast(other)) || - (TCoords2 != other.TCoords2)); + return ((static_cast(*this) != static_cast(other)) || + (TCoords2 != other.TCoords2)); } - constexpr bool operator<(const S3DVertex2TCoords& other) const + constexpr bool operator<(const S3DVertex2TCoords &other) const { return ((static_cast(*this) < other) || - ((static_cast(*this) == static_cast(other)) && (TCoords2 < other.TCoords2))); + ((static_cast(*this) == static_cast(other)) && (TCoords2 < other.TCoords2))); } static E_VERTEX_TYPE getType() @@ -174,7 +181,7 @@ struct S3DVertex2TCoords : public S3DVertex } //\param d d=0 returns other, d=1 returns this, values between interpolate. - S3DVertex2TCoords getInterpolated(const S3DVertex2TCoords& other, f32 d) + S3DVertex2TCoords getInterpolated(const S3DVertex2TCoords &other, f32 d) { d = core::clamp(d, 0.0f, 1.0f); return S3DVertex2TCoords(Pos.getInterpolated(other.Pos, d), @@ -185,7 +192,6 @@ struct S3DVertex2TCoords : public S3DVertex } }; - //! Vertex with a tangent and binormal vector. /** Usually used for tangent space normal mapping. Usually tangent and binormal get send to shaders as texture coordinate sets 1 and 2. @@ -193,30 +199,34 @@ struct S3DVertex2TCoords : public S3DVertex struct S3DVertexTangents : public S3DVertex { //! default constructor - S3DVertexTangents() : S3DVertex() { } + S3DVertexTangents() : + S3DVertex() {} //! constructor - constexpr S3DVertexTangents(f32 x, f32 y, f32 z, f32 nx=0.0f, f32 ny=0.0f, f32 nz=0.0f, - SColor c = 0xFFFFFFFF, f32 tu=0.0f, f32 tv=0.0f, - f32 tanx=0.0f, f32 tany=0.0f, f32 tanz=0.0f, - f32 bx=0.0f, f32 by=0.0f, f32 bz=0.0f) - : S3DVertex(x,y,z, nx,ny,nz, c, tu,tv), Tangent(tanx,tany,tanz), Binormal(bx,by,bz) { } + constexpr S3DVertexTangents(f32 x, f32 y, f32 z, f32 nx = 0.0f, f32 ny = 0.0f, f32 nz = 0.0f, + SColor c = 0xFFFFFFFF, f32 tu = 0.0f, f32 tv = 0.0f, + f32 tanx = 0.0f, f32 tany = 0.0f, f32 tanz = 0.0f, + f32 bx = 0.0f, f32 by = 0.0f, f32 bz = 0.0f) : + S3DVertex(x, y, z, nx, ny, nz, c, tu, tv), + Tangent(tanx, tany, tanz), Binormal(bx, by, bz) {} //! constructor - constexpr S3DVertexTangents(const core::vector3df& pos, SColor c, - const core::vector2df& tcoords) - : S3DVertex(pos, core::vector3df(), c, tcoords) { } + constexpr S3DVertexTangents(const core::vector3df &pos, SColor c, + const core::vector2df &tcoords) : + S3DVertex(pos, core::vector3df(), c, tcoords) {} //! constructor - constexpr S3DVertexTangents(const core::vector3df& pos, - const core::vector3df& normal, SColor c, - const core::vector2df& tcoords, - const core::vector3df& tangent=core::vector3df(), - const core::vector3df& binormal=core::vector3df()) - : S3DVertex(pos, normal, c, tcoords), Tangent(tangent), Binormal(binormal) { } + constexpr S3DVertexTangents(const core::vector3df &pos, + const core::vector3df &normal, SColor c, + const core::vector2df &tcoords, + const core::vector3df &tangent = core::vector3df(), + const core::vector3df &binormal = core::vector3df()) : + S3DVertex(pos, normal, c, tcoords), + Tangent(tangent), Binormal(binormal) {} //! constructor from S3DVertex - constexpr S3DVertexTangents(const S3DVertex& o) : S3DVertex(o) {} + constexpr S3DVertexTangents(const S3DVertex &o) : + S3DVertex(o) {} //! Tangent vector along the x-axis of the texture core::vector3df Tangent; @@ -224,25 +234,25 @@ struct S3DVertexTangents : public S3DVertex //! Binormal vector (tangent x normal) core::vector3df Binormal; - constexpr bool operator==(const S3DVertexTangents& other) const + constexpr bool operator==(const S3DVertexTangents &other) const { - return ((static_cast(*this)==static_cast(other)) && - (Tangent == other.Tangent) && - (Binormal == other.Binormal)); + return ((static_cast(*this) == static_cast(other)) && + (Tangent == other.Tangent) && + (Binormal == other.Binormal)); } - constexpr bool operator!=(const S3DVertexTangents& other) const + constexpr bool operator!=(const S3DVertexTangents &other) const { - return ((static_cast(*this)!=static_cast(other)) || - (Tangent != other.Tangent) || - (Binormal != other.Binormal)); + return ((static_cast(*this) != static_cast(other)) || + (Tangent != other.Tangent) || + (Binormal != other.Binormal)); } - constexpr bool operator<(const S3DVertexTangents& other) const + constexpr bool operator<(const S3DVertexTangents &other) const { return ((static_cast(*this) < other) || - ((static_cast(*this) == static_cast(other)) && (Tangent < other.Tangent)) || - ((static_cast(*this) == static_cast(other)) && (Tangent == other.Tangent) && (Binormal < other.Binormal))); + ((static_cast(*this) == static_cast(other)) && (Tangent < other.Tangent)) || + ((static_cast(*this) == static_cast(other)) && (Tangent == other.Tangent) && (Binormal < other.Binormal))); } static E_VERTEX_TYPE getType() @@ -250,7 +260,7 @@ struct S3DVertexTangents : public S3DVertex return EVT_TANGENTS; } - S3DVertexTangents getInterpolated(const S3DVertexTangents& other, f32 d) + S3DVertexTangents getInterpolated(const S3DVertexTangents &other, f32 d) { d = core::clamp(d, 0.0f, 1.0f); return S3DVertexTangents(Pos.getInterpolated(other.Pos, d), @@ -262,12 +272,9 @@ struct S3DVertexTangents : public S3DVertex } }; - - inline u32 getVertexPitchFromType(E_VERTEX_TYPE vertexType) { - switch (vertexType) - { + switch (vertexType) { case video::EVT_2TCOORDS: return sizeof(video::S3DVertex2TCoords); case video::EVT_TANGENTS: @@ -277,6 +284,5 @@ inline u32 getVertexPitchFromType(E_VERTEX_TYPE vertexType) } } - } // end namespace video } // end namespace irr diff --git a/include/SAnimatedMesh.h b/include/SAnimatedMesh.h index 5c5934dc..8fdaae0e 100644 --- a/include/SAnimatedMesh.h +++ b/include/SAnimatedMesh.h @@ -14,165 +14,164 @@ namespace irr namespace scene { - //! Simple implementation of the IAnimatedMesh interface. - struct SAnimatedMesh : public IAnimatedMesh +//! Simple implementation of the IAnimatedMesh interface. +struct SAnimatedMesh : public IAnimatedMesh +{ + //! constructor + SAnimatedMesh(scene::IMesh *mesh = 0, scene::E_ANIMATED_MESH_TYPE type = scene::EAMT_UNKNOWN) : + IAnimatedMesh(), FramesPerSecond(25.f), Type(type) { - //! constructor - SAnimatedMesh(scene::IMesh* mesh=0, scene::E_ANIMATED_MESH_TYPE type=scene::EAMT_UNKNOWN) : IAnimatedMesh(), FramesPerSecond(25.f), Type(type) - { - #ifdef _DEBUG - setDebugName("SAnimatedMesh"); - #endif - addMesh(mesh); - recalculateBoundingBox(); +#ifdef _DEBUG + setDebugName("SAnimatedMesh"); +#endif + addMesh(mesh); + recalculateBoundingBox(); + } + + //! destructor + virtual ~SAnimatedMesh() + { + // drop meshes + for (u32 i = 0; i < Meshes.size(); ++i) + Meshes[i]->drop(); + } + + //! Gets the frame count of the animated mesh. + /** \return Amount of frames. If the amount is 1, it is a static, non animated mesh. */ + u32 getFrameCount() const override + { + return Meshes.size(); + } + + //! Gets the default animation speed of the animated mesh. + /** \return Amount of frames per second. If the amount is 0, it is a static, non animated mesh. */ + f32 getAnimationSpeed() const override + { + return FramesPerSecond; + } + + //! Gets the frame count of the animated mesh. + /** \param fps Frames per second to play the animation with. If the amount is 0, it is not animated. + The actual speed is set in the scene node the mesh is instantiated in.*/ + void setAnimationSpeed(f32 fps) override + { + FramesPerSecond = fps; + } + + //! Returns the IMesh interface for a frame. + /** \param frame: Frame number as zero based index. The maximum frame number is + getFrameCount() - 1; + \param detailLevel: Level of detail. 0 is the lowest, + 255 the highest level of detail. Most meshes will ignore the detail level. + \param startFrameLoop: start frame + \param endFrameLoop: end frame + \return The animated mesh based on a detail level. */ + IMesh *getMesh(s32 frame, s32 detailLevel = 255, s32 startFrameLoop = -1, s32 endFrameLoop = -1) override + { + if (Meshes.empty()) + return 0; + + return Meshes[frame]; + } + + //! adds a Mesh + void addMesh(IMesh *mesh) + { + if (mesh) { + mesh->grab(); + Meshes.push_back(mesh); } + } - //! destructor - virtual ~SAnimatedMesh() - { - // drop meshes - for (u32 i=0; idrop(); - } + //! Returns an axis aligned bounding box of the mesh. + /** \return A bounding box of this mesh is returned. */ + const core::aabbox3d &getBoundingBox() const override + { + return Box; + } - //! Gets the frame count of the animated mesh. - /** \return Amount of frames. If the amount is 1, it is a static, non animated mesh. */ - u32 getFrameCount() const override - { - return Meshes.size(); - } + //! set user axis aligned bounding box + void setBoundingBox(const core::aabbox3df &box) override + { + Box = box; + } - //! Gets the default animation speed of the animated mesh. - /** \return Amount of frames per second. If the amount is 0, it is a static, non animated mesh. */ - f32 getAnimationSpeed() const override - { - return FramesPerSecond; - } + //! Recalculates the bounding box. + void recalculateBoundingBox() + { + Box.reset(0, 0, 0); - //! Gets the frame count of the animated mesh. - /** \param fps Frames per second to play the animation with. If the amount is 0, it is not animated. - The actual speed is set in the scene node the mesh is instantiated in.*/ - void setAnimationSpeed(f32 fps) override - { - FramesPerSecond=fps; - } + if (Meshes.empty()) + return; - //! Returns the IMesh interface for a frame. - /** \param frame: Frame number as zero based index. The maximum frame number is - getFrameCount() - 1; - \param detailLevel: Level of detail. 0 is the lowest, - 255 the highest level of detail. Most meshes will ignore the detail level. - \param startFrameLoop: start frame - \param endFrameLoop: end frame - \return The animated mesh based on a detail level. */ - IMesh* getMesh(s32 frame, s32 detailLevel=255, s32 startFrameLoop=-1, s32 endFrameLoop=-1) override - { - if (Meshes.empty()) - return 0; + Box = Meshes[0]->getBoundingBox(); - return Meshes[frame]; - } + for (u32 i = 1; i < Meshes.size(); ++i) + Box.addInternalBox(Meshes[i]->getBoundingBox()); + } - //! adds a Mesh - void addMesh(IMesh* mesh) - { - if (mesh) - { - mesh->grab(); - Meshes.push_back(mesh); - } - } + //! Returns the type of the animated mesh. + E_ANIMATED_MESH_TYPE getMeshType() const override + { + return Type; + } - //! Returns an axis aligned bounding box of the mesh. - /** \return A bounding box of this mesh is returned. */ - const core::aabbox3d& getBoundingBox() const override - { - return Box; - } + //! returns amount of mesh buffers. + u32 getMeshBufferCount() const override + { + if (Meshes.empty()) + return 0; - //! set user axis aligned bounding box - void setBoundingBox(const core::aabbox3df& box) override - { - Box = box; - } + return Meshes[0]->getMeshBufferCount(); + } - //! Recalculates the bounding box. - void recalculateBoundingBox() - { - Box.reset(0,0,0); + //! returns pointer to a mesh buffer + IMeshBuffer *getMeshBuffer(u32 nr) const override + { + if (Meshes.empty()) + return 0; - if (Meshes.empty()) - return; + return Meshes[0]->getMeshBuffer(nr); + } - Box = Meshes[0]->getBoundingBox(); + //! Returns pointer to a mesh buffer which fits a material + /** \param material: material to search for + \return Returns the pointer to the mesh buffer or + NULL if there is no such mesh buffer. */ + IMeshBuffer *getMeshBuffer(const video::SMaterial &material) const override + { + if (Meshes.empty()) + return 0; - for (u32 i=1; igetBoundingBox()); - } + return Meshes[0]->getMeshBuffer(material); + } - //! Returns the type of the animated mesh. - E_ANIMATED_MESH_TYPE getMeshType() const override - { - return Type; - } + //! set the hardware mapping hint, for driver + void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override + { + for (u32 i = 0; i < Meshes.size(); ++i) + Meshes[i]->setHardwareMappingHint(newMappingHint, buffer); + } - //! returns amount of mesh buffers. - u32 getMeshBufferCount() const override - { - if (Meshes.empty()) - return 0; + //! flags the meshbuffer as changed, reloads hardware buffers + void setDirty(E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override + { + for (u32 i = 0; i < Meshes.size(); ++i) + Meshes[i]->setDirty(buffer); + } - return Meshes[0]->getMeshBufferCount(); - } + //! All meshes defining the animated mesh + core::array Meshes; - //! returns pointer to a mesh buffer - IMeshBuffer* getMeshBuffer(u32 nr) const override - { - if (Meshes.empty()) - return 0; + //! The bounding box of this mesh + core::aabbox3d Box; - return Meshes[0]->getMeshBuffer(nr); - } - - //! Returns pointer to a mesh buffer which fits a material - /** \param material: material to search for - \return Returns the pointer to the mesh buffer or - NULL if there is no such mesh buffer. */ - IMeshBuffer* getMeshBuffer( const video::SMaterial &material) const override - { - if (Meshes.empty()) - return 0; - - return Meshes[0]->getMeshBuffer(material); - } - - //! set the hardware mapping hint, for driver - void setHardwareMappingHint( E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX ) override - { - for (u32 i=0; isetHardwareMappingHint(newMappingHint, buffer); - } - - //! flags the meshbuffer as changed, reloads hardware buffers - void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) override - { - for (u32 i=0; isetDirty(buffer); - } - - //! All meshes defining the animated mesh - core::array Meshes; - - //! The bounding box of this mesh - core::aabbox3d Box; - - //! Default animation speed of this mesh. - f32 FramesPerSecond; - - //! The type of the mesh. - E_ANIMATED_MESH_TYPE Type; - }; + //! Default animation speed of this mesh. + f32 FramesPerSecond; + //! The type of the mesh. + E_ANIMATED_MESH_TYPE Type; +}; } // end namespace scene } // end namespace irr diff --git a/include/SColor.h b/include/SColor.h index 532c34b2..5f73585c 100644 --- a/include/SColor.h +++ b/include/SColor.h @@ -11,741 +11,719 @@ namespace irr { namespace video { - //! An enum for the color format of textures used by the Irrlicht Engine. - /** A color format specifies how color information is stored. - NOTE: Byte order in memory is usually flipped (it's probably correct in bitmap files, but flipped on reading). - So for example ECF_A8R8G8B8 is BGRA in memory same as in DX9's D3DFMT_A8R8G8B8 format. +//! An enum for the color format of textures used by the Irrlicht Engine. +/** A color format specifies how color information is stored. + NOTE: Byte order in memory is usually flipped (it's probably correct in bitmap files, but flipped on reading). + So for example ECF_A8R8G8B8 is BGRA in memory same as in DX9's D3DFMT_A8R8G8B8 format. +*/ +enum ECOLOR_FORMAT +{ + //! 16 bit color format used by the software driver. + /** It is thus preferred by all other irrlicht engine video drivers. + There are 5 bits for every color component, and a single bit is left + for alpha information. */ + ECF_A1R5G5B5 = 0, + + //! Standard 16 bit color format. + ECF_R5G6B5, + + //! 24 bit color, no alpha channel, but 8 bit for red, green and blue. + //! Warning: 24 bit formats tend to be badly supported. Depending on driver it's usually converted to another + // format or even not working at all. It's mostly better to use 16-bit or 32-bit formats. + ECF_R8G8B8, + + //! Default 32 bit color format. 8 bits are used for every component: red, green, blue and alpha. + //! Warning: This tends to be BGRA in memory (it's ARGB on file, but with usual big-endian memory it's flipped) + ECF_A8R8G8B8, + + /** The following formats may only be used for render target textures. */ + + /** Floating point formats. */ + + //! 16 bit format using 16 bits for the red channel. + ECF_R16F, + + //! 32 bit format using 16 bits for the red and green channels. + ECF_G16R16F, + + //! 64 bit format using 16 bits for the red, green, blue and alpha channels. + ECF_A16B16G16R16F, + + //! 32 bit format using 32 bits for the red channel. + ECF_R32F, + + //! 64 bit format using 32 bits for the red and green channels. + ECF_G32R32F, + + //! 128 bit format using 32 bits for the red, green, blue and alpha channels. + ECF_A32B32G32R32F, + + /** Unsigned normalized integer formats. */ + + //! 8 bit format using 8 bits for the red channel. + ECF_R8, + + //! 16 bit format using 8 bits for the red and green channels. + ECF_R8G8, + + //! 16 bit format using 16 bits for the red channel. + ECF_R16, + + //! 32 bit format using 16 bits for the red and green channels. + ECF_R16G16, + + /** Depth and stencil formats. */ + + //! 16 bit format using 16 bits for depth. + ECF_D16, + + //! 32 bit format using 32 bits for depth. + ECF_D32, + + //! 32 bit format using 24 bits for depth and 8 bits for stencil. + ECF_D24S8, + + //! Unknown color format: + ECF_UNKNOWN +}; + +//! Names for ECOLOR_FORMAT types +const c8 *const ColorFormatNames[ECF_UNKNOWN + 2] = + { + "A1R5G5B5", + "R5G6B5", + "R8G8B8", + "A8R8G8B8", + "R16F", + "G16R16F", + "A16B16G16R16F", + "R32F", + "G32R32F", + "A32B32G32R32F", + "R8", + "R8G8", + "R16", + "R16G16", + "D16", + "D32", + "D24S8", + "UNKNOWN", + 0}; + +//! Creates a 16 bit A1R5G5B5 color +inline u16 RGBA16(u32 r, u32 g, u32 b, u32 a = 0xFF) +{ + return (u16)((a & 0x80) << 8 | + (r & 0xF8) << 7 | + (g & 0xF8) << 2 | + (b & 0xF8) >> 3); +} + +//! Creates a 16 bit A1R5G5B5 color +inline u16 RGB16(u32 r, u32 g, u32 b) +{ + return RGBA16(r, g, b); +} + +//! Creates a 16bit A1R5G5B5 color, based on 16bit input values +inline u16 RGB16from16(u16 r, u16 g, u16 b) +{ + return (0x8000 | + (r & 0x1F) << 10 | + (g & 0x1F) << 5 | + (b & 0x1F)); +} + +//! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color +inline u16 X8R8G8B8toA1R5G5B5(u32 color) +{ + return (u16)(0x8000 | + (color & 0x00F80000) >> 9 | + (color & 0x0000F800) >> 6 | + (color & 0x000000F8) >> 3); +} + +//! Converts a 32bit (A8R8G8B8) color to a 16bit A1R5G5B5 color +inline u16 A8R8G8B8toA1R5G5B5(u32 color) +{ + return (u16)((color & 0x80000000) >> 16 | + (color & 0x00F80000) >> 9 | + (color & 0x0000F800) >> 6 | + (color & 0x000000F8) >> 3); +} + +//! Converts a 32bit (A8R8G8B8) color to a 16bit R5G6B5 color +inline u16 A8R8G8B8toR5G6B5(u32 color) +{ + return (u16)((color & 0x00F80000) >> 8 | + (color & 0x0000FC00) >> 5 | + (color & 0x000000F8) >> 3); +} + +//! Convert A8R8G8B8 Color from A1R5G5B5 color +/** build a nicer 32bit Color by extending dest lower bits with source high bits. */ +inline u32 A1R5G5B5toA8R8G8B8(u16 color) +{ + return (((-((s32)color & 0x00008000) >> (s32)31) & 0xFF000000) | + ((color & 0x00007C00) << 9) | ((color & 0x00007000) << 4) | + ((color & 0x000003E0) << 6) | ((color & 0x00000380) << 1) | + ((color & 0x0000001F) << 3) | ((color & 0x0000001C) >> 2)); +} + +//! Returns A8R8G8B8 Color from R5G6B5 color +inline u32 R5G6B5toA8R8G8B8(u16 color) +{ + return 0xFF000000 | + ((color & 0xF800) << 8) | + ((color & 0x07E0) << 5) | + ((color & 0x001F) << 3); +} + +//! Returns A1R5G5B5 Color from R5G6B5 color +inline u16 R5G6B5toA1R5G5B5(u16 color) +{ + return 0x8000 | (((color & 0xFFC0) >> 1) | (color & 0x1F)); +} + +//! Returns R5G6B5 Color from A1R5G5B5 color +inline u16 A1R5G5B5toR5G6B5(u16 color) +{ + return (((color & 0x7FE0) << 1) | (color & 0x1F)); +} + +//! Returns the alpha component from A1R5G5B5 color +/** In Irrlicht, alpha refers to opacity. +\return The alpha value of the color. 0 is transparent, 1 is opaque. */ +inline u32 getAlpha(u16 color) +{ + return ((color >> 15) & 0x1); +} + +//! Returns the red component from A1R5G5B5 color. +/** Shift left by 3 to get 8 bit value. */ +inline u32 getRed(u16 color) +{ + return ((color >> 10) & 0x1F); +} + +//! Returns the green component from A1R5G5B5 color +/** Shift left by 3 to get 8 bit value. */ +inline u32 getGreen(u16 color) +{ + return ((color >> 5) & 0x1F); +} + +//! Returns the blue component from A1R5G5B5 color +/** Shift left by 3 to get 8 bit value. */ +inline u32 getBlue(u16 color) +{ + return (color & 0x1F); +} + +//! Returns the average from a 16 bit A1R5G5B5 color +inline s32 getAverage(s16 color) +{ + return ((getRed(color) << 3) + (getGreen(color) << 3) + (getBlue(color) << 3)) / 3; +} + +//! Class representing a 32 bit ARGB color. +/** The color values for alpha, red, green, and blue are +stored in a single u32. So all four values may be between 0 and 255. +Alpha in Irrlicht is opacity, so 0 is fully transparent, 255 is fully opaque (solid). +This class is used by most parts of the Irrlicht Engine +to specify a color. Another way is using the class SColorf, which +stores the color values in 4 floats. +This class must consist of only one u32 and must not use virtual functions. +*/ +class SColor +{ +public: + //! Constructor of the Color. Does nothing. + /** The color value is not initialized to save time. */ + SColor() {} + + //! Constructs the color from 4 values representing the alpha, red, green and blue component. + /** Must be values between 0 and 255. */ + constexpr SColor(u32 a, u32 r, u32 g, u32 b) : + color(((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) {} + + //! Constructs the color from a 32 bit value. Could be another color. + constexpr SColor(u32 clr) : + color(clr) {} + + //! Returns the alpha component of the color. + /** The alpha component defines how opaque a color is. + \return The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ + u32 getAlpha() const { return color >> 24; } + + //! Returns the red component of the color. + /** \return Value between 0 and 255, specifying how red the color is. + 0 means no red, 255 means full red. */ + u32 getRed() const { return (color >> 16) & 0xff; } + + //! Returns the green component of the color. + /** \return Value between 0 and 255, specifying how green the color is. + 0 means no green, 255 means full green. */ + u32 getGreen() const { return (color >> 8) & 0xff; } + + //! Returns the blue component of the color. + /** \return Value between 0 and 255, specifying how blue the color is. + 0 means no blue, 255 means full blue. */ + u32 getBlue() const { return color & 0xff; } + + //! Get lightness of the color in the range [0,255] + f32 getLightness() const + { + return 0.5f * (core::max_(core::max_(getRed(), getGreen()), getBlue()) + core::min_(core::min_(getRed(), getGreen()), getBlue())); + } + + //! Get luminance of the color in the range [0,255]. + f32 getLuminance() const + { + return 0.3f * getRed() + 0.59f * getGreen() + 0.11f * getBlue(); + } + + //! Get average intensity of the color in the range [0,255]. + u32 getAverage() const + { + return (getRed() + getGreen() + getBlue()) / 3; + } + + //! Sets the alpha component of the Color. + /** The alpha component defines how transparent a color should be. + \param a The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ + void setAlpha(u32 a) { color = ((a & 0xff) << 24) | (color & 0x00ffffff); } + + //! Sets the red component of the Color. + /** \param r: Has to be a value between 0 and 255. + 0 means no red, 255 means full red. */ + void setRed(u32 r) { color = ((r & 0xff) << 16) | (color & 0xff00ffff); } + + //! Sets the green component of the Color. + /** \param g: Has to be a value between 0 and 255. + 0 means no green, 255 means full green. */ + void setGreen(u32 g) { color = ((g & 0xff) << 8) | (color & 0xffff00ff); } + + //! Sets the blue component of the Color. + /** \param b: Has to be a value between 0 and 255. + 0 means no blue, 255 means full blue. */ + void setBlue(u32 b) { color = (b & 0xff) | (color & 0xffffff00); } + + //! Calculates a 16 bit A1R5G5B5 value of this color. + /** \return 16 bit A1R5G5B5 value of this color. */ + u16 toA1R5G5B5() const { return A8R8G8B8toA1R5G5B5(color); } + + //! Converts color to OpenGL color format + /** From ARGB to RGBA in 4 byte components for endian aware + passing to OpenGL + \param dest: address where the 4x8 bit OpenGL color is stored. */ + void toOpenGLColor(u8 *dest) const + { + *dest = (u8)getRed(); + *++dest = (u8)getGreen(); + *++dest = (u8)getBlue(); + *++dest = (u8)getAlpha(); + } + + //! Sets all four components of the color at once. + /** Constructs the color from 4 values representing the alpha, + red, green and blue components of the color. Must be values + between 0 and 255. + \param a: Alpha component of the color. The alpha component + defines how transparent a color should be. Has to be a value + between 0 and 255. 255 means not transparent (opaque), 0 means + fully transparent. + \param r: Sets the red component of the Color. Has to be a + value between 0 and 255. 0 means no red, 255 means full red. + \param g: Sets the green component of the Color. Has to be a + value between 0 and 255. 0 means no green, 255 means full + green. + \param b: Sets the blue component of the Color. Has to be a + value between 0 and 255. 0 means no blue, 255 means full blue. */ + void set(u32 a, u32 r, u32 g, u32 b) + { + color = (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)); + } + void set(u32 col) { color = col; } + + //! Compares the color to another color. + /** \return True if the colors are the same, and false if not. */ + bool operator==(const SColor &other) const { return other.color == color; } + + //! Compares the color to another color. + /** \return True if the colors are different, and false if they are the same. */ + bool operator!=(const SColor &other) const { return other.color != color; } + + //! comparison operator + /** \return True if this color is smaller than the other one */ + bool operator<(const SColor &other) const { return (color < other.color); } + + //! Adds two colors, result is clamped to 0..255 values + /** \param other Color to add to this color + \return Addition of the two colors, clamped to 0..255 values */ + SColor operator+(const SColor &other) const + { + return SColor(core::min_(getAlpha() + other.getAlpha(), 255u), + core::min_(getRed() + other.getRed(), 255u), + core::min_(getGreen() + other.getGreen(), 255u), + core::min_(getBlue() + other.getBlue(), 255u)); + } + + //! Interpolates the color with a f32 value to another color + /** \param other: Other color + \param d: value between 0.0f and 1.0f. d=0 returns other, d=1 returns this, values between interpolate. + \return Interpolated color. */ + SColor getInterpolated(const SColor &other, f32 d) const + { + d = core::clamp(d, 0.f, 1.f); + const f32 inv = 1.0f - d; + return SColor((u32)core::round32(other.getAlpha() * inv + getAlpha() * d), + (u32)core::round32(other.getRed() * inv + getRed() * d), + (u32)core::round32(other.getGreen() * inv + getGreen() * d), + (u32)core::round32(other.getBlue() * inv + getBlue() * d)); + } + + //! Returns interpolated color. ( quadratic ) + /** \param c1: first color to interpolate with + \param c2: second color to interpolate with + \param d: value between 0.0f and 1.0f. */ + SColor getInterpolated_quadratic(const SColor &c1, const SColor &c2, f32 d) const + { + // this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d; + d = core::clamp(d, 0.f, 1.f); + const f32 inv = 1.f - d; + const f32 mul0 = inv * inv; + const f32 mul1 = 2.f * d * inv; + const f32 mul2 = d * d; + + return SColor( + core::clamp(core::floor32( + getAlpha() * mul0 + c1.getAlpha() * mul1 + c2.getAlpha() * mul2), + 0, 255), + core::clamp(core::floor32( + getRed() * mul0 + c1.getRed() * mul1 + c2.getRed() * mul2), + 0, 255), + core::clamp(core::floor32( + getGreen() * mul0 + c1.getGreen() * mul1 + c2.getGreen() * mul2), + 0, 255), + core::clamp(core::floor32( + getBlue() * mul0 + c1.getBlue() * mul1 + c2.getBlue() * mul2), + 0, 255)); + } + + //! set the color by expecting data in the given format + /** \param data: must point to valid memory containing color information in the given format + \param format: tells the format in which data is available */ - enum ECOLOR_FORMAT + void setData(const void *data, ECOLOR_FORMAT format) { - //! 16 bit color format used by the software driver. - /** It is thus preferred by all other irrlicht engine video drivers. - There are 5 bits for every color component, and a single bit is left - for alpha information. */ - ECF_A1R5G5B5 = 0, - - //! Standard 16 bit color format. - ECF_R5G6B5, - - //! 24 bit color, no alpha channel, but 8 bit for red, green and blue. - //! Warning: 24 bit formats tend to be badly supported. Depending on driver it's usually converted to another - // format or even not working at all. It's mostly better to use 16-bit or 32-bit formats. - ECF_R8G8B8, - - //! Default 32 bit color format. 8 bits are used for every component: red, green, blue and alpha. - //! Warning: This tends to be BGRA in memory (it's ARGB on file, but with usual big-endian memory it's flipped) - ECF_A8R8G8B8, - - /** The following formats may only be used for render target textures. */ - - /** Floating point formats. */ - - //! 16 bit format using 16 bits for the red channel. - ECF_R16F, - - //! 32 bit format using 16 bits for the red and green channels. - ECF_G16R16F, - - //! 64 bit format using 16 bits for the red, green, blue and alpha channels. - ECF_A16B16G16R16F, - - //! 32 bit format using 32 bits for the red channel. - ECF_R32F, - - //! 64 bit format using 32 bits for the red and green channels. - ECF_G32R32F, - - //! 128 bit format using 32 bits for the red, green, blue and alpha channels. - ECF_A32B32G32R32F, - - /** Unsigned normalized integer formats. */ - - //! 8 bit format using 8 bits for the red channel. - ECF_R8, - - //! 16 bit format using 8 bits for the red and green channels. - ECF_R8G8, - - //! 16 bit format using 16 bits for the red channel. - ECF_R16, - - //! 32 bit format using 16 bits for the red and green channels. - ECF_R16G16, - - /** Depth and stencil formats. */ - - //! 16 bit format using 16 bits for depth. - ECF_D16, - - //! 32 bit format using 32 bits for depth. - ECF_D32, - - //! 32 bit format using 24 bits for depth and 8 bits for stencil. - ECF_D24S8, - - //! Unknown color format: - ECF_UNKNOWN - }; - - //! Names for ECOLOR_FORMAT types - const c8* const ColorFormatNames[ECF_UNKNOWN+2] = - { - "A1R5G5B5", - "R5G6B5", - "R8G8B8", - "A8R8G8B8", - "R16F", - "G16R16F", - "A16B16G16R16F", - "R32F", - "G32R32F", - "A32B32G32R32F", - "R8", - "R8G8", - "R16", - "R16G16", - "D16", - "D32", - "D24S8", - "UNKNOWN", - 0 - }; - - - //! Creates a 16 bit A1R5G5B5 color - inline u16 RGBA16(u32 r, u32 g, u32 b, u32 a=0xFF) - { - return (u16)((a & 0x80) << 8 | - (r & 0xF8) << 7 | - (g & 0xF8) << 2 | - (b & 0xF8) >> 3); + switch (format) { + case ECF_A1R5G5B5: + color = A1R5G5B5toA8R8G8B8(*(u16 *)data); + break; + case ECF_R5G6B5: + color = R5G6B5toA8R8G8B8(*(u16 *)data); + break; + case ECF_A8R8G8B8: + color = *(u32 *)data; + break; + case ECF_R8G8B8: { + const u8 *p = (u8 *)data; + set(255, p[0], p[1], p[2]); + } break; + default: + color = 0xffffffff; + break; + } } - - //! Creates a 16 bit A1R5G5B5 color - inline u16 RGB16(u32 r, u32 g, u32 b) - { - return RGBA16(r,g,b); - } - - - //! Creates a 16bit A1R5G5B5 color, based on 16bit input values - inline u16 RGB16from16(u16 r, u16 g, u16 b) - { - return (0x8000 | - (r & 0x1F) << 10 | - (g & 0x1F) << 5 | - (b & 0x1F)); - } - - - //! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color - inline u16 X8R8G8B8toA1R5G5B5(u32 color) - { - return (u16)(0x8000 | - ( color & 0x00F80000) >> 9 | - ( color & 0x0000F800) >> 6 | - ( color & 0x000000F8) >> 3); - } - - - //! Converts a 32bit (A8R8G8B8) color to a 16bit A1R5G5B5 color - inline u16 A8R8G8B8toA1R5G5B5(u32 color) - { - return (u16)(( color & 0x80000000) >> 16| - ( color & 0x00F80000) >> 9 | - ( color & 0x0000F800) >> 6 | - ( color & 0x000000F8) >> 3); - } - - - //! Converts a 32bit (A8R8G8B8) color to a 16bit R5G6B5 color - inline u16 A8R8G8B8toR5G6B5(u32 color) - { - return (u16)(( color & 0x00F80000) >> 8 | - ( color & 0x0000FC00) >> 5 | - ( color & 0x000000F8) >> 3); - } - - - //! Convert A8R8G8B8 Color from A1R5G5B5 color - /** build a nicer 32bit Color by extending dest lower bits with source high bits. */ - inline u32 A1R5G5B5toA8R8G8B8(u16 color) - { - return ( (( -( (s32) color & 0x00008000 ) >> (s32) 31 ) & 0xFF000000 ) | - (( color & 0x00007C00 ) << 9) | (( color & 0x00007000 ) << 4) | - (( color & 0x000003E0 ) << 6) | (( color & 0x00000380 ) << 1) | - (( color & 0x0000001F ) << 3) | (( color & 0x0000001C ) >> 2) - ); - } - - - //! Returns A8R8G8B8 Color from R5G6B5 color - inline u32 R5G6B5toA8R8G8B8(u16 color) - { - return 0xFF000000 | - ((color & 0xF800) << 8)| - ((color & 0x07E0) << 5)| - ((color & 0x001F) << 3); - } - - - //! Returns A1R5G5B5 Color from R5G6B5 color - inline u16 R5G6B5toA1R5G5B5(u16 color) - { - return 0x8000 | (((color & 0xFFC0) >> 1) | (color & 0x1F)); - } - - - //! Returns R5G6B5 Color from A1R5G5B5 color - inline u16 A1R5G5B5toR5G6B5(u16 color) - { - return (((color & 0x7FE0) << 1) | (color & 0x1F)); - } - - - - //! Returns the alpha component from A1R5G5B5 color - /** In Irrlicht, alpha refers to opacity. - \return The alpha value of the color. 0 is transparent, 1 is opaque. */ - inline u32 getAlpha(u16 color) - { - return ((color >> 15)&0x1); - } - - - //! Returns the red component from A1R5G5B5 color. - /** Shift left by 3 to get 8 bit value. */ - inline u32 getRed(u16 color) - { - return ((color >> 10)&0x1F); - } - - - //! Returns the green component from A1R5G5B5 color - /** Shift left by 3 to get 8 bit value. */ - inline u32 getGreen(u16 color) - { - return ((color >> 5)&0x1F); - } - - - //! Returns the blue component from A1R5G5B5 color - /** Shift left by 3 to get 8 bit value. */ - inline u32 getBlue(u16 color) - { - return (color & 0x1F); - } - - - //! Returns the average from a 16 bit A1R5G5B5 color - inline s32 getAverage(s16 color) - { - return ((getRed(color)<<3) + (getGreen(color)<<3) + (getBlue(color)<<3)) / 3; - } - - - //! Class representing a 32 bit ARGB color. - /** The color values for alpha, red, green, and blue are - stored in a single u32. So all four values may be between 0 and 255. - Alpha in Irrlicht is opacity, so 0 is fully transparent, 255 is fully opaque (solid). - This class is used by most parts of the Irrlicht Engine - to specify a color. Another way is using the class SColorf, which - stores the color values in 4 floats. - This class must consist of only one u32 and must not use virtual functions. + //! Write the color to data in the defined format + /** \param data: target to write the color. Must contain sufficiently large memory to receive the number of bytes neede for format + \param format: tells the format used to write the color into data */ - class SColor + void getData(void *data, ECOLOR_FORMAT format) const { - public: + switch (format) { + case ECF_A1R5G5B5: { + u16 *dest = (u16 *)data; + *dest = video::A8R8G8B8toA1R5G5B5(color); + } break; - //! Constructor of the Color. Does nothing. - /** The color value is not initialized to save time. */ - SColor() {} + case ECF_R5G6B5: { + u16 *dest = (u16 *)data; + *dest = video::A8R8G8B8toR5G6B5(color); + } break; - //! Constructs the color from 4 values representing the alpha, red, green and blue component. - /** Must be values between 0 and 255. */ - constexpr SColor (u32 a, u32 r, u32 g, u32 b) - : color(((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)) {} + case ECF_R8G8B8: { + u8 *dest = (u8 *)data; + dest[0] = (u8)getRed(); + dest[1] = (u8)getGreen(); + dest[2] = (u8)getBlue(); + } break; - //! Constructs the color from a 32 bit value. Could be another color. - constexpr SColor(u32 clr) - : color(clr) {} + case ECF_A8R8G8B8: { + u32 *dest = (u32 *)data; + *dest = color; + } break; - //! Returns the alpha component of the color. - /** The alpha component defines how opaque a color is. - \return The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ - u32 getAlpha() const { return color>>24; } - - //! Returns the red component of the color. - /** \return Value between 0 and 255, specifying how red the color is. - 0 means no red, 255 means full red. */ - u32 getRed() const { return (color>>16) & 0xff; } - - //! Returns the green component of the color. - /** \return Value between 0 and 255, specifying how green the color is. - 0 means no green, 255 means full green. */ - u32 getGreen() const { return (color>>8) & 0xff; } - - //! Returns the blue component of the color. - /** \return Value between 0 and 255, specifying how blue the color is. - 0 means no blue, 255 means full blue. */ - u32 getBlue() const { return color & 0xff; } - - //! Get lightness of the color in the range [0,255] - f32 getLightness() const - { - return 0.5f*(core::max_(core::max_(getRed(),getGreen()),getBlue())+core::min_(core::min_(getRed(),getGreen()),getBlue())); + default: + break; } - - //! Get luminance of the color in the range [0,255]. - f32 getLuminance() const - { - return 0.3f*getRed() + 0.59f*getGreen() + 0.11f*getBlue(); - } - - //! Get average intensity of the color in the range [0,255]. - u32 getAverage() const - { - return ( getRed() + getGreen() + getBlue() ) / 3; - } - - //! Sets the alpha component of the Color. - /** The alpha component defines how transparent a color should be. - \param a The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ - void setAlpha(u32 a) { color = ((a & 0xff)<<24) | (color & 0x00ffffff); } - - //! Sets the red component of the Color. - /** \param r: Has to be a value between 0 and 255. - 0 means no red, 255 means full red. */ - void setRed(u32 r) { color = ((r & 0xff)<<16) | (color & 0xff00ffff); } - - //! Sets the green component of the Color. - /** \param g: Has to be a value between 0 and 255. - 0 means no green, 255 means full green. */ - void setGreen(u32 g) { color = ((g & 0xff)<<8) | (color & 0xffff00ff); } - - //! Sets the blue component of the Color. - /** \param b: Has to be a value between 0 and 255. - 0 means no blue, 255 means full blue. */ - void setBlue(u32 b) { color = (b & 0xff) | (color & 0xffffff00); } - - //! Calculates a 16 bit A1R5G5B5 value of this color. - /** \return 16 bit A1R5G5B5 value of this color. */ - u16 toA1R5G5B5() const { return A8R8G8B8toA1R5G5B5(color); } - - //! Converts color to OpenGL color format - /** From ARGB to RGBA in 4 byte components for endian aware - passing to OpenGL - \param dest: address where the 4x8 bit OpenGL color is stored. */ - void toOpenGLColor(u8* dest) const - { - *dest = (u8)getRed(); - *++dest = (u8)getGreen(); - *++dest = (u8)getBlue(); - *++dest = (u8)getAlpha(); - } - - //! Sets all four components of the color at once. - /** Constructs the color from 4 values representing the alpha, - red, green and blue components of the color. Must be values - between 0 and 255. - \param a: Alpha component of the color. The alpha component - defines how transparent a color should be. Has to be a value - between 0 and 255. 255 means not transparent (opaque), 0 means - fully transparent. - \param r: Sets the red component of the Color. Has to be a - value between 0 and 255. 0 means no red, 255 means full red. - \param g: Sets the green component of the Color. Has to be a - value between 0 and 255. 0 means no green, 255 means full - green. - \param b: Sets the blue component of the Color. Has to be a - value between 0 and 255. 0 means no blue, 255 means full blue. */ - void set(u32 a, u32 r, u32 g, u32 b) - { - color = (((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)); - } - void set(u32 col) { color = col; } - - //! Compares the color to another color. - /** \return True if the colors are the same, and false if not. */ - bool operator==(const SColor& other) const { return other.color == color; } - - //! Compares the color to another color. - /** \return True if the colors are different, and false if they are the same. */ - bool operator!=(const SColor& other) const { return other.color != color; } - - //! comparison operator - /** \return True if this color is smaller than the other one */ - bool operator<(const SColor& other) const { return (color < other.color); } - - //! Adds two colors, result is clamped to 0..255 values - /** \param other Color to add to this color - \return Addition of the two colors, clamped to 0..255 values */ - SColor operator+(const SColor& other) const - { - return SColor(core::min_(getAlpha() + other.getAlpha(), 255u), - core::min_(getRed() + other.getRed(), 255u), - core::min_(getGreen() + other.getGreen(), 255u), - core::min_(getBlue() + other.getBlue(), 255u)); - } - - //! Interpolates the color with a f32 value to another color - /** \param other: Other color - \param d: value between 0.0f and 1.0f. d=0 returns other, d=1 returns this, values between interpolate. - \return Interpolated color. */ - SColor getInterpolated(const SColor &other, f32 d) const - { - d = core::clamp(d, 0.f, 1.f); - const f32 inv = 1.0f - d; - return SColor((u32)core::round32(other.getAlpha()*inv + getAlpha()*d), - (u32)core::round32(other.getRed()*inv + getRed()*d), - (u32)core::round32(other.getGreen()*inv + getGreen()*d), - (u32)core::round32(other.getBlue()*inv + getBlue()*d)); - } - - //! Returns interpolated color. ( quadratic ) - /** \param c1: first color to interpolate with - \param c2: second color to interpolate with - \param d: value between 0.0f and 1.0f. */ - SColor getInterpolated_quadratic(const SColor& c1, const SColor& c2, f32 d) const - { - // this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d; - d = core::clamp(d, 0.f, 1.f); - const f32 inv = 1.f - d; - const f32 mul0 = inv * inv; - const f32 mul1 = 2.f * d * inv; - const f32 mul2 = d * d; - - return SColor( - core::clamp( core::floor32( - getAlpha() * mul0 + c1.getAlpha() * mul1 + c2.getAlpha() * mul2 ), 0, 255 ), - core::clamp( core::floor32( - getRed() * mul0 + c1.getRed() * mul1 + c2.getRed() * mul2 ), 0, 255 ), - core::clamp ( core::floor32( - getGreen() * mul0 + c1.getGreen() * mul1 + c2.getGreen() * mul2 ), 0, 255 ), - core::clamp ( core::floor32( - getBlue() * mul0 + c1.getBlue() * mul1 + c2.getBlue() * mul2 ), 0, 255 )); - } - - //! set the color by expecting data in the given format - /** \param data: must point to valid memory containing color information in the given format - \param format: tells the format in which data is available - */ - void setData(const void *data, ECOLOR_FORMAT format) - { - switch (format) - { - case ECF_A1R5G5B5: - color = A1R5G5B5toA8R8G8B8(*(u16*)data); - break; - case ECF_R5G6B5: - color = R5G6B5toA8R8G8B8(*(u16*)data); - break; - case ECF_A8R8G8B8: - color = *(u32*)data; - break; - case ECF_R8G8B8: - { - const u8* p = (u8*)data; - set(255, p[0],p[1],p[2]); - } - break; - default: - color = 0xffffffff; - break; - } - } - - //! Write the color to data in the defined format - /** \param data: target to write the color. Must contain sufficiently large memory to receive the number of bytes neede for format - \param format: tells the format used to write the color into data - */ - void getData(void *data, ECOLOR_FORMAT format) const - { - switch(format) - { - case ECF_A1R5G5B5: - { - u16 * dest = (u16*)data; - *dest = video::A8R8G8B8toA1R5G5B5( color ); - } - break; - - case ECF_R5G6B5: - { - u16 * dest = (u16*)data; - *dest = video::A8R8G8B8toR5G6B5( color ); - } - break; - - case ECF_R8G8B8: - { - u8* dest = (u8*)data; - dest[0] = (u8)getRed(); - dest[1] = (u8)getGreen(); - dest[2] = (u8)getBlue(); - } - break; - - case ECF_A8R8G8B8: - { - u32 * dest = (u32*)data; - *dest = color; - } - break; - - default: - break; - } - } - - //! color in A8R8G8B8 Format - u32 color; - }; - - - //! Class representing a color with four floats. - /** The color values for red, green, blue - and alpha are each stored in a 32 bit floating point variable. - So all four values may be between 0.0f and 1.0f. - Another, faster way to define colors is using the class SColor, which - stores the color values in a single 32 bit integer. - */ - class SColorf - { - public: - //! Default constructor for SColorf. - /** Sets red, green and blue to 0.0f and alpha to 1.0f. */ - SColorf() : r(0.0f), g(0.0f), b(0.0f), a(1.0f) {} - - //! Constructs a color from up to four color values: red, green, blue, and alpha. - /** \param r: Red color component. Should be a value between - 0.0f meaning no red and 1.0f, meaning full red. - \param g: Green color component. Should be a value between 0.0f - meaning no green and 1.0f, meaning full green. - \param b: Blue color component. Should be a value between 0.0f - meaning no blue and 1.0f, meaning full blue. - \param a: Alpha color component of the color. The alpha - component defines how transparent a color should be. Has to be - a value between 0.0f and 1.0f, 1.0f means not transparent - (opaque), 0.0f means fully transparent. */ - SColorf(f32 r, f32 g, f32 b, f32 a = 1.0f) : r(r), g(g), b(b), a(a) {} - - //! Constructs a color from 32 bit Color. - /** \param c: 32 bit color from which this SColorf class is - constructed from. */ - SColorf(SColor c) - { - const f32 inv = 1.0f / 255.0f; - r = c.getRed() * inv; - g = c.getGreen() * inv; - b = c.getBlue() * inv; - a = c.getAlpha() * inv; - } - - //! Converts this color to a SColor without floats. - SColor toSColor() const - { - return SColor((u32)core::round32(a*255.0f), (u32)core::round32(r*255.0f), (u32)core::round32(g*255.0f), (u32)core::round32(b*255.0f)); - } - - //! Sets three color components to new values at once. - /** \param rr: Red color component. Should be a value between 0.0f meaning - no red (=black) and 1.0f, meaning full red. - \param gg: Green color component. Should be a value between 0.0f meaning - no green (=black) and 1.0f, meaning full green. - \param bb: Blue color component. Should be a value between 0.0f meaning - no blue (=black) and 1.0f, meaning full blue. */ - void set(f32 rr, f32 gg, f32 bb) {r = rr; g =gg; b = bb; } - - //! Sets all four color components to new values at once. - /** \param aa: Alpha component. Should be a value between 0.0f meaning - fully transparent and 1.0f, meaning opaque. - \param rr: Red color component. Should be a value between 0.0f meaning - no red and 1.0f, meaning full red. - \param gg: Green color component. Should be a value between 0.0f meaning - no green and 1.0f, meaning full green. - \param bb: Blue color component. Should be a value between 0.0f meaning - no blue and 1.0f, meaning full blue. */ - void set(f32 aa, f32 rr, f32 gg, f32 bb) {a = aa; r = rr; g =gg; b = bb; } - - //! Interpolates the color with a f32 value to another color - /** \param other: Other color - \param d: value between 0.0f and 1.0f - \return Interpolated color. */ - SColorf getInterpolated(const SColorf &other, f32 d) const - { - d = core::clamp(d, 0.f, 1.f); - const f32 inv = 1.0f - d; - return SColorf(other.r*inv + r*d, - other.g*inv + g*d, other.b*inv + b*d, other.a*inv + a*d); - } - - //! Returns interpolated color. ( quadratic ) - /** \param c1: first color to interpolate with - \param c2: second color to interpolate with - \param d: value between 0.0f and 1.0f. */ - inline SColorf getInterpolated_quadratic(const SColorf& c1, const SColorf& c2, - f32 d) const - { - d = core::clamp(d, 0.f, 1.f); - // this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d; - const f32 inv = 1.f - d; - const f32 mul0 = inv * inv; - const f32 mul1 = 2.f * d * inv; - const f32 mul2 = d * d; - - return SColorf (r * mul0 + c1.r * mul1 + c2.r * mul2, - g * mul0 + c1.g * mul1 + c2.g * mul2, - b * mul0 + c1.b * mul1 + c2.b * mul2, - a * mul0 + c1.a * mul1 + c2.a * mul2); - } - - - //! Sets a color component by index. R=0, G=1, B=2, A=3 - void setColorComponentValue(s32 index, f32 value) - { - switch(index) - { - case 0: r = value; break; - case 1: g = value; break; - case 2: b = value; break; - case 3: a = value; break; - } - } - - //! Returns the alpha component of the color in the range 0.0 (transparent) to 1.0 (opaque) - f32 getAlpha() const { return a; } - - //! Returns the red component of the color in the range 0.0 to 1.0 - f32 getRed() const { return r; } - - //! Returns the green component of the color in the range 0.0 to 1.0 - f32 getGreen() const { return g; } - - //! Returns the blue component of the color in the range 0.0 to 1.0 - f32 getBlue() const { return b; } - - //! red color component - f32 r; - - //! green color component - f32 g; - - //! blue component - f32 b; - - //! alpha color component - f32 a; - }; - - - //! Class representing a color in HSL format - /** The color values for hue, saturation, luminance - are stored in 32bit floating point variables. Hue is in range [0,360], - Luminance and Saturation are in percent [0,100] - */ - class SColorHSL - { - public: - constexpr SColorHSL ( f32 h = 0.f, f32 s = 0.f, f32 l = 0.f ) - : Hue ( h ), Saturation ( s ), Luminance ( l ) {} - - void fromRGB(const SColorf &color); - void toRGB(SColorf &color) const; - - f32 Hue; - f32 Saturation; - f32 Luminance; - - private: - inline f32 toRGB1(f32 rm1, f32 rm2, f32 rh) const; - - }; - - inline void SColorHSL::fromRGB(const SColorf &color) - { - const f32 maxVal = core::max_(color.getRed(), color.getGreen(), color.getBlue()); - const f32 minVal = (f32)core::min_(color.getRed(), color.getGreen(), color.getBlue()); - Luminance = (maxVal+minVal)*50; - if (core::equals(maxVal, minVal)) - { - Hue=0.f; - Saturation=0.f; - return; - } - - const f32 delta = maxVal-minVal; - if ( Luminance <= 50 ) - { - Saturation = (delta)/(maxVal+minVal); - } - else - { - Saturation = (delta)/(2-maxVal-minVal); - } - Saturation *= 100; - - if (core::equals(maxVal, color.getRed())) - Hue = (color.getGreen()-color.getBlue())/delta; - else if (core::equals(maxVal, color.getGreen())) - Hue = 2+((color.getBlue()-color.getRed())/delta); - else // blue is max - Hue = 4+((color.getRed()-color.getGreen())/delta); - - Hue *= 60.0f; - while ( Hue < 0.f ) - Hue += 360; } + //! color in A8R8G8B8 Format + u32 color; +}; - inline void SColorHSL::toRGB(SColorf &color) const +//! Class representing a color with four floats. +/** The color values for red, green, blue +and alpha are each stored in a 32 bit floating point variable. +So all four values may be between 0.0f and 1.0f. +Another, faster way to define colors is using the class SColor, which +stores the color values in a single 32 bit integer. +*/ +class SColorf +{ +public: + //! Default constructor for SColorf. + /** Sets red, green and blue to 0.0f and alpha to 1.0f. */ + SColorf() : + r(0.0f), g(0.0f), b(0.0f), a(1.0f) {} + + //! Constructs a color from up to four color values: red, green, blue, and alpha. + /** \param r: Red color component. Should be a value between + 0.0f meaning no red and 1.0f, meaning full red. + \param g: Green color component. Should be a value between 0.0f + meaning no green and 1.0f, meaning full green. + \param b: Blue color component. Should be a value between 0.0f + meaning no blue and 1.0f, meaning full blue. + \param a: Alpha color component of the color. The alpha + component defines how transparent a color should be. Has to be + a value between 0.0f and 1.0f, 1.0f means not transparent + (opaque), 0.0f means fully transparent. */ + SColorf(f32 r, f32 g, f32 b, f32 a = 1.0f) : + r(r), g(g), b(b), a(a) {} + + //! Constructs a color from 32 bit Color. + /** \param c: 32 bit color from which this SColorf class is + constructed from. */ + SColorf(SColor c) { - const f32 l = Luminance/100; - if (core::iszero(Saturation)) // grey - { - color.set(l, l, l); - return; + const f32 inv = 1.0f / 255.0f; + r = c.getRed() * inv; + g = c.getGreen() * inv; + b = c.getBlue() * inv; + a = c.getAlpha() * inv; + } + + //! Converts this color to a SColor without floats. + SColor toSColor() const + { + return SColor((u32)core::round32(a * 255.0f), (u32)core::round32(r * 255.0f), (u32)core::round32(g * 255.0f), (u32)core::round32(b * 255.0f)); + } + + //! Sets three color components to new values at once. + /** \param rr: Red color component. Should be a value between 0.0f meaning + no red (=black) and 1.0f, meaning full red. + \param gg: Green color component. Should be a value between 0.0f meaning + no green (=black) and 1.0f, meaning full green. + \param bb: Blue color component. Should be a value between 0.0f meaning + no blue (=black) and 1.0f, meaning full blue. */ + void set(f32 rr, f32 gg, f32 bb) + { + r = rr; + g = gg; + b = bb; + } + + //! Sets all four color components to new values at once. + /** \param aa: Alpha component. Should be a value between 0.0f meaning + fully transparent and 1.0f, meaning opaque. + \param rr: Red color component. Should be a value between 0.0f meaning + no red and 1.0f, meaning full red. + \param gg: Green color component. Should be a value between 0.0f meaning + no green and 1.0f, meaning full green. + \param bb: Blue color component. Should be a value between 0.0f meaning + no blue and 1.0f, meaning full blue. */ + void set(f32 aa, f32 rr, f32 gg, f32 bb) + { + a = aa; + r = rr; + g = gg; + b = bb; + } + + //! Interpolates the color with a f32 value to another color + /** \param other: Other color + \param d: value between 0.0f and 1.0f + \return Interpolated color. */ + SColorf getInterpolated(const SColorf &other, f32 d) const + { + d = core::clamp(d, 0.f, 1.f); + const f32 inv = 1.0f - d; + return SColorf(other.r * inv + r * d, + other.g * inv + g * d, other.b * inv + b * d, other.a * inv + a * d); + } + + //! Returns interpolated color. ( quadratic ) + /** \param c1: first color to interpolate with + \param c2: second color to interpolate with + \param d: value between 0.0f and 1.0f. */ + inline SColorf getInterpolated_quadratic(const SColorf &c1, const SColorf &c2, + f32 d) const + { + d = core::clamp(d, 0.f, 1.f); + // this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d; + const f32 inv = 1.f - d; + const f32 mul0 = inv * inv; + const f32 mul1 = 2.f * d * inv; + const f32 mul2 = d * d; + + return SColorf(r * mul0 + c1.r * mul1 + c2.r * mul2, + g * mul0 + c1.g * mul1 + c2.g * mul2, + b * mul0 + c1.b * mul1 + c2.b * mul2, + a * mul0 + c1.a * mul1 + c2.a * mul2); + } + + //! Sets a color component by index. R=0, G=1, B=2, A=3 + void setColorComponentValue(s32 index, f32 value) + { + switch (index) { + case 0: + r = value; + break; + case 1: + g = value; + break; + case 2: + b = value; + break; + case 3: + a = value; + break; } + } - f32 rm2; + //! Returns the alpha component of the color in the range 0.0 (transparent) to 1.0 (opaque) + f32 getAlpha() const { return a; } - if ( Luminance <= 50 ) - { - rm2 = l + l * (Saturation/100); - } - else - { - rm2 = l + (1 - l) * (Saturation/100); - } + //! Returns the red component of the color in the range 0.0 to 1.0 + f32 getRed() const { return r; } - const f32 rm1 = 2.0f * l - rm2; + //! Returns the green component of the color in the range 0.0 to 1.0 + f32 getGreen() const { return g; } - const f32 h = Hue / 360.0f; - color.set( toRGB1(rm1, rm2, h + 1.f/3.f), + //! Returns the blue component of the color in the range 0.0 to 1.0 + f32 getBlue() const { return b; } + + //! red color component + f32 r; + + //! green color component + f32 g; + + //! blue component + f32 b; + + //! alpha color component + f32 a; +}; + +//! Class representing a color in HSL format +/** The color values for hue, saturation, luminance +are stored in 32bit floating point variables. Hue is in range [0,360], +Luminance and Saturation are in percent [0,100] +*/ +class SColorHSL +{ +public: + constexpr SColorHSL(f32 h = 0.f, f32 s = 0.f, f32 l = 0.f) : + Hue(h), Saturation(s), Luminance(l) {} + + void fromRGB(const SColorf &color); + void toRGB(SColorf &color) const; + + f32 Hue; + f32 Saturation; + f32 Luminance; + +private: + inline f32 toRGB1(f32 rm1, f32 rm2, f32 rh) const; +}; + +inline void SColorHSL::fromRGB(const SColorf &color) +{ + const f32 maxVal = core::max_(color.getRed(), color.getGreen(), color.getBlue()); + const f32 minVal = (f32)core::min_(color.getRed(), color.getGreen(), color.getBlue()); + Luminance = (maxVal + minVal) * 50; + if (core::equals(maxVal, minVal)) { + Hue = 0.f; + Saturation = 0.f; + return; + } + + const f32 delta = maxVal - minVal; + if (Luminance <= 50) { + Saturation = (delta) / (maxVal + minVal); + } else { + Saturation = (delta) / (2 - maxVal - minVal); + } + Saturation *= 100; + + if (core::equals(maxVal, color.getRed())) + Hue = (color.getGreen() - color.getBlue()) / delta; + else if (core::equals(maxVal, color.getGreen())) + Hue = 2 + ((color.getBlue() - color.getRed()) / delta); + else // blue is max + Hue = 4 + ((color.getRed() - color.getGreen()) / delta); + + Hue *= 60.0f; + while (Hue < 0.f) + Hue += 360; +} + +inline void SColorHSL::toRGB(SColorf &color) const +{ + const f32 l = Luminance / 100; + if (core::iszero(Saturation)) // grey + { + color.set(l, l, l); + return; + } + + f32 rm2; + + if (Luminance <= 50) { + rm2 = l + l * (Saturation / 100); + } else { + rm2 = l + (1 - l) * (Saturation / 100); + } + + const f32 rm1 = 2.0f * l - rm2; + + const f32 h = Hue / 360.0f; + color.set(toRGB1(rm1, rm2, h + 1.f / 3.f), toRGB1(rm1, rm2, h), - toRGB1(rm1, rm2, h - 1.f/3.f) - ); - } + toRGB1(rm1, rm2, h - 1.f / 3.f)); +} +// algorithm from Foley/Van-Dam +inline f32 SColorHSL::toRGB1(f32 rm1, f32 rm2, f32 rh) const +{ + if (rh < 0) + rh += 1; + if (rh > 1) + rh -= 1; - // algorithm from Foley/Van-Dam - inline f32 SColorHSL::toRGB1(f32 rm1, f32 rm2, f32 rh) const - { - if (rh<0) - rh += 1; - if (rh>1) - rh -= 1; + if (rh < 1.f / 6.f) + rm1 = rm1 + (rm2 - rm1) * rh * 6.f; + else if (rh < 0.5f) + rm1 = rm2; + else if (rh < 2.f / 3.f) + rm1 = rm1 + (rm2 - rm1) * ((2.f / 3.f) - rh) * 6.f; - if (rh < 1.f/6.f) - rm1 = rm1 + (rm2 - rm1) * rh*6.f; - else if (rh < 0.5f) - rm1 = rm2; - else if (rh < 2.f/3.f) - rm1 = rm1 + (rm2 - rm1) * ((2.f/3.f)-rh)*6.f; - - return rm1; - } + return rm1; +} } // end namespace video } // end namespace irr diff --git a/include/SExposedVideoData.h b/include/SExposedVideoData.h index f630dc91..346bd037 100644 --- a/include/SExposedVideoData.h +++ b/include/SExposedVideoData.h @@ -17,52 +17,62 @@ you are using the software or the null device. */ struct SExposedVideoData { - SExposedVideoData() {OpenGLWin32.HDc=0; OpenGLWin32.HRc=0; OpenGLWin32.HWnd=0;} - explicit SExposedVideoData(void* Window) {OpenGLWin32.HDc=0; OpenGLWin32.HRc=0; OpenGLWin32.HWnd=Window;} + SExposedVideoData() + { + OpenGLWin32.HDc = 0; + OpenGLWin32.HRc = 0; + OpenGLWin32.HWnd = 0; + } + explicit SExposedVideoData(void *Window) + { + OpenGLWin32.HDc = 0; + OpenGLWin32.HRc = 0; + OpenGLWin32.HWnd = Window; + } struct SOpenGLWin32 { //! Private GDI Device Context. /** Get if for example with: HDC h = reinterpret_cast(exposedData.OpenGLWin32.HDc) */ - void* HDc; + void *HDc; //! Permanent Rendering Context. /** Get if for example with: HGLRC h = reinterpret_cast(exposedData.OpenGLWin32.HRc) */ - void* HRc; + void *HRc; //! Window handle. /** Get with for example with: HWND h = reinterpret_cast(exposedData.OpenGLWin32.HWnd) */ - void* HWnd; + void *HWnd; }; struct SOpenGLLinux { // XWindow handles - void* X11Display; - void* X11Context; + void *X11Display; + void *X11Context; unsigned long X11Window; unsigned long GLXWindow; }; - struct SOpenGLOSX - { - //! The NSOpenGLContext object. - void* Context; + struct SOpenGLOSX + { + //! The NSOpenGLContext object. + void *Context; - //! The NSWindow object. - void* Window; - }; + //! The NSWindow object. + void *Window; + }; struct SOpenGLFB { //! The EGLNativeWindowType object. - void* Window; + void *Window; }; struct SOGLESAndroid { //! The ANativeWindow object. - void* Window; + void *Window; }; union diff --git a/include/SIrrCreationParameters.h b/include/SIrrCreationParameters.h index 4051cd56..26e46e32 100644 --- a/include/SIrrCreationParameters.h +++ b/include/SIrrCreationParameters.h @@ -14,18 +14,18 @@ namespace irr { - class IEventReceiver; +class IEventReceiver; - //! Structure for holding Irrlicht Device creation parameters. - /** This structure is used in the createDeviceEx() function. */ - struct SIrrlichtCreationParameters - { - //! Constructs a SIrrlichtCreationParameters structure with default values. - SIrrlichtCreationParameters() : +//! Structure for holding Irrlicht Device creation parameters. +/** This structure is used in the createDeviceEx() function. */ +struct SIrrlichtCreationParameters +{ + //! Constructs a SIrrlichtCreationParameters structure with default values. + SIrrlichtCreationParameters() : DeviceType(EIDT_BEST), DriverType(video::EDT_OPENGL), WindowSize(core::dimension2d(800, 600)), - WindowPosition(core::position2di(-1,-1)), + WindowPosition(core::position2di(-1, -1)), Bits(32), ZBufferBits(24), Fullscreen(false), @@ -51,216 +51,217 @@ namespace irr #else OGLES2ShaderPath("../../media/Shaders/") #endif - { - } + { + } - SIrrlichtCreationParameters(const SIrrlichtCreationParameters& other) : + SIrrlichtCreationParameters(const SIrrlichtCreationParameters &other) : SDK_version_do_not_use(IRRLICHT_SDK_VERSION) - {*this = other;} + { + *this = other; + } - SIrrlichtCreationParameters& operator=(const SIrrlichtCreationParameters& other) + SIrrlichtCreationParameters &operator=(const SIrrlichtCreationParameters &other) + { + DeviceType = other.DeviceType; + DriverType = other.DriverType; + WindowSize = other.WindowSize; + WindowPosition = other.WindowPosition; + Bits = other.Bits; + ZBufferBits = other.ZBufferBits; + Fullscreen = other.Fullscreen; + WindowMaximized = other.WindowMaximized; + WindowResizable = other.WindowResizable; + Stencilbuffer = other.Stencilbuffer; + Vsync = other.Vsync; + AntiAlias = other.AntiAlias; + WithAlphaChannel = other.WithAlphaChannel; + Doublebuffer = other.Doublebuffer; + Stereobuffer = other.Stereobuffer; + EventReceiver = other.EventReceiver; + WindowId = other.WindowId; + LoggingLevel = other.LoggingLevel; + PrivateData = other.PrivateData; + OGLES2ShaderPath = other.OGLES2ShaderPath; + return *this; + } + + //! Type of the device. + /** This setting decides the windowing system used by the device, most device types are native + to a specific operating system and so may not be available. + EIDT_WIN32 is only available on Windows desktops, + EIDT_COCOA is only available on Mac OSX, + EIDT_X11 is available on Linux, Solaris, BSD and other operating systems which use X11, + EIDT_SDL is available on most systems if compiled in, + EIDT_BEST will select the best available device for your operating system. + Default: EIDT_BEST. */ + E_DEVICE_TYPE DeviceType; + + //! Type of video driver used to render graphics. + video::E_DRIVER_TYPE DriverType; + + //! Size of the window or the video mode in fullscreen mode. Default: 800x600 + core::dimension2d WindowSize; + + //! Position of the window on-screen. Default: (-1, -1) or centered. + core::position2di WindowPosition; + + //! Minimum Bits per pixel of the color buffer in fullscreen mode. Ignored if windowed mode. Default: 32. + u8 Bits; + + //! Minimum Bits per pixel of the depth buffer. Default: 24. + u8 ZBufferBits; + + //! Should be set to true if the device should run in fullscreen. + /** Otherwise the device runs in windowed mode. Default: false. */ + bool Fullscreen; + + //! Maximised window. (Only supported on SDL.) Default: false + bool WindowMaximized; + + //! Should a non-fullscreen window be resizable. + /** Might not be supported by all devices. Ignored when Fullscreen is true. + Values: 0 = not resizable, 1 = resizable, 2 = system decides default itself + Default: 2*/ + u8 WindowResizable; + + //! Specifies if the stencil buffer should be enabled. + /** Set this to true, if you want the engine be able to draw + stencil buffer shadows. Note that not all drivers are able to + use the stencil buffer, hence it can be ignored during device + creation. Without the stencil buffer no shadows will be drawn. + Default: true. */ + bool Stencilbuffer; + + //! Specifies vertical synchronization. + /** If set to true, the driver will wait for the vertical + retrace period, otherwise not. May be silently ignored. + Default: false */ + bool Vsync; + + //! Specifies if the device should use fullscreen anti aliasing + /** Makes sharp/pixelated edges softer, but requires more + performance. Also, 2D elements might look blurred with this + switched on. The resulting rendering quality also depends on + the hardware and driver you are using, your program might look + different on different hardware with this. So if you are + writing a game/application with AntiAlias switched on, it would + be a good idea to make it possible to switch this option off + again by the user. + The value is the maximal antialiasing factor requested for + the device. The creation method will automatically try smaller + values if no window can be created with the given value. + Value one is usually the same as 0 (disabled), but might be a + special value on some platforms. On D3D devices it maps to + NONMASKABLE. + Default value: 0 - disabled */ + u8 AntiAlias; + + //! Whether the main framebuffer uses an alpha channel. + /** In some situations it might be desirable to get a color + buffer with an alpha channel, e.g. when rendering into a + transparent window or overlay. If this flag is set the device + tries to create a framebuffer with alpha channel. + If this flag is set, only color buffers with alpha channel + are considered. Otherwise, it depends on the actual hardware + if the colorbuffer has an alpha channel or not. + Default value: false */ + bool WithAlphaChannel; + + //! Whether the main framebuffer uses doublebuffering. + /** This should be usually enabled, in order to avoid render + artifacts on the visible framebuffer. However, it might be + useful to use only one buffer on very small devices. If no + doublebuffering is available, the drivers will fall back to + single buffers. Default value: true */ + bool Doublebuffer; + + //! Specifies if the device should use stereo buffers + /** Some high-end gfx cards support two framebuffers for direct + support of stereoscopic output devices. If this flag is set the + device tries to create a stereo context. + Currently only supported by OpenGL. + Default value: false */ + bool Stereobuffer; + + //! A user created event receiver. + IEventReceiver *EventReceiver; + + //! Window Id. + /** If this is set to a value other than 0, the Irrlicht Engine + will be created in an already existing window. + For Windows, set this to the HWND of the window you want. + The windowSize and FullScreen options will be ignored when using + the WindowId parameter. Default this is set to 0. + To make Irrlicht run inside the custom window, you still will + have to draw Irrlicht on your own. You can use this loop, as + usual: + \code + while (device->run()) + { + driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, 0); + smgr->drawAll(); + driver->endScene(); + } + \endcode + Instead of this, you can also simply use your own message loop + using GetMessage, DispatchMessage and whatever. Calling + IrrlichtDevice::run() will cause Irrlicht to dispatch messages + internally too. You need not call Device->run() if you want to + do your own message dispatching loop, but Irrlicht will not be + able to fetch user input then and you have to do it on your own + using the window messages, DirectInput, or whatever. Also, + you'll have to increment the Irrlicht timer. + An alternative, own message dispatching loop without + device->run() would look like this: + \code + MSG msg; + while (true) + { + if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - DeviceType = other.DeviceType; - DriverType = other.DriverType; - WindowSize = other.WindowSize; - WindowPosition = other.WindowPosition; - Bits = other.Bits; - ZBufferBits = other.ZBufferBits; - Fullscreen = other.Fullscreen; - WindowMaximized = other.WindowMaximized; - WindowResizable = other.WindowResizable; - Stencilbuffer = other.Stencilbuffer; - Vsync = other.Vsync; - AntiAlias = other.AntiAlias; - WithAlphaChannel = other.WithAlphaChannel; - Doublebuffer = other.Doublebuffer; - Stereobuffer = other.Stereobuffer; - EventReceiver = other.EventReceiver; - WindowId = other.WindowId; - LoggingLevel = other.LoggingLevel; - PrivateData = other.PrivateData; - OGLES2ShaderPath = other.OGLES2ShaderPath; - return *this; + TranslateMessage(&msg); + DispatchMessage(&msg); + + if (msg.message == WM_QUIT) + break; } - //! Type of the device. - /** This setting decides the windowing system used by the device, most device types are native - to a specific operating system and so may not be available. - EIDT_WIN32 is only available on Windows desktops, - EIDT_COCOA is only available on Mac OSX, - EIDT_X11 is available on Linux, Solaris, BSD and other operating systems which use X11, - EIDT_SDL is available on most systems if compiled in, - EIDT_BEST will select the best available device for your operating system. - Default: EIDT_BEST. */ - E_DEVICE_TYPE DeviceType; + // increase virtual timer time + device->getTimer()->tick(); - //! Type of video driver used to render graphics. - video::E_DRIVER_TYPE DriverType; + // draw engine picture + driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, 0); + smgr->drawAll(); + driver->endScene(); + } + \endcode + However, there is no need to draw the picture this often. Just + do it how you like. */ + void *WindowId; - //! Size of the window or the video mode in fullscreen mode. Default: 800x600 - core::dimension2d WindowSize; + //! Specifies the logging level used in the logging interface. + /** The default value is ELL_INFORMATION. You can access the ILogger interface + later on from the IrrlichtDevice with getLogger() and set another level. + But if you need more or less logging information already from device creation, + then you have to change it here. + */ + ELOG_LEVEL LoggingLevel; - //! Position of the window on-screen. Default: (-1, -1) or centered. - core::position2di WindowPosition; + //! Don't use or change this parameter. + /** Always set it to IRRLICHT_SDK_VERSION, which is done by default. + This is needed for sdk version checks. */ + const c8 *const SDK_version_do_not_use; - //! Minimum Bits per pixel of the color buffer in fullscreen mode. Ignored if windowed mode. Default: 32. - u8 Bits; - - //! Minimum Bits per pixel of the depth buffer. Default: 24. - u8 ZBufferBits; - - //! Should be set to true if the device should run in fullscreen. - /** Otherwise the device runs in windowed mode. Default: false. */ - bool Fullscreen; - - //! Maximised window. (Only supported on SDL.) Default: false - bool WindowMaximized; - - //! Should a non-fullscreen window be resizable. - /** Might not be supported by all devices. Ignored when Fullscreen is true. - Values: 0 = not resizable, 1 = resizable, 2 = system decides default itself - Default: 2*/ - u8 WindowResizable; - - //! Specifies if the stencil buffer should be enabled. - /** Set this to true, if you want the engine be able to draw - stencil buffer shadows. Note that not all drivers are able to - use the stencil buffer, hence it can be ignored during device - creation. Without the stencil buffer no shadows will be drawn. - Default: true. */ - bool Stencilbuffer; - - //! Specifies vertical synchronization. - /** If set to true, the driver will wait for the vertical - retrace period, otherwise not. May be silently ignored. - Default: false */ - bool Vsync; - - //! Specifies if the device should use fullscreen anti aliasing - /** Makes sharp/pixelated edges softer, but requires more - performance. Also, 2D elements might look blurred with this - switched on. The resulting rendering quality also depends on - the hardware and driver you are using, your program might look - different on different hardware with this. So if you are - writing a game/application with AntiAlias switched on, it would - be a good idea to make it possible to switch this option off - again by the user. - The value is the maximal antialiasing factor requested for - the device. The creation method will automatically try smaller - values if no window can be created with the given value. - Value one is usually the same as 0 (disabled), but might be a - special value on some platforms. On D3D devices it maps to - NONMASKABLE. - Default value: 0 - disabled */ - u8 AntiAlias; - - //! Whether the main framebuffer uses an alpha channel. - /** In some situations it might be desirable to get a color - buffer with an alpha channel, e.g. when rendering into a - transparent window or overlay. If this flag is set the device - tries to create a framebuffer with alpha channel. - If this flag is set, only color buffers with alpha channel - are considered. Otherwise, it depends on the actual hardware - if the colorbuffer has an alpha channel or not. - Default value: false */ - bool WithAlphaChannel; - - //! Whether the main framebuffer uses doublebuffering. - /** This should be usually enabled, in order to avoid render - artifacts on the visible framebuffer. However, it might be - useful to use only one buffer on very small devices. If no - doublebuffering is available, the drivers will fall back to - single buffers. Default value: true */ - bool Doublebuffer; - - //! Specifies if the device should use stereo buffers - /** Some high-end gfx cards support two framebuffers for direct - support of stereoscopic output devices. If this flag is set the - device tries to create a stereo context. - Currently only supported by OpenGL. - Default value: false */ - bool Stereobuffer; - - //! A user created event receiver. - IEventReceiver* EventReceiver; - - //! Window Id. - /** If this is set to a value other than 0, the Irrlicht Engine - will be created in an already existing window. - For Windows, set this to the HWND of the window you want. - The windowSize and FullScreen options will be ignored when using - the WindowId parameter. Default this is set to 0. - To make Irrlicht run inside the custom window, you still will - have to draw Irrlicht on your own. You can use this loop, as - usual: - \code - while (device->run()) - { - driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, 0); - smgr->drawAll(); - driver->endScene(); - } - \endcode - Instead of this, you can also simply use your own message loop - using GetMessage, DispatchMessage and whatever. Calling - IrrlichtDevice::run() will cause Irrlicht to dispatch messages - internally too. You need not call Device->run() if you want to - do your own message dispatching loop, but Irrlicht will not be - able to fetch user input then and you have to do it on your own - using the window messages, DirectInput, or whatever. Also, - you'll have to increment the Irrlicht timer. - An alternative, own message dispatching loop without - device->run() would look like this: - \code - MSG msg; - while (true) - { - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - - if (msg.message == WM_QUIT) - break; - } - - // increase virtual timer time - device->getTimer()->tick(); - - // draw engine picture - driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, 0); - smgr->drawAll(); - driver->endScene(); - } - \endcode - However, there is no need to draw the picture this often. Just - do it how you like. */ - void* WindowId; - - //! Specifies the logging level used in the logging interface. - /** The default value is ELL_INFORMATION. You can access the ILogger interface - later on from the IrrlichtDevice with getLogger() and set another level. - But if you need more or less logging information already from device creation, - then you have to change it here. - */ - ELOG_LEVEL LoggingLevel; - - //! Don't use or change this parameter. - /** Always set it to IRRLICHT_SDK_VERSION, which is done by default. - This is needed for sdk version checks. */ - const c8* const SDK_version_do_not_use; - - //! Define some private data storage. - /** Used when platform devices need access to OS specific data structures etc. - This is only used for Android at the moment in order to access the native - Java RE. */ - void *PrivateData; - - //! Set the path where default-shaders to simulate the fixed-function pipeline can be found. - /** This is about the shaders which can be found in media/Shaders by default. It's only necessary - to set when using OGL-ES 2.0 */ - irr::io::path OGLES2ShaderPath; - }; + //! Define some private data storage. + /** Used when platform devices need access to OS specific data structures etc. + This is only used for Android at the moment in order to access the native + Java RE. */ + void *PrivateData; + //! Set the path where default-shaders to simulate the fixed-function pipeline can be found. + /** This is about the shaders which can be found in media/Shaders by default. It's only necessary + to set when using OGL-ES 2.0 */ + irr::io::path OGLES2ShaderPath; +}; } // end namespace irr diff --git a/include/SMaterial.h b/include/SMaterial.h index 05024c0f..0826f291 100644 --- a/include/SMaterial.h +++ b/include/SMaterial.h @@ -17,479 +17,475 @@ namespace irr { namespace video { - class ITexture; +class ITexture; - //! Flag for MaterialTypeParam (in combination with EMT_ONETEXTURE_BLEND) or for BlendFactor - //! BlendFunc = source * sourceFactor + dest * destFactor - enum E_BLEND_FACTOR - { - EBF_ZERO = 0, //!< src & dest (0, 0, 0, 0) - EBF_ONE, //!< src & dest (1, 1, 1, 1) - EBF_DST_COLOR, //!< src (destR, destG, destB, destA) - EBF_ONE_MINUS_DST_COLOR, //!< src (1-destR, 1-destG, 1-destB, 1-destA) - EBF_SRC_COLOR, //!< dest (srcR, srcG, srcB, srcA) - EBF_ONE_MINUS_SRC_COLOR, //!< dest (1-srcR, 1-srcG, 1-srcB, 1-srcA) - EBF_SRC_ALPHA, //!< src & dest (srcA, srcA, srcA, srcA) - EBF_ONE_MINUS_SRC_ALPHA, //!< src & dest (1-srcA, 1-srcA, 1-srcA, 1-srcA) - EBF_DST_ALPHA, //!< src & dest (destA, destA, destA, destA) - EBF_ONE_MINUS_DST_ALPHA, //!< src & dest (1-destA, 1-destA, 1-destA, 1-destA) - EBF_SRC_ALPHA_SATURATE //!< src (min(srcA, 1-destA), idem, ...) - }; +//! Flag for MaterialTypeParam (in combination with EMT_ONETEXTURE_BLEND) or for BlendFactor +//! BlendFunc = source * sourceFactor + dest * destFactor +enum E_BLEND_FACTOR +{ + EBF_ZERO = 0, //!< src & dest (0, 0, 0, 0) + EBF_ONE, //!< src & dest (1, 1, 1, 1) + EBF_DST_COLOR, //!< src (destR, destG, destB, destA) + EBF_ONE_MINUS_DST_COLOR, //!< src (1-destR, 1-destG, 1-destB, 1-destA) + EBF_SRC_COLOR, //!< dest (srcR, srcG, srcB, srcA) + EBF_ONE_MINUS_SRC_COLOR, //!< dest (1-srcR, 1-srcG, 1-srcB, 1-srcA) + EBF_SRC_ALPHA, //!< src & dest (srcA, srcA, srcA, srcA) + EBF_ONE_MINUS_SRC_ALPHA, //!< src & dest (1-srcA, 1-srcA, 1-srcA, 1-srcA) + EBF_DST_ALPHA, //!< src & dest (destA, destA, destA, destA) + EBF_ONE_MINUS_DST_ALPHA, //!< src & dest (1-destA, 1-destA, 1-destA, 1-destA) + EBF_SRC_ALPHA_SATURATE //!< src (min(srcA, 1-destA), idem, ...) +}; - //! Values defining the blend operation - enum E_BLEND_OPERATION - { - EBO_NONE = 0, //!< No blending happens - EBO_ADD, //!< Default blending adds the color values - EBO_SUBTRACT, //!< This mode subtracts the color values - EBO_REVSUBTRACT,//!< This modes subtracts destination from source - EBO_MIN, //!< Choose minimum value of each color channel - EBO_MAX, //!< Choose maximum value of each color channel - EBO_MIN_FACTOR, //!< Choose minimum value of each color channel after applying blend factors, not widely supported - EBO_MAX_FACTOR, //!< Choose maximum value of each color channel after applying blend factors, not widely supported - EBO_MIN_ALPHA, //!< Choose minimum value of each color channel based on alpha value, not widely supported - EBO_MAX_ALPHA //!< Choose maximum value of each color channel based on alpha value, not widely supported - }; +//! Values defining the blend operation +enum E_BLEND_OPERATION +{ + EBO_NONE = 0, //!< No blending happens + EBO_ADD, //!< Default blending adds the color values + EBO_SUBTRACT, //!< This mode subtracts the color values + EBO_REVSUBTRACT, //!< This modes subtracts destination from source + EBO_MIN, //!< Choose minimum value of each color channel + EBO_MAX, //!< Choose maximum value of each color channel + EBO_MIN_FACTOR, //!< Choose minimum value of each color channel after applying blend factors, not widely supported + EBO_MAX_FACTOR, //!< Choose maximum value of each color channel after applying blend factors, not widely supported + EBO_MIN_ALPHA, //!< Choose minimum value of each color channel based on alpha value, not widely supported + EBO_MAX_ALPHA //!< Choose maximum value of each color channel based on alpha value, not widely supported +}; - //! MaterialTypeParam: e.g. DirectX: D3DTOP_MODULATE, D3DTOP_MODULATE2X, D3DTOP_MODULATE4X - enum E_MODULATE_FUNC - { - EMFN_MODULATE_1X = 1, - EMFN_MODULATE_2X = 2, - EMFN_MODULATE_4X = 4 - }; +//! MaterialTypeParam: e.g. DirectX: D3DTOP_MODULATE, D3DTOP_MODULATE2X, D3DTOP_MODULATE4X +enum E_MODULATE_FUNC +{ + EMFN_MODULATE_1X = 1, + EMFN_MODULATE_2X = 2, + EMFN_MODULATE_4X = 4 +}; - //! Comparison function, e.g. for depth buffer test - enum E_COMPARISON_FUNC - { - //! Depth test disabled (disable also write to depth buffer) - ECFN_DISABLED=0, - //! <= test, default for e.g. depth test - ECFN_LESSEQUAL=1, - //! Exact equality - ECFN_EQUAL=2, - //! exclusive less comparison, i.e. < - ECFN_LESS, - //! Succeeds almost always, except for exact equality - ECFN_NOTEQUAL, - //! >= test - ECFN_GREATEREQUAL, - //! inverse of <= - ECFN_GREATER, - //! test succeeds always - ECFN_ALWAYS, - //! Test never succeeds - ECFN_NEVER - }; +//! Comparison function, e.g. for depth buffer test +enum E_COMPARISON_FUNC +{ + //! Depth test disabled (disable also write to depth buffer) + ECFN_DISABLED = 0, + //! <= test, default for e.g. depth test + ECFN_LESSEQUAL = 1, + //! Exact equality + ECFN_EQUAL = 2, + //! exclusive less comparison, i.e. < + ECFN_LESS, + //! Succeeds almost always, except for exact equality + ECFN_NOTEQUAL, + //! >= test + ECFN_GREATEREQUAL, + //! inverse of <= + ECFN_GREATER, + //! test succeeds always + ECFN_ALWAYS, + //! Test never succeeds + ECFN_NEVER +}; - //! Enum values for enabling/disabling color planes for rendering - enum E_COLOR_PLANE - { - //! No color enabled - ECP_NONE=0, - //! Alpha enabled - ECP_ALPHA=1, - //! Red enabled - ECP_RED=2, - //! Green enabled - ECP_GREEN=4, - //! Blue enabled - ECP_BLUE=8, - //! All colors, no alpha - ECP_RGB=14, - //! All planes enabled - ECP_ALL=15 - }; +//! Enum values for enabling/disabling color planes for rendering +enum E_COLOR_PLANE +{ + //! No color enabled + ECP_NONE = 0, + //! Alpha enabled + ECP_ALPHA = 1, + //! Red enabled + ECP_RED = 2, + //! Green enabled + ECP_GREEN = 4, + //! Blue enabled + ECP_BLUE = 8, + //! All colors, no alpha + ECP_RGB = 14, + //! All planes enabled + ECP_ALL = 15 +}; - //! Source of the alpha value to take - /** This is currently only supported in EMT_ONETEXTURE_BLEND. You can use an - or'ed combination of values. Alpha values are modulated (multiplied). */ - enum E_ALPHA_SOURCE - { - //! Use no alpha, somewhat redundant with other settings - EAS_NONE=0, - //! Use vertex color alpha - EAS_VERTEX_COLOR, - //! Use texture alpha channel - EAS_TEXTURE - }; +//! Source of the alpha value to take +/** This is currently only supported in EMT_ONETEXTURE_BLEND. You can use an +or'ed combination of values. Alpha values are modulated (multiplied). */ +enum E_ALPHA_SOURCE +{ + //! Use no alpha, somewhat redundant with other settings + EAS_NONE = 0, + //! Use vertex color alpha + EAS_VERTEX_COLOR, + //! Use texture alpha channel + EAS_TEXTURE +}; - //! Pack srcFact, dstFact, Modulate and alpha source to MaterialTypeParam or BlendFactor - /** alpha source can be an OR'ed combination of E_ALPHA_SOURCE values. */ - inline f32 pack_textureBlendFunc(const E_BLEND_FACTOR srcFact, const E_BLEND_FACTOR dstFact, - const E_MODULATE_FUNC modulate=EMFN_MODULATE_1X, const u32 alphaSource=EAS_TEXTURE) - { - const u32 tmp = (alphaSource << 20) | (modulate << 16) | (srcFact << 12) | (dstFact << 8) | (srcFact << 4) | dstFact; - return FR(tmp); +//! Pack srcFact, dstFact, Modulate and alpha source to MaterialTypeParam or BlendFactor +/** alpha source can be an OR'ed combination of E_ALPHA_SOURCE values. */ +inline f32 pack_textureBlendFunc(const E_BLEND_FACTOR srcFact, const E_BLEND_FACTOR dstFact, + const E_MODULATE_FUNC modulate = EMFN_MODULATE_1X, const u32 alphaSource = EAS_TEXTURE) +{ + const u32 tmp = (alphaSource << 20) | (modulate << 16) | (srcFact << 12) | (dstFact << 8) | (srcFact << 4) | dstFact; + return FR(tmp); +} + +//! Pack srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, Modulate and alpha source to MaterialTypeParam or BlendFactor +/** alpha source can be an OR'ed combination of E_ALPHA_SOURCE values. */ +inline f32 pack_textureBlendFuncSeparate(const E_BLEND_FACTOR srcRGBFact, const E_BLEND_FACTOR dstRGBFact, + const E_BLEND_FACTOR srcAlphaFact, const E_BLEND_FACTOR dstAlphaFact, + const E_MODULATE_FUNC modulate = EMFN_MODULATE_1X, const u32 alphaSource = EAS_TEXTURE) +{ + const u32 tmp = (alphaSource << 20) | (modulate << 16) | (srcAlphaFact << 12) | (dstAlphaFact << 8) | (srcRGBFact << 4) | dstRGBFact; + return FR(tmp); +} + +//! Unpack srcFact, dstFact, modulo and alphaSource factors +/** The fields don't use the full byte range, so we could pack even more... */ +inline void unpack_textureBlendFunc(E_BLEND_FACTOR &srcFact, E_BLEND_FACTOR &dstFact, + E_MODULATE_FUNC &modulo, u32 &alphaSource, const f32 param) +{ + const u32 state = IR(param); + alphaSource = (state & 0x00F00000) >> 20; + modulo = E_MODULATE_FUNC((state & 0x000F0000) >> 16); + srcFact = E_BLEND_FACTOR((state & 0x000000F0) >> 4); + dstFact = E_BLEND_FACTOR((state & 0x0000000F)); +} + +//! Unpack srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo and alphaSource factors +/** The fields don't use the full byte range, so we could pack even more... */ +inline void unpack_textureBlendFuncSeparate(E_BLEND_FACTOR &srcRGBFact, E_BLEND_FACTOR &dstRGBFact, + E_BLEND_FACTOR &srcAlphaFact, E_BLEND_FACTOR &dstAlphaFact, + E_MODULATE_FUNC &modulo, u32 &alphaSource, const f32 param) +{ + const u32 state = IR(param); + alphaSource = (state & 0x00F00000) >> 20; + modulo = E_MODULATE_FUNC((state & 0x000F0000) >> 16); + srcAlphaFact = E_BLEND_FACTOR((state & 0x0000F000) >> 12); + dstAlphaFact = E_BLEND_FACTOR((state & 0x00000F00) >> 8); + srcRGBFact = E_BLEND_FACTOR((state & 0x000000F0) >> 4); + dstRGBFact = E_BLEND_FACTOR((state & 0x0000000F)); +} + +//! has blend factor alphablending +inline bool textureBlendFunc_hasAlpha(const E_BLEND_FACTOR factor) +{ + switch (factor) { + case EBF_SRC_ALPHA: + case EBF_ONE_MINUS_SRC_ALPHA: + case EBF_DST_ALPHA: + case EBF_ONE_MINUS_DST_ALPHA: + case EBF_SRC_ALPHA_SATURATE: + return true; + default: + return false; } +} - //! Pack srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, Modulate and alpha source to MaterialTypeParam or BlendFactor - /** alpha source can be an OR'ed combination of E_ALPHA_SOURCE values. */ - inline f32 pack_textureBlendFuncSeparate(const E_BLEND_FACTOR srcRGBFact, const E_BLEND_FACTOR dstRGBFact, - const E_BLEND_FACTOR srcAlphaFact, const E_BLEND_FACTOR dstAlphaFact, - const E_MODULATE_FUNC modulate=EMFN_MODULATE_1X, const u32 alphaSource=EAS_TEXTURE) - { - const u32 tmp = (alphaSource << 20) | (modulate << 16) | (srcAlphaFact << 12) | (dstAlphaFact << 8) | (srcRGBFact << 4) | dstRGBFact; - return FR(tmp); - } +//! These flags are used to specify the anti-aliasing and smoothing modes +/** Techniques supported are multisampling, geometry smoothing, and alpha +to coverage. +Some drivers don't support a per-material setting of the anti-aliasing +modes. In those cases, FSAA/multisampling is defined by the device mode +chosen upon creation via irr::SIrrCreationParameters. +*/ +enum E_ANTI_ALIASING_MODE +{ + //! Use to turn off anti-aliasing for this material + EAAM_OFF = 0, + //! Default anti-aliasing mode + EAAM_SIMPLE = 1, + //! High-quality anti-aliasing, not always supported, automatically enables SIMPLE mode + EAAM_QUALITY = 3, + //! Enhanced anti-aliasing for transparent materials + /** Usually used with EMT_TRANSPARENT_ALPHA_CHANNEL_REF and multisampling. */ + EAAM_ALPHA_TO_COVERAGE = 4 +}; - //! Unpack srcFact, dstFact, modulo and alphaSource factors - /** The fields don't use the full byte range, so we could pack even more... */ - inline void unpack_textureBlendFunc(E_BLEND_FACTOR &srcFact, E_BLEND_FACTOR &dstFact, - E_MODULATE_FUNC &modulo, u32& alphaSource, const f32 param) - { - const u32 state = IR(param); - alphaSource = (state & 0x00F00000) >> 20; - modulo = E_MODULATE_FUNC( ( state & 0x000F0000 ) >> 16 ); - srcFact = E_BLEND_FACTOR ( ( state & 0x000000F0 ) >> 4 ); - dstFact = E_BLEND_FACTOR ( ( state & 0x0000000F ) ); - } +//! These flags allow to define the interpretation of vertex color when lighting is enabled +/** Without lighting being enabled the vertex color is the only value defining the fragment color. +Once lighting is enabled, the four values for diffuse, ambient, emissive, and specular take over. +With these flags it is possible to define which lighting factor shall be defined by the vertex color +instead of the lighting factor which is the same for all faces of that material. +The default is to use vertex color for the diffuse value, another pretty common value is to use +vertex color for both diffuse and ambient factor. */ +enum E_COLOR_MATERIAL +{ + //! Don't use vertex color for lighting + ECM_NONE = 0, + //! Use vertex color for diffuse light, this is default + ECM_DIFFUSE, + //! Use vertex color for ambient light + ECM_AMBIENT, + //! Use vertex color for emissive light + ECM_EMISSIVE, + //! Use vertex color for specular light + ECM_SPECULAR, + //! Use vertex color for both diffuse and ambient light + ECM_DIFFUSE_AND_AMBIENT +}; - //! Unpack srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo and alphaSource factors - /** The fields don't use the full byte range, so we could pack even more... */ - inline void unpack_textureBlendFuncSeparate(E_BLEND_FACTOR &srcRGBFact, E_BLEND_FACTOR &dstRGBFact, - E_BLEND_FACTOR &srcAlphaFact, E_BLEND_FACTOR &dstAlphaFact, - E_MODULATE_FUNC &modulo, u32& alphaSource, const f32 param) - { - const u32 state = IR(param); - alphaSource = (state & 0x00F00000) >> 20; - modulo = E_MODULATE_FUNC( ( state & 0x000F0000 ) >> 16 ); - srcAlphaFact = E_BLEND_FACTOR ( ( state & 0x0000F000 ) >> 12 ); - dstAlphaFact = E_BLEND_FACTOR ( ( state & 0x00000F00 ) >> 8 ); - srcRGBFact = E_BLEND_FACTOR ( ( state & 0x000000F0 ) >> 4 ); - dstRGBFact = E_BLEND_FACTOR ( ( state & 0x0000000F ) ); - } - - //! has blend factor alphablending - inline bool textureBlendFunc_hasAlpha ( const E_BLEND_FACTOR factor ) - { - switch ( factor ) +//! Names for polygon offset direction +const c8 *const PolygonOffsetDirectionNames[] = { - case EBF_SRC_ALPHA: - case EBF_ONE_MINUS_SRC_ALPHA: - case EBF_DST_ALPHA: - case EBF_ONE_MINUS_DST_ALPHA: - case EBF_SRC_ALPHA_SATURATE: - return true; - default: - return false; + "Back", + "Front", + 0}; + +//! For SMaterial.ZWriteEnable +enum E_ZWRITE +{ + //! zwrite always disabled for this material + EZW_OFF = 0, + + //! This is the default setting for SMaterial and tries to handle things automatically. + //! This is what you want to set to enable zwriting. + //! Usually zwriting is enabled non-transparent materials - as far as Irrlicht can recognize those. + //! Basically Irrlicht tries to handle the zwriting for you and assumes transparent materials don't need it. + //! This is addionally affected by IVideoDriver::setAllowZWriteOnTransparent + EZW_AUTO, + + //! zwrite always enabled for this material + EZW_ON +}; + +//! Names for E_ZWRITE +const c8 *const ZWriteNames[] = + { + "Off", + "Auto", + "On", + 0}; + +//! Maximum number of texture an SMaterial can have. +/** SMaterial might ignore some textures in most function, like assignment and comparison, + when SIrrlichtCreationParameters::MaxTextureUnits is set to a lower number. +*/ +const u32 MATERIAL_MAX_TEXTURES = 4; + +//! Struct for holding parameters for a material renderer +// Note for implementors: Serialization is in CNullDriver +class SMaterial +{ +public: + //! Default constructor. Creates a solid, lit material with white colors + SMaterial() : + MaterialType(EMT_SOLID), AmbientColor(255, 255, 255, 255), + DiffuseColor(255, 255, 255, 255), EmissiveColor(0, 0, 0, 0), + SpecularColor(255, 255, 255, 255), Shininess(0.0f), + MaterialTypeParam(0.0f), Thickness(1.0f), ZBuffer(ECFN_LESSEQUAL), + AntiAliasing(EAAM_SIMPLE), ColorMask(ECP_ALL), ColorMaterial(ECM_DIFFUSE), + BlendOperation(EBO_NONE), BlendFactor(0.0f), PolygonOffsetDepthBias(0.f), + PolygonOffsetSlopeScale(0.f), Wireframe(false), PointCloud(false), + GouraudShading(true), Lighting(true), ZWriteEnable(EZW_AUTO), + BackfaceCulling(true), FrontfaceCulling(false), FogEnable(false), + NormalizeNormals(false), UseMipMaps(true) + { + } + + //! Texture layer array. + SMaterialLayer TextureLayers[MATERIAL_MAX_TEXTURES]; + + //! Type of the material. Specifies how everything is blended together + E_MATERIAL_TYPE MaterialType; + + //! How much ambient light (a global light) is reflected by this material. + /** The default is full white, meaning objects are completely + globally illuminated. Reduce this if you want to see diffuse + or specular light effects. */ + SColor AmbientColor; + + //! How much diffuse light coming from a light source is reflected by this material. + /** The default is full white. */ + SColor DiffuseColor; + + //! Light emitted by this material. Default is to emit no light. + SColor EmissiveColor; + + //! How much specular light (highlights from a light) is reflected. + /** The default is to reflect white specular light. See + SMaterial::Shininess on how to enable specular lights. */ + SColor SpecularColor; + + //! Value affecting the size of specular highlights. + /** A value of 20 is common. If set to 0, no specular + highlights are being used. To activate, simply set the + shininess of a material to a value in the range [0.5;128]: + \code + sceneNode->getMaterial(0).Shininess = 20.0f; + \endcode + + You can change the color of the highlights using + \code + sceneNode->getMaterial(0).SpecularColor.set(255,255,255,255); + \endcode + + The specular color of the dynamic lights + (SLight::SpecularColor) will influence the the highlight color + too, but they are set to a useful value by default when + creating the light scene node.*/ + f32 Shininess; + + //! Free parameter, dependent on the material type. + /** Mostly ignored, used for example in + EMT_TRANSPARENT_ALPHA_CHANNEL and EMT_ONETEXTURE_BLEND. */ + f32 MaterialTypeParam; + + //! Thickness of non-3dimensional elements such as lines and points. + f32 Thickness; + + //! Is the ZBuffer enabled? Default: ECFN_LESSEQUAL + /** If you want to disable depth test for this material + just set this parameter to ECFN_DISABLED. + Values are from E_COMPARISON_FUNC. */ + u8 ZBuffer; + + //! Sets the antialiasing mode + /** Values are chosen from E_ANTI_ALIASING_MODE. Default is + EAAM_SIMPLE, i.e. simple multi-sample anti-aliasing. */ + u8 AntiAliasing; + + //! Defines the enabled color planes + /** Values are defined as or'ed values of the E_COLOR_PLANE enum. + Only enabled color planes will be rendered to the current render + target. Typical use is to disable all colors when rendering only to + depth or stencil buffer, or using Red and Green for Stereo rendering. */ + u8 ColorMask : 4; + + //! Defines the interpretation of vertex color in the lighting equation + /** Values should be chosen from E_COLOR_MATERIAL. + When lighting is enabled, vertex color can be used instead of the + material values for light modulation. This allows to easily change e.g. the + diffuse light behavior of each face. The default, ECM_DIFFUSE, will result in + a very similar rendering as with lighting turned off, just with light shading. */ + u8 ColorMaterial : 3; + + //! Store the blend operation of choice + /** Values to be chosen from E_BLEND_OPERATION. */ + E_BLEND_OPERATION BlendOperation : 4; + + //! Store the blend factors + /** textureBlendFunc/textureBlendFuncSeparate functions should be used to write + properly blending factors to this parameter. + Due to historical reasons this parameter is not used for material type + EMT_ONETEXTURE_BLEND which uses MaterialTypeParam instead for the blend factor. + It's generally used only for materials without any blending otherwise (like EMT_SOLID). + It's main use is to allow having shader materials which can enable/disable + blending after they have been created. + When you set this you usually also have to set BlendOperation to a value != EBO_NONE + (setting it to EBO_ADD is probably the most common one value). */ + f32 BlendFactor; + + //! A constant z-buffer offset for a polygon/line/point + /** The range of the value is driver specific. + On OpenGL you get units which are multiplied by the smallest value that is guaranteed to produce a resolvable offset. + On D3D9 you can pass a range between -1 and 1. But you should likely divide it by the range of the depthbuffer. + Like dividing by 65535.0 for a 16 bit depthbuffer. Thought it still might produce too large of a bias. + Some article (https://aras-p.info/blog/2008/06/12/depth-bias-and-the-power-of-deceiving-yourself/) + recommends multiplying by 2.0*4.8e-7 (and strangely on both 16 bit and 24 bit). */ + f32 PolygonOffsetDepthBias; + + //! Variable Z-Buffer offset based on the slope of the polygon. + /** For polygons looking flat at a camera you could use 0 (for example in a 2D game) + But in most cases you will have polygons rendered at a certain slope. + The driver will calculate the slope for you and this value allows to scale that slope. + The complete polygon offset is: PolygonOffsetSlopeScale*slope + PolygonOffsetDepthBias + A good default here is to use 1.f if you want to push the polygons away from the camera + and -1.f to pull them towards the camera. */ + f32 PolygonOffsetSlopeScale; + + //! Draw as wireframe or filled triangles? Default: false + bool Wireframe : 1; + + //! Draw as point cloud or filled triangles? Default: false + bool PointCloud : 1; + + //! Flat or Gouraud shading? Default: true + bool GouraudShading : 1; + + //! Will this material be lighted? Default: true + bool Lighting : 1; + + //! Is the zbuffer writable or is it read-only. Default: EZW_AUTO. + /** If this parameter is not EZW_OFF, you probably also want to set ZBuffer + to values other than ECFN_DISABLED */ + E_ZWRITE ZWriteEnable : 2; + + //! Is backface culling enabled? Default: true + bool BackfaceCulling : 1; + + //! Is frontface culling enabled? Default: false + bool FrontfaceCulling : 1; + + //! Is fog enabled? Default: false + bool FogEnable : 1; + + //! Should normals be normalized? + /** Always use this if the mesh lit and scaled. Default: false */ + bool NormalizeNormals : 1; + + //! Shall mipmaps be used if available + /** Sometimes, disabling mipmap usage can be useful. Default: true */ + bool UseMipMaps : 1; + + //! Execute a function on all texture layers. + /** Useful for setting properties which are not per material, but per + texture layer, e.g. bilinear filtering. */ + template + void forEachTexture(F &&fn) + { + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; i++) { + fn(TextureLayers[i]); } } - - //! These flags are used to specify the anti-aliasing and smoothing modes - /** Techniques supported are multisampling, geometry smoothing, and alpha - to coverage. - Some drivers don't support a per-material setting of the anti-aliasing - modes. In those cases, FSAA/multisampling is defined by the device mode - chosen upon creation via irr::SIrrCreationParameters. - */ - enum E_ANTI_ALIASING_MODE + //! Gets the texture transformation matrix for level i + /** \param i The desired level. Must not be larger than MATERIAL_MAX_TEXTURES + \return Texture matrix for texture level i. */ + core::matrix4 &getTextureMatrix(u32 i) { - //! Use to turn off anti-aliasing for this material - EAAM_OFF=0, - //! Default anti-aliasing mode - EAAM_SIMPLE=1, - //! High-quality anti-aliasing, not always supported, automatically enables SIMPLE mode - EAAM_QUALITY=3, - //! Enhanced anti-aliasing for transparent materials - /** Usually used with EMT_TRANSPARENT_ALPHA_CHANNEL_REF and multisampling. */ - EAAM_ALPHA_TO_COVERAGE=4 - }; + return TextureLayers[i].getTextureMatrix(); + } - //! These flags allow to define the interpretation of vertex color when lighting is enabled - /** Without lighting being enabled the vertex color is the only value defining the fragment color. - Once lighting is enabled, the four values for diffuse, ambient, emissive, and specular take over. - With these flags it is possible to define which lighting factor shall be defined by the vertex color - instead of the lighting factor which is the same for all faces of that material. - The default is to use vertex color for the diffuse value, another pretty common value is to use - vertex color for both diffuse and ambient factor. */ - enum E_COLOR_MATERIAL + //! Gets the immutable texture transformation matrix for level i + /** \param i The desired level. + \return Texture matrix for texture level i, or identity matrix for levels larger than MATERIAL_MAX_TEXTURES. */ + const core::matrix4 &getTextureMatrix(u32 i) const { - //! Don't use vertex color for lighting - ECM_NONE=0, - //! Use vertex color for diffuse light, this is default - ECM_DIFFUSE, - //! Use vertex color for ambient light - ECM_AMBIENT, - //! Use vertex color for emissive light - ECM_EMISSIVE, - //! Use vertex color for specular light - ECM_SPECULAR, - //! Use vertex color for both diffuse and ambient light - ECM_DIFFUSE_AND_AMBIENT - }; - - //! Names for polygon offset direction - const c8* const PolygonOffsetDirectionNames[] = - { - "Back", - "Front", - 0 - }; - - //! For SMaterial.ZWriteEnable - enum E_ZWRITE - { - //! zwrite always disabled for this material - EZW_OFF = 0, - - //! This is the default setting for SMaterial and tries to handle things automatically. - //! This is what you want to set to enable zwriting. - //! Usually zwriting is enabled non-transparent materials - as far as Irrlicht can recognize those. - //! Basically Irrlicht tries to handle the zwriting for you and assumes transparent materials don't need it. - //! This is addionally affected by IVideoDriver::setAllowZWriteOnTransparent - EZW_AUTO, - - //! zwrite always enabled for this material - EZW_ON - }; - - //! Names for E_ZWRITE - const c8* const ZWriteNames[] = - { - "Off", - "Auto", - "On", - 0 - }; - - - - //! Maximum number of texture an SMaterial can have. - /** SMaterial might ignore some textures in most function, like assignment and comparison, - when SIrrlichtCreationParameters::MaxTextureUnits is set to a lower number. - */ - const u32 MATERIAL_MAX_TEXTURES = 4; - - //! Struct for holding parameters for a material renderer - // Note for implementors: Serialization is in CNullDriver - class SMaterial - { - public: - //! Default constructor. Creates a solid, lit material with white colors - SMaterial() : - MaterialType(EMT_SOLID), AmbientColor(255, 255, 255, 255), - DiffuseColor(255, 255, 255, 255), EmissiveColor(0, 0, 0, 0), - SpecularColor(255, 255, 255, 255), Shininess(0.0f), - MaterialTypeParam(0.0f), Thickness(1.0f), ZBuffer(ECFN_LESSEQUAL), - AntiAliasing(EAAM_SIMPLE), ColorMask(ECP_ALL), ColorMaterial(ECM_DIFFUSE), - BlendOperation(EBO_NONE), BlendFactor(0.0f), PolygonOffsetDepthBias(0.f), - PolygonOffsetSlopeScale(0.f), Wireframe(false), PointCloud(false), - GouraudShading(true), Lighting(true), ZWriteEnable(EZW_AUTO), - BackfaceCulling(true), FrontfaceCulling(false), FogEnable(false), - NormalizeNormals(false), UseMipMaps(true) - { } - - //! Texture layer array. - SMaterialLayer TextureLayers[MATERIAL_MAX_TEXTURES]; - - //! Type of the material. Specifies how everything is blended together - E_MATERIAL_TYPE MaterialType; - - //! How much ambient light (a global light) is reflected by this material. - /** The default is full white, meaning objects are completely - globally illuminated. Reduce this if you want to see diffuse - or specular light effects. */ - SColor AmbientColor; - - //! How much diffuse light coming from a light source is reflected by this material. - /** The default is full white. */ - SColor DiffuseColor; - - //! Light emitted by this material. Default is to emit no light. - SColor EmissiveColor; - - //! How much specular light (highlights from a light) is reflected. - /** The default is to reflect white specular light. See - SMaterial::Shininess on how to enable specular lights. */ - SColor SpecularColor; - - //! Value affecting the size of specular highlights. - /** A value of 20 is common. If set to 0, no specular - highlights are being used. To activate, simply set the - shininess of a material to a value in the range [0.5;128]: - \code - sceneNode->getMaterial(0).Shininess = 20.0f; - \endcode - - You can change the color of the highlights using - \code - sceneNode->getMaterial(0).SpecularColor.set(255,255,255,255); - \endcode - - The specular color of the dynamic lights - (SLight::SpecularColor) will influence the the highlight color - too, but they are set to a useful value by default when - creating the light scene node.*/ - f32 Shininess; - - //! Free parameter, dependent on the material type. - /** Mostly ignored, used for example in - EMT_TRANSPARENT_ALPHA_CHANNEL and EMT_ONETEXTURE_BLEND. */ - f32 MaterialTypeParam; - - //! Thickness of non-3dimensional elements such as lines and points. - f32 Thickness; - - //! Is the ZBuffer enabled? Default: ECFN_LESSEQUAL - /** If you want to disable depth test for this material - just set this parameter to ECFN_DISABLED. - Values are from E_COMPARISON_FUNC. */ - u8 ZBuffer; - - //! Sets the antialiasing mode - /** Values are chosen from E_ANTI_ALIASING_MODE. Default is - EAAM_SIMPLE, i.e. simple multi-sample anti-aliasing. */ - u8 AntiAliasing; - - //! Defines the enabled color planes - /** Values are defined as or'ed values of the E_COLOR_PLANE enum. - Only enabled color planes will be rendered to the current render - target. Typical use is to disable all colors when rendering only to - depth or stencil buffer, or using Red and Green for Stereo rendering. */ - u8 ColorMask:4; - - //! Defines the interpretation of vertex color in the lighting equation - /** Values should be chosen from E_COLOR_MATERIAL. - When lighting is enabled, vertex color can be used instead of the - material values for light modulation. This allows to easily change e.g. the - diffuse light behavior of each face. The default, ECM_DIFFUSE, will result in - a very similar rendering as with lighting turned off, just with light shading. */ - u8 ColorMaterial:3; - - //! Store the blend operation of choice - /** Values to be chosen from E_BLEND_OPERATION. */ - E_BLEND_OPERATION BlendOperation:4; - - //! Store the blend factors - /** textureBlendFunc/textureBlendFuncSeparate functions should be used to write - properly blending factors to this parameter. - Due to historical reasons this parameter is not used for material type - EMT_ONETEXTURE_BLEND which uses MaterialTypeParam instead for the blend factor. - It's generally used only for materials without any blending otherwise (like EMT_SOLID). - It's main use is to allow having shader materials which can enable/disable - blending after they have been created. - When you set this you usually also have to set BlendOperation to a value != EBO_NONE - (setting it to EBO_ADD is probably the most common one value). */ - f32 BlendFactor; - - //! A constant z-buffer offset for a polygon/line/point - /** The range of the value is driver specific. - On OpenGL you get units which are multiplied by the smallest value that is guaranteed to produce a resolvable offset. - On D3D9 you can pass a range between -1 and 1. But you should likely divide it by the range of the depthbuffer. - Like dividing by 65535.0 for a 16 bit depthbuffer. Thought it still might produce too large of a bias. - Some article (https://aras-p.info/blog/2008/06/12/depth-bias-and-the-power-of-deceiving-yourself/) - recommends multiplying by 2.0*4.8e-7 (and strangely on both 16 bit and 24 bit). */ - f32 PolygonOffsetDepthBias; - - //! Variable Z-Buffer offset based on the slope of the polygon. - /** For polygons looking flat at a camera you could use 0 (for example in a 2D game) - But in most cases you will have polygons rendered at a certain slope. - The driver will calculate the slope for you and this value allows to scale that slope. - The complete polygon offset is: PolygonOffsetSlopeScale*slope + PolygonOffsetDepthBias - A good default here is to use 1.f if you want to push the polygons away from the camera - and -1.f to pull them towards the camera. */ - f32 PolygonOffsetSlopeScale; - - //! Draw as wireframe or filled triangles? Default: false - bool Wireframe:1; - - //! Draw as point cloud or filled triangles? Default: false - bool PointCloud:1; - - //! Flat or Gouraud shading? Default: true - bool GouraudShading:1; - - //! Will this material be lighted? Default: true - bool Lighting:1; - - //! Is the zbuffer writable or is it read-only. Default: EZW_AUTO. - /** If this parameter is not EZW_OFF, you probably also want to set ZBuffer - to values other than ECFN_DISABLED */ - E_ZWRITE ZWriteEnable:2; - - //! Is backface culling enabled? Default: true - bool BackfaceCulling:1; - - //! Is frontface culling enabled? Default: false - bool FrontfaceCulling:1; - - //! Is fog enabled? Default: false - bool FogEnable:1; - - //! Should normals be normalized? - /** Always use this if the mesh lit and scaled. Default: false */ - bool NormalizeNormals:1; - - //! Shall mipmaps be used if available - /** Sometimes, disabling mipmap usage can be useful. Default: true */ - bool UseMipMaps:1; - - //! Execute a function on all texture layers. - /** Useful for setting properties which are not per material, but per - texture layer, e.g. bilinear filtering. */ - template - void forEachTexture(F &&fn) { - for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; i++) { - fn(TextureLayers[i]); - } - } - - //! Gets the texture transformation matrix for level i - /** \param i The desired level. Must not be larger than MATERIAL_MAX_TEXTURES - \return Texture matrix for texture level i. */ - core::matrix4& getTextureMatrix(u32 i) - { + if (i < MATERIAL_MAX_TEXTURES) return TextureLayers[i].getTextureMatrix(); - } + else + return core::IdentityMatrix; + } - //! Gets the immutable texture transformation matrix for level i - /** \param i The desired level. - \return Texture matrix for texture level i, or identity matrix for levels larger than MATERIAL_MAX_TEXTURES. */ - const core::matrix4& getTextureMatrix(u32 i) const - { - if (i= MATERIAL_MAX_TEXTURES) + return; + TextureLayers[i].setTextureMatrix(mat); + } - //! Sets the i-th texture transformation matrix - /** \param i The desired level. - \param mat Texture matrix for texture level i. */ - void setTextureMatrix(u32 i, const core::matrix4& mat) - { - if (i>=MATERIAL_MAX_TEXTURES) - return; - TextureLayers[i].setTextureMatrix(mat); - } + //! Gets the i-th texture + /** \param i The desired level. + \return Texture for texture level i, if defined, else 0. */ + ITexture *getTexture(u32 i) const + { + return i < MATERIAL_MAX_TEXTURES ? TextureLayers[i].Texture : 0; + } - //! Gets the i-th texture - /** \param i The desired level. - \return Texture for texture level i, if defined, else 0. */ - ITexture* getTexture(u32 i) const - { - return i < MATERIAL_MAX_TEXTURES ? TextureLayers[i].Texture : 0; - } + //! Sets the i-th texture + /** If i>=MATERIAL_MAX_TEXTURES this setting will be ignored. + \param i The desired level. + \param tex Texture for texture level i. */ + void setTexture(u32 i, ITexture *tex) + { + if (i >= MATERIAL_MAX_TEXTURES) + return; + TextureLayers[i].Texture = tex; + } - //! Sets the i-th texture - /** If i>=MATERIAL_MAX_TEXTURES this setting will be ignored. - \param i The desired level. - \param tex Texture for texture level i. */ - void setTexture(u32 i, ITexture* tex) - { - if (i>=MATERIAL_MAX_TEXTURES) - return; - TextureLayers[i].Texture = tex; - } - - //! Inequality operator - /** \param b Material to compare to. - \return True if the materials differ, else false. */ - inline bool operator!=(const SMaterial& b) const - { - bool different = + //! Inequality operator + /** \param b Material to compare to. + \return True if the materials differ, else false. */ + inline bool operator!=(const SMaterial &b) const + { + bool different = MaterialType != b.MaterialType || AmbientColor != b.AmbientColor || DiffuseColor != b.DiffuseColor || @@ -515,58 +511,56 @@ namespace video BlendFactor != b.BlendFactor || PolygonOffsetDepthBias != b.PolygonOffsetDepthBias || PolygonOffsetSlopeScale != b.PolygonOffsetSlopeScale || - UseMipMaps != b.UseMipMaps - ; - for (u32 i=0; (idrop(); + } + + //! clean mesh + virtual void clear() + { + for (u32 i = 0; i < MeshBuffers.size(); ++i) + MeshBuffers[i]->drop(); + MeshBuffers.clear(); + BoundingBox.reset(0.f, 0.f, 0.f); + } + + //! returns amount of mesh buffers. + u32 getMeshBufferCount() const override + { + return MeshBuffers.size(); + } + + //! returns pointer to a mesh buffer + IMeshBuffer *getMeshBuffer(u32 nr) const override + { + return MeshBuffers[nr]; + } + + //! returns a meshbuffer which fits a material + /** reverse search */ + IMeshBuffer *getMeshBuffer(const video::SMaterial &material) const override + { + for (s32 i = (s32)MeshBuffers.size() - 1; i >= 0; --i) { + if (material == MeshBuffers[i]->getMaterial()) + return MeshBuffers[i]; } - //! destructor - virtual ~SMesh() - { - // drop buffers - for (u32 i=0; idrop(); - } + return 0; + } - //! clean mesh - virtual void clear() - { - for (u32 i=0; idrop(); - MeshBuffers.clear(); - BoundingBox.reset ( 0.f, 0.f, 0.f ); - } + //! returns an axis aligned bounding box + const core::aabbox3d &getBoundingBox() const override + { + return BoundingBox; + } + //! set user axis aligned bounding box + void setBoundingBox(const core::aabbox3df &box) override + { + BoundingBox = box; + } - //! returns amount of mesh buffers. - u32 getMeshBufferCount() const override - { - return MeshBuffers.size(); - } - - //! returns pointer to a mesh buffer - IMeshBuffer* getMeshBuffer(u32 nr) const override - { - return MeshBuffers[nr]; - } - - //! returns a meshbuffer which fits a material - /** reverse search */ - IMeshBuffer* getMeshBuffer( const video::SMaterial & material) const override - { - for (s32 i = (s32)MeshBuffers.size()-1; i >= 0; --i) - { - if ( material == MeshBuffers[i]->getMaterial()) - return MeshBuffers[i]; - } - - return 0; - } - - //! returns an axis aligned bounding box - const core::aabbox3d& getBoundingBox() const override - { - return BoundingBox; - } - - //! set user axis aligned bounding box - void setBoundingBox( const core::aabbox3df& box) override - { - BoundingBox = box; - } - - //! recalculates the bounding box - void recalculateBoundingBox() - { - bool hasMeshBufferBBox = false; - for (u32 i=0; igetBoundingBox(); - if ( !bb.isEmpty() ) - { - if ( !hasMeshBufferBBox ) - { - hasMeshBufferBBox = true; - BoundingBox = bb; - } - else - { - BoundingBox.addInternalBox(bb); - } - + //! recalculates the bounding box + void recalculateBoundingBox() + { + bool hasMeshBufferBBox = false; + for (u32 i = 0; i < MeshBuffers.size(); ++i) { + const core::aabbox3df &bb = MeshBuffers[i]->getBoundingBox(); + if (!bb.isEmpty()) { + if (!hasMeshBufferBBox) { + hasMeshBufferBBox = true; + BoundingBox = bb; + } else { + BoundingBox.addInternalBox(bb); } } - - if ( !hasMeshBufferBBox ) - BoundingBox.reset(0.0f, 0.0f, 0.0f); } - //! adds a MeshBuffer - /** The bounding box is not updated automatically. */ - void addMeshBuffer(IMeshBuffer* buf) - { - if (buf) - { - buf->grab(); - MeshBuffers.push_back(buf); - } + if (!hasMeshBufferBBox) + BoundingBox.reset(0.0f, 0.0f, 0.0f); + } + + //! adds a MeshBuffer + /** The bounding box is not updated automatically. */ + void addMeshBuffer(IMeshBuffer *buf) + { + if (buf) { + buf->grab(); + MeshBuffers.push_back(buf); } + } - //! set the hardware mapping hint, for driver - void setHardwareMappingHint( E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX ) override - { - for (u32 i=0; isetHardwareMappingHint(newMappingHint, buffer); - } + //! set the hardware mapping hint, for driver + void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override + { + for (u32 i = 0; i < MeshBuffers.size(); ++i) + MeshBuffers[i]->setHardwareMappingHint(newMappingHint, buffer); + } - //! flags the meshbuffer as changed, reloads hardware buffers - void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) override - { - for (u32 i=0; isetDirty(buffer); - } + //! flags the meshbuffer as changed, reloads hardware buffers + void setDirty(E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override + { + for (u32 i = 0; i < MeshBuffers.size(); ++i) + MeshBuffers[i]->setDirty(buffer); + } - //! The meshbuffers of this mesh - core::array MeshBuffers; - - //! The bounding box of this mesh - core::aabbox3d BoundingBox; - }; + //! The meshbuffers of this mesh + core::array MeshBuffers; + //! The bounding box of this mesh + core::aabbox3d BoundingBox; +}; } // end namespace scene } // end namespace irr diff --git a/include/SMeshBuffer.h b/include/SMeshBuffer.h index 2c3b7e23..2053db95 100644 --- a/include/SMeshBuffer.h +++ b/include/SMeshBuffer.h @@ -4,4 +4,3 @@ // replaced by template #include "CMeshBuffer.h" - diff --git a/include/SOverrideMaterial.h b/include/SOverrideMaterial.h index 6b95c66a..6de6e6eb 100644 --- a/include/SOverrideMaterial.h +++ b/include/SOverrideMaterial.h @@ -11,166 +11,182 @@ namespace irr namespace video { - struct SOverrideMaterial +struct SOverrideMaterial +{ + //! The Material values + SMaterial Material; + + //! Which values are overridden + /** OR'ed values from E_MATERIAL_PROPS. */ + u32 EnableProps; + + //! For those properties in EnableProps which affect layers, set which of the layers are affected + bool EnableLayerProps[MATERIAL_MAX_TEXTURES]; + + //! Which textures are overridden + bool EnableTextures[MATERIAL_MAX_TEXTURES]; + + //! Overwrite complete layers (settings of EnableLayerProps and EnableTextures don't matter then for layer data) + bool EnableLayers[MATERIAL_MAX_TEXTURES]; + + //! Set in which render passes the material override is active. + /** OR'ed values from E_SCENE_NODE_RENDER_PASS. */ + u16 EnablePasses; + + //! Global enable flag, overwritten by the SceneManager in each pass + /** NOTE: This is generally _not_ set by users of the engine, but the + Scenemanager uses the EnablePass array and sets Enabled to true if the + Override material is enabled in the current pass. + As user you generally _only_ set EnablePasses. + The exception is when rendering without SceneManager but using draw calls in the VideoDriver. */ + bool Enabled; + + struct SMaterialTypeReplacement { - //! The Material values - SMaterial Material; + SMaterialTypeReplacement(s32 original, u32 replacement) : + Original(original), Replacement(replacement) {} + SMaterialTypeReplacement(u32 replacement) : + Original(-1), Replacement(replacement) {} - //! Which values are overridden - /** OR'ed values from E_MATERIAL_PROPS. */ - u32 EnableProps; - - //! For those properties in EnableProps which affect layers, set which of the layers are affected - bool EnableLayerProps[MATERIAL_MAX_TEXTURES]; - - //! Which textures are overridden - bool EnableTextures[MATERIAL_MAX_TEXTURES]; - - //! Overwrite complete layers (settings of EnableLayerProps and EnableTextures don't matter then for layer data) - bool EnableLayers[MATERIAL_MAX_TEXTURES]; - - //! Set in which render passes the material override is active. - /** OR'ed values from E_SCENE_NODE_RENDER_PASS. */ - u16 EnablePasses; - - //! Global enable flag, overwritten by the SceneManager in each pass - /** NOTE: This is generally _not_ set by users of the engine, but the - Scenemanager uses the EnablePass array and sets Enabled to true if the - Override material is enabled in the current pass. - As user you generally _only_ set EnablePasses. - The exception is when rendering without SceneManager but using draw calls in the VideoDriver. */ - bool Enabled; - - struct SMaterialTypeReplacement - { - SMaterialTypeReplacement(s32 original, u32 replacement) : Original(original), Replacement(replacement) {} - SMaterialTypeReplacement(u32 replacement) : Original(-1), Replacement(replacement) {} - - //! SMaterial.MaterialType to replace. - //! -1 for all types or a specific value to only replace that one (which is either one of E_MATERIAL_TYPE or a shader material id) - s32 Original; - - //! MaterialType to used to override Original (either one of E_MATERIAL_TYPE or a shader material id) - u32 Replacement; - }; - - //! To overwrite SMaterial::MaterialType - core::array MaterialTypes; - - //! Default constructor - SOverrideMaterial() : EnableProps(0), EnablePasses(0), Enabled(false) - { - } - - //! disable overrides and reset all properties - void reset() - { - EnableProps = 0; - EnablePasses = 0; - Enabled = false; - for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) - { - EnableLayerProps[i] = true; // doesn't do anything unless EnableProps is set, just saying by default all texture layers are affected by properties - EnableTextures[i] = false; - EnableLayers[i] = false; - } - MaterialTypes.clear(); - } - - //! Apply the enabled overrides - void apply(SMaterial& material) - { - if (Enabled) - { - for (u32 i = 0; i < MaterialTypes.size(); ++i) - { - const SMaterialTypeReplacement& mtr = MaterialTypes[i]; - if (mtr.Original < 0 || (s32)mtr.Original == material.MaterialType) - material.MaterialType = (E_MATERIAL_TYPE)mtr.Replacement; - } - for (u32 f=0; f<32; ++f) - { - const u32 num=(1< MaterialTypes; + + //! Default constructor + SOverrideMaterial() : + EnableProps(0), EnablePasses(0), Enabled(false) + { + } + + //! disable overrides and reset all properties + void reset() + { + EnableProps = 0; + EnablePasses = 0; + Enabled = false; + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + EnableLayerProps[i] = true; // doesn't do anything unless EnableProps is set, just saying by default all texture layers are affected by properties + EnableTextures[i] = false; + EnableLayers[i] = false; + } + MaterialTypes.clear(); + } + + //! Apply the enabled overrides + void apply(SMaterial &material) + { + if (Enabled) { + for (u32 i = 0; i < MaterialTypes.size(); ++i) { + const SMaterialTypeReplacement &mtr = MaterialTypes[i]; + if (mtr.Original < 0 || (s32)mtr.Original == material.MaterialType) + material.MaterialType = (E_MATERIAL_TYPE)mtr.Replacement; + } + for (u32 f = 0; f < 32; ++f) { + const u32 num = (1 << f); + if (EnableProps & num) { + switch (num) { + case EMP_WIREFRAME: + material.Wireframe = Material.Wireframe; + break; + case EMP_POINTCLOUD: + material.PointCloud = Material.PointCloud; + break; + case EMP_GOURAUD_SHADING: + material.GouraudShading = Material.GouraudShading; + break; + case EMP_LIGHTING: + material.Lighting = Material.Lighting; + break; + case EMP_ZBUFFER: + material.ZBuffer = Material.ZBuffer; + break; + case EMP_ZWRITE_ENABLE: + material.ZWriteEnable = Material.ZWriteEnable; + break; + case EMP_BACK_FACE_CULLING: + material.BackfaceCulling = Material.BackfaceCulling; + break; + case EMP_FRONT_FACE_CULLING: + material.FrontfaceCulling = Material.FrontfaceCulling; + break; + case EMP_MIN_FILTER: + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (EnableLayerProps[i]) { + material.TextureLayers[i].MinFilter = Material.TextureLayers[i].MinFilter; + } + } + break; + case EMP_MAG_FILTER: + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (EnableLayerProps[i]) { + material.TextureLayers[i].MagFilter = Material.TextureLayers[i].MagFilter; + } + } + break; + case EMP_ANISOTROPIC_FILTER: + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (EnableLayerProps[i]) { + material.TextureLayers[i].AnisotropicFilter = Material.TextureLayers[i].AnisotropicFilter; + } + } + break; + case EMP_FOG_ENABLE: + material.FogEnable = Material.FogEnable; + break; + case EMP_NORMALIZE_NORMALS: + material.NormalizeNormals = Material.NormalizeNormals; + break; + case EMP_TEXTURE_WRAP: + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (EnableLayerProps[i]) { + material.TextureLayers[i].TextureWrapU = Material.TextureLayers[i].TextureWrapU; + material.TextureLayers[i].TextureWrapV = Material.TextureLayers[i].TextureWrapV; + material.TextureLayers[i].TextureWrapW = Material.TextureLayers[i].TextureWrapW; + } + } + break; + case EMP_ANTI_ALIASING: + material.AntiAliasing = Material.AntiAliasing; + break; + case EMP_COLOR_MASK: + material.ColorMask = Material.ColorMask; + break; + case EMP_COLOR_MATERIAL: + material.ColorMaterial = Material.ColorMaterial; + break; + case EMP_USE_MIP_MAPS: + material.UseMipMaps = Material.UseMipMaps; + break; + case EMP_BLEND_OPERATION: + material.BlendOperation = Material.BlendOperation; + break; + case EMP_BLEND_FACTOR: + material.BlendFactor = Material.BlendFactor; + break; + case EMP_POLYGON_OFFSET: + material.PolygonOffsetDepthBias = Material.PolygonOffsetDepthBias; + material.PolygonOffsetSlopeScale = Material.PolygonOffsetSlopeScale; + break; + } + } + } + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (EnableLayers[i]) { + material.TextureLayers[i] = Material.TextureLayers[i]; + } else if (EnableTextures[i]) { + material.TextureLayers[i].Texture = Material.TextureLayers[i].Texture; + } + } + } + } +}; + } // end namespace video } // end namespace irr diff --git a/include/SSkinMeshBuffer.h b/include/SSkinMeshBuffer.h index f31115f5..5ced6057 100644 --- a/include/SSkinMeshBuffer.h +++ b/include/SSkinMeshBuffer.h @@ -7,37 +7,35 @@ #include "IMeshBuffer.h" #include "S3DVertex.h" - namespace irr { namespace scene { - //! A mesh buffer able to choose between S3DVertex2TCoords, S3DVertex and S3DVertexTangents at runtime struct SSkinMeshBuffer : public IMeshBuffer { //! Default constructor - SSkinMeshBuffer(video::E_VERTEX_TYPE vt=video::EVT_STANDARD) : - ChangedID_Vertex(1), ChangedID_Index(1), VertexType(vt), - PrimitiveType(EPT_TRIANGLES), - MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER), - HWBuffer(NULL), - BoundingBoxNeedsRecalculated(true) + SSkinMeshBuffer(video::E_VERTEX_TYPE vt = video::EVT_STANDARD) : + ChangedID_Vertex(1), ChangedID_Index(1), VertexType(vt), + PrimitiveType(EPT_TRIANGLES), + MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER), + HWBuffer(NULL), + BoundingBoxNeedsRecalculated(true) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("SSkinMeshBuffer"); - #endif +#endif } //! Get Material of this buffer. - const video::SMaterial& getMaterial() const override + const video::SMaterial &getMaterial() const override { return Material; } //! Get Material of this buffer. - video::SMaterial& getMaterial() override + video::SMaterial &getMaterial() override { return Material; } @@ -45,56 +43,52 @@ struct SSkinMeshBuffer : public IMeshBuffer //! Get standard vertex at given index virtual video::S3DVertex *getVertex(u32 index) { - switch (VertexType) - { - case video::EVT_2TCOORDS: - return (video::S3DVertex*)&Vertices_2TCoords[index]; - case video::EVT_TANGENTS: - return (video::S3DVertex*)&Vertices_Tangents[index]; - default: - return &Vertices_Standard[index]; + switch (VertexType) { + case video::EVT_2TCOORDS: + return (video::S3DVertex *)&Vertices_2TCoords[index]; + case video::EVT_TANGENTS: + return (video::S3DVertex *)&Vertices_Tangents[index]; + default: + return &Vertices_Standard[index]; } } //! Get pointer to vertex array - const void* getVertices() const override + const void *getVertices() const override { - switch (VertexType) - { - case video::EVT_2TCOORDS: - return Vertices_2TCoords.const_pointer(); - case video::EVT_TANGENTS: - return Vertices_Tangents.const_pointer(); - default: - return Vertices_Standard.const_pointer(); + switch (VertexType) { + case video::EVT_2TCOORDS: + return Vertices_2TCoords.const_pointer(); + case video::EVT_TANGENTS: + return Vertices_Tangents.const_pointer(); + default: + return Vertices_Standard.const_pointer(); } } //! Get pointer to vertex array - void* getVertices() override + void *getVertices() override { - switch (VertexType) - { - case video::EVT_2TCOORDS: - return Vertices_2TCoords.pointer(); - case video::EVT_TANGENTS: - return Vertices_Tangents.pointer(); - default: - return Vertices_Standard.pointer(); + switch (VertexType) { + case video::EVT_2TCOORDS: + return Vertices_2TCoords.pointer(); + case video::EVT_TANGENTS: + return Vertices_Tangents.pointer(); + default: + return Vertices_Standard.pointer(); } } //! Get vertex count u32 getVertexCount() const override { - switch (VertexType) - { - case video::EVT_2TCOORDS: - return Vertices_2TCoords.size(); - case video::EVT_TANGENTS: - return Vertices_Tangents.size(); - default: - return Vertices_Standard.size(); + switch (VertexType) { + case video::EVT_2TCOORDS: + return Vertices_2TCoords.size(); + case video::EVT_TANGENTS: + return Vertices_Tangents.size(); + default: + return Vertices_Standard.size(); } } @@ -106,13 +100,13 @@ struct SSkinMeshBuffer : public IMeshBuffer } //! Get pointer to index array - const u16* getIndices() const override + const u16 *getIndices() const override { return Indices.const_pointer(); } //! Get pointer to index array - u16* getIndices() override + u16 *getIndices() override { return Indices.pointer(); } @@ -124,13 +118,13 @@ struct SSkinMeshBuffer : public IMeshBuffer } //! Get bounding box - const core::aabbox3d& getBoundingBox() const override + const core::aabbox3d &getBoundingBox() const override { return BoundingBox; } //! Set bounding box - void setBoundingBox( const core::aabbox3df& box) override + void setBoundingBox(const core::aabbox3df &box) override { BoundingBox = box; } @@ -138,49 +132,42 @@ struct SSkinMeshBuffer : public IMeshBuffer //! Recalculate bounding box void recalculateBoundingBox() override { - if(!BoundingBoxNeedsRecalculated) + if (!BoundingBoxNeedsRecalculated) return; BoundingBoxNeedsRecalculated = false; - switch (VertexType) - { - case video::EVT_STANDARD: - { - if (Vertices_Standard.empty()) - BoundingBox.reset(0,0,0); - else - { - BoundingBox.reset(Vertices_Standard[0].Pos); - for (u32 i=1; i + void operator()(VType &vertex) const { - public: - SVertexPositionScaleManipulator(const core::vector3df& factor) : Factor(factor) {} - template - void operator()(VType& vertex) const - { - vertex.Pos *= Factor; - } - private: - core::vector3df Factor; - }; + vertex.Pos *= Factor; + } + +private: + core::vector3df Factor; +}; } // end namespace scene } // end namespace irr diff --git a/include/SViewFrustum.h b/include/SViewFrustum.h index 15154482..06983cc5 100644 --- a/include/SViewFrustum.h +++ b/include/SViewFrustum.h @@ -16,443 +16,434 @@ namespace irr namespace scene { - //! Defines the view frustum. That's the space visible by the camera. - /** The view frustum is enclosed by 6 planes. These six planes share - eight points. A bounding box around these eight points is also stored in - this structure. - */ - struct SViewFrustum +//! Defines the view frustum. That's the space visible by the camera. +/** The view frustum is enclosed by 6 planes. These six planes share +eight points. A bounding box around these eight points is also stored in +this structure. +*/ +struct SViewFrustum +{ + enum VFPLANES { - enum VFPLANES - { - //! Far plane of the frustum. That is the plane furthest away from the eye. - VF_FAR_PLANE = 0, - //! Near plane of the frustum. That is the plane nearest to the eye. - VF_NEAR_PLANE, - //! Left plane of the frustum. - VF_LEFT_PLANE, - //! Right plane of the frustum. - VF_RIGHT_PLANE, - //! Bottom plane of the frustum. - VF_BOTTOM_PLANE, - //! Top plane of the frustum. - VF_TOP_PLANE, + //! Far plane of the frustum. That is the plane furthest away from the eye. + VF_FAR_PLANE = 0, + //! Near plane of the frustum. That is the plane nearest to the eye. + VF_NEAR_PLANE, + //! Left plane of the frustum. + VF_LEFT_PLANE, + //! Right plane of the frustum. + VF_RIGHT_PLANE, + //! Bottom plane of the frustum. + VF_BOTTOM_PLANE, + //! Top plane of the frustum. + VF_TOP_PLANE, - //! Amount of planes enclosing the view frustum. Should be 6. - VF_PLANE_COUNT - }; - - - //! Default Constructor - SViewFrustum() : BoundingRadius(0.f), FarNearDistance(0.f) {} - - //! Copy Constructor - SViewFrustum(const SViewFrustum& other); - - //! This constructor creates a view frustum based on a projection and/or view matrix. - //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). - SViewFrustum(const core::matrix4& mat, bool zClipFromZero); - - //! This constructor creates a view frustum based on a projection and/or view matrix. - //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). - inline void setFrom(const core::matrix4& mat, bool zClipFromZero); - - //! transforms the frustum by the matrix - /** \param mat: Matrix by which the view frustum is transformed.*/ - void transform(const core::matrix4& mat); - - //! returns the point which is on the far left upper corner inside the the view frustum. - core::vector3df getFarLeftUp() const; - - //! returns the point which is on the far left bottom corner inside the the view frustum. - core::vector3df getFarLeftDown() const; - - //! returns the point which is on the far right top corner inside the the view frustum. - core::vector3df getFarRightUp() const; - - //! returns the point which is on the far right bottom corner inside the the view frustum. - core::vector3df getFarRightDown() const; - - //! returns the point which is on the near left upper corner inside the the view frustum. - core::vector3df getNearLeftUp() const; - - //! returns the point which is on the near left bottom corner inside the the view frustum. - core::vector3df getNearLeftDown() const; - - //! returns the point which is on the near right top corner inside the the view frustum. - core::vector3df getNearRightUp() const; - - //! returns the point which is on the near right bottom corner inside the the view frustum. - core::vector3df getNearRightDown() const; - - //! returns a bounding box enclosing the whole view frustum - const core::aabbox3d &getBoundingBox() const; - - //! recalculates the bounding box and sphere based on the planes - inline void recalculateBoundingBox(); - - //! get the bounding sphere's radius (of an optimized sphere, not the AABB's) - float getBoundingRadius() const; - - //! get the bounding sphere's radius (of an optimized sphere, not the AABB's) - core::vector3df getBoundingCenter() const; - - //! the cam should tell the frustum the distance between far and near - void setFarNearDistance(float distance); - - //! get the given state's matrix based on frustum E_TRANSFORMATION_STATE - core::matrix4& getTransform( video::E_TRANSFORMATION_STATE state); - - //! get the given state's matrix based on frustum E_TRANSFORMATION_STATE - const core::matrix4& getTransform( video::E_TRANSFORMATION_STATE state) const; - - //! clips a line to the view frustum. - /** \return True if the line was clipped, false if not */ - bool clipLine(core::line3d& line) const; - - //! the position of the camera - core::vector3df cameraPosition; - - //! all planes enclosing the view frustum. - core::plane3d planes[VF_PLANE_COUNT]; - - //! bounding box around the view frustum - core::aabbox3d boundingBox; - - private: - //! Hold a copy of important transform matrices - enum E_TRANSFORMATION_STATE_FRUSTUM - { - ETS_VIEW = 0, - ETS_PROJECTION = 1, - ETS_COUNT_FRUSTUM - }; - - //! recalculates the bounding sphere based on the planes - inline void recalculateBoundingSphere(); - - //! Hold a copy of important transform matrices - core::matrix4 Matrices[ETS_COUNT_FRUSTUM]; - - float BoundingRadius; - float FarNearDistance; - core::vector3df BoundingCenter; + //! Amount of planes enclosing the view frustum. Should be 6. + VF_PLANE_COUNT }; + //! Default Constructor + SViewFrustum() : + BoundingRadius(0.f), FarNearDistance(0.f) {} - /*! - Copy constructor ViewFrustum - */ - inline SViewFrustum::SViewFrustum(const SViewFrustum& other) + //! Copy Constructor + SViewFrustum(const SViewFrustum &other); + + //! This constructor creates a view frustum based on a projection and/or view matrix. + //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). + SViewFrustum(const core::matrix4 &mat, bool zClipFromZero); + + //! This constructor creates a view frustum based on a projection and/or view matrix. + //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). + inline void setFrom(const core::matrix4 &mat, bool zClipFromZero); + + //! transforms the frustum by the matrix + /** \param mat: Matrix by which the view frustum is transformed.*/ + void transform(const core::matrix4 &mat); + + //! returns the point which is on the far left upper corner inside the the view frustum. + core::vector3df getFarLeftUp() const; + + //! returns the point which is on the far left bottom corner inside the the view frustum. + core::vector3df getFarLeftDown() const; + + //! returns the point which is on the far right top corner inside the the view frustum. + core::vector3df getFarRightUp() const; + + //! returns the point which is on the far right bottom corner inside the the view frustum. + core::vector3df getFarRightDown() const; + + //! returns the point which is on the near left upper corner inside the the view frustum. + core::vector3df getNearLeftUp() const; + + //! returns the point which is on the near left bottom corner inside the the view frustum. + core::vector3df getNearLeftDown() const; + + //! returns the point which is on the near right top corner inside the the view frustum. + core::vector3df getNearRightUp() const; + + //! returns the point which is on the near right bottom corner inside the the view frustum. + core::vector3df getNearRightDown() const; + + //! returns a bounding box enclosing the whole view frustum + const core::aabbox3d &getBoundingBox() const; + + //! recalculates the bounding box and sphere based on the planes + inline void recalculateBoundingBox(); + + //! get the bounding sphere's radius (of an optimized sphere, not the AABB's) + float getBoundingRadius() const; + + //! get the bounding sphere's radius (of an optimized sphere, not the AABB's) + core::vector3df getBoundingCenter() const; + + //! the cam should tell the frustum the distance between far and near + void setFarNearDistance(float distance); + + //! get the given state's matrix based on frustum E_TRANSFORMATION_STATE + core::matrix4 &getTransform(video::E_TRANSFORMATION_STATE state); + + //! get the given state's matrix based on frustum E_TRANSFORMATION_STATE + const core::matrix4 &getTransform(video::E_TRANSFORMATION_STATE state) const; + + //! clips a line to the view frustum. + /** \return True if the line was clipped, false if not */ + bool clipLine(core::line3d &line) const; + + //! the position of the camera + core::vector3df cameraPosition; + + //! all planes enclosing the view frustum. + core::plane3d planes[VF_PLANE_COUNT]; + + //! bounding box around the view frustum + core::aabbox3d boundingBox; + +private: + //! Hold a copy of important transform matrices + enum E_TRANSFORMATION_STATE_FRUSTUM { - cameraPosition=other.cameraPosition; - boundingBox=other.boundingBox; + ETS_VIEW = 0, + ETS_PROJECTION = 1, + ETS_COUNT_FRUSTUM + }; - u32 i; - for (i=0; i &SViewFrustum::getBoundingBox() const - { - return boundingBox; - } +inline const core::aabbox3d &SViewFrustum::getBoundingBox() const +{ + return boundingBox; +} - inline void SViewFrustum::recalculateBoundingBox() - { - boundingBox.reset(getNearLeftUp()); - boundingBox.addInternalPoint(getNearRightUp()); - boundingBox.addInternalPoint(getNearLeftDown()); - boundingBox.addInternalPoint(getNearRightDown()); - boundingBox.addInternalPoint(getFarRightUp()); - boundingBox.addInternalPoint(getFarLeftDown()); - boundingBox.addInternalPoint(getFarRightDown()); - boundingBox.addInternalPoint(getFarLeftUp()); +inline void SViewFrustum::recalculateBoundingBox() +{ + boundingBox.reset(getNearLeftUp()); + boundingBox.addInternalPoint(getNearRightUp()); + boundingBox.addInternalPoint(getNearLeftDown()); + boundingBox.addInternalPoint(getNearRightDown()); + boundingBox.addInternalPoint(getFarRightUp()); + boundingBox.addInternalPoint(getFarLeftDown()); + boundingBox.addInternalPoint(getFarRightDown()); + boundingBox.addInternalPoint(getFarLeftUp()); - // Also recalculate the bounding sphere when the bbox changes - recalculateBoundingSphere(); - } + // Also recalculate the bounding sphere when the bbox changes + recalculateBoundingSphere(); +} - inline float SViewFrustum::getBoundingRadius() const - { - return BoundingRadius; - } +inline float SViewFrustum::getBoundingRadius() const +{ + return BoundingRadius; +} - inline core::vector3df SViewFrustum::getBoundingCenter() const - { - return BoundingCenter; - } +inline core::vector3df SViewFrustum::getBoundingCenter() const +{ + return BoundingCenter; +} - inline void SViewFrustum::setFarNearDistance(float distance) - { - FarNearDistance = distance; - } +inline void SViewFrustum::setFarNearDistance(float distance) +{ + FarNearDistance = distance; +} - //! This constructor creates a view frustum based on a projection - //! and/or view matrix. - inline void SViewFrustum::setFrom(const core::matrix4& mat, bool zClipFromZero) - { - // left clipping plane - planes[VF_LEFT_PLANE].Normal.X = mat[3 ] + mat[0]; - planes[VF_LEFT_PLANE].Normal.Y = mat[7 ] + mat[4]; - planes[VF_LEFT_PLANE].Normal.Z = mat[11] + mat[8]; - planes[VF_LEFT_PLANE].D = mat[15] + mat[12]; +//! This constructor creates a view frustum based on a projection +//! and/or view matrix. +inline void SViewFrustum::setFrom(const core::matrix4 &mat, bool zClipFromZero) +{ + // left clipping plane + planes[VF_LEFT_PLANE].Normal.X = mat[3] + mat[0]; + planes[VF_LEFT_PLANE].Normal.Y = mat[7] + mat[4]; + planes[VF_LEFT_PLANE].Normal.Z = mat[11] + mat[8]; + planes[VF_LEFT_PLANE].D = mat[15] + mat[12]; - // right clipping plane - planes[VF_RIGHT_PLANE].Normal.X = mat[3 ] - mat[0]; - planes[VF_RIGHT_PLANE].Normal.Y = mat[7 ] - mat[4]; - planes[VF_RIGHT_PLANE].Normal.Z = mat[11] - mat[8]; - planes[VF_RIGHT_PLANE].D = mat[15] - mat[12]; + // right clipping plane + planes[VF_RIGHT_PLANE].Normal.X = mat[3] - mat[0]; + planes[VF_RIGHT_PLANE].Normal.Y = mat[7] - mat[4]; + planes[VF_RIGHT_PLANE].Normal.Z = mat[11] - mat[8]; + planes[VF_RIGHT_PLANE].D = mat[15] - mat[12]; - // top clipping plane - planes[VF_TOP_PLANE].Normal.X = mat[3 ] - mat[1]; - planes[VF_TOP_PLANE].Normal.Y = mat[7 ] - mat[5]; - planes[VF_TOP_PLANE].Normal.Z = mat[11] - mat[9]; - planes[VF_TOP_PLANE].D = mat[15] - mat[13]; + // top clipping plane + planes[VF_TOP_PLANE].Normal.X = mat[3] - mat[1]; + planes[VF_TOP_PLANE].Normal.Y = mat[7] - mat[5]; + planes[VF_TOP_PLANE].Normal.Z = mat[11] - mat[9]; + planes[VF_TOP_PLANE].D = mat[15] - mat[13]; - // bottom clipping plane - planes[VF_BOTTOM_PLANE].Normal.X = mat[3 ] + mat[1]; - planes[VF_BOTTOM_PLANE].Normal.Y = mat[7 ] + mat[5]; - planes[VF_BOTTOM_PLANE].Normal.Z = mat[11] + mat[9]; - planes[VF_BOTTOM_PLANE].D = mat[15] + mat[13]; + // bottom clipping plane + planes[VF_BOTTOM_PLANE].Normal.X = mat[3] + mat[1]; + planes[VF_BOTTOM_PLANE].Normal.Y = mat[7] + mat[5]; + planes[VF_BOTTOM_PLANE].Normal.Z = mat[11] + mat[9]; + planes[VF_BOTTOM_PLANE].D = mat[15] + mat[13]; - // far clipping plane - planes[VF_FAR_PLANE].Normal.X = mat[3 ] - mat[2]; - planes[VF_FAR_PLANE].Normal.Y = mat[7 ] - mat[6]; - planes[VF_FAR_PLANE].Normal.Z = mat[11] - mat[10]; - planes[VF_FAR_PLANE].D = mat[15] - mat[14]; + // far clipping plane + planes[VF_FAR_PLANE].Normal.X = mat[3] - mat[2]; + planes[VF_FAR_PLANE].Normal.Y = mat[7] - mat[6]; + planes[VF_FAR_PLANE].Normal.Z = mat[11] - mat[10]; + planes[VF_FAR_PLANE].D = mat[15] - mat[14]; + // near clipping plane + if (zClipFromZero) { + planes[VF_NEAR_PLANE].Normal.X = mat[2]; + planes[VF_NEAR_PLANE].Normal.Y = mat[6]; + planes[VF_NEAR_PLANE].Normal.Z = mat[10]; + planes[VF_NEAR_PLANE].D = mat[14]; + } else { // near clipping plane - if ( zClipFromZero ) - { - planes[VF_NEAR_PLANE].Normal.X = mat[2]; - planes[VF_NEAR_PLANE].Normal.Y = mat[6]; - planes[VF_NEAR_PLANE].Normal.Z = mat[10]; - planes[VF_NEAR_PLANE].D = mat[14]; - } - else - { - // near clipping plane - planes[VF_NEAR_PLANE].Normal.X = mat[3 ] + mat[2]; - planes[VF_NEAR_PLANE].Normal.Y = mat[7 ] + mat[6]; - planes[VF_NEAR_PLANE].Normal.Z = mat[11] + mat[10]; - planes[VF_NEAR_PLANE].D = mat[15] + mat[14]; - } - - // normalize normals - u32 i; - for ( i=0; i != VF_PLANE_COUNT; ++i) - { - const f32 len = -core::reciprocal_squareroot( - planes[i].Normal.getLengthSQ()); - planes[i].Normal *= len; - planes[i].D *= len; - } - - // make bounding box - recalculateBoundingBox(); + planes[VF_NEAR_PLANE].Normal.X = mat[3] + mat[2]; + planes[VF_NEAR_PLANE].Normal.Y = mat[7] + mat[6]; + planes[VF_NEAR_PLANE].Normal.Z = mat[11] + mat[10]; + planes[VF_NEAR_PLANE].D = mat[15] + mat[14]; } - /*! - View Frustum depends on Projection & View Matrix - */ - inline core::matrix4& SViewFrustum::getTransform(video::E_TRANSFORMATION_STATE state) - { - u32 index = 0; - switch ( state ) - { - case video::ETS_PROJECTION: - index = SViewFrustum::ETS_PROJECTION; break; - case video::ETS_VIEW: - index = SViewFrustum::ETS_VIEW; break; - default: - break; - } - return Matrices [ index ]; + // normalize normals + u32 i; + for (i = 0; i != VF_PLANE_COUNT; ++i) { + const f32 len = -core::reciprocal_squareroot( + planes[i].Normal.getLengthSQ()); + planes[i].Normal *= len; + planes[i].D *= len; } - /*! - View Frustum depends on Projection & View Matrix - */ - inline const core::matrix4& SViewFrustum::getTransform(video::E_TRANSFORMATION_STATE state) const - { - u32 index = 0; - switch ( state ) - { - case video::ETS_PROJECTION: - index = SViewFrustum::ETS_PROJECTION; break; - case video::ETS_VIEW: - index = SViewFrustum::ETS_VIEW; break; - default: - break; + // make bounding box + recalculateBoundingBox(); +} + +/*! + View Frustum depends on Projection & View Matrix +*/ +inline core::matrix4 &SViewFrustum::getTransform(video::E_TRANSFORMATION_STATE state) +{ + u32 index = 0; + switch (state) { + case video::ETS_PROJECTION: + index = SViewFrustum::ETS_PROJECTION; + break; + case video::ETS_VIEW: + index = SViewFrustum::ETS_VIEW; + break; + default: + break; + } + return Matrices[index]; +} + +/*! + View Frustum depends on Projection & View Matrix +*/ +inline const core::matrix4 &SViewFrustum::getTransform(video::E_TRANSFORMATION_STATE state) const +{ + u32 index = 0; + switch (state) { + case video::ETS_PROJECTION: + index = SViewFrustum::ETS_PROJECTION; + break; + case video::ETS_VIEW: + index = SViewFrustum::ETS_VIEW; + break; + default: + break; + } + return Matrices[index]; +} + +//! Clips a line to the frustum +inline bool SViewFrustum::clipLine(core::line3d &line) const +{ + bool wasClipped = false; + for (u32 i = 0; i < VF_PLANE_COUNT; ++i) { + if (planes[i].classifyPointRelation(line.start) == core::ISREL3D_FRONT) { + line.start = line.start.getInterpolated(line.end, + 1.f - planes[i].getKnownIntersectionWithLine(line.start, line.end)); + wasClipped = true; } - return Matrices [ index ]; + if (planes[i].classifyPointRelation(line.end) == core::ISREL3D_FRONT) { + line.end = line.start.getInterpolated(line.end, + 1.f - planes[i].getKnownIntersectionWithLine(line.start, line.end)); + wasClipped = true; + } + } + return wasClipped; +} + +inline void SViewFrustum::recalculateBoundingSphere() +{ + // Find the center + const float shortlen = (getNearLeftUp() - getNearRightUp()).getLength(); + const float longlen = (getFarLeftUp() - getFarRightUp()).getLength(); + + const float farlen = FarNearDistance; + const float fartocenter = (farlen + (shortlen - longlen) * (shortlen + longlen) / (4 * farlen)) / 2; + const float neartocenter = farlen - fartocenter; + + BoundingCenter = cameraPosition + -planes[VF_NEAR_PLANE].Normal * neartocenter; + + // Find the radius + core::vector3df dir[8]; + dir[0] = getFarLeftUp() - BoundingCenter; + dir[1] = getFarRightUp() - BoundingCenter; + dir[2] = getFarLeftDown() - BoundingCenter; + dir[3] = getFarRightDown() - BoundingCenter; + dir[4] = getNearRightDown() - BoundingCenter; + dir[5] = getNearLeftDown() - BoundingCenter; + dir[6] = getNearRightUp() - BoundingCenter; + dir[7] = getNearLeftUp() - BoundingCenter; + + u32 i = 0; + float diam[8] = {0.f}; + + for (i = 0; i < 8; ++i) + diam[i] = dir[i].getLengthSQ(); + + float longest = 0; + + for (i = 0; i < 8; ++i) { + if (diam[i] > longest) + longest = diam[i]; } - //! Clips a line to the frustum - inline bool SViewFrustum::clipLine(core::line3d& line) const - { - bool wasClipped = false; - for (u32 i=0; i < VF_PLANE_COUNT; ++i) - { - if (planes[i].classifyPointRelation(line.start) == core::ISREL3D_FRONT) - { - line.start = line.start.getInterpolated(line.end, - 1.f-planes[i].getKnownIntersectionWithLine(line.start, line.end)); - wasClipped = true; - } - if (planes[i].classifyPointRelation(line.end) == core::ISREL3D_FRONT) - { - line.end = line.start.getInterpolated(line.end, - 1.f-planes[i].getKnownIntersectionWithLine(line.start, line.end)); - wasClipped = true; - } - } - return wasClipped; - } - - inline void SViewFrustum::recalculateBoundingSphere() - { - // Find the center - const float shortlen = (getNearLeftUp() - getNearRightUp()).getLength(); - const float longlen = (getFarLeftUp() - getFarRightUp()).getLength(); - - const float farlen = FarNearDistance; - const float fartocenter = (farlen + (shortlen - longlen) * (shortlen + longlen)/(4*farlen)) / 2; - const float neartocenter = farlen - fartocenter; - - BoundingCenter = cameraPosition + -planes[VF_NEAR_PLANE].Normal * neartocenter; - - // Find the radius - core::vector3df dir[8]; - dir[0] = getFarLeftUp() - BoundingCenter; - dir[1] = getFarRightUp() - BoundingCenter; - dir[2] = getFarLeftDown() - BoundingCenter; - dir[3] = getFarRightDown() - BoundingCenter; - dir[4] = getNearRightDown() - BoundingCenter; - dir[5] = getNearLeftDown() - BoundingCenter; - dir[6] = getNearRightUp() - BoundingCenter; - dir[7] = getNearLeftUp() - BoundingCenter; - - u32 i = 0; - float diam[8] = { 0.f }; - - for (i = 0; i < 8; ++i) - diam[i] = dir[i].getLengthSQ(); - - float longest = 0; - - for (i = 0; i < 8; ++i) - { - if (diam[i] > longest) - longest = diam[i]; - } - - BoundingRadius = sqrtf(longest); - } + BoundingRadius = sqrtf(longest); +} } // end namespace scene } // end namespace irr diff --git a/include/SceneParameters.h b/include/SceneParameters.h index 73921fe8..717797e2 100644 --- a/include/SceneParameters.h +++ b/include/SceneParameters.h @@ -17,35 +17,34 @@ namespace irr { namespace scene { - //! Name of the parameter for changing how Irrlicht handles the ZWrite flag for transparent (blending) materials - /** The default behavior in Irrlicht is to disable writing to the - z-buffer for all really transparent, i.e. blending materials. This - avoids problems with intersecting faces, but can also break renderings. - If transparent materials should use the SMaterial flag for ZWriteEnable - just as other material types use this attribute. - Use it like this: - \code - SceneManager->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); - \endcode - **/ - const c8* const ALLOW_ZWRITE_ON_TRANSPARENT = "Allow_ZWrite_On_Transparent"; +//! Name of the parameter for changing how Irrlicht handles the ZWrite flag for transparent (blending) materials +/** The default behavior in Irrlicht is to disable writing to the +z-buffer for all really transparent, i.e. blending materials. This +avoids problems with intersecting faces, but can also break renderings. +If transparent materials should use the SMaterial flag for ZWriteEnable +just as other material types use this attribute. +Use it like this: +\code +SceneManager->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); +\endcode +**/ +const c8 *const ALLOW_ZWRITE_ON_TRANSPARENT = "Allow_ZWrite_On_Transparent"; - //! Flag to avoid loading group structures in .obj files - /** Use it like this: - \code - SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_GROUPS, true); - \endcode - **/ - const c8* const OBJ_LOADER_IGNORE_GROUPS = "OBJ_IgnoreGroups"; +//! Flag to avoid loading group structures in .obj files +/** Use it like this: +\code +SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_GROUPS, true); +\endcode +**/ +const c8 *const OBJ_LOADER_IGNORE_GROUPS = "OBJ_IgnoreGroups"; - - //! Flag to avoid loading material .mtl file for .obj files - /** Use it like this: - \code - SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); - \endcode - **/ - const c8* const OBJ_LOADER_IGNORE_MATERIAL_FILES = "OBJ_IgnoreMaterialFiles"; +//! Flag to avoid loading material .mtl file for .obj files +/** Use it like this: +\code +SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); +\endcode +**/ +const c8 *const OBJ_LOADER_IGNORE_MATERIAL_FILES = "OBJ_IgnoreMaterialFiles"; } // end namespace scene } // end namespace irr diff --git a/include/aabbox3d.h b/include/aabbox3d.h index e7117b5e..81c2293a 100644 --- a/include/aabbox3d.h +++ b/include/aabbox3d.h @@ -15,354 +15,375 @@ namespace core //! Axis aligned bounding box in 3d dimensional space. /** Has some useful methods used with occlusion culling or clipping. -*/ + */ template class aabbox3d { - public: - - //! Default Constructor. - constexpr aabbox3d(): MinEdge(-1,-1,-1), MaxEdge(1,1,1) {} - //! Constructor with min edge and max edge. - constexpr aabbox3d(const vector3d& min, const vector3d& max): MinEdge(min), MaxEdge(max) {} - //! Constructor with only one point. - constexpr aabbox3d(const vector3d& init): MinEdge(init), MaxEdge(init) {} - //! Constructor with min edge and max edge as single values, not vectors. - constexpr aabbox3d(T minx, T miny, T minz, T maxx, T maxy, T maxz): +public: + //! Default Constructor. + constexpr aabbox3d() : + MinEdge(-1, -1, -1), MaxEdge(1, 1, 1) {} + //! Constructor with min edge and max edge. + constexpr aabbox3d(const vector3d &min, const vector3d &max) : + MinEdge(min), MaxEdge(max) {} + //! Constructor with only one point. + constexpr aabbox3d(const vector3d &init) : + MinEdge(init), MaxEdge(init) {} + //! Constructor with min edge and max edge as single values, not vectors. + constexpr aabbox3d(T minx, T miny, T minz, T maxx, T maxy, T maxz) : MinEdge(minx, miny, minz), MaxEdge(maxx, maxy, maxz) {} - // operators - //! Equality operator - /** \param other box to compare with. - \return True if both boxes are equal, else false. */ - constexpr inline bool operator==(const aabbox3d& other) const - { return (MinEdge == other.MinEdge && other.MaxEdge == MaxEdge); } - //! Inequality operator - /** \param other box to compare with. - \return True if both boxes are different, else false. */ - constexpr inline bool operator!=(const aabbox3d& other) const - { return !(MinEdge == other.MinEdge && other.MaxEdge == MaxEdge); } + // operators + //! Equality operator + /** \param other box to compare with. + \return True if both boxes are equal, else false. */ + constexpr inline bool operator==(const aabbox3d &other) const + { + return (MinEdge == other.MinEdge && other.MaxEdge == MaxEdge); + } + //! Inequality operator + /** \param other box to compare with. + \return True if both boxes are different, else false. */ + constexpr inline bool operator!=(const aabbox3d &other) const + { + return !(MinEdge == other.MinEdge && other.MaxEdge == MaxEdge); + } - // functions + // functions - //! Resets the bounding box to a one-point box. - /** \param x X coord of the point. - \param y Y coord of the point. - \param z Z coord of the point. */ - void reset(T x, T y, T z) - { - MaxEdge.set(x,y,z); - MinEdge = MaxEdge; + //! Resets the bounding box to a one-point box. + /** \param x X coord of the point. + \param y Y coord of the point. + \param z Z coord of the point. */ + void reset(T x, T y, T z) + { + MaxEdge.set(x, y, z); + MinEdge = MaxEdge; + } + + //! Resets the bounding box. + /** \param initValue New box to set this one to. */ + void reset(const aabbox3d &initValue) + { + *this = initValue; + } + + //! Resets the bounding box to a one-point box. + /** \param initValue New point. */ + void reset(const vector3d &initValue) + { + MaxEdge = initValue; + MinEdge = initValue; + } + + //! Adds a point to the bounding box + /** The box grows bigger, if point was outside of the box. + \param p: Point to add into the box. */ + void addInternalPoint(const vector3d &p) + { + addInternalPoint(p.X, p.Y, p.Z); + } + + //! Adds another bounding box + /** The box grows bigger, if the new box was outside of the box. + \param b: Other bounding box to add into this box. */ + void addInternalBox(const aabbox3d &b) + { + addInternalPoint(b.MaxEdge); + addInternalPoint(b.MinEdge); + } + + //! Adds a point to the bounding box + /** The box grows bigger, if point is outside of the box. + \param x X coordinate of the point to add to this box. + \param y Y coordinate of the point to add to this box. + \param z Z coordinate of the point to add to this box. */ + void addInternalPoint(T x, T y, T z) + { + if (x > MaxEdge.X) + MaxEdge.X = x; + if (y > MaxEdge.Y) + MaxEdge.Y = y; + if (z > MaxEdge.Z) + MaxEdge.Z = z; + + if (x < MinEdge.X) + MinEdge.X = x; + if (y < MinEdge.Y) + MinEdge.Y = y; + if (z < MinEdge.Z) + MinEdge.Z = z; + } + + //! Get center of the bounding box + /** \return Center of the bounding box. */ + vector3d getCenter() const + { + return (MinEdge + MaxEdge) / 2; + } + + //! Get extent of the box (maximal distance of two points in the box) + /** \return Extent of the bounding box. */ + vector3d getExtent() const + { + return MaxEdge - MinEdge; + } + + //! Get radius of the bounding sphere + /** \return Radius of the bounding sphere. */ + T getRadius() const + { + const T radius = getExtent().getLength() / 2; + return radius; + } + + //! Check if the box is empty. + /** This means that there is no space between the min and max edge. + \return True if box is empty, else false. */ + bool isEmpty() const + { + return MinEdge.equals(MaxEdge); + } + + //! Get the volume enclosed by the box in cubed units + T getVolume() const + { + const vector3d e = getExtent(); + return e.X * e.Y * e.Z; + } + + //! Get the surface area of the box in squared units + T getArea() const + { + const vector3d e = getExtent(); + return 2 * (e.X * e.Y + e.X * e.Z + e.Y * e.Z); + } + + //! Stores all 8 edges of the box into an array + /** \param edges: Pointer to array of 8 edges. */ + void getEdges(vector3d *edges) const + { + const core::vector3d middle = getCenter(); + const core::vector3d diag = middle - MaxEdge; + + /* + Edges are stored in this way: + Hey, am I an ascii artist, or what? :) niko. + /3--------/7 + / | / | + / | / | + 1---------5 | + | /2- - -|- -6 + | / | / + |/ | / + 0---------4/ + */ + + edges[0].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z + diag.Z); + edges[1].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z + diag.Z); + edges[2].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z - diag.Z); + edges[3].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z - diag.Z); + edges[4].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z + diag.Z); + edges[5].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z + diag.Z); + edges[6].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z - diag.Z); + edges[7].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z - diag.Z); + } + + //! Repairs the box. + /** Necessary if for example MinEdge and MaxEdge are swapped. */ + void repair() + { + T t; + + if (MinEdge.X > MaxEdge.X) { + t = MinEdge.X; + MinEdge.X = MaxEdge.X; + MaxEdge.X = t; } - - //! Resets the bounding box. - /** \param initValue New box to set this one to. */ - void reset(const aabbox3d& initValue) - { - *this = initValue; + if (MinEdge.Y > MaxEdge.Y) { + t = MinEdge.Y; + MinEdge.Y = MaxEdge.Y; + MaxEdge.Y = t; } - - //! Resets the bounding box to a one-point box. - /** \param initValue New point. */ - void reset(const vector3d& initValue) - { - MaxEdge = initValue; - MinEdge = initValue; + if (MinEdge.Z > MaxEdge.Z) { + t = MinEdge.Z; + MinEdge.Z = MaxEdge.Z; + MaxEdge.Z = t; } + } - //! Adds a point to the bounding box - /** The box grows bigger, if point was outside of the box. - \param p: Point to add into the box. */ - void addInternalPoint(const vector3d& p) - { - addInternalPoint(p.X, p.Y, p.Z); - } + // Check if MaxEdge > MinEdge + bool isValid() const + { + if (MinEdge.X > MaxEdge.X) + return false; + if (MinEdge.Y > MaxEdge.Y) + return false; + if (MinEdge.Z > MaxEdge.Z) + return false; - //! Adds another bounding box - /** The box grows bigger, if the new box was outside of the box. - \param b: Other bounding box to add into this box. */ - void addInternalBox(const aabbox3d& b) - { - addInternalPoint(b.MaxEdge); - addInternalPoint(b.MinEdge); - } + return true; + } - //! Adds a point to the bounding box - /** The box grows bigger, if point is outside of the box. - \param x X coordinate of the point to add to this box. - \param y Y coordinate of the point to add to this box. - \param z Z coordinate of the point to add to this box. */ - void addInternalPoint(T x, T y, T z) - { - if (x>MaxEdge.X) MaxEdge.X = x; - if (y>MaxEdge.Y) MaxEdge.Y = y; - if (z>MaxEdge.Z) MaxEdge.Z = z; + //! Calculates a new interpolated bounding box. + /** d=0 returns other, d=1 returns this, all other values blend between + the two boxes. + \param other Other box to interpolate between + \param d Value between 0.0f and 1.0f. + \return Interpolated box. */ + aabbox3d getInterpolated(const aabbox3d &other, f32 d) const + { + f32 inv = 1.0f - d; + return aabbox3d((other.MinEdge * inv) + (MinEdge * d), + (other.MaxEdge * inv) + (MaxEdge * d)); + } - if (x getCenter() const - { - return (MinEdge + MaxEdge) / 2; - } - - //! Get extent of the box (maximal distance of two points in the box) - /** \return Extent of the bounding box. */ - vector3d getExtent() const - { - return MaxEdge - MinEdge; - } - - //! Get radius of the bounding sphere - /** \return Radius of the bounding sphere. */ - T getRadius() const - { - const T radius = getExtent().getLength() / 2; - return radius; - } - - //! Check if the box is empty. - /** This means that there is no space between the min and max edge. - \return True if box is empty, else false. */ - bool isEmpty() const - { - return MinEdge.equals ( MaxEdge ); - } - - //! Get the volume enclosed by the box in cubed units - T getVolume() const - { - const vector3d e = getExtent(); - return e.X * e.Y * e.Z; - } - - //! Get the surface area of the box in squared units - T getArea() const - { - const vector3d e = getExtent(); - return 2*(e.X*e.Y + e.X*e.Z + e.Y*e.Z); - } - - //! Stores all 8 edges of the box into an array - /** \param edges: Pointer to array of 8 edges. */ - void getEdges(vector3d *edges) const - { - const core::vector3d middle = getCenter(); - const core::vector3d diag = middle - MaxEdge; - - /* - Edges are stored in this way: - Hey, am I an ascii artist, or what? :) niko. - /3--------/7 - / | / | - / | / | - 1---------5 | - | /2- - -|- -6 - | / | / - |/ | / - 0---------4/ - */ - - edges[0].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z + diag.Z); - edges[1].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z + diag.Z); - edges[2].set(middle.X + diag.X, middle.Y + diag.Y, middle.Z - diag.Z); - edges[3].set(middle.X + diag.X, middle.Y - diag.Y, middle.Z - diag.Z); - edges[4].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z + diag.Z); - edges[5].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z + diag.Z); - edges[6].set(middle.X - diag.X, middle.Y + diag.Y, middle.Z - diag.Z); - edges[7].set(middle.X - diag.X, middle.Y - diag.Y, middle.Z - diag.Z); - } - - //! Repairs the box. - /** Necessary if for example MinEdge and MaxEdge are swapped. */ - void repair() - { - T t; - - if (MinEdge.X > MaxEdge.X) - { t=MinEdge.X; MinEdge.X = MaxEdge.X; MaxEdge.X=t; } - if (MinEdge.Y > MaxEdge.Y) - { t=MinEdge.Y; MinEdge.Y = MaxEdge.Y; MaxEdge.Y=t; } - if (MinEdge.Z > MaxEdge.Z) - { t=MinEdge.Z; MinEdge.Z = MaxEdge.Z; MaxEdge.Z=t; } - } - - // Check if MaxEdge > MinEdge - bool isValid() const - { - if (MinEdge.X > MaxEdge.X) return false; - if (MinEdge.Y > MaxEdge.Y) return false; - if (MinEdge.Z > MaxEdge.Z) return false; - - return true; - } - - //! Calculates a new interpolated bounding box. - /** d=0 returns other, d=1 returns this, all other values blend between - the two boxes. - \param other Other box to interpolate between - \param d Value between 0.0f and 1.0f. - \return Interpolated box. */ - aabbox3d getInterpolated(const aabbox3d& other, f32 d) const - { - f32 inv = 1.0f - d; - return aabbox3d((other.MinEdge*inv) + (MinEdge*d), - (other.MaxEdge*inv) + (MaxEdge*d)); - } - - //! Determines if a point is within this box. - /** Border is included (IS part of the box)! - \param p: Point to check. - \return True if the point is within the box and false if not */ - bool isPointInside(const vector3d& p) const - { - return (p.X >= MinEdge.X && p.X <= MaxEdge.X && + //! Determines if a point is within this box. + /** Border is included (IS part of the box)! + \param p: Point to check. + \return True if the point is within the box and false if not */ + bool isPointInside(const vector3d &p) const + { + return (p.X >= MinEdge.X && p.X <= MaxEdge.X && p.Y >= MinEdge.Y && p.Y <= MaxEdge.Y && p.Z >= MinEdge.Z && p.Z <= MaxEdge.Z); - } + } - //! Determines if a point is within this box and not its borders. - /** Border is excluded (NOT part of the box)! - \param p: Point to check. - \return True if the point is within the box and false if not. */ - bool isPointTotalInside(const vector3d& p) const - { - return (p.X > MinEdge.X && p.X < MaxEdge.X && + //! Determines if a point is within this box and not its borders. + /** Border is excluded (NOT part of the box)! + \param p: Point to check. + \return True if the point is within the box and false if not. */ + bool isPointTotalInside(const vector3d &p) const + { + return (p.X > MinEdge.X && p.X < MaxEdge.X && p.Y > MinEdge.Y && p.Y < MaxEdge.Y && p.Z > MinEdge.Z && p.Z < MaxEdge.Z); - } + } - //! Check if this box is completely inside the 'other' box. - /** \param other: Other box to check against. - \return True if this box is completely inside the other box, - otherwise false. */ - bool isFullInside(const aabbox3d& other) const - { - return (MinEdge.X >= other.MinEdge.X && MinEdge.Y >= other.MinEdge.Y && MinEdge.Z >= other.MinEdge.Z && + //! Check if this box is completely inside the 'other' box. + /** \param other: Other box to check against. + \return True if this box is completely inside the other box, + otherwise false. */ + bool isFullInside(const aabbox3d &other) const + { + return (MinEdge.X >= other.MinEdge.X && MinEdge.Y >= other.MinEdge.Y && MinEdge.Z >= other.MinEdge.Z && MaxEdge.X <= other.MaxEdge.X && MaxEdge.Y <= other.MaxEdge.Y && MaxEdge.Z <= other.MaxEdge.Z); - } + } - //! Returns the intersection of this box with another, if possible. - aabbox3d intersect(const aabbox3d& other) const - { - aabbox3d out; - - if (!intersectsWithBox(other)) - return out; - - out.MaxEdge.X = min_(MaxEdge.X, other.MaxEdge.X); - out.MaxEdge.Y = min_(MaxEdge.Y, other.MaxEdge.Y); - out.MaxEdge.Z = min_(MaxEdge.Z, other.MaxEdge.Z); - - out.MinEdge.X = max_(MinEdge.X, other.MinEdge.X); - out.MinEdge.Y = max_(MinEdge.Y, other.MinEdge.Y); - out.MinEdge.Z = max_(MinEdge.Z, other.MinEdge.Z); + //! Returns the intersection of this box with another, if possible. + aabbox3d intersect(const aabbox3d &other) const + { + aabbox3d out; + if (!intersectsWithBox(other)) return out; - } - //! Determines if the axis-aligned box intersects with another axis-aligned box. - /** \param other: Other box to check a intersection with. - \return True if there is an intersection with the other box, - otherwise false. */ - bool intersectsWithBox(const aabbox3d& other) const - { - return (MinEdge.X <= other.MaxEdge.X && MinEdge.Y <= other.MaxEdge.Y && MinEdge.Z <= other.MaxEdge.Z && + out.MaxEdge.X = min_(MaxEdge.X, other.MaxEdge.X); + out.MaxEdge.Y = min_(MaxEdge.Y, other.MaxEdge.Y); + out.MaxEdge.Z = min_(MaxEdge.Z, other.MaxEdge.Z); + + out.MinEdge.X = max_(MinEdge.X, other.MinEdge.X); + out.MinEdge.Y = max_(MinEdge.Y, other.MinEdge.Y); + out.MinEdge.Z = max_(MinEdge.Z, other.MinEdge.Z); + + return out; + } + + //! Determines if the axis-aligned box intersects with another axis-aligned box. + /** \param other: Other box to check a intersection with. + \return True if there is an intersection with the other box, + otherwise false. */ + bool intersectsWithBox(const aabbox3d &other) const + { + return (MinEdge.X <= other.MaxEdge.X && MinEdge.Y <= other.MaxEdge.Y && MinEdge.Z <= other.MaxEdge.Z && MaxEdge.X >= other.MinEdge.X && MaxEdge.Y >= other.MinEdge.Y && MaxEdge.Z >= other.MinEdge.Z); - } + } - //! Tests if the box intersects with a line - /** \param line: Line to test intersection with. - \return True if there is an intersection , else false. */ - bool intersectsWithLine(const line3d& line) const - { - return intersectsWithLine(line.getMiddle(), line.getVector().normalize(), - (T)(line.getLength() * 0.5)); - } + //! Tests if the box intersects with a line + /** \param line: Line to test intersection with. + \return True if there is an intersection , else false. */ + bool intersectsWithLine(const line3d &line) const + { + return intersectsWithLine(line.getMiddle(), line.getVector().normalize(), + (T)(line.getLength() * 0.5)); + } - //! Tests if the box intersects with a line - /** \param linemiddle Center of the line. - \param linevect Vector of the line. - \param halflength Half length of the line. - \return True if there is an intersection, else false. */ - bool intersectsWithLine(const vector3d& linemiddle, - const vector3d& linevect, T halflength) const - { - const vector3d e = getExtent() * (T)0.5; - const vector3d t = getCenter() - linemiddle; + //! Tests if the box intersects with a line + /** \param linemiddle Center of the line. + \param linevect Vector of the line. + \param halflength Half length of the line. + \return True if there is an intersection, else false. */ + bool intersectsWithLine(const vector3d &linemiddle, + const vector3d &linevect, T halflength) const + { + const vector3d e = getExtent() * (T)0.5; + const vector3d t = getCenter() - linemiddle; - if ((fabs(t.X) > e.X + halflength * fabs(linevect.X)) || + if ((fabs(t.X) > e.X + halflength * fabs(linevect.X)) || (fabs(t.Y) > e.Y + halflength * fabs(linevect.Y)) || - (fabs(t.Z) > e.Z + halflength * fabs(linevect.Z)) ) - return false; + (fabs(t.Z) > e.Z + halflength * fabs(linevect.Z))) + return false; - T r = e.Y * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.Y); - if (fabs(t.Y*linevect.Z - t.Z*linevect.Y) > r ) - return false; + T r = e.Y * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.Y); + if (fabs(t.Y * linevect.Z - t.Z * linevect.Y) > r) + return false; - r = e.X * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.X); - if (fabs(t.Z*linevect.X - t.X*linevect.Z) > r ) - return false; + r = e.X * (T)fabs(linevect.Z) + e.Z * (T)fabs(linevect.X); + if (fabs(t.Z * linevect.X - t.X * linevect.Z) > r) + return false; - r = e.X * (T)fabs(linevect.Y) + e.Y * (T)fabs(linevect.X); - if (fabs(t.X*linevect.Y - t.Y*linevect.X) > r) - return false; + r = e.X * (T)fabs(linevect.Y) + e.Y * (T)fabs(linevect.X); + if (fabs(t.X * linevect.Y - t.Y * linevect.X) > r) + return false; - return true; + return true; + } + + //! Classifies a relation with a plane. + /** \param plane Plane to classify relation to. + \return Returns ISREL3D_FRONT if the box is in front of the plane, + ISREL3D_BACK if the box is behind the plane, and + ISREL3D_CLIPPED if it is on both sides of the plane. */ + EIntersectionRelation3D classifyPlaneRelation(const plane3d &plane) const + { + vector3d nearPoint(MaxEdge); + vector3d farPoint(MinEdge); + + if (plane.Normal.X > (T)0) { + nearPoint.X = MinEdge.X; + farPoint.X = MaxEdge.X; } - //! Classifies a relation with a plane. - /** \param plane Plane to classify relation to. - \return Returns ISREL3D_FRONT if the box is in front of the plane, - ISREL3D_BACK if the box is behind the plane, and - ISREL3D_CLIPPED if it is on both sides of the plane. */ - EIntersectionRelation3D classifyPlaneRelation(const plane3d& plane) const - { - vector3d nearPoint(MaxEdge); - vector3d farPoint(MinEdge); - - if (plane.Normal.X > (T)0) - { - nearPoint.X = MinEdge.X; - farPoint.X = MaxEdge.X; - } - - if (plane.Normal.Y > (T)0) - { - nearPoint.Y = MinEdge.Y; - farPoint.Y = MaxEdge.Y; - } - - if (plane.Normal.Z > (T)0) - { - nearPoint.Z = MinEdge.Z; - farPoint.Z = MaxEdge.Z; - } - - if (plane.Normal.dotProduct(nearPoint) + plane.D > (T)0) - return ISREL3D_FRONT; - - if (plane.Normal.dotProduct(farPoint) + plane.D > (T)0) - return ISREL3D_CLIPPED; - - return ISREL3D_BACK; + if (plane.Normal.Y > (T)0) { + nearPoint.Y = MinEdge.Y; + farPoint.Y = MaxEdge.Y; } - //! The near edge - vector3d MinEdge; + if (plane.Normal.Z > (T)0) { + nearPoint.Z = MinEdge.Z; + farPoint.Z = MaxEdge.Z; + } - //! The far edge - vector3d MaxEdge; + if (plane.Normal.dotProduct(nearPoint) + plane.D > (T)0) + return ISREL3D_FRONT; + + if (plane.Normal.dotProduct(farPoint) + plane.D > (T)0) + return ISREL3D_CLIPPED; + + return ISREL3D_BACK; + } + + //! The near edge + vector3d MinEdge; + + //! The far edge + vector3d MaxEdge; }; - //! Typedef for a f32 3d bounding box. - typedef aabbox3d aabbox3df; - //! Typedef for an integer 3d bounding box. - typedef aabbox3d aabbox3di; +//! Typedef for a f32 3d bounding box. +typedef aabbox3d aabbox3df; +//! Typedef for an integer 3d bounding box. +typedef aabbox3d aabbox3di; } // end namespace core } // end namespace irr diff --git a/include/coreutil.h b/include/coreutil.h index ea519cfd..60014c4a 100644 --- a/include/coreutil.h +++ b/include/coreutil.h @@ -19,62 +19,61 @@ namespace core // ----------- some basic quite often used string functions ----------------- //! search if a filename has a proper extension -inline s32 isFileExtension (const io::path& filename, const io::path& ext0, - const io::path& ext1, const io::path& ext2) +inline s32 isFileExtension(const io::path &filename, const io::path &ext0, + const io::path &ext1, const io::path &ext2) { - s32 extPos = filename.findLast ( '.' ); - if ( extPos < 0 ) + s32 extPos = filename.findLast('.'); + if (extPos < 0) return 0; extPos += 1; - if ( filename.equals_substring_ignore_case ( ext0, extPos ) ) + if (filename.equals_substring_ignore_case(ext0, extPos)) return 1; - if ( filename.equals_substring_ignore_case ( ext1, extPos ) ) + if (filename.equals_substring_ignore_case(ext1, extPos)) return 2; - if ( filename.equals_substring_ignore_case ( ext2, extPos ) ) + if (filename.equals_substring_ignore_case(ext2, extPos)) return 3; return 0; } //! search if a filename has a proper extension -inline bool hasFileExtension(const io::path& filename, const io::path& ext0, - const io::path& ext1 = "", const io::path& ext2 = "") +inline bool hasFileExtension(const io::path &filename, const io::path &ext0, + const io::path &ext1 = "", const io::path &ext2 = "") { - return isFileExtension ( filename, ext0, ext1, ext2 ) > 0; + return isFileExtension(filename, ext0, ext1, ext2) > 0; } //! cut the filename extension from a source file path and store it in a dest file path -inline io::path& cutFilenameExtension ( io::path &dest, const io::path &source ) +inline io::path &cutFilenameExtension(io::path &dest, const io::path &source) { - s32 endPos = source.findLast ( '.' ); - dest = source.subString ( 0, endPos < 0 ? source.size () : endPos ); + s32 endPos = source.findLast('.'); + dest = source.subString(0, endPos < 0 ? source.size() : endPos); return dest; } //! get the filename extension from a file path -inline io::path& getFileNameExtension ( io::path &dest, const io::path &source ) +inline io::path &getFileNameExtension(io::path &dest, const io::path &source) { - s32 endPos = source.findLast ( '.' ); - if ( endPos < 0 ) + s32 endPos = source.findLast('.'); + if (endPos < 0) dest = ""; else - dest = source.subString ( endPos, source.size () ); + dest = source.subString(endPos, source.size()); return dest; } //! delete path from filename -inline io::path& deletePathFromFilename(io::path& filename) +inline io::path &deletePathFromFilename(io::path &filename) { // delete path from filename - const fschar_t* s = filename.c_str(); - const fschar_t* p = s + filename.size(); + const fschar_t *s = filename.c_str(); + const fschar_t *p = s + filename.size(); // search for path separator or beginning - while ( *p != '/' && *p != '\\' && p != s ) + while (*p != '/' && *p != '\\' && p != s) p--; - if ( p != s ) - { + if (p != s) { ++p; filename = p; } @@ -82,51 +81,45 @@ inline io::path& deletePathFromFilename(io::path& filename) } //! trim paths -inline io::path& deletePathFromPath(io::path& filename, s32 pathCount) +inline io::path &deletePathFromPath(io::path &filename, s32 pathCount) { // delete path from filename s32 i = filename.size(); // search for path separator or beginning - while ( i>=0 ) - { - if ( filename[i] == '/' || filename[i] == '\\' ) - { - if ( --pathCount <= 0 ) + while (i >= 0) { + if (filename[i] == '/' || filename[i] == '\\') { + if (--pathCount <= 0) break; } --i; } - if ( i>0 ) - { - filename [ i + 1 ] = 0; + if (i > 0) { + filename[i + 1] = 0; filename.validate(); - } - else - filename=""; + } else + filename = ""; return filename; } //! looks if file is in the same directory of path. returns offset of directory. //! 0 means in same directory. 1 means file is direct child of path -inline s32 isInSameDirectory ( const io::path& path, const io::path& file ) +inline s32 isInSameDirectory(const io::path &path, const io::path &file) { - if ( path.size() && !path.equalsn ( file, path.size() ) ) + if (path.size() && !path.equalsn(file, path.size())) return -1; s32 subA = 0; s32 subB = 0; s32 pos = 0; - while ( (pos = path.findNext ( '/', pos )) >= 0 ) - { + while ((pos = path.findNext('/', pos)) >= 0) { subA += 1; pos += 1; } pos = 0; - while ( (pos = file.findNext ( '/', pos )) >= 0 ) - { + while ((pos = file.findNext('/', pos)) >= 0) { subB += 1; pos += 1; } @@ -135,55 +128,47 @@ inline s32 isInSameDirectory ( const io::path& path, const io::path& file ) } //! splits a path into components -static inline void splitFilename(const io::path &name, io::path* path=0, - io::path* filename=0, io::path* extension=0, bool make_lower=false) +static inline void splitFilename(const io::path &name, io::path *path = 0, + io::path *filename = 0, io::path *extension = 0, bool make_lower = false) { s32 i = name.size(); s32 extpos = i; // search for path separator or beginning - while ( i >= 0 ) - { - if ( name[i] == '.' ) - { + while (i >= 0) { + if (name[i] == '.') { extpos = i; - if ( extension ) - *extension = name.subString ( extpos + 1, name.size() - (extpos + 1), make_lower ); - } - else - if ( name[i] == '/' || name[i] == '\\' ) - { - if ( filename ) - *filename = name.subString ( i + 1, extpos - (i + 1), make_lower ); - if ( path ) - { - *path = name.subString ( 0, i + 1, make_lower ); - path->replace ( '\\', '/' ); + if (extension) + *extension = name.subString(extpos + 1, name.size() - (extpos + 1), make_lower); + } else if (name[i] == '/' || name[i] == '\\') { + if (filename) + *filename = name.subString(i + 1, extpos - (i + 1), make_lower); + if (path) { + *path = name.subString(0, i + 1, make_lower); + path->replace('\\', '/'); } return; } i -= 1; } - if ( filename ) - *filename = name.subString ( 0, extpos, make_lower ); + if (filename) + *filename = name.subString(0, extpos, make_lower); } //! create a filename from components -static inline io::path mergeFilename(const io::path& path, const io::path& filename, const io::path& extension = "") +static inline io::path mergeFilename(const io::path &path, const io::path &filename, const io::path &extension = "") { io::path result(path); - if ( !result.empty() ) - { + if (!result.empty()) { fschar_t last = result.lastChar(); - if ( last != _IRR_TEXT('/') && last != _IRR_TEXT('\\') ) + if (last != _IRR_TEXT('/') && last != _IRR_TEXT('\\')) result += _IRR_TEXT('/'); } - if ( !filename.empty() ) + if (!filename.empty()) result += filename; - if ( !extension.empty() ) - { - if ( !result.empty() && extension[0] != _IRR_TEXT('.') ) + if (!extension.empty()) { + if (!result.empty() && extension[0] != _IRR_TEXT('.')) result += _IRR_TEXT('.'); result += extension; } @@ -191,13 +176,19 @@ static inline io::path mergeFilename(const io::path& path, const io::path& filen return result; } - //! some standard function ( to remove dependencies ) -inline bool isdigit(s32 c) { return c >= '0' && c <= '9'; } -inline bool isspace(s32 c) { return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; } -inline bool isupper(s32 c) { return c >= 'A' && c <= 'Z'; } - +inline bool isdigit(s32 c) +{ + return c >= '0' && c <= '9'; +} +inline bool isspace(s32 c) +{ + return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; +} +inline bool isupper(s32 c) +{ + return c >= 'A' && c <= 'Z'; +} } // end namespace core } // end namespace irr - diff --git a/include/dimension2d.h b/include/dimension2d.h index fceb39a1..ab6c81c3 100644 --- a/include/dimension2d.h +++ b/include/dimension2d.h @@ -11,212 +11,206 @@ namespace irr { namespace core { - template - class vector2d; +template +class vector2d; - //! Specifies a 2 dimensional size. - template - class dimension2d +//! Specifies a 2 dimensional size. +template +class dimension2d +{ +public: + //! Default constructor for empty dimension + constexpr dimension2d() : + Width(0), Height(0) {} + //! Constructor with width and height + constexpr dimension2d(const T &width, const T &height) : + Width(width), Height(height) {} + + dimension2d(const vector2d &other); // Defined in vector2d.h + + //! Use this constructor only where you are sure that the conversion is valid. + template + explicit constexpr dimension2d(const dimension2d &other) : + Width((T)other.Width), Height((T)other.Height) { - public: - //! Default constructor for empty dimension - constexpr dimension2d() : Width(0), Height(0) {} - //! Constructor with width and height - constexpr dimension2d(const T& width, const T& height) - : Width(width), Height(height) {} + } - dimension2d(const vector2d& other); // Defined in vector2d.h + template + dimension2d &operator=(const dimension2d &other) + { + Width = (T)other.Width; + Height = (T)other.Height; + return *this; + } - //! Use this constructor only where you are sure that the conversion is valid. - template - explicit constexpr dimension2d(const dimension2d& other) : - Width((T)other.Width), Height((T)other.Height) { } + //! Equality operator + bool operator==(const dimension2d &other) const + { + return core::equals(Width, other.Width) && + core::equals(Height, other.Height); + } - template - dimension2d& operator=(const dimension2d& other) - { - Width = (T) other.Width; - Height = (T) other.Height; - return *this; - } + //! Inequality operator + bool operator!=(const dimension2d &other) const + { + return !(*this == other); + } + bool operator==(const vector2d &other) const; // Defined in vector2d.h - //! Equality operator - bool operator==(const dimension2d& other) const - { - return core::equals(Width, other.Width) && - core::equals(Height, other.Height); - } + bool operator!=(const vector2d &other) const + { + return !(*this == other); + } - //! Inequality operator - bool operator!=(const dimension2d& other) const - { - return ! (*this == other); - } + //! Set to new values + dimension2d &set(const T &width, const T &height) + { + Width = width; + Height = height; + return *this; + } - bool operator==(const vector2d& other) const; // Defined in vector2d.h + //! Divide width and height by scalar + dimension2d &operator/=(const T &scale) + { + Width /= scale; + Height /= scale; + return *this; + } - bool operator!=(const vector2d& other) const - { - return !(*this == other); - } + //! Divide width and height by scalar + dimension2d operator/(const T &scale) const + { + return dimension2d(Width / scale, Height / scale); + } - //! Set to new values - dimension2d& set(const T& width, const T& height) - { - Width = width; - Height = height; - return *this; - } + //! Multiply width and height by scalar + dimension2d &operator*=(const T &scale) + { + Width *= scale; + Height *= scale; + return *this; + } - //! Divide width and height by scalar - dimension2d& operator/=(const T& scale) - { - Width /= scale; - Height /= scale; - return *this; - } + //! Multiply width and height by scalar + dimension2d operator*(const T &scale) const + { + return dimension2d(Width * scale, Height * scale); + } - //! Divide width and height by scalar - dimension2d operator/(const T& scale) const - { - return dimension2d(Width/scale, Height/scale); - } + //! Add another dimension to this one. + dimension2d &operator+=(const dimension2d &other) + { + Width += other.Width; + Height += other.Height; + return *this; + } - //! Multiply width and height by scalar - dimension2d& operator*=(const T& scale) - { - Width *= scale; - Height *= scale; - return *this; - } + //! Add two dimensions + dimension2d operator+(const dimension2d &other) const + { + return dimension2d(Width + other.Width, Height + other.Height); + } - //! Multiply width and height by scalar - dimension2d operator*(const T& scale) const - { - return dimension2d(Width*scale, Height*scale); - } + //! Subtract a dimension from this one + dimension2d &operator-=(const dimension2d &other) + { + Width -= other.Width; + Height -= other.Height; + return *this; + } - //! Add another dimension to this one. - dimension2d& operator+=(const dimension2d& other) - { - Width += other.Width; - Height += other.Height; - return *this; - } + //! Subtract one dimension from another + dimension2d operator-(const dimension2d &other) const + { + return dimension2d(Width - other.Width, Height - other.Height); + } - //! Add two dimensions - dimension2d operator+(const dimension2d& other) const - { - return dimension2d(Width+other.Width, Height+other.Height); - } + //! Get area + T getArea() const + { + return Width * Height; + } - //! Subtract a dimension from this one - dimension2d& operator-=(const dimension2d& other) - { - Width -= other.Width; - Height -= other.Height; - return *this; - } + //! Get the optimal size according to some properties + /** This is a function often used for texture dimension + calculations. The function returns the next larger or + smaller dimension which is a power-of-two dimension + (2^n,2^m) and/or square (Width=Height). + \param requirePowerOfTwo Forces the result to use only + powers of two as values. + \param requireSquare Makes width==height in the result + \param larger Choose whether the result is larger or + smaller than the current dimension. If one dimension + need not be changed it is kept with any value of larger. + \param maxValue Maximum texturesize. if value > 0 size is + clamped to maxValue + \return The optimal dimension under the given + constraints. */ + dimension2d getOptimalSize( + bool requirePowerOfTwo = true, + bool requireSquare = false, + bool larger = true, + u32 maxValue = 0) const + { + u32 i = 1; + u32 j = 1; + if (requirePowerOfTwo) { + while (i < (u32)Width) + i <<= 1; + if (!larger && i != 1 && i != (u32)Width) + i >>= 1; + while (j < (u32)Height) + j <<= 1; + if (!larger && j != 1 && j != (u32)Height) + j >>= 1; + } else { + i = (u32)Width; + j = (u32)Height; + } - //! Subtract one dimension from another - dimension2d operator-(const dimension2d& other) const - { - return dimension2d(Width-other.Width, Height-other.Height); - } + if (requireSquare) { + if ((larger && (i > j)) || (!larger && (i < j))) + j = i; + else + i = j; + } - //! Get area - T getArea() const - { - return Width*Height; - } + if (maxValue > 0 && i > maxValue) + i = maxValue; - //! Get the optimal size according to some properties - /** This is a function often used for texture dimension - calculations. The function returns the next larger or - smaller dimension which is a power-of-two dimension - (2^n,2^m) and/or square (Width=Height). - \param requirePowerOfTwo Forces the result to use only - powers of two as values. - \param requireSquare Makes width==height in the result - \param larger Choose whether the result is larger or - smaller than the current dimension. If one dimension - need not be changed it is kept with any value of larger. - \param maxValue Maximum texturesize. if value > 0 size is - clamped to maxValue - \return The optimal dimension under the given - constraints. */ - dimension2d getOptimalSize( - bool requirePowerOfTwo=true, - bool requireSquare=false, - bool larger=true, - u32 maxValue = 0) const - { - u32 i=1; - u32 j=1; - if (requirePowerOfTwo) - { - while (i<(u32)Width) - i<<=1; - if (!larger && i!=1 && i!=(u32)Width) - i>>=1; - while (j<(u32)Height) - j<<=1; - if (!larger && j!=1 && j!=(u32)Height) - j>>=1; - } - else - { - i=(u32)Width; - j=(u32)Height; - } + if (maxValue > 0 && j > maxValue) + j = maxValue; - if (requireSquare) - { - if ((larger && (i>j)) || (!larger && (i((T)i, (T)j); + } - if ( maxValue > 0 && i > maxValue) - i = maxValue; + //! Get the interpolated dimension + /** \param other Other dimension to interpolate with. + \param d Value between 0.0f and 1.0f. d=0 returns other, d=1 returns this, values between interpolate. + \return Interpolated dimension. */ + dimension2d getInterpolated(const dimension2d &other, f32 d) const + { + f32 inv = (1.0f - d); + return dimension2d((T)(other.Width * inv + Width * d), (T)(other.Height * inv + Height * d)); + } - if ( maxValue > 0 && j > maxValue) - j = maxValue; + //! Width of the dimension. + T Width; + //! Height of the dimension. + T Height; +}; - return dimension2d((T)i,(T)j); - } - - //! Get the interpolated dimension - /** \param other Other dimension to interpolate with. - \param d Value between 0.0f and 1.0f. d=0 returns other, d=1 returns this, values between interpolate. - \return Interpolated dimension. */ - dimension2d getInterpolated(const dimension2d& other, f32 d) const - { - f32 inv = (1.0f - d); - return dimension2d( (T)(other.Width*inv + Width*d), (T)(other.Height*inv + Height*d)); - } - - - //! Width of the dimension. - T Width; - //! Height of the dimension. - T Height; - }; - - //! Typedef for an f32 dimension. - typedef dimension2d dimension2df; - //! Typedef for an unsigned integer dimension. - typedef dimension2d dimension2du; - - //! Typedef for an integer dimension. - /** There are few cases where negative dimensions make sense. Please consider using - dimension2du instead. */ - typedef dimension2d dimension2di; +//! Typedef for an f32 dimension. +typedef dimension2d dimension2df; +//! Typedef for an unsigned integer dimension. +typedef dimension2d dimension2du; +//! Typedef for an integer dimension. +/** There are few cases where negative dimensions make sense. Please consider using + dimension2du instead. */ +typedef dimension2d dimension2di; } // end namespace core } // end namespace irr - - diff --git a/include/fast_atof.h b/include/fast_atof.h index 85fcd77a..8bbd0e9f 100644 --- a/include/fast_atof.h +++ b/include/fast_atof.h @@ -15,51 +15,47 @@ namespace core #define IRR_ATOF_TABLE_SIZE 17 // we write [IRR_ATOF_TABLE_SIZE] here instead of [] to work around a swig bug const float fast_atof_table[17] = { - 0.f, - 0.1f, - 0.01f, - 0.001f, - 0.0001f, - 0.00001f, - 0.000001f, - 0.0000001f, - 0.00000001f, - 0.000000001f, - 0.0000000001f, - 0.00000000001f, - 0.000000000001f, - 0.0000000000001f, - 0.00000000000001f, - 0.000000000000001f, - 0.0000000000000001f -}; + 0.f, + 0.1f, + 0.01f, + 0.001f, + 0.0001f, + 0.00001f, + 0.000001f, + 0.0000001f, + 0.00000001f, + 0.000000001f, + 0.0000000001f, + 0.00000000001f, + 0.000000000001f, + 0.0000000000001f, + 0.00000000000001f, + 0.000000000000001f, + 0.0000000000000001f}; //! Convert a simple string of base 10 digits into an unsigned 32 bit integer. /** \param[in] in: The string of digits to convert. No leading chars are - allowed, only digits 0 to 9. Parsing stops at the first non-digit. - \param[out] out: (optional) If provided, it will be set to point at the - first character not used in the calculation. - \return The unsigned integer value of the digits. If the string specifies - too many digits to encode in an u32 then INT_MAX will be returned. + allowed, only digits 0 to 9. Parsing stops at the first non-digit. + \param[out] out: (optional) If provided, it will be set to point at the + first character not used in the calculation. + \return The unsigned integer value of the digits. If the string specifies + too many digits to encode in an u32 then INT_MAX will be returned. */ -inline u32 strtoul10(const char* in, const char** out=0) +inline u32 strtoul10(const char *in, const char **out = 0) { - if (!in) - { + if (!in) { if (out) *out = in; return 0; } - bool overflow=false; + bool overflow = false; u32 unsignedValue = 0; - while ( ( *in >= '0') && ( *in <= '9' )) - { - const u32 tmp = ( unsignedValue * 10 ) + ( *in - '0' ); - if (tmp= '0') && (*in <= '9')) { + const u32 tmp = (unsignedValue * 10) + (*in - '0'); + if (tmp < unsignedValue) { + unsignedValue = (u32)0xffffffff; + overflow = true; } if (!overflow) unsignedValue = tmp; @@ -74,18 +70,17 @@ inline u32 strtoul10(const char* in, const char** out=0) //! Convert a simple string of base 10 digits into a signed 32 bit integer. /** \param[in] in: The string of digits to convert. Only a leading - or + - followed by digits 0 to 9 will be considered. Parsing stops at the first - non-digit. - \param[out] out: (optional) If provided, it will be set to point at the - first character not used in the calculation. - \return The signed integer value of the digits. If the string specifies - too many digits to encode in an s32 then +INT_MAX or -INT_MAX will be - returned. + followed by digits 0 to 9 will be considered. Parsing stops at the first + non-digit. + \param[out] out: (optional) If provided, it will be set to point at the + first character not used in the calculation. + \return The signed integer value of the digits. If the string specifies + too many digits to encode in an s32 then +INT_MAX or -INT_MAX will be + returned. */ -inline s32 strtol10(const char* in, const char** out=0) +inline s32 strtol10(const char *in, const char **out = 0) { - if (!in) - { + if (!in) { if (out) *out = in; return 0; @@ -95,16 +90,13 @@ inline s32 strtol10(const char* in, const char** out=0) if (negative || ('+' == *in)) ++in; - const u32 unsignedValue = strtoul10(in,out); - if (unsignedValue > (u32)INT_MAX) - { + const u32 unsignedValue = strtoul10(in, out); + if (unsignedValue > (u32)INT_MAX) { if (negative) return (s32)INT_MIN; else return (s32)INT_MAX; - } - else - { + } else { if (negative) return -((s32)unsignedValue); else @@ -114,9 +106,9 @@ inline s32 strtol10(const char* in, const char** out=0) //! Convert a hex-encoded character to an unsigned integer. /** \param[in] in The digit to convert. Only digits 0 to 9 and chars A-F,a-f - will be considered. - \return The unsigned integer value of the digit. 0xffffffff if the input is - not hex + will be considered. + \return The unsigned integer value of the digit. 0xffffffff if the input is + not hex */ inline u32 ctoul16(char in) { @@ -132,26 +124,24 @@ inline u32 ctoul16(char in) //! Convert a simple string of base 16 digits into an unsigned 32 bit integer. /** \param[in] in: The string of digits to convert. No leading chars are - allowed, only digits 0 to 9 and chars A-F,a-f are allowed. Parsing stops - at the first illegal char. - \param[out] out: (optional) If provided, it will be set to point at the - first character not used in the calculation. - \return The unsigned integer value of the digits. If the string specifies - too many digits to encode in an u32 then INT_MAX will be returned. + allowed, only digits 0 to 9 and chars A-F,a-f are allowed. Parsing stops + at the first illegal char. + \param[out] out: (optional) If provided, it will be set to point at the + first character not used in the calculation. + \return The unsigned integer value of the digits. If the string specifies + too many digits to encode in an u32 then INT_MAX will be returned. */ -inline u32 strtoul16(const char* in, const char** out=0) +inline u32 strtoul16(const char *in, const char **out = 0) { - if (!in) - { + if (!in) { if (out) *out = in; return 0; } - bool overflow=false; + bool overflow = false; u32 unsignedValue = 0; - while (true) - { + while (true) { u32 tmp = 0; if ((*in >= '0') && (*in <= '9')) tmp = (unsignedValue << 4u) + (*in - '0'); @@ -161,10 +151,9 @@ inline u32 strtoul16(const char* in, const char** out=0) tmp = (unsignedValue << 4u) + (*in - 'a') + 10; else break; - if (tmp= '0') && (*in <= '7')) tmp = (unsignedValue << 3u) + (*in - '0'); else break; - if (tmp= '0') && ( *in <= '9' ) ) - { + while ((*in >= '0') && (*in <= '9')) { // If it looks like we're going to overflow, bail out // now and start using floating point. if (intValue >= MAX_SAFE_U32_VALUE) @@ -280,8 +263,7 @@ inline f32 strtof10(const char* in, const char** out = 0) // If there are any digits left to parse, then we need to use // floating point arithmetic from here. - while ( ( *in >= '0') && ( *in <= '9' ) ) - { + while ((*in >= '0') && (*in <= '9')) { floatValue = (floatValue * 10.f) + (f32)(*in - '0'); ++in; if (floatValue > FLT_MAX) // Just give up. @@ -296,13 +278,13 @@ inline f32 strtof10(const char* in, const char** out = 0) //! Provides a fast function for converting a string into a float. /** This is not guaranteed to be as accurate as atof(), but is - approximately 6 to 8 times as fast. - \param[in] in The string to convert. - \param[out] result The resultant float will be written here. - \return Pointer to the first character in the string that wasn't used - to create the float value. + approximately 6 to 8 times as fast. + \param[in] in The string to convert. + \param[out] result The resultant float will be written here. + \return Pointer to the first character in the string that wasn't used + to create the float value. */ -inline const char* fast_atof_move(const char* in, f32& result) +inline const char *fast_atof_move(const char *in, f32 &result) { // Please run the regression test when making any modifications to this function. @@ -311,29 +293,24 @@ inline const char* fast_atof_move(const char* in, f32& result) return 0; const bool negative = ('-' == *in); - if (negative || ('+'==*in)) + if (negative || ('+' == *in)) ++in; f32 value = strtof10(in, &in); - if ( *in == '.' ) - { - const char* afterDecimal = ++in; + if (*in == '.') { + const char *afterDecimal = ++in; const f32 decimal = strtof10(in, &afterDecimal); const size_t numDecimals = afterDecimal - in; - if (numDecimals < IRR_ATOF_TABLE_SIZE) - { + if (numDecimals < IRR_ATOF_TABLE_SIZE) { value += decimal * fast_atof_table[numDecimals]; - } - else - { + } else { value += decimal * (f32)pow(10.f, -(float)numDecimals); } in = afterDecimal; } - if ('e' == *in || 'E' == *in) - { + if ('e' == *in || 'E' == *in) { ++in; // Assume that the exponent is a whole number. // strtol10() will deal with both + and - signs, @@ -342,21 +319,21 @@ inline const char* fast_atof_move(const char* in, f32& result) value *= (f32)pow(10.f, (f32)strtol10(in, &in)); } - result = negative?-value:value; + result = negative ? -value : value; return in; } //! Convert a string to a floating point number /** \param floatAsString The string to convert. - \param out Optional pointer to the first character in the string that - wasn't used to create the float value. - \result Float value parsed from the input string + \param out Optional pointer to the first character in the string that + wasn't used to create the float value. + \result Float value parsed from the input string */ -inline float fast_atof(const char* floatAsString, const char** out=0) +inline float fast_atof(const char *floatAsString, const char **out = 0) { float ret; if (out) - *out=fast_atof_move(floatAsString, ret); + *out = fast_atof_move(floatAsString, ret); else fast_atof_move(floatAsString, ret); return ret; diff --git a/include/irrArray.h b/include/irrArray.h index 5c1c75cf..b6f573a7 100644 --- a/include/irrArray.h +++ b/include/irrArray.h @@ -17,28 +17,33 @@ namespace core //! Self reallocating template array (like stl vector) with additional features. /** Some features are: Heap sorting, binary search methods, easier debugging. -*/ + */ template class array { public: static_assert(!std::is_same::value, - "irr::core::array with T = bool not supported. Use std::vector instead."); + "irr::core::array with T = bool not supported. Use std::vector instead."); //! Default constructor for empty array. - array() : m_data(), is_sorted(true) - { } + array() : + m_data(), is_sorted(true) + { + } //! Constructs an array and allocates an initial chunk of memory. /** \param start_count Amount of elements to pre-allocate. */ - explicit array(u32 start_count) : m_data(), is_sorted(true) + explicit array(u32 start_count) : + m_data(), is_sorted(true) { m_data.reserve(start_count); } //! Copy constructor - array(const array& other) : m_data(other.m_data), is_sorted(other.is_sorted) - { } + array(const array &other) : + m_data(other.m_data), is_sorted(other.is_sorted) + { + } //! Reallocates the array, make it bigger or smaller. /** \param new_size New size of array. @@ -46,7 +51,7 @@ public: enough space is available. Setting this flag to false can speed up array usage, but may use more memory than required by the data. */ - void reallocate(u32 new_size, bool canShrink=true) + void reallocate(u32 new_size, bool canShrink = true) { size_t allocated = m_data.capacity(); if (new_size < allocated) { @@ -60,42 +65,40 @@ public: //! Adds an element at back of array. /** If the array is too small to add this new element it is made bigger. \param element: Element to add at the back of the array. */ - void push_back(const T& element) + void push_back(const T &element) { m_data.push_back(element); is_sorted = false; } - void push_back(T&& element) + void push_back(T &&element) { m_data.push_back(std::move(element)); is_sorted = false; } - //! Adds an element at the front of the array. /** If the array is to small to add this new element, the array is made bigger. Please note that this is slow, because the whole array needs to be copied for this. \param element Element to add at the back of the array. */ - void push_front(const T& element) + void push_front(const T &element) { m_data.insert(m_data.begin(), element); is_sorted = false; } - void push_front(T&& element) + void push_front(T &&element) { m_data.insert(m_data.begin(), std::move(element)); is_sorted = false; } - //! Insert item into array at specified position. /** \param element: Element to be inserted \param index: Where position to insert the new element. */ - void insert(const T& element, u32 index=0) + void insert(const T &element, u32 index = 0) { _IRR_DEBUG_BREAK_IF(index > m_data.size()) // access violation auto pos = std::next(m_data.begin(), index); @@ -119,7 +122,7 @@ public: May reduce memory usage, but call is more whenever size changes. \param newDataIsSorted Info if you pass sorted/unsorted data */ - void set_data(const T* newData, u32 newSize, bool newDataIsSorted=false, bool canShrink=false) + void set_data(const T *newData, u32 newSize, bool newDataIsSorted = false, bool canShrink = false) { m_data.resize(newSize); if (canShrink) { @@ -133,7 +136,7 @@ public: /** Like operator ==, but without the need to create the array \param otherData Address to data against which we compare, must contain size elements \param size Amount of elements in otherData */ - bool equals(const T* otherData, u32 size) const + bool equals(const T *otherData, u32 size) const { if (m_data.size() != size) return false; @@ -148,7 +151,7 @@ public: } //! Assignment operator - const array& operator=(const array& other) + const array &operator=(const array &other) { if (this == &other) return *this; @@ -157,14 +160,14 @@ public: return *this; } - array& operator=(const std::vector &other) + array &operator=(const std::vector &other) { m_data = other; is_sorted = false; return *this; } - array& operator=(std::vector &&other) + array &operator=(std::vector &&other) { m_data = std::move(other); is_sorted = false; @@ -172,71 +175,63 @@ public: } //! Equality operator - bool operator == (const array& other) const + bool operator==(const array &other) const { return equals(other.const_pointer(), other.size()); } - //! Inequality operator - bool operator != (const array& other) const + bool operator!=(const array &other) const { - return !(*this==other); + return !(*this == other); } - //! Direct access operator - T& operator [](u32 index) + T &operator[](u32 index) { _IRR_DEBUG_BREAK_IF(index >= m_data.size()) // access violation return m_data[index]; } - //! Direct const access operator - const T& operator [](u32 index) const + const T &operator[](u32 index) const { _IRR_DEBUG_BREAK_IF(index >= m_data.size()) // access violation return m_data[index]; } - //! Gets last element. - T& getLast() + T &getLast() { _IRR_DEBUG_BREAK_IF(m_data.empty()) // access violation return m_data.back(); } - //! Gets last element - const T& getLast() const + const T &getLast() const { _IRR_DEBUG_BREAK_IF(m_data.empty()) // access violation return m_data.back(); } - //! Gets a pointer to the array. /** \return Pointer to the array. */ - T* pointer() + T *pointer() { return m_data.empty() ? nullptr : &m_data[0]; } - //! Gets a const pointer to the array. /** \return Pointer to the array. */ - const T* const_pointer() const + const T *const_pointer() const { return m_data.empty() ? nullptr : &m_data[0]; } - //! Get number of occupied elements of the array. /** \return Size of elements in the array which are actually occupied. */ u32 size() const @@ -244,7 +239,6 @@ public: return static_cast(m_data.size()); } - //! Get amount of memory allocated. /** \return Amount of memory allocated. The amount of bytes allocated would be allocated_size() * sizeof(ElementTypeUsed); */ @@ -253,7 +247,6 @@ public: return m_data.capacity(); } - //! Check if array is empty. /** \return True if the array is empty false if not. */ bool empty() const @@ -261,7 +254,6 @@ public: return m_data.empty(); } - //! Sorts the array using heapsort. /** There is no additional memory waste and the algorithm performs O(n*log n) in worst case. */ @@ -273,7 +265,6 @@ public: } } - //! Performs a binary search for an element, returns -1 if not found. /** The array will be sorted before the binary search if it is not already sorted. Caution is advised! Be careful not to call this on @@ -281,7 +272,7 @@ public: \param element Element to search for. \return Position of the searched element if it was found, otherwise -1 is returned. */ - s32 binary_search(const T& element) + s32 binary_search(const T &element) { sort(); return binary_search(element, 0, (s32)m_data.size() - 1); @@ -293,7 +284,7 @@ public: \param element Element to search for. \return Position of the searched element if it was found, otherwise -1 is returned. */ - s32 binary_search(const T& element) const + s32 binary_search(const T &element) const { if (is_sorted) return binary_search(element, 0, (s32)m_data.size() - 1); @@ -307,7 +298,7 @@ public: \param right Last right index. \return Position of the searched element if it was found, otherwise -1 is returned. */ - s32 binary_search(const T& element, s32 left, s32 right) const + s32 binary_search(const T &element, s32 left, s32 right) const { if (left > right) return -1; @@ -320,7 +311,6 @@ public: return static_cast(it - m_data.begin()); } - //! Performs a binary search for an element, returns -1 if not found. //! it is used for searching a multiset /** The array will be sorted before the binary search if it is not @@ -329,7 +319,7 @@ public: \param &last return lastIndex of equal elements \return Position of the first searched element if it was found, otherwise -1 is returned. */ - s32 binary_search_multi(const T& element, s32 &last) + s32 binary_search_multi(const T &element, s32 &last) { sort(); auto iters = std::equal_range(m_data.begin(), m_data.end(), element); @@ -339,14 +329,13 @@ public: return static_cast(iters.first - m_data.begin()); } - //! Finds an element in linear time, which is very slow. /** Use binary_search for faster finding. Only works if ==operator is implemented. \param element Element to search for. \return Position of the searched element if it was found, otherwise -1 is returned. */ - s32 linear_search(const T& element) const + s32 linear_search(const T &element) const { auto it = std::find(m_data.begin(), m_data.end(), element); if (it == m_data.end()) @@ -354,14 +343,13 @@ public: return static_cast(it - m_data.begin()); } - //! Finds an element in linear time, which is very slow. /** Use binary_search for faster finding. Only works if ==operator is implemented. \param element: Element to search for. \return Position of the searched element if it was found, otherwise -1 is returned. */ - s32 linear_reverse_search(const T& element) const + s32 linear_reverse_search(const T &element) const { auto it = std::find(m_data.rbegin(), m_data.rend(), element); if (it == m_data.rend()) @@ -370,7 +358,6 @@ public: return m_data.size() - offset - 1; } - //! Erases an element from the array. /** May be slow, because all elements following after the erased element have to be copied. @@ -382,7 +369,6 @@ public: m_data.erase(it); } - //! Erases some elements from the array. /** May be slow, because all elements following after the erased element have to be copied. @@ -404,12 +390,11 @@ public: is_sorted = _is_sorted; } - //! Swap the content of this array container with the content of another array /** Afterward this object will contain the content of the other object and the other object will contain the content of this object. \param other Swap content with this object */ - void swap(array& other) + void swap(array &other) { m_data.swap(other.m_data); std::swap(is_sorted, other.is_sorted); @@ -435,5 +420,3 @@ private: } // end namespace core } // end namespace irr - - diff --git a/include/irrMath.h b/include/irrMath.h index 553a4c89..3a1471a0 100644 --- a/include/irrMath.h +++ b/include/irrMath.h @@ -16,445 +16,462 @@ namespace irr namespace core { - //! Rounding error constant often used when comparing f32 values. +//! Rounding error constant often used when comparing f32 values. - const f32 ROUNDING_ERROR_f32 = 0.000001f; - const f64 ROUNDING_ERROR_f64 = 0.00000001; +const f32 ROUNDING_ERROR_f32 = 0.000001f; +const f64 ROUNDING_ERROR_f64 = 0.00000001; #ifdef PI // make sure we don't collide with a define #undef PI #endif - //! Constant for PI. - const f32 PI = 3.14159265359f; +//! Constant for PI. +const f32 PI = 3.14159265359f; - //! Constant for reciprocal of PI. - const f32 RECIPROCAL_PI = 1.0f/PI; +//! Constant for reciprocal of PI. +const f32 RECIPROCAL_PI = 1.0f / PI; - //! Constant for half of PI. - const f32 HALF_PI = PI/2.0f; +//! Constant for half of PI. +const f32 HALF_PI = PI / 2.0f; #ifdef PI64 // make sure we don't collide with a define #undef PI64 #endif - //! Constant for 64bit PI. - const f64 PI64 = 3.1415926535897932384626433832795028841971693993751; +//! Constant for 64bit PI. +const f64 PI64 = 3.1415926535897932384626433832795028841971693993751; - //! Constant for 64bit reciprocal of PI. - const f64 RECIPROCAL_PI64 = 1.0/PI64; +//! Constant for 64bit reciprocal of PI. +const f64 RECIPROCAL_PI64 = 1.0 / PI64; - //! 32bit Constant for converting from degrees to radians - const f32 DEGTORAD = PI / 180.0f; +//! 32bit Constant for converting from degrees to radians +const f32 DEGTORAD = PI / 180.0f; - //! 32bit constant for converting from radians to degrees (formally known as GRAD_PI) - const f32 RADTODEG = 180.0f / PI; +//! 32bit constant for converting from radians to degrees (formally known as GRAD_PI) +const f32 RADTODEG = 180.0f / PI; - //! 64bit constant for converting from degrees to radians (formally known as GRAD_PI2) - const f64 DEGTORAD64 = PI64 / 180.0; +//! 64bit constant for converting from degrees to radians (formally known as GRAD_PI2) +const f64 DEGTORAD64 = PI64 / 180.0; - //! 64bit constant for converting from radians to degrees - const f64 RADTODEG64 = 180.0 / PI64; +//! 64bit constant for converting from radians to degrees +const f64 RADTODEG64 = 180.0 / PI64; - //! Utility function to convert a radian value to degrees - /** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X - \param radians The radians value to convert to degrees. - */ - inline f32 radToDeg(f32 radians) - { - return RADTODEG * radians; - } +//! Utility function to convert a radian value to degrees +/** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X +\param radians The radians value to convert to degrees. +*/ +inline f32 radToDeg(f32 radians) +{ + return RADTODEG * radians; +} - //! Utility function to convert a radian value to degrees - /** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X - \param radians The radians value to convert to degrees. - */ - inline f64 radToDeg(f64 radians) - { - return RADTODEG64 * radians; - } +//! Utility function to convert a radian value to degrees +/** Provided as it can be clearer to write radToDeg(X) than RADTODEG * X +\param radians The radians value to convert to degrees. +*/ +inline f64 radToDeg(f64 radians) +{ + return RADTODEG64 * radians; +} - //! Utility function to convert a degrees value to radians - /** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X - \param degrees The degrees value to convert to radians. - */ - inline f32 degToRad(f32 degrees) - { - return DEGTORAD * degrees; - } +//! Utility function to convert a degrees value to radians +/** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X +\param degrees The degrees value to convert to radians. +*/ +inline f32 degToRad(f32 degrees) +{ + return DEGTORAD * degrees; +} - //! Utility function to convert a degrees value to radians - /** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X - \param degrees The degrees value to convert to radians. - */ - inline f64 degToRad(f64 degrees) - { - return DEGTORAD64 * degrees; - } +//! Utility function to convert a degrees value to radians +/** Provided as it can be clearer to write degToRad(X) than DEGTORAD * X +\param degrees The degrees value to convert to radians. +*/ +inline f64 degToRad(f64 degrees) +{ + return DEGTORAD64 * degrees; +} - //! returns minimum of two values. Own implementation to get rid of the STL (VS6 problems) - template - inline const T& min_(const T& a, const T& b) - { - return a < b ? a : b; - } +//! returns minimum of two values. Own implementation to get rid of the STL (VS6 problems) +template +inline const T &min_(const T &a, const T &b) +{ + return a < b ? a : b; +} - //! returns minimum of three values. Own implementation to get rid of the STL (VS6 problems) - template - inline const T& min_(const T& a, const T& b, const T& c) - { - return a < b ? min_(a, c) : min_(b, c); - } +//! returns minimum of three values. Own implementation to get rid of the STL (VS6 problems) +template +inline const T &min_(const T &a, const T &b, const T &c) +{ + return a < b ? min_(a, c) : min_(b, c); +} - //! returns maximum of two values. Own implementation to get rid of the STL (VS6 problems) - template - inline const T& max_(const T& a, const T& b) - { - return a < b ? b : a; - } +//! returns maximum of two values. Own implementation to get rid of the STL (VS6 problems) +template +inline const T &max_(const T &a, const T &b) +{ + return a < b ? b : a; +} - //! returns maximum of three values. Own implementation to get rid of the STL (VS6 problems) - template - inline const T& max_(const T& a, const T& b, const T& c) - { - return a < b ? max_(b, c) : max_(a, c); - } +//! returns maximum of three values. Own implementation to get rid of the STL (VS6 problems) +template +inline const T &max_(const T &a, const T &b, const T &c) +{ + return a < b ? max_(b, c) : max_(a, c); +} - //! returns abs of two values. Own implementation to get rid of STL (VS6 problems) - template - inline T abs_(const T& a) - { - return a < (T)0 ? -a : a; - } +//! returns abs of two values. Own implementation to get rid of STL (VS6 problems) +template +inline T abs_(const T &a) +{ + return a < (T)0 ? -a : a; +} - //! returns linear interpolation of a and b with ratio t - //! \return: a if t==0, b if t==1, and the linear interpolation else - template - inline T lerp(const T& a, const T& b, const f32 t) - { - return (T)(a*(1.f-t)) + (b*t); - } +//! returns linear interpolation of a and b with ratio t +//! \return: a if t==0, b if t==1, and the linear interpolation else +template +inline T lerp(const T &a, const T &b, const f32 t) +{ + return (T)(a * (1.f - t)) + (b * t); +} - //! clamps a value between low and high - template - inline const T clamp (const T& value, const T& low, const T& high) - { - return min_ (max_(value,low), high); - } +//! clamps a value between low and high +template +inline const T clamp(const T &value, const T &low, const T &high) +{ + return min_(max_(value, low), high); +} - //! swaps the content of the passed parameters - // Note: We use the same trick as boost and use two template arguments to - // avoid ambiguity when swapping objects of an Irrlicht type that has not - // it's own swap overload. Otherwise we get conflicts with some compilers - // in combination with stl. - template - inline void swap(T1& a, T2& b) - { - T1 c(a); - a = b; - b = c; - } +//! swaps the content of the passed parameters +// Note: We use the same trick as boost and use two template arguments to +// avoid ambiguity when swapping objects of an Irrlicht type that has not +// it's own swap overload. Otherwise we get conflicts with some compilers +// in combination with stl. +template +inline void swap(T1 &a, T2 &b) +{ + T1 c(a); + a = b; + b = c; +} - template - inline T roundingError(); +template +inline T roundingError(); - template <> - inline f32 roundingError() - { - return ROUNDING_ERROR_f32; - } +template <> +inline f32 roundingError() +{ + return ROUNDING_ERROR_f32; +} - template <> - inline f64 roundingError() - { - return ROUNDING_ERROR_f64; - } +template <> +inline f64 roundingError() +{ + return ROUNDING_ERROR_f64; +} - template - inline T relativeErrorFactor() - { - return 1; - } +template +inline T relativeErrorFactor() +{ + return 1; +} - template <> - inline f32 relativeErrorFactor() - { - return 4; - } +template <> +inline f32 relativeErrorFactor() +{ + return 4; +} - template <> - inline f64 relativeErrorFactor() - { - return 8; - } +template <> +inline f64 relativeErrorFactor() +{ + return 8; +} - //! returns if a equals b, for types without rounding errors - template ::value, bool> = true> - inline bool equals(const T a, const T b) - { - return a == b; - } +//! returns if a equals b, for types without rounding errors +template ::value, bool> = true> +inline bool equals(const T a, const T b) +{ + return a == b; +} - //! returns if a equals b, taking possible rounding errors into account - template ::value, bool> = true> - inline bool equals(const T a, const T b, const T tolerance = roundingError()) - { - return std::abs(a - b) <= tolerance; - } +//! returns if a equals b, taking possible rounding errors into account +template ::value, bool> = true> +inline bool equals(const T a, const T b, const T tolerance = roundingError()) +{ + return std::abs(a - b) <= tolerance; +} - //! returns if a equals b, taking relative error in form of factor - //! this particular function does not involve any division. - template - inline bool equalsRelative( const T a, const T b, const T factor = relativeErrorFactor()) - { - //https://eagergames.wordpress.com/2017/04/01/fast-parallel-lines-and-vectors-test/ +//! returns if a equals b, taking relative error in form of factor +//! this particular function does not involve any division. +template +inline bool equalsRelative(const T a, const T b, const T factor = relativeErrorFactor()) +{ + // https://eagergames.wordpress.com/2017/04/01/fast-parallel-lines-and-vectors-test/ - const T maxi = max_( a, b); - const T mini = min_( a, b); - const T maxMagnitude = max_( maxi, -mini); + const T maxi = max_(a, b); + const T mini = min_(a, b); + const T maxMagnitude = max_(maxi, -mini); - return (maxMagnitude*factor + maxi) == (maxMagnitude*factor + mini); // MAD Wise - } + return (maxMagnitude * factor + maxi) == (maxMagnitude * factor + mini); // MAD Wise +} - union FloatIntUnion32 - { - FloatIntUnion32(float f1 = 0.0f) : f(f1) {} - // Portable sign-extraction - bool sign() const { return (i >> 31) != 0; } +union FloatIntUnion32 +{ + FloatIntUnion32(float f1 = 0.0f) : + f(f1) {} + // Portable sign-extraction + bool sign() const { return (i >> 31) != 0; } - irr::s32 i; - irr::f32 f; - }; + irr::s32 i; + irr::f32 f; +}; - //! We compare the difference in ULP's (spacing between floating-point numbers, aka ULP=1 means there exists no float between). - //\result true when numbers have a ULP <= maxUlpDiff AND have the same sign. - inline bool equalsByUlp(f32 a, f32 b, int maxUlpDiff) - { - // Based on the ideas and code from Bruce Dawson on - // http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/ - // When floats are interpreted as integers the two nearest possible float numbers differ just - // by one integer number. Also works the other way round, an integer of 1 interpreted as float - // is for example the smallest possible float number. +//! We compare the difference in ULP's (spacing between floating-point numbers, aka ULP=1 means there exists no float between). +//\result true when numbers have a ULP <= maxUlpDiff AND have the same sign. +inline bool equalsByUlp(f32 a, f32 b, int maxUlpDiff) +{ + // Based on the ideas and code from Bruce Dawson on + // http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/ + // When floats are interpreted as integers the two nearest possible float numbers differ just + // by one integer number. Also works the other way round, an integer of 1 interpreted as float + // is for example the smallest possible float number. - const FloatIntUnion32 fa(a); - const FloatIntUnion32 fb(b); + const FloatIntUnion32 fa(a); + const FloatIntUnion32 fb(b); - // Different signs, we could maybe get difference to 0, but so close to 0 using epsilons is better. - if ( fa.sign() != fb.sign() ) - { - // Check for equality to make sure +0==-0 - if (fa.i == fb.i) - return true; - return false; - } - - // Find the difference in ULPs. - const int ulpsDiff = abs_(fa.i- fb.i); - if (ulpsDiff <= maxUlpDiff) + // Different signs, we could maybe get difference to 0, but so close to 0 using epsilons is better. + if (fa.sign() != fb.sign()) { + // Check for equality to make sure +0==-0 + if (fa.i == fb.i) return true; - return false; } - //! returns if a equals zero, taking rounding errors into account - inline bool iszero(const f64 a, const f64 tolerance = ROUNDING_ERROR_f64) - { - return fabs(a) <= tolerance; - } + // Find the difference in ULPs. + const int ulpsDiff = abs_(fa.i - fb.i); + if (ulpsDiff <= maxUlpDiff) + return true; - //! returns if a equals zero, taking rounding errors into account - inline bool iszero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32) - { - return fabsf(a) <= tolerance; - } + return false; +} - //! returns if a equals not zero, taking rounding errors into account - inline bool isnotzero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32) - { - return fabsf(a) > tolerance; - } +//! returns if a equals zero, taking rounding errors into account +inline bool iszero(const f64 a, const f64 tolerance = ROUNDING_ERROR_f64) +{ + return fabs(a) <= tolerance; +} - //! returns if a equals zero, taking rounding errors into account - inline bool iszero(const s32 a, const s32 tolerance = 0) - { - return ( a & 0x7ffffff ) <= tolerance; - } +//! returns if a equals zero, taking rounding errors into account +inline bool iszero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32) +{ + return fabsf(a) <= tolerance; +} - //! returns if a equals zero, taking rounding errors into account - inline bool iszero(const u32 a, const u32 tolerance = 0) - { - return a <= tolerance; - } +//! returns if a equals not zero, taking rounding errors into account +inline bool isnotzero(const f32 a, const f32 tolerance = ROUNDING_ERROR_f32) +{ + return fabsf(a) > tolerance; +} - //! returns if a equals zero, taking rounding errors into account - inline bool iszero(const s64 a, const s64 tolerance = 0) - { - return abs_(a) <= tolerance; - } +//! returns if a equals zero, taking rounding errors into account +inline bool iszero(const s32 a, const s32 tolerance = 0) +{ + return (a & 0x7ffffff) <= tolerance; +} - inline s32 s32_min(s32 a, s32 b) - { - return min_(a, b); - } +//! returns if a equals zero, taking rounding errors into account +inline bool iszero(const u32 a, const u32 tolerance = 0) +{ + return a <= tolerance; +} - inline s32 s32_max(s32 a, s32 b) - { - return max_(a, b); - } +//! returns if a equals zero, taking rounding errors into account +inline bool iszero(const s64 a, const s64 tolerance = 0) +{ + return abs_(a) <= tolerance; +} - inline s32 s32_clamp (s32 value, s32 low, s32 high) - { - return clamp(value, low, high); - } +inline s32 s32_min(s32 a, s32 b) +{ + return min_(a, b); +} - /* - float IEEE-754 bit representation +inline s32 s32_max(s32 a, s32 b) +{ + return max_(a, b); +} - 0 0x00000000 - 1.0 0x3f800000 - 0.5 0x3f000000 - 3 0x40400000 - +inf 0x7f800000 - -inf 0xff800000 - +NaN 0x7fc00000 or 0x7ff00000 - in general: number = (sign ? -1:1) * 2^(exponent) * 1.(mantissa bits) - */ +inline s32 s32_clamp(s32 value, s32 low, s32 high) +{ + return clamp(value, low, high); +} - typedef union { u32 u; s32 s; f32 f; } inttofloat; +/* + float IEEE-754 bit representation - #define F32_AS_S32(f) (*((s32 *) &(f))) - #define F32_AS_U32(f) (*((u32 *) &(f))) - #define F32_AS_U32_POINTER(f) ( ((u32 *) &(f))) + 0 0x00000000 + 1.0 0x3f800000 + 0.5 0x3f000000 + 3 0x40400000 + +inf 0x7f800000 + -inf 0xff800000 + +NaN 0x7fc00000 or 0x7ff00000 + in general: number = (sign ? -1:1) * 2^(exponent) * 1.(mantissa bits) +*/ - #define F32_VALUE_0 0x00000000 - #define F32_VALUE_1 0x3f800000 +typedef union +{ + u32 u; + s32 s; + f32 f; +} inttofloat; - //! code is taken from IceFPU - //! Integer representation of a floating-point value. - inline u32 IR(f32 x) {inttofloat tmp; tmp.f=x; return tmp.u;} +#define F32_AS_S32(f) (*((s32 *)&(f))) +#define F32_AS_U32(f) (*((u32 *)&(f))) +#define F32_AS_U32_POINTER(f) (((u32 *)&(f))) - //! Floating-point representation of an integer value. - inline f32 FR(u32 x) {inttofloat tmp; tmp.u=x; return tmp.f;} - inline f32 FR(s32 x) {inttofloat tmp; tmp.s=x; return tmp.f;} +#define F32_VALUE_0 0x00000000 +#define F32_VALUE_1 0x3f800000 - #define F32_LOWER_0(n) ((n) < 0.0f) - #define F32_LOWER_EQUAL_0(n) ((n) <= 0.0f) - #define F32_GREATER_0(n) ((n) > 0.0f) - #define F32_GREATER_EQUAL_0(n) ((n) >= 0.0f) - #define F32_EQUAL_1(n) ((n) == 1.0f) - #define F32_EQUAL_0(n) ((n) == 0.0f) - #define F32_A_GREATER_B(a,b) ((a) > (b)) +//! code is taken from IceFPU +//! Integer representation of a floating-point value. +inline u32 IR(f32 x) +{ + inttofloat tmp; + tmp.f = x; + return tmp.u; +} + +//! Floating-point representation of an integer value. +inline f32 FR(u32 x) +{ + inttofloat tmp; + tmp.u = x; + return tmp.f; +} +inline f32 FR(s32 x) +{ + inttofloat tmp; + tmp.s = x; + return tmp.f; +} + +#define F32_LOWER_0(n) ((n) < 0.0f) +#define F32_LOWER_EQUAL_0(n) ((n) <= 0.0f) +#define F32_GREATER_0(n) ((n) > 0.0f) +#define F32_GREATER_EQUAL_0(n) ((n) >= 0.0f) +#define F32_EQUAL_1(n) ((n) == 1.0f) +#define F32_EQUAL_0(n) ((n) == 0.0f) +#define F32_A_GREATER_B(a, b) ((a) > (b)) #ifndef REALINLINE - #ifdef _MSC_VER - #define REALINLINE __forceinline - #else - #define REALINLINE inline - #endif +#ifdef _MSC_VER +#define REALINLINE __forceinline +#else +#define REALINLINE inline +#endif #endif +// NOTE: This is not as exact as the c99/c++11 round function, especially at high numbers starting with 8388609 +// (only low number which seems to go wrong is 0.49999997 which is rounded to 1) +// Also negative 0.5 is rounded up not down unlike with the standard function (p.E. input -0.5 will be 0 and not -1) +inline f32 round_(f32 x) +{ + return floorf(x + 0.5f); +} - // NOTE: This is not as exact as the c99/c++11 round function, especially at high numbers starting with 8388609 - // (only low number which seems to go wrong is 0.49999997 which is rounded to 1) - // Also negative 0.5 is rounded up not down unlike with the standard function (p.E. input -0.5 will be 0 and not -1) - inline f32 round_( f32 x ) - { - return floorf( x + 0.5f ); - } +// calculate: sqrt ( x ) +REALINLINE f32 squareroot(const f32 f) +{ + return sqrtf(f); +} - // calculate: sqrt ( x ) - REALINLINE f32 squareroot(const f32 f) - { - return sqrtf(f); - } +// calculate: sqrt ( x ) +REALINLINE f64 squareroot(const f64 f) +{ + return sqrt(f); +} - // calculate: sqrt ( x ) - REALINLINE f64 squareroot(const f64 f) - { - return sqrt(f); - } +// calculate: sqrt ( x ) +REALINLINE s32 squareroot(const s32 f) +{ + return static_cast(squareroot(static_cast(f))); +} - // calculate: sqrt ( x ) - REALINLINE s32 squareroot(const s32 f) - { - return static_cast(squareroot(static_cast(f))); - } +// calculate: sqrt ( x ) +REALINLINE s64 squareroot(const s64 f) +{ + return static_cast(squareroot(static_cast(f))); +} - // calculate: sqrt ( x ) - REALINLINE s64 squareroot(const s64 f) - { - return static_cast(squareroot(static_cast(f))); - } +// calculate: 1 / sqrt ( x ) +REALINLINE f64 reciprocal_squareroot(const f64 x) +{ + return 1.0 / sqrt(x); +} - // calculate: 1 / sqrt ( x ) - REALINLINE f64 reciprocal_squareroot(const f64 x) - { - return 1.0 / sqrt(x); - } +// calculate: 1 / sqrtf ( x ) +REALINLINE f32 reciprocal_squareroot(const f32 f) +{ + return 1.f / sqrtf(f); +} - // calculate: 1 / sqrtf ( x ) - REALINLINE f32 reciprocal_squareroot(const f32 f) - { - return 1.f / sqrtf(f); - } +// calculate: 1 / sqrtf( x ) +REALINLINE s32 reciprocal_squareroot(const s32 x) +{ + return static_cast(reciprocal_squareroot(static_cast(x))); +} - // calculate: 1 / sqrtf( x ) - REALINLINE s32 reciprocal_squareroot(const s32 x) - { - return static_cast(reciprocal_squareroot(static_cast(x))); - } +// calculate: 1 / x +REALINLINE f32 reciprocal(const f32 f) +{ + return 1.f / f; +} - // calculate: 1 / x - REALINLINE f32 reciprocal( const f32 f ) - { - return 1.f / f; - } +// calculate: 1 / x +REALINLINE f64 reciprocal(const f64 f) +{ + return 1.0 / f; +} - // calculate: 1 / x - REALINLINE f64 reciprocal ( const f64 f ) - { - return 1.0 / f; - } +// calculate: 1 / x, low precision allowed +REALINLINE f32 reciprocal_approxim(const f32 f) +{ + return 1.f / f; +} +REALINLINE s32 floor32(f32 x) +{ + return (s32)floorf(x); +} - // calculate: 1 / x, low precision allowed - REALINLINE f32 reciprocal_approxim ( const f32 f ) - { - return 1.f / f; - } +REALINLINE s32 ceil32(f32 x) +{ + return (s32)ceilf(x); +} - REALINLINE s32 floor32(f32 x) - { - return (s32) floorf ( x ); - } +// NOTE: Please check round_ documentation about some inaccuracies in this compared to standard library round function. +REALINLINE s32 round32(f32 x) +{ + return (s32)round_(x); +} - REALINLINE s32 ceil32 ( f32 x ) - { - return (s32) ceilf ( x ); - } +inline f32 f32_max3(const f32 a, const f32 b, const f32 c) +{ + return a > b ? (a > c ? a : c) : (b > c ? b : c); +} - // NOTE: Please check round_ documentation about some inaccuracies in this compared to standard library round function. - REALINLINE s32 round32(f32 x) - { - return (s32) round_(x); - } +inline f32 f32_min3(const f32 a, const f32 b, const f32 c) +{ + return a < b ? (a < c ? a : c) : (b < c ? b : c); +} - inline f32 f32_max3(const f32 a, const f32 b, const f32 c) - { - return a > b ? (a > c ? a : c) : (b > c ? b : c); - } - - inline f32 f32_min3(const f32 a, const f32 b, const f32 c) - { - return a < b ? (a < c ? a : c) : (b < c ? b : c); - } - - inline f32 fract ( f32 x ) - { - return x - floorf ( x ); - } +inline f32 fract(f32 x) +{ + return x - floorf(x); +} } // end namespace core } // end namespace irr -using irr::core::IR; using irr::core::FR; - +using irr::core::IR; diff --git a/include/irrString.h b/include/irrString.h index 7c56f980..5bf604e4 100644 --- a/include/irrString.h +++ b/include/irrString.h @@ -43,48 +43,44 @@ typedef string stringc; //! Typedef for wide character strings typedef string stringw; - //! Returns a character converted to lower case -static inline u32 locale_lower ( u32 x ) +static inline u32 locale_lower(u32 x) { // ansi return x >= 'A' && x <= 'Z' ? x + 0x20 : x; } //! Returns a character converted to upper case -static inline u32 locale_upper ( u32 x ) +static inline u32 locale_upper(u32 x) { // ansi - return x >= 'a' && x <= 'z' ? x + ( 'A' - 'a' ) : x; + return x >= 'a' && x <= 'z' ? x + ('A' - 'a') : x; } - template class string { public: - typedef T char_type; //! Default constructor string() - {} - + { + } //! Copy constructor - string(const string& other) + string(const string &other) { *this = other; } //! Constructor from other string types template - string(const string& other) + string(const string &other) { *this = other; } - //! Constructs a string from a float explicit string(const double number) { @@ -93,63 +89,56 @@ public: str = tmpbuf; } - //! Constructs a string from an int explicit string(int number) { str = std::to_string(number); } - //! Constructs a string from an unsigned int explicit string(unsigned int number) { str = std::to_string(number); } - //! Constructs a string from a long explicit string(long number) { str = std::to_string(number); } - //! Constructs a string from an unsigned long explicit string(unsigned long number) { str = std::to_string(number); } - //! Constructor for copying a string from a pointer with a given length template - string(const B* const c, u32 length) + string(const B *const c, u32 length) { if (!c) return; str.resize(length); - for (u32 l = 0; l - string(const B* const c) + string(const B *const c) { *this = c; } - //! Destructor ~string() - {} - + { + } //! Assignment operator - string& operator=(const string& other) + string &operator=(const string &other) { if (this == &other) return *this; @@ -160,37 +149,34 @@ public: //! Assignment operator for other string types template - string& operator=(const string& other) + string &operator=(const string &other) { *this = other.c_str(); return *this; } - //! Assignment operator for strings, ASCII and Unicode template - string& operator=(const B* const c) + string &operator=(const B *const c) { - if (!c) - { + if (!c) { clear(); return *this; } // no longer allowed! - _IRR_DEBUG_BREAK_IF((void*)c == (void*)c_str()); + _IRR_DEBUG_BREAK_IF((void *)c == (void *)c_str()); u32 len = calclen(c); str.resize(len); - for (u32 l = 0; l operator+(const string& other) const + string operator+(const string &other) const { string tmp(*this); tmp.append(other); @@ -198,10 +184,9 @@ public: return tmp; } - //! Append operator for strings, ASCII and Unicode template - string operator+(const B* const c) const + string operator+(const B *const c) const { string tmp(*this); tmp.append(c); @@ -209,58 +194,50 @@ public: return tmp; } - //! Direct access operator - T& operator [](const u32 index) + T &operator[](const u32 index) { return str[index]; } - //! Direct access operator - const T& operator [](const u32 index) const + const T &operator[](const u32 index) const { return str[index]; } - //! Equality operator - bool operator==(const T* const other) const + bool operator==(const T *const other) const { if (!other) return false; return !cmp(c_str(), other); } - //! Equality operator - bool operator==(const string& other) const + bool operator==(const string &other) const { return str == other.str; } - //! Is smaller comparator - bool operator<(const string& other) const + bool operator<(const string &other) const { return str < other.str; } - //! Inequality operator - bool operator!=(const T* const other) const + bool operator!=(const T *const other) const { return !(*this == other); } - //! Inequality operator - bool operator!=(const string& other) const + bool operator!=(const string &other) const { return !(*this == other); } - //! Returns length of the string's content /** \return Length of the string's content in characters, excluding the trailing NUL. */ @@ -276,7 +253,7 @@ public: return str.empty(); } - void clear(bool releaseMemory=true) + void clear(bool releaseMemory = true) { if (releaseMemory) { stl_type empty; @@ -288,39 +265,36 @@ public: //! Returns character string /** \return pointer to C-style NUL terminated string. */ - const T* c_str() const + const T *c_str() const { return str.c_str(); } - //! Makes the string lower case. - string& make_lower() + string &make_lower() { - std::transform(str.begin(), str.end(), str.begin(), [](const T& c) { + std::transform(str.begin(), str.end(), str.begin(), [](const T &c) { return locale_lower(c); }); return *this; } - //! Makes the string upper case. - string& make_upper() + string &make_upper() { - std::transform(str.begin(), str.end(), str.begin(), [](const T& c) { + std::transform(str.begin(), str.end(), str.begin(), [](const T &c) { return locale_upper(c); }); return *this; } - //! Compares the strings ignoring case. /** \param other: Other string to compare. \return True if the strings are equal ignoring case. */ - bool equals_ignore_case(const string& other) const + bool equals_ignore_case(const string &other) const { - const T* array = c_str(); - for(u32 i=0; array[i] && other[i]; ++i) + const T *array = c_str(); + for (u32 i = 0; array[i] && other[i]; ++i) if (locale_lower(array[i]) != locale_lower(other[i])) return false; @@ -331,47 +305,44 @@ public: /** \param other: Other string to compare. \param sourcePos: where to start to compare in the string \return True if the strings are equal ignoring case. */ - bool equals_substring_ignore_case(const string&other, const u32 sourcePos = 0 ) const + bool equals_substring_ignore_case(const string &other, const u32 sourcePos = 0) const { - if ( sourcePos >= size() + 1 ) + if (sourcePos >= size() + 1) return false; - const T* array = c_str(); + const T *array = c_str(); u32 i; - for(i=0; array[sourcePos + i] && other[i]; ++i) + for (i = 0; array[sourcePos + i] && other[i]; ++i) if (locale_lower(array[sourcePos + i]) != locale_lower(other[i])) return false; return array[sourcePos + i] == 0 && other[i] == 0; } - //! Compares the strings ignoring case. /** \param other: Other string to compare. \return True if this string is smaller ignoring case. */ - bool lower_ignore_case(const string& other) const + bool lower_ignore_case(const string &other) const { - const T* array = c_str(); - for(u32 i=0; array[i] && other[i]; ++i) - { - s32 diff = (s32) locale_lower ( array[i] ) - (s32) locale_lower ( other[i] ); - if ( diff ) + const T *array = c_str(); + for (u32 i = 0; array[i] && other[i]; ++i) { + s32 diff = (s32)locale_lower(array[i]) - (s32)locale_lower(other[i]); + if (diff) return diff < 0; } return size() < other.size(); } - //! compares the first n characters of the strings /** \param other Other string to compare. \param n Number of characters to compare \return True if the n first characters of both strings are equal. */ - bool equalsn(const string& other, u32 n) const + bool equalsn(const string &other, u32 n) const { - const T* array = c_str(); + const T *array = c_str(); u32 i; - for(i=0; i < n && array[i] && other[i]; ++i) + for (i = 0; i < n && array[i] && other[i]; ++i) if (array[i] != other[i]) return false; @@ -380,18 +351,17 @@ public: return (i == n) || (size() == other.size()); } - //! compares the first n characters of the strings /** \param str Other string to compare. \param n Number of characters to compare \return True if the n first characters of both strings are equal. */ - bool equalsn(const T* const other, u32 n) const + bool equalsn(const T *const other, u32 n) const { if (!other) return false; - const T* array = c_str(); + const T *array = c_str(); u32 i; - for(i=0; i < n && array[i] && other[i]; ++i) + for (i = 0; i < n && array[i] && other[i]; ++i) if (array[i] != other[i]) return false; @@ -400,20 +370,18 @@ public: return (i == n) || (array[i] == 0 && other[i] == 0); } - //! Appends a character to this string /** \param character: Character to append. */ - string& append(T character) + string &append(T character) { str.append(1, character); return *this; } - //! Appends a char string to this string /** \param other: Char string to append. */ /** \param length: The length of the string to append. */ - string& append(const T* const other, u32 length=0xffffffff) + string &append(const T *const other, u32 length = 0xffffffff) { if (!other) return *this; @@ -426,20 +394,18 @@ public: return *this; } - //! Appends a string to this string /** \param other: String to append. */ - string& append(const string& other) + string &append(const string &other) { str.append(other.str); return *this; } - //! Appends a string of the length l to this string. /** \param other: other String to append to this string. \param length: How much characters of the other string to add to this one. */ - string& append(const string& other, u32 length) + string &append(const string &other, u32 length) { if (other.size() < length) append(other); @@ -452,10 +418,9 @@ public: //\param pos Insert the characters before this index //\param s String to insert. Must be at least of size n //\param n Number of characters from string s to use. - string& insert(u32 pos, const T* s, u32 n) + string &insert(u32 pos, const T *s, u32 n) { - if ( pos < size()+1 ) - { + if (pos < size() + 1) { str.insert(pos, s, n); } @@ -472,7 +437,6 @@ public: str.reserve(count - 1); } - //! finds first occurrence of character in string /** \param c: Character to search for. \return Position where the character has been found, @@ -490,7 +454,7 @@ public: this should be strlen(c) \return Position where one of the characters has been found, or -1 if not found. */ - s32 findFirstChar(const T* const c, u32 count=1) const + s32 findFirstChar(const T *const c, u32 count = 1) const { if (!c || !count) return -1; @@ -499,7 +463,6 @@ public: return pos_from_stl(r); } - //! Finds first position of a character not in a given list. /** \param c: List of characters not to find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". @@ -507,7 +470,7 @@ public: this should be strlen(c) \return Position where the character has been found, or -1 if not found. */ - s32 findFirstCharNotInList(const T* const c, u32 count=1) const + s32 findFirstCharNotInList(const T *const c, u32 count = 1) const { if (!c || !count) return -1; @@ -523,7 +486,7 @@ public: this should be strlen(c) \return Position where the character has been found, or -1 if not found. */ - s32 findLastCharNotInList(const T* const c, u32 count=1) const + s32 findLastCharNotInList(const T *const c, u32 count = 1) const { if (!c || !count) return -1; @@ -543,7 +506,6 @@ public: return pos_from_stl(r); } - //! finds last occurrence of character in string /** \param c: Character to search for. \param start: start to search reverse ( default = -1, on end ) @@ -562,7 +524,7 @@ public: this should be strlen(c) \return Position where one of the characters has been found, or -1 if not found. */ - s32 findLastChar(const T* const c, u32 count=1) const + s32 findLastChar(const T *const c, u32 count = 1) const { if (!c || !count) return -1; @@ -571,16 +533,14 @@ public: return pos_from_stl(r); } - //! finds another string in this string /** \param str: Another string \param start: Start position of the search \return Positions where the string has been found, or -1 if not found. */ - s32 find(const T* const other, const u32 start = 0) const + s32 find(const T *const other, const u32 start = 0) const { - if (other && *other) - { + if (other && *other) { auto r = str.find(other, start); return pos_from_stl(r); } @@ -588,16 +548,15 @@ public: return -1; } - //! Returns a substring /** \param begin Start of substring. \param length Length of substring. \param make_lower copy only lower case */ - string subString(u32 begin, s32 length, bool make_lower = false ) const + string subString(u32 begin, s32 length, bool make_lower = false) const { // if start after string // or no proper substring length - if ((length <= 0) || (begin>=size())) + if ((length <= 0) || (begin >= size())) return string(""); string o = str.substr(begin, length); @@ -606,142 +565,126 @@ public: return o; } - //! Appends a character to this string /** \param c Character to append. */ - string& operator += (T c) + string &operator+=(T c) { append(c); return *this; } - //! Appends a char string to this string /** \param c Char string to append. */ - string& operator += (const T* const c) + string &operator+=(const T *const c) { append(c); return *this; } - //! Appends a string to this string /** \param other String to append. */ - string& operator += (const string& other) + string &operator+=(const string &other) { append(other); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const int i) + string &operator+=(const int i) { append(string(i)); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const unsigned int i) + string &operator+=(const unsigned int i) { append(string(i)); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const long i) + string &operator+=(const long i) { append(string(i)); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const unsigned long i) + string &operator+=(const unsigned long i) { append(string(i)); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const double i) + string &operator+=(const double i) { append(string(i)); return *this; } - //! Appends a string representation of a number to this string /** \param i Number to append. */ - string& operator += (const float i) + string &operator+=(const float i) { append(string(i)); return *this; } - //! Replaces all characters of a special type with another one /** \param toReplace Character to replace. \param replaceWith Character replacing the old one. */ - string& replace(T toReplace, T replaceWith) + string &replace(T toReplace, T replaceWith) { std::replace(str.begin(), str.end(), toReplace, replaceWith); return *this; } - //! Replaces all instances of a string with another one. /** \param toReplace The string to replace. \param replaceWith The string replacing the old one. */ - string& replace(const string& toReplace, const string& replaceWith) + string &replace(const string &toReplace, const string &replaceWith) { size_type pos = 0; - while ((pos = str.find(toReplace.str, pos)) != npos) { - str.replace(pos, toReplace.size(), replaceWith.str); - pos += replaceWith.size(); - } + while ((pos = str.find(toReplace.str, pos)) != npos) { + str.replace(pos, toReplace.size(), replaceWith.str); + pos += replaceWith.size(); + } return *this; } - //! Removes a character from a string. /** \param c: Character to remove. */ - string& remove(T c) + string &remove(T c) { str.erase(std::remove(str.begin(), str.end(), c), str.end()); return *this; } - //! Removes a string from the string. /** \param toRemove: String to remove. */ - string& remove(const string& toRemove) + string &remove(const string &toRemove) { u32 size = toRemove.size(); - if ( size == 0 ) + if (size == 0) return *this; u32 pos = 0; u32 found = 0; - for (u32 i=0; i& removeChars(const string & characters) + string &removeChars(const string &characters) { if (characters.size() == 0) return *this; @@ -766,34 +708,33 @@ public: return *this; } - //! Trims the string. /** Removes the specified characters (by default, Latin-1 whitespace) from the beginning and the end of the string. */ - string& trim(const string & whitespace = " \t\n\r") + string &trim(const string &whitespace = " \t\n\r") { // find start and end of the substring without the specified characters const s32 begin = findFirstCharNotInList(whitespace.c_str(), whitespace.size()); if (begin == -1) - return (*this=""); + return (*this = ""); const s32 end = findLastCharNotInList(whitespace.c_str(), whitespace.size()); - return (*this = subString(begin, (end +1) - begin)); + return (*this = subString(begin, (end + 1) - begin)); } //! Erases a character from the string. /** May be slow, because all elements following after the erased element have to be copied. \param index: Index of element to be erased. */ - string& erase(u32 index) + string &erase(u32 index) { str.erase(str.begin() + index); return *this; } //! verify the existing string. - string& validate() + string &validate() { // truncate to existing null u32 len = calclen(c_str()); @@ -828,31 +769,27 @@ public: characters between the delimiters are returned. \return The number of resulting substrings */ - template - u32 split(container& ret, const T* const delimiter, u32 countDelimiters=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const + template + u32 split(container &ret, const T *const delimiter, u32 countDelimiters = 1, bool ignoreEmptyTokens = true, bool keepSeparators = false) const { if (!delimiter) return 0; - const u32 oldSize=static_cast(ret.size()); + const u32 oldSize = static_cast(ret.size()); u32 tokenStartIdx = 0; - for (u32 i=0; i 0) ret.push_back(string(&str[tokenStartIdx], i - tokenStartIdx)); - else if ( !ignoreEmptyTokens ) + else if (!ignoreEmptyTokens) ret.push_back(string()); - if ( keepSeparators ) - { + if (keepSeparators) { ret.push_back(string(&str[i], 1)); } - tokenStartIdx = i+1; + tokenStartIdx = i + 1; break; } } @@ -862,66 +799,74 @@ public: else if (!ignoreEmptyTokens) ret.push_back(string()); - return static_cast(ret.size()-oldSize); + return static_cast(ret.size() - oldSize); } // This function should not be used and is only kept for "CGUIFileOpenDialog::pathToStringW". - friend size_t multibyteToWString(stringw& destination, const stringc &source); + friend size_t multibyteToWString(stringw &destination, const stringc &source); friend size_t utf8ToWString(stringw &destination, const char *source); friend size_t wStringToUTF8(stringc &destination, const wchar_t *source); private: - typedef std::basic_string stl_type; //! Private constructor - string(stl_type &&str) : str(str) - {} + string(stl_type &&str) : + str(str) + { + } //! strlen wrapper template - static inline u32 calclen(const U* p) { + static inline u32 calclen(const U *p) + { u32 len = 0; while (*p++) len++; return len; } - static inline u32 calclen(const char* p) { + static inline u32 calclen(const char *p) + { return static_cast(strlen(p)); } - static inline u32 calclen(const wchar_t* p) { + static inline u32 calclen(const wchar_t *p) + { return static_cast(wcslen(p)); } //! strcmp wrapper template - static inline int cmp(const U* p, const U* p2) { + static inline int cmp(const U *p, const U *p2) + { while (*p && *p == *p2) p++, p2++; return (int)*p - (int)*p2; } - static inline int cmp(const char* p, const char* p2) { + static inline int cmp(const char *p, const char *p2) + { return strcmp(p, p2); } - static inline int cmp(const wchar_t* p, const wchar_t* p2) { + static inline int cmp(const wchar_t *p, const wchar_t *p2) + { return wcscmp(p, p2); } typedef typename stl_type::size_type size_type; static const size_type npos = stl_type::npos; - static inline s32 pos_from_stl(size_type pos) { + static inline s32 pos_from_stl(size_type pos) + { return pos == npos ? -1 : (s32)pos; } - static inline size_type pos_to_stl(s32 pos) { + static inline size_type pos_to_stl(s32 pos) + { return pos == -1 ? npos : (size_type)pos; } stl_type str; }; - //! Convert multibyte string to wide-character string /** Wrapper around mbstowcs from standard library, but directly using Irrlicht string class. What the function does exactly depends on the LC_CTYPE of the current c locale. @@ -930,41 +875,34 @@ What the function does exactly depends on the LC_CTYPE of the current c locale. \return The number of wide characters written to destination, not including the eventual terminating null character or -1 when conversion failed This function should not be used and is only kept for "CGUIFileOpenDialog::pathToStringW". */ -inline size_t multibyteToWString(stringw& destination, const core::stringc& source) +inline size_t multibyteToWString(stringw &destination, const core::stringc &source) { u32 sourceSize = source.size(); - if ( sourceSize ) - { - destination.str.resize(sourceSize+1); + if (sourceSize) { + destination.str.resize(sourceSize + 1); #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable: 4996) // 'mbstowcs': This function or variable may be unsafe. Consider using mbstowcs_s instead. +#pragma warning(disable : 4996) // 'mbstowcs': This function or variable may be unsafe. Consider using mbstowcs_s instead. #endif const size_t written = mbstowcs(&destination[0], source.c_str(), (size_t)sourceSize); #if defined(_MSC_VER) #pragma warning(pop) #endif - if ( written != (size_t)-1 ) - { + if (written != (size_t)-1) { destination.str.resize(written); - } - else - { + } else { // Likely character which got converted until the invalid character was encountered are in destination now. // And it seems even 0-terminated, but I found no documentation anywhere that this (the 0-termination) is guaranteed :-( destination.clear(); } return written; - } - else - { + } else { destination.clear(); return 0; } } - inline size_t utf8ToWString(stringw &destination, const char *source) { std::wstring_convert> conv; @@ -989,8 +927,5 @@ inline size_t wStringToUTF8(stringc &destination, const stringw &source) return wStringToUTF8(destination, source.c_str()); } - } // end namespace core } // end namespace irr - - diff --git a/include/irrTypes.h b/include/irrTypes.h index 9ee00356..6c0ee661 100644 --- a/include/irrTypes.h +++ b/include/irrTypes.h @@ -10,52 +10,43 @@ namespace irr { //! 8 bit unsigned variable. -typedef uint8_t u8; +typedef uint8_t u8; //! 8 bit signed variable. -typedef int8_t s8; +typedef int8_t s8; //! 8 bit character variable. /** This is a typedef for char, it ensures portability of the engine. */ -typedef char c8; - - +typedef char c8; //! 16 bit unsigned variable. -typedef uint16_t u16; +typedef uint16_t u16; //! 16 bit signed variable. -typedef int16_t s16; - - +typedef int16_t s16; //! 32 bit unsigned variable. -typedef uint32_t u32; +typedef uint32_t u32; //! 32 bit signed variable. -typedef int32_t s32; - +typedef int32_t s32; //! 64 bit unsigned variable. -typedef uint64_t u64; +typedef uint64_t u64; //! 64 bit signed variable. -typedef int64_t s64; - - +typedef int64_t s64; //! 32 bit floating point variable. /** This is a typedef for float, it ensures portability of the engine. */ -typedef float f32; +typedef float f32; //! 64 bit floating point variable. /** This is a typedef for double, it ensures portability of the engine. */ -typedef double f64; - +typedef double f64; } // end namespace irr - //! Defines for snprintf_irr because snprintf method does not match the ISO C //! standard on Windows platforms. //! We want int snprintf_irr(char *str, size_t size, const char *format, ...); @@ -69,22 +60,25 @@ namespace irr { //! Type name for character type used by the file system (legacy). - typedef char fschar_t; - #define _IRR_TEXT(X) X +typedef char fschar_t; +#define _IRR_TEXT(X) X } // end namespace irr //! define a break macro for debugging. #if defined(_DEBUG) #if defined(_IRR_WINDOWS_API_) && defined(_MSC_VER) - #include - #define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) if (_CONDITION_) {_CrtDbgBreak();} +#include +#define _IRR_DEBUG_BREAK_IF(_CONDITION_) \ + if (_CONDITION_) { \ + _CrtDbgBreak(); \ + } #else - #include - #define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) assert( !(_CONDITION_) ); +#include +#define _IRR_DEBUG_BREAK_IF(_CONDITION_) assert(!(_CONDITION_)); #endif #else - #define _IRR_DEBUG_BREAK_IF( _CONDITION_ ) +#define _IRR_DEBUG_BREAK_IF(_CONDITION_) #endif //! deprecated macro for virtual function override @@ -94,7 +88,6 @@ namespace irr //! creates four CC codes used in Irrlicht for simple ids /** some compilers can create those by directly writing the code like 'code', but some generate warnings so we use this macro here */ -#define MAKE_IRR_ID(c0, c1, c2, c3) \ - ((irr::u32)(irr::u8)(c0) | ((irr::u32)(irr::u8)(c1) << 8) | \ - ((irr::u32)(irr::u8)(c2) << 16) | ((irr::u32)(irr::u8)(c3) << 24 )) - +#define MAKE_IRR_ID(c0, c1, c2, c3) \ + ((irr::u32)(irr::u8)(c0) | ((irr::u32)(irr::u8)(c1) << 8) | \ + ((irr::u32)(irr::u8)(c2) << 16) | ((irr::u32)(irr::u8)(c3) << 24)) diff --git a/include/irrlicht.h b/include/irrlicht.h index e8f091f7..5b7042fc 100644 --- a/include/irrlicht.h +++ b/include/irrlicht.h @@ -11,11 +11,11 @@ freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. + misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Please note that the Irrlicht Engine is based in part on the work of the @@ -246,72 +246,71 @@ //! Everything in the Irrlicht Engine can be found in this namespace. namespace irr { - //! Creates an Irrlicht device. The Irrlicht device is the root object for using the engine. - /** If you need more parameters to be passed to the creation of the Irrlicht Engine device, - use the createDeviceEx() function. - \param driverType: Type of the video driver to use. - \param windowSize: Size of the window or the video mode in fullscreen mode. - \param bits: Bits per pixel in fullscreen mode. Ignored if windowed mode. - \param fullscreen: Should be set to true if the device should run in fullscreen. Otherwise - the device runs in windowed mode. - \param stencilbuffer: Specifies if the stencil buffer should be enabled. Set this to true, - if you want the engine be able to draw stencil buffer shadows. Note that not all - devices are able to use the stencil buffer. If they don't no shadows will be drawn. - \param vsync: Specifies vertical synchronization: If set to true, the driver will wait - for the vertical retrace period, otherwise not. - \param receiver: A user created event receiver. - \return Returns pointer to the created IrrlichtDevice or null if the - device could not be created. - */ - extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDevice( +//! Creates an Irrlicht device. The Irrlicht device is the root object for using the engine. +/** If you need more parameters to be passed to the creation of the Irrlicht Engine device, +use the createDeviceEx() function. +\param driverType: Type of the video driver to use. +\param windowSize: Size of the window or the video mode in fullscreen mode. +\param bits: Bits per pixel in fullscreen mode. Ignored if windowed mode. +\param fullscreen: Should be set to true if the device should run in fullscreen. Otherwise + the device runs in windowed mode. +\param stencilbuffer: Specifies if the stencil buffer should be enabled. Set this to true, +if you want the engine be able to draw stencil buffer shadows. Note that not all +devices are able to use the stencil buffer. If they don't no shadows will be drawn. +\param vsync: Specifies vertical synchronization: If set to true, the driver will wait +for the vertical retrace period, otherwise not. +\param receiver: A user created event receiver. +\return Returns pointer to the created IrrlichtDevice or null if the +device could not be created. +*/ +extern "C" IRRLICHT_API IrrlichtDevice *IRRCALLCONV createDevice( video::E_DRIVER_TYPE driverType = video::EDT_OPENGL, // parentheses are necessary for some compilers - const core::dimension2d& windowSize = (core::dimension2d(640,480)), + const core::dimension2d &windowSize = (core::dimension2d(640, 480)), u32 bits = 32, bool fullscreen = false, bool stencilbuffer = true, bool vsync = false, - IEventReceiver* receiver = 0); + IEventReceiver *receiver = 0); +//! Creates an Irrlicht device with the option to specify advanced parameters. +/** Usually you should used createDevice() for creating an Irrlicht Engine device. +Use this function only if you wish to specify advanced parameters like a window +handle in which the device should be created. +\param parameters: Structure containing advanced parameters for the creation of the device. +See irr::SIrrlichtCreationParameters for details. +\return Returns pointer to the created IrrlichtDevice or null if the +device could not be created. */ +extern "C" IRRLICHT_API IrrlichtDevice *IRRCALLCONV createDeviceEx( + const SIrrlichtCreationParameters ¶meters); - //! Creates an Irrlicht device with the option to specify advanced parameters. - /** Usually you should used createDevice() for creating an Irrlicht Engine device. - Use this function only if you wish to specify advanced parameters like a window - handle in which the device should be created. - \param parameters: Structure containing advanced parameters for the creation of the device. - See irr::SIrrlichtCreationParameters for details. - \return Returns pointer to the created IrrlichtDevice or null if the - device could not be created. */ - extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDeviceEx( - const SIrrlichtCreationParameters& parameters); +// THE FOLLOWING IS AN EMPTY LIST OF ALL SUB NAMESPACES +// EXISTING ONLY FOR THE DOCUMENTATION SOFTWARE DOXYGEN. - // THE FOLLOWING IS AN EMPTY LIST OF ALL SUB NAMESPACES - // EXISTING ONLY FOR THE DOCUMENTATION SOFTWARE DOXYGEN. +//! Basic classes such as vectors, planes, arrays, lists, and so on can be found in this namespace. +namespace core +{ +} - //! Basic classes such as vectors, planes, arrays, lists, and so on can be found in this namespace. - namespace core - { - } +//! The gui namespace contains useful classes for easy creation of a graphical user interface. +namespace gui +{ +} - //! The gui namespace contains useful classes for easy creation of a graphical user interface. - namespace gui - { - } +//! This namespace provides interfaces for input/output: Reading and writing files, accessing zip archives, ... +namespace io +{ +} - //! This namespace provides interfaces for input/output: Reading and writing files, accessing zip archives, ... - namespace io - { - } +//! All scene management can be found in this namespace: Mesh loading, special scene nodes like octrees and billboards, ... +namespace scene +{ +} - //! All scene management can be found in this namespace: Mesh loading, special scene nodes like octrees and billboards, ... - namespace scene - { - } - - //! The video namespace contains classes for accessing the video driver. All 2d and 3d rendering is done here. - namespace video - { - } +//! The video namespace contains classes for accessing the video driver. All 2d and 3d rendering is done here. +namespace video +{ +} } /*! \file irrlicht.h diff --git a/include/irrpack.h b/include/irrpack.h index c8ddb6a0..5887cda6 100644 --- a/include/irrpack.h +++ b/include/irrpack.h @@ -14,13 +14,12 @@ // byte-align structures #if defined(_MSC_VER) -# pragma warning(disable: 4103) -# pragma pack( push, packing ) -# pragma pack( 1 ) -# define PACK_STRUCT -#elif defined( __GNUC__ ) -# define PACK_STRUCT __attribute__((packed)) +#pragma warning(disable : 4103) +#pragma pack(push, packing) +#pragma pack(1) +#define PACK_STRUCT +#elif defined(__GNUC__) +#define PACK_STRUCT __attribute__((packed)) #else -# error compiler not supported +#error compiler not supported #endif - diff --git a/include/irrunpack.h b/include/irrunpack.h index 4df86b33..999e1ea0 100644 --- a/include/irrunpack.h +++ b/include/irrunpack.h @@ -7,8 +7,7 @@ // Default alignment #if defined(_MSC_VER) -# pragma pack( pop, packing ) +#pragma pack(pop, packing) #endif #undef PACK_STRUCT - diff --git a/include/line2d.h b/include/line2d.h index 88b6a0db..fb58f0b7 100644 --- a/include/line2d.h +++ b/include/line2d.h @@ -16,342 +16,365 @@ namespace core template class line2d { - public: - //! Default constructor for line going from (0,0) to (1,1). - constexpr line2d() : start(0,0), end(1,1) {} - //! Constructor for line between the two points. - constexpr line2d(T xa, T ya, T xb, T yb) : start(xa, ya), end(xb, yb) {} - //! Constructor for line between the two points given as vectors. - constexpr line2d(const vector2d& start, const vector2d& end) : start(start), end(end) {} +public: + //! Default constructor for line going from (0,0) to (1,1). + constexpr line2d() : + start(0, 0), end(1, 1) {} + //! Constructor for line between the two points. + constexpr line2d(T xa, T ya, T xb, T yb) : + start(xa, ya), end(xb, yb) {} + //! Constructor for line between the two points given as vectors. + constexpr line2d(const vector2d &start, const vector2d &end) : + start(start), end(end) {} - // operators + // operators - line2d operator+(const vector2d& point) const { return line2d(start + point, end + point); } - line2d& operator+=(const vector2d& point) { start += point; end += point; return *this; } + line2d operator+(const vector2d &point) const { return line2d(start + point, end + point); } + line2d &operator+=(const vector2d &point) + { + start += point; + end += point; + return *this; + } - line2d operator-(const vector2d& point) const { return line2d(start - point, end - point); } - line2d& operator-=(const vector2d& point) { start -= point; end -= point; return *this; } + line2d operator-(const vector2d &point) const { return line2d(start - point, end - point); } + line2d &operator-=(const vector2d &point) + { + start -= point; + end -= point; + return *this; + } - constexpr bool operator==(const line2d& other) const - { return (start==other.start && end==other.end) || (end==other.start && start==other.end);} - constexpr bool operator!=(const line2d& other) const - { return !(start==other.start && end==other.end) || (end==other.start && start==other.end);} + constexpr bool operator==(const line2d &other) const + { + return (start == other.start && end == other.end) || (end == other.start && start == other.end); + } + constexpr bool operator!=(const line2d &other) const + { + return !(start == other.start && end == other.end) || (end == other.start && start == other.end); + } - // functions - //! Set this line to new line going through the two points. - void setLine(const T& xa, const T& ya, const T& xb, const T& yb){start.set(xa, ya); end.set(xb, yb);} - //! Set this line to new line going through the two points. - void setLine(const vector2d& nstart, const vector2d& nend){start.set(nstart); end.set(nend);} - //! Set this line to new line given as parameter. - void setLine(const line2d& line){start.set(line.start); end.set(line.end);} + // functions + //! Set this line to new line going through the two points. + void setLine(const T &xa, const T &ya, const T &xb, const T &yb) + { + start.set(xa, ya); + end.set(xb, yb); + } + //! Set this line to new line going through the two points. + void setLine(const vector2d &nstart, const vector2d &nend) + { + start.set(nstart); + end.set(nend); + } + //! Set this line to new line given as parameter. + void setLine(const line2d &line) + { + start.set(line.start); + end.set(line.end); + } - //! Get length of line - /** \return Length of the line. */ - T getLength() const { return start.getDistanceFrom(end); } + //! Get length of line + /** \return Length of the line. */ + T getLength() const { return start.getDistanceFrom(end); } - //! Get squared length of the line - /** \return Squared length of line. */ - T getLengthSQ() const { return start.getDistanceFromSQ(end); } + //! Get squared length of the line + /** \return Squared length of line. */ + T getLengthSQ() const { return start.getDistanceFromSQ(end); } - //! Get middle of the line - /** \return center of the line. */ - vector2d getMiddle() const - { - return (start + end)/(T)2; - } + //! Get middle of the line + /** \return center of the line. */ + vector2d getMiddle() const + { + return (start + end) / (T)2; + } - //! Get the vector of the line. - /** \return The vector of the line. */ - vector2d getVector() const { return vector2d( end.X - start.X, end.Y - start.Y); } + //! Get the vector of the line. + /** \return The vector of the line. */ + vector2d getVector() const { return vector2d(end.X - start.X, end.Y - start.Y); } - /*! Check if this segment intersects another segment, - or if segments are coincident (colinear). */ - bool intersectAsSegments( const line2d& other) const - { - // Taken from: - // http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/ + /*! Check if this segment intersects another segment, + or if segments are coincident (colinear). */ + bool intersectAsSegments(const line2d &other) const + { + // Taken from: + // http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/ - // Find the four orientations needed for general and - // special cases - s32 o1 = start.checkOrientation( end, other.start); - s32 o2 = start.checkOrientation( end, other.end); - s32 o3 = other.start.checkOrientation( other.end, start); - s32 o4 = other.start.checkOrientation( other.end, end); + // Find the four orientations needed for general and + // special cases + s32 o1 = start.checkOrientation(end, other.start); + s32 o2 = start.checkOrientation(end, other.end); + s32 o3 = other.start.checkOrientation(other.end, start); + s32 o4 = other.start.checkOrientation(other.end, end); - // General case - if (o1 != o2 && o3 != o4) - return true; + // General case + if (o1 != o2 && o3 != o4) + return true; - // Special Cases to check if segments are colinear - if (o1 == 0 && other.start.isBetweenPoints( start, end)) return true; - if (o2 == 0 && other.end.isBetweenPoints( start, end)) return true; - if (o3 == 0 && start.isBetweenPoints( other.start, other.end)) return true; - if (o4 == 0 && end.isBetweenPoints( other.start, other.end)) return true; + // Special Cases to check if segments are colinear + if (o1 == 0 && other.start.isBetweenPoints(start, end)) + return true; + if (o2 == 0 && other.end.isBetweenPoints(start, end)) + return true; + if (o3 == 0 && start.isBetweenPoints(other.start, other.end)) + return true; + if (o4 == 0 && end.isBetweenPoints(other.start, other.end)) + return true; - return false; // Doesn't fall in any of the above cases - } + return false; // Doesn't fall in any of the above cases + } - /*! Check if 2 segments are incident (intersects in exactly 1 point).*/ - bool incidentSegments( const line2d& other) const - { - return - start.checkOrientation( end, other.start) != start.checkOrientation( end, other.end) - && other.start.checkOrientation( other.end, start) != other.start.checkOrientation( other.end, end); - } + /*! Check if 2 segments are incident (intersects in exactly 1 point).*/ + bool incidentSegments(const line2d &other) const + { + return start.checkOrientation(end, other.start) != start.checkOrientation(end, other.end) && other.start.checkOrientation(other.end, start) != other.start.checkOrientation(other.end, end); + } - /*! Check if 2 lines/segments are parallel or nearly parallel.*/ - bool nearlyParallel( const line2d& line, const T factor = relativeErrorFactor()) const - { - const vector2d a = getVector(); - const vector2d b = line.getVector(); + /*! Check if 2 lines/segments are parallel or nearly parallel.*/ + bool nearlyParallel(const line2d &line, const T factor = relativeErrorFactor()) const + { + const vector2d a = getVector(); + const vector2d b = line.getVector(); - return a.nearlyParallel( b, factor); - } + return a.nearlyParallel(b, factor); + } - /*! returns a intersection point of 2 lines (if lines are not parallel). Behaviour - undefined if lines are parallel or coincident. - It's on optimized intersectWith with checkOnlySegments=false and ignoreCoincidentLines=true - */ - vector2d fastLinesIntersection( const line2d& l) const - { - const f32 commonDenominator = (f32)((l.end.Y - l.start.Y)*(end.X - start.X) - - (l.end.X - l.start.X)*(end.Y - start.Y)); + /*! returns a intersection point of 2 lines (if lines are not parallel). Behaviour + undefined if lines are parallel or coincident. + It's on optimized intersectWith with checkOnlySegments=false and ignoreCoincidentLines=true + */ + vector2d fastLinesIntersection(const line2d &l) const + { + const f32 commonDenominator = (f32)((l.end.Y - l.start.Y) * (end.X - start.X) - + (l.end.X - l.start.X) * (end.Y - start.Y)); - if ( commonDenominator != 0.f ) - { - const f32 numeratorA = (f32)((l.end.X - l.start.X)*(start.Y - l.start.Y) - - (l.end.Y - l.start.Y)*(start.X - l.start.X)); + if (commonDenominator != 0.f) { + const f32 numeratorA = (f32)((l.end.X - l.start.X) * (start.Y - l.start.Y) - + (l.end.Y - l.start.Y) * (start.X - l.start.X)); - const f32 uA = numeratorA / commonDenominator; - - // Calculate the intersection point. - return vector2d ( - (T)(start.X + uA * (end.X - start.X)), - (T)(start.Y + uA * (end.Y - start.Y)) - ); - } - else - return l.start; - } - - /*! Check if this line intersect a segment. The eventual intersection point is returned in "out".*/ - bool lineIntersectSegment( const line2d& segment, vector2d & out) const - { - if (nearlyParallel( segment)) - return false; - - out = fastLinesIntersection( segment); - - return out.isBetweenPoints( segment.start, segment.end); - } - - //! Tests if this line intersects with another line. - /** \param l: Other line to test intersection with. - \param checkOnlySegments: Default is to check intersection between the begin and endpoints. - When set to false the function will check for the first intersection point when extending the lines. - \param out: If there is an intersection, the location of the - intersection will be stored in this vector. - \param ignoreCoincidentLines: When true coincident lines (lines above each other) are never considered as intersecting. - When false the center of the overlapping part is returned. - \return True if there is an intersection, false if not. */ - bool intersectWith(const line2d& l, vector2d& out, bool checkOnlySegments=true, bool ignoreCoincidentLines=false) const - { - // Uses the method given at: - // http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ - const f32 commonDenominator = (f32)((l.end.Y - l.start.Y)*(end.X - start.X) - - (l.end.X - l.start.X)*(end.Y - start.Y)); - - const f32 numeratorA = (f32)((l.end.X - l.start.X)*(start.Y - l.start.Y) - - (l.end.Y - l.start.Y)*(start.X -l.start.X)); - - const f32 numeratorB = (f32)((end.X - start.X)*(start.Y - l.start.Y) - - (end.Y - start.Y)*(start.X -l.start.X)); - - if(equals(commonDenominator, 0.f)) - { - // The lines are either coincident or parallel - // if both numerators are 0, the lines are coincident - if(!ignoreCoincidentLines && equals(numeratorA, 0.f) && equals(numeratorB, 0.f)) - { - // Try and find a common endpoint - if(l.start == start || l.end == start) - out = start; - else if(l.end == end || l.start == end) - out = end; - // now check if the two segments are disjunct - else if (l.start.X>start.X && l.end.X>start.X && l.start.X>end.X && l.end.X>end.X) - return false; - else if (l.start.Y>start.Y && l.end.Y>start.Y && l.start.Y>end.Y && l.end.Y>end.Y) - return false; - else if (l.start.X maxp; - vector2d minp; - if ((start.X>l.start.X && start.X>l.end.X && start.X>end.X) || (start.Y>l.start.Y && start.Y>l.end.Y && start.Y>end.Y)) - maxp=start; - else if ((end.X>l.start.X && end.X>l.end.X && end.X>start.X) || (end.Y>l.start.Y && end.Y>l.end.Y && end.Y>start.Y)) - maxp=end; - else if ((l.start.X>start.X && l.start.X>l.end.X && l.start.X>end.X) || (l.start.Y>start.Y && l.start.Y>l.end.Y && l.start.Y>end.Y)) - maxp=l.start; - else - maxp=l.end; - if (maxp != start && ((start.X(); - if (start != maxp && start != minp) - out += start; - if (end != maxp && end != minp) - out += end; - if (l.start != maxp && l.start != minp) - out += l.start; - if (l.end != maxp && l.end != minp) - out += l.end; - out.X = (T)(out.X/2); - out.Y = (T)(out.Y/2); - } - - return true; // coincident - } - - return false; // parallel - } - - // Get the point of intersection on this line, checking that - // it is within the line segment. const f32 uA = numeratorA / commonDenominator; - if (checkOnlySegments) - { - if(uA < 0.f || uA > 1.f) - return false; // Outside the line segment - - const f32 uB = numeratorB / commonDenominator; - if(uB < 0.f || uB > 1.f) - return false; // Outside the line segment - } // Calculate the intersection point. - out.X = (T)(start.X + uA * (end.X - start.X)); - out.Y = (T)(start.Y + uA * (end.Y - start.Y)); - return true; - } + return vector2d( + (T)(start.X + uA * (end.X - start.X)), + (T)(start.Y + uA * (end.Y - start.Y))); + } else + return l.start; + } - //! Get unit vector of the line. - /** \return Unit vector of this line. */ - vector2d getUnitVector() const - { - T len = (T)(1.0 / getLength()); - return vector2d((end.X - start.X) * len, (end.Y - start.Y) * len); - } + /*! Check if this line intersect a segment. The eventual intersection point is returned in "out".*/ + bool lineIntersectSegment(const line2d &segment, vector2d &out) const + { + if (nearlyParallel(segment)) + return false; - //! Get angle between this line and given line. - /** \param l Other line for test. - \return Angle in degrees. */ - f64 getAngleWith(const line2d& l) const - { - vector2d vect = getVector(); - vector2d vect2 = l.getVector(); - return vect.getAngleWith(vect2); - } + out = fastLinesIntersection(segment); - //! Tells us if the given point lies to the left, right, or on the line. - /** \return 0 if the point is on the line - <0 if to the left, or >0 if to the right. */ - T getPointOrientation(const vector2d& point) const - { - return ( (end.X - start.X) * (point.Y - start.Y) - - (point.X - start.X) * (end.Y - start.Y) ); - } + return out.isBetweenPoints(segment.start, segment.end); + } - //! Check if the given point is a member of the line - /** \return True if point is between start and end, else false. */ - bool isPointOnLine(const vector2d& point) const - { - T d = getPointOrientation(point); - return (d == 0 && point.isBetweenPoints(start, end)); - } + //! Tests if this line intersects with another line. + /** \param l: Other line to test intersection with. + \param checkOnlySegments: Default is to check intersection between the begin and endpoints. + When set to false the function will check for the first intersection point when extending the lines. + \param out: If there is an intersection, the location of the + intersection will be stored in this vector. + \param ignoreCoincidentLines: When true coincident lines (lines above each other) are never considered as intersecting. + When false the center of the overlapping part is returned. + \return True if there is an intersection, false if not. */ + bool intersectWith(const line2d &l, vector2d &out, bool checkOnlySegments = true, bool ignoreCoincidentLines = false) const + { + // Uses the method given at: + // http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ + const f32 commonDenominator = (f32)((l.end.Y - l.start.Y) * (end.X - start.X) - + (l.end.X - l.start.X) * (end.Y - start.Y)); - //! Check if the given point is between start and end of the line. - /** Assumes that the point is already somewhere on the line. */ - bool isPointBetweenStartAndEnd(const vector2d& point) const - { - return point.isBetweenPoints(start, end); - } + const f32 numeratorA = (f32)((l.end.X - l.start.X) * (start.Y - l.start.Y) - + (l.end.Y - l.start.Y) * (start.X - l.start.X)); - //! Get the closest point on this line to a point - /** \param point: Starting search at this point - \param checkOnlySegments: Default (true) is to return a point on the line-segment (between begin and end) of the line. - When set to false the function will check for the first the closest point on the the line even when outside the segment. */ - vector2d getClosestPoint(const vector2d& point, bool checkOnlySegments=true) const - { - vector2d c((f64)(point.X-start.X), (f64)(point.Y- start.Y)); - vector2d v((f64)(end.X-start.X), (f64)(end.Y-start.Y)); - f64 d = v.getLength(); - if ( d == 0 ) // can't tell much when the line is just a single point - return start; - v /= d; - f64 t = v.dotProduct(c); + const f32 numeratorB = (f32)((end.X - start.X) * (start.Y - l.start.Y) - + (end.Y - start.Y) * (start.X - l.start.X)); - if ( checkOnlySegments ) - { - if (t < 0) return vector2d((T)start.X, (T)start.Y); - if (t > d) return vector2d((T)end.X, (T)end.Y); + if (equals(commonDenominator, 0.f)) { + // The lines are either coincident or parallel + // if both numerators are 0, the lines are coincident + if (!ignoreCoincidentLines && equals(numeratorA, 0.f) && equals(numeratorB, 0.f)) { + // Try and find a common endpoint + if (l.start == start || l.end == start) + out = start; + else if (l.end == end || l.start == end) + out = end; + // now check if the two segments are disjunct + else if (l.start.X > start.X && l.end.X > start.X && l.start.X > end.X && l.end.X > end.X) + return false; + else if (l.start.Y > start.Y && l.end.Y > start.Y && l.start.Y > end.Y && l.end.Y > end.Y) + return false; + else if (l.start.X < start.X && l.end.X < start.X && l.start.X < end.X && l.end.X < end.X) + return false; + else if (l.start.Y < start.Y && l.end.Y < start.Y && l.start.Y < end.Y && l.end.Y < end.Y) + return false; + // else the lines are overlapping to some extent + else { + // find the points which are not contributing to the + // common part + vector2d maxp; + vector2d minp; + if ((start.X > l.start.X && start.X > l.end.X && start.X > end.X) || (start.Y > l.start.Y && start.Y > l.end.Y && start.Y > end.Y)) + maxp = start; + else if ((end.X > l.start.X && end.X > l.end.X && end.X > start.X) || (end.Y > l.start.Y && end.Y > l.end.Y && end.Y > start.Y)) + maxp = end; + else if ((l.start.X > start.X && l.start.X > l.end.X && l.start.X > end.X) || (l.start.Y > start.Y && l.start.Y > l.end.Y && l.start.Y > end.Y)) + maxp = l.start; + else + maxp = l.end; + if (maxp != start && ((start.X < l.start.X && start.X < l.end.X && start.X < end.X) || (start.Y < l.start.Y && start.Y < l.end.Y && start.Y < end.Y))) + minp = start; + else if (maxp != end && ((end.X < l.start.X && end.X < l.end.X && end.X < start.X) || (end.Y < l.start.Y && end.Y < l.end.Y && end.Y < start.Y))) + minp = end; + else if (maxp != l.start && ((l.start.X < start.X && l.start.X < l.end.X && l.start.X < end.X) || (l.start.Y < start.Y && l.start.Y < l.end.Y && l.start.Y < end.Y))) + minp = l.start; + else + minp = l.end; + + // one line is contained in the other. Pick the center + // of the remaining points, which overlap for sure + out = core::vector2d(); + if (start != maxp && start != minp) + out += start; + if (end != maxp && end != minp) + out += end; + if (l.start != maxp && l.start != minp) + out += l.start; + if (l.end != maxp && l.end != minp) + out += l.end; + out.X = (T)(out.X / 2); + out.Y = (T)(out.Y / 2); + } + + return true; // coincident } - v *= t; - return vector2d((T)(start.X + v.X), (T)(start.Y + v.Y)); + return false; // parallel } - //! Start point of the line. - vector2d start; - //! End point of the line. - vector2d end; -}; + // Get the point of intersection on this line, checking that + // it is within the line segment. + const f32 uA = numeratorA / commonDenominator; + if (checkOnlySegments) { + if (uA < 0.f || uA > 1.f) + return false; // Outside the line segment - // partial specialization to optimize lines (avoiding casts) - template <> - inline vector2df line2d::getClosestPoint(const vector2df& point, bool checkOnlySegments) const + const f32 uB = numeratorB / commonDenominator; + if (uB < 0.f || uB > 1.f) + return false; // Outside the line segment + } + + // Calculate the intersection point. + out.X = (T)(start.X + uA * (end.X - start.X)); + out.Y = (T)(start.Y + uA * (end.Y - start.Y)); + return true; + } + + //! Get unit vector of the line. + /** \return Unit vector of this line. */ + vector2d getUnitVector() const { - const vector2df c = point - start; - vector2df v = end - start; - const f32 d = (f32)v.getLength(); - if ( d == 0 ) // can't tell much when the line is just a single point + T len = (T)(1.0 / getLength()); + return vector2d((end.X - start.X) * len, (end.Y - start.Y) * len); + } + + //! Get angle between this line and given line. + /** \param l Other line for test. + \return Angle in degrees. */ + f64 getAngleWith(const line2d &l) const + { + vector2d vect = getVector(); + vector2d vect2 = l.getVector(); + return vect.getAngleWith(vect2); + } + + //! Tells us if the given point lies to the left, right, or on the line. + /** \return 0 if the point is on the line + <0 if to the left, or >0 if to the right. */ + T getPointOrientation(const vector2d &point) const + { + return ((end.X - start.X) * (point.Y - start.Y) - + (point.X - start.X) * (end.Y - start.Y)); + } + + //! Check if the given point is a member of the line + /** \return True if point is between start and end, else false. */ + bool isPointOnLine(const vector2d &point) const + { + T d = getPointOrientation(point); + return (d == 0 && point.isBetweenPoints(start, end)); + } + + //! Check if the given point is between start and end of the line. + /** Assumes that the point is already somewhere on the line. */ + bool isPointBetweenStartAndEnd(const vector2d &point) const + { + return point.isBetweenPoints(start, end); + } + + //! Get the closest point on this line to a point + /** \param point: Starting search at this point + \param checkOnlySegments: Default (true) is to return a point on the line-segment (between begin and end) of the line. + When set to false the function will check for the first the closest point on the the line even when outside the segment. */ + vector2d getClosestPoint(const vector2d &point, bool checkOnlySegments = true) const + { + vector2d c((f64)(point.X - start.X), (f64)(point.Y - start.Y)); + vector2d v((f64)(end.X - start.X), (f64)(end.Y - start.Y)); + f64 d = v.getLength(); + if (d == 0) // can't tell much when the line is just a single point return start; v /= d; - const f32 t = v.dotProduct(c); + f64 t = v.dotProduct(c); - if ( checkOnlySegments ) - { - if (t < 0) return start; - if (t > d) return end; + if (checkOnlySegments) { + if (t < 0) + return vector2d((T)start.X, (T)start.Y); + if (t > d) + return vector2d((T)end.X, (T)end.Y); } v *= t; - return start + v; + return vector2d((T)(start.X + v.X), (T)(start.Y + v.Y)); } + //! Start point of the line. + vector2d start; + //! End point of the line. + vector2d end; +}; - //! Typedef for an f32 line. - typedef line2d line2df; - //! Typedef for an integer line. - typedef line2d line2di; +// partial specialization to optimize lines (avoiding casts) +template <> +inline vector2df line2d::getClosestPoint(const vector2df &point, bool checkOnlySegments) const +{ + const vector2df c = point - start; + vector2df v = end - start; + const f32 d = (f32)v.getLength(); + if (d == 0) // can't tell much when the line is just a single point + return start; + v /= d; + const f32 t = v.dotProduct(c); + + if (checkOnlySegments) { + if (t < 0) + return start; + if (t > d) + return end; + } + + v *= t; + return start + v; +} + +//! Typedef for an f32 line. +typedef line2d line2df; +//! Typedef for an integer line. +typedef line2d line2di; } // end namespace core } // end namespace irr - - diff --git a/include/line3d.h b/include/line3d.h index 0372ba41..ea198fba 100644 --- a/include/line3d.h +++ b/include/line3d.h @@ -16,127 +16,150 @@ namespace core template class line3d { - public: +public: + //! Default constructor + /** line from (0,0,0) to (1,1,1) */ + constexpr line3d() : + start(0, 0, 0), end(1, 1, 1) {} + //! Constructor with two points + constexpr line3d(T xa, T ya, T za, T xb, T yb, T zb) : + start(xa, ya, za), end(xb, yb, zb) {} + //! Constructor with two points as vectors + constexpr line3d(const vector3d &start, const vector3d &end) : + start(start), end(end) {} - //! Default constructor - /** line from (0,0,0) to (1,1,1) */ - constexpr line3d() : start(0,0,0), end(1,1,1) {} - //! Constructor with two points - constexpr line3d(T xa, T ya, T za, T xb, T yb, T zb) : start(xa, ya, za), end(xb, yb, zb) {} - //! Constructor with two points as vectors - constexpr line3d(const vector3d& start, const vector3d& end) : start(start), end(end) {} + // operators - // operators + line3d operator+(const vector3d &point) const { return line3d(start + point, end + point); } + line3d &operator+=(const vector3d &point) + { + start += point; + end += point; + return *this; + } - line3d operator+(const vector3d& point) const { return line3d(start + point, end + point); } - line3d& operator+=(const vector3d& point) { start += point; end += point; return *this; } + line3d operator-(const vector3d &point) const { return line3d(start - point, end - point); } + line3d &operator-=(const vector3d &point) + { + start -= point; + end -= point; + return *this; + } - line3d operator-(const vector3d& point) const { return line3d(start - point, end - point); } - line3d& operator-=(const vector3d& point) { start -= point; end -= point; return *this; } + constexpr bool operator==(const line3d &other) const + { + return (start == other.start && end == other.end) || (end == other.start && start == other.end); + } + constexpr bool operator!=(const line3d &other) const + { + return !(start == other.start && end == other.end) || (end == other.start && start == other.end); + } - constexpr bool operator==(const line3d& other) const - { return (start==other.start && end==other.end) || (end==other.start && start==other.end);} - constexpr bool operator!=(const line3d& other) const - { return !(start==other.start && end==other.end) || (end==other.start && start==other.end);} + // functions + //! Set this line to a new line going through the two points. + void setLine(const T &xa, const T &ya, const T &za, const T &xb, const T &yb, const T &zb) + { + start.set(xa, ya, za); + end.set(xb, yb, zb); + } + //! Set this line to a new line going through the two points. + void setLine(const vector3d &nstart, const vector3d &nend) + { + start.set(nstart); + end.set(nend); + } + //! Set this line to new line given as parameter. + void setLine(const line3d &line) + { + start.set(line.start); + end.set(line.end); + } - // functions - //! Set this line to a new line going through the two points. - void setLine(const T& xa, const T& ya, const T& za, const T& xb, const T& yb, const T& zb) - {start.set(xa, ya, za); end.set(xb, yb, zb);} - //! Set this line to a new line going through the two points. - void setLine(const vector3d& nstart, const vector3d& nend) - {start.set(nstart); end.set(nend);} - //! Set this line to new line given as parameter. - void setLine(const line3d& line) - {start.set(line.start); end.set(line.end);} + //! Get length of line + /** \return Length of line. */ + T getLength() const { return start.getDistanceFrom(end); } - //! Get length of line - /** \return Length of line. */ - T getLength() const { return start.getDistanceFrom(end); } + //! Get squared length of line + /** \return Squared length of line. */ + T getLengthSQ() const { return start.getDistanceFromSQ(end); } - //! Get squared length of line - /** \return Squared length of line. */ - T getLengthSQ() const { return start.getDistanceFromSQ(end); } + //! Get middle of line + /** \return Center of line. */ + vector3d getMiddle() const + { + return (start + end) / (T)2; + } - //! Get middle of line - /** \return Center of line. */ - vector3d getMiddle() const - { - return (start + end)/(T)2; - } + //! Get vector of line + /** \return vector of line. */ + vector3d getVector() const + { + return end - start; + } - //! Get vector of line - /** \return vector of line. */ - vector3d getVector() const - { - return end - start; - } + //! Check if the given point is between start and end of the line. + /** Assumes that the point is already somewhere on the line. + \param point The point to test. + \return True if point is on the line between start and end, else false. + */ + bool isPointBetweenStartAndEnd(const vector3d &point) const + { + return point.isBetweenPoints(start, end); + } - //! Check if the given point is between start and end of the line. - /** Assumes that the point is already somewhere on the line. - \param point The point to test. - \return True if point is on the line between start and end, else false. - */ - bool isPointBetweenStartAndEnd(const vector3d& point) const - { - return point.isBetweenPoints(start, end); - } + //! Get the closest point on this line to a point + /** \param point The point to compare to. + \return The nearest point which is part of the line. */ + vector3d getClosestPoint(const vector3d &point) const + { + vector3d c = point - start; + vector3d v = end - start; + T d = (T)v.getLength(); + v /= d; + T t = v.dotProduct(c); - //! Get the closest point on this line to a point - /** \param point The point to compare to. - \return The nearest point which is part of the line. */ - vector3d getClosestPoint(const vector3d& point) const - { - vector3d c = point - start; - vector3d v = end - start; - T d = (T)v.getLength(); - v /= d; - T t = v.dotProduct(c); + if (t < (T)0.0) + return start; + if (t > d) + return end; - if (t < (T)0.0) - return start; - if (t > d) - return end; + v *= t; + return start + v; + } - v *= t; - return start + v; - } + //! Check if the line intersects with a sphere + /** \param sorigin: Origin of the sphere. + \param sradius: Radius of the sphere. + \param outdistance: The distance to the first intersection point. + \return True if there is an intersection. + If there is one, the distance to the first intersection point + is stored in outdistance. */ + bool getIntersectionWithSphere(const vector3d &sorigin, T sradius, f64 &outdistance) const + { + const vector3d q = sorigin - start; + T c = q.getLength(); + T v = q.dotProduct(getVector().normalize()); + T d = sradius * sradius - (c * c - v * v); - //! Check if the line intersects with a sphere - /** \param sorigin: Origin of the sphere. - \param sradius: Radius of the sphere. - \param outdistance: The distance to the first intersection point. - \return True if there is an intersection. - If there is one, the distance to the first intersection point - is stored in outdistance. */ - bool getIntersectionWithSphere(const vector3d& sorigin, T sradius, f64& outdistance) const - { - const vector3d q = sorigin - start; - T c = q.getLength(); - T v = q.dotProduct(getVector().normalize()); - T d = sradius * sradius - (c*c - v*v); + if (d < 0.0) + return false; - if (d < 0.0) - return false; + outdistance = v - core::squareroot(d); + return true; + } - outdistance = v - core::squareroot ( d ); - return true; - } + // member variables - // member variables - - //! Start point of line - vector3d start; - //! End point of line - vector3d end; + //! Start point of line + vector3d start; + //! End point of line + vector3d end; }; - //! Typedef for an f32 line. - typedef line3d line3df; - //! Typedef for an integer line. - typedef line3d line3di; +//! Typedef for an f32 line. +typedef line3d line3df; +//! Typedef for an integer line. +typedef line3d line3di; } // end namespace core } // end namespace irr - - diff --git a/include/matrix4.h b/include/matrix4.h index 3e5e0c44..11994e85 100644 --- a/include/matrix4.h +++ b/include/matrix4.h @@ -16,1056 +16,1047 @@ // enable this to keep track of changes to the matrix // and make simpler identity check for seldom changing matrices // otherwise identity check will always compare the elements -//#define USE_MATRIX_TEST +// #define USE_MATRIX_TEST namespace irr { namespace core { - //! 4x4 matrix. Mostly used as transformation matrix for 3d calculations. - /** The matrix is a D3D style matrix, row major with translations in the 4th row. */ - template - class CMatrix4 +//! 4x4 matrix. Mostly used as transformation matrix for 3d calculations. +/** The matrix is a D3D style matrix, row major with translations in the 4th row. */ +template +class CMatrix4 +{ +public: + //! Constructor Flags + enum eConstructor { - public: - - //! Constructor Flags - enum eConstructor - { - EM4CONST_NOTHING = 0, - EM4CONST_COPY, - EM4CONST_IDENTITY, - EM4CONST_TRANSPOSED, - EM4CONST_INVERSE, - EM4CONST_INVERSE_TRANSPOSED - }; - - //! Default constructor - /** \param constructor Choose the initialization style */ - CMatrix4( eConstructor constructor = EM4CONST_IDENTITY ); - - //! Constructor with value initialization - constexpr CMatrix4(const T& r0c0, const T& r0c1, const T& r0c2, const T& r0c3, - const T& r1c0, const T& r1c1, const T& r1c2, const T& r1c3, - const T& r2c0, const T& r2c1, const T& r2c2, const T& r2c3, - const T& r3c0, const T& r3c1, const T& r3c2, const T& r3c3) - { - M[0] = r0c0; M[1] = r0c1; M[2] = r0c2; M[3] = r0c3; - M[4] = r1c0; M[5] = r1c1; M[6] = r1c2; M[7] = r1c3; - M[8] = r2c0; M[9] = r2c1; M[10] = r2c2; M[11] = r2c3; - M[12] = r3c0; M[13] = r3c1; M[14] = r3c2; M[15] = r3c3; - } - - //! Copy constructor - /** \param other Other matrix to copy from - \param constructor Choose the initialization style */ - CMatrix4(const CMatrix4& other, eConstructor constructor = EM4CONST_COPY); - - //! Simple operator for directly accessing every element of the matrix. - T& operator()(const s32 row, const s32 col) - { -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return M[ row * 4 + col ]; - } - - //! Simple operator for directly accessing every element of the matrix. - const T& operator()(const s32 row, const s32 col) const { return M[row * 4 + col]; } - - //! Simple operator for linearly accessing every element of the matrix. - T& operator[](u32 index) - { -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return M[index]; - } - - //! Simple operator for linearly accessing every element of the matrix. - const T& operator[](u32 index) const { return M[index]; } - - //! Sets this matrix equal to the other matrix. - CMatrix4& operator=(const CMatrix4 &other) = default; - - //! Sets all elements of this matrix to the value. - inline CMatrix4& operator=(const T& scalar); - - //! Returns pointer to internal array - const T* pointer() const { return M; } - T* pointer() - { -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return M; - } - - //! Returns true if other matrix is equal to this matrix. - constexpr bool operator==(const CMatrix4 &other) const - { -#if defined ( USE_MATRIX_TEST ) - if (definitelyIdentityMatrix && other.definitelyIdentityMatrix) - return true; -#endif - for (s32 i = 0; i < 16; ++i) - if (M[i] != other.M[i]) - return false; - - return true; - } - - //! Returns true if other matrix is not equal to this matrix. - constexpr bool operator!=(const CMatrix4 &other) const - { - return !(*this == other); - } - - //! Add another matrix. - CMatrix4 operator+(const CMatrix4& other) const; - - //! Add another matrix. - CMatrix4& operator+=(const CMatrix4& other); - - //! Subtract another matrix. - CMatrix4 operator-(const CMatrix4& other) const; - - //! Subtract another matrix. - CMatrix4& operator-=(const CMatrix4& other); - - //! set this matrix to the product of two matrices - /** Calculate b*a */ - inline CMatrix4& setbyproduct(const CMatrix4& other_a,const CMatrix4& other_b ); - - //! Set this matrix to the product of two matrices - /** Calculate b*a, no optimization used, - use it if you know you never have an identity matrix */ - CMatrix4& setbyproduct_nocheck(const CMatrix4& other_a,const CMatrix4& other_b ); - - //! Multiply by another matrix. - /** Calculate other*this */ - CMatrix4 operator*(const CMatrix4& other) const; - - //! Multiply by another matrix. - /** Like calling: (*this) = (*this) * other - */ - CMatrix4& operator*=(const CMatrix4& other); - - //! Multiply by scalar. - CMatrix4 operator*(const T& scalar) const; - - //! Multiply by scalar. - CMatrix4& operator*=(const T& scalar); - - //! Set matrix to identity. - inline CMatrix4& makeIdentity(); - - //! Returns true if the matrix is the identity matrix - inline bool isIdentity() const; - - //! Returns true if the matrix is orthogonal - inline bool isOrthogonal() const; - - //! Returns true if the matrix is the identity matrix - bool isIdentity_integer_base () const; - - //! Set the translation of the current matrix. Will erase any previous values. - CMatrix4& setTranslation( const vector3d& translation ); - - //! Gets the current translation - vector3d getTranslation() const; - - //! Set the inverse translation of the current matrix. Will erase any previous values. - CMatrix4& setInverseTranslation( const vector3d& translation ); - - //! Make a rotation matrix from Euler angles. The 4th row and column are unmodified. - inline CMatrix4& setRotationRadians( const vector3d& rotation ); - - //! Make a rotation matrix from Euler angles. The 4th row and column are unmodified. - CMatrix4& setRotationDegrees( const vector3d& rotation ); - - //! Get the rotation, as set by setRotation() when you already know the scale used to create the matrix - /** NOTE: The scale needs to be the correct one used to create this matrix. - You can _not_ use the result of getScale(), but have to save your scale - variable in another place (like ISceneNode does). - NOTE: No scale value can be 0 or the result is undefined. - NOTE: It does not necessarily return the *same* Euler angles as those set by setRotationDegrees(), - but the rotation will be equivalent, i.e. will have the same result when used to rotate a vector or node. - NOTE: It will (usually) give wrong results when further transformations have been added in the matrix (like shear). - WARNING: There have been troubles with this function over the years and we may still have missed some corner cases. - It's generally safer to keep the rotation and scale you used to create the matrix around and work with those. - */ - core::vector3d getRotationDegrees(const vector3d& scale) const; - - //! Returns the rotation, as set by setRotation(). - /** NOTE: You will have the same end-rotation as used in setRotation, but it might not use the same axis values. - NOTE: This only works correct if no other matrix operations have been done on the inner 3x3 matrix besides - setting rotation (so no scale/shear). Thought it (probably) works as long as scale doesn't flip handedness. - NOTE: It does not necessarily return the *same* Euler angles as those set by setRotationDegrees(), - but the rotation will be equivalent, i.e. will have the same result when used to rotate a vector or node. - */ - core::vector3d getRotationDegrees() const; - - //! Make an inverted rotation matrix from Euler angles. - /** The 4th row and column are unmodified. */ - inline CMatrix4& setInverseRotationRadians( const vector3d& rotation ); - - //! Make an inverted rotation matrix from Euler angles. - /** The 4th row and column are unmodified. */ - inline CMatrix4& setInverseRotationDegrees( const vector3d& rotation ); - - //! Make a rotation matrix from angle and axis, assuming left handed rotation. - /** The 4th row and column are unmodified. */ - inline CMatrix4& setRotationAxisRadians(const T& angle, const vector3d& axis); - - //! Set Scale - CMatrix4& setScale( const vector3d& scale ); - - //! Set Scale - CMatrix4& setScale( const T scale ) { return setScale(core::vector3d(scale,scale,scale)); } - - //! Get Scale - core::vector3d getScale() const; - - //! Translate a vector by the inverse of the translation part of this matrix. - void inverseTranslateVect( vector3df& vect ) const; - - //! Rotate a vector by the inverse of the rotation part of this matrix. - void inverseRotateVect( vector3df& vect ) const; - - //! Rotate a vector by the rotation part of this matrix. - void rotateVect( vector3df& vect ) const; - - //! An alternate transform vector method, writing into a second vector - void rotateVect(core::vector3df& out, const core::vector3df& in) const; - - //! An alternate transform vector method, writing into an array of 3 floats - void rotateVect(T *out,const core::vector3df &in) const; - - //! Transforms the vector by this matrix - /** This operation is performed as if the vector was 4d with the 4th component =1 */ - void transformVect( vector3df& vect) const; - - //! Transforms input vector by this matrix and stores result in output vector - /** This operation is performed as if the vector was 4d with the 4th component =1 */ - void transformVect( vector3df& out, const vector3df& in ) const; - - //! An alternate transform vector method, writing into an array of 4 floats - /** This operation is performed as if the vector was 4d with the 4th component =1. - NOTE: out[3] will be written to (4th vector component)*/ - void transformVect(T *out,const core::vector3df &in) const; - - //! An alternate transform vector method, reading from and writing to an array of 3 floats - /** This operation is performed as if the vector was 4d with the 4th component =1 - NOTE: out[3] will be written to (4th vector component)*/ - void transformVec3(T *out, const T * in) const; - - //! An alternate transform vector method, reading from and writing to an array of 4 floats - void transformVec4(T *out, const T * in) const; - - //! Translate a vector by the translation part of this matrix. - /** This operation is performed as if the vector was 4d with the 4th component =1 */ - void translateVect( vector3df& vect ) const; - - //! Transforms a plane by this matrix - void transformPlane( core::plane3d &plane) const; - - //! Transforms a plane by this matrix - void transformPlane( const core::plane3d &in, core::plane3d &out) const; - - //! Transforms a axis aligned bounding box - void transformBoxEx(core::aabbox3d& box) const; - - //! Multiplies this matrix by a 1x4 matrix - void multiplyWith1x4Matrix(T* matrix) const; - - //! Calculates inverse of matrix. Slow. - /** \return Returns false if there is no inverse matrix.*/ - bool makeInverse(); - - - //! Inverts a primitive matrix which only contains a translation and a rotation - /** \param out: where result matrix is written to. */ - bool getInversePrimitive ( CMatrix4& out ) const; - - //! Gets the inverse matrix of this one - /** \param out: where result matrix is written to. - \return Returns false if there is no inverse matrix. */ - bool getInverse(CMatrix4& out) const; - - //! Builds a right-handed perspective projection matrix based on a field of view - //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). - CMatrix4& buildProjectionMatrixPerspectiveFovRH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a left-handed perspective projection matrix based on a field of view - CMatrix4& buildProjectionMatrixPerspectiveFovLH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a left-handed perspective projection matrix based on a field of view, with far plane at infinity - CMatrix4& buildProjectionMatrixPerspectiveFovInfinityLH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 epsilon=0); - - //! Builds a right-handed perspective projection matrix. - CMatrix4& buildProjectionMatrixPerspectiveRH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a left-handed perspective projection matrix. - CMatrix4& buildProjectionMatrixPerspectiveLH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a left-handed orthogonal projection matrix. - //\param zClipFromZero: Clipping of z can be projected from 0 to 1 when true (D3D style) and from -1 to 1 when false (OGL style). - CMatrix4& buildProjectionMatrixOrthoLH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a right-handed orthogonal projection matrix. - CMatrix4& buildProjectionMatrixOrthoRH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero=true); - - //! Builds a left-handed look-at matrix. - CMatrix4& buildCameraLookAtMatrixLH( - const vector3df& position, - const vector3df& target, - const vector3df& upVector); - - //! Builds a right-handed look-at matrix. - CMatrix4& buildCameraLookAtMatrixRH( - const vector3df& position, - const vector3df& target, - const vector3df& upVector); - - //! Builds a matrix that flattens geometry into a plane. - /** \param light: light source - \param plane: plane into which the geometry if flattened into - \param point: value between 0 and 1, describing the light source. - If this is 1, it is a point light, if it is 0, it is a directional light. */ - CMatrix4& buildShadowMatrix(const core::vector3df& light, core::plane3df plane, f32 point=1.0f); - - //! Builds a matrix which transforms a normalized Device Coordinate to Device Coordinates. - /** Used to scale <-1,-1><1,1> to viewport, for example from <-1,-1> <1,1> to the viewport <0,0><0,640> */ - CMatrix4& buildNDCToDCMatrix( const core::rect& area, f32 zScale); - - //! Creates a new matrix as interpolated matrix from two other ones. - /** \param b: other matrix to interpolate with - \param time: Must be a value between 0 and 1. */ - CMatrix4 interpolate(const core::CMatrix4& b, f32 time) const; - - //! Gets transposed matrix - CMatrix4 getTransposed() const; - - //! Gets transposed matrix - inline void getTransposed( CMatrix4& dest ) const; - - //! Builds a matrix that rotates from one vector to another - /** \param from: vector to rotate from - \param to: vector to rotate to - */ - CMatrix4& buildRotateFromTo(const core::vector3df& from, const core::vector3df& to); - - //! Builds a combined matrix which translates to a center before rotation and translates from origin afterwards - /** \param center Position to rotate around - \param translate Translation applied after the rotation - */ - void setRotationCenter(const core::vector3df& center, const core::vector3df& translate); - - //! Builds a matrix which rotates a source vector to a look vector over an arbitrary axis - /** \param camPos: viewer position in world coo - \param center: object position in world-coo and rotation pivot - \param translation: object final translation from center - \param axis: axis to rotate about - \param from: source vector to rotate from - */ - void buildAxisAlignedBillboard(const core::vector3df& camPos, - const core::vector3df& center, - const core::vector3df& translation, - const core::vector3df& axis, - const core::vector3df& from); - - /* - construct 2D Texture transformations - rotate about center, scale, and transform. - */ - //! Set to a texture transformation matrix with the given parameters. - CMatrix4& buildTextureTransform( f32 rotateRad, - const core::vector2df &rotatecenter, - const core::vector2df &translate, - const core::vector2df &scale); - - //! Set texture transformation rotation - /** Rotate about z axis, recenter at (0.5,0.5). - Doesn't clear other elements than those affected - \param radAngle Angle in radians - \return Altered matrix */ - CMatrix4& setTextureRotationCenter( f32 radAngle ); - - //! Set texture transformation translation - /** Doesn't clear other elements than those affected. - \param x Offset on x axis - \param y Offset on y axis - \return Altered matrix */ - CMatrix4& setTextureTranslate( f32 x, f32 y ); - - //! Get texture transformation translation - /** \param x returns offset on x axis - \param y returns offset on y axis */ - void getTextureTranslate( f32& x, f32& y ) const; - - //! Set texture transformation translation, using a transposed representation - /** Doesn't clear other elements than those affected. - \param x Offset on x axis - \param y Offset on y axis - \return Altered matrix */ - CMatrix4& setTextureTranslateTransposed( f32 x, f32 y ); - - //! Set texture transformation scale - /** Doesn't clear other elements than those affected. - \param sx Scale factor on x axis - \param sy Scale factor on y axis - \return Altered matrix. */ - CMatrix4& setTextureScale( f32 sx, f32 sy ); - - //! Get texture transformation scale - /** \param sx Returns x axis scale factor - \param sy Returns y axis scale factor */ - void getTextureScale( f32& sx, f32& sy ) const; - - //! Set texture transformation scale, and recenter at (0.5,0.5) - /** Doesn't clear other elements than those affected. - \param sx Scale factor on x axis - \param sy Scale factor on y axis - \return Altered matrix. */ - CMatrix4& setTextureScaleCenter( f32 sx, f32 sy ); - - //! Sets all matrix data members at once - CMatrix4& setM(const T* data); - - //! Sets if the matrix is definitely identity matrix - void setDefinitelyIdentityMatrix( bool isDefinitelyIdentityMatrix); - - //! Gets if the matrix is definitely identity matrix - bool getDefinitelyIdentityMatrix() const; - - //! Compare two matrices using the equal method - bool equals(const core::CMatrix4& other, const T tolerance=(T)ROUNDING_ERROR_f64) const; - - private: - //! Matrix data, stored in row-major order - T M[16]; -#if defined ( USE_MATRIX_TEST ) - //! Flag is this matrix is identity matrix - mutable u32 definitelyIdentityMatrix; -#endif - + EM4CONST_NOTHING = 0, + EM4CONST_COPY, + EM4CONST_IDENTITY, + EM4CONST_TRANSPOSED, + EM4CONST_INVERSE, + EM4CONST_INVERSE_TRANSPOSED }; - // Default constructor - template - inline CMatrix4::CMatrix4( eConstructor constructor ) -#if defined ( USE_MATRIX_TEST ) - : definitelyIdentityMatrix(BIT_UNTESTED) + //! Default constructor + /** \param constructor Choose the initialization style */ + CMatrix4(eConstructor constructor = EM4CONST_IDENTITY); + + //! Constructor with value initialization + constexpr CMatrix4(const T &r0c0, const T &r0c1, const T &r0c2, const T &r0c3, + const T &r1c0, const T &r1c1, const T &r1c2, const T &r1c3, + const T &r2c0, const T &r2c1, const T &r2c2, const T &r2c3, + const T &r3c0, const T &r3c1, const T &r3c2, const T &r3c3) + { + M[0] = r0c0; + M[1] = r0c1; + M[2] = r0c2; + M[3] = r0c3; + M[4] = r1c0; + M[5] = r1c1; + M[6] = r1c2; + M[7] = r1c3; + M[8] = r2c0; + M[9] = r2c1; + M[10] = r2c2; + M[11] = r2c3; + M[12] = r3c0; + M[13] = r3c1; + M[14] = r3c2; + M[15] = r3c3; + } + + //! Copy constructor + /** \param other Other matrix to copy from + \param constructor Choose the initialization style */ + CMatrix4(const CMatrix4 &other, eConstructor constructor = EM4CONST_COPY); + + //! Simple operator for directly accessing every element of the matrix. + T &operator()(const s32 row, const s32 col) + { +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; #endif - { - switch ( constructor ) - { - case EM4CONST_NOTHING: - case EM4CONST_COPY: - break; - case EM4CONST_IDENTITY: - case EM4CONST_INVERSE: - default: - makeIdentity(); - break; - } + return M[row * 4 + col]; } - // Copy constructor - template - inline CMatrix4::CMatrix4( const CMatrix4& other, eConstructor constructor) -#if defined ( USE_MATRIX_TEST ) - : definitelyIdentityMatrix(BIT_UNTESTED) + //! Simple operator for directly accessing every element of the matrix. + const T &operator()(const s32 row, const s32 col) const { return M[row * 4 + col]; } + + //! Simple operator for linearly accessing every element of the matrix. + T &operator[](u32 index) + { +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; #endif - { - switch ( constructor ) - { - case EM4CONST_IDENTITY: - makeIdentity(); - break; - case EM4CONST_NOTHING: - break; - case EM4CONST_COPY: - *this = other; - break; - case EM4CONST_TRANSPOSED: - other.getTransposed(*this); - break; - case EM4CONST_INVERSE: - if (!other.getInverse(*this)) - memset(M, 0, 16*sizeof(T)); - break; - case EM4CONST_INVERSE_TRANSPOSED: - if (!other.getInverse(*this)) - memset(M, 0, 16*sizeof(T)); - else - *this=getTransposed(); - break; - } + return M[index]; } - //! Add another matrix. - template - inline CMatrix4 CMatrix4::operator+(const CMatrix4& other) const + //! Simple operator for linearly accessing every element of the matrix. + const T &operator[](u32 index) const { return M[index]; } + + //! Sets this matrix equal to the other matrix. + CMatrix4 &operator=(const CMatrix4 &other) = default; + + //! Sets all elements of this matrix to the value. + inline CMatrix4 &operator=(const T &scalar); + + //! Returns pointer to internal array + const T *pointer() const { return M; } + T *pointer() { - CMatrix4 temp ( EM4CONST_NOTHING ); - - temp[0] = M[0]+other[0]; - temp[1] = M[1]+other[1]; - temp[2] = M[2]+other[2]; - temp[3] = M[3]+other[3]; - temp[4] = M[4]+other[4]; - temp[5] = M[5]+other[5]; - temp[6] = M[6]+other[6]; - temp[7] = M[7]+other[7]; - temp[8] = M[8]+other[8]; - temp[9] = M[9]+other[9]; - temp[10] = M[10]+other[10]; - temp[11] = M[11]+other[11]; - temp[12] = M[12]+other[12]; - temp[13] = M[13]+other[13]; - temp[14] = M[14]+other[14]; - temp[15] = M[15]+other[15]; - - return temp; - } - - //! Add another matrix. - template - inline CMatrix4& CMatrix4::operator+=(const CMatrix4& other) - { - M[0]+=other[0]; - M[1]+=other[1]; - M[2]+=other[2]; - M[3]+=other[3]; - M[4]+=other[4]; - M[5]+=other[5]; - M[6]+=other[6]; - M[7]+=other[7]; - M[8]+=other[8]; - M[9]+=other[9]; - M[10]+=other[10]; - M[11]+=other[11]; - M[12]+=other[12]; - M[13]+=other[13]; - M[14]+=other[14]; - M[15]+=other[15]; - - return *this; - } - - //! Subtract another matrix. - template - inline CMatrix4 CMatrix4::operator-(const CMatrix4& other) const - { - CMatrix4 temp ( EM4CONST_NOTHING ); - - temp[0] = M[0]-other[0]; - temp[1] = M[1]-other[1]; - temp[2] = M[2]-other[2]; - temp[3] = M[3]-other[3]; - temp[4] = M[4]-other[4]; - temp[5] = M[5]-other[5]; - temp[6] = M[6]-other[6]; - temp[7] = M[7]-other[7]; - temp[8] = M[8]-other[8]; - temp[9] = M[9]-other[9]; - temp[10] = M[10]-other[10]; - temp[11] = M[11]-other[11]; - temp[12] = M[12]-other[12]; - temp[13] = M[13]-other[13]; - temp[14] = M[14]-other[14]; - temp[15] = M[15]-other[15]; - - return temp; - } - - //! Subtract another matrix. - template - inline CMatrix4& CMatrix4::operator-=(const CMatrix4& other) - { - M[0]-=other[0]; - M[1]-=other[1]; - M[2]-=other[2]; - M[3]-=other[3]; - M[4]-=other[4]; - M[5]-=other[5]; - M[6]-=other[6]; - M[7]-=other[7]; - M[8]-=other[8]; - M[9]-=other[9]; - M[10]-=other[10]; - M[11]-=other[11]; - M[12]-=other[12]; - M[13]-=other[13]; - M[14]-=other[14]; - M[15]-=other[15]; - - return *this; - } - - //! Multiply by scalar. - template - inline CMatrix4 CMatrix4::operator*(const T& scalar) const - { - CMatrix4 temp ( EM4CONST_NOTHING ); - - temp[0] = M[0]*scalar; - temp[1] = M[1]*scalar; - temp[2] = M[2]*scalar; - temp[3] = M[3]*scalar; - temp[4] = M[4]*scalar; - temp[5] = M[5]*scalar; - temp[6] = M[6]*scalar; - temp[7] = M[7]*scalar; - temp[8] = M[8]*scalar; - temp[9] = M[9]*scalar; - temp[10] = M[10]*scalar; - temp[11] = M[11]*scalar; - temp[12] = M[12]*scalar; - temp[13] = M[13]*scalar; - temp[14] = M[14]*scalar; - temp[15] = M[15]*scalar; - - return temp; - } - - //! Multiply by scalar. - template - inline CMatrix4& CMatrix4::operator*=(const T& scalar) - { - M[0]*=scalar; - M[1]*=scalar; - M[2]*=scalar; - M[3]*=scalar; - M[4]*=scalar; - M[5]*=scalar; - M[6]*=scalar; - M[7]*=scalar; - M[8]*=scalar; - M[9]*=scalar; - M[10]*=scalar; - M[11]*=scalar; - M[12]*=scalar; - M[13]*=scalar; - M[14]*=scalar; - M[15]*=scalar; - - return *this; - } - - //! Multiply by another matrix. - template - inline CMatrix4& CMatrix4::operator*=(const CMatrix4& other) - { -#if defined ( USE_MATRIX_TEST ) - // do checks on your own in order to avoid copy creation - if ( !other.isIdentity() ) - { - if ( this->isIdentity() ) - { - return (*this = other); - } - else - { - CMatrix4 temp ( *this ); - return setbyproduct_nocheck( temp, other ); - } - } - return *this; -#else - CMatrix4 temp ( *this ); - return setbyproduct_nocheck( temp, other ); +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; #endif + return M; } - //! multiply by another matrix - // set this matrix to the product of two other matrices - // goal is to reduce stack use and copy - template - inline CMatrix4& CMatrix4::setbyproduct_nocheck(const CMatrix4& other_a,const CMatrix4& other_b ) + //! Returns true if other matrix is equal to this matrix. + constexpr bool operator==(const CMatrix4 &other) const { - const T *m1 = other_a.M; - const T *m2 = other_b.M; - - M[0] = m1[0]*m2[0] + m1[4]*m2[1] + m1[8]*m2[2] + m1[12]*m2[3]; - M[1] = m1[1]*m2[0] + m1[5]*m2[1] + m1[9]*m2[2] + m1[13]*m2[3]; - M[2] = m1[2]*m2[0] + m1[6]*m2[1] + m1[10]*m2[2] + m1[14]*m2[3]; - M[3] = m1[3]*m2[0] + m1[7]*m2[1] + m1[11]*m2[2] + m1[15]*m2[3]; - - M[4] = m1[0]*m2[4] + m1[4]*m2[5] + m1[8]*m2[6] + m1[12]*m2[7]; - M[5] = m1[1]*m2[4] + m1[5]*m2[5] + m1[9]*m2[6] + m1[13]*m2[7]; - M[6] = m1[2]*m2[4] + m1[6]*m2[5] + m1[10]*m2[6] + m1[14]*m2[7]; - M[7] = m1[3]*m2[4] + m1[7]*m2[5] + m1[11]*m2[6] + m1[15]*m2[7]; - - M[8] = m1[0]*m2[8] + m1[4]*m2[9] + m1[8]*m2[10] + m1[12]*m2[11]; - M[9] = m1[1]*m2[8] + m1[5]*m2[9] + m1[9]*m2[10] + m1[13]*m2[11]; - M[10] = m1[2]*m2[8] + m1[6]*m2[9] + m1[10]*m2[10] + m1[14]*m2[11]; - M[11] = m1[3]*m2[8] + m1[7]*m2[9] + m1[11]*m2[10] + m1[15]*m2[11]; - - M[12] = m1[0]*m2[12] + m1[4]*m2[13] + m1[8]*m2[14] + m1[12]*m2[15]; - M[13] = m1[1]*m2[12] + m1[5]*m2[13] + m1[9]*m2[14] + m1[13]*m2[15]; - M[14] = m1[2]*m2[12] + m1[6]*m2[13] + m1[10]*m2[14] + m1[14]*m2[15]; - M[15] = m1[3]*m2[12] + m1[7]*m2[13] + m1[11]*m2[14] + m1[15]*m2[15]; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - //! multiply by another matrix - // set this matrix to the product of two other matrices - // goal is to reduce stack use and copy - template - inline CMatrix4& CMatrix4::setbyproduct(const CMatrix4& other_a, const CMatrix4& other_b ) - { -#if defined ( USE_MATRIX_TEST ) - if ( other_a.isIdentity () ) - return (*this = other_b); - else - if ( other_b.isIdentity () ) - return (*this = other_a); - else - return setbyproduct_nocheck(other_a,other_b); -#else - return setbyproduct_nocheck(other_a,other_b); -#endif - } - - //! multiply by another matrix - template - inline CMatrix4 CMatrix4::operator*(const CMatrix4& m2) const - { -#if defined ( USE_MATRIX_TEST ) - // Testing purpose.. - if ( this->isIdentity() ) - return m2; - if ( m2.isIdentity() ) - return *this; -#endif - - CMatrix4 m3 ( EM4CONST_NOTHING ); - - const T *m1 = M; - - m3[0] = m1[0]*m2[0] + m1[4]*m2[1] + m1[8]*m2[2] + m1[12]*m2[3]; - m3[1] = m1[1]*m2[0] + m1[5]*m2[1] + m1[9]*m2[2] + m1[13]*m2[3]; - m3[2] = m1[2]*m2[0] + m1[6]*m2[1] + m1[10]*m2[2] + m1[14]*m2[3]; - m3[3] = m1[3]*m2[0] + m1[7]*m2[1] + m1[11]*m2[2] + m1[15]*m2[3]; - - m3[4] = m1[0]*m2[4] + m1[4]*m2[5] + m1[8]*m2[6] + m1[12]*m2[7]; - m3[5] = m1[1]*m2[4] + m1[5]*m2[5] + m1[9]*m2[6] + m1[13]*m2[7]; - m3[6] = m1[2]*m2[4] + m1[6]*m2[5] + m1[10]*m2[6] + m1[14]*m2[7]; - m3[7] = m1[3]*m2[4] + m1[7]*m2[5] + m1[11]*m2[6] + m1[15]*m2[7]; - - m3[8] = m1[0]*m2[8] + m1[4]*m2[9] + m1[8]*m2[10] + m1[12]*m2[11]; - m3[9] = m1[1]*m2[8] + m1[5]*m2[9] + m1[9]*m2[10] + m1[13]*m2[11]; - m3[10] = m1[2]*m2[8] + m1[6]*m2[9] + m1[10]*m2[10] + m1[14]*m2[11]; - m3[11] = m1[3]*m2[8] + m1[7]*m2[9] + m1[11]*m2[10] + m1[15]*m2[11]; - - m3[12] = m1[0]*m2[12] + m1[4]*m2[13] + m1[8]*m2[14] + m1[12]*m2[15]; - m3[13] = m1[1]*m2[12] + m1[5]*m2[13] + m1[9]*m2[14] + m1[13]*m2[15]; - m3[14] = m1[2]*m2[12] + m1[6]*m2[13] + m1[10]*m2[14] + m1[14]*m2[15]; - m3[15] = m1[3]*m2[12] + m1[7]*m2[13] + m1[11]*m2[14] + m1[15]*m2[15]; - return m3; - } - - - - template - inline vector3d CMatrix4::getTranslation() const - { - return vector3d(M[12], M[13], M[14]); - } - - - template - inline CMatrix4& CMatrix4::setTranslation( const vector3d& translation ) - { - M[12] = translation.X; - M[13] = translation.Y; - M[14] = translation.Z; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - template - inline CMatrix4& CMatrix4::setInverseTranslation( const vector3d& translation ) - { - M[12] = -translation.X; - M[13] = -translation.Y; - M[14] = -translation.Z; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - template - inline CMatrix4& CMatrix4::setScale( const vector3d& scale ) - { - M[0] = scale.X; - M[5] = scale.Y; - M[10] = scale.Z; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - //! Returns the absolute values of the scales of the matrix. - /** - Note: You only get back original values if the matrix only set the scale. - Otherwise the result is a scale you can use to normalize the matrix axes, - but it's usually no longer what you did set with setScale. - */ - template - inline vector3d CMatrix4::getScale() const - { - // See http://www.robertblum.com/articles/2005/02/14/decomposing-matrices - - // Deal with the 0 rotation case first - // Prior to Irrlicht 1.6, we always returned this value. - if(core::iszero(M[1]) && core::iszero(M[2]) && - core::iszero(M[4]) && core::iszero(M[6]) && - core::iszero(M[8]) && core::iszero(M[9])) - return vector3d(M[0], M[5], M[10]); - - // We have to do the full calculation. - return vector3d(sqrtf(M[0] * M[0] + M[1] * M[1] + M[2] * M[2]), - sqrtf(M[4] * M[4] + M[5] * M[5] + M[6] * M[6]), - sqrtf(M[8] * M[8] + M[9] * M[9] + M[10] * M[10])); - } - - template - inline CMatrix4& CMatrix4::setRotationDegrees( const vector3d& rotation ) - { - return setRotationRadians( rotation * core::DEGTORAD ); - } - - template - inline CMatrix4& CMatrix4::setInverseRotationDegrees( const vector3d& rotation ) - { - return setInverseRotationRadians( rotation * core::DEGTORAD ); - } - - template - inline CMatrix4& CMatrix4::setRotationRadians( const vector3d& rotation ) - { - const f64 cr = cos( rotation.X ); - const f64 sr = sin( rotation.X ); - const f64 cp = cos( rotation.Y ); - const f64 sp = sin( rotation.Y ); - const f64 cy = cos( rotation.Z ); - const f64 sy = sin( rotation.Z ); - - M[0] = (T)( cp*cy ); - M[1] = (T)( cp*sy ); - M[2] = (T)( -sp ); - - const f64 srsp = sr*sp; - const f64 crsp = cr*sp; - - M[4] = (T)( srsp*cy-cr*sy ); - M[5] = (T)( srsp*sy+cr*cy ); - M[6] = (T)( sr*cp ); - - M[8] = (T)( crsp*cy+sr*sy ); - M[9] = (T)( crsp*sy-sr*cy ); - M[10] = (T)( cr*cp ); -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - //! Returns a rotation which (mostly) works in combination with the given scale - /** - This code was originally written by by Chev (assuming no scaling back then, - we can be blamed for all problems added by regarding scale) - */ - template - inline core::vector3d CMatrix4::getRotationDegrees(const vector3d& scale_) const - { - const CMatrix4 &mat = *this; - const core::vector3d scale(core::iszero(scale_.X) ? FLT_MAX : scale_.X , core::iszero(scale_.Y) ? FLT_MAX : scale_.Y, core::iszero(scale_.Z) ? FLT_MAX : scale_.Z); - const core::vector3d invScale(core::reciprocal(scale.X),core::reciprocal(scale.Y),core::reciprocal(scale.Z)); - - f64 Y = -asin(core::clamp(mat[2]*invScale.X, -1.0, 1.0)); - const f64 C = cos(Y); - Y *= RADTODEG64; - - f64 rotx, roty, X, Z; - - if (!core::iszero((T)C)) - { - const f64 invC = core::reciprocal(C); - rotx = mat[10] * invC * invScale.Z; - roty = mat[6] * invC * invScale.Y; - X = atan2( roty, rotx ) * RADTODEG64; - rotx = mat[0] * invC * invScale.X; - roty = mat[1] * invC * invScale.X; - Z = atan2( roty, rotx ) * RADTODEG64; - } - else - { - X = 0.0; - rotx = mat[5] * invScale.Y; - roty = -mat[4] * invScale.Y; - Z = atan2( roty, rotx ) * RADTODEG64; - } - - // fix values that get below zero - if (X < 0.0) X += 360.0; - if (Y < 0.0) Y += 360.0; - if (Z < 0.0) Z += 360.0; - - return vector3d((T)X,(T)Y,(T)Z); - } - - //! Returns a rotation that is equivalent to that set by setRotationDegrees(). - template - inline core::vector3d CMatrix4::getRotationDegrees() const - { - // Note: Using getScale() here make it look like it could do matrix decomposition. - // It can't! It works (or should work) as long as rotation doesn't flip the handedness - // aka scale swapping 1 or 3 axes. (I think we could catch that as well by comparing - // crossproduct of first 2 axes to direction of third axis, but TODO) - // And maybe it should also offer the solution for the simple calculation - // without regarding scaling as Irrlicht did before 1.7 - core::vector3d scale(getScale()); - - // We assume the matrix uses rotations instead of negative scaling 2 axes. - // Otherwise it fails even for some simple cases, like rotating around - // 2 axes by 180° which getScale thinks is a negative scaling. - if (scale.Y<0 && scale.Z<0) - { - scale.Y =-scale.Y; - scale.Z =-scale.Z; - } - else if (scale.X<0 && scale.Z<0) - { - scale.X =-scale.X; - scale.Z =-scale.Z; - } - else if (scale.X<0 && scale.Y<0) - { - scale.X =-scale.X; - scale.Y =-scale.Y; - } - - return getRotationDegrees(scale); - } - - - //! Sets matrix to rotation matrix of inverse angles given as parameters - template - inline CMatrix4& CMatrix4::setInverseRotationRadians( const vector3d& rotation ) - { - f64 cr = cos( rotation.X ); - f64 sr = sin( rotation.X ); - f64 cp = cos( rotation.Y ); - f64 sp = sin( rotation.Y ); - f64 cy = cos( rotation.Z ); - f64 sy = sin( rotation.Z ); - - M[0] = (T)( cp*cy ); - M[4] = (T)( cp*sy ); - M[8] = (T)( -sp ); - - f64 srsp = sr*sp; - f64 crsp = cr*sp; - - M[1] = (T)( srsp*cy-cr*sy ); - M[5] = (T)( srsp*sy+cr*cy ); - M[9] = (T)( sr*cp ); - - M[2] = (T)( crsp*cy+sr*sy ); - M[6] = (T)( crsp*sy-sr*cy ); - M[10] = (T)( cr*cp ); -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - //! Sets matrix to rotation matrix defined by axis and angle, assuming LH rotation - template - inline CMatrix4& CMatrix4::setRotationAxisRadians( const T& angle, const vector3d& axis ) - { - const f64 c = cos(angle); - const f64 s = sin(angle); - const f64 t = 1.0 - c; - - const f64 tx = t * axis.X; - const f64 ty = t * axis.Y; - const f64 tz = t * axis.Z; - - const f64 sx = s * axis.X; - const f64 sy = s * axis.Y; - const f64 sz = s * axis.Z; - - M[0] = (T)(tx * axis.X + c); - M[1] = (T)(tx * axis.Y + sz); - M[2] = (T)(tx * axis.Z - sy); - - M[4] = (T)(ty * axis.X - sz); - M[5] = (T)(ty * axis.Y + c); - M[6] = (T)(ty * axis.Z + sx); - - M[8] = (T)(tz * axis.X + sy); - M[9] = (T)(tz * axis.Y - sx); - M[10] = (T)(tz * axis.Z + c); - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - /*! - */ - template - inline CMatrix4& CMatrix4::makeIdentity() - { - memset(M, 0, 16*sizeof(T)); - M[0] = M[5] = M[10] = M[15] = (T)1; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=true; -#endif - return *this; - } - - - /* - check identity with epsilon - solve floating range problems.. - */ - template - inline bool CMatrix4::isIdentity() const - { -#if defined ( USE_MATRIX_TEST ) - if (definitelyIdentityMatrix) +#if defined(USE_MATRIX_TEST) + if (definitelyIdentityMatrix && other.definitelyIdentityMatrix) return true; #endif - if (!core::equals( M[12], (T)0 ) || !core::equals( M[13], (T)0 ) || !core::equals( M[14], (T)0 ) || !core::equals( M[15], (T)1 )) - return false; + for (s32 i = 0; i < 16; ++i) + if (M[i] != other.M[i]) + return false; - if (!core::equals( M[ 0], (T)1 ) || !core::equals( M[ 1], (T)0 ) || !core::equals( M[ 2], (T)0 ) || !core::equals( M[ 3], (T)0 )) - return false; + return true; + } - if (!core::equals( M[ 4], (T)0 ) || !core::equals( M[ 5], (T)1 ) || !core::equals( M[ 6], (T)0 ) || !core::equals( M[ 7], (T)0 )) - return false; + //! Returns true if other matrix is not equal to this matrix. + constexpr bool operator!=(const CMatrix4 &other) const + { + return !(*this == other); + } - if (!core::equals( M[ 8], (T)0 ) || !core::equals( M[ 9], (T)0 ) || !core::equals( M[10], (T)1 ) || !core::equals( M[11], (T)0 )) - return false; + //! Add another matrix. + CMatrix4 operator+(const CMatrix4 &other) const; + + //! Add another matrix. + CMatrix4 &operator+=(const CMatrix4 &other); + + //! Subtract another matrix. + CMatrix4 operator-(const CMatrix4 &other) const; + + //! Subtract another matrix. + CMatrix4 &operator-=(const CMatrix4 &other); + + //! set this matrix to the product of two matrices + /** Calculate b*a */ + inline CMatrix4 &setbyproduct(const CMatrix4 &other_a, const CMatrix4 &other_b); + + //! Set this matrix to the product of two matrices + /** Calculate b*a, no optimization used, + use it if you know you never have an identity matrix */ + CMatrix4 &setbyproduct_nocheck(const CMatrix4 &other_a, const CMatrix4 &other_b); + + //! Multiply by another matrix. + /** Calculate other*this */ + CMatrix4 operator*(const CMatrix4 &other) const; + + //! Multiply by another matrix. + /** Like calling: (*this) = (*this) * other + */ + CMatrix4 &operator*=(const CMatrix4 &other); + + //! Multiply by scalar. + CMatrix4 operator*(const T &scalar) const; + + //! Multiply by scalar. + CMatrix4 &operator*=(const T &scalar); + + //! Set matrix to identity. + inline CMatrix4 &makeIdentity(); + + //! Returns true if the matrix is the identity matrix + inline bool isIdentity() const; + + //! Returns true if the matrix is orthogonal + inline bool isOrthogonal() const; + + //! Returns true if the matrix is the identity matrix + bool isIdentity_integer_base() const; + + //! Set the translation of the current matrix. Will erase any previous values. + CMatrix4 &setTranslation(const vector3d &translation); + + //! Gets the current translation + vector3d getTranslation() const; + + //! Set the inverse translation of the current matrix. Will erase any previous values. + CMatrix4 &setInverseTranslation(const vector3d &translation); + + //! Make a rotation matrix from Euler angles. The 4th row and column are unmodified. + inline CMatrix4 &setRotationRadians(const vector3d &rotation); + + //! Make a rotation matrix from Euler angles. The 4th row and column are unmodified. + CMatrix4 &setRotationDegrees(const vector3d &rotation); + + //! Get the rotation, as set by setRotation() when you already know the scale used to create the matrix + /** NOTE: The scale needs to be the correct one used to create this matrix. + You can _not_ use the result of getScale(), but have to save your scale + variable in another place (like ISceneNode does). + NOTE: No scale value can be 0 or the result is undefined. + NOTE: It does not necessarily return the *same* Euler angles as those set by setRotationDegrees(), + but the rotation will be equivalent, i.e. will have the same result when used to rotate a vector or node. + NOTE: It will (usually) give wrong results when further transformations have been added in the matrix (like shear). + WARNING: There have been troubles with this function over the years and we may still have missed some corner cases. + It's generally safer to keep the rotation and scale you used to create the matrix around and work with those. + */ + core::vector3d getRotationDegrees(const vector3d &scale) const; + + //! Returns the rotation, as set by setRotation(). + /** NOTE: You will have the same end-rotation as used in setRotation, but it might not use the same axis values. + NOTE: This only works correct if no other matrix operations have been done on the inner 3x3 matrix besides + setting rotation (so no scale/shear). Thought it (probably) works as long as scale doesn't flip handedness. + NOTE: It does not necessarily return the *same* Euler angles as those set by setRotationDegrees(), + but the rotation will be equivalent, i.e. will have the same result when used to rotate a vector or node. + */ + core::vector3d getRotationDegrees() const; + + //! Make an inverted rotation matrix from Euler angles. + /** The 4th row and column are unmodified. */ + inline CMatrix4 &setInverseRotationRadians(const vector3d &rotation); + + //! Make an inverted rotation matrix from Euler angles. + /** The 4th row and column are unmodified. */ + inline CMatrix4 &setInverseRotationDegrees(const vector3d &rotation); + + //! Make a rotation matrix from angle and axis, assuming left handed rotation. + /** The 4th row and column are unmodified. */ + inline CMatrix4 &setRotationAxisRadians(const T &angle, const vector3d &axis); + + //! Set Scale + CMatrix4 &setScale(const vector3d &scale); + + //! Set Scale + CMatrix4 &setScale(const T scale) { return setScale(core::vector3d(scale, scale, scale)); } + + //! Get Scale + core::vector3d getScale() const; + + //! Translate a vector by the inverse of the translation part of this matrix. + void inverseTranslateVect(vector3df &vect) const; + + //! Rotate a vector by the inverse of the rotation part of this matrix. + void inverseRotateVect(vector3df &vect) const; + + //! Rotate a vector by the rotation part of this matrix. + void rotateVect(vector3df &vect) const; + + //! An alternate transform vector method, writing into a second vector + void rotateVect(core::vector3df &out, const core::vector3df &in) const; + + //! An alternate transform vector method, writing into an array of 3 floats + void rotateVect(T *out, const core::vector3df &in) const; + + //! Transforms the vector by this matrix + /** This operation is performed as if the vector was 4d with the 4th component =1 */ + void transformVect(vector3df &vect) const; + + //! Transforms input vector by this matrix and stores result in output vector + /** This operation is performed as if the vector was 4d with the 4th component =1 */ + void transformVect(vector3df &out, const vector3df &in) const; + + //! An alternate transform vector method, writing into an array of 4 floats + /** This operation is performed as if the vector was 4d with the 4th component =1. + NOTE: out[3] will be written to (4th vector component)*/ + void transformVect(T *out, const core::vector3df &in) const; + + //! An alternate transform vector method, reading from and writing to an array of 3 floats + /** This operation is performed as if the vector was 4d with the 4th component =1 + NOTE: out[3] will be written to (4th vector component)*/ + void transformVec3(T *out, const T *in) const; + + //! An alternate transform vector method, reading from and writing to an array of 4 floats + void transformVec4(T *out, const T *in) const; + + //! Translate a vector by the translation part of this matrix. + /** This operation is performed as if the vector was 4d with the 4th component =1 */ + void translateVect(vector3df &vect) const; + + //! Transforms a plane by this matrix + void transformPlane(core::plane3d &plane) const; + + //! Transforms a plane by this matrix + void transformPlane(const core::plane3d &in, core::plane3d &out) const; + + //! Transforms a axis aligned bounding box + void transformBoxEx(core::aabbox3d &box) const; + + //! Multiplies this matrix by a 1x4 matrix + void multiplyWith1x4Matrix(T *matrix) const; + + //! Calculates inverse of matrix. Slow. + /** \return Returns false if there is no inverse matrix.*/ + bool makeInverse(); + + //! Inverts a primitive matrix which only contains a translation and a rotation + /** \param out: where result matrix is written to. */ + bool getInversePrimitive(CMatrix4 &out) const; + + //! Gets the inverse matrix of this one + /** \param out: where result matrix is written to. + \return Returns false if there is no inverse matrix. */ + bool getInverse(CMatrix4 &out) const; + + //! Builds a right-handed perspective projection matrix based on a field of view + //\param zClipFromZero: Clipping of z can be projected from 0 to w when true (D3D style) and from -w to w when false (OGL style). + CMatrix4 &buildProjectionMatrixPerspectiveFovRH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a left-handed perspective projection matrix based on a field of view + CMatrix4 &buildProjectionMatrixPerspectiveFovLH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a left-handed perspective projection matrix based on a field of view, with far plane at infinity + CMatrix4 &buildProjectionMatrixPerspectiveFovInfinityLH(f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 epsilon = 0); + + //! Builds a right-handed perspective projection matrix. + CMatrix4 &buildProjectionMatrixPerspectiveRH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a left-handed perspective projection matrix. + CMatrix4 &buildProjectionMatrixPerspectiveLH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a left-handed orthogonal projection matrix. + //\param zClipFromZero: Clipping of z can be projected from 0 to 1 when true (D3D style) and from -1 to 1 when false (OGL style). + CMatrix4 &buildProjectionMatrixOrthoLH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a right-handed orthogonal projection matrix. + CMatrix4 &buildProjectionMatrixOrthoRH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero = true); + + //! Builds a left-handed look-at matrix. + CMatrix4 &buildCameraLookAtMatrixLH( + const vector3df &position, + const vector3df &target, + const vector3df &upVector); + + //! Builds a right-handed look-at matrix. + CMatrix4 &buildCameraLookAtMatrixRH( + const vector3df &position, + const vector3df &target, + const vector3df &upVector); + + //! Builds a matrix that flattens geometry into a plane. + /** \param light: light source + \param plane: plane into which the geometry if flattened into + \param point: value between 0 and 1, describing the light source. + If this is 1, it is a point light, if it is 0, it is a directional light. */ + CMatrix4 &buildShadowMatrix(const core::vector3df &light, core::plane3df plane, f32 point = 1.0f); + + //! Builds a matrix which transforms a normalized Device Coordinate to Device Coordinates. + /** Used to scale <-1,-1><1,1> to viewport, for example from <-1,-1> <1,1> to the viewport <0,0><0,640> */ + CMatrix4 &buildNDCToDCMatrix(const core::rect &area, f32 zScale); + + //! Creates a new matrix as interpolated matrix from two other ones. + /** \param b: other matrix to interpolate with + \param time: Must be a value between 0 and 1. */ + CMatrix4 interpolate(const core::CMatrix4 &b, f32 time) const; + + //! Gets transposed matrix + CMatrix4 getTransposed() const; + + //! Gets transposed matrix + inline void getTransposed(CMatrix4 &dest) const; + + //! Builds a matrix that rotates from one vector to another + /** \param from: vector to rotate from + \param to: vector to rotate to + */ + CMatrix4 &buildRotateFromTo(const core::vector3df &from, const core::vector3df &to); + + //! Builds a combined matrix which translates to a center before rotation and translates from origin afterwards + /** \param center Position to rotate around + \param translate Translation applied after the rotation + */ + void setRotationCenter(const core::vector3df ¢er, const core::vector3df &translate); + + //! Builds a matrix which rotates a source vector to a look vector over an arbitrary axis + /** \param camPos: viewer position in world coo + \param center: object position in world-coo and rotation pivot + \param translation: object final translation from center + \param axis: axis to rotate about + \param from: source vector to rotate from + */ + void buildAxisAlignedBillboard(const core::vector3df &camPos, + const core::vector3df ¢er, + const core::vector3df &translation, + const core::vector3df &axis, + const core::vector3df &from); + + /* + construct 2D Texture transformations + rotate about center, scale, and transform. + */ + //! Set to a texture transformation matrix with the given parameters. + CMatrix4 &buildTextureTransform(f32 rotateRad, + const core::vector2df &rotatecenter, + const core::vector2df &translate, + const core::vector2df &scale); + + //! Set texture transformation rotation + /** Rotate about z axis, recenter at (0.5,0.5). + Doesn't clear other elements than those affected + \param radAngle Angle in radians + \return Altered matrix */ + CMatrix4 &setTextureRotationCenter(f32 radAngle); + + //! Set texture transformation translation + /** Doesn't clear other elements than those affected. + \param x Offset on x axis + \param y Offset on y axis + \return Altered matrix */ + CMatrix4 &setTextureTranslate(f32 x, f32 y); + + //! Get texture transformation translation + /** \param x returns offset on x axis + \param y returns offset on y axis */ + void getTextureTranslate(f32 &x, f32 &y) const; + + //! Set texture transformation translation, using a transposed representation + /** Doesn't clear other elements than those affected. + \param x Offset on x axis + \param y Offset on y axis + \return Altered matrix */ + CMatrix4 &setTextureTranslateTransposed(f32 x, f32 y); + + //! Set texture transformation scale + /** Doesn't clear other elements than those affected. + \param sx Scale factor on x axis + \param sy Scale factor on y axis + \return Altered matrix. */ + CMatrix4 &setTextureScale(f32 sx, f32 sy); + + //! Get texture transformation scale + /** \param sx Returns x axis scale factor + \param sy Returns y axis scale factor */ + void getTextureScale(f32 &sx, f32 &sy) const; + + //! Set texture transformation scale, and recenter at (0.5,0.5) + /** Doesn't clear other elements than those affected. + \param sx Scale factor on x axis + \param sy Scale factor on y axis + \return Altered matrix. */ + CMatrix4 &setTextureScaleCenter(f32 sx, f32 sy); + + //! Sets all matrix data members at once + CMatrix4 &setM(const T *data); + + //! Sets if the matrix is definitely identity matrix + void setDefinitelyIdentityMatrix(bool isDefinitelyIdentityMatrix); + + //! Gets if the matrix is definitely identity matrix + bool getDefinitelyIdentityMatrix() const; + + //! Compare two matrices using the equal method + bool equals(const core::CMatrix4 &other, const T tolerance = (T)ROUNDING_ERROR_f64) const; + +private: + //! Matrix data, stored in row-major order + T M[16]; +#if defined(USE_MATRIX_TEST) + //! Flag is this matrix is identity matrix + mutable u32 definitelyIdentityMatrix; +#endif +}; + +// Default constructor +template +inline CMatrix4::CMatrix4(eConstructor constructor) +#if defined(USE_MATRIX_TEST) + : + definitelyIdentityMatrix(BIT_UNTESTED) +#endif +{ + switch (constructor) { + case EM4CONST_NOTHING: + case EM4CONST_COPY: + break; + case EM4CONST_IDENTITY: + case EM4CONST_INVERSE: + default: + makeIdentity(); + break; + } +} + +// Copy constructor +template +inline CMatrix4::CMatrix4(const CMatrix4 &other, eConstructor constructor) +#if defined(USE_MATRIX_TEST) + : + definitelyIdentityMatrix(BIT_UNTESTED) +#endif +{ + switch (constructor) { + case EM4CONST_IDENTITY: + makeIdentity(); + break; + case EM4CONST_NOTHING: + break; + case EM4CONST_COPY: + *this = other; + break; + case EM4CONST_TRANSPOSED: + other.getTransposed(*this); + break; + case EM4CONST_INVERSE: + if (!other.getInverse(*this)) + memset(M, 0, 16 * sizeof(T)); + break; + case EM4CONST_INVERSE_TRANSPOSED: + if (!other.getInverse(*this)) + memset(M, 0, 16 * sizeof(T)); + else + *this = getTransposed(); + break; + } +} + +//! Add another matrix. +template +inline CMatrix4 CMatrix4::operator+(const CMatrix4 &other) const +{ + CMatrix4 temp(EM4CONST_NOTHING); + + temp[0] = M[0] + other[0]; + temp[1] = M[1] + other[1]; + temp[2] = M[2] + other[2]; + temp[3] = M[3] + other[3]; + temp[4] = M[4] + other[4]; + temp[5] = M[5] + other[5]; + temp[6] = M[6] + other[6]; + temp[7] = M[7] + other[7]; + temp[8] = M[8] + other[8]; + temp[9] = M[9] + other[9]; + temp[10] = M[10] + other[10]; + temp[11] = M[11] + other[11]; + temp[12] = M[12] + other[12]; + temp[13] = M[13] + other[13]; + temp[14] = M[14] + other[14]; + temp[15] = M[15] + other[15]; + + return temp; +} + +//! Add another matrix. +template +inline CMatrix4 &CMatrix4::operator+=(const CMatrix4 &other) +{ + M[0] += other[0]; + M[1] += other[1]; + M[2] += other[2]; + M[3] += other[3]; + M[4] += other[4]; + M[5] += other[5]; + M[6] += other[6]; + M[7] += other[7]; + M[8] += other[8]; + M[9] += other[9]; + M[10] += other[10]; + M[11] += other[11]; + M[12] += other[12]; + M[13] += other[13]; + M[14] += other[14]; + M[15] += other[15]; + + return *this; +} + +//! Subtract another matrix. +template +inline CMatrix4 CMatrix4::operator-(const CMatrix4 &other) const +{ + CMatrix4 temp(EM4CONST_NOTHING); + + temp[0] = M[0] - other[0]; + temp[1] = M[1] - other[1]; + temp[2] = M[2] - other[2]; + temp[3] = M[3] - other[3]; + temp[4] = M[4] - other[4]; + temp[5] = M[5] - other[5]; + temp[6] = M[6] - other[6]; + temp[7] = M[7] - other[7]; + temp[8] = M[8] - other[8]; + temp[9] = M[9] - other[9]; + temp[10] = M[10] - other[10]; + temp[11] = M[11] - other[11]; + temp[12] = M[12] - other[12]; + temp[13] = M[13] - other[13]; + temp[14] = M[14] - other[14]; + temp[15] = M[15] - other[15]; + + return temp; +} + +//! Subtract another matrix. +template +inline CMatrix4 &CMatrix4::operator-=(const CMatrix4 &other) +{ + M[0] -= other[0]; + M[1] -= other[1]; + M[2] -= other[2]; + M[3] -= other[3]; + M[4] -= other[4]; + M[5] -= other[5]; + M[6] -= other[6]; + M[7] -= other[7]; + M[8] -= other[8]; + M[9] -= other[9]; + M[10] -= other[10]; + M[11] -= other[11]; + M[12] -= other[12]; + M[13] -= other[13]; + M[14] -= other[14]; + M[15] -= other[15]; + + return *this; +} + +//! Multiply by scalar. +template +inline CMatrix4 CMatrix4::operator*(const T &scalar) const +{ + CMatrix4 temp(EM4CONST_NOTHING); + + temp[0] = M[0] * scalar; + temp[1] = M[1] * scalar; + temp[2] = M[2] * scalar; + temp[3] = M[3] * scalar; + temp[4] = M[4] * scalar; + temp[5] = M[5] * scalar; + temp[6] = M[6] * scalar; + temp[7] = M[7] * scalar; + temp[8] = M[8] * scalar; + temp[9] = M[9] * scalar; + temp[10] = M[10] * scalar; + temp[11] = M[11] * scalar; + temp[12] = M[12] * scalar; + temp[13] = M[13] * scalar; + temp[14] = M[14] * scalar; + temp[15] = M[15] * scalar; + + return temp; +} + +//! Multiply by scalar. +template +inline CMatrix4 &CMatrix4::operator*=(const T &scalar) +{ + M[0] *= scalar; + M[1] *= scalar; + M[2] *= scalar; + M[3] *= scalar; + M[4] *= scalar; + M[5] *= scalar; + M[6] *= scalar; + M[7] *= scalar; + M[8] *= scalar; + M[9] *= scalar; + M[10] *= scalar; + M[11] *= scalar; + M[12] *= scalar; + M[13] *= scalar; + M[14] *= scalar; + M[15] *= scalar; + + return *this; +} + +//! Multiply by another matrix. +template +inline CMatrix4 &CMatrix4::operator*=(const CMatrix4 &other) +{ +#if defined(USE_MATRIX_TEST) + // do checks on your own in order to avoid copy creation + if (!other.isIdentity()) { + if (this->isIdentity()) { + return (*this = other); + } else { + CMatrix4 temp(*this); + return setbyproduct_nocheck(temp, other); + } + } + return *this; +#else + CMatrix4 temp(*this); + return setbyproduct_nocheck(temp, other); +#endif +} + +//! multiply by another matrix +// set this matrix to the product of two other matrices +// goal is to reduce stack use and copy +template +inline CMatrix4 &CMatrix4::setbyproduct_nocheck(const CMatrix4 &other_a, const CMatrix4 &other_b) +{ + const T *m1 = other_a.M; + const T *m2 = other_b.M; + + M[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; + M[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; + M[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; + M[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; + + M[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; + M[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; + M[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; + M[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; + + M[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; + M[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; + M[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; + M[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; + + M[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; + M[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; + M[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; + M[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +//! multiply by another matrix +// set this matrix to the product of two other matrices +// goal is to reduce stack use and copy +template +inline CMatrix4 &CMatrix4::setbyproduct(const CMatrix4 &other_a, const CMatrix4 &other_b) +{ +#if defined(USE_MATRIX_TEST) + if (other_a.isIdentity()) + return (*this = other_b); + else if (other_b.isIdentity()) + return (*this = other_a); + else + return setbyproduct_nocheck(other_a, other_b); +#else + return setbyproduct_nocheck(other_a, other_b); +#endif +} + +//! multiply by another matrix +template +inline CMatrix4 CMatrix4::operator*(const CMatrix4 &m2) const +{ +#if defined(USE_MATRIX_TEST) + // Testing purpose.. + if (this->isIdentity()) + return m2; + if (m2.isIdentity()) + return *this; +#endif + + CMatrix4 m3(EM4CONST_NOTHING); + + const T *m1 = M; + + m3[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; + m3[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; + m3[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; + m3[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; + + m3[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; + m3[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; + m3[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; + m3[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; + + m3[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; + m3[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; + m3[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; + m3[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; + + m3[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; + m3[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; + m3[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; + m3[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; + return m3; +} + +template +inline vector3d CMatrix4::getTranslation() const +{ + return vector3d(M[12], M[13], M[14]); +} + +template +inline CMatrix4 &CMatrix4::setTranslation(const vector3d &translation) +{ + M[12] = translation.X; + M[13] = translation.Y; + M[14] = translation.Z; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +template +inline CMatrix4 &CMatrix4::setInverseTranslation(const vector3d &translation) +{ + M[12] = -translation.X; + M[13] = -translation.Y; + M[14] = -translation.Z; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +template +inline CMatrix4 &CMatrix4::setScale(const vector3d &scale) +{ + M[0] = scale.X; + M[5] = scale.Y; + M[10] = scale.Z; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +//! Returns the absolute values of the scales of the matrix. +/** +Note: You only get back original values if the matrix only set the scale. +Otherwise the result is a scale you can use to normalize the matrix axes, +but it's usually no longer what you did set with setScale. +*/ +template +inline vector3d CMatrix4::getScale() const +{ + // See http://www.robertblum.com/articles/2005/02/14/decomposing-matrices + + // Deal with the 0 rotation case first + // Prior to Irrlicht 1.6, we always returned this value. + if (core::iszero(M[1]) && core::iszero(M[2]) && + core::iszero(M[4]) && core::iszero(M[6]) && + core::iszero(M[8]) && core::iszero(M[9])) + return vector3d(M[0], M[5], M[10]); + + // We have to do the full calculation. + return vector3d(sqrtf(M[0] * M[0] + M[1] * M[1] + M[2] * M[2]), + sqrtf(M[4] * M[4] + M[5] * M[5] + M[6] * M[6]), + sqrtf(M[8] * M[8] + M[9] * M[9] + M[10] * M[10])); +} + +template +inline CMatrix4 &CMatrix4::setRotationDegrees(const vector3d &rotation) +{ + return setRotationRadians(rotation * core::DEGTORAD); +} + +template +inline CMatrix4 &CMatrix4::setInverseRotationDegrees(const vector3d &rotation) +{ + return setInverseRotationRadians(rotation * core::DEGTORAD); +} + +template +inline CMatrix4 &CMatrix4::setRotationRadians(const vector3d &rotation) +{ + const f64 cr = cos(rotation.X); + const f64 sr = sin(rotation.X); + const f64 cp = cos(rotation.Y); + const f64 sp = sin(rotation.Y); + const f64 cy = cos(rotation.Z); + const f64 sy = sin(rotation.Z); + + M[0] = (T)(cp * cy); + M[1] = (T)(cp * sy); + M[2] = (T)(-sp); + + const f64 srsp = sr * sp; + const f64 crsp = cr * sp; + + M[4] = (T)(srsp * cy - cr * sy); + M[5] = (T)(srsp * sy + cr * cy); + M[6] = (T)(sr * cp); + + M[8] = (T)(crsp * cy + sr * sy); + M[9] = (T)(crsp * sy - sr * cy); + M[10] = (T)(cr * cp); +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +//! Returns a rotation which (mostly) works in combination with the given scale +/** +This code was originally written by by Chev (assuming no scaling back then, +we can be blamed for all problems added by regarding scale) +*/ +template +inline core::vector3d CMatrix4::getRotationDegrees(const vector3d &scale_) const +{ + const CMatrix4 &mat = *this; + const core::vector3d scale(core::iszero(scale_.X) ? FLT_MAX : scale_.X, core::iszero(scale_.Y) ? FLT_MAX : scale_.Y, core::iszero(scale_.Z) ? FLT_MAX : scale_.Z); + const core::vector3d invScale(core::reciprocal(scale.X), core::reciprocal(scale.Y), core::reciprocal(scale.Z)); + + f64 Y = -asin(core::clamp(mat[2] * invScale.X, -1.0, 1.0)); + const f64 C = cos(Y); + Y *= RADTODEG64; + + f64 rotx, roty, X, Z; + + if (!core::iszero((T)C)) { + const f64 invC = core::reciprocal(C); + rotx = mat[10] * invC * invScale.Z; + roty = mat[6] * invC * invScale.Y; + X = atan2(roty, rotx) * RADTODEG64; + rotx = mat[0] * invC * invScale.X; + roty = mat[1] * invC * invScale.X; + Z = atan2(roty, rotx) * RADTODEG64; + } else { + X = 0.0; + rotx = mat[5] * invScale.Y; + roty = -mat[4] * invScale.Y; + Z = atan2(roty, rotx) * RADTODEG64; + } + + // fix values that get below zero + if (X < 0.0) + X += 360.0; + if (Y < 0.0) + Y += 360.0; + if (Z < 0.0) + Z += 360.0; + + return vector3d((T)X, (T)Y, (T)Z); +} + +//! Returns a rotation that is equivalent to that set by setRotationDegrees(). +template +inline core::vector3d CMatrix4::getRotationDegrees() const +{ + // Note: Using getScale() here make it look like it could do matrix decomposition. + // It can't! It works (or should work) as long as rotation doesn't flip the handedness + // aka scale swapping 1 or 3 axes. (I think we could catch that as well by comparing + // crossproduct of first 2 axes to direction of third axis, but TODO) + // And maybe it should also offer the solution for the simple calculation + // without regarding scaling as Irrlicht did before 1.7 + core::vector3d scale(getScale()); + + // We assume the matrix uses rotations instead of negative scaling 2 axes. + // Otherwise it fails even for some simple cases, like rotating around + // 2 axes by 180° which getScale thinks is a negative scaling. + if (scale.Y < 0 && scale.Z < 0) { + scale.Y = -scale.Y; + scale.Z = -scale.Z; + } else if (scale.X < 0 && scale.Z < 0) { + scale.X = -scale.X; + scale.Z = -scale.Z; + } else if (scale.X < 0 && scale.Y < 0) { + scale.X = -scale.X; + scale.Y = -scale.Y; + } + + return getRotationDegrees(scale); +} + +//! Sets matrix to rotation matrix of inverse angles given as parameters +template +inline CMatrix4 &CMatrix4::setInverseRotationRadians(const vector3d &rotation) +{ + f64 cr = cos(rotation.X); + f64 sr = sin(rotation.X); + f64 cp = cos(rotation.Y); + f64 sp = sin(rotation.Y); + f64 cy = cos(rotation.Z); + f64 sy = sin(rotation.Z); + + M[0] = (T)(cp * cy); + M[4] = (T)(cp * sy); + M[8] = (T)(-sp); + + f64 srsp = sr * sp; + f64 crsp = cr * sp; + + M[1] = (T)(srsp * cy - cr * sy); + M[5] = (T)(srsp * sy + cr * cy); + M[9] = (T)(sr * cp); + + M[2] = (T)(crsp * cy + sr * sy); + M[6] = (T)(crsp * sy - sr * cy); + M[10] = (T)(cr * cp); +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +//! Sets matrix to rotation matrix defined by axis and angle, assuming LH rotation +template +inline CMatrix4 &CMatrix4::setRotationAxisRadians(const T &angle, const vector3d &axis) +{ + const f64 c = cos(angle); + const f64 s = sin(angle); + const f64 t = 1.0 - c; + + const f64 tx = t * axis.X; + const f64 ty = t * axis.Y; + const f64 tz = t * axis.Z; + + const f64 sx = s * axis.X; + const f64 sy = s * axis.Y; + const f64 sz = s * axis.Z; + + M[0] = (T)(tx * axis.X + c); + M[1] = (T)(tx * axis.Y + sz); + M[2] = (T)(tx * axis.Z - sy); + + M[4] = (T)(ty * axis.X - sz); + M[5] = (T)(ty * axis.Y + c); + M[6] = (T)(ty * axis.Z + sx); + + M[8] = (T)(tz * axis.X + sy); + M[9] = (T)(tz * axis.Y - sx); + M[10] = (T)(tz * axis.Z + c); + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +/*! + */ +template +inline CMatrix4 &CMatrix4::makeIdentity() +{ + memset(M, 0, 16 * sizeof(T)); + M[0] = M[5] = M[10] = M[15] = (T)1; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = true; +#endif + return *this; +} + +/* + check identity with epsilon + solve floating range problems.. +*/ +template +inline bool CMatrix4::isIdentity() const +{ +#if defined(USE_MATRIX_TEST) + if (definitelyIdentityMatrix) + return true; +#endif + if (!core::equals(M[12], (T)0) || !core::equals(M[13], (T)0) || !core::equals(M[14], (T)0) || !core::equals(M[15], (T)1)) + return false; + + if (!core::equals(M[0], (T)1) || !core::equals(M[1], (T)0) || !core::equals(M[2], (T)0) || !core::equals(M[3], (T)0)) + return false; + + if (!core::equals(M[4], (T)0) || !core::equals(M[5], (T)1) || !core::equals(M[6], (T)0) || !core::equals(M[7], (T)0)) + return false; + + if (!core::equals(M[8], (T)0) || !core::equals(M[9], (T)0) || !core::equals(M[10], (T)1) || !core::equals(M[11], (T)0)) + return false; /* if (!core::equals( M[ 0], (T)1 ) || !core::equals( M[ 5], (T)1 ) || @@ -1078,1254 +1069,1218 @@ namespace core if ((j != i) && (!iszero((*this)(i,j)))) return false; */ -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=true; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = true; #endif + return true; +} + +/* Check orthogonality of matrix. */ +template +inline bool CMatrix4::isOrthogonal() const +{ + T dp = M[0] * M[4] + M[1] * M[5] + M[2] * M[6] + M[3] * M[7]; + if (!iszero(dp)) + return false; + dp = M[0] * M[8] + M[1] * M[9] + M[2] * M[10] + M[3] * M[11]; + if (!iszero(dp)) + return false; + dp = M[0] * M[12] + M[1] * M[13] + M[2] * M[14] + M[3] * M[15]; + if (!iszero(dp)) + return false; + dp = M[4] * M[8] + M[5] * M[9] + M[6] * M[10] + M[7] * M[11]; + if (!iszero(dp)) + return false; + dp = M[4] * M[12] + M[5] * M[13] + M[6] * M[14] + M[7] * M[15]; + if (!iszero(dp)) + return false; + dp = M[8] * M[12] + M[9] * M[13] + M[10] * M[14] + M[11] * M[15]; + return (iszero(dp)); +} + +/* + doesn't solve floating range problems.. + but takes care on +/- 0 on translation because we are changing it.. + reducing floating point branches + but it needs the floats in memory.. +*/ +template +inline bool CMatrix4::isIdentity_integer_base() const +{ +#if defined(USE_MATRIX_TEST) + if (definitelyIdentityMatrix) return true; - } - - - /* Check orthogonality of matrix. */ - template - inline bool CMatrix4::isOrthogonal() const - { - T dp=M[0] * M[4 ] + M[1] * M[5 ] + M[2 ] * M[6 ] + M[3 ] * M[7 ]; - if (!iszero(dp)) - return false; - dp = M[0] * M[8 ] + M[1] * M[9 ] + M[2 ] * M[10] + M[3 ] * M[11]; - if (!iszero(dp)) - return false; - dp = M[0] * M[12] + M[1] * M[13] + M[2 ] * M[14] + M[3 ] * M[15]; - if (!iszero(dp)) - return false; - dp = M[4] * M[8 ] + M[5] * M[9 ] + M[6 ] * M[10] + M[7 ] * M[11]; - if (!iszero(dp)) - return false; - dp = M[4] * M[12] + M[5] * M[13] + M[6 ] * M[14] + M[7 ] * M[15]; - if (!iszero(dp)) - return false; - dp = M[8] * M[12] + M[9] * M[13] + M[10] * M[14] + M[11] * M[15]; - return (iszero(dp)); - } - - - /* - doesn't solve floating range problems.. - but takes care on +/- 0 on translation because we are changing it.. - reducing floating point branches - but it needs the floats in memory.. - */ - template - inline bool CMatrix4::isIdentity_integer_base() const - { -#if defined ( USE_MATRIX_TEST ) - if (definitelyIdentityMatrix) - return true; #endif - if(IR(M[0])!=F32_VALUE_1) return false; - if(IR(M[1])!=0) return false; - if(IR(M[2])!=0) return false; - if(IR(M[3])!=0) return false; + if (IR(M[0]) != F32_VALUE_1) + return false; + if (IR(M[1]) != 0) + return false; + if (IR(M[2]) != 0) + return false; + if (IR(M[3]) != 0) + return false; - if(IR(M[4])!=0) return false; - if(IR(M[5])!=F32_VALUE_1) return false; - if(IR(M[6])!=0) return false; - if(IR(M[7])!=0) return false; + if (IR(M[4]) != 0) + return false; + if (IR(M[5]) != F32_VALUE_1) + return false; + if (IR(M[6]) != 0) + return false; + if (IR(M[7]) != 0) + return false; - if(IR(M[8])!=0) return false; - if(IR(M[9])!=0) return false; - if(IR(M[10])!=F32_VALUE_1) return false; - if(IR(M[11])!=0) return false; + if (IR(M[8]) != 0) + return false; + if (IR(M[9]) != 0) + return false; + if (IR(M[10]) != F32_VALUE_1) + return false; + if (IR(M[11]) != 0) + return false; - if(IR(M[12])!=0) return false; - if(IR(M[13])!=0) return false; - if(IR(M[13])!=0) return false; - if(IR(M[15])!=F32_VALUE_1) return false; + if (IR(M[12]) != 0) + return false; + if (IR(M[13]) != 0) + return false; + if (IR(M[13]) != 0) + return false; + if (IR(M[15]) != F32_VALUE_1) + return false; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=true; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = true; #endif - return true; - } + return true; +} +template +inline void CMatrix4::rotateVect(vector3df &vect) const +{ + vector3d tmp(static_cast(vect.X), static_cast(vect.Y), static_cast(vect.Z)); + vect.X = static_cast(tmp.X * M[0] + tmp.Y * M[4] + tmp.Z * M[8]); + vect.Y = static_cast(tmp.X * M[1] + tmp.Y * M[5] + tmp.Z * M[9]); + vect.Z = static_cast(tmp.X * M[2] + tmp.Y * M[6] + tmp.Z * M[10]); +} - template - inline void CMatrix4::rotateVect( vector3df& vect ) const - { - vector3d tmp(static_cast(vect.X), static_cast(vect.Y), static_cast(vect.Z)); - vect.X = static_cast(tmp.X*M[0] + tmp.Y*M[4] + tmp.Z*M[8]); - vect.Y = static_cast(tmp.X*M[1] + tmp.Y*M[5] + tmp.Z*M[9]); - vect.Z = static_cast(tmp.X*M[2] + tmp.Y*M[6] + tmp.Z*M[10]); - } +//! An alternate transform vector method, writing into a second vector +template +inline void CMatrix4::rotateVect(core::vector3df &out, const core::vector3df &in) const +{ + out.X = in.X * M[0] + in.Y * M[4] + in.Z * M[8]; + out.Y = in.X * M[1] + in.Y * M[5] + in.Z * M[9]; + out.Z = in.X * M[2] + in.Y * M[6] + in.Z * M[10]; +} - //! An alternate transform vector method, writing into a second vector - template - inline void CMatrix4::rotateVect(core::vector3df& out, const core::vector3df& in) const - { - out.X = in.X*M[0] + in.Y*M[4] + in.Z*M[8]; - out.Y = in.X*M[1] + in.Y*M[5] + in.Z*M[9]; - out.Z = in.X*M[2] + in.Y*M[6] + in.Z*M[10]; - } +//! An alternate transform vector method, writing into an array of 3 floats +template +inline void CMatrix4::rotateVect(T *out, const core::vector3df &in) const +{ + out[0] = in.X * M[0] + in.Y * M[4] + in.Z * M[8]; + out[1] = in.X * M[1] + in.Y * M[5] + in.Z * M[9]; + out[2] = in.X * M[2] + in.Y * M[6] + in.Z * M[10]; +} - //! An alternate transform vector method, writing into an array of 3 floats - template - inline void CMatrix4::rotateVect(T *out, const core::vector3df& in) const - { - out[0] = in.X*M[0] + in.Y*M[4] + in.Z*M[8]; - out[1] = in.X*M[1] + in.Y*M[5] + in.Z*M[9]; - out[2] = in.X*M[2] + in.Y*M[6] + in.Z*M[10]; - } +template +inline void CMatrix4::inverseRotateVect(vector3df &vect) const +{ + vector3d tmp(static_cast(vect.X), static_cast(vect.Y), static_cast(vect.Z)); + vect.X = static_cast(tmp.X * M[0] + tmp.Y * M[1] + tmp.Z * M[2]); + vect.Y = static_cast(tmp.X * M[4] + tmp.Y * M[5] + tmp.Z * M[6]); + vect.Z = static_cast(tmp.X * M[8] + tmp.Y * M[9] + tmp.Z * M[10]); +} - template - inline void CMatrix4::inverseRotateVect( vector3df& vect ) const - { - vector3d tmp(static_cast(vect.X), static_cast(vect.Y), static_cast(vect.Z)); - vect.X = static_cast(tmp.X*M[0] + tmp.Y*M[1] + tmp.Z*M[2]); - vect.Y = static_cast(tmp.X*M[4] + tmp.Y*M[5] + tmp.Z*M[6]); - vect.Z = static_cast(tmp.X*M[8] + tmp.Y*M[9] + tmp.Z*M[10]); - } +template +inline void CMatrix4::transformVect(vector3df &vect) const +{ + T vector[3]; - template - inline void CMatrix4::transformVect( vector3df& vect) const - { - T vector[3]; + vector[0] = vect.X * M[0] + vect.Y * M[4] + vect.Z * M[8] + M[12]; + vector[1] = vect.X * M[1] + vect.Y * M[5] + vect.Z * M[9] + M[13]; + vector[2] = vect.X * M[2] + vect.Y * M[6] + vect.Z * M[10] + M[14]; - vector[0] = vect.X*M[0] + vect.Y*M[4] + vect.Z*M[8] + M[12]; - vector[1] = vect.X*M[1] + vect.Y*M[5] + vect.Z*M[9] + M[13]; - vector[2] = vect.X*M[2] + vect.Y*M[6] + vect.Z*M[10] + M[14]; + vect.X = static_cast(vector[0]); + vect.Y = static_cast(vector[1]); + vect.Z = static_cast(vector[2]); +} - vect.X = static_cast(vector[0]); - vect.Y = static_cast(vector[1]); - vect.Z = static_cast(vector[2]); - } +template +inline void CMatrix4::transformVect(vector3df &out, const vector3df &in) const +{ + out.X = in.X * M[0] + in.Y * M[4] + in.Z * M[8] + M[12]; + out.Y = in.X * M[1] + in.Y * M[5] + in.Z * M[9] + M[13]; + out.Z = in.X * M[2] + in.Y * M[6] + in.Z * M[10] + M[14]; +} - template - inline void CMatrix4::transformVect( vector3df& out, const vector3df& in) const - { - out.X = in.X*M[0] + in.Y*M[4] + in.Z*M[8] + M[12]; - out.Y = in.X*M[1] + in.Y*M[5] + in.Z*M[9] + M[13]; - out.Z = in.X*M[2] + in.Y*M[6] + in.Z*M[10] + M[14]; - } +template +inline void CMatrix4::transformVect(T *out, const core::vector3df &in) const +{ + out[0] = in.X * M[0] + in.Y * M[4] + in.Z * M[8] + M[12]; + out[1] = in.X * M[1] + in.Y * M[5] + in.Z * M[9] + M[13]; + out[2] = in.X * M[2] + in.Y * M[6] + in.Z * M[10] + M[14]; + out[3] = in.X * M[3] + in.Y * M[7] + in.Z * M[11] + M[15]; +} +template +inline void CMatrix4::transformVec3(T *out, const T *in) const +{ + out[0] = in[0] * M[0] + in[1] * M[4] + in[2] * M[8] + M[12]; + out[1] = in[0] * M[1] + in[1] * M[5] + in[2] * M[9] + M[13]; + out[2] = in[0] * M[2] + in[1] * M[6] + in[2] * M[10] + M[14]; +} - template - inline void CMatrix4::transformVect(T *out, const core::vector3df &in) const - { - out[0] = in.X*M[0] + in.Y*M[4] + in.Z*M[8] + M[12]; - out[1] = in.X*M[1] + in.Y*M[5] + in.Z*M[9] + M[13]; - out[2] = in.X*M[2] + in.Y*M[6] + in.Z*M[10] + M[14]; - out[3] = in.X*M[3] + in.Y*M[7] + in.Z*M[11] + M[15]; - } +template +inline void CMatrix4::transformVec4(T *out, const T *in) const +{ + out[0] = in[0] * M[0] + in[1] * M[4] + in[2] * M[8] + in[3] * M[12]; + out[1] = in[0] * M[1] + in[1] * M[5] + in[2] * M[9] + in[3] * M[13]; + out[2] = in[0] * M[2] + in[1] * M[6] + in[2] * M[10] + in[3] * M[14]; + out[3] = in[0] * M[3] + in[1] * M[7] + in[2] * M[11] + in[3] * M[15]; +} - template - inline void CMatrix4::transformVec3(T *out, const T * in) const - { - out[0] = in[0]*M[0] + in[1]*M[4] + in[2]*M[8] + M[12]; - out[1] = in[0]*M[1] + in[1]*M[5] + in[2]*M[9] + M[13]; - out[2] = in[0]*M[2] + in[1]*M[6] + in[2]*M[10] + M[14]; - } +//! Transforms a plane by this matrix +template +inline void CMatrix4::transformPlane(core::plane3d &plane) const +{ + vector3df member; + // Transform the plane member point, i.e. rotate, translate and scale it. + transformVect(member, plane.getMemberPoint()); - template - inline void CMatrix4::transformVec4(T *out, const T * in) const - { - out[0] = in[0]*M[0] + in[1]*M[4] + in[2]*M[8] + in[3]*M[12]; - out[1] = in[0]*M[1] + in[1]*M[5] + in[2]*M[9] + in[3]*M[13]; - out[2] = in[0]*M[2] + in[1]*M[6] + in[2]*M[10] + in[3]*M[14]; - out[3] = in[0]*M[3] + in[1]*M[7] + in[2]*M[11] + in[3]*M[15]; - } + // Transform the normal by the transposed inverse of the matrix + CMatrix4 transposedInverse(*this, EM4CONST_INVERSE_TRANSPOSED); + vector3df normal = plane.Normal; + transposedInverse.rotateVect(normal); + plane.setPlane(member, normal.normalize()); +} +//! Transforms a plane by this matrix +template +inline void CMatrix4::transformPlane(const core::plane3d &in, core::plane3d &out) const +{ + out = in; + transformPlane(out); +} - //! Transforms a plane by this matrix - template - inline void CMatrix4::transformPlane( core::plane3d &plane) const - { - vector3df member; - // Transform the plane member point, i.e. rotate, translate and scale it. - transformVect(member, plane.getMemberPoint()); - - // Transform the normal by the transposed inverse of the matrix - CMatrix4 transposedInverse(*this, EM4CONST_INVERSE_TRANSPOSED); - vector3df normal = plane.Normal; - transposedInverse.rotateVect(normal); - plane.setPlane(member, normal.normalize()); - } - - //! Transforms a plane by this matrix - template - inline void CMatrix4::transformPlane( const core::plane3d &in, core::plane3d &out) const - { - out = in; - transformPlane( out ); - } - - //! Transforms a axis aligned bounding box more accurately than transformBox() - template - inline void CMatrix4::transformBoxEx(core::aabbox3d& box) const - { -#if defined ( USE_MATRIX_TEST ) - if (isIdentity()) - return; +//! Transforms a axis aligned bounding box more accurately than transformBox() +template +inline void CMatrix4::transformBoxEx(core::aabbox3d &box) const +{ +#if defined(USE_MATRIX_TEST) + if (isIdentity()) + return; #endif - const f32 Amin[3] = {box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z}; - const f32 Amax[3] = {box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z}; + const f32 Amin[3] = {box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z}; + const f32 Amax[3] = {box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z}; - f32 Bmin[3]; - f32 Bmax[3]; + f32 Bmin[3]; + f32 Bmax[3]; - Bmin[0] = Bmax[0] = M[12]; - Bmin[1] = Bmax[1] = M[13]; - Bmin[2] = Bmax[2] = M[14]; + Bmin[0] = Bmax[0] = M[12]; + Bmin[1] = Bmax[1] = M[13]; + Bmin[2] = Bmax[2] = M[14]; - const CMatrix4 &m = *this; + const CMatrix4 &m = *this; - for (u32 i = 0; i < 3; ++i) - { - for (u32 j = 0; j < 3; ++j) - { - const f32 a = m(j,i) * Amin[j]; - const f32 b = m(j,i) * Amax[j]; + for (u32 i = 0; i < 3; ++i) { + for (u32 j = 0; j < 3; ++j) { + const f32 a = m(j, i) * Amin[j]; + const f32 b = m(j, i) * Amax[j]; - if (a < b) - { - Bmin[i] += a; - Bmax[i] += b; - } - else - { - Bmin[i] += b; - Bmax[i] += a; - } + if (a < b) { + Bmin[i] += a; + Bmax[i] += b; + } else { + Bmin[i] += b; + Bmax[i] += a; } } - - box.MinEdge.X = Bmin[0]; - box.MinEdge.Y = Bmin[1]; - box.MinEdge.Z = Bmin[2]; - - box.MaxEdge.X = Bmax[0]; - box.MaxEdge.Y = Bmax[1]; - box.MaxEdge.Z = Bmax[2]; } + box.MinEdge.X = Bmin[0]; + box.MinEdge.Y = Bmin[1]; + box.MinEdge.Z = Bmin[2]; - //! Multiplies this matrix by a 1x4 matrix - template - inline void CMatrix4::multiplyWith1x4Matrix(T* matrix) const - { - /* - 0 1 2 3 - 4 5 6 7 - 8 9 10 11 - 12 13 14 15 - */ + box.MaxEdge.X = Bmax[0]; + box.MaxEdge.Y = Bmax[1]; + box.MaxEdge.Z = Bmax[2]; +} - T mat[4]; - mat[0] = matrix[0]; - mat[1] = matrix[1]; - mat[2] = matrix[2]; - mat[3] = matrix[3]; +//! Multiplies this matrix by a 1x4 matrix +template +inline void CMatrix4::multiplyWith1x4Matrix(T *matrix) const +{ + /* + 0 1 2 3 + 4 5 6 7 + 8 9 10 11 + 12 13 14 15 + */ - matrix[0] = M[0]*mat[0] + M[4]*mat[1] + M[8]*mat[2] + M[12]*mat[3]; - matrix[1] = M[1]*mat[0] + M[5]*mat[1] + M[9]*mat[2] + M[13]*mat[3]; - matrix[2] = M[2]*mat[0] + M[6]*mat[1] + M[10]*mat[2] + M[14]*mat[3]; - matrix[3] = M[3]*mat[0] + M[7]*mat[1] + M[11]*mat[2] + M[15]*mat[3]; + T mat[4]; + mat[0] = matrix[0]; + mat[1] = matrix[1]; + mat[2] = matrix[2]; + mat[3] = matrix[3]; + + matrix[0] = M[0] * mat[0] + M[4] * mat[1] + M[8] * mat[2] + M[12] * mat[3]; + matrix[1] = M[1] * mat[0] + M[5] * mat[1] + M[9] * mat[2] + M[13] * mat[3]; + matrix[2] = M[2] * mat[0] + M[6] * mat[1] + M[10] * mat[2] + M[14] * mat[3]; + matrix[3] = M[3] * mat[0] + M[7] * mat[1] + M[11] * mat[2] + M[15] * mat[3]; +} + +template +inline void CMatrix4::inverseTranslateVect(vector3df &vect) const +{ + vect.X = vect.X - M[12]; + vect.Y = vect.Y - M[13]; + vect.Z = vect.Z - M[14]; +} + +template +inline void CMatrix4::translateVect(vector3df &vect) const +{ + vect.X = vect.X + M[12]; + vect.Y = vect.Y + M[13]; + vect.Z = vect.Z + M[14]; +} + +template +inline bool CMatrix4::getInverse(CMatrix4 &out) const +{ + /// Calculates the inverse of this Matrix + /// The inverse is calculated using Cramers rule. + /// If no inverse exists then 'false' is returned. + +#if defined(USE_MATRIX_TEST) + if (this->isIdentity()) { + out = *this; + return true; } - - template - inline void CMatrix4::inverseTranslateVect( vector3df& vect ) const - { - vect.X = vect.X-M[12]; - vect.Y = vect.Y-M[13]; - vect.Z = vect.Z-M[14]; - } - - template - inline void CMatrix4::translateVect( vector3df& vect ) const - { - vect.X = vect.X+M[12]; - vect.Y = vect.Y+M[13]; - vect.Z = vect.Z+M[14]; - } - - - template - inline bool CMatrix4::getInverse(CMatrix4& out) const - { - /// Calculates the inverse of this Matrix - /// The inverse is calculated using Cramers rule. - /// If no inverse exists then 'false' is returned. - -#if defined ( USE_MATRIX_TEST ) - if ( this->isIdentity() ) - { - out=*this; - return true; - } #endif - const CMatrix4 &m = *this; + const CMatrix4 &m = *this; - f32 d = (m[0] * m[5] - m[1] * m[4]) * (m[10] * m[15] - m[11] * m[14]) - + f32 d = (m[0] * m[5] - m[1] * m[4]) * (m[10] * m[15] - m[11] * m[14]) - (m[0] * m[6] - m[2] * m[4]) * (m[9] * m[15] - m[11] * m[13]) + (m[0] * m[7] - m[3] * m[4]) * (m[9] * m[14] - m[10] * m[13]) + (m[1] * m[6] - m[2] * m[5]) * (m[8] * m[15] - m[11] * m[12]) - (m[1] * m[7] - m[3] * m[5]) * (m[8] * m[14] - m[10] * m[12]) + (m[2] * m[7] - m[3] * m[6]) * (m[8] * m[13] - m[9] * m[12]); - if( core::iszero ( d, FLT_MIN ) ) + if (core::iszero(d, FLT_MIN)) + return false; + + d = core::reciprocal(d); + + out[0] = d * (m[5] * (m[10] * m[15] - m[11] * m[14]) + + m[6] * (m[11] * m[13] - m[9] * m[15]) + + m[7] * (m[9] * m[14] - m[10] * m[13])); + out[1] = d * (m[9] * (m[2] * m[15] - m[3] * m[14]) + + m[10] * (m[3] * m[13] - m[1] * m[15]) + + m[11] * (m[1] * m[14] - m[2] * m[13])); + out[2] = d * (m[13] * (m[2] * m[7] - m[3] * m[6]) + + m[14] * (m[3] * m[5] - m[1] * m[7]) + + m[15] * (m[1] * m[6] - m[2] * m[5])); + out[3] = d * (m[1] * (m[7] * m[10] - m[6] * m[11]) + + m[2] * (m[5] * m[11] - m[7] * m[9]) + + m[3] * (m[6] * m[9] - m[5] * m[10])); + out[4] = d * (m[6] * (m[8] * m[15] - m[11] * m[12]) + + m[7] * (m[10] * m[12] - m[8] * m[14]) + + m[4] * (m[11] * m[14] - m[10] * m[15])); + out[5] = d * (m[10] * (m[0] * m[15] - m[3] * m[12]) + + m[11] * (m[2] * m[12] - m[0] * m[14]) + + m[8] * (m[3] * m[14] - m[2] * m[15])); + out[6] = d * (m[14] * (m[0] * m[7] - m[3] * m[4]) + + m[15] * (m[2] * m[4] - m[0] * m[6]) + + m[12] * (m[3] * m[6] - m[2] * m[7])); + out[7] = d * (m[2] * (m[7] * m[8] - m[4] * m[11]) + + m[3] * (m[4] * m[10] - m[6] * m[8]) + + m[0] * (m[6] * m[11] - m[7] * m[10])); + out[8] = d * (m[7] * (m[8] * m[13] - m[9] * m[12]) + + m[4] * (m[9] * m[15] - m[11] * m[13]) + + m[5] * (m[11] * m[12] - m[8] * m[15])); + out[9] = d * (m[11] * (m[0] * m[13] - m[1] * m[12]) + + m[8] * (m[1] * m[15] - m[3] * m[13]) + + m[9] * (m[3] * m[12] - m[0] * m[15])); + out[10] = d * (m[15] * (m[0] * m[5] - m[1] * m[4]) + + m[12] * (m[1] * m[7] - m[3] * m[5]) + + m[13] * (m[3] * m[4] - m[0] * m[7])); + out[11] = d * (m[3] * (m[5] * m[8] - m[4] * m[9]) + + m[0] * (m[7] * m[9] - m[5] * m[11]) + + m[1] * (m[4] * m[11] - m[7] * m[8])); + out[12] = d * (m[4] * (m[10] * m[13] - m[9] * m[14]) + + m[5] * (m[8] * m[14] - m[10] * m[12]) + + m[6] * (m[9] * m[12] - m[8] * m[13])); + out[13] = d * (m[8] * (m[2] * m[13] - m[1] * m[14]) + + m[9] * (m[0] * m[14] - m[2] * m[12]) + + m[10] * (m[1] * m[12] - m[0] * m[13])); + out[14] = d * (m[12] * (m[2] * m[5] - m[1] * m[6]) + + m[13] * (m[0] * m[6] - m[2] * m[4]) + + m[14] * (m[1] * m[4] - m[0] * m[5])); + out[15] = d * (m[0] * (m[5] * m[10] - m[6] * m[9]) + + m[1] * (m[6] * m[8] - m[4] * m[10]) + + m[2] * (m[4] * m[9] - m[5] * m[8])); + +#if defined(USE_MATRIX_TEST) + out.definitelyIdentityMatrix = definitelyIdentityMatrix; +#endif + return true; +} + +//! Inverts a primitive matrix which only contains a translation and a rotation +//! \param out: where result matrix is written to. +template +inline bool CMatrix4::getInversePrimitive(CMatrix4 &out) const +{ + out.M[0] = M[0]; + out.M[1] = M[4]; + out.M[2] = M[8]; + out.M[3] = 0; + + out.M[4] = M[1]; + out.M[5] = M[5]; + out.M[6] = M[9]; + out.M[7] = 0; + + out.M[8] = M[2]; + out.M[9] = M[6]; + out.M[10] = M[10]; + out.M[11] = 0; + + out.M[12] = (T) - (M[12] * M[0] + M[13] * M[1] + M[14] * M[2]); + out.M[13] = (T) - (M[12] * M[4] + M[13] * M[5] + M[14] * M[6]); + out.M[14] = (T) - (M[12] * M[8] + M[13] * M[9] + M[14] * M[10]); + out.M[15] = 1; + +#if defined(USE_MATRIX_TEST) + out.definitelyIdentityMatrix = definitelyIdentityMatrix; +#endif + return true; +} + +/*! + */ +template +inline bool CMatrix4::makeInverse() +{ +#if defined(USE_MATRIX_TEST) + if (definitelyIdentityMatrix) + return true; +#endif + CMatrix4 temp(EM4CONST_NOTHING); + + if (getInverse(temp)) { + *this = temp; + return true; + } + + return false; +} + +template +inline CMatrix4 &CMatrix4::operator=(const T &scalar) +{ + for (s32 i = 0; i < 16; ++i) + M[i] = scalar; + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a right-handed perspective projection matrix based on a field of view +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixPerspectiveFovRH( + f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero) +{ + const f64 h = reciprocal(tan(fieldOfViewRadians * 0.5)); + _IRR_DEBUG_BREAK_IF(aspectRatio == 0.f); // divide by zero + const T w = static_cast(h / aspectRatio); + + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = w; + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)h; + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = -1; + + M[12] = 0; + M[13] = 0; + // M[14] + M[15] = 0; + + if (zClipFromZero) // DirectX version + { + M[10] = (T)(zFar / (zNear - zFar)); + M[14] = (T)(zNear * zFar / (zNear - zFar)); + } else // OpenGL version + { + M[10] = (T)((zFar + zNear) / (zNear - zFar)); + M[14] = (T)(2.0f * zNear * zFar / (zNear - zFar)); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a left-handed perspective projection matrix based on a field of view +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixPerspectiveFovLH( + f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero) +{ + const f64 h = reciprocal(tan(fieldOfViewRadians * 0.5)); + _IRR_DEBUG_BREAK_IF(aspectRatio == 0.f); // divide by zero + const T w = static_cast(h / aspectRatio); + + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = w; + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)h; + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = 1; + + M[12] = 0; + M[13] = 0; + // M[14] + M[15] = 0; + + if (zClipFromZero) // DirectX version + { + M[10] = (T)(zFar / (zFar - zNear)); + M[14] = (T)(-zNear * zFar / (zFar - zNear)); + } else // OpenGL version + { + M[10] = (T)((zFar + zNear) / (zFar - zNear)); + M[14] = (T)(2.0f * zNear * zFar / (zNear - zFar)); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a left-handed perspective projection matrix based on a field of view, with far plane culling at infinity +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixPerspectiveFovInfinityLH( + f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 epsilon) +{ + const f64 h = reciprocal(tan(fieldOfViewRadians * 0.5)); + _IRR_DEBUG_BREAK_IF(aspectRatio == 0.f); // divide by zero + const T w = static_cast(h / aspectRatio); + + M[0] = w; + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)h; + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + M[10] = (T)(1.f - epsilon); + M[11] = 1; + + M[12] = 0; + M[13] = 0; + M[14] = (T)(zNear * (epsilon - 1.f)); + M[15] = 0; + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a left-handed orthogonal projection matrix. +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixOrthoLH( + f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) +{ + _IRR_DEBUG_BREAK_IF(widthOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(heightOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = (T)(2 / widthOfViewVolume); + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)(2 / heightOfViewVolume); + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = 0; + + M[12] = 0; + M[13] = 0; + // M[14] + M[15] = 1; + + if (zClipFromZero) { + M[10] = (T)(1 / (zFar - zNear)); + M[14] = (T)(zNear / (zNear - zFar)); + } else { + M[10] = (T)(2 / (zFar - zNear)); + M[14] = (T) - (zFar + zNear) / (zFar - zNear); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a right-handed orthogonal projection matrix. +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixOrthoRH( + f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) +{ + _IRR_DEBUG_BREAK_IF(widthOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(heightOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = (T)(2 / widthOfViewVolume); + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)(2 / heightOfViewVolume); + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = 0; + + M[12] = 0; + M[13] = 0; + // M[14] + M[15] = 1; + + if (zClipFromZero) { + M[10] = (T)(1 / (zNear - zFar)); + M[14] = (T)(zNear / (zNear - zFar)); + } else { + M[10] = (T)(2 / (zNear - zFar)); + M[14] = (T) - (zFar + zNear) / (zFar - zNear); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a right-handed perspective projection matrix. +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixPerspectiveRH( + f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) +{ + _IRR_DEBUG_BREAK_IF(widthOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(heightOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = (T)(2 * zNear / widthOfViewVolume); + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)(2 * zNear / heightOfViewVolume); + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = -1; + + M[12] = 0; + M[13] = 0; + // M[14] + M[15] = 0; + + if (zClipFromZero) // DirectX version + { + M[10] = (T)(zFar / (zNear - zFar)); + M[14] = (T)(zNear * zFar / (zNear - zFar)); + } else // OpenGL version + { + M[10] = (T)((zFar + zNear) / (zNear - zFar)); + M[14] = (T)(2.0f * zNear * zFar / (zNear - zFar)); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a left-handed perspective projection matrix. +template +inline CMatrix4 &CMatrix4::buildProjectionMatrixPerspectiveLH( + f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) +{ + _IRR_DEBUG_BREAK_IF(widthOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(heightOfViewVolume == 0.f); // divide by zero + _IRR_DEBUG_BREAK_IF(zNear == zFar); // divide by zero + M[0] = (T)(2 * zNear / widthOfViewVolume); + M[1] = 0; + M[2] = 0; + M[3] = 0; + + M[4] = 0; + M[5] = (T)(2 * zNear / heightOfViewVolume); + M[6] = 0; + M[7] = 0; + + M[8] = 0; + M[9] = 0; + // M[10] + M[11] = 1; + + M[12] = 0; + M[13] = 0; + // M[14] = (T)(zNear*zFar/(zNear-zFar)); + M[15] = 0; + + if (zClipFromZero) // DirectX version + { + M[10] = (T)(zFar / (zFar - zNear)); + M[14] = (T)(zNear * zFar / (zNear - zFar)); + } else // OpenGL version + { + M[10] = (T)((zFar + zNear) / (zFar - zNear)); + M[14] = (T)(2.0f * zNear * zFar / (zNear - zFar)); + } + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a matrix that flattens geometry into a plane. +template +inline CMatrix4 &CMatrix4::buildShadowMatrix(const core::vector3df &light, core::plane3df plane, f32 point) +{ + plane.Normal.normalize(); + const f32 d = plane.Normal.dotProduct(light); + + M[0] = (T)(-plane.Normal.X * light.X + d); + M[1] = (T)(-plane.Normal.X * light.Y); + M[2] = (T)(-plane.Normal.X * light.Z); + M[3] = (T)(-plane.Normal.X * point); + + M[4] = (T)(-plane.Normal.Y * light.X); + M[5] = (T)(-plane.Normal.Y * light.Y + d); + M[6] = (T)(-plane.Normal.Y * light.Z); + M[7] = (T)(-plane.Normal.Y * point); + + M[8] = (T)(-plane.Normal.Z * light.X); + M[9] = (T)(-plane.Normal.Z * light.Y); + M[10] = (T)(-plane.Normal.Z * light.Z + d); + M[11] = (T)(-plane.Normal.Z * point); + + M[12] = (T)(-plane.D * light.X); + M[13] = (T)(-plane.D * light.Y); + M[14] = (T)(-plane.D * light.Z); + M[15] = (T)(-plane.D * point + d); +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a left-handed look-at matrix. +template +inline CMatrix4 &CMatrix4::buildCameraLookAtMatrixLH( + const vector3df &position, + const vector3df &target, + const vector3df &upVector) +{ + vector3df zaxis = target - position; + zaxis.normalize(); + + vector3df xaxis = upVector.crossProduct(zaxis); + xaxis.normalize(); + + vector3df yaxis = zaxis.crossProduct(xaxis); + + M[0] = (T)xaxis.X; + M[1] = (T)yaxis.X; + M[2] = (T)zaxis.X; + M[3] = 0; + + M[4] = (T)xaxis.Y; + M[5] = (T)yaxis.Y; + M[6] = (T)zaxis.Y; + M[7] = 0; + + M[8] = (T)xaxis.Z; + M[9] = (T)yaxis.Z; + M[10] = (T)zaxis.Z; + M[11] = 0; + + M[12] = (T)-xaxis.dotProduct(position); + M[13] = (T)-yaxis.dotProduct(position); + M[14] = (T)-zaxis.dotProduct(position); + M[15] = 1; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// Builds a right-handed look-at matrix. +template +inline CMatrix4 &CMatrix4::buildCameraLookAtMatrixRH( + const vector3df &position, + const vector3df &target, + const vector3df &upVector) +{ + vector3df zaxis = position - target; + zaxis.normalize(); + + vector3df xaxis = upVector.crossProduct(zaxis); + xaxis.normalize(); + + vector3df yaxis = zaxis.crossProduct(xaxis); + + M[0] = (T)xaxis.X; + M[1] = (T)yaxis.X; + M[2] = (T)zaxis.X; + M[3] = 0; + + M[4] = (T)xaxis.Y; + M[5] = (T)yaxis.Y; + M[6] = (T)zaxis.Y; + M[7] = 0; + + M[8] = (T)xaxis.Z; + M[9] = (T)yaxis.Z; + M[10] = (T)zaxis.Z; + M[11] = 0; + + M[12] = (T)-xaxis.dotProduct(position); + M[13] = (T)-yaxis.dotProduct(position); + M[14] = (T)-zaxis.dotProduct(position); + M[15] = 1; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// creates a new matrix as interpolated matrix from this and the passed one. +template +inline CMatrix4 CMatrix4::interpolate(const core::CMatrix4 &b, f32 time) const +{ + CMatrix4 mat(EM4CONST_NOTHING); + + for (u32 i = 0; i < 16; i += 4) { + mat.M[i + 0] = (T)(M[i + 0] + (b.M[i + 0] - M[i + 0]) * time); + mat.M[i + 1] = (T)(M[i + 1] + (b.M[i + 1] - M[i + 1]) * time); + mat.M[i + 2] = (T)(M[i + 2] + (b.M[i + 2] - M[i + 2]) * time); + mat.M[i + 3] = (T)(M[i + 3] + (b.M[i + 3] - M[i + 3]) * time); + } + return mat; +} + +// returns transposed matrix +template +inline CMatrix4 CMatrix4::getTransposed() const +{ + CMatrix4 t(EM4CONST_NOTHING); + getTransposed(t); + return t; +} + +// returns transposed matrix +template +inline void CMatrix4::getTransposed(CMatrix4 &o) const +{ + o[0] = M[0]; + o[1] = M[4]; + o[2] = M[8]; + o[3] = M[12]; + + o[4] = M[1]; + o[5] = M[5]; + o[6] = M[9]; + o[7] = M[13]; + + o[8] = M[2]; + o[9] = M[6]; + o[10] = M[10]; + o[11] = M[14]; + + o[12] = M[3]; + o[13] = M[7]; + o[14] = M[11]; + o[15] = M[15]; +#if defined(USE_MATRIX_TEST) + o.definitelyIdentityMatrix = definitelyIdentityMatrix; +#endif +} + +// used to scale <-1,-1><1,1> to viewport +template +inline CMatrix4 &CMatrix4::buildNDCToDCMatrix(const core::rect &viewport, f32 zScale) +{ + const f32 scaleX = (viewport.getWidth() - 0.75f) * 0.5f; + const f32 scaleY = -(viewport.getHeight() - 0.75f) * 0.5f; + + const f32 dx = -0.5f + ((viewport.UpperLeftCorner.X + viewport.LowerRightCorner.X) * 0.5f); + const f32 dy = -0.5f + ((viewport.UpperLeftCorner.Y + viewport.LowerRightCorner.Y) * 0.5f); + + makeIdentity(); + M[12] = (T)dx; + M[13] = (T)dy; + return setScale(core::vector3d((T)scaleX, (T)scaleY, (T)zScale)); +} + +//! Builds a matrix that rotates from one vector to another +/** \param from: vector to rotate from +\param to: vector to rotate to + + http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm + */ +template +inline CMatrix4 &CMatrix4::buildRotateFromTo(const core::vector3df &from, const core::vector3df &to) +{ + // unit vectors + core::vector3df f(from); + core::vector3df t(to); + f.normalize(); + t.normalize(); + + // axis multiplication by sin + core::vector3df vs(t.crossProduct(f)); + + // axis of rotation + core::vector3df v(vs); + v.normalize(); + + // cosine angle + T ca = f.dotProduct(t); + + core::vector3df vt(v * (1 - ca)); + + M[0] = vt.X * v.X + ca; + M[5] = vt.Y * v.Y + ca; + M[10] = vt.Z * v.Z + ca; + + vt.X *= v.Y; + vt.Z *= v.X; + vt.Y *= v.Z; + + M[1] = vt.X - vs.Z; + M[2] = vt.Z + vs.Y; + M[3] = 0; + + M[4] = vt.X + vs.Z; + M[6] = vt.Y - vs.X; + M[7] = 0; + + M[8] = vt.Z - vs.Y; + M[9] = vt.Y + vs.X; + M[11] = 0; + + M[12] = 0; + M[13] = 0; + M[14] = 0; + M[15] = 1; + + return *this; +} + +//! Builds a matrix which rotates a source vector to a look vector over an arbitrary axis +/** \param camPos: viewer position in world coord +\param center: object position in world-coord, rotation pivot +\param translation: object final translation from center +\param axis: axis to rotate about +\param from: source vector to rotate from + */ +template +inline void CMatrix4::buildAxisAlignedBillboard( + const core::vector3df &camPos, + const core::vector3df ¢er, + const core::vector3df &translation, + const core::vector3df &axis, + const core::vector3df &from) +{ + // axis of rotation + core::vector3df up = axis; + up.normalize(); + const core::vector3df forward = (camPos - center).normalize(); + const core::vector3df right = up.crossProduct(forward).normalize(); + + // correct look vector + const core::vector3df look = right.crossProduct(up); + + // rotate from to + // axis multiplication by sin + const core::vector3df vs = look.crossProduct(from); + + // cosine angle + const f32 ca = from.dotProduct(look); + + core::vector3df vt(up * (1.f - ca)); + + M[0] = static_cast(vt.X * up.X + ca); + M[5] = static_cast(vt.Y * up.Y + ca); + M[10] = static_cast(vt.Z * up.Z + ca); + + vt.X *= up.Y; + vt.Z *= up.X; + vt.Y *= up.Z; + + M[1] = static_cast(vt.X - vs.Z); + M[2] = static_cast(vt.Z + vs.Y); + M[3] = 0; + + M[4] = static_cast(vt.X + vs.Z); + M[6] = static_cast(vt.Y - vs.X); + M[7] = 0; + + M[8] = static_cast(vt.Z - vs.Y); + M[9] = static_cast(vt.Y + vs.X); + M[11] = 0; + + setRotationCenter(center, translation); +} + +//! Builds a combined matrix which translate to a center before rotation and translate afterward +template +inline void CMatrix4::setRotationCenter(const core::vector3df ¢er, const core::vector3df &translation) +{ + M[12] = -M[0] * center.X - M[4] * center.Y - M[8] * center.Z + (center.X - translation.X); + M[13] = -M[1] * center.X - M[5] * center.Y - M[9] * center.Z + (center.Y - translation.Y); + M[14] = -M[2] * center.X - M[6] * center.Y - M[10] * center.Z + (center.Z - translation.Z); + M[15] = (T)1.0; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif +} + +/*! + Generate texture coordinates as linear functions so that: + u = Ux*x + Uy*y + Uz*z + Uw + v = Vx*x + Vy*y + Vz*z + Vw + The matrix M for this case is: + Ux Vx 0 0 + Uy Vy 0 0 + Uz Vz 0 0 + Uw Vw 0 0 +*/ + +template +inline CMatrix4 &CMatrix4::buildTextureTransform(f32 rotateRad, + const core::vector2df &rotatecenter, + const core::vector2df &translate, + const core::vector2df &scale) +{ + const f32 c = cosf(rotateRad); + const f32 s = sinf(rotateRad); + + M[0] = (T)(c * scale.X); + M[1] = (T)(s * scale.Y); + M[2] = 0; + M[3] = 0; + + M[4] = (T)(-s * scale.X); + M[5] = (T)(c * scale.Y); + M[6] = 0; + M[7] = 0; + + M[8] = (T)(c * scale.X * rotatecenter.X + -s * rotatecenter.Y + translate.X); + M[9] = (T)(s * scale.Y * rotatecenter.X + c * rotatecenter.Y + translate.Y); + M[10] = 1; + M[11] = 0; + + M[12] = 0; + M[13] = 0; + M[14] = 0; + M[15] = 1; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// rotate about z axis, center ( 0.5, 0.5 ) +template +inline CMatrix4 &CMatrix4::setTextureRotationCenter(f32 rotateRad) +{ + const f32 c = cosf(rotateRad); + const f32 s = sinf(rotateRad); + M[0] = (T)c; + M[1] = (T)s; + + M[4] = (T)-s; + M[5] = (T)c; + + M[8] = (T)(0.5f * (s - c) + 0.5f); + M[9] = (T)(-0.5f * (s + c) + 0.5f); + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = definitelyIdentityMatrix && (rotateRad == 0.0f); +#endif + return *this; +} + +template +inline CMatrix4 &CMatrix4::setTextureTranslate(f32 x, f32 y) +{ + M[8] = (T)x; + M[9] = (T)y; + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = definitelyIdentityMatrix && (x == 0.0f) && (y == 0.0f); +#endif + return *this; +} + +template +inline void CMatrix4::getTextureTranslate(f32 &x, f32 &y) const +{ + x = (f32)M[8]; + y = (f32)M[9]; +} + +template +inline CMatrix4 &CMatrix4::setTextureTranslateTransposed(f32 x, f32 y) +{ + M[2] = (T)x; + M[6] = (T)y; + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = definitelyIdentityMatrix && (x == 0.0f) && (y == 0.0f); +#endif + return *this; +} + +template +inline CMatrix4 &CMatrix4::setTextureScale(f32 sx, f32 sy) +{ + M[0] = (T)sx; + M[5] = (T)sy; +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = definitelyIdentityMatrix && (sx == 1.0f) && (sy == 1.0f); +#endif + return *this; +} + +template +inline void CMatrix4::getTextureScale(f32 &sx, f32 &sy) const +{ + sx = (f32)M[0]; + sy = (f32)M[5]; +} + +template +inline CMatrix4 &CMatrix4::setTextureScaleCenter(f32 sx, f32 sy) +{ + M[0] = (T)sx; + M[5] = (T)sy; + M[8] = (T)(0.5f - 0.5f * sx); + M[9] = (T)(0.5f - 0.5f * sy); + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = definitelyIdentityMatrix && (sx == 1.0f) && (sy == 1.0f); +#endif + return *this; +} + +// sets all matrix data members at once +template +inline CMatrix4 &CMatrix4::setM(const T *data) +{ + memcpy(M, data, 16 * sizeof(T)); + +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = false; +#endif + return *this; +} + +// sets if the matrix is definitely identity matrix +template +inline void CMatrix4::setDefinitelyIdentityMatrix(bool isDefinitelyIdentityMatrix) +{ +#if defined(USE_MATRIX_TEST) + definitelyIdentityMatrix = isDefinitelyIdentityMatrix; +#else + (void)isDefinitelyIdentityMatrix; // prevent compiler warning +#endif +} + +// gets if the matrix is definitely identity matrix +template +inline bool CMatrix4::getDefinitelyIdentityMatrix() const +{ +#if defined(USE_MATRIX_TEST) + return definitelyIdentityMatrix; +#else + return false; +#endif +} + +//! Compare two matrices using the equal method +template +inline bool CMatrix4::equals(const core::CMatrix4 &other, const T tolerance) const +{ +#if defined(USE_MATRIX_TEST) + if (definitelyIdentityMatrix && other.definitelyIdentityMatrix) + return true; +#endif + for (s32 i = 0; i < 16; ++i) + if (!core::equals(M[i], other.M[i], tolerance)) return false; - d = core::reciprocal ( d ); + return true; +} - out[0] = d * (m[5] * (m[10] * m[15] - m[11] * m[14]) + - m[6] * (m[11] * m[13] - m[9] * m[15]) + - m[7] * (m[9] * m[14] - m[10] * m[13])); - out[1] = d * (m[9] * (m[2] * m[15] - m[3] * m[14]) + - m[10] * (m[3] * m[13] - m[1] * m[15]) + - m[11] * (m[1] * m[14] - m[2] * m[13])); - out[2] = d * (m[13] * (m[2] * m[7] - m[3] * m[6]) + - m[14] * (m[3] * m[5] - m[1] * m[7]) + - m[15] * (m[1] * m[6] - m[2] * m[5])); - out[3] = d * (m[1] * (m[7] * m[10] - m[6] * m[11]) + - m[2] * (m[5] * m[11] - m[7] * m[9]) + - m[3] * (m[6] * m[9] - m[5] * m[10])); - out[4] = d * (m[6] * (m[8] * m[15] - m[11] * m[12]) + - m[7] * (m[10] * m[12] - m[8] * m[14]) + - m[4] * (m[11] * m[14] - m[10] * m[15])); - out[5] = d * (m[10] * (m[0] * m[15] - m[3] * m[12]) + - m[11] * (m[2] * m[12] - m[0] * m[14]) + - m[8] * (m[3] * m[14] - m[2] * m[15])); - out[6] = d * (m[14] * (m[0] * m[7] - m[3] * m[4]) + - m[15] * (m[2] * m[4] - m[0] * m[6]) + - m[12] * (m[3] * m[6] - m[2] * m[7])); - out[7] = d * (m[2] * (m[7] * m[8] - m[4] * m[11]) + - m[3] * (m[4] * m[10] - m[6] * m[8]) + - m[0] * (m[6] * m[11] - m[7] * m[10])); - out[8] = d * (m[7] * (m[8] * m[13] - m[9] * m[12]) + - m[4] * (m[9] * m[15] - m[11] * m[13]) + - m[5] * (m[11] * m[12] - m[8] * m[15])); - out[9] = d * (m[11] * (m[0] * m[13] - m[1] * m[12]) + - m[8] * (m[1] * m[15] - m[3] * m[13]) + - m[9] * (m[3] * m[12] - m[0] * m[15])); - out[10] = d * (m[15] * (m[0] * m[5] - m[1] * m[4]) + - m[12] * (m[1] * m[7] - m[3] * m[5]) + - m[13] * (m[3] * m[4] - m[0] * m[7])); - out[11] = d * (m[3] * (m[5] * m[8] - m[4] * m[9]) + - m[0] * (m[7] * m[9] - m[5] * m[11]) + - m[1] * (m[4] * m[11] - m[7] * m[8])); - out[12] = d * (m[4] * (m[10] * m[13] - m[9] * m[14]) + - m[5] * (m[8] * m[14] - m[10] * m[12]) + - m[6] * (m[9] * m[12] - m[8] * m[13])); - out[13] = d * (m[8] * (m[2] * m[13] - m[1] * m[14]) + - m[9] * (m[0] * m[14] - m[2] * m[12]) + - m[10] * (m[1] * m[12] - m[0] * m[13])); - out[14] = d * (m[12] * (m[2] * m[5] - m[1] * m[6]) + - m[13] * (m[0] * m[6] - m[2] * m[4]) + - m[14] * (m[1] * m[4] - m[0] * m[5])); - out[15] = d * (m[0] * (m[5] * m[10] - m[6] * m[9]) + - m[1] * (m[6] * m[8] - m[4] * m[10]) + - m[2] * (m[4] * m[9] - m[5] * m[8])); +// Multiply by scalar. +template +inline CMatrix4 operator*(const T scalar, const CMatrix4 &mat) +{ + return mat * scalar; +} -#if defined ( USE_MATRIX_TEST ) - out.definitelyIdentityMatrix = definitelyIdentityMatrix; -#endif - return true; - } +//! Typedef for f32 matrix +typedef CMatrix4 matrix4; - - //! Inverts a primitive matrix which only contains a translation and a rotation - //! \param out: where result matrix is written to. - template - inline bool CMatrix4::getInversePrimitive ( CMatrix4& out ) const - { - out.M[0 ] = M[0]; - out.M[1 ] = M[4]; - out.M[2 ] = M[8]; - out.M[3 ] = 0; - - out.M[4 ] = M[1]; - out.M[5 ] = M[5]; - out.M[6 ] = M[9]; - out.M[7 ] = 0; - - out.M[8 ] = M[2]; - out.M[9 ] = M[6]; - out.M[10] = M[10]; - out.M[11] = 0; - - out.M[12] = (T)-(M[12]*M[0] + M[13]*M[1] + M[14]*M[2]); - out.M[13] = (T)-(M[12]*M[4] + M[13]*M[5] + M[14]*M[6]); - out.M[14] = (T)-(M[12]*M[8] + M[13]*M[9] + M[14]*M[10]); - out.M[15] = 1; - -#if defined ( USE_MATRIX_TEST ) - out.definitelyIdentityMatrix = definitelyIdentityMatrix; -#endif - return true; - } - - /*! - */ - template - inline bool CMatrix4::makeInverse() - { -#if defined ( USE_MATRIX_TEST ) - if (definitelyIdentityMatrix) - return true; -#endif - CMatrix4 temp ( EM4CONST_NOTHING ); - - if (getInverse(temp)) - { - *this = temp; - return true; - } - - return false; - } - - - template - inline CMatrix4& CMatrix4::operator=(const T& scalar) - { - for (s32 i = 0; i < 16; ++i) - M[i]=scalar; - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a right-handed perspective projection matrix based on a field of view - template - inline CMatrix4& CMatrix4::buildProjectionMatrixPerspectiveFovRH( - f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero) - { - const f64 h = reciprocal(tan(fieldOfViewRadians*0.5)); - _IRR_DEBUG_BREAK_IF(aspectRatio==0.f); //divide by zero - const T w = static_cast(h / aspectRatio); - - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = w; - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)h; - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - //M[10] - M[11] = -1; - - M[12] = 0; - M[13] = 0; - //M[14] - M[15] = 0; - - if ( zClipFromZero ) // DirectX version - { - M[10] = (T)(zFar/(zNear-zFar)); - M[14] = (T)(zNear*zFar/(zNear-zFar)); - } - else // OpenGL version - { - M[10] = (T)((zFar+zNear)/(zNear-zFar)); - M[14] = (T)(2.0f*zNear*zFar/(zNear-zFar)); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a left-handed perspective projection matrix based on a field of view - template - inline CMatrix4& CMatrix4::buildProjectionMatrixPerspectiveFovLH( - f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 zFar, bool zClipFromZero) - { - const f64 h = reciprocal(tan(fieldOfViewRadians*0.5)); - _IRR_DEBUG_BREAK_IF(aspectRatio==0.f); //divide by zero - const T w = static_cast(h / aspectRatio); - - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = w; - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)h; - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - //M[10] - M[11] = 1; - - M[12] = 0; - M[13] = 0; - //M[14] - M[15] = 0; - - if ( zClipFromZero ) // DirectX version - { - M[10] = (T)(zFar/(zFar-zNear)); - M[14] = (T)(-zNear*zFar/(zFar-zNear)); - } - else // OpenGL version - { - M[10] = (T)((zFar+zNear)/(zFar-zNear)); - M[14] = (T)(2.0f*zNear*zFar/(zNear-zFar)); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a left-handed perspective projection matrix based on a field of view, with far plane culling at infinity - template - inline CMatrix4& CMatrix4::buildProjectionMatrixPerspectiveFovInfinityLH( - f32 fieldOfViewRadians, f32 aspectRatio, f32 zNear, f32 epsilon) - { - const f64 h = reciprocal(tan(fieldOfViewRadians*0.5)); - _IRR_DEBUG_BREAK_IF(aspectRatio==0.f); //divide by zero - const T w = static_cast(h / aspectRatio); - - M[0] = w; - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)h; - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - M[10] = (T)(1.f-epsilon); - M[11] = 1; - - M[12] = 0; - M[13] = 0; - M[14] = (T)(zNear*(epsilon-1.f)); - M[15] = 0; - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a left-handed orthogonal projection matrix. - template - inline CMatrix4& CMatrix4::buildProjectionMatrixOrthoLH( - f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) - { - _IRR_DEBUG_BREAK_IF(widthOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(heightOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = (T)(2/widthOfViewVolume); - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)(2/heightOfViewVolume); - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - // M[10] - M[11] = 0; - - M[12] = 0; - M[13] = 0; - // M[14] - M[15] = 1; - - if ( zClipFromZero ) - { - M[10] = (T)(1/(zFar-zNear)); - M[14] = (T)(zNear/(zNear-zFar)); - } - else - { - M[10] = (T)(2/(zFar-zNear)); - M[14] = (T)-(zFar+zNear)/(zFar-zNear); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a right-handed orthogonal projection matrix. - template - inline CMatrix4& CMatrix4::buildProjectionMatrixOrthoRH( - f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) - { - _IRR_DEBUG_BREAK_IF(widthOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(heightOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = (T)(2/widthOfViewVolume); - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)(2/heightOfViewVolume); - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - // M[10] - M[11] = 0; - - M[12] = 0; - M[13] = 0; - // M[14] - M[15] = 1; - - if ( zClipFromZero ) - { - M[10] = (T)(1/(zNear-zFar)); - M[14] = (T)(zNear/(zNear-zFar)); - } - else - { - M[10] = (T)(2/(zNear-zFar)); - M[14] = (T)-(zFar+zNear)/(zFar-zNear); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a right-handed perspective projection matrix. - template - inline CMatrix4& CMatrix4::buildProjectionMatrixPerspectiveRH( - f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) - { - _IRR_DEBUG_BREAK_IF(widthOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(heightOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = (T)(2*zNear/widthOfViewVolume); - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)(2*zNear/heightOfViewVolume); - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - //M[10] - M[11] = -1; - - M[12] = 0; - M[13] = 0; - //M[14] - M[15] = 0; - - if ( zClipFromZero ) // DirectX version - { - M[10] = (T)(zFar/(zNear-zFar)); - M[14] = (T)(zNear*zFar/(zNear-zFar)); - } - else // OpenGL version - { - M[10] = (T)((zFar+zNear)/(zNear-zFar)); - M[14] = (T)(2.0f*zNear*zFar/(zNear-zFar)); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a left-handed perspective projection matrix. - template - inline CMatrix4& CMatrix4::buildProjectionMatrixPerspectiveLH( - f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar, bool zClipFromZero) - { - _IRR_DEBUG_BREAK_IF(widthOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(heightOfViewVolume==0.f); //divide by zero - _IRR_DEBUG_BREAK_IF(zNear==zFar); //divide by zero - M[0] = (T)(2*zNear/widthOfViewVolume); - M[1] = 0; - M[2] = 0; - M[3] = 0; - - M[4] = 0; - M[5] = (T)(2*zNear/heightOfViewVolume); - M[6] = 0; - M[7] = 0; - - M[8] = 0; - M[9] = 0; - //M[10] - M[11] = 1; - - M[12] = 0; - M[13] = 0; - //M[14] = (T)(zNear*zFar/(zNear-zFar)); - M[15] = 0; - - if ( zClipFromZero ) // DirectX version - { - M[10] = (T)(zFar/(zFar-zNear)); - M[14] = (T)(zNear*zFar/(zNear-zFar)); - } - else // OpenGL version - { - M[10] = (T)((zFar+zNear)/(zFar-zNear)); - M[14] = (T)(2.0f*zNear*zFar/(zNear-zFar)); - } - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a matrix that flattens geometry into a plane. - template - inline CMatrix4& CMatrix4::buildShadowMatrix(const core::vector3df& light, core::plane3df plane, f32 point) - { - plane.Normal.normalize(); - const f32 d = plane.Normal.dotProduct(light); - - M[ 0] = (T)(-plane.Normal.X * light.X + d); - M[ 1] = (T)(-plane.Normal.X * light.Y); - M[ 2] = (T)(-plane.Normal.X * light.Z); - M[ 3] = (T)(-plane.Normal.X * point); - - M[ 4] = (T)(-plane.Normal.Y * light.X); - M[ 5] = (T)(-plane.Normal.Y * light.Y + d); - M[ 6] = (T)(-plane.Normal.Y * light.Z); - M[ 7] = (T)(-plane.Normal.Y * point); - - M[ 8] = (T)(-plane.Normal.Z * light.X); - M[ 9] = (T)(-plane.Normal.Z * light.Y); - M[10] = (T)(-plane.Normal.Z * light.Z + d); - M[11] = (T)(-plane.Normal.Z * point); - - M[12] = (T)(-plane.D * light.X); - M[13] = (T)(-plane.D * light.Y); - M[14] = (T)(-plane.D * light.Z); - M[15] = (T)(-plane.D * point + d); -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - // Builds a left-handed look-at matrix. - template - inline CMatrix4& CMatrix4::buildCameraLookAtMatrixLH( - const vector3df& position, - const vector3df& target, - const vector3df& upVector) - { - vector3df zaxis = target - position; - zaxis.normalize(); - - vector3df xaxis = upVector.crossProduct(zaxis); - xaxis.normalize(); - - vector3df yaxis = zaxis.crossProduct(xaxis); - - M[0] = (T)xaxis.X; - M[1] = (T)yaxis.X; - M[2] = (T)zaxis.X; - M[3] = 0; - - M[4] = (T)xaxis.Y; - M[5] = (T)yaxis.Y; - M[6] = (T)zaxis.Y; - M[7] = 0; - - M[8] = (T)xaxis.Z; - M[9] = (T)yaxis.Z; - M[10] = (T)zaxis.Z; - M[11] = 0; - - M[12] = (T)-xaxis.dotProduct(position); - M[13] = (T)-yaxis.dotProduct(position); - M[14] = (T)-zaxis.dotProduct(position); - M[15] = 1; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // Builds a right-handed look-at matrix. - template - inline CMatrix4& CMatrix4::buildCameraLookAtMatrixRH( - const vector3df& position, - const vector3df& target, - const vector3df& upVector) - { - vector3df zaxis = position - target; - zaxis.normalize(); - - vector3df xaxis = upVector.crossProduct(zaxis); - xaxis.normalize(); - - vector3df yaxis = zaxis.crossProduct(xaxis); - - M[0] = (T)xaxis.X; - M[1] = (T)yaxis.X; - M[2] = (T)zaxis.X; - M[3] = 0; - - M[4] = (T)xaxis.Y; - M[5] = (T)yaxis.Y; - M[6] = (T)zaxis.Y; - M[7] = 0; - - M[8] = (T)xaxis.Z; - M[9] = (T)yaxis.Z; - M[10] = (T)zaxis.Z; - M[11] = 0; - - M[12] = (T)-xaxis.dotProduct(position); - M[13] = (T)-yaxis.dotProduct(position); - M[14] = (T)-zaxis.dotProduct(position); - M[15] = 1; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // creates a new matrix as interpolated matrix from this and the passed one. - template - inline CMatrix4 CMatrix4::interpolate(const core::CMatrix4& b, f32 time) const - { - CMatrix4 mat ( EM4CONST_NOTHING ); - - for (u32 i=0; i < 16; i += 4) - { - mat.M[i+0] = (T)(M[i+0] + ( b.M[i+0] - M[i+0] ) * time); - mat.M[i+1] = (T)(M[i+1] + ( b.M[i+1] - M[i+1] ) * time); - mat.M[i+2] = (T)(M[i+2] + ( b.M[i+2] - M[i+2] ) * time); - mat.M[i+3] = (T)(M[i+3] + ( b.M[i+3] - M[i+3] ) * time); - } - return mat; - } - - - // returns transposed matrix - template - inline CMatrix4 CMatrix4::getTransposed() const - { - CMatrix4 t ( EM4CONST_NOTHING ); - getTransposed ( t ); - return t; - } - - - // returns transposed matrix - template - inline void CMatrix4::getTransposed( CMatrix4& o ) const - { - o[ 0] = M[ 0]; - o[ 1] = M[ 4]; - o[ 2] = M[ 8]; - o[ 3] = M[12]; - - o[ 4] = M[ 1]; - o[ 5] = M[ 5]; - o[ 6] = M[ 9]; - o[ 7] = M[13]; - - o[ 8] = M[ 2]; - o[ 9] = M[ 6]; - o[10] = M[10]; - o[11] = M[14]; - - o[12] = M[ 3]; - o[13] = M[ 7]; - o[14] = M[11]; - o[15] = M[15]; -#if defined ( USE_MATRIX_TEST ) - o.definitelyIdentityMatrix=definitelyIdentityMatrix; -#endif - } - - - // used to scale <-1,-1><1,1> to viewport - template - inline CMatrix4& CMatrix4::buildNDCToDCMatrix( const core::rect& viewport, f32 zScale) - { - const f32 scaleX = (viewport.getWidth() - 0.75f ) * 0.5f; - const f32 scaleY = -(viewport.getHeight() - 0.75f ) * 0.5f; - - const f32 dx = -0.5f + ( (viewport.UpperLeftCorner.X + viewport.LowerRightCorner.X ) * 0.5f ); - const f32 dy = -0.5f + ( (viewport.UpperLeftCorner.Y + viewport.LowerRightCorner.Y ) * 0.5f ); - - makeIdentity(); - M[12] = (T)dx; - M[13] = (T)dy; - return setScale(core::vector3d((T)scaleX, (T)scaleY, (T)zScale)); - } - - //! Builds a matrix that rotates from one vector to another - /** \param from: vector to rotate from - \param to: vector to rotate to - - http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm - */ - template - inline CMatrix4& CMatrix4::buildRotateFromTo(const core::vector3df& from, const core::vector3df& to) - { - // unit vectors - core::vector3df f(from); - core::vector3df t(to); - f.normalize(); - t.normalize(); - - // axis multiplication by sin - core::vector3df vs(t.crossProduct(f)); - - // axis of rotation - core::vector3df v(vs); - v.normalize(); - - // cosine angle - T ca = f.dotProduct(t); - - core::vector3df vt(v * (1 - ca)); - - M[0] = vt.X * v.X + ca; - M[5] = vt.Y * v.Y + ca; - M[10] = vt.Z * v.Z + ca; - - vt.X *= v.Y; - vt.Z *= v.X; - vt.Y *= v.Z; - - M[1] = vt.X - vs.Z; - M[2] = vt.Z + vs.Y; - M[3] = 0; - - M[4] = vt.X + vs.Z; - M[6] = vt.Y - vs.X; - M[7] = 0; - - M[8] = vt.Z - vs.Y; - M[9] = vt.Y + vs.X; - M[11] = 0; - - M[12] = 0; - M[13] = 0; - M[14] = 0; - M[15] = 1; - - return *this; - } - - //! Builds a matrix which rotates a source vector to a look vector over an arbitrary axis - /** \param camPos: viewer position in world coord - \param center: object position in world-coord, rotation pivot - \param translation: object final translation from center - \param axis: axis to rotate about - \param from: source vector to rotate from - */ - template - inline void CMatrix4::buildAxisAlignedBillboard( - const core::vector3df& camPos, - const core::vector3df& center, - const core::vector3df& translation, - const core::vector3df& axis, - const core::vector3df& from) - { - // axis of rotation - core::vector3df up = axis; - up.normalize(); - const core::vector3df forward = (camPos - center).normalize(); - const core::vector3df right = up.crossProduct(forward).normalize(); - - // correct look vector - const core::vector3df look = right.crossProduct(up); - - // rotate from to - // axis multiplication by sin - const core::vector3df vs = look.crossProduct(from); - - // cosine angle - const f32 ca = from.dotProduct(look); - - core::vector3df vt(up * (1.f - ca)); - - M[0] = static_cast(vt.X * up.X + ca); - M[5] = static_cast(vt.Y * up.Y + ca); - M[10] = static_cast(vt.Z * up.Z + ca); - - vt.X *= up.Y; - vt.Z *= up.X; - vt.Y *= up.Z; - - M[1] = static_cast(vt.X - vs.Z); - M[2] = static_cast(vt.Z + vs.Y); - M[3] = 0; - - M[4] = static_cast(vt.X + vs.Z); - M[6] = static_cast(vt.Y - vs.X); - M[7] = 0; - - M[8] = static_cast(vt.Z - vs.Y); - M[9] = static_cast(vt.Y + vs.X); - M[11] = 0; - - setRotationCenter(center, translation); - } - - - //! Builds a combined matrix which translate to a center before rotation and translate afterward - template - inline void CMatrix4::setRotationCenter(const core::vector3df& center, const core::vector3df& translation) - { - M[12] = -M[0]*center.X - M[4]*center.Y - M[8]*center.Z + (center.X - translation.X ); - M[13] = -M[1]*center.X - M[5]*center.Y - M[9]*center.Z + (center.Y - translation.Y ); - M[14] = -M[2]*center.X - M[6]*center.Y - M[10]*center.Z + (center.Z - translation.Z ); - M[15] = (T) 1.0; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - } - - /*! - Generate texture coordinates as linear functions so that: - u = Ux*x + Uy*y + Uz*z + Uw - v = Vx*x + Vy*y + Vz*z + Vw - The matrix M for this case is: - Ux Vx 0 0 - Uy Vy 0 0 - Uz Vz 0 0 - Uw Vw 0 0 - */ - - - template - inline CMatrix4& CMatrix4::buildTextureTransform( f32 rotateRad, - const core::vector2df &rotatecenter, - const core::vector2df &translate, - const core::vector2df &scale) - { - const f32 c = cosf(rotateRad); - const f32 s = sinf(rotateRad); - - M[0] = (T)(c * scale.X); - M[1] = (T)(s * scale.Y); - M[2] = 0; - M[3] = 0; - - M[4] = (T)(-s * scale.X); - M[5] = (T)(c * scale.Y); - M[6] = 0; - M[7] = 0; - - M[8] = (T)(c * scale.X * rotatecenter.X + -s * rotatecenter.Y + translate.X); - M[9] = (T)(s * scale.Y * rotatecenter.X + c * rotatecenter.Y + translate.Y); - M[10] = 1; - M[11] = 0; - - M[12] = 0; - M[13] = 0; - M[14] = 0; - M[15] = 1; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // rotate about z axis, center ( 0.5, 0.5 ) - template - inline CMatrix4& CMatrix4::setTextureRotationCenter( f32 rotateRad ) - { - const f32 c = cosf(rotateRad); - const f32 s = sinf(rotateRad); - M[0] = (T)c; - M[1] = (T)s; - - M[4] = (T)-s; - M[5] = (T)c; - - M[8] = (T)(0.5f * ( s - c) + 0.5f); - M[9] = (T)(-0.5f * ( s + c) + 0.5f); - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = definitelyIdentityMatrix && (rotateRad==0.0f); -#endif - return *this; - } - - - template - inline CMatrix4& CMatrix4::setTextureTranslate ( f32 x, f32 y ) - { - M[8] = (T)x; - M[9] = (T)y; - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = definitelyIdentityMatrix && (x==0.0f) && (y==0.0f); -#endif - return *this; - } - - template - inline void CMatrix4::getTextureTranslate(f32& x, f32& y) const - { - x = (f32)M[8]; - y = (f32)M[9]; - } - - template - inline CMatrix4& CMatrix4::setTextureTranslateTransposed ( f32 x, f32 y ) - { - M[2] = (T)x; - M[6] = (T)y; - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = definitelyIdentityMatrix && (x==0.0f) && (y==0.0f); -#endif - return *this; - } - - template - inline CMatrix4& CMatrix4::setTextureScale ( f32 sx, f32 sy ) - { - M[0] = (T)sx; - M[5] = (T)sy; -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = definitelyIdentityMatrix && (sx==1.0f) && (sy==1.0f); -#endif - return *this; - } - - template - inline void CMatrix4::getTextureScale ( f32& sx, f32& sy ) const - { - sx = (f32)M[0]; - sy = (f32)M[5]; - } - - template - inline CMatrix4& CMatrix4::setTextureScaleCenter( f32 sx, f32 sy ) - { - M[0] = (T)sx; - M[5] = (T)sy; - M[8] = (T)(0.5f - 0.5f * sx); - M[9] = (T)(0.5f - 0.5f * sy); - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = definitelyIdentityMatrix && (sx==1.0f) && (sy==1.0f); -#endif - return *this; - } - - - // sets all matrix data members at once - template - inline CMatrix4& CMatrix4::setM(const T* data) - { - memcpy(M,data, 16*sizeof(T)); - -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix=false; -#endif - return *this; - } - - - // sets if the matrix is definitely identity matrix - template - inline void CMatrix4::setDefinitelyIdentityMatrix( bool isDefinitelyIdentityMatrix) - { -#if defined ( USE_MATRIX_TEST ) - definitelyIdentityMatrix = isDefinitelyIdentityMatrix; -#else - (void)isDefinitelyIdentityMatrix; // prevent compiler warning -#endif - } - - - // gets if the matrix is definitely identity matrix - template - inline bool CMatrix4::getDefinitelyIdentityMatrix() const - { -#if defined ( USE_MATRIX_TEST ) - return definitelyIdentityMatrix; -#else - return false; -#endif - } - - - //! Compare two matrices using the equal method - template - inline bool CMatrix4::equals(const core::CMatrix4& other, const T tolerance) const - { -#if defined ( USE_MATRIX_TEST ) - if (definitelyIdentityMatrix && other.definitelyIdentityMatrix) - return true; -#endif - for (s32 i = 0; i < 16; ++i) - if (!core::equals(M[i],other.M[i], tolerance)) - return false; - - return true; - } - - - // Multiply by scalar. - template - inline CMatrix4 operator*(const T scalar, const CMatrix4& mat) - { - return mat*scalar; - } - - - //! Typedef for f32 matrix - typedef CMatrix4 matrix4; - - //! global const identity matrix - IRRLICHT_API extern const matrix4 IdentityMatrix; +//! global const identity matrix +IRRLICHT_API extern const matrix4 IdentityMatrix; } // end namespace core } // end namespace irr - - diff --git a/include/path.h b/include/path.h index 4fa117d8..06476ef7 100644 --- a/include/path.h +++ b/include/path.h @@ -13,7 +13,7 @@ namespace io //! Type used for all file system related strings. /** This type will transparently handle different file system encodings. - NOTE: For historical reasons the tool-functions using io::path are all in coreutil.h + NOTE: For historical reasons the tool-functions using io::path are all in coreutil.h */ typedef core::string path; @@ -22,7 +22,7 @@ static_assert(sizeof(fschar_t) == sizeof(char)); //! Used in places where we identify objects by a filename, but don't actually work with the real filename /** Irrlicht is internally not case-sensitive when it comes to names. - Also this class is a first step towards support for correctly serializing renamed objects. + Also this class is a first step towards support for correctly serializing renamed objects. */ struct SNamedPath { @@ -30,32 +30,33 @@ struct SNamedPath SNamedPath() {} //! Constructor - SNamedPath(const path& p) : Path(p), InternalName( PathToName(p) ) + SNamedPath(const path &p) : + Path(p), InternalName(PathToName(p)) { } //! Is smaller comparator - bool operator <(const SNamedPath& other) const + bool operator<(const SNamedPath &other) const { return InternalName < other.InternalName; } //! Set the path. - void setPath(const path& p) + void setPath(const path &p) { Path = p; InternalName = PathToName(p); } //! Get the path. - const path& getPath() const + const path &getPath() const { return Path; }; //! Get the name which is used to identify the file. //! This string is similar to the names and filenames used before Irrlicht 1.7 - const path& getInternalName() const + const path &getInternalName() const { return InternalName; } @@ -68,10 +69,10 @@ struct SNamedPath protected: // convert the given path string to a name string. - path PathToName(const path& p) const + path PathToName(const path &p) const { path name(p); - name.replace( '\\', '/' ); + name.replace('\\', '/'); name.make_lower(); return name; } @@ -83,4 +84,3 @@ private: } // io } // irr - diff --git a/include/plane3d.h b/include/plane3d.h index b2df1201..4003325b 100644 --- a/include/plane3d.h +++ b/include/plane3d.h @@ -24,213 +24,216 @@ enum EIntersectionRelation3D //! Template plane class with some intersection testing methods. /** It has to be ensured, that the normal is always normalized. The constructors - and setters of this class will not ensure this automatically. So any normal - passed in has to be normalized in advance. No change to the normal will be - made by any of the class methods. + and setters of this class will not ensure this automatically. So any normal + passed in has to be normalized in advance. No change to the normal will be + made by any of the class methods. */ template class plane3d { - public: +public: + // Constructors - // Constructors + plane3d() : + Normal(0, 1, 0) { recalculateD(vector3d(0, 0, 0)); } - plane3d(): Normal(0,1,0) { recalculateD(vector3d(0,0,0)); } + plane3d(const vector3d &MPoint, const vector3d &Normal) : + Normal(Normal) { recalculateD(MPoint); } - plane3d(const vector3d& MPoint, const vector3d& Normal) : Normal(Normal) { recalculateD(MPoint); } + plane3d(T px, T py, T pz, T nx, T ny, T nz) : + Normal(nx, ny, nz) { recalculateD(vector3d(px, py, pz)); } - plane3d(T px, T py, T pz, T nx, T ny, T nz) : Normal(nx, ny, nz) { recalculateD(vector3d(px, py, pz)); } + plane3d(const vector3d &point1, const vector3d &point2, const vector3d &point3) + { + setPlane(point1, point2, point3); + } - plane3d(const vector3d& point1, const vector3d& point2, const vector3d& point3) - { setPlane(point1, point2, point3); } + plane3d(const vector3d &normal, const T d) : + Normal(normal), D(d) {} - plane3d(const vector3d & normal, const T d) : Normal(normal), D(d) { } + // operators - // operators + inline bool operator==(const plane3d &other) const { return (equals(D, other.D) && Normal == other.Normal); } - inline bool operator==(const plane3d& other) const { return (equals(D, other.D) && Normal==other.Normal);} + inline bool operator!=(const plane3d &other) const { return !(*this == other); } - inline bool operator!=(const plane3d& other) const { return !(*this == other);} + // functions - // functions + void setPlane(const vector3d &point, const vector3d &nvector) + { + Normal = nvector; + recalculateD(point); + } - void setPlane(const vector3d& point, const vector3d& nvector) - { - Normal = nvector; - recalculateD(point); - } + void setPlane(const vector3d &nvect, T d) + { + Normal = nvect; + D = d; + } - void setPlane(const vector3d& nvect, T d) - { - Normal = nvect; - D = d; - } + void setPlane(const vector3d &point1, const vector3d &point2, const vector3d &point3) + { + // creates the plane from 3 memberpoints + Normal = (point2 - point1).crossProduct(point3 - point1); + Normal.normalize(); - void setPlane(const vector3d& point1, const vector3d& point2, const vector3d& point3) - { - // creates the plane from 3 memberpoints - Normal = (point2 - point1).crossProduct(point3 - point1); - Normal.normalize(); + recalculateD(point1); + } - recalculateD(point1); - } - - - //! Get an intersection with a 3d line. - /** \param lineVect Vector of the line to intersect with. - \param linePoint Point of the line to intersect with. - \param outIntersection Place to store the intersection point, if there is one. - \return True if there was an intersection, false if there was not. - */ - bool getIntersectionWithLine(const vector3d& linePoint, - const vector3d& lineVect, - vector3d& outIntersection) const - { - T t2 = Normal.dotProduct(lineVect); - - if (t2 == 0) - return false; - - T t =- (Normal.dotProduct(linePoint) + D) / t2; - outIntersection = linePoint + (lineVect * t); - return true; - } - - //! Get percentage of line between two points where an intersection with this plane happens. - /** Only useful if known that there is an intersection. - \param linePoint1 Point1 of the line to intersect with. - \param linePoint2 Point2 of the line to intersect with. - \return Where on a line between two points an intersection with this plane happened. - For example, 0.5 is returned if the intersection happened exactly in the middle of the two points. - */ - f32 getKnownIntersectionWithLine(const vector3d& linePoint1, - const vector3d& linePoint2) const - { - vector3d vect = linePoint2 - linePoint1; - T t2 = (f32)Normal.dotProduct(vect); - return (f32)-((Normal.dotProduct(linePoint1) + D) / t2); - } - - //! Get an intersection with a 3d line, limited between two 3d points. - /** \param linePoint1 Point 1 of the line. - \param linePoint2 Point 2 of the line. - \param outIntersection Place to store the intersection point, if there is one. - \return True if there was an intersection, false if there was not. - */ - bool getIntersectionWithLimitedLine( - const vector3d& linePoint1, - const vector3d& linePoint2, - vector3d& outIntersection) const - { - return (getIntersectionWithLine(linePoint1, linePoint2 - linePoint1, outIntersection) && - outIntersection.isBetweenPoints(linePoint1, linePoint2)); - } - - //! Classifies the relation of a point to this plane. - /** \param point Point to classify its relation. - \return ISREL3D_FRONT if the point is in front of the plane, - ISREL3D_BACK if the point is behind of the plane, and - ISREL3D_PLANAR if the point is within the plane. */ - EIntersectionRelation3D classifyPointRelation(const vector3d& point) const - { - const T d = Normal.dotProduct(point) + D; - - if (d < -ROUNDING_ERROR_f32) - return ISREL3D_BACK; - - if (d > ROUNDING_ERROR_f32) - return ISREL3D_FRONT; - - return ISREL3D_PLANAR; - } - - //! Recalculates the distance from origin by applying a new member point to the plane. - void recalculateD(const vector3d& MPoint) - { - D = - MPoint.dotProduct(Normal); - } - - //! Gets a member point of the plane. - vector3d getMemberPoint() const - { - return Normal * -D; - } - - //! Tests if there is an intersection with the other plane - /** \return True if there is a intersection. */ - bool existsIntersection(const plane3d& other) const - { - vector3d cross = other.Normal.crossProduct(Normal); - return cross.getLength() > core::ROUNDING_ERROR_f32; - } - - //! Intersects this plane with another. - /** \param other Other plane to intersect with. - \param outLinePoint Base point of intersection line. - \param outLineVect Vector of intersection. - \return True if there is a intersection, false if not. */ - bool getIntersectionWithPlane(const plane3d& other, - vector3d& outLinePoint, - vector3d& outLineVect) const - { - const T fn00 = Normal.getLength(); - const T fn01 = Normal.dotProduct(other.Normal); - const T fn11 = other.Normal.getLength(); - const f64 det = fn00*fn11 - fn01*fn01; - - if (fabs(det) < ROUNDING_ERROR_f64 ) - return false; - - const f64 invdet = 1.0 / det; - const f64 fc0 = (fn11*-D + fn01*other.D) * invdet; - const f64 fc1 = (fn00*-other.D + fn01*D) * invdet; - - outLineVect = Normal.crossProduct(other.Normal); - outLinePoint = Normal*(T)fc0 + other.Normal*(T)fc1; - return true; - } - - //! Get the intersection point with two other planes if there is one. - bool getIntersectionWithPlanes(const plane3d& o1, - const plane3d& o2, vector3d& outPoint) const - { - vector3d linePoint, lineVect; - if (getIntersectionWithPlane(o1, linePoint, lineVect)) - return o2.getIntersectionWithLine(linePoint, lineVect, outPoint); + //! Get an intersection with a 3d line. + /** \param lineVect Vector of the line to intersect with. + \param linePoint Point of the line to intersect with. + \param outIntersection Place to store the intersection point, if there is one. + \return True if there was an intersection, false if there was not. + */ + bool getIntersectionWithLine(const vector3d &linePoint, + const vector3d &lineVect, + vector3d &outIntersection) const + { + T t2 = Normal.dotProduct(lineVect); + if (t2 == 0) return false; - } - //! Test if the triangle would be front or backfacing from any point. - /** Thus, this method assumes a camera position from - which the triangle is definitely visible when looking into - the given direction. - Note that this only works if the normal is Normalized. - Do not use this method with points as it will give wrong results! - \param lookDirection: Look direction. - \return True if the plane is front facing and - false if it is backfacing. */ - bool isFrontFacing(const vector3d& lookDirection) const - { - const f32 d = Normal.dotProduct(lookDirection); - return F32_LOWER_EQUAL_0 ( d ); - } + T t = -(Normal.dotProduct(linePoint) + D) / t2; + outIntersection = linePoint + (lineVect * t); + return true; + } - //! Get the distance to a point. - /** Note that this only works if the normal is normalized. */ - T getDistanceTo(const vector3d& point) const - { - return point.dotProduct(Normal) + D; - } + //! Get percentage of line between two points where an intersection with this plane happens. + /** Only useful if known that there is an intersection. + \param linePoint1 Point1 of the line to intersect with. + \param linePoint2 Point2 of the line to intersect with. + \return Where on a line between two points an intersection with this plane happened. + For example, 0.5 is returned if the intersection happened exactly in the middle of the two points. + */ + f32 getKnownIntersectionWithLine(const vector3d &linePoint1, + const vector3d &linePoint2) const + { + vector3d vect = linePoint2 - linePoint1; + T t2 = (f32)Normal.dotProduct(vect); + return (f32) - ((Normal.dotProduct(linePoint1) + D) / t2); + } - //! Normal vector of the plane. - vector3d Normal; + //! Get an intersection with a 3d line, limited between two 3d points. + /** \param linePoint1 Point 1 of the line. + \param linePoint2 Point 2 of the line. + \param outIntersection Place to store the intersection point, if there is one. + \return True if there was an intersection, false if there was not. + */ + bool getIntersectionWithLimitedLine( + const vector3d &linePoint1, + const vector3d &linePoint2, + vector3d &outIntersection) const + { + return (getIntersectionWithLine(linePoint1, linePoint2 - linePoint1, outIntersection) && + outIntersection.isBetweenPoints(linePoint1, linePoint2)); + } - //! Distance from origin. - T D; + //! Classifies the relation of a point to this plane. + /** \param point Point to classify its relation. + \return ISREL3D_FRONT if the point is in front of the plane, + ISREL3D_BACK if the point is behind of the plane, and + ISREL3D_PLANAR if the point is within the plane. */ + EIntersectionRelation3D classifyPointRelation(const vector3d &point) const + { + const T d = Normal.dotProduct(point) + D; + + if (d < -ROUNDING_ERROR_f32) + return ISREL3D_BACK; + + if (d > ROUNDING_ERROR_f32) + return ISREL3D_FRONT; + + return ISREL3D_PLANAR; + } + + //! Recalculates the distance from origin by applying a new member point to the plane. + void recalculateD(const vector3d &MPoint) + { + D = -MPoint.dotProduct(Normal); + } + + //! Gets a member point of the plane. + vector3d getMemberPoint() const + { + return Normal * -D; + } + + //! Tests if there is an intersection with the other plane + /** \return True if there is a intersection. */ + bool existsIntersection(const plane3d &other) const + { + vector3d cross = other.Normal.crossProduct(Normal); + return cross.getLength() > core::ROUNDING_ERROR_f32; + } + + //! Intersects this plane with another. + /** \param other Other plane to intersect with. + \param outLinePoint Base point of intersection line. + \param outLineVect Vector of intersection. + \return True if there is a intersection, false if not. */ + bool getIntersectionWithPlane(const plane3d &other, + vector3d &outLinePoint, + vector3d &outLineVect) const + { + const T fn00 = Normal.getLength(); + const T fn01 = Normal.dotProduct(other.Normal); + const T fn11 = other.Normal.getLength(); + const f64 det = fn00 * fn11 - fn01 * fn01; + + if (fabs(det) < ROUNDING_ERROR_f64) + return false; + + const f64 invdet = 1.0 / det; + const f64 fc0 = (fn11 * -D + fn01 * other.D) * invdet; + const f64 fc1 = (fn00 * -other.D + fn01 * D) * invdet; + + outLineVect = Normal.crossProduct(other.Normal); + outLinePoint = Normal * (T)fc0 + other.Normal * (T)fc1; + return true; + } + + //! Get the intersection point with two other planes if there is one. + bool getIntersectionWithPlanes(const plane3d &o1, + const plane3d &o2, vector3d &outPoint) const + { + vector3d linePoint, lineVect; + if (getIntersectionWithPlane(o1, linePoint, lineVect)) + return o2.getIntersectionWithLine(linePoint, lineVect, outPoint); + + return false; + } + + //! Test if the triangle would be front or backfacing from any point. + /** Thus, this method assumes a camera position from + which the triangle is definitely visible when looking into + the given direction. + Note that this only works if the normal is Normalized. + Do not use this method with points as it will give wrong results! + \param lookDirection: Look direction. + \return True if the plane is front facing and + false if it is backfacing. */ + bool isFrontFacing(const vector3d &lookDirection) const + { + const f32 d = Normal.dotProduct(lookDirection); + return F32_LOWER_EQUAL_0(d); + } + + //! Get the distance to a point. + /** Note that this only works if the normal is normalized. */ + T getDistanceTo(const vector3d &point) const + { + return point.dotProduct(Normal) + D; + } + + //! Normal vector of the plane. + vector3d Normal; + + //! Distance from origin. + T D; }; - //! Typedef for a f32 3d plane. typedef plane3d plane3df; @@ -239,5 +242,3 @@ typedef plane3d plane3di; } // end namespace core } // end namespace irr - - diff --git a/include/position2d.h b/include/position2d.h index 92a35a63..ff0d30f4 100644 --- a/include/position2d.h +++ b/include/position2d.h @@ -26,5 +26,3 @@ typedef vector2d position2di; // ...and use a #define to catch the rest, for (e.g.) position2d #define position2d vector2d - - diff --git a/include/quaternion.h b/include/quaternion.h index 41fc6d08..47cb6238 100644 --- a/include/quaternion.h +++ b/include/quaternion.h @@ -29,202 +29,201 @@ namespace core Also useful for interpolations. */ class quaternion { - public: +public: + //! Default Constructor + constexpr quaternion() : + X(0.0f), Y(0.0f), Z(0.0f), W(1.0f) {} - //! Default Constructor - constexpr quaternion() : X(0.0f), Y(0.0f), Z(0.0f), W(1.0f) {} + //! Constructor + constexpr quaternion(f32 x, f32 y, f32 z, f32 w) : + X(x), Y(y), Z(z), W(w) {} - //! Constructor - constexpr quaternion(f32 x, f32 y, f32 z, f32 w) : X(x), Y(y), Z(z), W(w) { } + //! Constructor which converts Euler angles (radians) to a quaternion + quaternion(f32 x, f32 y, f32 z); - //! Constructor which converts Euler angles (radians) to a quaternion - quaternion(f32 x, f32 y, f32 z); - - //! Constructor which converts Euler angles (radians) to a quaternion - quaternion(const vector3df& vec); + //! Constructor which converts Euler angles (radians) to a quaternion + quaternion(const vector3df &vec); #ifndef IRR_TEST_BROKEN_QUATERNION_USE - //! Constructor which converts a matrix to a quaternion - quaternion(const matrix4& mat); + //! Constructor which converts a matrix to a quaternion + quaternion(const matrix4 &mat); #endif - //! Equality operator - constexpr bool operator==(const quaternion& other) const - { - return ((X == other.X) && + //! Equality operator + constexpr bool operator==(const quaternion &other) const + { + return ((X == other.X) && (Y == other.Y) && (Z == other.Z) && (W == other.W)); - } + } - //! inequality operator - constexpr bool operator!=(const quaternion& other) const - { - return !(*this == other); - } + //! inequality operator + constexpr bool operator!=(const quaternion &other) const + { + return !(*this == other); + } #ifndef IRR_TEST_BROKEN_QUATERNION_USE - //! Matrix assignment operator - inline quaternion& operator=(const matrix4& other); + //! Matrix assignment operator + inline quaternion &operator=(const matrix4 &other); #endif - //! Add operator - quaternion operator+(const quaternion& other) const; + //! Add operator + quaternion operator+(const quaternion &other) const; - //! Multiplication operator - //! Be careful, unfortunately the operator order here is opposite of that in CMatrix4::operator* - quaternion operator*(const quaternion& other) const; + //! Multiplication operator + //! Be careful, unfortunately the operator order here is opposite of that in CMatrix4::operator* + quaternion operator*(const quaternion &other) const; - //! Multiplication operator with scalar - quaternion operator*(f32 s) const; + //! Multiplication operator with scalar + quaternion operator*(f32 s) const; - //! Multiplication operator with scalar - quaternion& operator*=(f32 s); + //! Multiplication operator with scalar + quaternion &operator*=(f32 s); - //! Multiplication operator - vector3df operator*(const vector3df& v) const; + //! Multiplication operator + vector3df operator*(const vector3df &v) const; - //! Multiplication operator - quaternion& operator*=(const quaternion& other); + //! Multiplication operator + quaternion &operator*=(const quaternion &other); - //! Calculates the dot product - inline f32 dotProduct(const quaternion& other) const; + //! Calculates the dot product + inline f32 dotProduct(const quaternion &other) const; - //! Sets new quaternion - inline quaternion& set(f32 x, f32 y, f32 z, f32 w); + //! Sets new quaternion + inline quaternion &set(f32 x, f32 y, f32 z, f32 w); - //! Sets new quaternion based on Euler angles (radians) - inline quaternion& set(f32 x, f32 y, f32 z); + //! Sets new quaternion based on Euler angles (radians) + inline quaternion &set(f32 x, f32 y, f32 z); - //! Sets new quaternion based on Euler angles (radians) - inline quaternion& set(const core::vector3df& vec); + //! Sets new quaternion based on Euler angles (radians) + inline quaternion &set(const core::vector3df &vec); - //! Sets new quaternion from other quaternion - inline quaternion& set(const core::quaternion& quat); + //! Sets new quaternion from other quaternion + inline quaternion &set(const core::quaternion &quat); - //! returns if this quaternion equals the other one, taking floating point rounding errors into account - inline bool equals(const quaternion& other, - const f32 tolerance = ROUNDING_ERROR_f32 ) const; + //! returns if this quaternion equals the other one, taking floating point rounding errors into account + inline bool equals(const quaternion &other, + const f32 tolerance = ROUNDING_ERROR_f32) const; - //! Normalizes the quaternion - inline quaternion& normalize(); + //! Normalizes the quaternion + inline quaternion &normalize(); #ifndef IRR_TEST_BROKEN_QUATERNION_USE - //! Creates a matrix from this quaternion - matrix4 getMatrix() const; + //! Creates a matrix from this quaternion + matrix4 getMatrix() const; #endif - //! Faster method to create a rotation matrix, you should normalize the quaternion before! - void getMatrixFast(matrix4 &dest) const; + //! Faster method to create a rotation matrix, you should normalize the quaternion before! + void getMatrixFast(matrix4 &dest) const; - //! Creates a matrix from this quaternion - void getMatrix( matrix4 &dest, const core::vector3df &translation=core::vector3df() ) const; + //! Creates a matrix from this quaternion + void getMatrix(matrix4 &dest, const core::vector3df &translation = core::vector3df()) const; - /*! - Creates a matrix from this quaternion - Rotate about a center point - shortcut for - core::quaternion q; - q.rotationFromTo ( vin[i].Normal, forward ); - q.getMatrixCenter ( lookat, center, newPos ); + /*! + Creates a matrix from this quaternion + Rotate about a center point + shortcut for + core::quaternion q; + q.rotationFromTo ( vin[i].Normal, forward ); + q.getMatrixCenter ( lookat, center, newPos ); - core::matrix4 m2; - m2.setInverseTranslation ( center ); - lookat *= m2; + core::matrix4 m2; + m2.setInverseTranslation ( center ); + lookat *= m2; - core::matrix4 m3; - m2.setTranslation ( newPos ); - lookat *= m3; + core::matrix4 m3; + m2.setTranslation ( newPos ); + lookat *= m3; - */ - void getMatrixCenter( matrix4 &dest, const core::vector3df ¢er, const core::vector3df &translation ) const; + */ + void getMatrixCenter(matrix4 &dest, const core::vector3df ¢er, const core::vector3df &translation) const; - //! Creates a matrix from this quaternion - inline void getMatrix_transposed( matrix4 &dest ) const; + //! Creates a matrix from this quaternion + inline void getMatrix_transposed(matrix4 &dest) const; - //! Inverts this quaternion - quaternion& makeInverse(); + //! Inverts this quaternion + quaternion &makeInverse(); - //! Set this quaternion to the linear interpolation between two quaternions - /** NOTE: lerp result is *not* a normalized quaternion. In most cases - you will want to use lerpN instead as most other quaternion functions expect - to work with a normalized quaternion. - \param q1 First quaternion to be interpolated. - \param q2 Second quaternion to be interpolated. - \param time Progress of interpolation. For time=0 the result is - q1, for time=1 the result is q2. Otherwise interpolation - between q1 and q2. Result is not normalized. - */ - quaternion& lerp(quaternion q1, quaternion q2, f32 time); + //! Set this quaternion to the linear interpolation between two quaternions + /** NOTE: lerp result is *not* a normalized quaternion. In most cases + you will want to use lerpN instead as most other quaternion functions expect + to work with a normalized quaternion. + \param q1 First quaternion to be interpolated. + \param q2 Second quaternion to be interpolated. + \param time Progress of interpolation. For time=0 the result is + q1, for time=1 the result is q2. Otherwise interpolation + between q1 and q2. Result is not normalized. + */ + quaternion &lerp(quaternion q1, quaternion q2, f32 time); - //! Set this quaternion to the linear interpolation between two quaternions and normalize the result - /** - \param q1 First quaternion to be interpolated. - \param q2 Second quaternion to be interpolated. - \param time Progress of interpolation. For time=0 the result is - q1, for time=1 the result is q2. Otherwise interpolation - between q1 and q2. Result is normalized. - */ - quaternion& lerpN(quaternion q1, quaternion q2, f32 time); + //! Set this quaternion to the linear interpolation between two quaternions and normalize the result + /** + \param q1 First quaternion to be interpolated. + \param q2 Second quaternion to be interpolated. + \param time Progress of interpolation. For time=0 the result is + q1, for time=1 the result is q2. Otherwise interpolation + between q1 and q2. Result is normalized. + */ + quaternion &lerpN(quaternion q1, quaternion q2, f32 time); - //! Set this quaternion to the result of the spherical interpolation between two quaternions - /** \param q1 First quaternion to be interpolated. - \param q2 Second quaternion to be interpolated. - \param time Progress of interpolation. For time=0 the result is - q1, for time=1 the result is q2. Otherwise interpolation - between q1 and q2. - \param threshold To avoid inaccuracies at the end (time=1) the - interpolation switches to linear interpolation at some point. - This value defines how much of the remaining interpolation will - be calculated with lerp. Everything from 1-threshold up will be - linear interpolation. - */ - quaternion& slerp(quaternion q1, quaternion q2, - f32 time, f32 threshold=.05f); + //! Set this quaternion to the result of the spherical interpolation between two quaternions + /** \param q1 First quaternion to be interpolated. + \param q2 Second quaternion to be interpolated. + \param time Progress of interpolation. For time=0 the result is + q1, for time=1 the result is q2. Otherwise interpolation + between q1 and q2. + \param threshold To avoid inaccuracies at the end (time=1) the + interpolation switches to linear interpolation at some point. + This value defines how much of the remaining interpolation will + be calculated with lerp. Everything from 1-threshold up will be + linear interpolation. + */ + quaternion &slerp(quaternion q1, quaternion q2, + f32 time, f32 threshold = .05f); - //! Set this quaternion to represent a rotation from angle and axis. - /** Axis must be unit length. - The quaternion representing the rotation is - q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k). - \param angle Rotation Angle in radians. - \param axis Rotation axis. */ - quaternion& fromAngleAxis (f32 angle, const vector3df& axis); + //! Set this quaternion to represent a rotation from angle and axis. + /** Axis must be unit length. + The quaternion representing the rotation is + q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k). + \param angle Rotation Angle in radians. + \param axis Rotation axis. */ + quaternion &fromAngleAxis(f32 angle, const vector3df &axis); - //! Fills an angle (radians) around an axis (unit vector) - void toAngleAxis (f32 &angle, core::vector3df& axis) const; + //! Fills an angle (radians) around an axis (unit vector) + void toAngleAxis(f32 &angle, core::vector3df &axis) const; - //! Output this quaternion to an Euler angle (radians) - void toEuler(vector3df& euler) const; + //! Output this quaternion to an Euler angle (radians) + void toEuler(vector3df &euler) const; - //! Set quaternion to identity - quaternion& makeIdentity(); + //! Set quaternion to identity + quaternion &makeIdentity(); - //! Set quaternion to represent a rotation from one vector to another. - quaternion& rotationFromTo(const vector3df& from, const vector3df& to); + //! Set quaternion to represent a rotation from one vector to another. + quaternion &rotationFromTo(const vector3df &from, const vector3df &to); - //! Quaternion elements. - f32 X; // vectorial (imaginary) part - f32 Y; - f32 Z; - f32 W; // real part + //! Quaternion elements. + f32 X; // vectorial (imaginary) part + f32 Y; + f32 Z; + f32 W; // real part }; - // Constructor which converts Euler angles to a quaternion inline quaternion::quaternion(f32 x, f32 y, f32 z) { - set(x,y,z); + set(x, y, z); } - // Constructor which converts Euler angles to a quaternion -inline quaternion::quaternion(const vector3df& vec) +inline quaternion::quaternion(const vector3df &vec) { - set(vec.X,vec.Y,vec.Z); + set(vec.X, vec.Y, vec.Z); } #ifndef IRR_TEST_BROKEN_QUATERNION_USE // Constructor which converts a matrix to a quaternion -inline quaternion::quaternion(const matrix4& mat) +inline quaternion::quaternion(const matrix4 &mat) { (*this) = mat; } @@ -232,12 +231,11 @@ inline quaternion::quaternion(const matrix4& mat) #ifndef IRR_TEST_BROKEN_QUATERNION_USE // matrix assignment operator -inline quaternion& quaternion::operator=(const matrix4& m) +inline quaternion &quaternion::operator=(const matrix4 &m) { const f32 diag = m[0] + m[5] + m[10] + 1; - if( diag > 0.0f ) - { + if (diag > 0.0f) { const f32 scale = sqrtf(diag) * 2.0f; // get scale from diagonal // TODO: speed this up @@ -245,11 +243,8 @@ inline quaternion& quaternion::operator=(const matrix4& m) Y = (m[8] - m[2]) / scale; Z = (m[1] - m[4]) / scale; W = 0.25f * scale; - } - else - { - if (m[0]>m[5] && m[0]>m[10]) - { + } else { + if (m[0] > m[5] && m[0] > m[10]) { // 1st element of diag is greatest value // find scale according to 1st element, and double it const f32 scale = sqrtf(1.0f + m[0] - m[5] - m[10]) * 2.0f; @@ -259,9 +254,7 @@ inline quaternion& quaternion::operator=(const matrix4& m) Y = (m[4] + m[1]) / scale; Z = (m[2] + m[8]) / scale; W = (m[6] - m[9]) / scale; - } - else if (m[5]>m[10]) - { + } else if (m[5] > m[10]) { // 2nd element of diag is greatest value // find scale according to 2nd element, and double it const f32 scale = sqrtf(1.0f + m[5] - m[0] - m[10]) * 2.0f; @@ -271,9 +264,7 @@ inline quaternion& quaternion::operator=(const matrix4& m) Y = 0.25f * scale; Z = (m[9] + m[6]) / scale; W = (m[8] - m[2]) / scale; - } - else - { + } else { // 3rd element of diag is greatest value // find scale according to 3rd element, and double it const f32 scale = sqrtf(1.0f + m[10] - m[0] - m[5]) * 2.0f; @@ -290,9 +281,8 @@ inline quaternion& quaternion::operator=(const matrix4& m) } #endif - // multiplication operator -inline quaternion quaternion::operator*(const quaternion& other) const +inline quaternion quaternion::operator*(const quaternion &other) const { quaternion tmp; @@ -304,34 +294,32 @@ inline quaternion quaternion::operator*(const quaternion& other) const return tmp; } - // multiplication operator inline quaternion quaternion::operator*(f32 s) const { - return quaternion(s*X, s*Y, s*Z, s*W); + return quaternion(s * X, s * Y, s * Z, s * W); } - // multiplication operator -inline quaternion& quaternion::operator*=(f32 s) +inline quaternion &quaternion::operator*=(f32 s) { - X*=s; - Y*=s; - Z*=s; - W*=s; + X *= s; + Y *= s; + Z *= s; + W *= s; return *this; } // multiplication operator -inline quaternion& quaternion::operator*=(const quaternion& other) +inline quaternion &quaternion::operator*=(const quaternion &other) { return (*this = other * (*this)); } // add operator -inline quaternion quaternion::operator+(const quaternion& b) const +inline quaternion quaternion::operator+(const quaternion &b) const { - return quaternion(X+b.X, Y+b.Y, Z+b.Z, W+b.W); + return quaternion(X + b.X, Y + b.Y, Z + b.Z, W + b.W); } #ifndef IRR_TEST_BROKEN_QUATERNION_USE @@ -345,24 +333,24 @@ inline matrix4 quaternion::getMatrix() const #endif //! Faster method to create a rotation matrix, you should normalize the quaternion before! -inline void quaternion::getMatrixFast( matrix4 &dest) const +inline void quaternion::getMatrixFast(matrix4 &dest) const { // TODO: // gpu quaternion skinning => fast Bones transform chain O_O YEAH! // http://www.mrelusive.com/publications/papers/SIMD-From-Quaternion-to-Matrix-and-Back.pdf - dest[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z; - dest[1] = 2.0f*X*Y + 2.0f*Z*W; - dest[2] = 2.0f*X*Z - 2.0f*Y*W; + dest[0] = 1.0f - 2.0f * Y * Y - 2.0f * Z * Z; + dest[1] = 2.0f * X * Y + 2.0f * Z * W; + dest[2] = 2.0f * X * Z - 2.0f * Y * W; dest[3] = 0.0f; - dest[4] = 2.0f*X*Y - 2.0f*Z*W; - dest[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z; - dest[6] = 2.0f*Z*Y + 2.0f*X*W; + dest[4] = 2.0f * X * Y - 2.0f * Z * W; + dest[5] = 1.0f - 2.0f * X * X - 2.0f * Z * Z; + dest[6] = 2.0f * Z * Y + 2.0f * X * W; dest[7] = 0.0f; - dest[8] = 2.0f*X*Z + 2.0f*Y*W; - dest[9] = 2.0f*Z*Y - 2.0f*X*W; - dest[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y; + dest[8] = 2.0f * X * Z + 2.0f * Y * W; + dest[9] = 2.0f * Z * Y - 2.0f * X * W; + dest[10] = 1.0f - 2.0f * X * X - 2.0f * Y * Y; dest[11] = 0.0f; dest[12] = 0.f; @@ -382,26 +370,26 @@ inline void quaternion::getMatrix(matrix4 &dest, // ok creating a copy may be slower, but at least avoid internal // state chance (also because otherwise we cannot keep this method "const"). - quaternion q( *this); + quaternion q(*this); q.normalize(); f32 X = q.X; f32 Y = q.Y; f32 Z = q.Z; f32 W = q.W; - dest[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z; - dest[1] = 2.0f*X*Y + 2.0f*Z*W; - dest[2] = 2.0f*X*Z - 2.0f*Y*W; + dest[0] = 1.0f - 2.0f * Y * Y - 2.0f * Z * Z; + dest[1] = 2.0f * X * Y + 2.0f * Z * W; + dest[2] = 2.0f * X * Z - 2.0f * Y * W; dest[3] = 0.0f; - dest[4] = 2.0f*X*Y - 2.0f*Z*W; - dest[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z; - dest[6] = 2.0f*Z*Y + 2.0f*X*W; + dest[4] = 2.0f * X * Y - 2.0f * Z * W; + dest[5] = 1.0f - 2.0f * X * X - 2.0f * Z * Z; + dest[6] = 2.0f * Z * Y + 2.0f * X * W; dest[7] = 0.0f; - dest[8] = 2.0f*X*Z + 2.0f*Y*W; - dest[9] = 2.0f*Z*Y - 2.0f*X*W; - dest[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y; + dest[8] = 2.0f * X * Z + 2.0f * Y * W; + dest[9] = 2.0f * Z * Y - 2.0f * X * W; + dest[10] = 1.0f - 2.0f * X * X - 2.0f * Y * Y; dest[11] = 0.0f; dest[12] = center.X; @@ -409,10 +397,9 @@ inline void quaternion::getMatrix(matrix4 &dest, dest[14] = center.Z; dest[15] = 1.f; - dest.setDefinitelyIdentityMatrix ( false ); + dest.setDefinitelyIdentityMatrix(false); } - /*! Creates a matrix from this quaternion Rotate about a center point @@ -426,8 +413,8 @@ inline void quaternion::getMatrix(matrix4 &dest, lookat *= m2; */ inline void quaternion::getMatrixCenter(matrix4 &dest, - const core::vector3df ¢er, - const core::vector3df &translation) const + const core::vector3df ¢er, + const core::vector3df &translation) const { quaternion q(*this); q.normalize(); @@ -436,22 +423,22 @@ inline void quaternion::getMatrixCenter(matrix4 &dest, f32 Z = q.Z; f32 W = q.W; - dest[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z; - dest[1] = 2.0f*X*Y + 2.0f*Z*W; - dest[2] = 2.0f*X*Z - 2.0f*Y*W; + dest[0] = 1.0f - 2.0f * Y * Y - 2.0f * Z * Z; + dest[1] = 2.0f * X * Y + 2.0f * Z * W; + dest[2] = 2.0f * X * Z - 2.0f * Y * W; dest[3] = 0.0f; - dest[4] = 2.0f*X*Y - 2.0f*Z*W; - dest[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z; - dest[6] = 2.0f*Z*Y + 2.0f*X*W; + dest[4] = 2.0f * X * Y - 2.0f * Z * W; + dest[5] = 1.0f - 2.0f * X * X - 2.0f * Z * Z; + dest[6] = 2.0f * Z * Y + 2.0f * X * W; dest[7] = 0.0f; - dest[8] = 2.0f*X*Z + 2.0f*Y*W; - dest[9] = 2.0f*Z*Y - 2.0f*X*W; - dest[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y; + dest[8] = 2.0f * X * Z + 2.0f * Y * W; + dest[9] = 2.0f * Z * Y - 2.0f * X * W; + dest[10] = 1.0f - 2.0f * X * X - 2.0f * Y * Y; dest[11] = 0.0f; - dest.setRotationCenter ( center, translation ); + dest.setRotationCenter(center, translation); } // Creates a matrix from this quaternion @@ -464,19 +451,19 @@ inline void quaternion::getMatrix_transposed(matrix4 &dest) const f32 Z = q.Z; f32 W = q.W; - dest[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z; - dest[4] = 2.0f*X*Y + 2.0f*Z*W; - dest[8] = 2.0f*X*Z - 2.0f*Y*W; + dest[0] = 1.0f - 2.0f * Y * Y - 2.0f * Z * Z; + dest[4] = 2.0f * X * Y + 2.0f * Z * W; + dest[8] = 2.0f * X * Z - 2.0f * Y * W; dest[12] = 0.0f; - dest[1] = 2.0f*X*Y - 2.0f*Z*W; - dest[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z; - dest[9] = 2.0f*Z*Y + 2.0f*X*W; + dest[1] = 2.0f * X * Y - 2.0f * Z * W; + dest[5] = 1.0f - 2.0f * X * X - 2.0f * Z * Z; + dest[9] = 2.0f * Z * Y + 2.0f * X * W; dest[13] = 0.0f; - dest[2] = 2.0f*X*Z + 2.0f*Y*W; - dest[6] = 2.0f*Z*Y - 2.0f*X*W; - dest[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y; + dest[2] = 2.0f * X * Z + 2.0f * Y * W; + dest[6] = 2.0f * Z * Y - 2.0f * X * W; + dest[10] = 1.0f - 2.0f * X * X - 2.0f * Y * Y; dest[14] = 0.0f; dest[3] = 0.f; @@ -487,17 +474,17 @@ inline void quaternion::getMatrix_transposed(matrix4 &dest) const dest.setDefinitelyIdentityMatrix(false); } - // Inverts this quaternion -inline quaternion& quaternion::makeInverse() +inline quaternion &quaternion::makeInverse() { - X = -X; Y = -Y; Z = -Z; + X = -X; + Y = -Y; + Z = -Z; return *this; } - // sets new quaternion -inline quaternion& quaternion::set(f32 x, f32 y, f32 z, f32 w) +inline quaternion &quaternion::set(f32 x, f32 y, f32 z, f32 w) { X = x; Y = y; @@ -506,9 +493,8 @@ inline quaternion& quaternion::set(f32 x, f32 y, f32 z, f32 w) return *this; } - // sets new quaternion based on Euler angles -inline quaternion& quaternion::set(f32 x, f32 y, f32 z) +inline quaternion &quaternion::set(f32 x, f32 y, f32 z) { f64 angle; @@ -538,108 +524,98 @@ inline quaternion& quaternion::set(f32 x, f32 y, f32 z) } // sets new quaternion based on Euler angles -inline quaternion& quaternion::set(const core::vector3df& vec) +inline quaternion &quaternion::set(const core::vector3df &vec) { - return set( vec.X, vec.Y, vec.Z); + return set(vec.X, vec.Y, vec.Z); } // sets new quaternion based on other quaternion -inline quaternion& quaternion::set(const core::quaternion& quat) +inline quaternion &quaternion::set(const core::quaternion &quat) { - return (*this=quat); + return (*this = quat); } - //! returns if this quaternion equals the other one, taking floating point rounding errors into account -inline bool quaternion::equals(const quaternion& other, const f32 tolerance) const +inline bool quaternion::equals(const quaternion &other, const f32 tolerance) const { - return core::equals( X, other.X, tolerance) && - core::equals( Y, other.Y, tolerance) && - core::equals( Z, other.Z, tolerance) && - core::equals( W, other.W, tolerance); + return core::equals(X, other.X, tolerance) && + core::equals(Y, other.Y, tolerance) && + core::equals(Z, other.Z, tolerance) && + core::equals(W, other.W, tolerance); } - // normalizes the quaternion -inline quaternion& quaternion::normalize() +inline quaternion &quaternion::normalize() { // removed conditional branch since it may slow down and anyway the condition was // false even after normalization in some cases. - return (*this *= (f32)reciprocal_squareroot ( (f64)(X*X + Y*Y + Z*Z + W*W) )); + return (*this *= (f32)reciprocal_squareroot((f64)(X * X + Y * Y + Z * Z + W * W))); } // Set this quaternion to the result of the linear interpolation between two quaternions -inline quaternion& quaternion::lerp( quaternion q1, quaternion q2, f32 time) +inline quaternion &quaternion::lerp(quaternion q1, quaternion q2, f32 time) { const f32 scale = 1.0f - time; - return (*this = (q1*scale) + (q2*time)); + return (*this = (q1 * scale) + (q2 * time)); } // Set this quaternion to the result of the linear interpolation between two quaternions and normalize the result -inline quaternion& quaternion::lerpN( quaternion q1, quaternion q2, f32 time) +inline quaternion &quaternion::lerpN(quaternion q1, quaternion q2, f32 time) { const f32 scale = 1.0f - time; - return (*this = ((q1*scale) + (q2*time)).normalize() ); + return (*this = ((q1 * scale) + (q2 * time)).normalize()); } // set this quaternion to the result of the interpolation between two quaternions -inline quaternion& quaternion::slerp( quaternion q1, quaternion q2, f32 time, f32 threshold) +inline quaternion &quaternion::slerp(quaternion q1, quaternion q2, f32 time, f32 threshold) { f32 angle = q1.dotProduct(q2); // make sure we use the short rotation - if (angle < 0.0f) - { + if (angle < 0.0f) { q1 *= -1.0f; angle *= -1.0f; } - if (angle <= (1-threshold)) // spherical interpolation + if (angle <= (1 - threshold)) // spherical interpolation { const f32 theta = acosf(angle); const f32 invsintheta = reciprocal(sinf(theta)); - const f32 scale = sinf(theta * (1.0f-time)) * invsintheta; + const f32 scale = sinf(theta * (1.0f - time)) * invsintheta; const f32 invscale = sinf(theta * time) * invsintheta; - return (*this = (q1*scale) + (q2*invscale)); - } - else // linear interpolation - return lerpN(q1,q2,time); + return (*this = (q1 * scale) + (q2 * invscale)); + } else // linear interpolation + return lerpN(q1, q2, time); } - // calculates the dot product -inline f32 quaternion::dotProduct(const quaternion& q2) const +inline f32 quaternion::dotProduct(const quaternion &q2) const { return (X * q2.X) + (Y * q2.Y) + (Z * q2.Z) + (W * q2.W); } - //! axis must be unit length, angle in radians -inline quaternion& quaternion::fromAngleAxis(f32 angle, const vector3df& axis) +inline quaternion &quaternion::fromAngleAxis(f32 angle, const vector3df &axis) { - const f32 fHalfAngle = 0.5f*angle; + const f32 fHalfAngle = 0.5f * angle; const f32 fSin = sinf(fHalfAngle); W = cosf(fHalfAngle); - X = fSin*axis.X; - Y = fSin*axis.Y; - Z = fSin*axis.Z; + X = fSin * axis.X; + Y = fSin * axis.Y; + Z = fSin * axis.Z; return *this; } - inline void quaternion::toAngleAxis(f32 &angle, core::vector3df &axis) const { - const f32 scale = sqrtf(X*X + Y*Y + Z*Z); + const f32 scale = sqrtf(X * X + Y * Y + Z * Z); - if (core::iszero(scale) || W > 1.0f || W < -1.0f) - { + if (core::iszero(scale) || W > 1.0f || W < -1.0f) { angle = 0.0f; axis.X = 0.0f; axis.Y = 1.0f; axis.Z = 0.0f; - } - else - { + } else { const f32 invscale = reciprocal(scale); angle = 2.0f * acosf(W); axis.X = X * invscale; @@ -648,45 +624,39 @@ inline void quaternion::toAngleAxis(f32 &angle, core::vector3df &axis) const } } -inline void quaternion::toEuler(vector3df& euler) const +inline void quaternion::toEuler(vector3df &euler) const { - const f64 sqw = W*W; - const f64 sqx = X*X; - const f64 sqy = Y*Y; - const f64 sqz = Z*Z; - const f64 test = 2.0 * (Y*W - X*Z); + const f64 sqw = W * W; + const f64 sqx = X * X; + const f64 sqy = Y * Y; + const f64 sqz = Z * Z; + const f64 test = 2.0 * (Y * W - X * Z); - if (core::equals(test, 1.0, 0.000001)) - { + if (core::equals(test, 1.0, 0.000001)) { // heading = rotation about z-axis - euler.Z = (f32) (-2.0*atan2(X, W)); + euler.Z = (f32)(-2.0 * atan2(X, W)); // bank = rotation about x-axis euler.X = 0; // attitude = rotation about y-axis - euler.Y = (f32) (core::PI64/2.0); - } - else if (core::equals(test, -1.0, 0.000001)) - { + euler.Y = (f32)(core::PI64 / 2.0); + } else if (core::equals(test, -1.0, 0.000001)) { // heading = rotation about z-axis - euler.Z = (f32) (2.0*atan2(X, W)); + euler.Z = (f32)(2.0 * atan2(X, W)); // bank = rotation about x-axis euler.X = 0; // attitude = rotation about y-axis - euler.Y = (f32) (core::PI64/-2.0); - } - else - { + euler.Y = (f32)(core::PI64 / -2.0); + } else { // heading = rotation about z-axis - euler.Z = (f32) atan2(2.0 * (X*Y +Z*W),(sqx - sqy - sqz + sqw)); + euler.Z = (f32)atan2(2.0 * (X * Y + Z * W), (sqx - sqy - sqz + sqw)); // bank = rotation about x-axis - euler.X = (f32) atan2(2.0 * (Y*Z +X*W),(-sqx - sqy + sqz + sqw)); + euler.X = (f32)atan2(2.0 * (Y * Z + X * W), (-sqx - sqy + sqz + sqw)); // attitude = rotation about y-axis - euler.Y = (f32) asin( clamp(test, -1.0, 1.0) ); + euler.Y = (f32)asin(clamp(test, -1.0, 1.0)); } } - -inline vector3df quaternion::operator* (const vector3df& v) const +inline vector3df quaternion::operator*(const vector3df &v) const { // nVidia SDK implementation @@ -701,7 +671,7 @@ inline vector3df quaternion::operator* (const vector3df& v) const } // set quaternion to identity -inline core::quaternion& quaternion::makeIdentity() +inline core::quaternion &quaternion::makeIdentity() { W = 1.f; X = 0.f; @@ -710,7 +680,7 @@ inline core::quaternion& quaternion::makeIdentity() return *this; } -inline core::quaternion& quaternion::rotationFromTo(const vector3df& from, const vector3df& to) +inline core::quaternion &quaternion::rotationFromTo(const vector3df &from, const vector3df &to) { // Based on Stan Melax's article in Game Programming Gems // Optimized by Robert Eisele: https://raw.org/proof/quaternion-from-two-vectors @@ -725,14 +695,12 @@ inline core::quaternion& quaternion::rotationFromTo(const vector3df& from, const if (d >= 1.0f) // If dot == 1, vectors are the same { return makeIdentity(); - } - else if (d <= -1.0f) // exactly opposite + } else if (d <= -1.0f) // exactly opposite { core::vector3df axis(1.0f, 0.f, 0.f); axis = axis.crossProduct(v0); - if (axis.getLength()==0) - { - axis.set(0.f,1.f,0.f); + if (axis.getLength() == 0) { + axis.set(0.f, 1.f, 0.f); axis = axis.crossProduct(v0); } // same as fromAngleAxis(core::PI, axis).normalize(); @@ -743,8 +711,5 @@ inline core::quaternion& quaternion::rotationFromTo(const vector3df& from, const return set(c.X, c.Y, c.Z, 1 + d).normalize(); } - } // end namespace core } // end namespace irr - - diff --git a/include/rect.h b/include/rect.h index bef37d72..bced2d59 100644 --- a/include/rect.h +++ b/include/rect.h @@ -13,274 +13,269 @@ namespace irr namespace core { - //! Rectangle template. - /** Mostly used by 2D GUI elements and for 2D drawing methods. - It has 2 positions instead of position and dimension and a fast - method for collision detection with other rectangles and points. +//! Rectangle template. +/** Mostly used by 2D GUI elements and for 2D drawing methods. +It has 2 positions instead of position and dimension and a fast +method for collision detection with other rectangles and points. - Coordinates are (0,0) for top-left corner, and increasing to the right - and to the bottom. - */ - template - class rect +Coordinates are (0,0) for top-left corner, and increasing to the right +and to the bottom. +*/ +template +class rect +{ +public: + //! Default constructor creating empty rectangle at (0,0) + constexpr rect() : + UpperLeftCorner(0, 0), LowerRightCorner(0, 0) {} + + //! Constructor with two corners + constexpr rect(T x, T y, T x2, T y2) : + UpperLeftCorner(x, y), LowerRightCorner(x2, y2) {} + + //! Constructor with two corners + constexpr rect(const position2d &upperLeft, const position2d &lowerRight) : + UpperLeftCorner(upperLeft), LowerRightCorner(lowerRight) {} + + //! Constructor with upper left corner and dimension + template + constexpr rect(const position2d &pos, const dimension2d &size) : + UpperLeftCorner(pos), LowerRightCorner(pos.X + size.Width, pos.Y + size.Height) { - public: + } - //! Default constructor creating empty rectangle at (0,0) - constexpr rect() : UpperLeftCorner(0,0), LowerRightCorner(0,0) {} + //! Constructor with upper left at 0,0 and lower right using dimension + template + explicit constexpr rect(const dimension2d &size) : + UpperLeftCorner(0, 0), LowerRightCorner(size.Width, size.Height) + { + } - //! Constructor with two corners - constexpr rect(T x, T y, T x2, T y2) - : UpperLeftCorner(x,y), LowerRightCorner(x2,y2) {} + //! move right by given numbers + rect operator+(const position2d &pos) const + { + rect ret(*this); + return ret += pos; + } - //! Constructor with two corners - constexpr rect(const position2d& upperLeft, const position2d& lowerRight) - : UpperLeftCorner(upperLeft), LowerRightCorner(lowerRight) {} + //! move right by given numbers + rect &operator+=(const position2d &pos) + { + UpperLeftCorner += pos; + LowerRightCorner += pos; + return *this; + } - //! Constructor with upper left corner and dimension - template - constexpr rect(const position2d& pos, const dimension2d& size) - : UpperLeftCorner(pos), LowerRightCorner(pos.X + size.Width, pos.Y + size.Height) {} + //! move left by given numbers + rect operator-(const position2d &pos) const + { + rect ret(*this); + return ret -= pos; + } - //! Constructor with upper left at 0,0 and lower right using dimension - template - explicit constexpr rect(const dimension2d& size) - : UpperLeftCorner(0,0), LowerRightCorner(size.Width, size.Height) {} + //! move left by given numbers + rect &operator-=(const position2d &pos) + { + UpperLeftCorner -= pos; + LowerRightCorner -= pos; + return *this; + } - //! move right by given numbers - rect operator+(const position2d& pos) const - { - rect ret(*this); - return ret+=pos; - } - - //! move right by given numbers - rect& operator+=(const position2d& pos) - { - UpperLeftCorner += pos; - LowerRightCorner += pos; - return *this; - } - - //! move left by given numbers - rect operator-(const position2d& pos) const - { - rect ret(*this); - return ret-=pos; - } - - //! move left by given numbers - rect& operator-=(const position2d& pos) - { - UpperLeftCorner -= pos; - LowerRightCorner -= pos; - return *this; - } - - //! equality operator - constexpr bool operator==(const rect& other) const - { - return (UpperLeftCorner == other.UpperLeftCorner && + //! equality operator + constexpr bool operator==(const rect &other) const + { + return (UpperLeftCorner == other.UpperLeftCorner && LowerRightCorner == other.LowerRightCorner); - } + } - //! inequality operator - constexpr bool operator!=(const rect& other) const - { - return (UpperLeftCorner != other.UpperLeftCorner || + //! inequality operator + constexpr bool operator!=(const rect &other) const + { + return (UpperLeftCorner != other.UpperLeftCorner || LowerRightCorner != other.LowerRightCorner); - } + } - //! compares size of rectangles - bool operator<(const rect& other) const - { - return getArea() < other.getArea(); - } + //! compares size of rectangles + bool operator<(const rect &other) const + { + return getArea() < other.getArea(); + } - //! Returns size of rectangle - T getArea() const - { - return getWidth() * getHeight(); - } + //! Returns size of rectangle + T getArea() const + { + return getWidth() * getHeight(); + } - //! Returns if a 2d point is within this rectangle. - /** \param pos Position to test if it lies within this rectangle. - \return True if the position is within the rectangle, false if not. */ - bool isPointInside(const position2d& pos) const - { - return (UpperLeftCorner.X <= pos.X && + //! Returns if a 2d point is within this rectangle. + /** \param pos Position to test if it lies within this rectangle. + \return True if the position is within the rectangle, false if not. */ + bool isPointInside(const position2d &pos) const + { + return (UpperLeftCorner.X <= pos.X && UpperLeftCorner.Y <= pos.Y && LowerRightCorner.X >= pos.X && LowerRightCorner.Y >= pos.Y); - } + } - //! Check if the rectangle collides with another rectangle. - /** \param other Rectangle to test collision with - \return True if the rectangles collide. */ - bool isRectCollided(const rect& other) const - { - return (LowerRightCorner.Y > other.UpperLeftCorner.Y && + //! Check if the rectangle collides with another rectangle. + /** \param other Rectangle to test collision with + \return True if the rectangles collide. */ + bool isRectCollided(const rect &other) const + { + return (LowerRightCorner.Y > other.UpperLeftCorner.Y && UpperLeftCorner.Y < other.LowerRightCorner.Y && LowerRightCorner.X > other.UpperLeftCorner.X && UpperLeftCorner.X < other.LowerRightCorner.X); + } + + //! Clips this rectangle with another one. + /** \param other Rectangle to clip with */ + void clipAgainst(const rect &other) + { + if (other.LowerRightCorner.X < LowerRightCorner.X) + LowerRightCorner.X = other.LowerRightCorner.X; + if (other.LowerRightCorner.Y < LowerRightCorner.Y) + LowerRightCorner.Y = other.LowerRightCorner.Y; + + if (other.UpperLeftCorner.X > LowerRightCorner.X) + LowerRightCorner.X = other.UpperLeftCorner.X; + if (other.UpperLeftCorner.Y > LowerRightCorner.Y) + LowerRightCorner.Y = other.UpperLeftCorner.Y; + + if (other.LowerRightCorner.X < UpperLeftCorner.X) + UpperLeftCorner.X = other.LowerRightCorner.X; + if (other.LowerRightCorner.Y < UpperLeftCorner.Y) + UpperLeftCorner.Y = other.LowerRightCorner.Y; + + if (other.UpperLeftCorner.X > UpperLeftCorner.X) + UpperLeftCorner.X = other.UpperLeftCorner.X; + if (other.UpperLeftCorner.Y > UpperLeftCorner.Y) + UpperLeftCorner.Y = other.UpperLeftCorner.Y; + } + + //! Moves this rectangle to fit inside another one. + /** \return True on success, false if not possible */ + bool constrainTo(const rect &other) + { + if (other.getWidth() < getWidth() || other.getHeight() < getHeight()) + return false; + + T diff = other.LowerRightCorner.X - LowerRightCorner.X; + if (diff < 0) { + LowerRightCorner.X += diff; + UpperLeftCorner.X += diff; } - //! Clips this rectangle with another one. - /** \param other Rectangle to clip with */ - void clipAgainst(const rect& other) - { - if (other.LowerRightCorner.X < LowerRightCorner.X) - LowerRightCorner.X = other.LowerRightCorner.X; - if (other.LowerRightCorner.Y < LowerRightCorner.Y) - LowerRightCorner.Y = other.LowerRightCorner.Y; - - if (other.UpperLeftCorner.X > LowerRightCorner.X) - LowerRightCorner.X = other.UpperLeftCorner.X; - if (other.UpperLeftCorner.Y > LowerRightCorner.Y) - LowerRightCorner.Y = other.UpperLeftCorner.Y; - - if (other.LowerRightCorner.X < UpperLeftCorner.X) - UpperLeftCorner.X = other.LowerRightCorner.X; - if (other.LowerRightCorner.Y < UpperLeftCorner.Y) - UpperLeftCorner.Y = other.LowerRightCorner.Y; - - if (other.UpperLeftCorner.X > UpperLeftCorner.X) - UpperLeftCorner.X = other.UpperLeftCorner.X; - if (other.UpperLeftCorner.Y > UpperLeftCorner.Y) - UpperLeftCorner.Y = other.UpperLeftCorner.Y; + diff = other.LowerRightCorner.Y - LowerRightCorner.Y; + if (diff < 0) { + LowerRightCorner.Y += diff; + UpperLeftCorner.Y += diff; } - //! Moves this rectangle to fit inside another one. - /** \return True on success, false if not possible */ - bool constrainTo(const rect& other) - { - if (other.getWidth() < getWidth() || other.getHeight() < getHeight()) - return false; - - T diff = other.LowerRightCorner.X - LowerRightCorner.X; - if (diff < 0) - { - LowerRightCorner.X += diff; - UpperLeftCorner.X += diff; - } - - diff = other.LowerRightCorner.Y - LowerRightCorner.Y; - if (diff < 0) - { - LowerRightCorner.Y += diff; - UpperLeftCorner.Y += diff; - } - - diff = UpperLeftCorner.X - other.UpperLeftCorner.X; - if (diff < 0) - { - UpperLeftCorner.X -= diff; - LowerRightCorner.X -= diff; - } - - diff = UpperLeftCorner.Y - other.UpperLeftCorner.Y; - if (diff < 0) - { - UpperLeftCorner.Y -= diff; - LowerRightCorner.Y -= diff; - } - - return true; + diff = UpperLeftCorner.X - other.UpperLeftCorner.X; + if (diff < 0) { + UpperLeftCorner.X -= diff; + LowerRightCorner.X -= diff; } - //! Get width of rectangle. - T getWidth() const - { - return LowerRightCorner.X - UpperLeftCorner.X; + diff = UpperLeftCorner.Y - other.UpperLeftCorner.Y; + if (diff < 0) { + UpperLeftCorner.Y -= diff; + LowerRightCorner.Y -= diff; } - //! Get height of rectangle. - T getHeight() const - { - return LowerRightCorner.Y - UpperLeftCorner.Y; + return true; + } + + //! Get width of rectangle. + T getWidth() const + { + return LowerRightCorner.X - UpperLeftCorner.X; + } + + //! Get height of rectangle. + T getHeight() const + { + return LowerRightCorner.Y - UpperLeftCorner.Y; + } + + //! If the lower right corner of the rect is smaller then the upper left, the points are swapped. + void repair() + { + if (LowerRightCorner.X < UpperLeftCorner.X) { + T t = LowerRightCorner.X; + LowerRightCorner.X = UpperLeftCorner.X; + UpperLeftCorner.X = t; } - //! If the lower right corner of the rect is smaller then the upper left, the points are swapped. - void repair() - { - if (LowerRightCorner.X < UpperLeftCorner.X) - { - T t = LowerRightCorner.X; - LowerRightCorner.X = UpperLeftCorner.X; - UpperLeftCorner.X = t; - } - - if (LowerRightCorner.Y < UpperLeftCorner.Y) - { - T t = LowerRightCorner.Y; - LowerRightCorner.Y = UpperLeftCorner.Y; - UpperLeftCorner.Y = t; - } + if (LowerRightCorner.Y < UpperLeftCorner.Y) { + T t = LowerRightCorner.Y; + LowerRightCorner.Y = UpperLeftCorner.Y; + UpperLeftCorner.Y = t; } + } - //! Returns if the rect is valid to draw. - /** It would be invalid if the UpperLeftCorner is lower or more - right than the LowerRightCorner. */ - bool isValid() const - { - return ((LowerRightCorner.X >= UpperLeftCorner.X) && + //! Returns if the rect is valid to draw. + /** It would be invalid if the UpperLeftCorner is lower or more + right than the LowerRightCorner. */ + bool isValid() const + { + return ((LowerRightCorner.X >= UpperLeftCorner.X) && (LowerRightCorner.Y >= UpperLeftCorner.Y)); - } + } - //! Get the center of the rectangle - position2d getCenter() const - { - return position2d( - (UpperLeftCorner.X + LowerRightCorner.X) / 2, - (UpperLeftCorner.Y + LowerRightCorner.Y) / 2); - } + //! Get the center of the rectangle + position2d getCenter() const + { + return position2d( + (UpperLeftCorner.X + LowerRightCorner.X) / 2, + (UpperLeftCorner.Y + LowerRightCorner.Y) / 2); + } - //! Get the dimensions of the rectangle - dimension2d getSize() const - { - return dimension2d(getWidth(), getHeight()); - } + //! Get the dimensions of the rectangle + dimension2d getSize() const + { + return dimension2d(getWidth(), getHeight()); + } + //! Adds a point to the rectangle + /** Causes the rectangle to grow bigger if point is outside of + the box + \param p Point to add to the box. */ + void addInternalPoint(const position2d &p) + { + addInternalPoint(p.X, p.Y); + } - //! Adds a point to the rectangle - /** Causes the rectangle to grow bigger if point is outside of - the box - \param p Point to add to the box. */ - void addInternalPoint(const position2d& p) - { - addInternalPoint(p.X, p.Y); - } + //! Adds a point to the bounding rectangle + /** Causes the rectangle to grow bigger if point is outside of + the box + \param x X-Coordinate of the point to add to this box. + \param y Y-Coordinate of the point to add to this box. */ + void addInternalPoint(T x, T y) + { + if (x > LowerRightCorner.X) + LowerRightCorner.X = x; + if (y > LowerRightCorner.Y) + LowerRightCorner.Y = y; - //! Adds a point to the bounding rectangle - /** Causes the rectangle to grow bigger if point is outside of - the box - \param x X-Coordinate of the point to add to this box. - \param y Y-Coordinate of the point to add to this box. */ - void addInternalPoint(T x, T y) - { - if (x>LowerRightCorner.X) - LowerRightCorner.X = x; - if (y>LowerRightCorner.Y) - LowerRightCorner.Y = y; + if (x < UpperLeftCorner.X) + UpperLeftCorner.X = x; + if (y < UpperLeftCorner.Y) + UpperLeftCorner.Y = y; + } - if (x UpperLeftCorner; + //! Lower right corner + position2d LowerRightCorner; +}; - //! Upper left corner - position2d UpperLeftCorner; - //! Lower right corner - position2d LowerRightCorner; - }; - - //! Rectangle with float values - typedef rect rectf; - //! Rectangle with int values - typedef rect recti; +//! Rectangle with float values +typedef rect rectf; +//! Rectangle with int values +typedef rect recti; } // end namespace core } // end namespace irr - - diff --git a/include/vector2d.h b/include/vector2d.h index 1b828600..4c41389f 100644 --- a/include/vector2d.h +++ b/include/vector2d.h @@ -14,7 +14,6 @@ namespace irr namespace core { - //! 2d vector template class with lots of operators and methods. /** As of Irrlicht 1.6, this class supersedes position2d, which should be considered deprecated. */ @@ -23,87 +22,148 @@ class vector2d { public: //! Default constructor (null vector) - constexpr vector2d() : X(0), Y(0) {} + constexpr vector2d() : + X(0), Y(0) {} //! Constructor with two different values - constexpr vector2d(T nx, T ny) : X(nx), Y(ny) {} + constexpr vector2d(T nx, T ny) : + X(nx), Y(ny) {} //! Constructor with the same value for both members - explicit constexpr vector2d(T n) : X(n), Y(n) {} + explicit constexpr vector2d(T n) : + X(n), Y(n) {} - constexpr vector2d(const dimension2d& other) : X(other.Width), Y(other.Height) {} + constexpr vector2d(const dimension2d &other) : + X(other.Width), Y(other.Height) {} // operators vector2d operator-() const { return vector2d(-X, -Y); } - vector2d& operator=(const dimension2d& other) { X = other.Width; Y = other.Height; return *this; } - - vector2d operator+(const vector2d& other) const { return vector2d(X + other.X, Y + other.Y); } - vector2d operator+(const dimension2d& other) const { return vector2d(X + other.Width, Y + other.Height); } - vector2d& operator+=(const vector2d& other) { X+=other.X; Y+=other.Y; return *this; } - vector2d operator+(const T v) const { return vector2d(X + v, Y + v); } - vector2d& operator+=(const T v) { X+=v; Y+=v; return *this; } - vector2d& operator+=(const dimension2d& other) { X += other.Width; Y += other.Height; return *this; } - - vector2d operator-(const vector2d& other) const { return vector2d(X - other.X, Y - other.Y); } - vector2d operator-(const dimension2d& other) const { return vector2d(X - other.Width, Y - other.Height); } - vector2d& operator-=(const vector2d& other) { X-=other.X; Y-=other.Y; return *this; } - vector2d operator-(const T v) const { return vector2d(X - v, Y - v); } - vector2d& operator-=(const T v) { X-=v; Y-=v; return *this; } - vector2d& operator-=(const dimension2d& other) { X -= other.Width; Y -= other.Height; return *this; } - - vector2d operator*(const vector2d& other) const { return vector2d(X * other.X, Y * other.Y); } - vector2d& operator*=(const vector2d& other) { X*=other.X; Y*=other.Y; return *this; } - vector2d operator*(const T v) const { return vector2d(X * v, Y * v); } - vector2d& operator*=(const T v) { X*=v; Y*=v; return *this; } - - vector2d operator/(const vector2d& other) const { return vector2d(X / other.X, Y / other.Y); } - vector2d& operator/=(const vector2d& other) { X/=other.X; Y/=other.Y; return *this; } - vector2d operator/(const T v) const { return vector2d(X / v, Y / v); } - vector2d& operator/=(const T v) { X/=v; Y/=v; return *this; } - - T& operator [](u32 index) + vector2d &operator=(const dimension2d &other) { - _IRR_DEBUG_BREAK_IF(index>1) // access violation - - return *(&X+index); + X = other.Width; + Y = other.Height; + return *this; } - const T& operator [](u32 index) const + vector2d operator+(const vector2d &other) const { return vector2d(X + other.X, Y + other.Y); } + vector2d operator+(const dimension2d &other) const { return vector2d(X + other.Width, Y + other.Height); } + vector2d &operator+=(const vector2d &other) { - _IRR_DEBUG_BREAK_IF(index>1) // access violation + X += other.X; + Y += other.Y; + return *this; + } + vector2d operator+(const T v) const { return vector2d(X + v, Y + v); } + vector2d &operator+=(const T v) + { + X += v; + Y += v; + return *this; + } + vector2d &operator+=(const dimension2d &other) + { + X += other.Width; + Y += other.Height; + return *this; + } - return *(&X+index); + vector2d operator-(const vector2d &other) const { return vector2d(X - other.X, Y - other.Y); } + vector2d operator-(const dimension2d &other) const { return vector2d(X - other.Width, Y - other.Height); } + vector2d &operator-=(const vector2d &other) + { + X -= other.X; + Y -= other.Y; + return *this; + } + vector2d operator-(const T v) const { return vector2d(X - v, Y - v); } + vector2d &operator-=(const T v) + { + X -= v; + Y -= v; + return *this; + } + vector2d &operator-=(const dimension2d &other) + { + X -= other.Width; + Y -= other.Height; + return *this; + } + + vector2d operator*(const vector2d &other) const { return vector2d(X * other.X, Y * other.Y); } + vector2d &operator*=(const vector2d &other) + { + X *= other.X; + Y *= other.Y; + return *this; + } + vector2d operator*(const T v) const { return vector2d(X * v, Y * v); } + vector2d &operator*=(const T v) + { + X *= v; + Y *= v; + return *this; + } + + vector2d operator/(const vector2d &other) const { return vector2d(X / other.X, Y / other.Y); } + vector2d &operator/=(const vector2d &other) + { + X /= other.X; + Y /= other.Y; + return *this; + } + vector2d operator/(const T v) const { return vector2d(X / v, Y / v); } + vector2d &operator/=(const T v) + { + X /= v; + Y /= v; + return *this; + } + + T &operator[](u32 index) + { + _IRR_DEBUG_BREAK_IF(index > 1) // access violation + + return *(&X + index); + } + + const T &operator[](u32 index) const + { + _IRR_DEBUG_BREAK_IF(index > 1) // access violation + + return *(&X + index); } //! sort in order X, Y. - constexpr bool operator<=(const vector2d&other) const + constexpr bool operator<=(const vector2d &other) const { return !(*this > other); } //! sort in order X, Y. - constexpr bool operator>=(const vector2d&other) const + constexpr bool operator>=(const vector2d &other) const { return !(*this < other); } //! sort in order X, Y. - constexpr bool operator<(const vector2d&other) const + constexpr bool operator<(const vector2d &other) const { return X < other.X || (X == other.X && Y < other.Y); } //! sort in order X, Y. - constexpr bool operator>(const vector2d&other) const + constexpr bool operator>(const vector2d &other) const { return X > other.X || (X == other.X && Y > other.Y); } - constexpr bool operator==(const vector2d& other) const { + constexpr bool operator==(const vector2d &other) const + { return X == other.X && Y == other.Y; } - constexpr bool operator!=(const vector2d& other) const { + constexpr bool operator!=(const vector2d &other) const + { return !(*this == other); } @@ -113,50 +173,59 @@ public: /** Takes floating point rounding errors into account. \param other Vector to compare with. \return True if the two vector are (almost) equal, else false. */ - bool equals(const vector2d& other) const + bool equals(const vector2d &other) const { return core::equals(X, other.X) && core::equals(Y, other.Y); } - vector2d& set(T nx, T ny) {X=nx; Y=ny; return *this; } - vector2d& set(const vector2d& p) { X=p.X; Y=p.Y; return *this; } + vector2d &set(T nx, T ny) + { + X = nx; + Y = ny; + return *this; + } + vector2d &set(const vector2d &p) + { + X = p.X; + Y = p.Y; + return *this; + } //! Gets the length of the vector. /** \return The length of the vector. */ - T getLength() const { return core::squareroot( X*X + Y*Y ); } + T getLength() const { return core::squareroot(X * X + Y * Y); } //! Get the squared length of this vector /** This is useful because it is much faster than getLength(). \return The squared length of the vector. */ - T getLengthSQ() const { return X*X + Y*Y; } + T getLengthSQ() const { return X * X + Y * Y; } //! Get the dot product of this vector with another. /** \param other Other vector to take dot product with. \return The dot product of the two vectors. */ - T dotProduct(const vector2d& other) const + T dotProduct(const vector2d &other) const { - return X*other.X + Y*other.Y; + return X * other.X + Y * other.Y; } //! check if this vector is parallel to another vector - bool nearlyParallel( const vector2d & other, const T factor = relativeErrorFactor()) const + bool nearlyParallel(const vector2d &other, const T factor = relativeErrorFactor()) const { // https://eagergames.wordpress.com/2017/04/01/fast-parallel-lines-and-vectors-test/ // if a || b then a.x/a.y = b.x/b.y (similar triangles) // if a || b then either both x are 0 or both y are 0. - return equalsRelative( X*other.Y, other.X* Y, factor) - && // a bit counterintuitive, but makes sure that - // only y or only x are 0, and at same time deals - // with the case where one vector is zero vector. - (X*other.X + Y*other.Y) != 0; + return equalsRelative(X * other.Y, other.X * Y, factor) && // a bit counterintuitive, but makes sure that + // only y or only x are 0, and at same time deals + // with the case where one vector is zero vector. + (X * other.X + Y * other.Y) != 0; } //! Gets distance from another point. /** Here, the vector is interpreted as a point in 2-dimensional space. \param other Other vector to measure from. \return Distance from other point. */ - T getDistanceFrom(const vector2d& other) const + T getDistanceFrom(const vector2d &other) const { return vector2d(X - other.X, Y - other.Y).getLength(); } @@ -165,7 +234,7 @@ public: /** Here, the vector is interpreted as a point in 2-dimensional space. \param other Other vector to measure from. \return Squared distance from other point. */ - T getDistanceFromSQ(const vector2d& other) const + T getDistanceFromSQ(const vector2d &other) const { return vector2d(X - other.X, Y - other.Y).getLengthSQ(); } @@ -174,7 +243,7 @@ public: /** \param degrees Amount of degrees to rotate by, anticlockwise. \param center Rotation center. \return This vector after transformation. */ - vector2d& rotateBy(f64 degrees, const vector2d& center=vector2d()) + vector2d &rotateBy(f64 degrees, const vector2d ¢er = vector2d()) { degrees *= DEGTORAD64; const f64 cs = cos(degrees); @@ -183,7 +252,7 @@ public: X -= center.X; Y -= center.Y; - set((T)(X*cs - Y*sn), (T)(X*sn + Y*cs)); + set((T)(X * cs - Y * sn), (T)(X * sn + Y * cs)); X += center.X; Y += center.Y; @@ -193,12 +262,12 @@ public: //! Normalize the vector. /** The null vector is left untouched. \return Reference to this vector, after normalization. */ - vector2d& normalize() + vector2d &normalize() { - f32 length = (f32)(X*X + Y*Y); - if ( length == 0 ) + f32 length = (f32)(X * X + Y * Y); + if (length == 0) return *this; - length = core::reciprocal_squareroot ( length ); + length = core::reciprocal_squareroot(length); X = (T)(X * length); Y = (T)(Y * length); return *this; @@ -212,20 +281,18 @@ public: { if (Y == 0) return X < 0 ? 180 : 0; - else - if (X == 0) + else if (X == 0) return Y < 0 ? 270 : 90; - if ( Y > 0) + if (Y > 0) if (X > 0) - return atan((irr::f64)Y/(irr::f64)X) * RADTODEG64; + return atan((irr::f64)Y / (irr::f64)X) * RADTODEG64; else - return 180.0-atan((irr::f64)Y/-(irr::f64)X) * RADTODEG64; + return 180.0 - atan((irr::f64)Y / -(irr::f64)X) * RADTODEG64; + else if (X > 0) + return 360.0 - atan(-(irr::f64)Y / (irr::f64)X) * RADTODEG64; else - if (X > 0) - return 360.0-atan(-(irr::f64)Y/(irr::f64)X) * RADTODEG64; - else - return 180.0+atan(-(irr::f64)Y/-(irr::f64)X) * RADTODEG64; + return 180.0 + atan(-(irr::f64)Y / -(irr::f64)X) * RADTODEG64; } //! Calculates the angle of this vector in degrees in the counter trigonometric sense. @@ -240,19 +307,16 @@ public: // don't use getLength here to avoid precision loss with s32 vectors // avoid floating-point trouble as sqrt(y*y) is occasionally larger than y, so clamp - const f64 tmp = core::clamp(Y / sqrt((f64)(X*X + Y*Y)), -1.0, 1.0); - const f64 angle = atan( core::squareroot(1 - tmp*tmp) / tmp) * RADTODEG64; + const f64 tmp = core::clamp(Y / sqrt((f64)(X * X + Y * Y)), -1.0, 1.0); + const f64 angle = atan(core::squareroot(1 - tmp * tmp) / tmp) * RADTODEG64; - if (X>0 && Y>0) + if (X > 0 && Y > 0) return angle + 270; - else - if (X>0 && Y<0) + else if (X > 0 && Y < 0) return angle + 90; - else - if (X<0 && Y<0) + else if (X < 0 && Y < 0) return 90 - angle; - else - if (X<0 && Y>0) + else if (X < 0 && Y > 0) return 270 - angle; return angle; @@ -261,20 +325,20 @@ public: //! Calculates the angle between this vector and another one in degree. /** \param b Other vector to test with. \return Returns a value between 0 and 90. */ - inline f64 getAngleWith(const vector2d& b) const + inline f64 getAngleWith(const vector2d &b) const { - f64 tmp = (f64)(X*b.X + Y*b.Y); + f64 tmp = (f64)(X * b.X + Y * b.Y); if (tmp == 0.0) return 90.0; - tmp = tmp / core::squareroot((f64)((X*X + Y*Y) * (b.X*b.X + b.Y*b.Y))); + tmp = tmp / core::squareroot((f64)((X * X + Y * Y) * (b.X * b.X + b.Y * b.Y))); if (tmp < 0.0) tmp = -tmp; - if ( tmp > 1.0 ) // avoid floating-point trouble + if (tmp > 1.0) // avoid floating-point trouble tmp = 1.0; - return atan(sqrt(1 - tmp*tmp) / tmp) * RADTODEG64; + return atan(sqrt(1 - tmp * tmp) / tmp) * RADTODEG64; } //! Returns if this vector interpreted as a point is on a line between two other points. @@ -282,7 +346,7 @@ public: \param begin Beginning vector to compare between. \param end Ending vector to compare between. \return True if this vector is between begin and end, false if not. */ - bool isBetweenPoints(const vector2d& begin, const vector2d& end) const + bool isBetweenPoints(const vector2d &begin, const vector2d &end) const { // . end // / @@ -293,13 +357,10 @@ public: // - // . this point (am I inside or outside)? // - if (begin.X != end.X) - { + if (begin.X != end.X) { return ((begin.X <= X && X <= end.X) || (begin.X >= X && X >= end.X)); - } - else - { + } else { return ((begin.Y <= Y && Y <= end.Y) || (begin.Y >= Y && Y >= end.Y)); } @@ -310,10 +371,10 @@ public: \param d Interpolation value between 0.0f (all the other vector) and 1.0f (all this vector). Note that this is the opposite direction of interpolation to getInterpolated_quadratic() \return An interpolated vector. This vector is not modified. */ - vector2d getInterpolated(const vector2d& other, f64 d) const + vector2d getInterpolated(const vector2d &other, f64 d) const { const f64 inv = 1.0f - d; - return vector2d((T)(other.X*inv + X*d), (T)(other.Y*inv + Y*d)); + return vector2d((T)(other.X * inv + X * d), (T)(other.Y * inv + Y * d)); } //! Creates a quadratically interpolated vector between this and two other vectors. @@ -322,7 +383,7 @@ public: \param d Interpolation value between 0.0f (all this vector) and 1.0f (all the 3rd vector). Note that this is the opposite direction of interpolation to getInterpolated() and interpolate() \return An interpolated vector. This vector is not modified. */ - vector2d getInterpolated_quadratic(const vector2d& v2, const vector2d& v3, f64 d) const + vector2d getInterpolated_quadratic(const vector2d &v2, const vector2d &v3, f64 d) const { // this*(1-d)*(1-d) + 2 * v2 * (1-d) + v3 * d * d; const f64 inv = 1.0f - d; @@ -330,8 +391,8 @@ public: const f64 mul1 = 2.0f * d * inv; const f64 mul2 = d * d; - return vector2d ( (T)(X * mul0 + v2.X * mul1 + v3.X * mul2), - (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2)); + return vector2d((T)(X * mul0 + v2.X * mul1 + v3.X * mul2), + (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2)); } /*! Test if this point and another 2 points taken as triplet @@ -339,7 +400,7 @@ public: to check winding order in triangles for 2D meshes. \return 0 if points are colinear, 1 if clockwise, 2 if anticlockwise */ - s32 checkOrientation( const vector2d & b, const vector2d & c) const + s32 checkOrientation(const vector2d &b, const vector2d &c) const { // Example of clockwise points // @@ -351,27 +412,28 @@ public: // +---------------> X T val = (b.Y - Y) * (c.X - b.X) - - (b.X - X) * (c.Y - b.Y); + (b.X - X) * (c.Y - b.Y); - if (val == 0) return 0; // colinear + if (val == 0) + return 0; // colinear return (val > 0) ? 1 : 2; // clock or counterclock wise } /*! Returns true if points (a,b,c) are clockwise on the X,Y plane*/ - inline bool areClockwise( const vector2d & b, const vector2d & c) const + inline bool areClockwise(const vector2d &b, const vector2d &c) const { T val = (b.Y - Y) * (c.X - b.X) - - (b.X - X) * (c.Y - b.Y); + (b.X - X) * (c.Y - b.Y); return val > 0; } /*! Returns true if points (a,b,c) are counterclockwise on the X,Y plane*/ - inline bool areCounterClockwise( const vector2d & b, const vector2d & c) const + inline bool areCounterClockwise(const vector2d &b, const vector2d &c) const { T val = (b.Y - Y) * (c.X - b.X) - - (b.X - X) * (c.Y - b.Y); + (b.X - X) * (c.Y - b.Y); return val < 0; } @@ -382,10 +444,10 @@ public: \param d Interpolation value between 0.0f (all vector b) and 1.0f (all vector a) Note that this is the opposite direction of interpolation to getInterpolated_quadratic() */ - vector2d& interpolate( const vector2d& a, const vector2d& b, f64 d) + vector2d &interpolate(const vector2d &a, const vector2d &b, f64 d) { - X = (T)((f64)b.X + ( ( a.X - b.X ) * d )); - Y = (T)((f64)b.Y + ( ( a.Y - b.Y ) * d )); + X = (T)((f64)b.X + ((a.X - b.X) * d)); + Y = (T)((f64)b.Y + ((a.Y - b.Y) * d)); return *this; } @@ -396,21 +458,30 @@ public: T Y; }; - //! Typedef for f32 2d vector. - typedef vector2d vector2df; +//! Typedef for f32 2d vector. +typedef vector2d vector2df; - //! Typedef for integer 2d vector. - typedef vector2d vector2di; +//! Typedef for integer 2d vector. +typedef vector2d vector2di; - template - vector2d operator*(const S scalar, const vector2d& vector) { return vector*scalar; } +template +vector2d operator*(const S scalar, const vector2d &vector) +{ + return vector * scalar; +} - // These methods are declared in dimension2d, but need definitions of vector2d - template - dimension2d::dimension2d(const vector2d& other) : Width(other.X), Height(other.Y) { } +// These methods are declared in dimension2d, but need definitions of vector2d +template +dimension2d::dimension2d(const vector2d &other) : + Width(other.X), Height(other.Y) +{ +} - template - bool dimension2d::operator==(const vector2d& other) const { return Width == other.X && Height == other.Y; } +template +bool dimension2d::operator==(const vector2d &other) const +{ + return Width == other.X && Height == other.Y; +} } // end namespace core } // end namespace irr @@ -418,10 +489,10 @@ public: namespace std { -template -struct hash > +template +struct hash> { - size_t operator()(const irr::core::vector2d& vec) const + size_t operator()(const irr::core::vector2d &vec) const { size_t h1 = hash()(vec.X); size_t h2 = hash()(vec.Y); @@ -430,5 +501,3 @@ struct hash > }; } - - diff --git a/include/vector3d.h b/include/vector3d.h index 4353ff14..a69f17e1 100644 --- a/include/vector3d.h +++ b/include/vector3d.h @@ -13,453 +13,520 @@ namespace irr namespace core { - //! 3d vector template class with lots of operators and methods. - /** The vector3d class is used in Irrlicht for three main purposes: - 1) As a direction vector (most of the methods assume this). - 2) As a position in 3d space (which is synonymous with a direction vector from the origin to this position). - 3) To hold three Euler rotations, where X is pitch, Y is yaw and Z is roll. +//! 3d vector template class with lots of operators and methods. +/** The vector3d class is used in Irrlicht for three main purposes: + 1) As a direction vector (most of the methods assume this). + 2) As a position in 3d space (which is synonymous with a direction vector from the origin to this position). + 3) To hold three Euler rotations, where X is pitch, Y is yaw and Z is roll. +*/ +template +class vector3d +{ +public: + //! Default constructor (null vector). + constexpr vector3d() : + X(0), Y(0), Z(0) {} + //! Constructor with three different values + constexpr vector3d(T nx, T ny, T nz) : + X(nx), Y(ny), Z(nz) {} + //! Constructor with the same value for all elements + explicit constexpr vector3d(T n) : + X(n), Y(n), Z(n) {} + + // operators + + vector3d operator-() const { return vector3d(-X, -Y, -Z); } + + vector3d operator+(const vector3d &other) const { return vector3d(X + other.X, Y + other.Y, Z + other.Z); } + vector3d &operator+=(const vector3d &other) + { + X += other.X; + Y += other.Y; + Z += other.Z; + return *this; + } + vector3d operator+(const T val) const { return vector3d(X + val, Y + val, Z + val); } + vector3d &operator+=(const T val) + { + X += val; + Y += val; + Z += val; + return *this; + } + + vector3d operator-(const vector3d &other) const { return vector3d(X - other.X, Y - other.Y, Z - other.Z); } + vector3d &operator-=(const vector3d &other) + { + X -= other.X; + Y -= other.Y; + Z -= other.Z; + return *this; + } + vector3d operator-(const T val) const { return vector3d(X - val, Y - val, Z - val); } + vector3d &operator-=(const T val) + { + X -= val; + Y -= val; + Z -= val; + return *this; + } + + vector3d operator*(const vector3d &other) const { return vector3d(X * other.X, Y * other.Y, Z * other.Z); } + vector3d &operator*=(const vector3d &other) + { + X *= other.X; + Y *= other.Y; + Z *= other.Z; + return *this; + } + vector3d operator*(const T v) const { return vector3d(X * v, Y * v, Z * v); } + vector3d &operator*=(const T v) + { + X *= v; + Y *= v; + Z *= v; + return *this; + } + + vector3d operator/(const vector3d &other) const { return vector3d(X / other.X, Y / other.Y, Z / other.Z); } + vector3d &operator/=(const vector3d &other) + { + X /= other.X; + Y /= other.Y; + Z /= other.Z; + return *this; + } + vector3d operator/(const T v) const { return vector3d(X / v, Y / v, Z / v); } + vector3d &operator/=(const T v) + { + X /= v; + Y /= v; + Z /= v; + return *this; + } + + T &operator[](u32 index) + { + _IRR_DEBUG_BREAK_IF(index > 2) // access violation + + return *(&X + index); + } + + const T &operator[](u32 index) const + { + _IRR_DEBUG_BREAK_IF(index > 2) // access violation + + return *(&X + index); + } + + //! sort in order X, Y, Z. + constexpr bool operator<=(const vector3d &other) const + { + return !(*this > other); + } + + //! sort in order X, Y, Z. + constexpr bool operator>=(const vector3d &other) const + { + return !(*this < other); + } + + //! sort in order X, Y, Z. + constexpr bool operator<(const vector3d &other) const + { + return X < other.X || (X == other.X && Y < other.Y) || + (X == other.X && Y == other.Y && Z < other.Z); + } + + //! sort in order X, Y, Z. + constexpr bool operator>(const vector3d &other) const + { + return X > other.X || (X == other.X && Y > other.Y) || + (X == other.X && Y == other.Y && Z > other.Z); + } + + constexpr bool operator==(const vector3d &other) const + { + return X == other.X && Y == other.Y && Z == other.Z; + } + + constexpr bool operator!=(const vector3d &other) const + { + return !(*this == other); + } + + // functions + + //! Checks if this vector equals the other one. + /** Takes floating point rounding errors into account. + \param other Vector to compare with. + \return True if the two vector are (almost) equal, else false. */ + bool equals(const vector3d &other) const + { + return core::equals(X, other.X) && core::equals(Y, other.Y) && core::equals(Z, other.Z); + } + + vector3d &set(const T nx, const T ny, const T nz) + { + X = nx; + Y = ny; + Z = nz; + return *this; + } + vector3d &set(const vector3d &p) + { + X = p.X; + Y = p.Y; + Z = p.Z; + return *this; + } + + //! Get length of the vector. + T getLength() const { return core::squareroot(X * X + Y * Y + Z * Z); } + + //! Get squared length of the vector. + /** This is useful because it is much faster than getLength(). + \return Squared length of the vector. */ + T getLengthSQ() const { return X * X + Y * Y + Z * Z; } + + //! Get the dot product with another vector. + T dotProduct(const vector3d &other) const + { + return X * other.X + Y * other.Y + Z * other.Z; + } + + //! Get distance from another point. + /** Here, the vector is interpreted as point in 3 dimensional space. */ + T getDistanceFrom(const vector3d &other) const + { + return vector3d(X - other.X, Y - other.Y, Z - other.Z).getLength(); + } + + //! Returns squared distance from another point. + /** Here, the vector is interpreted as point in 3 dimensional space. */ + T getDistanceFromSQ(const vector3d &other) const + { + return vector3d(X - other.X, Y - other.Y, Z - other.Z).getLengthSQ(); + } + + //! Calculates the cross product with another vector. + /** \param p Vector to multiply with. + \return Cross product of this vector with p. */ + vector3d crossProduct(const vector3d &p) const + { + return vector3d(Y * p.Z - Z * p.Y, Z * p.X - X * p.Z, X * p.Y - Y * p.X); + } + + //! Returns if this vector interpreted as a point is on a line between two other points. + /** It is assumed that the point is on the line. + \param begin Beginning vector to compare between. + \param end Ending vector to compare between. + \return True if this vector is between begin and end, false if not. */ + bool isBetweenPoints(const vector3d &begin, const vector3d &end) const + { + const T f = (end - begin).getLengthSQ(); + return getDistanceFromSQ(begin) <= f && + getDistanceFromSQ(end) <= f; + } + + //! Normalizes the vector. + /** In case of the 0 vector the result is still 0, otherwise + the length of the vector will be 1. + \return Reference to this vector after normalization. */ + vector3d &normalize() + { + f64 length = X * X + Y * Y + Z * Z; + if (length == 0) // this check isn't an optimization but prevents getting NAN in the sqrt. + return *this; + length = core::reciprocal_squareroot(length); + + X = (T)(X * length); + Y = (T)(Y * length); + Z = (T)(Z * length); + return *this; + } + + //! Sets the length of the vector to a new value + vector3d &setLength(T newlength) + { + normalize(); + return (*this *= newlength); + } + + //! Inverts the vector. + vector3d &invert() + { + X *= -1; + Y *= -1; + Z *= -1; + return *this; + } + + //! Rotates the vector by a specified number of degrees around the Y axis and the specified center. + /** CAREFUL: For historical reasons rotateXZBy uses a right-handed rotation + (maybe to make it more similar to the 2D vector rotations which are counterclockwise). + To have this work the same way as rest of Irrlicht (nodes, matrices, other rotateBy functions) pass -1*degrees in here. + \param degrees Number of degrees to rotate around the Y axis. + \param center The center of the rotation. */ + void rotateXZBy(f64 degrees, const vector3d ¢er = vector3d()) + { + degrees *= DEGTORAD64; + f64 cs = cos(degrees); + f64 sn = sin(degrees); + X -= center.X; + Z -= center.Z; + set((T)(X * cs - Z * sn), Y, (T)(X * sn + Z * cs)); + X += center.X; + Z += center.Z; + } + + //! Rotates the vector by a specified number of degrees around the Z axis and the specified center. + /** \param degrees: Number of degrees to rotate around the Z axis. + \param center: The center of the rotation. */ + void rotateXYBy(f64 degrees, const vector3d ¢er = vector3d()) + { + degrees *= DEGTORAD64; + f64 cs = cos(degrees); + f64 sn = sin(degrees); + X -= center.X; + Y -= center.Y; + set((T)(X * cs - Y * sn), (T)(X * sn + Y * cs), Z); + X += center.X; + Y += center.Y; + } + + //! Rotates the vector by a specified number of degrees around the X axis and the specified center. + /** \param degrees: Number of degrees to rotate around the X axis. + \param center: The center of the rotation. */ + void rotateYZBy(f64 degrees, const vector3d ¢er = vector3d()) + { + degrees *= DEGTORAD64; + f64 cs = cos(degrees); + f64 sn = sin(degrees); + Z -= center.Z; + Y -= center.Y; + set(X, (T)(Y * cs - Z * sn), (T)(Y * sn + Z * cs)); + Z += center.Z; + Y += center.Y; + } + + //! Creates an interpolated vector between this vector and another vector. + /** \param other The other vector to interpolate with. + \param d Interpolation value between 0.0f (all the other vector) and 1.0f (all this vector). + Note that this is the opposite direction of interpolation to getInterpolated_quadratic() + \return An interpolated vector. This vector is not modified. */ + vector3d getInterpolated(const vector3d &other, f64 d) const + { + const f64 inv = 1.0 - d; + return vector3d((T)(other.X * inv + X * d), (T)(other.Y * inv + Y * d), (T)(other.Z * inv + Z * d)); + } + + //! Creates a quadratically interpolated vector between this and two other vectors. + /** \param v2 Second vector to interpolate with. + \param v3 Third vector to interpolate with (maximum at 1.0f) + \param d Interpolation value between 0.0f (all this vector) and 1.0f (all the 3rd vector). + Note that this is the opposite direction of interpolation to getInterpolated() and interpolate() + \return An interpolated vector. This vector is not modified. */ + vector3d getInterpolated_quadratic(const vector3d &v2, const vector3d &v3, f64 d) const + { + // this*(1-d)*(1-d) + 2 * v2 * (1-d) + v3 * d * d; + const f64 inv = (T)1.0 - d; + const f64 mul0 = inv * inv; + const f64 mul1 = (T)2.0 * d * inv; + const f64 mul2 = d * d; + + return vector3d((T)(X * mul0 + v2.X * mul1 + v3.X * mul2), + (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2), + (T)(Z * mul0 + v2.Z * mul1 + v3.Z * mul2)); + } + + //! Sets this vector to the linearly interpolated vector between a and b. + /** \param a first vector to interpolate with, maximum at 1.0f + \param b second vector to interpolate with, maximum at 0.0f + \param d Interpolation value between 0.0f (all vector b) and 1.0f (all vector a) + Note that this is the opposite direction of interpolation to getInterpolated_quadratic() */ - template - class vector3d + vector3d &interpolate(const vector3d &a, const vector3d &b, f64 d) { - public: - //! Default constructor (null vector). - constexpr vector3d() : X(0), Y(0), Z(0) {} - //! Constructor with three different values - constexpr vector3d(T nx, T ny, T nz) : X(nx), Y(ny), Z(nz) {} - //! Constructor with the same value for all elements - explicit constexpr vector3d(T n) : X(n), Y(n), Z(n) {} + X = (T)((f64)b.X + ((a.X - b.X) * d)); + Y = (T)((f64)b.Y + ((a.Y - b.Y) * d)); + Z = (T)((f64)b.Z + ((a.Z - b.Z) * d)); + return *this; + } - // operators + //! Get the rotations that would make a (0,0,1) direction vector point in the same direction as this direction vector. + /** Thanks to Arras on the Irrlicht forums for this method. This utility method is very useful for + orienting scene nodes towards specific targets. For example, if this vector represents the difference + between two scene nodes, then applying the result of getHorizontalAngle() to one scene node will point + it at the other one. + Example code: + // Where target and seeker are of type ISceneNode* + const vector3df toTarget(target->getAbsolutePosition() - seeker->getAbsolutePosition()); + const vector3df requiredRotation = toTarget.getHorizontalAngle(); + seeker->setRotation(requiredRotation); - vector3d operator-() const { return vector3d(-X, -Y, -Z); } - - vector3d operator+(const vector3d& other) const { return vector3d(X + other.X, Y + other.Y, Z + other.Z); } - vector3d& operator+=(const vector3d& other) { X+=other.X; Y+=other.Y; Z+=other.Z; return *this; } - vector3d operator+(const T val) const { return vector3d(X + val, Y + val, Z + val); } - vector3d& operator+=(const T val) { X+=val; Y+=val; Z+=val; return *this; } - - vector3d operator-(const vector3d& other) const { return vector3d(X - other.X, Y - other.Y, Z - other.Z); } - vector3d& operator-=(const vector3d& other) { X-=other.X; Y-=other.Y; Z-=other.Z; return *this; } - vector3d operator-(const T val) const { return vector3d(X - val, Y - val, Z - val); } - vector3d& operator-=(const T val) { X-=val; Y-=val; Z-=val; return *this; } - - vector3d operator*(const vector3d& other) const { return vector3d(X * other.X, Y * other.Y, Z * other.Z); } - vector3d& operator*=(const vector3d& other) { X*=other.X; Y*=other.Y; Z*=other.Z; return *this; } - vector3d operator*(const T v) const { return vector3d(X * v, Y * v, Z * v); } - vector3d& operator*=(const T v) { X*=v; Y*=v; Z*=v; return *this; } - - vector3d operator/(const vector3d& other) const { return vector3d(X / other.X, Y / other.Y, Z / other.Z); } - vector3d& operator/=(const vector3d& other) { X/=other.X; Y/=other.Y; Z/=other.Z; return *this; } - vector3d operator/(const T v) const { return vector3d(X/v, Y/v, Z/v); } - vector3d& operator/=(const T v) { X/=v; Y/=v; Z/=v; return *this; } - - T& operator [](u32 index) - { - _IRR_DEBUG_BREAK_IF(index>2) // access violation - - return *(&X+index); - } - - const T& operator [](u32 index) const - { - _IRR_DEBUG_BREAK_IF(index>2) // access violation - - return *(&X+index); - } - - //! sort in order X, Y, Z. - constexpr bool operator<=(const vector3d&other) const - { - return !(*this > other); - } - - //! sort in order X, Y, Z. - constexpr bool operator>=(const vector3d&other) const - { - return !(*this < other); - } - - //! sort in order X, Y, Z. - constexpr bool operator<(const vector3d&other) const - { - return X < other.X || (X == other.X && Y < other.Y) || - (X == other.X && Y == other.Y && Z < other.Z); - } - - //! sort in order X, Y, Z. - constexpr bool operator>(const vector3d&other) const - { - return X > other.X || (X == other.X && Y > other.Y) || - (X == other.X && Y == other.Y && Z > other.Z); - } - - constexpr bool operator==(const vector3d& other) const - { - return X == other.X && Y == other.Y && Z == other.Z; - } - - constexpr bool operator!=(const vector3d& other) const - { - return !(*this == other); - } - - // functions - - //! Checks if this vector equals the other one. - /** Takes floating point rounding errors into account. - \param other Vector to compare with. - \return True if the two vector are (almost) equal, else false. */ - bool equals(const vector3d& other) const - { - return core::equals(X, other.X) && core::equals(Y, other.Y) && core::equals(Z, other.Z); - } - - vector3d& set(const T nx, const T ny, const T nz) {X=nx; Y=ny; Z=nz; return *this;} - vector3d& set(const vector3d& p) {X=p.X; Y=p.Y; Z=p.Z;return *this;} - - //! Get length of the vector. - T getLength() const { return core::squareroot( X*X + Y*Y + Z*Z ); } - - //! Get squared length of the vector. - /** This is useful because it is much faster than getLength(). - \return Squared length of the vector. */ - T getLengthSQ() const { return X*X + Y*Y + Z*Z; } - - //! Get the dot product with another vector. - T dotProduct(const vector3d& other) const - { - return X*other.X + Y*other.Y + Z*other.Z; - } - - //! Get distance from another point. - /** Here, the vector is interpreted as point in 3 dimensional space. */ - T getDistanceFrom(const vector3d& other) const - { - return vector3d(X - other.X, Y - other.Y, Z - other.Z).getLength(); - } - - //! Returns squared distance from another point. - /** Here, the vector is interpreted as point in 3 dimensional space. */ - T getDistanceFromSQ(const vector3d& other) const - { - return vector3d(X - other.X, Y - other.Y, Z - other.Z).getLengthSQ(); - } - - //! Calculates the cross product with another vector. - /** \param p Vector to multiply with. - \return Cross product of this vector with p. */ - vector3d crossProduct(const vector3d& p) const - { - return vector3d(Y * p.Z - Z * p.Y, Z * p.X - X * p.Z, X * p.Y - Y * p.X); - } - - //! Returns if this vector interpreted as a point is on a line between two other points. - /** It is assumed that the point is on the line. - \param begin Beginning vector to compare between. - \param end Ending vector to compare between. - \return True if this vector is between begin and end, false if not. */ - bool isBetweenPoints(const vector3d& begin, const vector3d& end) const - { - const T f = (end - begin).getLengthSQ(); - return getDistanceFromSQ(begin) <= f && - getDistanceFromSQ(end) <= f; - } - - //! Normalizes the vector. - /** In case of the 0 vector the result is still 0, otherwise - the length of the vector will be 1. - \return Reference to this vector after normalization. */ - vector3d& normalize() - { - f64 length = X*X + Y*Y + Z*Z; - if (length == 0 ) // this check isn't an optimization but prevents getting NAN in the sqrt. - return *this; - length = core::reciprocal_squareroot(length); - - X = (T)(X * length); - Y = (T)(Y * length); - Z = (T)(Z * length); - return *this; - } - - //! Sets the length of the vector to a new value - vector3d& setLength(T newlength) - { - normalize(); - return (*this *= newlength); - } - - //! Inverts the vector. - vector3d& invert() - { - X *= -1; - Y *= -1; - Z *= -1; - return *this; - } - - //! Rotates the vector by a specified number of degrees around the Y axis and the specified center. - /** CAREFUL: For historical reasons rotateXZBy uses a right-handed rotation - (maybe to make it more similar to the 2D vector rotations which are counterclockwise). - To have this work the same way as rest of Irrlicht (nodes, matrices, other rotateBy functions) pass -1*degrees in here. - \param degrees Number of degrees to rotate around the Y axis. - \param center The center of the rotation. */ - void rotateXZBy(f64 degrees, const vector3d& center=vector3d()) - { - degrees *= DEGTORAD64; - f64 cs = cos(degrees); - f64 sn = sin(degrees); - X -= center.X; - Z -= center.Z; - set((T)(X*cs - Z*sn), Y, (T)(X*sn + Z*cs)); - X += center.X; - Z += center.Z; - } - - //! Rotates the vector by a specified number of degrees around the Z axis and the specified center. - /** \param degrees: Number of degrees to rotate around the Z axis. - \param center: The center of the rotation. */ - void rotateXYBy(f64 degrees, const vector3d& center=vector3d()) - { - degrees *= DEGTORAD64; - f64 cs = cos(degrees); - f64 sn = sin(degrees); - X -= center.X; - Y -= center.Y; - set((T)(X*cs - Y*sn), (T)(X*sn + Y*cs), Z); - X += center.X; - Y += center.Y; - } - - //! Rotates the vector by a specified number of degrees around the X axis and the specified center. - /** \param degrees: Number of degrees to rotate around the X axis. - \param center: The center of the rotation. */ - void rotateYZBy(f64 degrees, const vector3d& center=vector3d()) - { - degrees *= DEGTORAD64; - f64 cs = cos(degrees); - f64 sn = sin(degrees); - Z -= center.Z; - Y -= center.Y; - set(X, (T)(Y*cs - Z*sn), (T)(Y*sn + Z*cs)); - Z += center.Z; - Y += center.Y; - } - - //! Creates an interpolated vector between this vector and another vector. - /** \param other The other vector to interpolate with. - \param d Interpolation value between 0.0f (all the other vector) and 1.0f (all this vector). - Note that this is the opposite direction of interpolation to getInterpolated_quadratic() - \return An interpolated vector. This vector is not modified. */ - vector3d getInterpolated(const vector3d& other, f64 d) const - { - const f64 inv = 1.0 - d; - return vector3d((T)(other.X*inv + X*d), (T)(other.Y*inv + Y*d), (T)(other.Z*inv + Z*d)); - } - - //! Creates a quadratically interpolated vector between this and two other vectors. - /** \param v2 Second vector to interpolate with. - \param v3 Third vector to interpolate with (maximum at 1.0f) - \param d Interpolation value between 0.0f (all this vector) and 1.0f (all the 3rd vector). - Note that this is the opposite direction of interpolation to getInterpolated() and interpolate() - \return An interpolated vector. This vector is not modified. */ - vector3d getInterpolated_quadratic(const vector3d& v2, const vector3d& v3, f64 d) const - { - // this*(1-d)*(1-d) + 2 * v2 * (1-d) + v3 * d * d; - const f64 inv = (T) 1.0 - d; - const f64 mul0 = inv * inv; - const f64 mul1 = (T) 2.0 * d * inv; - const f64 mul2 = d * d; - - return vector3d ((T)(X * mul0 + v2.X * mul1 + v3.X * mul2), - (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2), - (T)(Z * mul0 + v2.Z * mul1 + v3.Z * mul2)); - } - - //! Sets this vector to the linearly interpolated vector between a and b. - /** \param a first vector to interpolate with, maximum at 1.0f - \param b second vector to interpolate with, maximum at 0.0f - \param d Interpolation value between 0.0f (all vector b) and 1.0f (all vector a) - Note that this is the opposite direction of interpolation to getInterpolated_quadratic() - */ - vector3d& interpolate(const vector3d& a, const vector3d& b, f64 d) - { - X = (T)((f64)b.X + ( ( a.X - b.X ) * d )); - Y = (T)((f64)b.Y + ( ( a.Y - b.Y ) * d )); - Z = (T)((f64)b.Z + ( ( a.Z - b.Z ) * d )); - return *this; - } - - - //! Get the rotations that would make a (0,0,1) direction vector point in the same direction as this direction vector. - /** Thanks to Arras on the Irrlicht forums for this method. This utility method is very useful for - orienting scene nodes towards specific targets. For example, if this vector represents the difference - between two scene nodes, then applying the result of getHorizontalAngle() to one scene node will point - it at the other one. - Example code: - // Where target and seeker are of type ISceneNode* - const vector3df toTarget(target->getAbsolutePosition() - seeker->getAbsolutePosition()); - const vector3df requiredRotation = toTarget.getHorizontalAngle(); - seeker->setRotation(requiredRotation); - - \return A rotation vector containing the X (pitch) and Y (raw) rotations (in degrees) that when applied to a - +Z (e.g. 0, 0, 1) direction vector would make it point in the same direction as this vector. The Z (roll) rotation - is always 0, since two Euler rotations are sufficient to point in any given direction. */ - vector3d getHorizontalAngle() const - { - vector3d angle; - - // tmp avoids some precision troubles on some compilers when working with T=s32 - f64 tmp = (atan2((f64)X, (f64)Z) * RADTODEG64); - angle.Y = (T)tmp; - - if (angle.Y < 0) - angle.Y += 360; - if (angle.Y >= 360) - angle.Y -= 360; - - const f64 z1 = core::squareroot(X*X + Z*Z); - - tmp = (atan2((f64)z1, (f64)Y) * RADTODEG64 - 90.0); - angle.X = (T)tmp; - - if (angle.X < 0) - angle.X += 360; - if (angle.X >= 360) - angle.X -= 360; - - return angle; - } - - //! Get the spherical coordinate angles - /** This returns Euler degrees for the point represented by - this vector. The calculation assumes the pole at (0,1,0) and - returns the angles in X and Y. - */ - vector3d getSphericalCoordinateAngles() const - { - vector3d angle; - const f64 length = X*X + Y*Y + Z*Z; - - if (length) - { - if (X!=0) - { - angle.Y = (T)(atan2((f64)Z,(f64)X) * RADTODEG64); - } - else if (Z<0) - angle.Y=180; - - angle.X = (T)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64); - } - return angle; - } - - //! Builds a direction vector from (this) rotation vector. - /** This vector is assumed to be a rotation vector composed of 3 Euler angle rotations, in degrees. - The implementation performs the same calculations as using a matrix to do the rotation. - - \param[in] forwards The direction representing "forwards" which will be rotated by this vector. - If you do not provide a direction, then the +Z axis (0, 0, 1) will be assumed to be forwards. - \return A direction vector calculated by rotating the forwards direction by the 3 Euler angles - (in degrees) represented by this vector. */ - vector3d rotationToDirection(const vector3d & forwards = vector3d(0, 0, 1)) const - { - const f64 cr = cos( core::DEGTORAD64 * X ); - const f64 sr = sin( core::DEGTORAD64 * X ); - const f64 cp = cos( core::DEGTORAD64 * Y ); - const f64 sp = sin( core::DEGTORAD64 * Y ); - const f64 cy = cos( core::DEGTORAD64 * Z ); - const f64 sy = sin( core::DEGTORAD64 * Z ); - - const f64 srsp = sr*sp; - const f64 crsp = cr*sp; - - const f64 pseudoMatrix[] = { - ( cp*cy ), ( cp*sy ), ( -sp ), - ( srsp*cy-cr*sy ), ( srsp*sy+cr*cy ), ( sr*cp ), - ( crsp*cy+sr*sy ), ( crsp*sy-sr*cy ), ( cr*cp )}; - - return vector3d( - (T)(forwards.X * pseudoMatrix[0] + - forwards.Y * pseudoMatrix[3] + - forwards.Z * pseudoMatrix[6]), - (T)(forwards.X * pseudoMatrix[1] + - forwards.Y * pseudoMatrix[4] + - forwards.Z * pseudoMatrix[7]), - (T)(forwards.X * pseudoMatrix[2] + - forwards.Y * pseudoMatrix[5] + - forwards.Z * pseudoMatrix[8])); - } - - //! Fills an array of 4 values with the vector data (usually floats). - /** Useful for setting in shader constants for example. The fourth value - will always be 0. */ - void getAs4Values(T* array) const - { - array[0] = X; - array[1] = Y; - array[2] = Z; - array[3] = 0; - } - - //! Fills an array of 3 values with the vector data (usually floats). - /** Useful for setting in shader constants for example.*/ - void getAs3Values(T* array) const - { - array[0] = X; - array[1] = Y; - array[2] = Z; - } - - - //! X coordinate of the vector - T X; - - //! Y coordinate of the vector - T Y; - - //! Z coordinate of the vector - T Z; - }; - - //! partial specialization for integer vectors - // Implementer note: inline keyword needed due to template specialization for s32. Otherwise put specialization into a .cpp - template <> - inline vector3d vector3d::operator /(s32 val) const {return core::vector3d(X/val,Y/val,Z/val);} - template <> - inline vector3d& vector3d::operator /=(s32 val) {X/=val;Y/=val;Z/=val; return *this;} - - template <> - inline vector3d vector3d::getSphericalCoordinateAngles() const + \return A rotation vector containing the X (pitch) and Y (raw) rotations (in degrees) that when applied to a + +Z (e.g. 0, 0, 1) direction vector would make it point in the same direction as this vector. The Z (roll) rotation + is always 0, since two Euler rotations are sufficient to point in any given direction. */ + vector3d getHorizontalAngle() const { - vector3d angle; - const f64 length = X*X + Y*Y + Z*Z; + vector3d angle; - if (length) - { - if (X!=0) - { - angle.Y = round32((f32)(atan2((f64)Z,(f64)X) * RADTODEG64)); - } - else if (Z<0) - angle.Y=180; + // tmp avoids some precision troubles on some compilers when working with T=s32 + f64 tmp = (atan2((f64)X, (f64)Z) * RADTODEG64); + angle.Y = (T)tmp; - angle.X = round32((f32)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64)); + if (angle.Y < 0) + angle.Y += 360; + if (angle.Y >= 360) + angle.Y -= 360; + + const f64 z1 = core::squareroot(X * X + Z * Z); + + tmp = (atan2((f64)z1, (f64)Y) * RADTODEG64 - 90.0); + angle.X = (T)tmp; + + if (angle.X < 0) + angle.X += 360; + if (angle.X >= 360) + angle.X -= 360; + + return angle; + } + + //! Get the spherical coordinate angles + /** This returns Euler degrees for the point represented by + this vector. The calculation assumes the pole at (0,1,0) and + returns the angles in X and Y. + */ + vector3d getSphericalCoordinateAngles() const + { + vector3d angle; + const f64 length = X * X + Y * Y + Z * Z; + + if (length) { + if (X != 0) { + angle.Y = (T)(atan2((f64)Z, (f64)X) * RADTODEG64); + } else if (Z < 0) + angle.Y = 180; + + angle.X = (T)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64); } return angle; } - //! Typedef for a f32 3d vector. - typedef vector3d vector3df; + //! Builds a direction vector from (this) rotation vector. + /** This vector is assumed to be a rotation vector composed of 3 Euler angle rotations, in degrees. + The implementation performs the same calculations as using a matrix to do the rotation. - //! Typedef for an integer 3d vector. - typedef vector3d vector3di; + \param[in] forwards The direction representing "forwards" which will be rotated by this vector. + If you do not provide a direction, then the +Z axis (0, 0, 1) will be assumed to be forwards. + \return A direction vector calculated by rotating the forwards direction by the 3 Euler angles + (in degrees) represented by this vector. */ + vector3d rotationToDirection(const vector3d &forwards = vector3d(0, 0, 1)) const + { + const f64 cr = cos(core::DEGTORAD64 * X); + const f64 sr = sin(core::DEGTORAD64 * X); + const f64 cp = cos(core::DEGTORAD64 * Y); + const f64 sp = sin(core::DEGTORAD64 * Y); + const f64 cy = cos(core::DEGTORAD64 * Z); + const f64 sy = sin(core::DEGTORAD64 * Z); - //! Function multiplying a scalar and a vector component-wise. - template - vector3d operator*(const S scalar, const vector3d& vector) { return vector*scalar; } + const f64 srsp = sr * sp; + const f64 crsp = cr * sp; + + const f64 pseudoMatrix[] = { + (cp * cy), (cp * sy), (-sp), + (srsp * cy - cr * sy), (srsp * sy + cr * cy), (sr * cp), + (crsp * cy + sr * sy), (crsp * sy - sr * cy), (cr * cp)}; + + return vector3d( + (T)(forwards.X * pseudoMatrix[0] + + forwards.Y * pseudoMatrix[3] + + forwards.Z * pseudoMatrix[6]), + (T)(forwards.X * pseudoMatrix[1] + + forwards.Y * pseudoMatrix[4] + + forwards.Z * pseudoMatrix[7]), + (T)(forwards.X * pseudoMatrix[2] + + forwards.Y * pseudoMatrix[5] + + forwards.Z * pseudoMatrix[8])); + } + + //! Fills an array of 4 values with the vector data (usually floats). + /** Useful for setting in shader constants for example. The fourth value + will always be 0. */ + void getAs4Values(T *array) const + { + array[0] = X; + array[1] = Y; + array[2] = Z; + array[3] = 0; + } + + //! Fills an array of 3 values with the vector data (usually floats). + /** Useful for setting in shader constants for example.*/ + void getAs3Values(T *array) const + { + array[0] = X; + array[1] = Y; + array[2] = Z; + } + + //! X coordinate of the vector + T X; + + //! Y coordinate of the vector + T Y; + + //! Z coordinate of the vector + T Z; +}; + +//! partial specialization for integer vectors +// Implementer note: inline keyword needed due to template specialization for s32. Otherwise put specialization into a .cpp +template <> +inline vector3d vector3d::operator/(s32 val) const +{ + return core::vector3d(X / val, Y / val, Z / val); +} +template <> +inline vector3d &vector3d::operator/=(s32 val) +{ + X /= val; + Y /= val; + Z /= val; + return *this; +} + +template <> +inline vector3d vector3d::getSphericalCoordinateAngles() const +{ + vector3d angle; + const f64 length = X * X + Y * Y + Z * Z; + + if (length) { + if (X != 0) { + angle.Y = round32((f32)(atan2((f64)Z, (f64)X) * RADTODEG64)); + } else if (Z < 0) + angle.Y = 180; + + angle.X = round32((f32)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64)); + } + return angle; +} + +//! Typedef for a f32 3d vector. +typedef vector3d vector3df; + +//! Typedef for an integer 3d vector. +typedef vector3d vector3di; + +//! Function multiplying a scalar and a vector component-wise. +template +vector3d operator*(const S scalar, const vector3d &vector) +{ + return vector * scalar; +} } // end namespace core } // end namespace irr @@ -467,10 +534,10 @@ namespace core namespace std { -template -struct hash > +template +struct hash> { - size_t operator()(const irr::core::vector3d& vec) const + size_t operator()(const irr::core::vector3d &vec) const { size_t h1 = hash()(vec.X); size_t h2 = hash()(vec.Y); @@ -480,5 +547,3 @@ struct hash > }; } - - diff --git a/source/Irrlicht/Android/CAndroidAssetFileArchive.cpp b/source/Irrlicht/Android/CAndroidAssetFileArchive.cpp index e4c1b8ce..59df2d2a 100644 --- a/source/Irrlicht/Android/CAndroidAssetFileArchive.cpp +++ b/source/Irrlicht/Android/CAndroidAssetFileArchive.cpp @@ -2,15 +2,13 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h - - #include "CAndroidAssetReader.h" #include "CReadFile.h" #include "coreutil.h" #include "CAndroidAssetFileArchive.h" #include "CIrrDeviceAndroid.h" -#include "os.h" // for logging (just keep it in even when not needed right now as it's used all the time) +#include "os.h" // for logging (just keep it in even when not needed right now as it's used all the time) #include #include @@ -21,82 +19,78 @@ namespace irr namespace io { -CAndroidAssetFileArchive::CAndroidAssetFileArchive(AAssetManager *assetManager, bool ignoreCase, bool ignorePaths) - : CFileList("/asset", ignoreCase, ignorePaths), AssetManager(assetManager) +CAndroidAssetFileArchive::CAndroidAssetFileArchive(AAssetManager *assetManager, bool ignoreCase, bool ignorePaths) : + CFileList("/asset", ignoreCase, ignorePaths), AssetManager(assetManager) { } - CAndroidAssetFileArchive::~CAndroidAssetFileArchive() { } - //! get the archive type E_FILE_ARCHIVE_TYPE CAndroidAssetFileArchive::getType() const { return EFAT_ANDROID_ASSET; } -const IFileList* CAndroidAssetFileArchive::getFileList() const +const IFileList *CAndroidAssetFileArchive::getFileList() const { - // The assert_manager can not read directory names, so - // getFileList returns only files in folders which have been added. - return this; + // The assert_manager can not read directory names, so + // getFileList returns only files in folders which have been added. + return this; } - //! opens a file by file name -IReadFile* CAndroidAssetFileArchive::createAndOpenFile(const io::path& filename) +IReadFile *CAndroidAssetFileArchive::createAndOpenFile(const io::path &filename) { - CAndroidAssetReader *reader = new CAndroidAssetReader(AssetManager, filename); + CAndroidAssetReader *reader = new CAndroidAssetReader(AssetManager, filename); - if(reader->isOpen()) + if (reader->isOpen()) return reader; reader->drop(); - return NULL; + return NULL; } //! opens a file by index -IReadFile* CAndroidAssetFileArchive::createAndOpenFile(u32 index) +IReadFile *CAndroidAssetFileArchive::createAndOpenFile(u32 index) { - const io::path& filename(getFullFileName(index)); - if ( filename.empty() ) + const io::path &filename(getFullFileName(index)); + if (filename.empty()) return 0; - return createAndOpenFile(filename); + return createAndOpenFile(filename); } void CAndroidAssetFileArchive::addDirectoryToFileList(const io::path &dirname_) { io::path dirname(dirname_); fschar_t lastChar = dirname.lastChar(); - if ( lastChar == '/' || lastChar == '\\' ) - dirname.erase(dirname.size()-1); + if (lastChar == '/' || lastChar == '\\') + dirname.erase(dirname.size() - 1); // os::Printer::log("addDirectoryToFileList:", dirname.c_str(), ELL_DEBUG); - if (findFile(dirname, true) >= 0 ) - return; // was already added + if (findFile(dirname, true) >= 0) + return; // was already added AAssetDir *dir = AAssetManager_openDir(AssetManager, core::stringc(dirname).c_str()); - if(!dir) + if (!dir) return; // add directory itself - addItem(dirname, 0, 0, /*isDir*/true, getFileCount()); + addItem(dirname, 0, 0, /*isDir*/ true, getFileCount()); // add all files in folder. // Note: AAssetDir_getNextFileName does not return directory names (neither does any other NDK function) - while(const char *filename = AAssetDir_getNextFileName(dir)) - { - core::stringc full_filename= dirname=="" ? filename - : dirname+"/"+filename; + while (const char *filename = AAssetDir_getNextFileName(dir)) { + core::stringc full_filename = dirname == "" ? filename + : dirname + "/" + filename; // We can't get the size without opening the file - so for performance // reasons we set the file size to 0. // TODO: Does this really cost so much performance that it's worth losing this information? Dirs are usually just added once at startup... - addItem(full_filename, /*offet*/0, /*size*/0, /*isDir*/false, getFileCount()); + addItem(full_filename, /*offet*/ 0, /*size*/ 0, /*isDir*/ false, getFileCount()); // os::Printer::log("addItem:", full_filename.c_str(), ELL_DEBUG); } AAssetDir_close(dir); @@ -104,4 +98,3 @@ void CAndroidAssetFileArchive::addDirectoryToFileList(const io::path &dirname_) } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/Android/CAndroidAssetFileArchive.h b/source/Irrlicht/Android/CAndroidAssetFileArchive.h index cc61728c..3ca815ed 100644 --- a/source/Irrlicht/Android/CAndroidAssetFileArchive.h +++ b/source/Irrlicht/Android/CAndroidAssetFileArchive.h @@ -18,43 +18,41 @@ namespace io /*! Android asset file system written August 2012 by J.Henrichs (later reworked by others). */ - class CAndroidAssetFileArchive : public virtual IFileArchive, - virtual CFileList - { - public: +class CAndroidAssetFileArchive : public virtual IFileArchive, + virtual CFileList +{ +public: + //! constructor + CAndroidAssetFileArchive(AAssetManager *assetManager, bool ignoreCase, bool ignorePaths); - //! constructor - CAndroidAssetFileArchive(AAssetManager *assetManager, bool ignoreCase, bool ignorePaths); + //! destructor + virtual ~CAndroidAssetFileArchive(); - //! destructor - virtual ~CAndroidAssetFileArchive(); + //! opens a file by file name + virtual IReadFile *createAndOpenFile(const io::path &filename); - //! opens a file by file name - virtual IReadFile* createAndOpenFile(const io::path& filename); + //! opens a file by index + virtual IReadFile *createAndOpenFile(u32 index); - //! opens a file by index - virtual IReadFile* createAndOpenFile(u32 index); + //! returns the list of files + virtual const IFileList *getFileList() const; - //! returns the list of files - virtual const IFileList* getFileList() const; + //! get the archive type + virtual E_FILE_ARCHIVE_TYPE getType() const; - //! get the archive type - virtual E_FILE_ARCHIVE_TYPE getType() const; + //! Add a directory to read files from. Since the Android + //! API does not return names of directories, they need to + //! be added manually. + virtual void addDirectoryToFileList(const io::path &filename); - //! Add a directory to read files from. Since the Android - //! API does not return names of directories, they need to - //! be added manually. - virtual void addDirectoryToFileList(const io::path &filename); + //! return the name (id) of the file Archive + const io::path &getArchiveName() const override { return Path; } - //! return the name (id) of the file Archive - const io::path& getArchiveName() const override {return Path;} +protected: + //! Android's asset manager + AAssetManager *AssetManager; - protected: - //! Android's asset manager - AAssetManager *AssetManager; - - }; // CAndroidAssetFileArchive +}; // CAndroidAssetFileArchive } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/Android/CAndroidAssetReader.cpp b/source/Irrlicht/Android/CAndroidAssetReader.cpp index e535d886..bf3c51af 100644 --- a/source/Irrlicht/Android/CAndroidAssetReader.cpp +++ b/source/Irrlicht/Android/CAndroidAssetReader.cpp @@ -17,34 +17,33 @@ namespace irr namespace io { -CAndroidAssetReader::CAndroidAssetReader(AAssetManager *assetManager, const io::path &filename) - : AssetManager(assetManager), Filename(filename) +CAndroidAssetReader::CAndroidAssetReader(AAssetManager *assetManager, const io::path &filename) : + AssetManager(assetManager), Filename(filename) { Asset = AAssetManager_open(AssetManager, - core::stringc(filename).c_str(), - AASSET_MODE_RANDOM); - + core::stringc(filename).c_str(), + AASSET_MODE_RANDOM); } CAndroidAssetReader::~CAndroidAssetReader() { - if(Asset) + if (Asset) AAsset_close(Asset); } -size_t CAndroidAssetReader::read(void* buffer, size_t sizeToRead) +size_t CAndroidAssetReader::read(void *buffer, size_t sizeToRead) { int readBytes = AAsset_read(Asset, buffer, sizeToRead); - if ( readBytes >= 0 ) + if (readBytes >= 0) return size_t(readBytes); - return 0; // direct fd access is not possible (for example, if the asset is compressed). + return 0; // direct fd access is not possible (for example, if the asset is compressed). } bool CAndroidAssetReader::seek(long finalPos, bool relativeMovement) { - off_t status = AAsset_seek(Asset, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET); + off_t status = AAsset_seek(Asset, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET); - return status+1; + return status + 1; } long CAndroidAssetReader::getSize() const @@ -57,12 +56,10 @@ long CAndroidAssetReader::getPos() const return AAsset_getLength(Asset) - AAsset_getRemainingLength(Asset); } -const io::path& CAndroidAssetReader::getFileName() const +const io::path &CAndroidAssetReader::getFileName() const { return Filename; } - } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/Android/CAndroidAssetReader.h b/source/Irrlicht/Android/CAndroidAssetReader.h index 16bed853..9f6156f3 100644 --- a/source/Irrlicht/Android/CAndroidAssetReader.h +++ b/source/Irrlicht/Android/CAndroidAssetReader.h @@ -15,51 +15,50 @@ namespace irr namespace io { - class CAndroidAssetReader : public virtual IReadFile - { - public: - CAndroidAssetReader(AAssetManager *assetManager, const io::path &filename); +class CAndroidAssetReader : public virtual IReadFile +{ +public: + CAndroidAssetReader(AAssetManager *assetManager, const io::path &filename); - virtual ~CAndroidAssetReader(); + virtual ~CAndroidAssetReader(); - //! Reads an amount of bytes from the file. - /** \param buffer Pointer to buffer where read bytes are written to. - \param sizeToRead Amount of bytes to read from the file. - \return How many bytes were read. */ - virtual size_t read(void* buffer, size_t sizeToRead); + //! Reads an amount of bytes from the file. + /** \param buffer Pointer to buffer where read bytes are written to. + \param sizeToRead Amount of bytes to read from the file. + \return How many bytes were read. */ + virtual size_t read(void *buffer, size_t sizeToRead); - //! Changes position in file - /** \param finalPos Destination position in the file. - \param relativeMovement If set to true, the position in the file is - changed relative to current position. Otherwise the position is changed - from beginning of file. - \return True if successful, otherwise false. */ - virtual bool seek(long finalPos, bool relativeMovement = false); + //! Changes position in file + /** \param finalPos Destination position in the file. + \param relativeMovement If set to true, the position in the file is + changed relative to current position. Otherwise the position is changed + from beginning of file. + \return True if successful, otherwise false. */ + virtual bool seek(long finalPos, bool relativeMovement = false); - //! Get size of file. - /** \return Size of the file in bytes. */ - virtual long getSize() const; + //! Get size of file. + /** \return Size of the file in bytes. */ + virtual long getSize() const; - //! Get the current position in the file. - /** \return Current position in the file in bytes. */ - virtual long getPos() const; + //! Get the current position in the file. + /** \return Current position in the file in bytes. */ + virtual long getPos() const; - //! Get name of file. - /** \return File name as zero terminated character string. */ - virtual const io::path& getFileName() const; + //! Get name of file. + /** \return File name as zero terminated character string. */ + virtual const io::path &getFileName() const; - /** Return true if the file could be opened. */ - bool isOpen() const { return Asset!=NULL; } + /** Return true if the file could be opened. */ + bool isOpen() const { return Asset != NULL; } - private: - //! Android's asset manager - AAssetManager *AssetManager; +private: + //! Android's asset manager + AAssetManager *AssetManager; - // An asset, i.e. file - AAsset *Asset; - path Filename; - }; + // An asset, i.e. file + AAsset *Asset; + path Filename; +}; } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/Android/CIrrDeviceAndroid.cpp b/source/Irrlicht/Android/CIrrDeviceAndroid.cpp index 52cc95d7..d0e9d18a 100644 --- a/source/Irrlicht/Android/CIrrDeviceAndroid.cpp +++ b/source/Irrlicht/Android/CIrrDeviceAndroid.cpp @@ -17,29 +17,29 @@ namespace irr { - namespace video - { - IVideoDriver* createOGLES1Driver(const SIrrlichtCreationParameters& params, - io::IFileSystem* io, video::IContextManager* contextManager); +namespace video +{ +IVideoDriver *createOGLES1Driver(const SIrrlichtCreationParameters ¶ms, + io::IFileSystem *io, video::IContextManager *contextManager); - IVideoDriver* createOGLES2Driver(const SIrrlichtCreationParameters& params, - io::IFileSystem* io, video::IContextManager* contextManager); - } +IVideoDriver *createOGLES2Driver(const SIrrlichtCreationParameters ¶ms, + io::IFileSystem *io, video::IContextManager *contextManager); +} } namespace irr { -CIrrDeviceAndroid::CIrrDeviceAndroid(const SIrrlichtCreationParameters& param) - : CIrrDeviceStub(param), Accelerometer(0), Gyroscope(0), Initialized(false), - Stopped(true), Paused(true), Focused(false), JNIEnvAttachedToVM(0) +CIrrDeviceAndroid::CIrrDeviceAndroid(const SIrrlichtCreationParameters ¶m) : + CIrrDeviceStub(param), Accelerometer(0), Gyroscope(0), Initialized(false), + Stopped(true), Paused(true), Focused(false), JNIEnvAttachedToVM(0) { #ifdef _DEBUG setDebugName("CIrrDeviceAndroid"); #endif // Get the interface to the native Android activity. - Android = (android_app*)(param.PrivateData); + Android = (android_app *)(param.PrivateData); // Set the private data so we can use it in any static callbacks. Android->userData = this; @@ -60,37 +60,30 @@ CIrrDeviceAndroid::CIrrDeviceAndroid(const SIrrlichtCreationParameters& param) os::Printer::log("Waiting for Android activity window to be created.", ELL_DEBUG); - do - { + do { s32 Events = 0; - android_poll_source* Source = 0; + android_poll_source *Source = 0; - while ((ALooper_pollAll((!Initialized || isWindowActive()) ? 0 : -1, 0, &Events, (void**)&Source)) >= 0) - { - if(Source) + while ((ALooper_pollAll((!Initialized || isWindowActive()) ? 0 : -1, 0, &Events, (void **)&Source)) >= 0) { + if (Source) Source->process(Android, Source); } - } - while(!Initialized); + } while (!Initialized); } - CIrrDeviceAndroid::~CIrrDeviceAndroid() { - if (GUIEnvironment) - { + if (GUIEnvironment) { GUIEnvironment->drop(); GUIEnvironment = 0; } - if (SceneManager) - { + if (SceneManager) { SceneManager->drop(); SceneManager = 0; } - if (VideoDriver) - { + if (VideoDriver) { VideoDriver->drop(); VideoDriver = 0; } @@ -105,47 +98,43 @@ bool CIrrDeviceAndroid::run() s32 id; s32 Events = 0; - android_poll_source* Source = 0; + android_poll_source *Source = 0; - while ((id = ALooper_pollAll(0, 0, &Events, (void**)&Source)) >= 0) - { - if(Source) + while ((id = ALooper_pollAll(0, 0, &Events, (void **)&Source)) >= 0) { + if (Source) Source->process(Android, Source); // if a sensor has data, we'll process it now. - if (id == LOOPER_ID_USER) - { + if (id == LOOPER_ID_USER) { ASensorEvent sensorEvent; - while (ASensorEventQueue_getEvents(SensorEventQueue, &sensorEvent, 1) > 0) - { - switch (sensorEvent.type) - { - case ASENSOR_TYPE_ACCELEROMETER: - SEvent accEvent; - accEvent.EventType = EET_ACCELEROMETER_EVENT; - accEvent.AccelerometerEvent.X = sensorEvent.acceleration.x; - accEvent.AccelerometerEvent.Y = sensorEvent.acceleration.y; - accEvent.AccelerometerEvent.Z = sensorEvent.acceleration.z; + while (ASensorEventQueue_getEvents(SensorEventQueue, &sensorEvent, 1) > 0) { + switch (sensorEvent.type) { + case ASENSOR_TYPE_ACCELEROMETER: + SEvent accEvent; + accEvent.EventType = EET_ACCELEROMETER_EVENT; + accEvent.AccelerometerEvent.X = sensorEvent.acceleration.x; + accEvent.AccelerometerEvent.Y = sensorEvent.acceleration.y; + accEvent.AccelerometerEvent.Z = sensorEvent.acceleration.z; - postEventFromUser(accEvent); + postEventFromUser(accEvent); break; - case ASENSOR_TYPE_GYROSCOPE: - SEvent gyroEvent; - gyroEvent.EventType = EET_GYROSCOPE_EVENT; - gyroEvent.GyroscopeEvent.X = sensorEvent.vector.x; - gyroEvent.GyroscopeEvent.Y = sensorEvent.vector.y; - gyroEvent.GyroscopeEvent.Z = sensorEvent.vector.z; + case ASENSOR_TYPE_GYROSCOPE: + SEvent gyroEvent; + gyroEvent.EventType = EET_GYROSCOPE_EVENT; + gyroEvent.GyroscopeEvent.X = sensorEvent.vector.x; + gyroEvent.GyroscopeEvent.Y = sensorEvent.vector.y; + gyroEvent.GyroscopeEvent.Z = sensorEvent.vector.z; - postEventFromUser(gyroEvent); + postEventFromUser(gyroEvent); break; - default: + default: break; } } } - if(!Initialized) + if (!Initialized) break; } @@ -154,7 +143,7 @@ bool CIrrDeviceAndroid::run() void CIrrDeviceAndroid::yield() { - struct timespec ts = {0,1}; + struct timespec ts = {0, 1}; nanosleep(&ts, NULL); } @@ -163,8 +152,8 @@ void CIrrDeviceAndroid::sleep(u32 timeMs, bool pauseTimer) const bool wasStopped = Timer ? Timer->isStopped() : true; struct timespec ts; - ts.tv_sec = (time_t) (timeMs / 1000); - ts.tv_nsec = (long) (timeMs % 1000) * 1000000; + ts.tv_sec = (time_t)(timeMs / 1000); + ts.tv_nsec = (long)(timeMs % 1000) * 1000000; if (pauseTimer && !wasStopped) Timer->stop(); @@ -175,7 +164,7 @@ void CIrrDeviceAndroid::sleep(u32 timeMs, bool pauseTimer) Timer->start(); } -void CIrrDeviceAndroid::setWindowCaption(const wchar_t* text) +void CIrrDeviceAndroid::setWindowCaption(const wchar_t *text) { } @@ -230,125 +219,119 @@ E_DEVICE_TYPE CIrrDeviceAndroid::getType() const return EIDT_ANDROID; } -void CIrrDeviceAndroid::handleAndroidCommand(android_app* app, int32_t cmd) +void CIrrDeviceAndroid::handleAndroidCommand(android_app *app, int32_t cmd) { - CIrrDeviceAndroid* device = (CIrrDeviceAndroid*)app->userData; + CIrrDeviceAndroid *device = (CIrrDeviceAndroid *)app->userData; SEvent event; event.EventType = EET_SYSTEM_EVENT; event.SystemEvent.EventType = ESET_ANDROID_CMD; event.SystemEvent.AndroidCmd.Cmd = cmd; - if ( device->postEventFromUser(event) ) + if (device->postEventFromUser(event)) return; - switch (cmd) - { - case APP_CMD_INPUT_CHANGED: - os::Printer::log("Android command APP_CMD_INPUT_CHANGED", ELL_DEBUG); + switch (cmd) { + case APP_CMD_INPUT_CHANGED: + os::Printer::log("Android command APP_CMD_INPUT_CHANGED", ELL_DEBUG); break; - case APP_CMD_WINDOW_RESIZED: - os::Printer::log("Android command APP_CMD_WINDOW_RESIZED", ELL_DEBUG); + case APP_CMD_WINDOW_RESIZED: + os::Printer::log("Android command APP_CMD_WINDOW_RESIZED", ELL_DEBUG); break; - case APP_CMD_WINDOW_REDRAW_NEEDED: - os::Printer::log("Android command APP_CMD_WINDOW_REDRAW_NEEDED", ELL_DEBUG); + case APP_CMD_WINDOW_REDRAW_NEEDED: + os::Printer::log("Android command APP_CMD_WINDOW_REDRAW_NEEDED", ELL_DEBUG); break; - case APP_CMD_SAVE_STATE: - os::Printer::log("Android command APP_CMD_SAVE_STATE", ELL_DEBUG); + case APP_CMD_SAVE_STATE: + os::Printer::log("Android command APP_CMD_SAVE_STATE", ELL_DEBUG); break; - case APP_CMD_CONTENT_RECT_CHANGED: - os::Printer::log("Android command APP_CMD_CONTENT_RECT_CHANGED", ELL_DEBUG); + case APP_CMD_CONTENT_RECT_CHANGED: + os::Printer::log("Android command APP_CMD_CONTENT_RECT_CHANGED", ELL_DEBUG); break; - case APP_CMD_CONFIG_CHANGED: - os::Printer::log("Android command APP_CMD_CONFIG_CHANGED", ELL_DEBUG); + case APP_CMD_CONFIG_CHANGED: + os::Printer::log("Android command APP_CMD_CONFIG_CHANGED", ELL_DEBUG); break; - case APP_CMD_LOW_MEMORY: - os::Printer::log("Android command APP_CMD_LOW_MEMORY", ELL_DEBUG); + case APP_CMD_LOW_MEMORY: + os::Printer::log("Android command APP_CMD_LOW_MEMORY", ELL_DEBUG); break; - case APP_CMD_START: - os::Printer::log("Android command APP_CMD_START", ELL_DEBUG); - device->Stopped = false; + case APP_CMD_START: + os::Printer::log("Android command APP_CMD_START", ELL_DEBUG); + device->Stopped = false; break; - case APP_CMD_INIT_WINDOW: - os::Printer::log("Android command APP_CMD_INIT_WINDOW", ELL_DEBUG); - device->getExposedVideoData().OGLESAndroid.Window = app->window; + case APP_CMD_INIT_WINDOW: + os::Printer::log("Android command APP_CMD_INIT_WINDOW", ELL_DEBUG); + device->getExposedVideoData().OGLESAndroid.Window = app->window; - if (device->CreationParams.WindowSize.Width == 0 || device->CreationParams.WindowSize.Height == 0) - { - device->CreationParams.WindowSize.Width = ANativeWindow_getWidth(app->window); - device->CreationParams.WindowSize.Height = ANativeWindow_getHeight(app->window); - } + if (device->CreationParams.WindowSize.Width == 0 || device->CreationParams.WindowSize.Height == 0) { + device->CreationParams.WindowSize.Width = ANativeWindow_getWidth(app->window); + device->CreationParams.WindowSize.Height = ANativeWindow_getHeight(app->window); + } - device->getContextManager()->initialize(device->CreationParams, device->ExposedVideoData); - device->getContextManager()->generateSurface(); - device->getContextManager()->generateContext(); - device->getContextManager()->activateContext(device->getContextManager()->getContext()); + device->getContextManager()->initialize(device->CreationParams, device->ExposedVideoData); + device->getContextManager()->generateSurface(); + device->getContextManager()->generateContext(); + device->getContextManager()->activateContext(device->getContextManager()->getContext()); - if (!device->Initialized) - { - io::CAndroidAssetFileArchive* assets = new io::CAndroidAssetFileArchive( device->Android->activity->assetManager, false, false); - assets->addDirectoryToFileList(""); - device->FileSystem->addFileArchive(assets); - assets->drop(); + if (!device->Initialized) { + io::CAndroidAssetFileArchive *assets = new io::CAndroidAssetFileArchive(device->Android->activity->assetManager, false, false); + assets->addDirectoryToFileList(""); + device->FileSystem->addFileArchive(assets); + assets->drop(); - device->createDriver(); + device->createDriver(); - if (device->VideoDriver) - device->createGUIAndScene(); - } - device->Initialized = true; + if (device->VideoDriver) + device->createGUIAndScene(); + } + device->Initialized = true; break; - case APP_CMD_TERM_WINDOW: - os::Printer::log("Android command APP_CMD_TERM_WINDOW", ELL_DEBUG); - device->getContextManager()->destroySurface(); + case APP_CMD_TERM_WINDOW: + os::Printer::log("Android command APP_CMD_TERM_WINDOW", ELL_DEBUG); + device->getContextManager()->destroySurface(); break; - case APP_CMD_GAINED_FOCUS: - os::Printer::log("Android command APP_CMD_GAINED_FOCUS", ELL_DEBUG); - device->Focused = true; + case APP_CMD_GAINED_FOCUS: + os::Printer::log("Android command APP_CMD_GAINED_FOCUS", ELL_DEBUG); + device->Focused = true; break; - case APP_CMD_LOST_FOCUS: - os::Printer::log("Android command APP_CMD_LOST_FOCUS", ELL_DEBUG); - device->Focused = false; + case APP_CMD_LOST_FOCUS: + os::Printer::log("Android command APP_CMD_LOST_FOCUS", ELL_DEBUG); + device->Focused = false; + break; + case APP_CMD_DESTROY: + os::Printer::log("Android command APP_CMD_DESTROY", ELL_DEBUG); + if (device->JNIEnvAttachedToVM) { + device->JNIEnvAttachedToVM = 0; + device->Android->activity->vm->DetachCurrentThread(); + } + device->Initialized = false; + break; + case APP_CMD_PAUSE: + os::Printer::log("Android command APP_CMD_PAUSE", ELL_DEBUG); + device->Paused = true; + break; + case APP_CMD_STOP: + os::Printer::log("Android command APP_CMD_STOP", ELL_DEBUG); + device->Stopped = true; + break; + case APP_CMD_RESUME: + os::Printer::log("Android command APP_CMD_RESUME", ELL_DEBUG); + device->Paused = false; + break; + default: break; - case APP_CMD_DESTROY: - os::Printer::log("Android command APP_CMD_DESTROY", ELL_DEBUG); - if ( device->JNIEnvAttachedToVM ) - { - device->JNIEnvAttachedToVM = 0; - device->Android->activity->vm->DetachCurrentThread(); - } - device->Initialized = false; - break; - case APP_CMD_PAUSE: - os::Printer::log("Android command APP_CMD_PAUSE", ELL_DEBUG); - device->Paused = true; - break; - case APP_CMD_STOP: - os::Printer::log("Android command APP_CMD_STOP", ELL_DEBUG); - device->Stopped = true; - break; - case APP_CMD_RESUME: - os::Printer::log("Android command APP_CMD_RESUME", ELL_DEBUG); - device->Paused = false; - break; - default: - break; } } -s32 CIrrDeviceAndroid::handleInput(android_app* app, AInputEvent* androidEvent) +s32 CIrrDeviceAndroid::handleInput(android_app *app, AInputEvent *androidEvent) { - CIrrDeviceAndroid* device = (CIrrDeviceAndroid*)app->userData; + CIrrDeviceAndroid *device = (CIrrDeviceAndroid *)app->userData; s32 status = 0; - switch ( AInputEvent_getType(androidEvent) ) - { - case AINPUT_EVENT_TYPE_MOTION: - { - SEvent event; - event.EventType = EET_TOUCH_INPUT_EVENT; + switch (AInputEvent_getType(androidEvent)) { + case AINPUT_EVENT_TYPE_MOTION: { + SEvent event; + event.EventType = EET_TOUCH_INPUT_EVENT; - s32 eventAction = AMotionEvent_getAction(androidEvent); - s32 eventType = eventAction & AMOTION_EVENT_ACTION_MASK; + s32 eventAction = AMotionEvent_getAction(androidEvent); + s32 eventType = eventAction & AMOTION_EVENT_ACTION_MASK; #if 0 // Useful for debugging. We might have to pass some of those infos on at some point. @@ -361,159 +344,141 @@ s32 CIrrDeviceAndroid::handleInput(android_app* app, AInputEvent* androidEvent) os::Printer::log("edgeFlags: ", core::stringc(flags).c_str(), ELL_DEBUG); #endif - bool touchReceived = true; + bool touchReceived = true; - switch (eventType) - { - case AMOTION_EVENT_ACTION_DOWN: - case AMOTION_EVENT_ACTION_POINTER_DOWN: - event.TouchInput.Event = ETIE_PRESSED_DOWN; - break; - case AMOTION_EVENT_ACTION_MOVE: - event.TouchInput.Event = ETIE_MOVED; - break; - case AMOTION_EVENT_ACTION_UP: - case AMOTION_EVENT_ACTION_POINTER_UP: - case AMOTION_EVENT_ACTION_CANCEL: - event.TouchInput.Event = ETIE_LEFT_UP; - break; - default: - touchReceived = false; - break; - } + switch (eventType) { + case AMOTION_EVENT_ACTION_DOWN: + case AMOTION_EVENT_ACTION_POINTER_DOWN: + event.TouchInput.Event = ETIE_PRESSED_DOWN; + break; + case AMOTION_EVENT_ACTION_MOVE: + event.TouchInput.Event = ETIE_MOVED; + break; + case AMOTION_EVENT_ACTION_UP: + case AMOTION_EVENT_ACTION_POINTER_UP: + case AMOTION_EVENT_ACTION_CANCEL: + event.TouchInput.Event = ETIE_LEFT_UP; + break; + default: + touchReceived = false; + break; + } - if (touchReceived) - { - // Process all touches for move action. - if (event.TouchInput.Event == ETIE_MOVED) - { - s32 pointerCount = AMotionEvent_getPointerCount(androidEvent); + if (touchReceived) { + // Process all touches for move action. + if (event.TouchInput.Event == ETIE_MOVED) { + s32 pointerCount = AMotionEvent_getPointerCount(androidEvent); - for (s32 i = 0; i < pointerCount; ++i) - { - event.TouchInput.ID = AMotionEvent_getPointerId(androidEvent, i); - event.TouchInput.X = AMotionEvent_getX(androidEvent, i); - event.TouchInput.Y = AMotionEvent_getY(androidEvent, i); - event.TouchInput.touchedCount = AMotionEvent_getPointerCount(androidEvent); - - device->postEventFromUser(event); - } - } - else // Process one touch for other actions. - { - s32 pointerIndex = (eventAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - - event.TouchInput.ID = AMotionEvent_getPointerId(androidEvent, pointerIndex); - event.TouchInput.X = AMotionEvent_getX(androidEvent, pointerIndex); - event.TouchInput.Y = AMotionEvent_getY(androidEvent, pointerIndex); + for (s32 i = 0; i < pointerCount; ++i) { + event.TouchInput.ID = AMotionEvent_getPointerId(androidEvent, i); + event.TouchInput.X = AMotionEvent_getX(androidEvent, i); + event.TouchInput.Y = AMotionEvent_getY(androidEvent, i); event.TouchInput.touchedCount = AMotionEvent_getPointerCount(androidEvent); device->postEventFromUser(event); } + } else // Process one touch for other actions. + { + s32 pointerIndex = (eventAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - status = 1; + event.TouchInput.ID = AMotionEvent_getPointerId(androidEvent, pointerIndex); + event.TouchInput.X = AMotionEvent_getX(androidEvent, pointerIndex); + event.TouchInput.Y = AMotionEvent_getY(androidEvent, pointerIndex); + event.TouchInput.touchedCount = AMotionEvent_getPointerCount(androidEvent); + + device->postEventFromUser(event); } - } - break; - case AINPUT_EVENT_TYPE_KEY: - { - SEvent event; - event.EventType = EET_KEY_INPUT_EVENT; - int32_t keyCode = AKeyEvent_getKeyCode(androidEvent); + status = 1; + } + } break; + case AINPUT_EVENT_TYPE_KEY: { + SEvent event; + event.EventType = EET_KEY_INPUT_EVENT; + + int32_t keyCode = AKeyEvent_getKeyCode(androidEvent); + // os::Printer::log("keyCode: ", core::stringc(keyCode).c_str(), ELL_DEBUG); + + int32_t keyAction = AKeyEvent_getAction(androidEvent); + int32_t keyMetaState = AKeyEvent_getMetaState(androidEvent); + + if (keyCode >= 0 && (u32)keyCode < device->KeyMap.size()) + event.KeyInput.Key = device->KeyMap[keyCode]; + else + event.KeyInput.Key = KEY_UNKNOWN; + event.KeyInput.SystemKeyCode = (u32)keyCode; + if (keyAction == AKEY_EVENT_ACTION_DOWN) + event.KeyInput.PressedDown = true; + else if (keyAction == AKEY_EVENT_ACTION_UP) + event.KeyInput.PressedDown = false; + else if (keyAction == AKEY_EVENT_ACTION_MULTIPLE) { + // TODO: Multiple duplicate key events have occurred in a row, + // or a complex string is being delivered. The repeat_count + // property of the key event contains the number of times the + // given key code should be executed. + // I guess this might necessary for more complicated i18n key input, + // but don't see yet how to handle this correctly. + } + + /* no use for meta keys so far. + if ( keyMetaState & AMETA_ALT_ON + || keyMetaState & AMETA_ALT_LEFT_ON + || keyMetaState & AMETA_ALT_RIGHT_ON ) + ; + // what is a sym? + if ( keyMetaState & AMETA_SYM_ON ) + ; + */ + if (keyMetaState & AMETA_SHIFT_ON || keyMetaState & AMETA_SHIFT_LEFT_ON || keyMetaState & AMETA_SHIFT_RIGHT_ON) + event.KeyInput.Shift = true; + else + event.KeyInput.Shift = false; + event.KeyInput.Control = false; + + // Having memory allocations + going through JNI for each key-press is pretty bad (slow). + // So we do it only for those keys which are likely text-characters and avoid it for all other keys. + // So it's fast for keys like game controller input and special keys. And text keys are typically + // only used or entering text and not for gaming on Android, so speed likely doesn't matter there too much. + if (event.KeyInput.Key > 0) { + // TODO: + // Not sure why we have to attach a JNIEnv here, but it won't work when doing that in the constructor or + // trying to use the activity->env. My best guess is that the event-handling happens in an own thread. + // It means JNIEnvAttachedToVM will never get detached as I don't know a safe way where to do that + // (we could attach & detach each time, but that would probably be slow) + // Also - it has to be each time as it get's invalid when the application mode changes. + if (device->Initialized && device->Android && device->Android->activity && device->Android->activity->vm) { + JavaVMAttachArgs attachArgs; + attachArgs.version = JNI_VERSION_1_6; + attachArgs.name = 0; + attachArgs.group = NULL; + + // Not a big problem calling it each time - it's a no-op when the thread already is attached. + // And we have to do that as someone else can have detached the thread in the meantime. + jint result = device->Android->activity->vm->AttachCurrentThread(&device->JNIEnvAttachedToVM, &attachArgs); + if (result == JNI_ERR) { + os::Printer::log("AttachCurrentThread for the JNI environment failed.", ELL_WARNING); + device->JNIEnvAttachedToVM = 0; + } + + if (device->JNIEnvAttachedToVM) { + jni::CKeyEventWrapper *keyEventWrapper = new jni::CKeyEventWrapper(device->JNIEnvAttachedToVM, keyAction, keyCode); + event.KeyInput.Char = keyEventWrapper->getUnicodeChar(keyMetaState); + delete keyEventWrapper; + } + } + if (event.KeyInput.Key == KEY_BACK) { + event.KeyInput.Char = 0x08; // same key-code as on other operating systems. Otherwise we have to handle too much system specific stuff in the editbox. + } + // os::Printer::log("char-code: ", core::stringc((int)event.KeyInput.Char).c_str(), ELL_DEBUG); + + } else { // os::Printer::log("keyCode: ", core::stringc(keyCode).c_str(), ELL_DEBUG); - - int32_t keyAction = AKeyEvent_getAction(androidEvent); - int32_t keyMetaState = AKeyEvent_getMetaState(androidEvent); - - if ( keyCode >= 0 && (u32)keyCode < device->KeyMap.size() ) - event.KeyInput.Key = device->KeyMap[keyCode]; - else - event.KeyInput.Key = KEY_UNKNOWN; - event.KeyInput.SystemKeyCode = (u32)keyCode; - if ( keyAction == AKEY_EVENT_ACTION_DOWN ) - event.KeyInput.PressedDown = true; - else if ( keyAction == AKEY_EVENT_ACTION_UP ) - event.KeyInput.PressedDown = false; - else if ( keyAction == AKEY_EVENT_ACTION_MULTIPLE ) - { - // TODO: Multiple duplicate key events have occurred in a row, - // or a complex string is being delivered. The repeat_count - // property of the key event contains the number of times the - // given key code should be executed. - // I guess this might necessary for more complicated i18n key input, - // but don't see yet how to handle this correctly. - } - - /* no use for meta keys so far. - if ( keyMetaState & AMETA_ALT_ON - || keyMetaState & AMETA_ALT_LEFT_ON - || keyMetaState & AMETA_ALT_RIGHT_ON ) - ; - // what is a sym? - if ( keyMetaState & AMETA_SYM_ON ) - ; - */ - if ( keyMetaState & AMETA_SHIFT_ON - || keyMetaState & AMETA_SHIFT_LEFT_ON - || keyMetaState & AMETA_SHIFT_RIGHT_ON ) - event.KeyInput.Shift = true; - else - event.KeyInput.Shift = false; - event.KeyInput.Control = false; - - // Having memory allocations + going through JNI for each key-press is pretty bad (slow). - // So we do it only for those keys which are likely text-characters and avoid it for all other keys. - // So it's fast for keys like game controller input and special keys. And text keys are typically - // only used or entering text and not for gaming on Android, so speed likely doesn't matter there too much. - if ( event.KeyInput.Key > 0 ) - { - // TODO: - // Not sure why we have to attach a JNIEnv here, but it won't work when doing that in the constructor or - // trying to use the activity->env. My best guess is that the event-handling happens in an own thread. - // It means JNIEnvAttachedToVM will never get detached as I don't know a safe way where to do that - // (we could attach & detach each time, but that would probably be slow) - // Also - it has to be each time as it get's invalid when the application mode changes. - if ( device->Initialized && device->Android && device->Android->activity && device->Android->activity->vm ) - { - JavaVMAttachArgs attachArgs; - attachArgs.version = JNI_VERSION_1_6; - attachArgs.name = 0; - attachArgs.group = NULL; - - // Not a big problem calling it each time - it's a no-op when the thread already is attached. - // And we have to do that as someone else can have detached the thread in the meantime. - jint result = device->Android->activity->vm->AttachCurrentThread(&device->JNIEnvAttachedToVM, &attachArgs); - if(result == JNI_ERR) - { - os::Printer::log("AttachCurrentThread for the JNI environment failed.", ELL_WARNING); - device->JNIEnvAttachedToVM = 0; - } - - if ( device->JNIEnvAttachedToVM ) - { - jni::CKeyEventWrapper * keyEventWrapper = new jni::CKeyEventWrapper(device->JNIEnvAttachedToVM, keyAction, keyCode); - event.KeyInput.Char = keyEventWrapper->getUnicodeChar(keyMetaState); - delete keyEventWrapper; - } - } - if ( event.KeyInput.Key == KEY_BACK ) - { - event.KeyInput.Char = 0x08; // same key-code as on other operating systems. Otherwise we have to handle too much system specific stuff in the editbox. - } - //os::Printer::log("char-code: ", core::stringc((int)event.KeyInput.Char).c_str(), ELL_DEBUG); - - } - else - { - // os::Printer::log("keyCode: ", core::stringc(keyCode).c_str(), ELL_DEBUG); - event.KeyInput.Char = 0; - } - - status = device->postEventFromUser(event); + event.KeyInput.Char = 0; } - break; - default: + + status = device->postEventFromUser(event); + } break; + default: break; } @@ -522,8 +487,7 @@ s32 CIrrDeviceAndroid::handleInput(android_app* app, AInputEvent* androidEvent) void CIrrDeviceAndroid::createDriver() { - switch(CreationParams.DriverType) - { + switch (CreationParams.DriverType) { case video::EDT_OGLES1: #ifdef _IRR_COMPILE_WITH_OGLES1_ VideoDriver = video::createOGLES1Driver(CreationParams, FileSystem, ContextManager); @@ -550,7 +514,7 @@ void CIrrDeviceAndroid::createDriver() } } -video::SExposedVideoData& CIrrDeviceAndroid::getExposedVideoData() +video::SExposedVideoData &CIrrDeviceAndroid::getExposedVideoData() { return ExposedVideoData; } @@ -559,232 +523,232 @@ void CIrrDeviceAndroid::createKeyMap() { KeyMap.set_used(223); - KeyMap[0] = KEY_UNKNOWN; // AKEYCODE_UNKNOWN - KeyMap[1] = KEY_LBUTTON; // AKEYCODE_SOFT_LEFT - KeyMap[2] = KEY_RBUTTON; // AKEYCODE_SOFT_RIGHT - KeyMap[3] = KEY_HOME; // AKEYCODE_HOME - KeyMap[4] = KEY_CANCEL; // AKEYCODE_BACK - KeyMap[5] = KEY_UNKNOWN; // AKEYCODE_CALL - KeyMap[6] = KEY_UNKNOWN; // AKEYCODE_ENDCALL - KeyMap[7] = KEY_KEY_0; // AKEYCODE_0 - KeyMap[8] = KEY_KEY_1; // AKEYCODE_1 - KeyMap[9] = KEY_KEY_2; // AKEYCODE_2 - KeyMap[10] = KEY_KEY_3; // AKEYCODE_3 - KeyMap[11] = KEY_KEY_4; // AKEYCODE_4 - KeyMap[12] = KEY_KEY_5; // AKEYCODE_5 - KeyMap[13] = KEY_KEY_6; // AKEYCODE_6 - KeyMap[14] = KEY_KEY_7; // AKEYCODE_7 - KeyMap[15] = KEY_KEY_8; // AKEYCODE_8 - KeyMap[16] = KEY_KEY_9; // AKEYCODE_9 - KeyMap[17] = KEY_UNKNOWN; // AKEYCODE_STAR - KeyMap[18] = KEY_UNKNOWN; // AKEYCODE_POUND - KeyMap[19] = KEY_UP; // AKEYCODE_DPAD_UP - KeyMap[20] = KEY_DOWN; // AKEYCODE_DPAD_DOWN - KeyMap[21] = KEY_LEFT; // AKEYCODE_DPAD_LEFT - KeyMap[22] = KEY_RIGHT; // AKEYCODE_DPAD_RIGHT - KeyMap[23] = KEY_SELECT; // AKEYCODE_DPAD_CENTER - KeyMap[24] = KEY_VOLUME_DOWN; // AKEYCODE_VOLUME_UP - KeyMap[25] = KEY_VOLUME_UP; // AKEYCODE_VOLUME_DOWN - KeyMap[26] = KEY_UNKNOWN; // AKEYCODE_POWER - KeyMap[27] = KEY_UNKNOWN; // AKEYCODE_CAMERA - KeyMap[28] = KEY_CLEAR; // AKEYCODE_CLEAR - KeyMap[29] = KEY_KEY_A; // AKEYCODE_A - KeyMap[30] = KEY_KEY_B; // AKEYCODE_B - KeyMap[31] = KEY_KEY_C; // AKEYCODE_C - KeyMap[32] = KEY_KEY_D; // AKEYCODE_D - KeyMap[33] = KEY_KEY_E; // AKEYCODE_E - KeyMap[34] = KEY_KEY_F; // AKEYCODE_F - KeyMap[35] = KEY_KEY_G; // AKEYCODE_G - KeyMap[36] = KEY_KEY_H; // AKEYCODE_H - KeyMap[37] = KEY_KEY_I; // AKEYCODE_I - KeyMap[38] = KEY_KEY_J; // AKEYCODE_J - KeyMap[39] = KEY_KEY_K; // AKEYCODE_K - KeyMap[40] = KEY_KEY_L; // AKEYCODE_L - KeyMap[41] = KEY_KEY_M; // AKEYCODE_M - KeyMap[42] = KEY_KEY_N; // AKEYCODE_N - KeyMap[43] = KEY_KEY_O; // AKEYCODE_O - KeyMap[44] = KEY_KEY_P; // AKEYCODE_P - KeyMap[45] = KEY_KEY_Q; // AKEYCODE_Q - KeyMap[46] = KEY_KEY_R; // AKEYCODE_R - KeyMap[47] = KEY_KEY_S; // AKEYCODE_S - KeyMap[48] = KEY_KEY_T; // AKEYCODE_T - KeyMap[49] = KEY_KEY_U; // AKEYCODE_U - KeyMap[50] = KEY_KEY_V; // AKEYCODE_V - KeyMap[51] = KEY_KEY_W; // AKEYCODE_W - KeyMap[52] = KEY_KEY_X; // AKEYCODE_X - KeyMap[53] = KEY_KEY_Y; // AKEYCODE_Y - KeyMap[54] = KEY_KEY_Z; // AKEYCODE_Z - KeyMap[55] = KEY_COMMA; // AKEYCODE_COMMA - KeyMap[56] = KEY_PERIOD; // AKEYCODE_PERIOD - KeyMap[57] = KEY_MENU; // AKEYCODE_ALT_LEFT - KeyMap[58] = KEY_MENU; // AKEYCODE_ALT_RIGHT - KeyMap[59] = KEY_LSHIFT; // AKEYCODE_SHIFT_LEFT - KeyMap[60] = KEY_RSHIFT; // AKEYCODE_SHIFT_RIGHT - KeyMap[61] = KEY_TAB; // AKEYCODE_TAB - KeyMap[62] = KEY_SPACE; // AKEYCODE_SPACE - KeyMap[63] = KEY_UNKNOWN; // AKEYCODE_SYM - KeyMap[64] = KEY_UNKNOWN; // AKEYCODE_EXPLORER - KeyMap[65] = KEY_UNKNOWN; // AKEYCODE_ENVELOPE - KeyMap[66] = KEY_RETURN; // AKEYCODE_ENTER - KeyMap[67] = KEY_BACK; // AKEYCODE_DEL - KeyMap[68] = KEY_OEM_3; // AKEYCODE_GRAVE - KeyMap[69] = KEY_MINUS; // AKEYCODE_MINUS - KeyMap[70] = KEY_UNKNOWN; // AKEYCODE_EQUALS - KeyMap[71] = KEY_UNKNOWN; // AKEYCODE_LEFT_BRACKET - KeyMap[72] = KEY_UNKNOWN; // AKEYCODE_RIGHT_BRACKET - KeyMap[73] = KEY_UNKNOWN; // AKEYCODE_BACKSLASH - KeyMap[74] = KEY_UNKNOWN; // AKEYCODE_SEMICOLON - KeyMap[75] = KEY_UNKNOWN; // AKEYCODE_APOSTROPHE - KeyMap[76] = KEY_UNKNOWN; // AKEYCODE_SLASH - KeyMap[77] = KEY_UNKNOWN; // AKEYCODE_AT - KeyMap[78] = KEY_UNKNOWN; // AKEYCODE_NUM - KeyMap[79] = KEY_UNKNOWN; // AKEYCODE_HEADSETHOOK - KeyMap[80] = KEY_UNKNOWN; // AKEYCODE_FOCUS (*Camera* focus) - KeyMap[81] = KEY_PLUS; // AKEYCODE_PLUS - KeyMap[82] = KEY_MENU; // AKEYCODE_MENU - KeyMap[83] = KEY_UNKNOWN; // AKEYCODE_NOTIFICATION - KeyMap[84] = KEY_UNKNOWN; // AKEYCODE_SEARCH - KeyMap[85] = KEY_MEDIA_PLAY_PAUSE; // AKEYCODE_MEDIA_PLAY_PAUSE - KeyMap[86] = KEY_MEDIA_STOP; // AKEYCODE_MEDIA_STOP - KeyMap[87] = KEY_MEDIA_NEXT_TRACK; // AKEYCODE_MEDIA_NEXT - KeyMap[88] = KEY_MEDIA_PREV_TRACK; // AKEYCODE_MEDIA_PREVIOUS - KeyMap[89] = KEY_UNKNOWN; // AKEYCODE_MEDIA_REWIND - KeyMap[90] = KEY_UNKNOWN; // AKEYCODE_MEDIA_FAST_FORWARD - KeyMap[91] = KEY_VOLUME_MUTE; // AKEYCODE_MUTE - KeyMap[92] = KEY_PRIOR; // AKEYCODE_PAGE_UP - KeyMap[93] = KEY_NEXT; // AKEYCODE_PAGE_DOWN - KeyMap[94] = KEY_UNKNOWN; // AKEYCODE_PICTSYMBOLS - KeyMap[95] = KEY_UNKNOWN; // AKEYCODE_SWITCH_CHARSET + KeyMap[0] = KEY_UNKNOWN; // AKEYCODE_UNKNOWN + KeyMap[1] = KEY_LBUTTON; // AKEYCODE_SOFT_LEFT + KeyMap[2] = KEY_RBUTTON; // AKEYCODE_SOFT_RIGHT + KeyMap[3] = KEY_HOME; // AKEYCODE_HOME + KeyMap[4] = KEY_CANCEL; // AKEYCODE_BACK + KeyMap[5] = KEY_UNKNOWN; // AKEYCODE_CALL + KeyMap[6] = KEY_UNKNOWN; // AKEYCODE_ENDCALL + KeyMap[7] = KEY_KEY_0; // AKEYCODE_0 + KeyMap[8] = KEY_KEY_1; // AKEYCODE_1 + KeyMap[9] = KEY_KEY_2; // AKEYCODE_2 + KeyMap[10] = KEY_KEY_3; // AKEYCODE_3 + KeyMap[11] = KEY_KEY_4; // AKEYCODE_4 + KeyMap[12] = KEY_KEY_5; // AKEYCODE_5 + KeyMap[13] = KEY_KEY_6; // AKEYCODE_6 + KeyMap[14] = KEY_KEY_7; // AKEYCODE_7 + KeyMap[15] = KEY_KEY_8; // AKEYCODE_8 + KeyMap[16] = KEY_KEY_9; // AKEYCODE_9 + KeyMap[17] = KEY_UNKNOWN; // AKEYCODE_STAR + KeyMap[18] = KEY_UNKNOWN; // AKEYCODE_POUND + KeyMap[19] = KEY_UP; // AKEYCODE_DPAD_UP + KeyMap[20] = KEY_DOWN; // AKEYCODE_DPAD_DOWN + KeyMap[21] = KEY_LEFT; // AKEYCODE_DPAD_LEFT + KeyMap[22] = KEY_RIGHT; // AKEYCODE_DPAD_RIGHT + KeyMap[23] = KEY_SELECT; // AKEYCODE_DPAD_CENTER + KeyMap[24] = KEY_VOLUME_DOWN; // AKEYCODE_VOLUME_UP + KeyMap[25] = KEY_VOLUME_UP; // AKEYCODE_VOLUME_DOWN + KeyMap[26] = KEY_UNKNOWN; // AKEYCODE_POWER + KeyMap[27] = KEY_UNKNOWN; // AKEYCODE_CAMERA + KeyMap[28] = KEY_CLEAR; // AKEYCODE_CLEAR + KeyMap[29] = KEY_KEY_A; // AKEYCODE_A + KeyMap[30] = KEY_KEY_B; // AKEYCODE_B + KeyMap[31] = KEY_KEY_C; // AKEYCODE_C + KeyMap[32] = KEY_KEY_D; // AKEYCODE_D + KeyMap[33] = KEY_KEY_E; // AKEYCODE_E + KeyMap[34] = KEY_KEY_F; // AKEYCODE_F + KeyMap[35] = KEY_KEY_G; // AKEYCODE_G + KeyMap[36] = KEY_KEY_H; // AKEYCODE_H + KeyMap[37] = KEY_KEY_I; // AKEYCODE_I + KeyMap[38] = KEY_KEY_J; // AKEYCODE_J + KeyMap[39] = KEY_KEY_K; // AKEYCODE_K + KeyMap[40] = KEY_KEY_L; // AKEYCODE_L + KeyMap[41] = KEY_KEY_M; // AKEYCODE_M + KeyMap[42] = KEY_KEY_N; // AKEYCODE_N + KeyMap[43] = KEY_KEY_O; // AKEYCODE_O + KeyMap[44] = KEY_KEY_P; // AKEYCODE_P + KeyMap[45] = KEY_KEY_Q; // AKEYCODE_Q + KeyMap[46] = KEY_KEY_R; // AKEYCODE_R + KeyMap[47] = KEY_KEY_S; // AKEYCODE_S + KeyMap[48] = KEY_KEY_T; // AKEYCODE_T + KeyMap[49] = KEY_KEY_U; // AKEYCODE_U + KeyMap[50] = KEY_KEY_V; // AKEYCODE_V + KeyMap[51] = KEY_KEY_W; // AKEYCODE_W + KeyMap[52] = KEY_KEY_X; // AKEYCODE_X + KeyMap[53] = KEY_KEY_Y; // AKEYCODE_Y + KeyMap[54] = KEY_KEY_Z; // AKEYCODE_Z + KeyMap[55] = KEY_COMMA; // AKEYCODE_COMMA + KeyMap[56] = KEY_PERIOD; // AKEYCODE_PERIOD + KeyMap[57] = KEY_MENU; // AKEYCODE_ALT_LEFT + KeyMap[58] = KEY_MENU; // AKEYCODE_ALT_RIGHT + KeyMap[59] = KEY_LSHIFT; // AKEYCODE_SHIFT_LEFT + KeyMap[60] = KEY_RSHIFT; // AKEYCODE_SHIFT_RIGHT + KeyMap[61] = KEY_TAB; // AKEYCODE_TAB + KeyMap[62] = KEY_SPACE; // AKEYCODE_SPACE + KeyMap[63] = KEY_UNKNOWN; // AKEYCODE_SYM + KeyMap[64] = KEY_UNKNOWN; // AKEYCODE_EXPLORER + KeyMap[65] = KEY_UNKNOWN; // AKEYCODE_ENVELOPE + KeyMap[66] = KEY_RETURN; // AKEYCODE_ENTER + KeyMap[67] = KEY_BACK; // AKEYCODE_DEL + KeyMap[68] = KEY_OEM_3; // AKEYCODE_GRAVE + KeyMap[69] = KEY_MINUS; // AKEYCODE_MINUS + KeyMap[70] = KEY_UNKNOWN; // AKEYCODE_EQUALS + KeyMap[71] = KEY_UNKNOWN; // AKEYCODE_LEFT_BRACKET + KeyMap[72] = KEY_UNKNOWN; // AKEYCODE_RIGHT_BRACKET + KeyMap[73] = KEY_UNKNOWN; // AKEYCODE_BACKSLASH + KeyMap[74] = KEY_UNKNOWN; // AKEYCODE_SEMICOLON + KeyMap[75] = KEY_UNKNOWN; // AKEYCODE_APOSTROPHE + KeyMap[76] = KEY_UNKNOWN; // AKEYCODE_SLASH + KeyMap[77] = KEY_UNKNOWN; // AKEYCODE_AT + KeyMap[78] = KEY_UNKNOWN; // AKEYCODE_NUM + KeyMap[79] = KEY_UNKNOWN; // AKEYCODE_HEADSETHOOK + KeyMap[80] = KEY_UNKNOWN; // AKEYCODE_FOCUS (*Camera* focus) + KeyMap[81] = KEY_PLUS; // AKEYCODE_PLUS + KeyMap[82] = KEY_MENU; // AKEYCODE_MENU + KeyMap[83] = KEY_UNKNOWN; // AKEYCODE_NOTIFICATION + KeyMap[84] = KEY_UNKNOWN; // AKEYCODE_SEARCH + KeyMap[85] = KEY_MEDIA_PLAY_PAUSE; // AKEYCODE_MEDIA_PLAY_PAUSE + KeyMap[86] = KEY_MEDIA_STOP; // AKEYCODE_MEDIA_STOP + KeyMap[87] = KEY_MEDIA_NEXT_TRACK; // AKEYCODE_MEDIA_NEXT + KeyMap[88] = KEY_MEDIA_PREV_TRACK; // AKEYCODE_MEDIA_PREVIOUS + KeyMap[89] = KEY_UNKNOWN; // AKEYCODE_MEDIA_REWIND + KeyMap[90] = KEY_UNKNOWN; // AKEYCODE_MEDIA_FAST_FORWARD + KeyMap[91] = KEY_VOLUME_MUTE; // AKEYCODE_MUTE + KeyMap[92] = KEY_PRIOR; // AKEYCODE_PAGE_UP + KeyMap[93] = KEY_NEXT; // AKEYCODE_PAGE_DOWN + KeyMap[94] = KEY_UNKNOWN; // AKEYCODE_PICTSYMBOLS + KeyMap[95] = KEY_UNKNOWN; // AKEYCODE_SWITCH_CHARSET - // following look like controller inputs - KeyMap[96] = KEY_UNKNOWN; // AKEYCODE_BUTTON_A - KeyMap[97] = KEY_UNKNOWN; // AKEYCODE_BUTTON_B - KeyMap[98] = KEY_UNKNOWN; // AKEYCODE_BUTTON_C - KeyMap[99] = KEY_UNKNOWN; // AKEYCODE_BUTTON_X - KeyMap[100] = KEY_UNKNOWN; // AKEYCODE_BUTTON_Y - KeyMap[101] = KEY_UNKNOWN; // AKEYCODE_BUTTON_Z - KeyMap[102] = KEY_UNKNOWN; // AKEYCODE_BUTTON_L1 - KeyMap[103] = KEY_UNKNOWN; // AKEYCODE_BUTTON_R1 - KeyMap[104] = KEY_UNKNOWN; // AKEYCODE_BUTTON_L2 - KeyMap[105] = KEY_UNKNOWN; // AKEYCODE_BUTTON_R2 - KeyMap[106] = KEY_UNKNOWN; // AKEYCODE_BUTTON_THUMBL - KeyMap[107] = KEY_UNKNOWN; // AKEYCODE_BUTTON_THUMBR - KeyMap[108] = KEY_UNKNOWN; // AKEYCODE_BUTTON_START - KeyMap[109] = KEY_UNKNOWN; // AKEYCODE_BUTTON_SELECT - KeyMap[110] = KEY_UNKNOWN; // AKEYCODE_BUTTON_MODE + // following look like controller inputs + KeyMap[96] = KEY_UNKNOWN; // AKEYCODE_BUTTON_A + KeyMap[97] = KEY_UNKNOWN; // AKEYCODE_BUTTON_B + KeyMap[98] = KEY_UNKNOWN; // AKEYCODE_BUTTON_C + KeyMap[99] = KEY_UNKNOWN; // AKEYCODE_BUTTON_X + KeyMap[100] = KEY_UNKNOWN; // AKEYCODE_BUTTON_Y + KeyMap[101] = KEY_UNKNOWN; // AKEYCODE_BUTTON_Z + KeyMap[102] = KEY_UNKNOWN; // AKEYCODE_BUTTON_L1 + KeyMap[103] = KEY_UNKNOWN; // AKEYCODE_BUTTON_R1 + KeyMap[104] = KEY_UNKNOWN; // AKEYCODE_BUTTON_L2 + KeyMap[105] = KEY_UNKNOWN; // AKEYCODE_BUTTON_R2 + KeyMap[106] = KEY_UNKNOWN; // AKEYCODE_BUTTON_THUMBL + KeyMap[107] = KEY_UNKNOWN; // AKEYCODE_BUTTON_THUMBR + KeyMap[108] = KEY_UNKNOWN; // AKEYCODE_BUTTON_START + KeyMap[109] = KEY_UNKNOWN; // AKEYCODE_BUTTON_SELECT + KeyMap[110] = KEY_UNKNOWN; // AKEYCODE_BUTTON_MODE - KeyMap[111] = KEY_ESCAPE; // AKEYCODE_ESCAPE - KeyMap[112] = KEY_DELETE; // AKEYCODE_FORWARD_DEL - KeyMap[113] = KEY_CONTROL; // AKEYCODE_CTRL_LEFT - KeyMap[114] = KEY_CONTROL; // AKEYCODE_CTRL_RIGHT - KeyMap[115] = KEY_CAPITAL; // AKEYCODE_CAPS_LOCK - KeyMap[116] = KEY_SCROLL; // AKEYCODE_SCROLL_LOCK - KeyMap[117] = KEY_UNKNOWN; // AKEYCODE_META_LEFT - KeyMap[118] = KEY_UNKNOWN; // AKEYCODE_META_RIGHT - KeyMap[119] = KEY_UNKNOWN; // AKEYCODE_FUNCTION - KeyMap[120] = KEY_SNAPSHOT; // AKEYCODE_SYSRQ - KeyMap[121] = KEY_PAUSE; // AKEYCODE_BREAK - KeyMap[122] = KEY_HOME; // AKEYCODE_MOVE_HOME - KeyMap[123] = KEY_END; // AKEYCODE_MOVE_END - KeyMap[124] = KEY_INSERT; // AKEYCODE_INSERT - KeyMap[125] = KEY_UNKNOWN; // AKEYCODE_FORWARD - KeyMap[126] = KEY_PLAY; // AKEYCODE_MEDIA_PLAY - KeyMap[127] = KEY_MEDIA_PLAY_PAUSE; // AKEYCODE_MEDIA_PAUSE - KeyMap[128] = KEY_UNKNOWN; // AKEYCODE_MEDIA_CLOSE - KeyMap[129] = KEY_UNKNOWN; // AKEYCODE_MEDIA_EJECT - KeyMap[130] = KEY_UNKNOWN; // AKEYCODE_MEDIA_RECORD - KeyMap[131] = KEY_F1; // AKEYCODE_F1 - KeyMap[132] = KEY_F2; // AKEYCODE_F2 - KeyMap[133] = KEY_F3; // AKEYCODE_F3 - KeyMap[134] = KEY_F4; // AKEYCODE_F4 - KeyMap[135] = KEY_F5; // AKEYCODE_F5 - KeyMap[136] = KEY_F6; // AKEYCODE_F6 - KeyMap[137] = KEY_F7; // AKEYCODE_F7 - KeyMap[138] = KEY_F8; // AKEYCODE_F8 - KeyMap[139] = KEY_F9; // AKEYCODE_F9 - KeyMap[140] = KEY_F10; // AKEYCODE_F10 - KeyMap[141] = KEY_F11; // AKEYCODE_F11 - KeyMap[142] = KEY_F12; // AKEYCODE_F12 - KeyMap[143] = KEY_NUMLOCK; // AKEYCODE_NUM_LOCK - KeyMap[144] = KEY_NUMPAD0; // AKEYCODE_NUMPAD_0 - KeyMap[145] = KEY_NUMPAD1; // AKEYCODE_NUMPAD_1 - KeyMap[146] = KEY_NUMPAD2; // AKEYCODE_NUMPAD_2 - KeyMap[147] = KEY_NUMPAD3; // AKEYCODE_NUMPAD_3 - KeyMap[148] = KEY_NUMPAD4; // AKEYCODE_NUMPAD_4 - KeyMap[149] = KEY_NUMPAD5; // AKEYCODE_NUMPAD_5 - KeyMap[150] = KEY_NUMPAD6; // AKEYCODE_NUMPAD_6 - KeyMap[151] = KEY_NUMPAD7; // AKEYCODE_NUMPAD_7 - KeyMap[152] = KEY_NUMPAD8; // AKEYCODE_NUMPAD_8 - KeyMap[153] = KEY_NUMPAD9; // AKEYCODE_NUMPAD_9 - KeyMap[154] = KEY_DIVIDE; // AKEYCODE_NUMPAD_DIVIDE - KeyMap[155] = KEY_MULTIPLY; // AKEYCODE_NUMPAD_MULTIPLY - KeyMap[156] = KEY_SUBTRACT; // AKEYCODE_NUMPAD_SUBTRACT - KeyMap[157] = KEY_ADD; // AKEYCODE_NUMPAD_ADD - KeyMap[158] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_DOT - KeyMap[159] = KEY_COMMA; // AKEYCODE_NUMPAD_COMMA - KeyMap[160] = KEY_RETURN; // AKEYCODE_NUMPAD_ENTER - KeyMap[161] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_EQUALS - KeyMap[162] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_LEFT_PAREN - KeyMap[163] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_RIGHT_PAREN - KeyMap[164] = KEY_VOLUME_MUTE; // AKEYCODE_VOLUME_MUTE - KeyMap[165] = KEY_UNKNOWN; // AKEYCODE_INFO - KeyMap[166] = KEY_UNKNOWN; // AKEYCODE_CHANNEL_UP - KeyMap[167] = KEY_UNKNOWN; // AKEYCODE_CHANNEL_DOWN - KeyMap[168] = KEY_ZOOM; // AKEYCODE_ZOOM_IN - KeyMap[169] = KEY_UNKNOWN; // AKEYCODE_ZOOM_OUT - KeyMap[170] = KEY_UNKNOWN; // AKEYCODE_TV - KeyMap[171] = KEY_UNKNOWN; // AKEYCODE_WINDOW - KeyMap[172] = KEY_UNKNOWN; // AKEYCODE_GUIDE - KeyMap[173] = KEY_UNKNOWN; // AKEYCODE_DVR - KeyMap[174] = KEY_UNKNOWN; // AKEYCODE_BOOKMARK - KeyMap[175] = KEY_UNKNOWN; // AKEYCODE_CAPTIONS - KeyMap[176] = KEY_UNKNOWN; // AKEYCODE_SETTINGS - KeyMap[177] = KEY_UNKNOWN; // AKEYCODE_TV_POWER - KeyMap[178] = KEY_UNKNOWN; // AKEYCODE_TV_INPUT - KeyMap[179] = KEY_UNKNOWN; // AKEYCODE_STB_POWER - KeyMap[180] = KEY_UNKNOWN; // AKEYCODE_STB_INPUT - KeyMap[181] = KEY_UNKNOWN; // AKEYCODE_AVR_POWER - KeyMap[182] = KEY_UNKNOWN; // AKEYCODE_AVR_INPUT - KeyMap[183] = KEY_UNKNOWN; // AKEYCODE_PROG_RED - KeyMap[184] = KEY_UNKNOWN; // AKEYCODE_PROG_GREEN - KeyMap[185] = KEY_UNKNOWN; // AKEYCODE_PROG_YELLOW - KeyMap[186] = KEY_UNKNOWN; // AKEYCODE_PROG_BLUE - KeyMap[187] = KEY_UNKNOWN; // AKEYCODE_APP_SWITCH - KeyMap[188] = KEY_UNKNOWN; // AKEYCODE_BUTTON_1 - KeyMap[189] = KEY_UNKNOWN; // AKEYCODE_BUTTON_2 - KeyMap[190] = KEY_UNKNOWN; // AKEYCODE_BUTTON_3 - KeyMap[191] = KEY_UNKNOWN; // AKEYCODE_BUTTON_4 - KeyMap[192] = KEY_UNKNOWN; // AKEYCODE_BUTTON_5 - KeyMap[193] = KEY_UNKNOWN; // AKEYCODE_BUTTON_6 - KeyMap[194] = KEY_UNKNOWN; // AKEYCODE_BUTTON_7 - KeyMap[195] = KEY_UNKNOWN; // AKEYCODE_BUTTON_8 - KeyMap[196] = KEY_UNKNOWN; // AKEYCODE_BUTTON_9 - KeyMap[197] = KEY_UNKNOWN; // AKEYCODE_BUTTON_10 - KeyMap[198] = KEY_UNKNOWN; // AKEYCODE_BUTTON_11 - KeyMap[199] = KEY_UNKNOWN; // AKEYCODE_BUTTON_12 - KeyMap[200] = KEY_UNKNOWN; // AKEYCODE_BUTTON_13 - KeyMap[201] = KEY_UNKNOWN; // AKEYCODE_BUTTON_14 - KeyMap[202] = KEY_UNKNOWN; // AKEYCODE_BUTTON_15 - KeyMap[203] = KEY_UNKNOWN; // AKEYCODE_BUTTON_16 - KeyMap[204] = KEY_UNKNOWN; // AKEYCODE_LANGUAGE_SWITCH - KeyMap[205] = KEY_UNKNOWN; // AKEYCODE_MANNER_MODE - KeyMap[206] = KEY_UNKNOWN; // AKEYCODE_3D_MODE - KeyMap[207] = KEY_UNKNOWN; // AKEYCODE_CONTACTS - KeyMap[208] = KEY_UNKNOWN; // AKEYCODE_CALENDAR - KeyMap[209] = KEY_UNKNOWN; // AKEYCODE_MUSIC - KeyMap[210] = KEY_UNKNOWN; // AKEYCODE_CALCULATOR - KeyMap[211] = KEY_UNKNOWN; // AKEYCODE_ZENKAKU_HANKAKU - KeyMap[212] = KEY_UNKNOWN; // AKEYCODE_EISU - KeyMap[213] = KEY_UNKNOWN; // AKEYCODE_MUHENKAN - KeyMap[214] = KEY_UNKNOWN; // AKEYCODE_HENKAN - KeyMap[215] = KEY_UNKNOWN; // AKEYCODE_KATAKANA_HIRAGANA - KeyMap[216] = KEY_UNKNOWN; // AKEYCODE_YEN - KeyMap[217] = KEY_UNKNOWN; // AKEYCODE_RO - KeyMap[218] = KEY_UNKNOWN; // AKEYCODE_KANA - KeyMap[219] = KEY_UNKNOWN; // AKEYCODE_ASSIST - KeyMap[220] = KEY_UNKNOWN; // AKEYCODE_BRIGHTNESS_DOWN - KeyMap[221] = KEY_UNKNOWN; // AKEYCODE_BRIGHTNESS_UP , - KeyMap[222] = KEY_UNKNOWN; // AKEYCODE_MEDIA_AUDIO_TRACK + KeyMap[111] = KEY_ESCAPE; // AKEYCODE_ESCAPE + KeyMap[112] = KEY_DELETE; // AKEYCODE_FORWARD_DEL + KeyMap[113] = KEY_CONTROL; // AKEYCODE_CTRL_LEFT + KeyMap[114] = KEY_CONTROL; // AKEYCODE_CTRL_RIGHT + KeyMap[115] = KEY_CAPITAL; // AKEYCODE_CAPS_LOCK + KeyMap[116] = KEY_SCROLL; // AKEYCODE_SCROLL_LOCK + KeyMap[117] = KEY_UNKNOWN; // AKEYCODE_META_LEFT + KeyMap[118] = KEY_UNKNOWN; // AKEYCODE_META_RIGHT + KeyMap[119] = KEY_UNKNOWN; // AKEYCODE_FUNCTION + KeyMap[120] = KEY_SNAPSHOT; // AKEYCODE_SYSRQ + KeyMap[121] = KEY_PAUSE; // AKEYCODE_BREAK + KeyMap[122] = KEY_HOME; // AKEYCODE_MOVE_HOME + KeyMap[123] = KEY_END; // AKEYCODE_MOVE_END + KeyMap[124] = KEY_INSERT; // AKEYCODE_INSERT + KeyMap[125] = KEY_UNKNOWN; // AKEYCODE_FORWARD + KeyMap[126] = KEY_PLAY; // AKEYCODE_MEDIA_PLAY + KeyMap[127] = KEY_MEDIA_PLAY_PAUSE; // AKEYCODE_MEDIA_PAUSE + KeyMap[128] = KEY_UNKNOWN; // AKEYCODE_MEDIA_CLOSE + KeyMap[129] = KEY_UNKNOWN; // AKEYCODE_MEDIA_EJECT + KeyMap[130] = KEY_UNKNOWN; // AKEYCODE_MEDIA_RECORD + KeyMap[131] = KEY_F1; // AKEYCODE_F1 + KeyMap[132] = KEY_F2; // AKEYCODE_F2 + KeyMap[133] = KEY_F3; // AKEYCODE_F3 + KeyMap[134] = KEY_F4; // AKEYCODE_F4 + KeyMap[135] = KEY_F5; // AKEYCODE_F5 + KeyMap[136] = KEY_F6; // AKEYCODE_F6 + KeyMap[137] = KEY_F7; // AKEYCODE_F7 + KeyMap[138] = KEY_F8; // AKEYCODE_F8 + KeyMap[139] = KEY_F9; // AKEYCODE_F9 + KeyMap[140] = KEY_F10; // AKEYCODE_F10 + KeyMap[141] = KEY_F11; // AKEYCODE_F11 + KeyMap[142] = KEY_F12; // AKEYCODE_F12 + KeyMap[143] = KEY_NUMLOCK; // AKEYCODE_NUM_LOCK + KeyMap[144] = KEY_NUMPAD0; // AKEYCODE_NUMPAD_0 + KeyMap[145] = KEY_NUMPAD1; // AKEYCODE_NUMPAD_1 + KeyMap[146] = KEY_NUMPAD2; // AKEYCODE_NUMPAD_2 + KeyMap[147] = KEY_NUMPAD3; // AKEYCODE_NUMPAD_3 + KeyMap[148] = KEY_NUMPAD4; // AKEYCODE_NUMPAD_4 + KeyMap[149] = KEY_NUMPAD5; // AKEYCODE_NUMPAD_5 + KeyMap[150] = KEY_NUMPAD6; // AKEYCODE_NUMPAD_6 + KeyMap[151] = KEY_NUMPAD7; // AKEYCODE_NUMPAD_7 + KeyMap[152] = KEY_NUMPAD8; // AKEYCODE_NUMPAD_8 + KeyMap[153] = KEY_NUMPAD9; // AKEYCODE_NUMPAD_9 + KeyMap[154] = KEY_DIVIDE; // AKEYCODE_NUMPAD_DIVIDE + KeyMap[155] = KEY_MULTIPLY; // AKEYCODE_NUMPAD_MULTIPLY + KeyMap[156] = KEY_SUBTRACT; // AKEYCODE_NUMPAD_SUBTRACT + KeyMap[157] = KEY_ADD; // AKEYCODE_NUMPAD_ADD + KeyMap[158] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_DOT + KeyMap[159] = KEY_COMMA; // AKEYCODE_NUMPAD_COMMA + KeyMap[160] = KEY_RETURN; // AKEYCODE_NUMPAD_ENTER + KeyMap[161] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_EQUALS + KeyMap[162] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_LEFT_PAREN + KeyMap[163] = KEY_UNKNOWN; // AKEYCODE_NUMPAD_RIGHT_PAREN + KeyMap[164] = KEY_VOLUME_MUTE; // AKEYCODE_VOLUME_MUTE + KeyMap[165] = KEY_UNKNOWN; // AKEYCODE_INFO + KeyMap[166] = KEY_UNKNOWN; // AKEYCODE_CHANNEL_UP + KeyMap[167] = KEY_UNKNOWN; // AKEYCODE_CHANNEL_DOWN + KeyMap[168] = KEY_ZOOM; // AKEYCODE_ZOOM_IN + KeyMap[169] = KEY_UNKNOWN; // AKEYCODE_ZOOM_OUT + KeyMap[170] = KEY_UNKNOWN; // AKEYCODE_TV + KeyMap[171] = KEY_UNKNOWN; // AKEYCODE_WINDOW + KeyMap[172] = KEY_UNKNOWN; // AKEYCODE_GUIDE + KeyMap[173] = KEY_UNKNOWN; // AKEYCODE_DVR + KeyMap[174] = KEY_UNKNOWN; // AKEYCODE_BOOKMARK + KeyMap[175] = KEY_UNKNOWN; // AKEYCODE_CAPTIONS + KeyMap[176] = KEY_UNKNOWN; // AKEYCODE_SETTINGS + KeyMap[177] = KEY_UNKNOWN; // AKEYCODE_TV_POWER + KeyMap[178] = KEY_UNKNOWN; // AKEYCODE_TV_INPUT + KeyMap[179] = KEY_UNKNOWN; // AKEYCODE_STB_POWER + KeyMap[180] = KEY_UNKNOWN; // AKEYCODE_STB_INPUT + KeyMap[181] = KEY_UNKNOWN; // AKEYCODE_AVR_POWER + KeyMap[182] = KEY_UNKNOWN; // AKEYCODE_AVR_INPUT + KeyMap[183] = KEY_UNKNOWN; // AKEYCODE_PROG_RED + KeyMap[184] = KEY_UNKNOWN; // AKEYCODE_PROG_GREEN + KeyMap[185] = KEY_UNKNOWN; // AKEYCODE_PROG_YELLOW + KeyMap[186] = KEY_UNKNOWN; // AKEYCODE_PROG_BLUE + KeyMap[187] = KEY_UNKNOWN; // AKEYCODE_APP_SWITCH + KeyMap[188] = KEY_UNKNOWN; // AKEYCODE_BUTTON_1 + KeyMap[189] = KEY_UNKNOWN; // AKEYCODE_BUTTON_2 + KeyMap[190] = KEY_UNKNOWN; // AKEYCODE_BUTTON_3 + KeyMap[191] = KEY_UNKNOWN; // AKEYCODE_BUTTON_4 + KeyMap[192] = KEY_UNKNOWN; // AKEYCODE_BUTTON_5 + KeyMap[193] = KEY_UNKNOWN; // AKEYCODE_BUTTON_6 + KeyMap[194] = KEY_UNKNOWN; // AKEYCODE_BUTTON_7 + KeyMap[195] = KEY_UNKNOWN; // AKEYCODE_BUTTON_8 + KeyMap[196] = KEY_UNKNOWN; // AKEYCODE_BUTTON_9 + KeyMap[197] = KEY_UNKNOWN; // AKEYCODE_BUTTON_10 + KeyMap[198] = KEY_UNKNOWN; // AKEYCODE_BUTTON_11 + KeyMap[199] = KEY_UNKNOWN; // AKEYCODE_BUTTON_12 + KeyMap[200] = KEY_UNKNOWN; // AKEYCODE_BUTTON_13 + KeyMap[201] = KEY_UNKNOWN; // AKEYCODE_BUTTON_14 + KeyMap[202] = KEY_UNKNOWN; // AKEYCODE_BUTTON_15 + KeyMap[203] = KEY_UNKNOWN; // AKEYCODE_BUTTON_16 + KeyMap[204] = KEY_UNKNOWN; // AKEYCODE_LANGUAGE_SWITCH + KeyMap[205] = KEY_UNKNOWN; // AKEYCODE_MANNER_MODE + KeyMap[206] = KEY_UNKNOWN; // AKEYCODE_3D_MODE + KeyMap[207] = KEY_UNKNOWN; // AKEYCODE_CONTACTS + KeyMap[208] = KEY_UNKNOWN; // AKEYCODE_CALENDAR + KeyMap[209] = KEY_UNKNOWN; // AKEYCODE_MUSIC + KeyMap[210] = KEY_UNKNOWN; // AKEYCODE_CALCULATOR + KeyMap[211] = KEY_UNKNOWN; // AKEYCODE_ZENKAKU_HANKAKU + KeyMap[212] = KEY_UNKNOWN; // AKEYCODE_EISU + KeyMap[213] = KEY_UNKNOWN; // AKEYCODE_MUHENKAN + KeyMap[214] = KEY_UNKNOWN; // AKEYCODE_HENKAN + KeyMap[215] = KEY_UNKNOWN; // AKEYCODE_KATAKANA_HIRAGANA + KeyMap[216] = KEY_UNKNOWN; // AKEYCODE_YEN + KeyMap[217] = KEY_UNKNOWN; // AKEYCODE_RO + KeyMap[218] = KEY_UNKNOWN; // AKEYCODE_KANA + KeyMap[219] = KEY_UNKNOWN; // AKEYCODE_ASSIST + KeyMap[220] = KEY_UNKNOWN; // AKEYCODE_BRIGHTNESS_DOWN + KeyMap[221] = KEY_UNKNOWN; // AKEYCODE_BRIGHTNESS_UP , + KeyMap[222] = KEY_UNKNOWN; // AKEYCODE_MEDIA_AUDIO_TRACK } bool CIrrDeviceAndroid::activateAccelerometer(float updateInterval) @@ -793,7 +757,7 @@ bool CIrrDeviceAndroid::activateAccelerometer(float updateInterval) return false; ASensorEventQueue_enableSensor(SensorEventQueue, Accelerometer); - ASensorEventQueue_setEventRate(SensorEventQueue, Accelerometer, (int32_t)(updateInterval*1000.f*1000.f)); // in microseconds + ASensorEventQueue_setEventRate(SensorEventQueue, Accelerometer, (int32_t)(updateInterval * 1000.f * 1000.f)); // in microseconds os::Printer::log("Activated accelerometer", ELL_DEBUG); return true; @@ -801,8 +765,7 @@ bool CIrrDeviceAndroid::activateAccelerometer(float updateInterval) bool CIrrDeviceAndroid::deactivateAccelerometer() { - if (Accelerometer) - { + if (Accelerometer) { ASensorEventQueue_disableSensor(SensorEventQueue, Accelerometer); Accelerometer = 0; os::Printer::log("Deactivated accelerometer", ELL_DEBUG); @@ -831,7 +794,7 @@ bool CIrrDeviceAndroid::activateGyroscope(float updateInterval) return false; ASensorEventQueue_enableSensor(SensorEventQueue, Gyroscope); - ASensorEventQueue_setEventRate(SensorEventQueue, Gyroscope, (int32_t)(updateInterval*1000.f*1000.f)); // in microseconds + ASensorEventQueue_setEventRate(SensorEventQueue, Gyroscope, (int32_t)(updateInterval * 1000.f * 1000.f)); // in microseconds os::Printer::log("Activated gyroscope", ELL_DEBUG); return true; @@ -839,8 +802,7 @@ bool CIrrDeviceAndroid::activateGyroscope(float updateInterval) bool CIrrDeviceAndroid::deactivateGyroscope() { - if (Gyroscope) - { + if (Gyroscope) { ASensorEventQueue_disableSensor(SensorEventQueue, Gyroscope); Gyroscope = 0; os::Printer::log("Deactivated gyroscope", ELL_DEBUG); diff --git a/source/Irrlicht/Android/CIrrDeviceAndroid.h b/source/Irrlicht/Android/CIrrDeviceAndroid.h index 9192cf13..19a35b15 100644 --- a/source/Irrlicht/Android/CIrrDeviceAndroid.h +++ b/source/Irrlicht/Android/CIrrDeviceAndroid.h @@ -4,8 +4,6 @@ #pragma once - - #include "CIrrDeviceStub.h" #include "IrrlichtDevice.h" #include "ICursorControl.h" @@ -15,88 +13,86 @@ namespace irr { - class CIrrDeviceAndroid : public CIrrDeviceStub - { - public: - CIrrDeviceAndroid(const SIrrlichtCreationParameters& param); +class CIrrDeviceAndroid : public CIrrDeviceStub +{ +public: + CIrrDeviceAndroid(const SIrrlichtCreationParameters ¶m); - virtual ~CIrrDeviceAndroid(); + virtual ~CIrrDeviceAndroid(); - virtual bool run(); + virtual bool run(); - virtual void yield(); + virtual void yield(); - virtual void sleep(u32 timeMs, bool pauseTimer = false); + virtual void sleep(u32 timeMs, bool pauseTimer = false); - virtual void setWindowCaption(const wchar_t* text); + virtual void setWindowCaption(const wchar_t *text); - virtual bool isWindowActive() const; + virtual bool isWindowActive() const; - virtual bool isWindowFocused() const; + virtual bool isWindowFocused() const; - virtual bool isWindowMinimized() const; + virtual bool isWindowMinimized() const; - virtual bool isWindowVisible() const; + virtual bool isWindowVisible() const; - virtual void closeDevice(); + virtual void closeDevice(); - virtual void setResizable(bool resize = false); + virtual void setResizable(bool resize = false); - virtual void minimizeWindow(); + virtual void minimizeWindow(); - virtual void maximizeWindow(); + virtual void maximizeWindow(); - virtual void restoreWindow(); + virtual void restoreWindow(); - virtual core::position2di getWindowPosition(); + virtual core::position2di getWindowPosition(); - virtual E_DEVICE_TYPE getType() const; + virtual E_DEVICE_TYPE getType() const; - virtual bool activateAccelerometer(float updateInterval); + virtual bool activateAccelerometer(float updateInterval); - virtual bool deactivateAccelerometer(); + virtual bool deactivateAccelerometer(); - virtual bool isAccelerometerActive(); + virtual bool isAccelerometerActive(); - virtual bool isAccelerometerAvailable(); + virtual bool isAccelerometerAvailable(); - virtual bool activateGyroscope(float updateInterval); + virtual bool activateGyroscope(float updateInterval); - virtual bool deactivateGyroscope(); + virtual bool deactivateGyroscope(); - virtual bool isGyroscopeActive(); + virtual bool isGyroscopeActive(); - virtual bool isGyroscopeAvailable(); + virtual bool isGyroscopeAvailable(); - private: +private: + static void handleAndroidCommand(android_app *app, int32_t cmd); - static void handleAndroidCommand(android_app* app, int32_t cmd); + static s32 handleInput(android_app *app, AInputEvent *event); - static s32 handleInput(android_app* app, AInputEvent* event); + void createDriver(); - void createDriver(); + void createKeyMap(); - void createKeyMap(); + video::SExposedVideoData &getExposedVideoData(); - video::SExposedVideoData& getExposedVideoData(); + android_app *Android; + ASensorManager *SensorManager; + ASensorEventQueue *SensorEventQueue; + const ASensor *Accelerometer; + const ASensor *Gyroscope; - android_app* Android; - ASensorManager* SensorManager; - ASensorEventQueue* SensorEventQueue; - const ASensor* Accelerometer; - const ASensor* Gyroscope; + bool Initialized; + bool Stopped; + bool Paused; + bool Focused; - bool Initialized; - bool Stopped; - bool Paused; - bool Focused; + JNIEnv *JNIEnvAttachedToVM; - JNIEnv* JNIEnvAttachedToVM; + video::SExposedVideoData ExposedVideoData; - video::SExposedVideoData ExposedVideoData; - - core::array KeyMap; - }; + core::array KeyMap; +}; } // end namespace irr - diff --git a/source/Irrlicht/Android/CKeyEventWrapper.cpp b/source/Irrlicht/Android/CKeyEventWrapper.cpp index f68e77db..4008c29c 100644 --- a/source/Irrlicht/Android/CKeyEventWrapper.cpp +++ b/source/Irrlicht/Android/CKeyEventWrapper.cpp @@ -14,18 +14,15 @@ jclass CKeyEventWrapper::Class_KeyEvent = 0; jmethodID CKeyEventWrapper::Method_constructor = 0; jmethodID CKeyEventWrapper::Method_getUnicodeChar = 0; -CKeyEventWrapper::CKeyEventWrapper(JNIEnv* jniEnv, int action, int code) - : JniEnv(jniEnv), JniKeyEvent(0) +CKeyEventWrapper::CKeyEventWrapper(JNIEnv *jniEnv, int action, int code) : + JniEnv(jniEnv), JniKeyEvent(0) { - if ( JniEnv ) - { - if (!Class_KeyEvent ) - { + if (JniEnv) { + if (!Class_KeyEvent) { // Find java classes & functions on first call os::Printer::log("CKeyEventWrapper first initialize", ELL_DEBUG); jclass localClass = JniEnv->FindClass("android/view/KeyEvent"); - if (localClass) - { + if (localClass) { Class_KeyEvent = reinterpret_cast(JniEnv->NewGlobalRef(localClass)); } @@ -33,12 +30,9 @@ CKeyEventWrapper::CKeyEventWrapper(JNIEnv* jniEnv, int action, int code) Method_getUnicodeChar = JniEnv->GetMethodID(Class_KeyEvent, "getUnicodeChar", "(I)I"); } - if ( Class_KeyEvent && Method_constructor ) - { + if (Class_KeyEvent && Method_constructor) { JniKeyEvent = JniEnv->NewObject(Class_KeyEvent, Method_constructor, action, code); - } - else - { + } else { os::Printer::log("CKeyEventWrapper didn't find JNI classes/methods", ELL_WARNING); } } diff --git a/source/Irrlicht/Android/CKeyEventWrapper.h b/source/Irrlicht/Android/CKeyEventWrapper.h index de21ffe2..9eb68697 100644 --- a/source/Irrlicht/Android/CKeyEventWrapper.h +++ b/source/Irrlicht/Android/CKeyEventWrapper.h @@ -18,7 +18,7 @@ namespace jni class CKeyEventWrapper { public: - CKeyEventWrapper(JNIEnv* jniEnv, int action, int code); + CKeyEventWrapper(JNIEnv *jniEnv, int action, int code); ~CKeyEventWrapper(); int getUnicodeChar(int metaState); @@ -27,8 +27,8 @@ private: static jclass Class_KeyEvent; static jmethodID Method_getUnicodeChar; static jmethodID Method_constructor; - JNIEnv* JniEnv; - jobject JniKeyEvent; // this object in java + JNIEnv *JniEnv; + jobject JniKeyEvent; // this object in java }; } // namespace jni diff --git a/source/Irrlicht/BuiltInFont.h b/source/Irrlicht/BuiltInFont.h index a7b2ba9c..590f5cfc 100644 --- a/source/Irrlicht/BuiltInFont.h +++ b/source/Irrlicht/BuiltInFont.h @@ -12,125 +12,124 @@ namespace irr namespace gui { const u8 BuiltInFontData[] = -{ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, - 0x04, 0x03, 0x00, 0x00, 0x00, 0x31, 0x10, 0x7c, 0xf8, 0x00, 0x00, 0x00, - 0x0f, 0x50, 0x4c, 0x54, 0x45, 0x18, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, - 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbd, 0xc8, 0xc8, 0xae, - 0x00, 0x00, 0x05, 0x11, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x62, 0x50, - 0x06, 0xf0, 0x62, 0x06, 0xb6, 0xed, 0xf4, 0x3a, 0x0c, 0xff, 0xf1, 0xba, - 0x00, 0xb9, 0x41, 0xde, 0x06, 0xd9, 0x7f, 0xba, 0x07, 0x98, 0x10, 0x6a, - 0x1f, 0xd2, 0xe2, 0x9f, 0xa0, 0xf8, 0x74, 0xaa, 0x65, 0xc9, 0x32, 0x23, - 0x39, 0xc4, 0xc1, 0xe9, 0xc5, 0x83, 0x0b, 0xd6, 0x58, 0x7d, 0xf4, 0xe9, - 0xec, 0x6a, 0xac, 0x6b, 0xd5, 0xc7, 0x9e, 0xfc, 0x17, 0x62, 0x09, 0x09, - 0x4c, 0x60, 0x59, 0x0b, 0x99, 0x0a, 0x6b, 0xde, 0xc1, 0x60, 0x62, 0x82, - 0xd2, 0xc0, 0x00, 0x90, 0x58, 0x21, 0xc2, 0xc6, 0x02, 0xef, 0x00, 0x16, - 0xc1, 0x2a, 0x2e, 0x46, 0x13, 0xb5, 0x0a, 0x00, 0x48, 0xc5, 0xef, 0x62, - 0x63, 0xde, 0x00, 0xd4, 0x28, 0xea, 0xc7, 0x77, 0x8a, 0x82, 0x07, 0xa0, - 0xcb, 0xe0, 0x0c, 0x80, 0x42, 0x41, 0x0b, 0x20, 0x83, 0xb0, 0xc1, 0xc2, - 0x8d, 0x22, 0x46, 0x12, 0x13, 0x1c, 0xec, 0x5b, 0x05, 0x03, 0xd0, 0x9d, - 0xc9, 0x00, 0xbc, 0x68, 0x21, 0x10, 0xa4, 0x01, 0xe8, 0x8a, 0x68, 0xb1, - 0x24, 0x73, 0x88, 0x30, 0x2d, 0xc8, 0x98, 0x11, 0x66, 0x7e, 0x02, 0x7c, - 0x26, 0x16, 0x6f, 0xc8, 0xf3, 0x0b, 0x9e, 0xd0, 0xf1, 0xb9, 0xfc, 0x3e, - 0x9d, 0x3d, 0x79, 0xd2, 0x61, 0xf4, 0xeb, 0x4c, 0x7e, 0x2c, 0x6e, 0x0e, - 0x41, 0x29, 0xab, 0x37, 0x53, 0xed, 0xf2, 0x46, 0xe3, 0x59, 0xfd, 0x53, - 0x09, 0x28, 0x80, 0x51, 0x8c, 0xb2, 0x4c, 0x42, 0xca, 0xdc, 0x32, 0xb4, - 0x26, 0xc8, 0xb2, 0x9a, 0x0f, 0xee, 0x2e, 0x8c, 0x29, 0x1d, 0xeb, 0xd4, - 0x54, 0x3d, 0x00, 0x62, 0x03, 0x70, 0x93, 0xfb, 0x01, 0xdd, 0xa6, 0x52, - 0xc2, 0xb8, 0x81, 0x98, 0x3a, 0x4a, 0x01, 0xca, 0x57, 0xdb, 0x92, 0xf0, - 0x37, 0xe3, 0x0a, 0x26, 0x15, 0x0d, 0x0d, 0x80, 0x59, 0x2a, 0x8b, 0x1f, - 0x01, 0xa6, 0x02, 0x50, 0x3f, 0xcd, 0x3f, 0xb6, 0xe0, 0xb6, 0x40, 0xbd, - 0x60, 0x8a, 0x47, 0xb3, 0x66, 0xe6, 0xf3, 0x10, 0xa7, 0x7e, 0x8b, 0x9e, - 0x65, 0x18, 0x4f, 0x01, 0xb1, 0x89, 0xc2, 0x7f, 0x2f, 0xe5, 0xe6, 0x10, - 0xb4, 0xac, 0xde, 0x4d, 0xb5, 0xcb, 0xdf, 0x34, 0xde, 0x92, 0x1e, 0x1b, - 0x73, 0x0f, 0xe7, 0xa0, 0x73, 0x9f, 0x26, 0x94, 0xcb, 0x75, 0x3e, 0x11, - 0xdd, 0xfd, 0x40, 0x4f, 0x9b, 0x90, 0x7c, 0x7f, 0x85, 0x63, 0x45, 0x42, - 0x30, 0x41, 0x1b, 0x71, 0x67, 0x8a, 0x98, 0x3d, 0x6b, 0x60, 0x07, 0x90, - 0xc0, 0x86, 0x59, 0xb1, 0xa9, 0xbc, 0x06, 0x28, 0x11, 0xc4, 0x6c, 0x5c, - 0x2e, 0x02, 0x3c, 0x8c, 0xa9, 0xc8, 0xc4, 0x1d, 0xdb, 0x82, 0x24, 0x12, - 0xd0, 0x4b, 0x80, 0x2d, 0x3e, 0x52, 0x56, 0x96, 0xa7, 0x4d, 0xf0, 0xd1, - 0x42, 0x37, 0xaa, 0x7f, 0xf5, 0x0e, 0x00, 0xdd, 0x01, 0x48, 0xf7, 0x06, - 0x0c, 0xf1, 0x00, 0x4c, 0xe1, 0xc9, 0x09, 0x40, 0xf6, 0x16, 0xfe, 0x4d, - 0x32, 0x7f, 0x31, 0x7f, 0x2f, 0x43, 0xca, 0xd1, 0x3a, 0x27, 0x9d, 0xfb, - 0x34, 0xa1, 0x5c, 0xae, 0xd3, 0x7b, 0xc5, 0x30, 0xf3, 0x5a, 0xce, 0xa3, - 0x0e, 0xa3, 0xcd, 0x68, 0x62, 0xc7, 0x46, 0xba, 0xc2, 0x9f, 0x88, 0x00, - 0x3c, 0xef, 0x5d, 0xfe, 0x49, 0xe6, 0xf5, 0x69, 0x60, 0x1b, 0x7e, 0x02, - 0xf0, 0x6b, 0x00, 0x97, 0xbd, 0x04, 0x85, 0xac, 0x98, 0xb0, 0x62, 0x42, - 0x83, 0xc4, 0x32, 0x21, 0x78, 0xad, 0xb9, 0xa3, 0x9a, 0x5c, 0x68, 0x09, - 0x17, 0x4d, 0x58, 0xc6, 0x52, 0x9d, 0xd1, 0x96, 0x35, 0x00, 0x6b, 0x3a, - 0xdc, 0x2d, 0x00, 0x3b, 0x80, 0x5e, 0x00, 0x34, 0xdd, 0x18, 0x0d, 0x16, - 0x5b, 0x05, 0x04, 0xa3, 0xdc, 0x01, 0x98, 0x16, 0xe6, 0x92, 0x56, 0x80, - 0xa5, 0x1c, 0x2d, 0x54, 0xf4, 0xe2, 0xac, 0x8e, 0x84, 0x5b, 0x7c, 0x00, - 0x46, 0xe4, 0x37, 0x00, 0xcc, 0x4d, 0x9e, 0xc3, 0xcc, 0x67, 0x2f, 0x15, - 0x75, 0x46, 0xcb, 0xdc, 0x67, 0x4d, 0xc7, 0x46, 0xd6, 0x4a, 0x2f, 0x18, - 0x6f, 0x6b, 0xb9, 0xff, 0x57, 0x4c, 0x16, 0x7e, 0x4b, 0xa9, 0x0c, 0x33, - 0x3e, 0x01, 0x30, 0x42, 0xc3, 0xaf, 0xcf, 0x2a, 0x08, 0xa2, 0x8c, 0xfe, - 0xac, 0x02, 0x41, 0xdc, 0x3e, 0xf8, 0x14, 0x40, 0x00, 0x9f, 0x56, 0x30, - 0x34, 0x07, 0x63, 0xde, 0x95, 0x73, 0xdb, 0xa7, 0x00, 0xf7, 0xbb, 0xf2, - 0xdb, 0x3a, 0xdc, 0x5f, 0xf3, 0xbe, 0x61, 0xfb, 0xf6, 0x5d, 0x5a, 0xa7, - 0x84, 0x5d, 0xbc, 0xdd, 0x7f, 0x00, 0x36, 0x75, 0xcc, 0x25, 0x7e, 0x90, - 0xe4, 0x8d, 0x76, 0x2c, 0xa1, 0x6c, 0xad, 0xcd, 0x09, 0xb3, 0x11, 0x07, - 0xd0, 0x18, 0x70, 0x43, 0x9d, 0xa9, 0x11, 0xcb, 0xf7, 0x53, 0x2e, 0x36, - 0xa0, 0x13, 0xc0, 0xcc, 0x25, 0xb3, 0x00, 0x06, 0x6c, 0x33, 0x32, 0x4e, - 0x13, 0x91, 0x86, 0x30, 0x54, 0x04, 0xe3, 0x22, 0x1d, 0x15, 0xd8, 0x8a, - 0x35, 0x15, 0x28, 0x34, 0x67, 0x66, 0x04, 0x1b, 0xec, 0x62, 0x18, 0x77, - 0x73, 0x26, 0x59, 0x83, 0x3d, 0xfd, 0x0d, 0x00, 0x01, 0xc6, 0x91, 0x8c, - 0x53, 0x43, 0x52, 0x90, 0x0a, 0x36, 0x23, 0x5b, 0x05, 0x36, 0xd9, 0x32, - 0x7a, 0x02, 0x35, 0x73, 0x0e, 0xbf, 0x4a, 0x8b, 0x7c, 0x99, 0x96, 0x77, - 0xee, 0x95, 0x32, 0x3f, 0xca, 0x93, 0x67, 0xdf, 0xbe, 0xd5, 0x27, 0x25, - 0xe9, 0x90, 0xfc, 0xfc, 0x01, 0xd8, 0xd5, 0x9a, 0x8e, 0x0f, 0x7c, 0x61, - 0x1e, 0xd2, 0x25, 0xf1, 0x10, 0x17, 0x94, 0xd3, 0xe6, 0xb1, 0x02, 0xff, - 0xc3, 0x8f, 0x4b, 0x97, 0x2f, 0x5d, 0xd0, 0x44, 0x66, 0x5b, 0x6b, 0x9c, - 0x1b, 0x29, 0x8c, 0x99, 0x05, 0x37, 0x80, 0x86, 0x53, 0x34, 0xe0, 0xd9, - 0x76, 0x12, 0x63, 0x8c, 0x62, 0x82, 0xe2, 0xd1, 0x01, 0x25, 0x41, 0x68, - 0xee, 0xd7, 0xca, 0x0f, 0x00, 0xe9, 0x47, 0xc2, 0xa6, 0x9e, 0x47, 0xd6, - 0x32, 0x8d, 0x41, 0x99, 0xa5, 0xdd, 0x90, 0x58, 0x1c, 0x15, 0x34, 0xd9, - 0x0a, 0x96, 0x7e, 0x05, 0x18, 0x53, 0x7d, 0x59, 0x01, 0x39, 0x01, 0x94, - 0x90, 0xf8, 0x30, 0xbf, 0xb6, 0x80, 0x6e, 0x00, 0xe8, 0x1e, 0x57, 0x4c, - 0x5e, 0xb5, 0xf0, 0xf2, 0x10, 0x7f, 0x27, 0xe0, 0xe7, 0x12, 0xde, 0x90, - 0xa1, 0xe7, 0x98, 0x65, 0x4f, 0x7d, 0xf6, 0x69, 0xc6, 0x69, 0x86, 0xc3, - 0x7d, 0xd1, 0x9a, 0x8b, 0x12, 0x5a, 0x2a, 0x5d, 0xa9, 0x3e, 0x8e, 0x61, - 0xa6, 0x77, 0xf2, 0x0e, 0x9d, 0x26, 0x26, 0x2a, 0x65, 0x98, 0xda, 0x98, - 0x26, 0x5f, 0x4b, 0xb7, 0xe3, 0x54, 0xfc, 0xe2, 0x2b, 0x99, 0x44, 0x63, - 0xab, 0x03, 0x95, 0xf3, 0x6b, 0x04, 0xac, 0x1b, 0x00, 0x36, 0x59, 0xe3, - 0x6f, 0x32, 0x7b, 0x84, 0x7d, 0x07, 0x10, 0x58, 0x94, 0x15, 0xc7, 0xd0, - 0x09, 0x47, 0x05, 0xfe, 0x11, 0xc0, 0x02, 0x73, 0x0e, 0xee, 0xa0, 0xa3, - 0x82, 0xf0, 0x02, 0x20, 0x73, 0x91, 0x3e, 0x86, 0x0c, 0xd4, 0x71, 0x88, - 0xc9, 0x38, 0x63, 0xe6, 0x95, 0x72, 0x6b, 0x80, 0x64, 0xa6, 0x7c, 0x24, - 0x7f, 0xcf, 0xf5, 0x72, 0xb2, 0xe3, 0xdd, 0x54, 0xf9, 0x3a, 0x87, 0x7d, - 0x5a, 0x4e, 0x5e, 0xf4, 0x59, 0xce, 0x5d, 0xef, 0x64, 0x9e, 0x2d, 0x70, - 0xfe, 0x23, 0xac, 0xae, 0x8c, 0x41, 0x55, 0x53, 0xa9, 0x77, 0xfe, 0xaa, - 0x50, 0x92, 0x00, 0xf3, 0x03, 0x47, 0x92, 0x00, 0xf6, 0xc3, 0xcf, 0x37, - 0x2e, 0x65, 0x8a, 0x8a, 0x82, 0xad, 0x01, 0x38, 0x44, 0xfe, 0xe7, 0x2f, - 0x40, 0x9a, 0x99, 0x37, 0x32, 0x62, 0xc2, 0x5d, 0x8d, 0x72, 0x52, 0xc9, - 0x0c, 0x0b, 0xa7, 0x85, 0x01, 0xe8, 0x12, 0xa7, 0x06, 0xdf, 0x00, 0x74, - 0x00, 0x80, 0x19, 0x00, 0x17, 0xed, 0x50, 0x4c, 0xf4, 0x0b, 0x00, 0x41, - 0x67, 0x05, 0xf7, 0x16, 0x20, 0x07, 0x99, 0x91, 0x11, 0x03, 0xf0, 0xbe, - 0x08, 0x51, 0xfd, 0x10, 0xc0, 0xed, 0x7a, 0x78, 0x40, 0x39, 0xf9, 0xec, - 0x53, 0xe7, 0xd4, 0x57, 0x64, 0xee, 0x16, 0x28, 0x95, 0xd9, 0xff, 0x4f, - 0x3c, 0x7f, 0x8f, 0x99, 0xcc, 0x7c, 0x72, 0xb8, 0x46, 0x47, 0x92, 0xf0, - 0xb9, 0x14, 0x40, 0xbe, 0x73, 0xd0, 0x2e, 0xdb, 0x5e, 0x81, 0x6b, 0x3d, - 0xe7, 0xa1, 0x84, 0x8c, 0xd3, 0x1c, 0x2f, 0x3f, 0xc4, 0x13, 0x40, 0x96, - 0x43, 0x20, 0xee, 0x32, 0x62, 0x0a, 0x40, 0x4d, 0x44, 0x41, 0x49, 0x88, - 0x63, 0x2d, 0x0f, 0x96, 0x4d, 0x48, 0x19, 0x53, 0x18, 0x17, 0x7f, 0x00, - 0x66, 0x4e, 0x62, 0x12, 0x2b, 0x4e, 0xe4, 0x34, 0xcd, 0x98, 0x44, 0x96, - 0x21, 0x64, 0x3a, 0x98, 0xae, 0x8d, 0x32, 0x15, 0x28, 0x09, 0x0a, 0xad, - 0x60, 0xcd, 0xc3, 0xb4, 0x30, 0x15, 0x30, 0x08, 0x61, 0x00, 0x20, 0xe3, - 0x35, 0xd2, 0x33, 0x88, 0xd9, 0xe5, 0x7e, 0x06, 0xb2, 0x06, 0xa0, 0x47, - 0x94, 0xec, 0x20, 0xfe, 0x91, 0xa7, 0x73, 0x06, 0xf9, 0x3e, 0x83, 0xf7, - 0xf8, 0xd0, 0x0e, 0xda, 0x4d, 0x65, 0xff, 0x3f, 0xf1, 0xfc, 0x7d, 0xcd, - 0x64, 0xe6, 0x93, 0x33, 0xf3, 0x21, 0xf2, 0x76, 0x53, 0x78, 0xfc, 0x7f, - 0x94, 0xa4, 0x46, 0x17, 0x17, 0x06, 0xca, 0x80, 0xa3, 0x88, 0x03, 0xa5, - 0x06, 0x88, 0x30, 0xb0, 0xb8, 0x90, 0x69, 0x88, 0x00, 0xd8, 0x00, 0x17, - 0x07, 0x17, 0x41, 0xf2, 0x3c, 0xc2, 0x08, 0x8a, 0x55, 0x47, 0x41, 0x41, - 0x07, 0x20, 0x16, 0x21, 0xdb, 0x05, 0x14, 0x19, 0xc0, 0x30, 0x28, 0x0c, - 0x70, 0x71, 0x01, 0x06, 0x22, 0x10, 0x90, 0x3d, 0x47, 0x82, 0x48, 0xa6, - 0x23, 0x13, 0x8c, 0x02, 0x00, 0xe7, 0xfb, 0x84, 0x1b, 0xf9, 0x8e, 0xc0, - 0x23, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, - 0x82 -}; + { + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, + 0x04, 0x03, 0x00, 0x00, 0x00, 0x31, 0x10, 0x7c, 0xf8, 0x00, 0x00, 0x00, + 0x0f, 0x50, 0x4c, 0x54, 0x45, 0x18, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbd, 0xc8, 0xc8, 0xae, + 0x00, 0x00, 0x05, 0x11, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x62, 0x50, + 0x06, 0xf0, 0x62, 0x06, 0xb6, 0xed, 0xf4, 0x3a, 0x0c, 0xff, 0xf1, 0xba, + 0x00, 0xb9, 0x41, 0xde, 0x06, 0xd9, 0x7f, 0xba, 0x07, 0x98, 0x10, 0x6a, + 0x1f, 0xd2, 0xe2, 0x9f, 0xa0, 0xf8, 0x74, 0xaa, 0x65, 0xc9, 0x32, 0x23, + 0x39, 0xc4, 0xc1, 0xe9, 0xc5, 0x83, 0x0b, 0xd6, 0x58, 0x7d, 0xf4, 0xe9, + 0xec, 0x6a, 0xac, 0x6b, 0xd5, 0xc7, 0x9e, 0xfc, 0x17, 0x62, 0x09, 0x09, + 0x4c, 0x60, 0x59, 0x0b, 0x99, 0x0a, 0x6b, 0xde, 0xc1, 0x60, 0x62, 0x82, + 0xd2, 0xc0, 0x00, 0x90, 0x58, 0x21, 0xc2, 0xc6, 0x02, 0xef, 0x00, 0x16, + 0xc1, 0x2a, 0x2e, 0x46, 0x13, 0xb5, 0x0a, 0x00, 0x48, 0xc5, 0xef, 0x62, + 0x63, 0xde, 0x00, 0xd4, 0x28, 0xea, 0xc7, 0x77, 0x8a, 0x82, 0x07, 0xa0, + 0xcb, 0xe0, 0x0c, 0x80, 0x42, 0x41, 0x0b, 0x20, 0x83, 0xb0, 0xc1, 0xc2, + 0x8d, 0x22, 0x46, 0x12, 0x13, 0x1c, 0xec, 0x5b, 0x05, 0x03, 0xd0, 0x9d, + 0xc9, 0x00, 0xbc, 0x68, 0x21, 0x10, 0xa4, 0x01, 0xe8, 0x8a, 0x68, 0xb1, + 0x24, 0x73, 0x88, 0x30, 0x2d, 0xc8, 0x98, 0x11, 0x66, 0x7e, 0x02, 0x7c, + 0x26, 0x16, 0x6f, 0xc8, 0xf3, 0x0b, 0x9e, 0xd0, 0xf1, 0xb9, 0xfc, 0x3e, + 0x9d, 0x3d, 0x79, 0xd2, 0x61, 0xf4, 0xeb, 0x4c, 0x7e, 0x2c, 0x6e, 0x0e, + 0x41, 0x29, 0xab, 0x37, 0x53, 0xed, 0xf2, 0x46, 0xe3, 0x59, 0xfd, 0x53, + 0x09, 0x28, 0x80, 0x51, 0x8c, 0xb2, 0x4c, 0x42, 0xca, 0xdc, 0x32, 0xb4, + 0x26, 0xc8, 0xb2, 0x9a, 0x0f, 0xee, 0x2e, 0x8c, 0x29, 0x1d, 0xeb, 0xd4, + 0x54, 0x3d, 0x00, 0x62, 0x03, 0x70, 0x93, 0xfb, 0x01, 0xdd, 0xa6, 0x52, + 0xc2, 0xb8, 0x81, 0x98, 0x3a, 0x4a, 0x01, 0xca, 0x57, 0xdb, 0x92, 0xf0, + 0x37, 0xe3, 0x0a, 0x26, 0x15, 0x0d, 0x0d, 0x80, 0x59, 0x2a, 0x8b, 0x1f, + 0x01, 0xa6, 0x02, 0x50, 0x3f, 0xcd, 0x3f, 0xb6, 0xe0, 0xb6, 0x40, 0xbd, + 0x60, 0x8a, 0x47, 0xb3, 0x66, 0xe6, 0xf3, 0x10, 0xa7, 0x7e, 0x8b, 0x9e, + 0x65, 0x18, 0x4f, 0x01, 0xb1, 0x89, 0xc2, 0x7f, 0x2f, 0xe5, 0xe6, 0x10, + 0xb4, 0xac, 0xde, 0x4d, 0xb5, 0xcb, 0xdf, 0x34, 0xde, 0x92, 0x1e, 0x1b, + 0x73, 0x0f, 0xe7, 0xa0, 0x73, 0x9f, 0x26, 0x94, 0xcb, 0x75, 0x3e, 0x11, + 0xdd, 0xfd, 0x40, 0x4f, 0x9b, 0x90, 0x7c, 0x7f, 0x85, 0x63, 0x45, 0x42, + 0x30, 0x41, 0x1b, 0x71, 0x67, 0x8a, 0x98, 0x3d, 0x6b, 0x60, 0x07, 0x90, + 0xc0, 0x86, 0x59, 0xb1, 0xa9, 0xbc, 0x06, 0x28, 0x11, 0xc4, 0x6c, 0x5c, + 0x2e, 0x02, 0x3c, 0x8c, 0xa9, 0xc8, 0xc4, 0x1d, 0xdb, 0x82, 0x24, 0x12, + 0xd0, 0x4b, 0x80, 0x2d, 0x3e, 0x52, 0x56, 0x96, 0xa7, 0x4d, 0xf0, 0xd1, + 0x42, 0x37, 0xaa, 0x7f, 0xf5, 0x0e, 0x00, 0xdd, 0x01, 0x48, 0xf7, 0x06, + 0x0c, 0xf1, 0x00, 0x4c, 0xe1, 0xc9, 0x09, 0x40, 0xf6, 0x16, 0xfe, 0x4d, + 0x32, 0x7f, 0x31, 0x7f, 0x2f, 0x43, 0xca, 0xd1, 0x3a, 0x27, 0x9d, 0xfb, + 0x34, 0xa1, 0x5c, 0xae, 0xd3, 0x7b, 0xc5, 0x30, 0xf3, 0x5a, 0xce, 0xa3, + 0x0e, 0xa3, 0xcd, 0x68, 0x62, 0xc7, 0x46, 0xba, 0xc2, 0x9f, 0x88, 0x00, + 0x3c, 0xef, 0x5d, 0xfe, 0x49, 0xe6, 0xf5, 0x69, 0x60, 0x1b, 0x7e, 0x02, + 0xf0, 0x6b, 0x00, 0x97, 0xbd, 0x04, 0x85, 0xac, 0x98, 0xb0, 0x62, 0x42, + 0x83, 0xc4, 0x32, 0x21, 0x78, 0xad, 0xb9, 0xa3, 0x9a, 0x5c, 0x68, 0x09, + 0x17, 0x4d, 0x58, 0xc6, 0x52, 0x9d, 0xd1, 0x96, 0x35, 0x00, 0x6b, 0x3a, + 0xdc, 0x2d, 0x00, 0x3b, 0x80, 0x5e, 0x00, 0x34, 0xdd, 0x18, 0x0d, 0x16, + 0x5b, 0x05, 0x04, 0xa3, 0xdc, 0x01, 0x98, 0x16, 0xe6, 0x92, 0x56, 0x80, + 0xa5, 0x1c, 0x2d, 0x54, 0xf4, 0xe2, 0xac, 0x8e, 0x84, 0x5b, 0x7c, 0x00, + 0x46, 0xe4, 0x37, 0x00, 0xcc, 0x4d, 0x9e, 0xc3, 0xcc, 0x67, 0x2f, 0x15, + 0x75, 0x46, 0xcb, 0xdc, 0x67, 0x4d, 0xc7, 0x46, 0xd6, 0x4a, 0x2f, 0x18, + 0x6f, 0x6b, 0xb9, 0xff, 0x57, 0x4c, 0x16, 0x7e, 0x4b, 0xa9, 0x0c, 0x33, + 0x3e, 0x01, 0x30, 0x42, 0xc3, 0xaf, 0xcf, 0x2a, 0x08, 0xa2, 0x8c, 0xfe, + 0xac, 0x02, 0x41, 0xdc, 0x3e, 0xf8, 0x14, 0x40, 0x00, 0x9f, 0x56, 0x30, + 0x34, 0x07, 0x63, 0xde, 0x95, 0x73, 0xdb, 0xa7, 0x00, 0xf7, 0xbb, 0xf2, + 0xdb, 0x3a, 0xdc, 0x5f, 0xf3, 0xbe, 0x61, 0xfb, 0xf6, 0x5d, 0x5a, 0xa7, + 0x84, 0x5d, 0xbc, 0xdd, 0x7f, 0x00, 0x36, 0x75, 0xcc, 0x25, 0x7e, 0x90, + 0xe4, 0x8d, 0x76, 0x2c, 0xa1, 0x6c, 0xad, 0xcd, 0x09, 0xb3, 0x11, 0x07, + 0xd0, 0x18, 0x70, 0x43, 0x9d, 0xa9, 0x11, 0xcb, 0xf7, 0x53, 0x2e, 0x36, + 0xa0, 0x13, 0xc0, 0xcc, 0x25, 0xb3, 0x00, 0x06, 0x6c, 0x33, 0x32, 0x4e, + 0x13, 0x91, 0x86, 0x30, 0x54, 0x04, 0xe3, 0x22, 0x1d, 0x15, 0xd8, 0x8a, + 0x35, 0x15, 0x28, 0x34, 0x67, 0x66, 0x04, 0x1b, 0xec, 0x62, 0x18, 0x77, + 0x73, 0x26, 0x59, 0x83, 0x3d, 0xfd, 0x0d, 0x00, 0x01, 0xc6, 0x91, 0x8c, + 0x53, 0x43, 0x52, 0x90, 0x0a, 0x36, 0x23, 0x5b, 0x05, 0x36, 0xd9, 0x32, + 0x7a, 0x02, 0x35, 0x73, 0x0e, 0xbf, 0x4a, 0x8b, 0x7c, 0x99, 0x96, 0x77, + 0xee, 0x95, 0x32, 0x3f, 0xca, 0x93, 0x67, 0xdf, 0xbe, 0xd5, 0x27, 0x25, + 0xe9, 0x90, 0xfc, 0xfc, 0x01, 0xd8, 0xd5, 0x9a, 0x8e, 0x0f, 0x7c, 0x61, + 0x1e, 0xd2, 0x25, 0xf1, 0x10, 0x17, 0x94, 0xd3, 0xe6, 0xb1, 0x02, 0xff, + 0xc3, 0x8f, 0x4b, 0x97, 0x2f, 0x5d, 0xd0, 0x44, 0x66, 0x5b, 0x6b, 0x9c, + 0x1b, 0x29, 0x8c, 0x99, 0x05, 0x37, 0x80, 0x86, 0x53, 0x34, 0xe0, 0xd9, + 0x76, 0x12, 0x63, 0x8c, 0x62, 0x82, 0xe2, 0xd1, 0x01, 0x25, 0x41, 0x68, + 0xee, 0xd7, 0xca, 0x0f, 0x00, 0xe9, 0x47, 0xc2, 0xa6, 0x9e, 0x47, 0xd6, + 0x32, 0x8d, 0x41, 0x99, 0xa5, 0xdd, 0x90, 0x58, 0x1c, 0x15, 0x34, 0xd9, + 0x0a, 0x96, 0x7e, 0x05, 0x18, 0x53, 0x7d, 0x59, 0x01, 0x39, 0x01, 0x94, + 0x90, 0xf8, 0x30, 0xbf, 0xb6, 0x80, 0x6e, 0x00, 0xe8, 0x1e, 0x57, 0x4c, + 0x5e, 0xb5, 0xf0, 0xf2, 0x10, 0x7f, 0x27, 0xe0, 0xe7, 0x12, 0xde, 0x90, + 0xa1, 0xe7, 0x98, 0x65, 0x4f, 0x7d, 0xf6, 0x69, 0xc6, 0x69, 0x86, 0xc3, + 0x7d, 0xd1, 0x9a, 0x8b, 0x12, 0x5a, 0x2a, 0x5d, 0xa9, 0x3e, 0x8e, 0x61, + 0xa6, 0x77, 0xf2, 0x0e, 0x9d, 0x26, 0x26, 0x2a, 0x65, 0x98, 0xda, 0x98, + 0x26, 0x5f, 0x4b, 0xb7, 0xe3, 0x54, 0xfc, 0xe2, 0x2b, 0x99, 0x44, 0x63, + 0xab, 0x03, 0x95, 0xf3, 0x6b, 0x04, 0xac, 0x1b, 0x00, 0x36, 0x59, 0xe3, + 0x6f, 0x32, 0x7b, 0x84, 0x7d, 0x07, 0x10, 0x58, 0x94, 0x15, 0xc7, 0xd0, + 0x09, 0x47, 0x05, 0xfe, 0x11, 0xc0, 0x02, 0x73, 0x0e, 0xee, 0xa0, 0xa3, + 0x82, 0xf0, 0x02, 0x20, 0x73, 0x91, 0x3e, 0x86, 0x0c, 0xd4, 0x71, 0x88, + 0xc9, 0x38, 0x63, 0xe6, 0x95, 0x72, 0x6b, 0x80, 0x64, 0xa6, 0x7c, 0x24, + 0x7f, 0xcf, 0xf5, 0x72, 0xb2, 0xe3, 0xdd, 0x54, 0xf9, 0x3a, 0x87, 0x7d, + 0x5a, 0x4e, 0x5e, 0xf4, 0x59, 0xce, 0x5d, 0xef, 0x64, 0x9e, 0x2d, 0x70, + 0xfe, 0x23, 0xac, 0xae, 0x8c, 0x41, 0x55, 0x53, 0xa9, 0x77, 0xfe, 0xaa, + 0x50, 0x92, 0x00, 0xf3, 0x03, 0x47, 0x92, 0x00, 0xf6, 0xc3, 0xcf, 0x37, + 0x2e, 0x65, 0x8a, 0x8a, 0x82, 0xad, 0x01, 0x38, 0x44, 0xfe, 0xe7, 0x2f, + 0x40, 0x9a, 0x99, 0x37, 0x32, 0x62, 0xc2, 0x5d, 0x8d, 0x72, 0x52, 0xc9, + 0x0c, 0x0b, 0xa7, 0x85, 0x01, 0xe8, 0x12, 0xa7, 0x06, 0xdf, 0x00, 0x74, + 0x00, 0x80, 0x19, 0x00, 0x17, 0xed, 0x50, 0x4c, 0xf4, 0x0b, 0x00, 0x41, + 0x67, 0x05, 0xf7, 0x16, 0x20, 0x07, 0x99, 0x91, 0x11, 0x03, 0xf0, 0xbe, + 0x08, 0x51, 0xfd, 0x10, 0xc0, 0xed, 0x7a, 0x78, 0x40, 0x39, 0xf9, 0xec, + 0x53, 0xe7, 0xd4, 0x57, 0x64, 0xee, 0x16, 0x28, 0x95, 0xd9, 0xff, 0x4f, + 0x3c, 0x7f, 0x8f, 0x99, 0xcc, 0x7c, 0x72, 0xb8, 0x46, 0x47, 0x92, 0xf0, + 0xb9, 0x14, 0x40, 0xbe, 0x73, 0xd0, 0x2e, 0xdb, 0x5e, 0x81, 0x6b, 0x3d, + 0xe7, 0xa1, 0x84, 0x8c, 0xd3, 0x1c, 0x2f, 0x3f, 0xc4, 0x13, 0x40, 0x96, + 0x43, 0x20, 0xee, 0x32, 0x62, 0x0a, 0x40, 0x4d, 0x44, 0x41, 0x49, 0x88, + 0x63, 0x2d, 0x0f, 0x96, 0x4d, 0x48, 0x19, 0x53, 0x18, 0x17, 0x7f, 0x00, + 0x66, 0x4e, 0x62, 0x12, 0x2b, 0x4e, 0xe4, 0x34, 0xcd, 0x98, 0x44, 0x96, + 0x21, 0x64, 0x3a, 0x98, 0xae, 0x8d, 0x32, 0x15, 0x28, 0x09, 0x0a, 0xad, + 0x60, 0xcd, 0xc3, 0xb4, 0x30, 0x15, 0x30, 0x08, 0x61, 0x00, 0x20, 0xe3, + 0x35, 0xd2, 0x33, 0x88, 0xd9, 0xe5, 0x7e, 0x06, 0xb2, 0x06, 0xa0, 0x47, + 0x94, 0xec, 0x20, 0xfe, 0x91, 0xa7, 0x73, 0x06, 0xf9, 0x3e, 0x83, 0xf7, + 0xf8, 0xd0, 0x0e, 0xda, 0x4d, 0x65, 0xff, 0x3f, 0xf1, 0xfc, 0x7d, 0xcd, + 0x64, 0xe6, 0x93, 0x33, 0xf3, 0x21, 0xf2, 0x76, 0x53, 0x78, 0xfc, 0x7f, + 0x94, 0xa4, 0x46, 0x17, 0x17, 0x06, 0xca, 0x80, 0xa3, 0x88, 0x03, 0xa5, + 0x06, 0x88, 0x30, 0xb0, 0xb8, 0x90, 0x69, 0x88, 0x00, 0xd8, 0x00, 0x17, + 0x07, 0x17, 0x41, 0xf2, 0x3c, 0xc2, 0x08, 0x8a, 0x55, 0x47, 0x41, 0x41, + 0x07, 0x20, 0x16, 0x21, 0xdb, 0x05, 0x14, 0x19, 0xc0, 0x30, 0x28, 0x0c, + 0x70, 0x71, 0x01, 0x06, 0x22, 0x10, 0x90, 0x3d, 0x47, 0x82, 0x48, 0xa6, + 0x23, 0x13, 0x8c, 0x02, 0x00, 0xe7, 0xfb, 0x84, 0x1b, 0xf9, 0x8e, 0xc0, + 0x23, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, + 0x82}; - const u32 BuiltInFontDataSize = sizeof(BuiltInFontData); +const u32 BuiltInFontDataSize = sizeof(BuiltInFontData); } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CAnimatedMeshSceneNode.cpp b/source/Irrlicht/CAnimatedMeshSceneNode.cpp index 3d664463..d61bc903 100644 --- a/source/Irrlicht/CAnimatedMeshSceneNode.cpp +++ b/source/Irrlicht/CAnimatedMeshSceneNode.cpp @@ -17,35 +17,33 @@ #include "IFileSystem.h" #include "quaternion.h" - namespace irr { namespace scene { - //! constructor -CAnimatedMeshSceneNode::CAnimatedMeshSceneNode(IAnimatedMesh* mesh, - ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position, - const core::vector3df& rotation, - const core::vector3df& scale) -: IAnimatedMeshSceneNode(parent, mgr, id, position, rotation, scale), Mesh(0), - StartFrame(0), EndFrame(0), FramesPerSecond(0.025f), - CurrentFrameNr(0.f), LastTimeMs(0), - TransitionTime(0), Transiting(0.f), TransitingBlend(0.f), - JointMode(EJUOR_NONE), JointsUsed(false), - Looping(true), ReadOnlyMaterials(false), RenderFromIdentity(false), - LoopCallBack(0), PassCount(0) +CAnimatedMeshSceneNode::CAnimatedMeshSceneNode(IAnimatedMesh *mesh, + ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position, + const core::vector3df &rotation, + const core::vector3df &scale) : + IAnimatedMeshSceneNode(parent, mgr, id, position, rotation, scale), + Mesh(0), + StartFrame(0), EndFrame(0), FramesPerSecond(0.025f), + CurrentFrameNr(0.f), LastTimeMs(0), + TransitionTime(0), Transiting(0.f), TransitingBlend(0.f), + JointMode(EJUOR_NONE), JointsUsed(false), + Looping(true), ReadOnlyMaterials(false), RenderFromIdentity(false), + LoopCallBack(0), PassCount(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CAnimatedMeshSceneNode"); - #endif +#endif setMesh(mesh); } - //! destructor CAnimatedMeshSceneNode::~CAnimatedMeshSceneNode() { @@ -55,77 +53,63 @@ CAnimatedMeshSceneNode::~CAnimatedMeshSceneNode() Mesh->drop(); } - //! Sets the current frame. From now on the animation is played from this frame. void CAnimatedMeshSceneNode::setCurrentFrame(f32 frame) { // if you pass an out of range value, we just clamp it - CurrentFrameNr = core::clamp ( frame, (f32)StartFrame, (f32)EndFrame ); + CurrentFrameNr = core::clamp(frame, (f32)StartFrame, (f32)EndFrame); - beginTransition(); //transit to this frame if enabled + beginTransition(); // transit to this frame if enabled } - //! Returns the currently displayed frame number. f32 CAnimatedMeshSceneNode::getFrameNr() const { return CurrentFrameNr; } - //! Get CurrentFrameNr and update transiting settings void CAnimatedMeshSceneNode::buildFrameNr(u32 timeMs) { - if (Transiting!=0.f) - { - TransitingBlend += (f32)(timeMs) * Transiting; - if (TransitingBlend > 1.f) - { - Transiting=0.f; - TransitingBlend=0.f; + if (Transiting != 0.f) { + TransitingBlend += (f32)(timeMs)*Transiting; + if (TransitingBlend > 1.f) { + Transiting = 0.f; + TransitingBlend = 0.f; } } - if (StartFrame==EndFrame) - { - CurrentFrameNr = (f32)StartFrame; //Support for non animated meshes - } - else if (Looping) - { + if (StartFrame == EndFrame) { + CurrentFrameNr = (f32)StartFrame; // Support for non animated meshes + } else if (Looping) { // play animation looped CurrentFrameNr += timeMs * FramesPerSecond; // We have no interpolation between EndFrame and StartFrame, // the last frame must be identical to first one with our current solution. - if (FramesPerSecond > 0.f) //forwards... + if (FramesPerSecond > 0.f) // forwards... { if (CurrentFrameNr > EndFrame) - CurrentFrameNr = StartFrame + fmodf(CurrentFrameNr - StartFrame, (f32)(EndFrame-StartFrame)); - } - else //backwards... + CurrentFrameNr = StartFrame + fmodf(CurrentFrameNr - StartFrame, (f32)(EndFrame - StartFrame)); + } else // backwards... { if (CurrentFrameNr < StartFrame) - CurrentFrameNr = EndFrame - fmodf(EndFrame - CurrentFrameNr, (f32)(EndFrame-StartFrame)); + CurrentFrameNr = EndFrame - fmodf(EndFrame - CurrentFrameNr, (f32)(EndFrame - StartFrame)); } - } - else - { + } else { // play animation non looped CurrentFrameNr += timeMs * FramesPerSecond; - if (FramesPerSecond > 0.f) //forwards... + if (FramesPerSecond > 0.f) // forwards... { - if (CurrentFrameNr > (f32)EndFrame) - { + if (CurrentFrameNr > (f32)EndFrame) { CurrentFrameNr = (f32)EndFrame; if (LoopCallBack) LoopCallBack->OnAnimationEnd(this); } - } - else //backwards... + } else // backwards... { - if (CurrentFrameNr < (f32)StartFrame) - { + if (CurrentFrameNr < (f32)StartFrame) { CurrentFrameNr = (f32)StartFrame; if (LoopCallBack) LoopCallBack->OnAnimationEnd(this); @@ -134,17 +118,15 @@ void CAnimatedMeshSceneNode::buildFrameNr(u32 timeMs) } } - void CAnimatedMeshSceneNode::OnRegisterSceneNode() { - if (IsVisible && Mesh) - { + if (IsVisible && Mesh) { // because this node supports rendering of mixed mode meshes consisting of // transparent and solid material at the same time, we need to go through all // materials, check of what type they are and register this node for the right // render pass according to that. - video::IVideoDriver* driver = SceneManager->getVideoDriver(); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); PassCount = 0; int transparentCount = 0; @@ -152,11 +134,10 @@ void CAnimatedMeshSceneNode::OnRegisterSceneNode() // count transparent and solid materials in this scene node const u32 numMaterials = ReadOnlyMaterials ? Mesh->getMeshBufferCount() : Materials.size(); - for (u32 i=0; igetMeshBuffer(i)->getMaterial() : Materials[i]; + for (u32 i = 0; i < numMaterials; ++i) { + const video::SMaterial &material = ReadOnlyMaterials ? Mesh->getMeshBuffer(i)->getMaterial() : Materials[i]; - if ( driver->needsTransparentRenderPass(material) ) + if (driver->needsTransparentRenderPass(material)) ++transparentCount; else ++solidCount; @@ -177,22 +158,19 @@ void CAnimatedMeshSceneNode::OnRegisterSceneNode() } } -IMesh * CAnimatedMeshSceneNode::getMeshForCurrentFrame() +IMesh *CAnimatedMeshSceneNode::getMeshForCurrentFrame() { - if(Mesh->getMeshType() != EAMT_SKINNED) - { - s32 frameNr = (s32) getFrameNr(); - s32 frameBlend = (s32) (core::fract ( getFrameNr() ) * 1000.f); + if (Mesh->getMeshType() != EAMT_SKINNED) { + s32 frameNr = (s32)getFrameNr(); + s32 frameBlend = (s32)(core::fract(getFrameNr()) * 1000.f); return Mesh->getMesh(frameNr, frameBlend, StartFrame, EndFrame); - } - else - { + } else { // As multiple scene nodes may be sharing the same skinned mesh, we have to // re-animate it every frame to ensure that this node gets the mesh that it needs. - CSkinnedMesh* skinnedMesh = static_cast(Mesh); + CSkinnedMesh *skinnedMesh = static_cast(Mesh); - if (JointMode == EJUOR_CONTROL)//write to mesh + if (JointMode == EJUOR_CONTROL) // write to mesh skinnedMesh->transferJointsToMesh(JointChildSceneNodes); else skinnedMesh->animateMesh(getFrameNr(), 1.0f); @@ -200,20 +178,18 @@ IMesh * CAnimatedMeshSceneNode::getMeshForCurrentFrame() // Update the skinned mesh for the current joint transforms. skinnedMesh->skinMesh(); - if (JointMode == EJUOR_READ)//read from mesh + if (JointMode == EJUOR_READ) // read from mesh { skinnedMesh->recoverJointsFromMesh(JointChildSceneNodes); //---slow--- - for (u32 n=0;ngetParent()==this) - { - JointChildSceneNodes[n]->updateAbsolutePositionOfAllChildren(); //temp, should be an option + for (u32 n = 0; n < JointChildSceneNodes.size(); ++n) + if (JointChildSceneNodes[n]->getParent() == this) { + JointChildSceneNodes[n]->updateAbsolutePositionOfAllChildren(); // temp, should be an option } } - if(JointMode == EJUOR_CONTROL) - { + if (JointMode == EJUOR_CONTROL) { // For meshes other than EJUOR_CONTROL, this is done by calling animateMesh() skinnedMesh->updateBoundingBox(); } @@ -222,67 +198,59 @@ IMesh * CAnimatedMeshSceneNode::getMeshForCurrentFrame() } } - //! OnAnimate() is called just before rendering the whole scene. void CAnimatedMeshSceneNode::OnAnimate(u32 timeMs) { - if (LastTimeMs==0) // first frame + if (LastTimeMs == 0) // first frame { LastTimeMs = timeMs; } // set CurrentFrameNr - buildFrameNr(timeMs-LastTimeMs); + buildFrameNr(timeMs - LastTimeMs); LastTimeMs = timeMs; IAnimatedMeshSceneNode::OnAnimate(timeMs); } - //! renders the node. void CAnimatedMeshSceneNode::render() { - video::IVideoDriver* driver = SceneManager->getVideoDriver(); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); if (!Mesh || !driver) return; - const bool isTransparentPass = - SceneManager->getSceneNodeRenderPass() == scene::ESNRP_TRANSPARENT; + SceneManager->getSceneNodeRenderPass() == scene::ESNRP_TRANSPARENT; ++PassCount; - scene::IMesh* m = getMeshForCurrentFrame(); + scene::IMesh *m = getMeshForCurrentFrame(); - if(m) - { + if (m) { Box = m->getBoundingBox(); - } - else - { - #ifdef _DEBUG - os::Printer::log("Animated Mesh returned no mesh to render.", Mesh->getDebugName(), ELL_WARNING); - #endif + } else { +#ifdef _DEBUG + os::Printer::log("Animated Mesh returned no mesh to render.", Mesh->getDebugName(), ELL_WARNING); +#endif return; } driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); - for (u32 i=0; igetMeshBufferCount(); ++i) - { + for (u32 i = 0; i < m->getMeshBufferCount(); ++i) { const bool transparent = driver->needsTransparentRenderPass(Materials[i]); // only render transparent buffer if this is the transparent render pass // and solid only in solid pass - if (transparent == isTransparentPass) - { - scene::IMeshBuffer* mb = m->getMeshBuffer(i); - const video::SMaterial& material = ReadOnlyMaterials ? mb->getMaterial() : Materials[i]; + if (transparent == isTransparentPass) { + scene::IMeshBuffer *mb = m->getMeshBuffer(i); + const video::SMaterial &material = ReadOnlyMaterials ? mb->getMaterial() : Materials[i]; if (RenderFromIdentity) - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix ); + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); else if (Mesh->getMeshType() == EAMT_SKINNED) - driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer*)mb)->Transformation); + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer *)mb)->Transformation); driver->setMaterial(material); driver->drawMeshBuffer(mb); @@ -292,27 +260,24 @@ void CAnimatedMeshSceneNode::render() driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); // for debug purposes only: - if (DebugDataVisible && PassCount==1) - { + if (DebugDataVisible && PassCount == 1) { video::SMaterial debug_mat; debug_mat.Lighting = false; - debug_mat.AntiAliasing=0; + debug_mat.AntiAliasing = 0; driver->setMaterial(debug_mat); // show normals - if (DebugDataVisible & scene::EDS_NORMALS) - { + if (DebugDataVisible & scene::EDS_NORMALS) { const f32 debugNormalLength = 1.f; const video::SColor debugNormalColor = video::SColor(255, 34, 221, 221); const u32 count = m->getMeshBufferCount(); // draw normals - for (u32 g=0; g < count; ++g) - { - scene::IMeshBuffer* mb = m->getMeshBuffer(g); + for (u32 g = 0; g < count; ++g) { + scene::IMeshBuffer *mb = m->getMeshBuffer(g); if (RenderFromIdentity) - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix ); + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); else if (Mesh->getMeshType() == EAMT_SKINNED) - driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer*)mb)->Transformation); + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer *)mb)->Transformation); driver->drawMeshBufferNormals(mb, debugNormalLength, debugNormalColor); } @@ -323,90 +288,76 @@ void CAnimatedMeshSceneNode::render() driver->setMaterial(debug_mat); if (DebugDataVisible & scene::EDS_BBOX) - driver->draw3DBox(Box, video::SColor(255,255,255,255)); + driver->draw3DBox(Box, video::SColor(255, 255, 255, 255)); // show bounding box - if (DebugDataVisible & scene::EDS_BBOX_BUFFERS) - { - for (u32 g=0; g< m->getMeshBufferCount(); ++g) - { - const IMeshBuffer* mb = m->getMeshBuffer(g); + if (DebugDataVisible & scene::EDS_BBOX_BUFFERS) { + for (u32 g = 0; g < m->getMeshBufferCount(); ++g) { + const IMeshBuffer *mb = m->getMeshBuffer(g); if (Mesh->getMeshType() == EAMT_SKINNED) - driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer*)mb)->Transformation); - driver->draw3DBox(mb->getBoundingBox(), video::SColor(255,190,128,128)); + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer *)mb)->Transformation); + driver->draw3DBox(mb->getBoundingBox(), video::SColor(255, 190, 128, 128)); } } // show skeleton - if (DebugDataVisible & scene::EDS_SKELETON) - { - if (Mesh->getMeshType() == EAMT_SKINNED) - { + if (DebugDataVisible & scene::EDS_SKELETON) { + if (Mesh->getMeshType() == EAMT_SKINNED) { // draw skeleton - for (u32 g=0; g < ((ISkinnedMesh*)Mesh)->getAllJoints().size(); ++g) - { - ISkinnedMesh::SJoint *joint=((ISkinnedMesh*)Mesh)->getAllJoints()[g]; + for (u32 g = 0; g < ((ISkinnedMesh *)Mesh)->getAllJoints().size(); ++g) { + ISkinnedMesh::SJoint *joint = ((ISkinnedMesh *)Mesh)->getAllJoints()[g]; - for (u32 n=0;nChildren.size();++n) - { + for (u32 n = 0; n < joint->Children.size(); ++n) { driver->draw3DLine(joint->GlobalAnimatedMatrix.getTranslation(), joint->Children[n]->GlobalAnimatedMatrix.getTranslation(), - video::SColor(255,51,66,255)); + video::SColor(255, 51, 66, 255)); } } } } // show mesh - if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY) - { + if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY) { debug_mat.Lighting = false; debug_mat.Wireframe = true; debug_mat.ZBuffer = video::ECFN_DISABLED; driver->setMaterial(debug_mat); - for (u32 g=0; ggetMeshBufferCount(); ++g) - { - const IMeshBuffer* mb = m->getMeshBuffer(g); + for (u32 g = 0; g < m->getMeshBufferCount(); ++g) { + const IMeshBuffer *mb = m->getMeshBuffer(g); if (RenderFromIdentity) - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix ); + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); else if (Mesh->getMeshType() == EAMT_SKINNED) - driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer*)mb)->Transformation); + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation * ((SSkinMeshBuffer *)mb)->Transformation); driver->drawMeshBuffer(mb); } } } } - //! Returns the current start frame number. s32 CAnimatedMeshSceneNode::getStartFrame() const { return StartFrame; } - //! Returns the current start frame number. s32 CAnimatedMeshSceneNode::getEndFrame() const { return EndFrame; } - //! sets the frames between the animation is looped. //! the default is 0 - MaximalFrameCount of the mesh. bool CAnimatedMeshSceneNode::setFrameLoop(s32 begin, s32 end) { const s32 maxFrameCount = Mesh->getFrameCount() - 1; - if (end < begin) - { + if (end < begin) { StartFrame = core::s32_clamp(end, 0, maxFrameCount); EndFrame = core::s32_clamp(begin, StartFrame, maxFrameCount); - } - else - { + } else { StartFrame = core::s32_clamp(begin, 0, maxFrameCount); EndFrame = core::s32_clamp(end, StartFrame, maxFrameCount); } @@ -418,29 +369,25 @@ bool CAnimatedMeshSceneNode::setFrameLoop(s32 begin, s32 end) return true; } - //! sets the speed with witch the animation is played void CAnimatedMeshSceneNode::setAnimationSpeed(f32 framesPerSecond) { FramesPerSecond = framesPerSecond * 0.001f; } - f32 CAnimatedMeshSceneNode::getAnimationSpeed() const { return FramesPerSecond * 1000.f; } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CAnimatedMeshSceneNode::getBoundingBox() const +const core::aabbox3d &CAnimatedMeshSceneNode::getBoundingBox() const { return Box; } - //! returns the material based on the zero based index i. -video::SMaterial& CAnimatedMeshSceneNode::getMaterial(u32 i) +video::SMaterial &CAnimatedMeshSceneNode::getMaterial(u32 i) { if (i >= Materials.size()) return ISceneNode::getMaterial(i); @@ -448,39 +395,33 @@ video::SMaterial& CAnimatedMeshSceneNode::getMaterial(u32 i) return Materials[i]; } - - //! returns amount of materials used by this scene node. u32 CAnimatedMeshSceneNode::getMaterialCount() const { return Materials.size(); } - //! Returns a pointer to a child node, which has the same transformation as //! the corresponding joint, if the mesh in this scene node is a skinned mesh. -IBoneSceneNode* CAnimatedMeshSceneNode::getJointNode(const c8* jointName) +IBoneSceneNode *CAnimatedMeshSceneNode::getJointNode(const c8 *jointName) { - if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) - { + if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) { os::Printer::log("No mesh, or mesh not of skinned mesh type", ELL_WARNING); return 0; } checkJoints(); - ISkinnedMesh *skinnedMesh=(ISkinnedMesh*)Mesh; + ISkinnedMesh *skinnedMesh = (ISkinnedMesh *)Mesh; const std::optional number = skinnedMesh->getJointNumber(jointName); - if (!number.has_value()) - { + if (!number.has_value()) { os::Printer::log("Joint with specified name not found in skinned mesh", jointName, ELL_DEBUG); return 0; } - if (JointChildSceneNodes.size() <= *number) - { + if (JointChildSceneNodes.size() <= *number) { os::Printer::log("Joint was found in mesh, but is not loaded into node", jointName, ELL_WARNING); return 0; } @@ -488,22 +429,18 @@ IBoneSceneNode* CAnimatedMeshSceneNode::getJointNode(const c8* jointName) return JointChildSceneNodes[*number]; } - - //! Returns a pointer to a child node, which has the same transformation as //! the corresponding joint, if the mesh in this scene node is a skinned mesh. -IBoneSceneNode* CAnimatedMeshSceneNode::getJointNode(u32 jointID) +IBoneSceneNode *CAnimatedMeshSceneNode::getJointNode(u32 jointID) { - if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) - { + if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) { os::Printer::log("No mesh, or mesh not of skinned mesh type", ELL_WARNING); return 0; } checkJoints(); - if (JointChildSceneNodes.size() <= jointID) - { + if (JointChildSceneNodes.size() <= jointID) { os::Printer::log("Joint not loaded into node", ELL_WARNING); return 0; } @@ -517,26 +454,22 @@ u32 CAnimatedMeshSceneNode::getJointCount() const if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) return 0; - ISkinnedMesh *skinnedMesh=(ISkinnedMesh*)Mesh; + ISkinnedMesh *skinnedMesh = (ISkinnedMesh *)Mesh; return skinnedMesh->getJointCount(); } - //! Removes a child from this scene node. //! Implemented here, to be able to remove the shadow properly, if there is one, //! or to remove attached childs. -bool CAnimatedMeshSceneNode::removeChild(ISceneNode* child) +bool CAnimatedMeshSceneNode::removeChild(ISceneNode *child) { - if (ISceneNode::removeChild(child)) - { - if (JointsUsed) //stop weird bugs caused while changing parents as the joints are being created + if (ISceneNode::removeChild(child)) { + if (JointsUsed) // stop weird bugs caused while changing parents as the joints are being created { - for (u32 i=0; igrab(); } - //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. void CAnimatedMeshSceneNode::setReadOnlyMaterials(bool readonly) { ReadOnlyMaterials = readonly; } - //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style bool CAnimatedMeshSceneNode::isReadOnlyMaterials() const { return ReadOnlyMaterials; } - //! Sets a new mesh -void CAnimatedMeshSceneNode::setMesh(IAnimatedMesh* mesh) +void CAnimatedMeshSceneNode::setMesh(IAnimatedMesh *mesh) { if (!mesh) return; // won't set null mesh - if (Mesh != mesh) - { + if (Mesh != mesh) { if (Mesh) Mesh->drop(); @@ -613,15 +540,13 @@ void CAnimatedMeshSceneNode::setMesh(IAnimatedMesh* mesh) // get materials and bounding box Box = Mesh->getBoundingBox(); - IMesh* m = Mesh->getMesh(0,0); - if (m) - { + IMesh *m = Mesh->getMesh(0, 0); + if (m) { Materials.clear(); Materials.reallocate(m->getMeshBufferCount()); - for (u32 i=0; igetMeshBufferCount(); ++i) - { - IMeshBuffer* mb = m->getMeshBuffer(i); + for (u32 i = 0; i < m->getMeshBufferCount(); ++i) { + IMeshBuffer *mb = m->getMeshBuffer(i); if (mb) Materials.push_back(mb->getMaterial()); else @@ -630,18 +555,16 @@ void CAnimatedMeshSceneNode::setMesh(IAnimatedMesh* mesh) } // clean up joint nodes - if (JointsUsed) - { - JointsUsed=false; + if (JointsUsed) { + JointsUsed = false; checkJoints(); } // get start and begin time - setAnimationSpeed(Mesh->getAnimationSpeed()); // NOTE: This had been commented out (but not removed!) in r3526. Which caused meshloader-values for speed to be ignored unless users specified explicitly. Missing a test-case where this could go wrong so I put the code back in. - setFrameLoop(0, Mesh->getFrameCount()-1); + setAnimationSpeed(Mesh->getAnimationSpeed()); // NOTE: This had been commented out (but not removed!) in r3526. Which caused meshloader-values for speed to be ignored unless users specified explicitly. Missing a test-case where this could go wrong so I put the code back in. + setFrameLoop(0, Mesh->getFrameCount() - 1); } - //! updates the absolute position based on the relative and the parents position void CAnimatedMeshSceneNode::updateAbsolutePosition() { @@ -652,15 +575,15 @@ void CAnimatedMeshSceneNode::updateAbsolutePosition() void CAnimatedMeshSceneNode::setJointMode(E_JOINT_UPDATE_ON_RENDER mode) { checkJoints(); - JointMode=mode; + JointMode = mode; } //! Sets the transition time in seconds (note: This needs to enable joints, and setJointmode maybe set to 2) //! you must call animateJoints(), or the mesh will not animate void CAnimatedMeshSceneNode::setTransitionTime(f32 time) { - const u32 ttime = (u32)core::floor32(time*1000.0f); - if (TransitionTime==ttime) + const u32 ttime = (u32)core::floor32(time * 1000.0f); + if (TransitionTime == ttime) return; TransitionTime = ttime; if (ttime != 0) @@ -669,69 +592,63 @@ void CAnimatedMeshSceneNode::setTransitionTime(f32 time) setJointMode(EJUOR_NONE); } - //! render mesh ignoring its transformation. Used with ragdolls. (culling is unaffected) void CAnimatedMeshSceneNode::setRenderFromIdentity(bool enable) { - RenderFromIdentity=enable; + RenderFromIdentity = enable; } - //! updates the joint positions of this mesh void CAnimatedMeshSceneNode::animateJoints(bool CalculateAbsolutePositions) { - if (Mesh && Mesh->getMeshType() == EAMT_SKINNED ) - { + if (Mesh && Mesh->getMeshType() == EAMT_SKINNED) { checkJoints(); - const f32 frame = getFrameNr(); //old? + const f32 frame = getFrameNr(); // old? - CSkinnedMesh* skinnedMesh=static_cast(Mesh); + CSkinnedMesh *skinnedMesh = static_cast(Mesh); - skinnedMesh->transferOnlyJointsHintsToMesh( JointChildSceneNodes ); + skinnedMesh->transferOnlyJointsHintsToMesh(JointChildSceneNodes); skinnedMesh->animateMesh(frame, 1.0f); - skinnedMesh->recoverJointsFromMesh( JointChildSceneNodes); + skinnedMesh->recoverJointsFromMesh(JointChildSceneNodes); //----------------------------------------- // Transition //----------------------------------------- - if (Transiting != 0.f) - { + if (Transiting != 0.f) { // Init additional matrices - if (PretransitingSave.size()setPosition( core::lerp( - PretransitingSave[n].getTranslation(), - JointChildSceneNodes[n]->getPosition(), - TransitingBlend)); + PretransitingSave[n].getTranslation(), + JointChildSceneNodes[n]->getPosition(), + TransitingBlend)); //------Rotation------ - //Code is slow, needs to be fixed up + // Code is slow, needs to be fixed up - const core::quaternion RotationStart(PretransitingSave[n].getRotationDegrees()*core::DEGTORAD); - const core::quaternion RotationEnd(JointChildSceneNodes[n]->getRotation()*core::DEGTORAD); + const core::quaternion RotationStart(PretransitingSave[n].getRotationDegrees() * core::DEGTORAD); + const core::quaternion RotationEnd(JointChildSceneNodes[n]->getRotation() * core::DEGTORAD); core::quaternion QRotation; QRotation.slerp(RotationStart, RotationEnd, TransitingBlend); core::vector3df tmpVector; QRotation.toEuler(tmpVector); - tmpVector*=core::RADTODEG; //convert from radians back to degrees - JointChildSceneNodes[n]->setRotation( tmpVector ); + tmpVector *= core::RADTODEG; // convert from radians back to degrees + JointChildSceneNodes[n]->setRotation(tmpVector); //------Scale------ - //JointChildSceneNodes[n]->setScale( + // JointChildSceneNodes[n]->setScale( // core::lerp( // PretransitingSave[n].getScale(), // JointChildSceneNodes[n]->getScale(), @@ -739,14 +656,11 @@ void CAnimatedMeshSceneNode::animateJoints(bool CalculateAbsolutePositions) } } - if (CalculateAbsolutePositions) - { + if (CalculateAbsolutePositions) { //---slow--- - for (u32 n=0;ngetParent()==this) - { - JointChildSceneNodes[n]->updateAbsolutePositionOfAllChildren(); //temp, should be an option + for (u32 n = 0; n < JointChildSceneNodes.size(); ++n) { + if (JointChildSceneNodes[n]->getParent() == this) { + JointChildSceneNodes[n]->updateAbsolutePositionOfAllChildren(); // temp, should be an option } } } @@ -754,69 +668,64 @@ void CAnimatedMeshSceneNode::animateJoints(bool CalculateAbsolutePositions) } /*! -*/ + */ void CAnimatedMeshSceneNode::checkJoints() { if (!Mesh || Mesh->getMeshType() != EAMT_SKINNED) return; - if (!JointsUsed) - { - for (u32 i=0; iaddJoints(JointChildSceneNodes, this, SceneManager); - ((CSkinnedMesh*)Mesh)->recoverJointsFromMesh(JointChildSceneNodes); + // Create joints for SkinnedMesh + ((CSkinnedMesh *)Mesh)->addJoints(JointChildSceneNodes, this, SceneManager); + ((CSkinnedMesh *)Mesh)->recoverJointsFromMesh(JointChildSceneNodes); - JointsUsed=true; - JointMode=EJUOR_READ; + JointsUsed = true; + JointMode = EJUOR_READ; } } /*! -*/ + */ void CAnimatedMeshSceneNode::beginTransition() { if (!JointsUsed) return; - if (TransitionTime != 0) - { - //Check the array is big enough - if (PretransitingSave.size()getRelativeTransformation(); + // Copy the position of joints + for (u32 n = 0; n < JointChildSceneNodes.size(); ++n) + PretransitingSave[n] = JointChildSceneNodes[n]->getRelativeTransformation(); Transiting = core::reciprocal((f32)TransitionTime); } TransitingBlend = 0.f; } - /*! -*/ -ISceneNode* CAnimatedMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) + */ +ISceneNode *CAnimatedMeshSceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { if (!newParent) newParent = Parent; if (!newManager) newManager = SceneManager; - CAnimatedMeshSceneNode* newNode = - new CAnimatedMeshSceneNode(Mesh, NULL, newManager, ID, RelativeTranslation, - RelativeRotation, RelativeScale); + CAnimatedMeshSceneNode *newNode = + new CAnimatedMeshSceneNode(Mesh, NULL, newManager, ID, RelativeTranslation, + RelativeRotation, RelativeScale); - if (newParent) - { - newNode->setParent(newParent); // not in constructor because virtual overload for updateAbsolutePosition won't be called + if (newParent) { + newNode->setParent(newParent); // not in constructor because virtual overload for updateAbsolutePosition won't be called newNode->drop(); } @@ -847,6 +756,5 @@ ISceneNode* CAnimatedMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* return newNode; } - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CAnimatedMeshSceneNode.h b/source/Irrlicht/CAnimatedMeshSceneNode.h index 33a675ef..5d912c7f 100644 --- a/source/Irrlicht/CAnimatedMeshSceneNode.h +++ b/source/Irrlicht/CAnimatedMeshSceneNode.h @@ -9,173 +9,169 @@ #include "matrix4.h" - namespace irr { namespace scene { - class IDummyTransformationSceneNode; +class IDummyTransformationSceneNode; - class CAnimatedMeshSceneNode : public IAnimatedMeshSceneNode - { - public: +class CAnimatedMeshSceneNode : public IAnimatedMeshSceneNode +{ +public: + //! constructor + CAnimatedMeshSceneNode(IAnimatedMesh *mesh, ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f)); - //! constructor - CAnimatedMeshSceneNode(IAnimatedMesh* mesh, ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)); + //! destructor + virtual ~CAnimatedMeshSceneNode(); - //! destructor - virtual ~CAnimatedMeshSceneNode(); + //! sets the current frame. from now on the animation is played from this frame. + void setCurrentFrame(f32 frame) override; - //! sets the current frame. from now on the animation is played from this frame. - void setCurrentFrame(f32 frame) override; + //! frame + void OnRegisterSceneNode() override; - //! frame - void OnRegisterSceneNode() override; + //! OnAnimate() is called just before rendering the whole scene. + void OnAnimate(u32 timeMs) override; - //! OnAnimate() is called just before rendering the whole scene. - void OnAnimate(u32 timeMs) override; + //! renders the node. + void render() override; - //! renders the node. - void render() override; + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! sets the frames between the animation is looped. + //! the default is 0 - MaximalFrameCount of the mesh. + //! NOTE: setMesh will also change this value and set it to the full range of animations of the mesh + bool setFrameLoop(s32 begin, s32 end) override; - //! sets the frames between the animation is looped. - //! the default is 0 - MaximalFrameCount of the mesh. - //! NOTE: setMesh will also change this value and set it to the full range of animations of the mesh - bool setFrameLoop(s32 begin, s32 end) override; + //! Sets looping mode which is on by default. If set to false, + //! animations will not be looped. + void setLoopMode(bool playAnimationLooped) override; - //! Sets looping mode which is on by default. If set to false, - //! animations will not be looped. - void setLoopMode(bool playAnimationLooped) override; + //! returns the current loop mode + bool getLoopMode() const override; - //! returns the current loop mode - bool getLoopMode() const override; + //! Sets a callback interface which will be called if an animation + //! playback has ended. Set this to 0 to disable the callback again. + void setAnimationEndCallback(IAnimationEndCallBack *callback = 0) override; - //! Sets a callback interface which will be called if an animation - //! playback has ended. Set this to 0 to disable the callback again. - void setAnimationEndCallback(IAnimationEndCallBack* callback=0) override; + //! sets the speed with which the animation is played + //! NOTE: setMesh will also change this value and set it to the default speed of the mesh + void setAnimationSpeed(f32 framesPerSecond) override; - //! sets the speed with which the animation is played - //! NOTE: setMesh will also change this value and set it to the default speed of the mesh - void setAnimationSpeed(f32 framesPerSecond) override; + //! gets the speed with which the animation is played + f32 getAnimationSpeed() const override; - //! gets the speed with which the animation is played - f32 getAnimationSpeed() const override; + //! returns the material based on the zero based index i. To get the amount + //! of materials used by this scene node, use getMaterialCount(). + //! This function is needed for inserting the node into the scene hierarchy on a + //! optimal position for minimizing renderstate changes, but can also be used + //! to directly modify the material of a scene node. + video::SMaterial &getMaterial(u32 i) override; - //! returns the material based on the zero based index i. To get the amount - //! of materials used by this scene node, use getMaterialCount(). - //! This function is needed for inserting the node into the scene hierarchy on a - //! optimal position for minimizing renderstate changes, but can also be used - //! to directly modify the material of a scene node. - video::SMaterial& getMaterial(u32 i) override; + //! returns amount of materials used by this scene node. + u32 getMaterialCount() const override; - //! returns amount of materials used by this scene node. - u32 getMaterialCount() const override; + //! Returns a pointer to a child node, which has the same transformation as + //! the corresponding joint, if the mesh in this scene node is a skinned mesh. + IBoneSceneNode *getJointNode(const c8 *jointName) override; - //! Returns a pointer to a child node, which has the same transformation as - //! the corresponding joint, if the mesh in this scene node is a skinned mesh. - IBoneSceneNode* getJointNode(const c8* jointName) override; + //! same as getJointNode(const c8* jointName), but based on id + IBoneSceneNode *getJointNode(u32 jointID) override; - //! same as getJointNode(const c8* jointName), but based on id - IBoneSceneNode* getJointNode(u32 jointID) override; + //! Gets joint count. + u32 getJointCount() const override; - //! Gets joint count. - u32 getJointCount() const override; + //! Removes a child from this scene node. + //! Implemented here, to be able to remove the shadow properly, if there is one, + //! or to remove attached child. + bool removeChild(ISceneNode *child) override; - //! Removes a child from this scene node. - //! Implemented here, to be able to remove the shadow properly, if there is one, - //! or to remove attached child. - bool removeChild(ISceneNode* child) override; + //! Returns the current displayed frame number. + f32 getFrameNr() const override; + //! Returns the current start frame number. + s32 getStartFrame() const override; + //! Returns the current end frame number. + s32 getEndFrame() const override; - //! Returns the current displayed frame number. - f32 getFrameNr() const override; - //! Returns the current start frame number. - s32 getStartFrame() const override; - //! Returns the current end frame number. - s32 getEndFrame() const override; + //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. + /* In this way it is possible to change the materials a mesh causing all mesh scene nodes + referencing this mesh to change too. */ + void setReadOnlyMaterials(bool readonly) override; - //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. - /* In this way it is possible to change the materials a mesh causing all mesh scene nodes - referencing this mesh to change too. */ - void setReadOnlyMaterials(bool readonly) override; + //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style + bool isReadOnlyMaterials() const override; - //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style - bool isReadOnlyMaterials() const override; + //! Sets a new mesh + void setMesh(IAnimatedMesh *mesh) override; - //! Sets a new mesh - void setMesh(IAnimatedMesh* mesh) override; + //! Returns the current mesh + IAnimatedMesh *getMesh(void) override { return Mesh; } - //! Returns the current mesh - IAnimatedMesh* getMesh(void) override { return Mesh; } + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_ANIMATED_MESH; } - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_ANIMATED_MESH; } + //! updates the absolute position based on the relative and the parents position + void updateAbsolutePosition() override; - //! updates the absolute position based on the relative and the parents position - void updateAbsolutePosition() override; + //! Set the joint update mode (0-unused, 1-get joints only, 2-set joints only, 3-move and set) + void setJointMode(E_JOINT_UPDATE_ON_RENDER mode) override; + //! Sets the transition time in seconds (note: This needs to enable joints, and setJointmode maybe set to 2) + //! you must call animateJoints(), or the mesh will not animate + void setTransitionTime(f32 Time) override; - //! Set the joint update mode (0-unused, 1-get joints only, 2-set joints only, 3-move and set) - void setJointMode(E_JOINT_UPDATE_ON_RENDER mode) override; + //! updates the joint positions of this mesh + void animateJoints(bool CalculateAbsolutePositions = true) override; - //! Sets the transition time in seconds (note: This needs to enable joints, and setJointmode maybe set to 2) - //! you must call animateJoints(), or the mesh will not animate - void setTransitionTime(f32 Time) override; + //! render mesh ignoring its transformation. Used with ragdolls. (culling is unaffected) + void setRenderFromIdentity(bool On) override; - //! updates the joint positions of this mesh - void animateJoints(bool CalculateAbsolutePositions=true) override; + //! Creates a clone of this scene node and its children. + /** \param newParent An optional new parent. + \param newManager An optional new scene manager. + \return The newly created clone of this node. */ + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; - //! render mesh ignoring its transformation. Used with ragdolls. (culling is unaffected) - void setRenderFromIdentity( bool On ) override; +private: + //! Get a static mesh for the current frame of this animated mesh + IMesh *getMeshForCurrentFrame(); - //! Creates a clone of this scene node and its children. - /** \param newParent An optional new parent. - \param newManager An optional new scene manager. - \return The newly created clone of this node. */ - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; + void buildFrameNr(u32 timeMs); + void checkJoints(); + void beginTransition(); - private: + core::array Materials; + core::aabbox3d Box; + IAnimatedMesh *Mesh; - //! Get a static mesh for the current frame of this animated mesh - IMesh* getMeshForCurrentFrame(); + s32 StartFrame; + s32 EndFrame; + f32 FramesPerSecond; + f32 CurrentFrameNr; - void buildFrameNr(u32 timeMs); - void checkJoints(); - void beginTransition(); + u32 LastTimeMs; + u32 TransitionTime; // Transition time in millisecs + f32 Transiting; // is mesh transiting (plus cache of TransitionTime) + f32 TransitingBlend; // 0-1, calculated on buildFrameNr - core::array Materials; - core::aabbox3d Box; - IAnimatedMesh* Mesh; + // 0-unused, 1-get joints only, 2-set joints only, 3-move and set + E_JOINT_UPDATE_ON_RENDER JointMode; + bool JointsUsed; - s32 StartFrame; - s32 EndFrame; - f32 FramesPerSecond; - f32 CurrentFrameNr; + bool Looping; + bool ReadOnlyMaterials; + bool RenderFromIdentity; - u32 LastTimeMs; - u32 TransitionTime; //Transition time in millisecs - f32 Transiting; //is mesh transiting (plus cache of TransitionTime) - f32 TransitingBlend; //0-1, calculated on buildFrameNr + IAnimationEndCallBack *LoopCallBack; + s32 PassCount; - //0-unused, 1-get joints only, 2-set joints only, 3-move and set - E_JOINT_UPDATE_ON_RENDER JointMode; - bool JointsUsed; - - bool Looping; - bool ReadOnlyMaterials; - bool RenderFromIdentity; - - IAnimationEndCallBack* LoopCallBack; - s32 PassCount; - - core::array JointChildSceneNodes; - core::array PretransitingSave; - }; + core::array JointChildSceneNodes; + core::array PretransitingSave; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CAttributeImpl.h b/source/Irrlicht/CAttributeImpl.h index 0e75652e..9065a734 100644 --- a/source/Irrlicht/CAttributeImpl.h +++ b/source/Irrlicht/CAttributeImpl.h @@ -20,8 +20,7 @@ namespace io class CBoolAttribute : public IAttribute { public: - - CBoolAttribute(const char* name, bool value) + CBoolAttribute(const char *name, bool value) { Name = name; setBool(value); @@ -69,8 +68,7 @@ public: class CIntAttribute : public IAttribute { public: - - CIntAttribute(const char* name, s32 value) + CIntAttribute(const char *name, s32 value) { Name = name; setInt(value); @@ -108,8 +106,7 @@ public: class CFloatAttribute : public IAttribute { public: - - CFloatAttribute(const char* name, f32 value) + CFloatAttribute(const char *name, f32 value) { Name = name; setFloat(value); diff --git a/source/Irrlicht/CAttributes.cpp b/source/Irrlicht/CAttributes.cpp index db39eaa1..2696d6bc 100644 --- a/source/Irrlicht/CAttributes.cpp +++ b/source/Irrlicht/CAttributes.cpp @@ -12,12 +12,12 @@ namespace irr namespace io { -CAttributes::CAttributes(video::IVideoDriver* driver) -: Driver(driver) +CAttributes::CAttributes(video::IVideoDriver *driver) : + Driver(driver) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CAttributes"); - #endif +#endif if (Driver) Driver->grab(); @@ -31,30 +31,28 @@ CAttributes::~CAttributes() Driver->drop(); } - //! Removes all attributes void CAttributes::clear() { - for (u32 i=0; idrop(); Attributes.clear(); } //! Returns attribute index from name, -1 if not found -s32 CAttributes::findAttribute(const c8* attributeName) const +s32 CAttributes::findAttribute(const c8 *attributeName) const { - for (u32 i=0; iName == attributeName) return i; return -1; } - -IAttribute* CAttributes::getAttributeP(const c8* attributeName) const +IAttribute *CAttributes::getAttributeP(const c8 *attributeName) const { - for (u32 i=0; iName == attributeName) return Attributes[i]; @@ -62,13 +60,12 @@ IAttribute* CAttributes::getAttributeP(const c8* attributeName) const } //! Sets a attribute as boolean value -void CAttributes::setAttribute(const c8* attributeName, bool value) +void CAttributes::setAttribute(const c8 *attributeName, bool value) { - IAttribute* att = getAttributeP(attributeName); + IAttribute *att = getAttributeP(attributeName); if (att) att->setBool(value); - else - { + else { Attributes.push_back(new CBoolAttribute(attributeName, value)); } } @@ -77,9 +74,9 @@ void CAttributes::setAttribute(const c8* attributeName, bool value) //! \param attributeName: Name of the attribute to get. //! \return Returns value of the attribute previously set by setAttribute() as bool //! or 0 if attribute is not set. -bool CAttributes::getAttributeAsBool(const c8* attributeName, bool defaultNotFound) const +bool CAttributes::getAttributeAsBool(const c8 *attributeName, bool defaultNotFound) const { - const IAttribute* att = getAttributeP(attributeName); + const IAttribute *att = getAttributeP(attributeName); if (att) return att->getBool(); else @@ -87,13 +84,12 @@ bool CAttributes::getAttributeAsBool(const c8* attributeName, bool defaultNotFou } //! Sets a attribute as integer value -void CAttributes::setAttribute(const c8* attributeName, s32 value) +void CAttributes::setAttribute(const c8 *attributeName, s32 value) { - IAttribute* att = getAttributeP(attributeName); + IAttribute *att = getAttributeP(attributeName); if (att) att->setInt(value); - else - { + else { Attributes.push_back(new CIntAttribute(attributeName, value)); } } @@ -102,9 +98,9 @@ void CAttributes::setAttribute(const c8* attributeName, s32 value) //! \param attributeName: Name of the attribute to get. //! \return Returns value of the attribute previously set by setAttribute() as integer //! or 0 if attribute is not set. -s32 CAttributes::getAttributeAsInt(const c8* attributeName, irr::s32 defaultNotFound) const +s32 CAttributes::getAttributeAsInt(const c8 *attributeName, irr::s32 defaultNotFound) const { - const IAttribute* att = getAttributeP(attributeName); + const IAttribute *att = getAttributeP(attributeName); if (att) return att->getInt(); else @@ -112,9 +108,9 @@ s32 CAttributes::getAttributeAsInt(const c8* attributeName, irr::s32 defaultNotF } //! Sets a attribute as float value -void CAttributes::setAttribute(const c8* attributeName, f32 value) +void CAttributes::setAttribute(const c8 *attributeName, f32 value) { - IAttribute* att = getAttributeP(attributeName); + IAttribute *att = getAttributeP(attributeName); if (att) att->setFloat(value); else @@ -125,9 +121,9 @@ void CAttributes::setAttribute(const c8* attributeName, f32 value) //! \param attributeName: Name of the attribute to get. //! \return Returns value of the attribute previously set by setAttribute() as float value //! or 0 if attribute is not set. -f32 CAttributes::getAttributeAsFloat(const c8* attributeName, irr::f32 defaultNotFound) const +f32 CAttributes::getAttributeAsFloat(const c8 *attributeName, irr::f32 defaultNotFound) const { - const IAttribute* att = getAttributeP(attributeName); + const IAttribute *att = getAttributeP(attributeName); if (att) return att->getFloat(); @@ -142,7 +138,7 @@ u32 CAttributes::getAttributeCount() const //! Returns string attribute name by index. //! \param index: Index value, must be between 0 and getStringAttributeCount()-1. -const c8* CAttributes::getAttributeName(s32 index) const +const c8 *CAttributes::getAttributeName(s32 index) const { if ((u32)index >= Attributes.size()) return 0; @@ -151,11 +147,11 @@ const c8* CAttributes::getAttributeName(s32 index) const } //! Returns the type of an attribute -E_ATTRIBUTE_TYPE CAttributes::getAttributeType(const c8* attributeName) const +E_ATTRIBUTE_TYPE CAttributes::getAttributeType(const c8 *attributeName) const { E_ATTRIBUTE_TYPE ret = EAT_UNKNOWN; - const IAttribute* att = getAttributeP(attributeName); + const IAttribute *att = getAttributeP(attributeName); if (att) ret = att->getType(); @@ -205,25 +201,25 @@ bool CAttributes::getAttributeAsBool(s32 index) const } //! Adds an attribute as integer -void CAttributes::addInt(const c8* attributeName, s32 value) +void CAttributes::addInt(const c8 *attributeName, s32 value) { Attributes.push_back(new CIntAttribute(attributeName, value)); } //! Adds an attribute as float -void CAttributes::addFloat(const c8* attributeName, f32 value) +void CAttributes::addFloat(const c8 *attributeName, f32 value) { Attributes.push_back(new CFloatAttribute(attributeName, value)); } //! Adds an attribute as bool -void CAttributes::addBool(const c8* attributeName, bool value) +void CAttributes::addBool(const c8 *attributeName, bool value) { Attributes.push_back(new CBoolAttribute(attributeName, value)); } //! Returns if an attribute with a name exists -bool CAttributes::existsAttribute(const c8* attributeName) const +bool CAttributes::existsAttribute(const c8 *attributeName) const { return getAttributeP(attributeName) != 0; } @@ -251,4 +247,3 @@ void CAttributes::setAttribute(s32 index, f32 value) } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CAttributes.h b/source/Irrlicht/CAttributes.h index 83c27a54..0fe2739b 100644 --- a/source/Irrlicht/CAttributes.h +++ b/source/Irrlicht/CAttributes.h @@ -11,19 +11,17 @@ namespace irr { namespace video { - class ITexture; - class IVideoDriver; +class ITexture; +class IVideoDriver; } namespace io { - //! Implementation of the IAttributes interface class CAttributes : public IAttributes { public: - - CAttributes(video::IVideoDriver* driver=0); + CAttributes(video::IVideoDriver *driver = 0); ~CAttributes(); //! Returns amount of attributes in this collection of attributes. @@ -31,26 +29,25 @@ public: //! Returns attribute name by index. //! \param index: Index value, must be between 0 and getAttributeCount()-1. - const c8* getAttributeName(s32 index) const override; + const c8 *getAttributeName(s32 index) const override; //! Returns the type of an attribute //! \param attributeName: Name for the attribute - E_ATTRIBUTE_TYPE getAttributeType(const c8* attributeName) const override; + E_ATTRIBUTE_TYPE getAttributeType(const c8 *attributeName) const override; //! Returns attribute type by index. //! \param index: Index value, must be between 0 and getAttributeCount()-1. E_ATTRIBUTE_TYPE getAttributeType(s32 index) const override; //! Returns if an attribute with a name exists - bool existsAttribute(const c8* attributeName) const override; + bool existsAttribute(const c8 *attributeName) const override; //! Returns attribute index from name, -1 if not found - s32 findAttribute(const c8* attributeName) const override; + s32 findAttribute(const c8 *attributeName) const override; //! Removes all attributes void clear() override; - /* Integer Attribute @@ -58,16 +55,16 @@ public: */ //! Adds an attribute as integer - void addInt(const c8* attributeName, s32 value) override; + void addInt(const c8 *attributeName, s32 value) override; //! Sets an attribute as integer value - void setAttribute(const c8* attributeName, s32 value) override; + void setAttribute(const c8 *attributeName, s32 value) override; //! Gets an attribute as integer value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - s32 getAttributeAsInt(const c8* attributeName, irr::s32 defaultNotFound=0) const override; + s32 getAttributeAsInt(const c8 *attributeName, irr::s32 defaultNotFound = 0) const override; //! Gets an attribute as integer value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -83,16 +80,16 @@ public: */ //! Adds an attribute as float - void addFloat(const c8* attributeName, f32 value) override; + void addFloat(const c8 *attributeName, f32 value) override; //! Sets a attribute as float value - void setAttribute(const c8* attributeName, f32 value) override; + void setAttribute(const c8 *attributeName, f32 value) override; //! Gets an attribute as float value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - f32 getAttributeAsFloat(const c8* attributeName, irr::f32 defaultNotFound=0.f) const override; + f32 getAttributeAsFloat(const c8 *attributeName, irr::f32 defaultNotFound = 0.f) const override; //! Gets an attribute as float value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -101,22 +98,21 @@ public: //! Sets an attribute as float value void setAttribute(s32 index, f32 value) override; - /* Bool Attribute */ //! Adds an attribute as bool - void addBool(const c8* attributeName, bool value) override; + void addBool(const c8 *attributeName, bool value) override; //! Sets an attribute as boolean value - void setAttribute(const c8* attributeName, bool value) override; + void setAttribute(const c8 *attributeName, bool value) override; //! Gets an attribute as boolean value //! \param attributeName: Name of the attribute to get. //! \param defaultNotFound Value returned when attributeName was not found //! \return Returns value of the attribute previously set by setAttribute() - bool getAttributeAsBool(const c8* attributeName, bool defaultNotFound=false) const override; + bool getAttributeAsBool(const c8 *attributeName, bool defaultNotFound = false) const override; //! Gets an attribute as boolean value //! \param index: Index value, must be between 0 and getAttributeCount()-1. @@ -126,14 +122,12 @@ public: void setAttribute(s32 index, bool value) override; protected: + core::array Attributes; - core::array Attributes; + IAttribute *getAttributeP(const c8 *attributeName) const; - IAttribute* getAttributeP(const c8* attributeName) const; - - video::IVideoDriver* Driver; + video::IVideoDriver *Driver; }; } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CB3DMeshFileLoader.cpp b/source/Irrlicht/CB3DMeshFileLoader.cpp index 59f35fda..c66c950e 100644 --- a/source/Irrlicht/CB3DMeshFileLoader.cpp +++ b/source/Irrlicht/CB3DMeshFileLoader.cpp @@ -24,29 +24,27 @@ namespace scene { //! Constructor -CB3DMeshFileLoader::CB3DMeshFileLoader(scene::ISceneManager* smgr) -: AnimatedMesh(0), B3DFile(0), VerticesStart(0), NormalsInFile(false), - HasVertexColors(false), ShowWarning(true) +CB3DMeshFileLoader::CB3DMeshFileLoader(scene::ISceneManager *smgr) : + AnimatedMesh(0), B3DFile(0), VerticesStart(0), NormalsInFile(false), + HasVertexColors(false), ShowWarning(true) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CB3DMeshFileLoader"); - #endif +#endif } - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") -bool CB3DMeshFileLoader::isALoadableFileExtension(const io::path& filename) const +bool CB3DMeshFileLoader::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "b3d" ); + return core::hasFileExtension(filename, "b3d"); } - //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. -IAnimatedMesh* CB3DMeshFileLoader::createMesh(io::IReadFile* file) +IAnimatedMesh *CB3DMeshFileLoader::createMesh(io::IReadFile *file) { if (!file) return 0; @@ -54,14 +52,11 @@ IAnimatedMesh* CB3DMeshFileLoader::createMesh(io::IReadFile* file) B3DFile = file; AnimatedMesh = new scene::CSkinnedMesh(); ShowWarning = true; // If true a warning is issued if too many textures are used - VerticesStart=0; + VerticesStart = 0; - if ( load() ) - { + if (load()) { AnimatedMesh->finalize(); - } - else - { + } else { AnimatedMesh->drop(); AnimatedMesh = 0; } @@ -69,13 +64,12 @@ IAnimatedMesh* CB3DMeshFileLoader::createMesh(io::IReadFile* file) return AnimatedMesh; } - bool CB3DMeshFileLoader::load() { B3dStack.clear(); - NormalsInFile=false; - HasVertexColors=false; + NormalsInFile = false; + HasVertexColors = false; //------ Get header ------ @@ -85,14 +79,13 @@ bool CB3DMeshFileLoader::load() header.size = os::Byteswap::byteswap(header.size); #endif - if ( strncmp( header.name, "BB3D", 4 ) != 0 ) - { + if (strncmp(header.name, "BB3D", 4) != 0) { os::Printer::log("File is not a b3d file. Loading failed (No header found)", B3DFile->getFileName(), ELL_ERROR); return false; } // Add main chunk... - B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8)); + B3dStack.push_back(SB3dChunk(header, B3DFile->getPos() - 8)); // Get file version, but ignore it, as it's not important with b3d files... s32 fileVersion; @@ -103,35 +96,27 @@ bool CB3DMeshFileLoader::load() //------ Read main chunk ------ - while ( (B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos() ) - { + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) { B3DFile->read(&header, sizeof(header)); #ifdef __BIG_ENDIAN__ header.size = os::Byteswap::byteswap(header.size); #endif - B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8)); + B3dStack.push_back(SB3dChunk(header, B3DFile->getPos() - 8)); - if ( strncmp( B3dStack.getLast().name, "TEXS", 4 ) == 0 ) - { + if (strncmp(B3dStack.getLast().name, "TEXS", 4) == 0) { if (!readChunkTEXS()) return false; - } - else if ( strncmp( B3dStack.getLast().name, "BRUS", 4 ) == 0 ) - { + } else if (strncmp(B3dStack.getLast().name, "BRUS", 4) == 0) { if (!readChunkBRUS()) return false; - } - else if ( strncmp( B3dStack.getLast().name, "NODE", 4 ) == 0 ) - { - if (!readChunkNODE((CSkinnedMesh::SJoint*)0) ) + } else if (strncmp(B3dStack.getLast().name, "NODE", 4) == 0) { + if (!readChunkNODE((CSkinnedMesh::SJoint *)0)) return false; - } - else - { + } else { os::Printer::log("Unknown chunk found in mesh base - skipping"); if (!B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length)) return false; - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); } } @@ -147,7 +132,6 @@ bool CB3DMeshFileLoader::load() return true; } - bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint) { CSkinnedMesh::SJoint *joint = AnimatedMesh->addJoint(inJoint); @@ -155,7 +139,7 @@ bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint) #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkNODE"; os::Printer::log(logStr.c_str(), joint->Name.value_or("").c_str(), ELL_DEBUG); @@ -167,16 +151,16 @@ bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint) readFloats(scale, 3); readFloats(rotation, 4); - joint->Animatedposition = core::vector3df(position[0],position[1],position[2]) ; - joint->Animatedscale = core::vector3df(scale[0],scale[1],scale[2]); + joint->Animatedposition = core::vector3df(position[0], position[1], position[2]); + joint->Animatedscale = core::vector3df(scale[0], scale[1], scale[2]); joint->Animatedrotation = core::quaternion(rotation[1], rotation[2], rotation[3], rotation[0]); - //Build LocalMatrix: + // Build LocalMatrix: core::matrix4 positionMatrix; - positionMatrix.setTranslation( joint->Animatedposition ); + positionMatrix.setTranslation(joint->Animatedposition); core::matrix4 scaleMatrix; - scaleMatrix.setScale( joint->Animatedscale ); + scaleMatrix.setScale(joint->Animatedscale); core::matrix4 rotationMatrix; joint->Animatedrotation.getMatrix_transposed(rotationMatrix); @@ -187,7 +171,7 @@ bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint) else joint->GlobalMatrix = joint->LocalMatrix; - while(B3dStack.getLast().startposition + B3dStack.getLast().length > B3DFile->getPos()) // this chunk repeats + while (B3dStack.getLast().startposition + B3dStack.getLast().length > B3DFile->getPos()) // this chunk repeats { SB3dChunkHeader header; B3DFile->read(&header, sizeof(header)); @@ -195,54 +179,42 @@ bool CB3DMeshFileLoader::readChunkNODE(CSkinnedMesh::SJoint *inJoint) header.size = os::Byteswap::byteswap(header.size); #endif - B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8)); + B3dStack.push_back(SB3dChunk(header, B3DFile->getPos() - 8)); - if ( strncmp( B3dStack.getLast().name, "NODE", 4 ) == 0 ) - { + if (strncmp(B3dStack.getLast().name, "NODE", 4) == 0) { if (!readChunkNODE(joint)) return false; - } - else if ( strncmp( B3dStack.getLast().name, "MESH", 4 ) == 0 ) - { - VerticesStart=BaseVertices.size(); + } else if (strncmp(B3dStack.getLast().name, "MESH", 4) == 0) { + VerticesStart = BaseVertices.size(); if (!readChunkMESH(joint)) return false; - } - else if ( strncmp( B3dStack.getLast().name, "BONE", 4 ) == 0 ) - { + } else if (strncmp(B3dStack.getLast().name, "BONE", 4) == 0) { if (!readChunkBONE(joint)) return false; - } - else if ( strncmp( B3dStack.getLast().name, "KEYS", 4 ) == 0 ) - { - if(!readChunkKEYS(joint)) + } else if (strncmp(B3dStack.getLast().name, "KEYS", 4) == 0) { + if (!readChunkKEYS(joint)) return false; - } - else if ( strncmp( B3dStack.getLast().name, "ANIM", 4 ) == 0 ) - { + } else if (strncmp(B3dStack.getLast().name, "ANIM", 4) == 0) { if (!readChunkANIM()) return false; - } - else - { + } else { os::Printer::log("Unknown chunk found in node chunk - skipping"); if (!B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length)) return false; - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); } } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkMESH(CSkinnedMesh::SJoint *inJoint) { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkMESH"; os::Printer::log(logStr.c_str(), ELL_DEBUG); @@ -254,10 +226,10 @@ bool CB3DMeshFileLoader::readChunkMESH(CSkinnedMesh::SJoint *inJoint) brushID = os::Byteswap::byteswap(brushID); #endif - NormalsInFile=false; - HasVertexColors=false; + NormalsInFile = false; + HasVertexColors = false; - while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { SB3dChunkHeader header; B3DFile->read(&header, sizeof(header)); @@ -265,69 +237,56 @@ bool CB3DMeshFileLoader::readChunkMESH(CSkinnedMesh::SJoint *inJoint) header.size = os::Byteswap::byteswap(header.size); #endif - B3dStack.push_back(SB3dChunk(header, B3DFile->getPos()-8)); + B3dStack.push_back(SB3dChunk(header, B3DFile->getPos() - 8)); - if ( strncmp( B3dStack.getLast().name, "VRTS", 4 ) == 0 ) - { + if (strncmp(B3dStack.getLast().name, "VRTS", 4) == 0) { if (!readChunkVRTS(inJoint)) return false; - } - else if ( strncmp( B3dStack.getLast().name, "TRIS", 4 ) == 0 ) - { + } else if (strncmp(B3dStack.getLast().name, "TRIS", 4) == 0) { scene::SSkinMeshBuffer *meshBuffer = AnimatedMesh->addMeshBuffer(); - if (brushID == -1) - { /* ok */ } - else if (brushID < 0 || (u32)brushID >= Materials.size()) - { + if (brushID == -1) { /* ok */ + } else if (brushID < 0 || (u32)brushID >= Materials.size()) { os::Printer::log("Illegal brush ID found", B3DFile->getFileName(), ELL_ERROR); return false; - } - else - { - meshBuffer->Material=Materials[brushID].Material; + } else { + meshBuffer->Material = Materials[brushID].Material; } - if(readChunkTRIS(meshBuffer,AnimatedMesh->getMeshBuffers().size()-1, VerticesStart)==false) + if (readChunkTRIS(meshBuffer, AnimatedMesh->getMeshBuffers().size() - 1, VerticesStart) == false) return false; - if (!NormalsInFile) - { + if (!NormalsInFile) { s32 i; - for ( i=0; i<(s32)meshBuffer->Indices.size(); i+=3) - { - core::plane3df p(meshBuffer->getVertex(meshBuffer->Indices[i+0])->Pos, - meshBuffer->getVertex(meshBuffer->Indices[i+1])->Pos, - meshBuffer->getVertex(meshBuffer->Indices[i+2])->Pos); + for (i = 0; i < (s32)meshBuffer->Indices.size(); i += 3) { + core::plane3df p(meshBuffer->getVertex(meshBuffer->Indices[i + 0])->Pos, + meshBuffer->getVertex(meshBuffer->Indices[i + 1])->Pos, + meshBuffer->getVertex(meshBuffer->Indices[i + 2])->Pos); - meshBuffer->getVertex(meshBuffer->Indices[i+0])->Normal += p.Normal; - meshBuffer->getVertex(meshBuffer->Indices[i+1])->Normal += p.Normal; - meshBuffer->getVertex(meshBuffer->Indices[i+2])->Normal += p.Normal; + meshBuffer->getVertex(meshBuffer->Indices[i + 0])->Normal += p.Normal; + meshBuffer->getVertex(meshBuffer->Indices[i + 1])->Normal += p.Normal; + meshBuffer->getVertex(meshBuffer->Indices[i + 2])->Normal += p.Normal; } - for ( i = 0; i<(s32)meshBuffer->getVertexCount(); ++i ) - { + for (i = 0; i < (s32)meshBuffer->getVertexCount(); ++i) { meshBuffer->getVertex(i)->Normal.normalize(); - BaseVertices[VerticesStart+i].Normal=meshBuffer->getVertex(i)->Normal; + BaseVertices[VerticesStart + i].Normal = meshBuffer->getVertex(i)->Normal; } } - } - else - { + } else { os::Printer::log("Unknown chunk found in mesh - skipping"); if (!B3DFile->seek(B3dStack.getLast().startposition + B3dStack.getLast().length)) return false; - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); } } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - /* VRTS: int flags ;1=normal values present, 2=rgba values present @@ -345,7 +304,7 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "ChunkVRTS"; os::Printer::log(logStr.c_str(), ELL_DEBUG); @@ -364,7 +323,7 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) #endif if (tex_coord_sets < 0 || tex_coord_set_size < 0 || - tex_coord_sets >= max_tex_coords || tex_coord_set_size >= 4) // Something is wrong + tex_coord_sets >= max_tex_coords || tex_coord_set_size >= 4) // Something is wrong { os::Printer::log("tex_coord_sets or tex_coord_set_size too big", B3DFile->getFileName(), ELL_ERROR); return false; @@ -374,18 +333,16 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) s32 numberOfReads = 3; - if (flags & 1) - { + if (flags & 1) { NormalsInFile = true; numberOfReads += 3; } - if (flags & 2) - { + if (flags & 2) { numberOfReads += 4; - HasVertexColors=true; + HasVertexColors = true; } - numberOfReads += tex_coord_sets*tex_coord_set_size; + numberOfReads += tex_coord_sets * tex_coord_set_size; const s32 memoryNeeded = (B3dStack.getLast().length / sizeof(f32)) / numberOfReads; @@ -394,11 +351,11 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) //--------------------------------------------// - while( (B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { f32 position[3]; - f32 normal[3]={0.f, 0.f, 0.f}; - f32 color[4]={1.0f, 1.0f, 1.0f, 1.0f}; + f32 normal[3] = {0.f, 0.f, 0.f}; + f32 color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; f32 tex_coords[max_tex_coords][4]; readFloats(position, 3); @@ -408,21 +365,19 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) if (flags & 2) readFloats(color, 4); - for (s32 i=0; i= 1 && tex_coord_set_size >= 2) - { - tu=tex_coords[0][0]; - tv=tex_coords[0][1]; + f32 tu = 0.0f, tv = 0.0f; + if (tex_coord_sets >= 1 && tex_coord_set_size >= 2) { + tu = tex_coords[0][0]; + tv = tex_coords[0][1]; } - f32 tu2=0.0f, tv2=0.0f; - if (tex_coord_sets>1 && tex_coord_set_size>1) - { - tu2=tex_coords[1][0]; - tv2=tex_coords[1][1]; + f32 tu2 = 0.0f, tv2 = 0.0f; + if (tex_coord_sets > 1 && tex_coord_set_size > 1) { + tu2 = tex_coords[1][0]; + tv2 = tex_coords[1][1]; } // Create Vertex... @@ -435,30 +390,29 @@ bool CB3DMeshFileLoader::readChunkVRTS(CSkinnedMesh::SJoint *inJoint) inJoint->GlobalMatrix.transformVect(Vertex.Pos); inJoint->GlobalMatrix.rotateVect(Vertex.Normal); - //Add it... + // Add it... BaseVertices.push_back(Vertex); AnimatedVertices_VertexID.push_back(-1); AnimatedVertices_BufferID.push_back(-1); } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 meshBufferID, s32 vertices_Start) { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "ChunkTRIS"; os::Printer::log(logStr.c_str(), ELL_DEBUG); #endif - bool showVertexWarning=false; + bool showVertexWarning = false; s32 triangle_brush_id; // Note: Irrlicht can't have different brushes for each triangle (using a workaround) B3DFile->read(&triangle_brush_id, sizeof(triangle_brush_id)); @@ -470,13 +424,10 @@ bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 m if (triangle_brush_id == -1) B3dMaterial = 0; - else if (triangle_brush_id < 0 || (u32)triangle_brush_id >= Materials.size()) - { + else if (triangle_brush_id < 0 || (u32)triangle_brush_id >= Materials.size()) { os::Printer::log("Illegal material index found", B3DFile->getFileName(), ELL_ERROR); return false; - } - else - { + } else { B3dMaterial = &Materials[triangle_brush_id]; meshBuffer->Material = B3dMaterial->Material; } @@ -484,68 +435,63 @@ bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 m const s32 memoryNeeded = B3dStack.getLast().length / sizeof(s32); meshBuffer->Indices.reallocate(memoryNeeded + meshBuffer->Indices.size() + 1); - while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { s32 vertex_id[3]; - B3DFile->read(vertex_id, 3*sizeof(s32)); + B3DFile->read(vertex_id, 3 * sizeof(s32)); #ifdef __BIG_ENDIAN__ vertex_id[0] = os::Byteswap::byteswap(vertex_id[0]); vertex_id[1] = os::Byteswap::byteswap(vertex_id[1]); vertex_id[2] = os::Byteswap::byteswap(vertex_id[2]); #endif - //Make Ids global: + // Make Ids global: vertex_id[0] += vertices_Start; vertex_id[1] += vertices_Start; vertex_id[2] += vertices_Start; - for(s32 i=0; i<3; ++i) - { - if ((u32)vertex_id[i] >= AnimatedVertices_VertexID.size()) - { + for (s32 i = 0; i < 3; ++i) { + if ((u32)vertex_id[i] >= AnimatedVertices_VertexID.size()) { os::Printer::log("Illegal vertex index found", B3DFile->getFileName(), ELL_ERROR); return false; } - if (AnimatedVertices_VertexID[ vertex_id[i] ] != -1) - { - if ( AnimatedVertices_BufferID[ vertex_id[i] ] != (s32)meshBufferID ) //If this vertex is linked in a different meshbuffer + if (AnimatedVertices_VertexID[vertex_id[i]] != -1) { + if (AnimatedVertices_BufferID[vertex_id[i]] != (s32)meshBufferID) // If this vertex is linked in a different meshbuffer { - AnimatedVertices_VertexID[ vertex_id[i] ] = -1; - AnimatedVertices_BufferID[ vertex_id[i] ] = -1; - showVertexWarning=true; + AnimatedVertices_VertexID[vertex_id[i]] = -1; + AnimatedVertices_BufferID[vertex_id[i]] = -1; + showVertexWarning = true; } } - if (AnimatedVertices_VertexID[ vertex_id[i] ] == -1) //If this vertex is not in the meshbuffer + if (AnimatedVertices_VertexID[vertex_id[i]] == -1) // If this vertex is not in the meshbuffer { - //Check for lightmapping: - if (BaseVertices[ vertex_id[i] ].TCoords2 != core::vector2df(0.f,0.f)) - meshBuffer->convertTo2TCoords(); //Will only affect the meshbuffer the first time this is called + // Check for lightmapping: + if (BaseVertices[vertex_id[i]].TCoords2 != core::vector2df(0.f, 0.f)) + meshBuffer->convertTo2TCoords(); // Will only affect the meshbuffer the first time this is called - //Add the vertex to the meshbuffer: + // Add the vertex to the meshbuffer: if (meshBuffer->VertexType == video::EVT_STANDARD) - meshBuffer->Vertices_Standard.push_back( BaseVertices[ vertex_id[i] ] ); + meshBuffer->Vertices_Standard.push_back(BaseVertices[vertex_id[i]]); else - meshBuffer->Vertices_2TCoords.push_back(BaseVertices[ vertex_id[i] ] ); + meshBuffer->Vertices_2TCoords.push_back(BaseVertices[vertex_id[i]]); - //create vertex id to meshbuffer index link: - AnimatedVertices_VertexID[ vertex_id[i] ] = meshBuffer->getVertexCount()-1; - AnimatedVertices_BufferID[ vertex_id[i] ] = meshBufferID; + // create vertex id to meshbuffer index link: + AnimatedVertices_VertexID[vertex_id[i]] = meshBuffer->getVertexCount() - 1; + AnimatedVertices_BufferID[vertex_id[i]] = meshBufferID; - if (B3dMaterial) - { + if (B3dMaterial) { // Apply Material/Color/etc... - video::S3DVertex *Vertex=meshBuffer->getVertex(meshBuffer->getVertexCount()-1); + video::S3DVertex *Vertex = meshBuffer->getVertex(meshBuffer->getVertexCount() - 1); if (!HasVertexColors) - Vertex->Color=B3dMaterial->Material.DiffuseColor; + Vertex->Color = B3dMaterial->Material.DiffuseColor; else if (Vertex->Color.getAlpha() == 255) - Vertex->Color.setAlpha( (s32)(B3dMaterial->alpha * 255.0f) ); + Vertex->Color.setAlpha((s32)(B3dMaterial->alpha * 255.0f)); // Use texture's scale - if (B3dMaterial->Textures[0]) - { + if (B3dMaterial->Textures[0]) { Vertex->TCoords.X *= B3dMaterial->Textures[0]->Xscale; Vertex->TCoords.Y *= B3dMaterial->Textures[0]->Yscale; } @@ -560,12 +506,12 @@ bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 m } } - meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[0] ] ); - meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[1] ] ); - meshBuffer->Indices.push_back( AnimatedVertices_VertexID[ vertex_id[2] ] ); + meshBuffer->Indices.push_back(AnimatedVertices_VertexID[vertex_id[0]]); + meshBuffer->Indices.push_back(AnimatedVertices_VertexID[vertex_id[1]]); + meshBuffer->Indices.push_back(AnimatedVertices_VertexID[vertex_id[2]]); } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); if (showVertexWarning) os::Printer::log("B3dMeshLoader: Warning, different meshbuffers linking to the same vertex, this will cause problems with animated meshes"); @@ -573,20 +519,18 @@ bool CB3DMeshFileLoader::readChunkTRIS(scene::SSkinMeshBuffer *meshBuffer, u32 m return true; } - bool CB3DMeshFileLoader::readChunkBONE(CSkinnedMesh::SJoint *inJoint) { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkBONE"; os::Printer::log(logStr.c_str(), ELL_DEBUG); #endif - if (B3dStack.getLast().length > 8) - { - while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats + if (B3dStack.getLast().length > 8) { + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { u32 globalVertexID; f32 strength; @@ -598,40 +542,34 @@ bool CB3DMeshFileLoader::readChunkBONE(CSkinnedMesh::SJoint *inJoint) #endif globalVertexID += VerticesStart; - if (globalVertexID >= AnimatedVertices_VertexID.size()) - { + if (globalVertexID >= AnimatedVertices_VertexID.size()) { os::Printer::log("Illegal vertex index found", B3DFile->getFileName(), ELL_ERROR); return false; } - if (AnimatedVertices_VertexID[globalVertexID]==-1) - { + if (AnimatedVertices_VertexID[globalVertexID] == -1) { os::Printer::log("B3dMeshLoader: Weight has bad vertex id (no link to meshbuffer index found)"); - } - else if (strength >0) - { - CSkinnedMesh::SWeight *weight=AnimatedMesh->addWeight(inJoint); - weight->strength=strength; - //Find the meshbuffer and Vertex index from the Global Vertex ID: + } else if (strength > 0) { + CSkinnedMesh::SWeight *weight = AnimatedMesh->addWeight(inJoint); + weight->strength = strength; + // Find the meshbuffer and Vertex index from the Global Vertex ID: weight->vertex_id = AnimatedVertices_VertexID[globalVertexID]; weight->buffer_id = AnimatedVertices_BufferID[globalVertexID]; } } } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkKEYS(CSkinnedMesh::SJoint *inJoint) { #ifdef _B3D_READER_DEBUG // Only print first, that's just too much output otherwise - if ( !inJoint || (inJoint->PositionKeys.empty() && inJoint->ScaleKeys.empty() && inJoint->RotationKeys.empty()) ) - { + if (!inJoint || (inJoint->PositionKeys.empty() && inJoint->ScaleKeys.empty() && inJoint->RotationKeys.empty())) { core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkKEYS"; os::Printer::log(logStr.c_str(), ELL_DEBUG); @@ -644,124 +582,103 @@ bool CB3DMeshFileLoader::readChunkKEYS(CSkinnedMesh::SJoint *inJoint) flags = os::Byteswap::byteswap(flags); #endif - CSkinnedMesh::SPositionKey *oldPosKey=0; + CSkinnedMesh::SPositionKey *oldPosKey = 0; core::vector3df oldPos[2]; - CSkinnedMesh::SScaleKey *oldScaleKey=0; + CSkinnedMesh::SScaleKey *oldScaleKey = 0; core::vector3df oldScale[2]; - CSkinnedMesh::SRotationKey *oldRotKey=0; + CSkinnedMesh::SRotationKey *oldRotKey = 0; core::quaternion oldRot[2]; - bool isFirst[3]={true,true,true}; - while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats + bool isFirst[3] = {true, true, true}; + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { s32 frame; B3DFile->read(&frame, sizeof(frame)); - #ifdef __BIG_ENDIAN__ +#ifdef __BIG_ENDIAN__ frame = os::Byteswap::byteswap(frame); - #endif +#endif // Add key frames, frames in Irrlicht are zero-based f32 data[4]; - if (flags & 1) - { + if (flags & 1) { readFloats(data, 3); - if ((oldPosKey!=0) && (oldPos[0]==oldPos[1])) - { + if ((oldPosKey != 0) && (oldPos[0] == oldPos[1])) { const core::vector3df pos(data[0], data[1], data[2]); - if (oldPos[1]==pos) - oldPosKey->frame = (f32)frame-1; - else - { - oldPos[0]=oldPos[1]; - oldPosKey=AnimatedMesh->addPositionKey(inJoint); - oldPosKey->frame = (f32)frame-1; + if (oldPos[1] == pos) + oldPosKey->frame = (f32)frame - 1; + else { + oldPos[0] = oldPos[1]; + oldPosKey = AnimatedMesh->addPositionKey(inJoint); + oldPosKey->frame = (f32)frame - 1; oldPos[1].set(oldPosKey->position.set(pos)); } - } - else if (oldPosKey==0 && isFirst[0]) - { - oldPosKey=AnimatedMesh->addPositionKey(inJoint); - oldPosKey->frame = (f32)frame-1; + } else if (oldPosKey == 0 && isFirst[0]) { + oldPosKey = AnimatedMesh->addPositionKey(inJoint); + oldPosKey->frame = (f32)frame - 1; oldPos[0].set(oldPosKey->position.set(data[0], data[1], data[2])); - oldPosKey=0; - isFirst[0]=false; - } - else - { - if (oldPosKey!=0) - oldPos[0]=oldPos[1]; - oldPosKey=AnimatedMesh->addPositionKey(inJoint); - oldPosKey->frame = (f32)frame-1; + oldPosKey = 0; + isFirst[0] = false; + } else { + if (oldPosKey != 0) + oldPos[0] = oldPos[1]; + oldPosKey = AnimatedMesh->addPositionKey(inJoint); + oldPosKey->frame = (f32)frame - 1; oldPos[1].set(oldPosKey->position.set(data[0], data[1], data[2])); } } - if (flags & 2) - { + if (flags & 2) { readFloats(data, 3); - if ((oldScaleKey!=0) && (oldScale[0]==oldScale[1])) - { + if ((oldScaleKey != 0) && (oldScale[0] == oldScale[1])) { const core::vector3df scale(data[0], data[1], data[2]); - if (oldScale[1]==scale) - oldScaleKey->frame = (f32)frame-1; - else - { - oldScale[0]=oldScale[1]; - oldScaleKey=AnimatedMesh->addScaleKey(inJoint); - oldScaleKey->frame = (f32)frame-1; + if (oldScale[1] == scale) + oldScaleKey->frame = (f32)frame - 1; + else { + oldScale[0] = oldScale[1]; + oldScaleKey = AnimatedMesh->addScaleKey(inJoint); + oldScaleKey->frame = (f32)frame - 1; oldScale[1].set(oldScaleKey->scale.set(scale)); } - } - else if (oldScaleKey==0 && isFirst[1]) - { - oldScaleKey=AnimatedMesh->addScaleKey(inJoint); - oldScaleKey->frame = (f32)frame-1; + } else if (oldScaleKey == 0 && isFirst[1]) { + oldScaleKey = AnimatedMesh->addScaleKey(inJoint); + oldScaleKey->frame = (f32)frame - 1; oldScale[0].set(oldScaleKey->scale.set(data[0], data[1], data[2])); - oldScaleKey=0; - isFirst[1]=false; - } - else - { - if (oldScaleKey!=0) - oldScale[0]=oldScale[1]; - oldScaleKey=AnimatedMesh->addScaleKey(inJoint); - oldScaleKey->frame = (f32)frame-1; + oldScaleKey = 0; + isFirst[1] = false; + } else { + if (oldScaleKey != 0) + oldScale[0] = oldScale[1]; + oldScaleKey = AnimatedMesh->addScaleKey(inJoint); + oldScaleKey->frame = (f32)frame - 1; oldScale[1].set(oldScaleKey->scale.set(data[0], data[1], data[2])); } } - if (flags & 4) - { + if (flags & 4) { readFloats(data, 4); - if ((oldRotKey!=0) && (oldRot[0]==oldRot[1])) - { + if ((oldRotKey != 0) && (oldRot[0] == oldRot[1])) { // meant to be in this order since b3d stores W first const core::quaternion rot(data[1], data[2], data[3], data[0]); - if (oldRot[1]==rot) - oldRotKey->frame = (f32)frame-1; - else - { - oldRot[0]=oldRot[1]; - oldRotKey=AnimatedMesh->addRotationKey(inJoint); - oldRotKey->frame = (f32)frame-1; + if (oldRot[1] == rot) + oldRotKey->frame = (f32)frame - 1; + else { + oldRot[0] = oldRot[1]; + oldRotKey = AnimatedMesh->addRotationKey(inJoint); + oldRotKey->frame = (f32)frame - 1; oldRot[1].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0])); oldRot[1].normalize(); } - } - else if (oldRotKey==0 && isFirst[2]) - { - oldRotKey=AnimatedMesh->addRotationKey(inJoint); - oldRotKey->frame = (f32)frame-1; + } else if (oldRotKey == 0 && isFirst[2]) { + oldRotKey = AnimatedMesh->addRotationKey(inJoint); + oldRotKey->frame = (f32)frame - 1; // meant to be in this order since b3d stores W first oldRot[0].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0])); oldRot[0].normalize(); - oldRotKey=0; - isFirst[2]=false; - } - else - { - if (oldRotKey!=0) - oldRot[0]=oldRot[1]; - oldRotKey=AnimatedMesh->addRotationKey(inJoint); - oldRotKey->frame = (f32)frame-1; + oldRotKey = 0; + isFirst[2] = false; + } else { + if (oldRotKey != 0) + oldRot[0] = oldRot[1]; + oldRotKey = AnimatedMesh->addRotationKey(inJoint); + oldRotKey->frame = (f32)frame - 1; // meant to be in this order since b3d stores W first oldRot[1].set(oldRotKey->rotation.set(data[1], data[2], data[3], data[0])); oldRot[1].normalize(); @@ -769,56 +686,54 @@ bool CB3DMeshFileLoader::readChunkKEYS(CSkinnedMesh::SJoint *inJoint) } } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkANIM() { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkANIM"; os::Printer::log(logStr.c_str(), ELL_DEBUG); #endif - s32 animFlags; //not stored\used - s32 animFrames;//not stored\used - f32 animFPS; //not stored\used + s32 animFlags; // not stored\used + s32 animFrames; // not stored\used + f32 animFPS; // not stored\used B3DFile->read(&animFlags, sizeof(s32)); B3DFile->read(&animFrames, sizeof(s32)); readFloats(&animFPS, 1); - if (animFPS>0.f) + if (animFPS > 0.f) AnimatedMesh->setAnimationSpeed(animFPS); os::Printer::log("FPS", io::path((double)animFPS), ELL_DEBUG); - #ifdef __BIG_ENDIAN__ - animFlags = os::Byteswap::byteswap(animFlags); - animFrames = os::Byteswap::byteswap(animFrames); - #endif +#ifdef __BIG_ENDIAN__ + animFlags = os::Byteswap::byteswap(animFlags); + animFrames = os::Byteswap::byteswap(animFrames); +#endif - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkTEXS() { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkTEXS"; os::Printer::log(logStr.c_str(), ELL_DEBUG); #endif - while((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) //this chunk repeats + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { Textures.push_back(SB3dTexture()); - SB3dTexture& B3dTexture = Textures.getLast(); + SB3dTexture &B3dTexture = Textures.getLast(); B3dTexture.TextureName = readString(); std::replace(B3dTexture.TextureName.begin(), B3dTexture.TextureName.end(), '\\', '/'); @@ -843,17 +758,16 @@ bool CB3DMeshFileLoader::readChunkTEXS() readFloats(&B3dTexture.Angle, 1); } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - bool CB3DMeshFileLoader::readChunkBRUS() { #ifdef _B3D_READER_DEBUG core::stringc logStr; - for ( u32 i=1; i < B3dStack.size(); ++i ) + for (u32 i = 1; i < B3dStack.size(); ++i) logStr += "-"; logStr += "read ChunkBRUS"; os::Printer::log(logStr.c_str(), ELL_DEBUG); @@ -868,9 +782,9 @@ bool CB3DMeshFileLoader::readChunkBRUS() // number of texture ids read for Irrlicht const u32 num_textures = core::min_(n_texs, video::MATERIAL_MAX_TEXTURES); // number of bytes to skip (for ignored texture ids) - const u32 n_texs_offset = (num_textures B3DFile->getPos()) //this chunk repeats + while ((B3dStack.getLast().startposition + B3dStack.getLast().length) > B3DFile->getPos()) // this chunk repeats { // This is what blitz basic calls a brush, like a Irrlicht Material @@ -879,7 +793,7 @@ bool CB3DMeshFileLoader::readChunkBRUS() os::Printer::log("read Material", name.c_str(), ELL_DEBUG); #endif Materials.push_back(SB3dMaterial()); - SB3dMaterial& B3dMaterial=Materials.getLast(); + SB3dMaterial &B3dMaterial = Materials.getLast(); readFloats(&B3dMaterial.red, 1); readFloats(&B3dMaterial.green, 1); @@ -899,43 +813,37 @@ bool CB3DMeshFileLoader::readChunkBRUS() #endif u32 i; - for (i=0; iread(&texture_id, sizeof(s32)); #ifdef __BIG_ENDIAN__ texture_id = os::Byteswap::byteswap(texture_id); #endif //--- Get pointers to the texture, based on the IDs --- - if ((u32)texture_id < Textures.size()) - { - B3dMaterial.Textures[i]=&Textures[texture_id]; + if ((u32)texture_id < Textures.size()) { + B3dMaterial.Textures[i] = &Textures[texture_id]; #ifdef _B3D_READER_DEBUG os::Printer::log("Layer", core::stringc(i).c_str(), ELL_DEBUG); os::Printer::log("using texture", Textures[texture_id].TextureName.c_str(), ELL_DEBUG); #endif - } - else - B3dMaterial.Textures[i]=0; + } else + B3dMaterial.Textures[i] = 0; } // skip other texture ids - for (i=0; iread(&texture_id, sizeof(s32)); #ifdef __BIG_ENDIAN__ texture_id = os::Byteswap::byteswap(texture_id); #endif - if (ShowWarning && (texture_id != -1) && (n_texs>video::MATERIAL_MAX_TEXTURES)) - { + if (ShowWarning && (texture_id != -1) && (n_texs > video::MATERIAL_MAX_TEXTURES)) { os::Printer::log("Too many textures used in one material", B3DFile->getFileName(), ELL_WARNING); ShowWarning = false; } } - //Fixes problems when the lightmap is on the first texture: - if (B3dMaterial.Textures[0] != 0) - { + // Fixes problems when the lightmap is on the first texture: + if (B3dMaterial.Textures[0] != 0) { if (B3dMaterial.Textures[0]->Flags & 65536) // 65536 = secondary UV { SB3dTexture *TmpTexture; @@ -945,79 +853,69 @@ bool CB3DMeshFileLoader::readChunkBRUS() } } - //If a preceeding texture slot is empty move the others down: - for (i=num_textures; i>0; --i) - { - for (u32 j=i-1; j 0; --i) { + for (u32 j = i - 1; j < num_textures - 1; ++j) { + if (B3dMaterial.Textures[j + 1] != 0 && B3dMaterial.Textures[j] == 0) { + B3dMaterial.Textures[j] = B3dMaterial.Textures[j + 1]; + B3dMaterial.Textures[j + 1] = 0; } } } //------ Convert blitz flags/blend to irrlicht ------- - //Two textures: - if (B3dMaterial.Textures[1]) - { + // Two textures: + if (B3dMaterial.Textures[1]) { B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; B3dMaterial.Material.ZWriteEnable = video::EZW_OFF; - } - else if (B3dMaterial.Textures[0]) //One texture: + } else if (B3dMaterial.Textures[0]) // One texture: { // Flags & 0x1 is usual SOLID, 0x8 is mipmap (handled before) if (B3dMaterial.Textures[0]->Flags & 0x2) //(Alpha mapped) { B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; B3dMaterial.Material.ZWriteEnable = video::EZW_OFF; - } - else if (B3dMaterial.Textures[0]->Flags & 0x4) //(Masked) + } else if (B3dMaterial.Textures[0]->Flags & 0x4) //(Masked) B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; // TODO: create color key texture else if (B3dMaterial.alpha == 1.f) B3dMaterial.Material.MaterialType = video::EMT_SOLID; - else - { + else { B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; B3dMaterial.Material.ZWriteEnable = video::EZW_OFF; } - } - else //No texture: + } else // No texture: { if (B3dMaterial.alpha == 1.f) B3dMaterial.Material.MaterialType = video::EMT_SOLID; - else - { + else { B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; B3dMaterial.Material.ZWriteEnable = video::EZW_OFF; } } B3dMaterial.Material.DiffuseColor = video::SColorf(B3dMaterial.red, B3dMaterial.green, B3dMaterial.blue, B3dMaterial.alpha).toSColor(); - B3dMaterial.Material.ColorMaterial=video::ECM_NONE; + B3dMaterial.Material.ColorMaterial = video::ECM_NONE; //------ Material fx ------ - if (B3dMaterial.fx & 1) //full-bright + if (B3dMaterial.fx & 1) // full-bright { B3dMaterial.Material.AmbientColor = video::SColor(255, 255, 255, 255); B3dMaterial.Material.Lighting = false; - } - else + } else B3dMaterial.Material.AmbientColor = B3dMaterial.Material.DiffuseColor; - if (B3dMaterial.fx & 2) //use vertex colors instead of brush color - B3dMaterial.Material.ColorMaterial=video::ECM_DIFFUSE_AND_AMBIENT; + if (B3dMaterial.fx & 2) // use vertex colors instead of brush color + B3dMaterial.Material.ColorMaterial = video::ECM_DIFFUSE_AND_AMBIENT; - if (B3dMaterial.fx & 4) //flatshaded + if (B3dMaterial.fx & 4) // flatshaded B3dMaterial.Material.GouraudShading = false; - if (B3dMaterial.fx & 16) //disable backface culling + if (B3dMaterial.fx & 16) // disable backface culling B3dMaterial.Material.BackfaceCulling = false; - if (B3dMaterial.fx & 32) //force vertex alpha-blending + if (B3dMaterial.fx & 32) // force vertex alpha-blending { B3dMaterial.Material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; B3dMaterial.Material.ZWriteEnable = video::EZW_OFF; @@ -1026,35 +924,32 @@ bool CB3DMeshFileLoader::readChunkBRUS() B3dMaterial.Material.Shininess = B3dMaterial.shininess; } - B3dStack.erase(B3dStack.size()-1); + B3dStack.erase(B3dStack.size() - 1); return true; } - std::string CB3DMeshFileLoader::readString() { std::string newstring = ""; - while (true) - { + while (true) { c8 character; if (B3DFile->read(&character, sizeof(character)) == 0) break; // eof - if (character==0) + if (character == 0) break; newstring.push_back(character); } return newstring; } - -void CB3DMeshFileLoader::readFloats(f32* vec, u32 count) +void CB3DMeshFileLoader::readFloats(f32 *vec, u32 count) { - B3DFile->read(vec, count*sizeof(f32)); - #ifdef __BIG_ENDIAN__ - for (u32 n=0; nread(vec, count * sizeof(f32)); +#ifdef __BIG_ENDIAN__ + for (u32 n = 0; n < count; ++n) vec[n] = os::Byteswap::byteswap(vec[n]); - #endif +#endif } } // end namespace scene diff --git a/source/Irrlicht/CB3DMeshFileLoader.h b/source/Irrlicht/CB3DMeshFileLoader.h index be5eeed1..808b6817 100644 --- a/source/Irrlicht/CB3DMeshFileLoader.h +++ b/source/Irrlicht/CB3DMeshFileLoader.h @@ -6,7 +6,6 @@ // File format designed by Mark Sibly for the Blitz3D engine and has been // declared public domain - #pragma once #include "IMeshLoader.h" @@ -25,35 +24,33 @@ namespace scene class CB3DMeshFileLoader : public IMeshLoader { public: - //! Constructor - CB3DMeshFileLoader(scene::ISceneManager* smgr); + CB3DMeshFileLoader(scene::ISceneManager *smgr); //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. - IAnimatedMesh* createMesh(io::IReadFile* file) override; + IAnimatedMesh *createMesh(io::IReadFile *file) override; private: - bool load(); - bool readChunkNODE(CSkinnedMesh::SJoint* InJoint); - bool readChunkMESH(CSkinnedMesh::SJoint* InJoint); - bool readChunkVRTS(CSkinnedMesh::SJoint* InJoint); + bool readChunkNODE(CSkinnedMesh::SJoint *InJoint); + bool readChunkMESH(CSkinnedMesh::SJoint *InJoint); + bool readChunkVRTS(CSkinnedMesh::SJoint *InJoint); bool readChunkTRIS(scene::SSkinMeshBuffer *MeshBuffer, u32 MeshBufferID, s32 Vertices_Start); - bool readChunkBONE(CSkinnedMesh::SJoint* InJoint); - bool readChunkKEYS(CSkinnedMesh::SJoint* InJoint); + bool readChunkBONE(CSkinnedMesh::SJoint *InJoint); + bool readChunkKEYS(CSkinnedMesh::SJoint *InJoint); bool readChunkANIM(); bool readChunkTEXS(); bool readChunkBRUS(); std::string readString(); - void readFloats(f32* vec, u32 count); + void readFloats(f32 *vec, u32 count); core::array B3dStack; @@ -66,11 +63,11 @@ private: core::array BaseVertices; - CSkinnedMesh* AnimatedMesh; - io::IReadFile* B3DFile; + CSkinnedMesh *AnimatedMesh; + io::IReadFile *B3DFile; - //B3Ds have Vertex ID's local within the mesh I don't want this - // Variable needs to be class member due to recursion in calls + // B3Ds have Vertex ID's local within the mesh I don't want this + // Variable needs to be class member due to recursion in calls u32 VerticesStart; bool NormalsInFile; @@ -78,6 +75,5 @@ private: bool ShowWarning; }; - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CBillboardSceneNode.cpp b/source/Irrlicht/CBillboardSceneNode.cpp index 1488ae6a..ddb9d465 100644 --- a/source/Irrlicht/CBillboardSceneNode.cpp +++ b/source/Irrlicht/CBillboardSceneNode.cpp @@ -14,15 +14,15 @@ namespace scene { //! constructor -CBillboardSceneNode::CBillboardSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position, const core::dimension2d& size, - video::SColor colorTop, video::SColor colorBottom) - : IBillboardSceneNode(parent, mgr, id, position) - , Buffer(new SMeshBuffer()) +CBillboardSceneNode::CBillboardSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position, const core::dimension2d &size, + video::SColor colorTop, video::SColor colorBottom) : + IBillboardSceneNode(parent, mgr, id, position), + Buffer(new SMeshBuffer()) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CBillboardSceneNode"); - #endif +#endif setSize(size); @@ -63,12 +63,11 @@ void CBillboardSceneNode::OnRegisterSceneNode() ISceneNode::OnRegisterSceneNode(); } - //! render void CBillboardSceneNode::render() { - video::IVideoDriver* driver = SceneManager->getVideoDriver(); - ICameraSceneNode* camera = SceneManager->getActiveCamera(); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); + ICameraSceneNode *camera = SceneManager->getActiveCamera(); if (!camera || !driver) return; @@ -80,17 +79,16 @@ void CBillboardSceneNode::render() driver->setMaterial(Buffer->Material); driver->drawMeshBuffer(Buffer); - if (DebugDataVisible & scene::EDS_BBOX) - { + if (DebugDataVisible & scene::EDS_BBOX) { driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); video::SMaterial m; m.Lighting = false; driver->setMaterial(m); - driver->draw3DBox(BBoxSafe, video::SColor(0,208,195,152)); + driver->draw3DBox(BBoxSafe, video::SColor(0, 208, 195, 152)); } } -void CBillboardSceneNode::updateMesh(const irr::scene::ICameraSceneNode* camera) +void CBillboardSceneNode::updateMesh(const irr::scene::ICameraSceneNode *camera) { // billboard looks toward camera core::vector3df pos = getAbsolutePosition(); @@ -102,9 +100,8 @@ void CBillboardSceneNode::updateMesh(const irr::scene::ICameraSceneNode* camera) view.normalize(); core::vector3df horizontal = up.crossProduct(view); - if ( horizontal.getLength() == 0 ) - { - horizontal.set(up.Y,up.X,up.Z); + if (horizontal.getLength() == 0) { + horizontal.set(up.Y, up.X, up.Z); } horizontal.normalize(); core::vector3df topHorizontal = horizontal * 0.5f * TopEdgeWidth; @@ -117,9 +114,9 @@ void CBillboardSceneNode::updateMesh(const irr::scene::ICameraSceneNode* camera) view *= -1.0f; - core::array& vertices = Buffer->Vertices; + core::array &vertices = Buffer->Vertices; - for (s32 i=0; i<4; ++i) + for (s32 i = 0; i < 4; ++i) vertices[i].Normal = view; /* Vertices are: @@ -137,21 +134,20 @@ void CBillboardSceneNode::updateMesh(const irr::scene::ICameraSceneNode* camera) Buffer->recalculateBoundingBox(); } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CBillboardSceneNode::getBoundingBox() const +const core::aabbox3d &CBillboardSceneNode::getBoundingBox() const { // Really wrong when scaled (as the node does not scale it's vertices - maybe it should?) return BBoxSafe; } -const core::aabbox3d& CBillboardSceneNode::getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode* camera) +const core::aabbox3d &CBillboardSceneNode::getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode *camera) { updateMesh(camera); return Buffer->BoundingBox; } -void CBillboardSceneNode::setSize(const core::dimension2d& size) +void CBillboardSceneNode::setSize(const core::dimension2d &size) { Size = size; @@ -162,12 +158,11 @@ void CBillboardSceneNode::setSize(const core::dimension2d& size) if (core::equals(Size.Height, 0.0f)) Size.Height = 1.0f; - const f32 extent = 0.5f*sqrtf(Size.Width*Size.Width + Size.Height*Size.Height); - BBoxSafe.MinEdge.set(-extent,-extent,-extent); - BBoxSafe.MaxEdge.set(extent,extent,extent); + const f32 extent = 0.5f * sqrtf(Size.Width * Size.Width + Size.Height * Size.Height); + BBoxSafe.MinEdge.set(-extent, -extent, -extent); + BBoxSafe.MaxEdge.set(extent, extent, extent); } - void CBillboardSceneNode::setSize(f32 height, f32 bottomEdgeWidth, f32 topEdgeWidth) { Size.set(bottomEdgeWidth, height); @@ -176,62 +171,55 @@ void CBillboardSceneNode::setSize(f32 height, f32 bottomEdgeWidth, f32 topEdgeWi if (core::equals(Size.Height, 0.0f)) Size.Height = 1.0f; - if (core::equals(Size.Width, 0.f) && core::equals(TopEdgeWidth, 0.f)) - { + if (core::equals(Size.Width, 0.f) && core::equals(TopEdgeWidth, 0.f)) { Size.Width = 1.0f; TopEdgeWidth = 1.0f; } - const f32 extent = 0.5f*sqrtf(Size.Width*Size.Width + Size.Height*Size.Height); - BBoxSafe.MinEdge.set(-extent,-extent,-extent); - BBoxSafe.MaxEdge.set(extent,extent,extent); + const f32 extent = 0.5f * sqrtf(Size.Width * Size.Width + Size.Height * Size.Height); + BBoxSafe.MinEdge.set(-extent, -extent, -extent); + BBoxSafe.MaxEdge.set(extent, extent, extent); } - -video::SMaterial& CBillboardSceneNode::getMaterial(u32 i) +video::SMaterial &CBillboardSceneNode::getMaterial(u32 i) { return Buffer->Material; } - //! returns amount of materials used by this scene node. u32 CBillboardSceneNode::getMaterialCount() const { return 1; } - //! gets the size of the billboard -const core::dimension2d& CBillboardSceneNode::getSize() const +const core::dimension2d &CBillboardSceneNode::getSize() const { return Size; } - //! Gets the widths of the top and bottom edges of the billboard. -void CBillboardSceneNode::getSize(f32& height, f32& bottomEdgeWidth, - f32& topEdgeWidth) const +void CBillboardSceneNode::getSize(f32 &height, f32 &bottomEdgeWidth, + f32 &topEdgeWidth) const { height = Size.Height; bottomEdgeWidth = Size.Width; topEdgeWidth = TopEdgeWidth; } - //! Set the color of all vertices of the billboard //! \param overallColor: the color to set -void CBillboardSceneNode::setColor(const video::SColor& overallColor) +void CBillboardSceneNode::setColor(const video::SColor &overallColor) { - for(u32 vertex = 0; vertex < 4; ++vertex) + for (u32 vertex = 0; vertex < 4; ++vertex) Buffer->Vertices[vertex].Color = overallColor; } - //! Set the color of the top and bottom vertices of the billboard //! \param topColor: the color to set the top vertices //! \param bottomColor: the color to set the bottom vertices -void CBillboardSceneNode::setColor(const video::SColor& topColor, - const video::SColor& bottomColor) +void CBillboardSceneNode::setColor(const video::SColor &topColor, + const video::SColor &bottomColor) { Buffer->Vertices[0].Color = bottomColor; Buffer->Vertices[1].Color = topColor; @@ -239,43 +227,40 @@ void CBillboardSceneNode::setColor(const video::SColor& topColor, Buffer->Vertices[3].Color = bottomColor; } - //! Gets the color of the top and bottom vertices of the billboard //! \param[out] topColor: stores the color of the top vertices //! \param[out] bottomColor: stores the color of the bottom vertices -void CBillboardSceneNode::getColor(video::SColor& topColor, - video::SColor& bottomColor) const +void CBillboardSceneNode::getColor(video::SColor &topColor, + video::SColor &bottomColor) const { bottomColor = Buffer->Vertices[0].Color; topColor = Buffer->Vertices[1].Color; } - //! Creates a clone of this scene node and its children. -ISceneNode* CBillboardSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) +ISceneNode *CBillboardSceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { if (!newParent) newParent = Parent; if (!newManager) newManager = SceneManager; - CBillboardSceneNode* nb = new CBillboardSceneNode(newParent, - newManager, ID, RelativeTranslation, Size); + CBillboardSceneNode *nb = new CBillboardSceneNode(newParent, + newManager, ID, RelativeTranslation, Size); nb->cloneMembers(this, newManager); nb->Buffer->Material = Buffer->Material; nb->Size = Size; nb->TopEdgeWidth = this->TopEdgeWidth; - video::SColor topColor,bottomColor; - getColor(topColor,bottomColor); - nb->setColor(topColor,bottomColor); + video::SColor topColor, bottomColor; + getColor(topColor, bottomColor); + nb->setColor(topColor, bottomColor); - if ( newParent ) + if (newParent) nb->drop(); return nb; } - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CBillboardSceneNode.h b/source/Irrlicht/CBillboardSceneNode.h index 327bc23a..f0d7f9dc 100644 --- a/source/Irrlicht/CBillboardSceneNode.h +++ b/source/Irrlicht/CBillboardSceneNode.h @@ -17,12 +17,11 @@ namespace scene class CBillboardSceneNode : virtual public IBillboardSceneNode { public: - //! constructor - CBillboardSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position, const core::dimension2d& size, - video::SColor colorTop=video::SColor(0xFFFFFFFF), - video::SColor colorBottom=video::SColor(0xFFFFFFFF)); + CBillboardSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position, const core::dimension2d &size, + video::SColor colorTop = video::SColor(0xFFFFFFFF), + video::SColor colorBottom = video::SColor(0xFFFFFFFF)); virtual ~CBillboardSceneNode(); @@ -33,43 +32,43 @@ public: void render() override; //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + const core::aabbox3d &getBoundingBox() const override; //! sets the size of the billboard - void setSize(const core::dimension2d& size) override; + void setSize(const core::dimension2d &size) override; //! Sets the widths of the top and bottom edges of the billboard independently. void setSize(f32 height, f32 bottomEdgeWidth, f32 topEdgeWidth) override; //! gets the size of the billboard - const core::dimension2d& getSize() const override; + const core::dimension2d &getSize() const override; //! Gets the widths of the top and bottom edges of the billboard. - void getSize(f32& height, f32& bottomEdgeWidth, f32& topEdgeWidth) const override; + void getSize(f32 &height, f32 &bottomEdgeWidth, f32 &topEdgeWidth) const override; - video::SMaterial& getMaterial(u32 i) override; + video::SMaterial &getMaterial(u32 i) override; //! returns amount of materials used by this scene node. u32 getMaterialCount() const override; //! Set the color of all vertices of the billboard //! \param overallColor: the color to set - void setColor(const video::SColor& overallColor) override; + void setColor(const video::SColor &overallColor) override; //! Set the color of the top and bottom vertices of the billboard //! \param topColor: the color to set the top vertices //! \param bottomColor: the color to set the bottom vertices - virtual void setColor(const video::SColor& topColor, - const video::SColor& bottomColor) override; + virtual void setColor(const video::SColor &topColor, + const video::SColor &bottomColor) override; //! Gets the color of the top and bottom vertices of the billboard //! \param[out] topColor: stores the color of the top vertices //! \param[out] bottomColor: stores the color of the bottom vertices - virtual void getColor(video::SColor& topColor, - video::SColor& bottomColor) const override; + virtual void getColor(video::SColor &topColor, + video::SColor &bottomColor) const override; //! Get the real boundingbox used by the billboard (which depends on the active camera) - const core::aabbox3d& getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode* camera) override; + const core::aabbox3d &getTransformedBillboardBoundingBox(const irr::scene::ICameraSceneNode *camera) override; //! Get the amount of mesh buffers. u32 getMeshBufferCount() const override @@ -78,9 +77,9 @@ public: } //! Get pointer to the mesh buffer. - IMeshBuffer* getMeshBuffer(u32 nr) const override + IMeshBuffer *getMeshBuffer(u32 nr) const override { - if ( nr == 0 ) + if (nr == 0) return Buffer; return 0; } @@ -89,13 +88,12 @@ public: ESCENE_NODE_TYPE getType() const override { return ESNT_BILLBOARD; } //! Creates a clone of this scene node and its children. - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; protected: - void updateMesh(const irr::scene::ICameraSceneNode* camera); + void updateMesh(const irr::scene::ICameraSceneNode *camera); private: - //! Size.Width is the bottom edge width core::dimension2d Size; f32 TopEdgeWidth; @@ -104,14 +102,12 @@ private: // TODO: BUG - still can be wrong with scaling < 1. Billboards should calculate relative coordinates for their mesh // and then use the node-scaling. But needs some work... /** Note that we can't use the real boundingbox for culling because at that point - the camera which is used to calculate the billboard is not yet updated. So we only - know the real boundingbox after rendering - which is too late for culling. */ + the camera which is used to calculate the billboard is not yet updated. So we only + know the real boundingbox after rendering - which is too late for culling. */ core::aabbox3d BBoxSafe; - scene::SMeshBuffer* Buffer; + scene::SMeshBuffer *Buffer; }; - } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CBlit.h b/source/Irrlicht/CBlit.h index 752cde73..8f145a33 100644 --- a/source/Irrlicht/CBlit.h +++ b/source/Irrlicht/CBlit.h @@ -13,80 +13,78 @@ namespace irr #define CBLIT_USE_FIXPOINT18 #if defined(CBLIT_USE_FIXPOINT18) - typedef int f18; - #define f18_one 262144 - #define f18_zero 0 - #define f32_to_f18(x)((f18)floorf(((x) * 262144.f) + 0.f)) - #define f32_to_f32(x)(x) - #define f18_floor(x) ((x)>>18) - #define f18_round(x) ((x+131.072)>>18) +typedef int f18; +#define f18_one 262144 +#define f18_zero 0 +#define f32_to_f18(x) ((f18)floorf(((x) * 262144.f) + 0.f)) +#define f32_to_f32(x) (x) +#define f18_floor(x) ((x) >> 18) +#define f18_round(x) ((x + 131.072) >> 18) #else - typedef float f18; - #define f18_one 1.f - #define f18_zero_dot_five 0.5f - #define f18_zero 0.f - #define f32_to_f18(x)(x) - #define f32_to_f32(x)(x) - #define f18_floor(x) ((int)(x)) - #define f18_round(x) ((int)(x+0.5f)) +typedef float f18; +#define f18_one 1.f +#define f18_zero_dot_five 0.5f +#define f18_zero 0.f +#define f32_to_f18(x) (x) +#define f32_to_f32(x) (x) +#define f18_floor(x) ((int)(x)) +#define f18_round(x) ((int)(x + 0.5f)) #endif - struct SBlitJob - { - AbsRectangle Dest; - AbsRectangle Source; +struct SBlitJob +{ + AbsRectangle Dest; + AbsRectangle Source; - u32 argb; + u32 argb; - const void* src; - void* dst; + const void *src; + void *dst; - u32 width; //draw size - u32 height; + u32 width; // draw size + u32 height; - u32 srcPixelMul; //pixel byte size - u32 dstPixelMul; + u32 srcPixelMul; // pixel byte size + u32 dstPixelMul; - int srcPitch; //scanline byte size. allow negative for mirror - u32 dstPitch; + int srcPitch; // scanline byte size. allow negative for mirror + u32 dstPitch; - bool stretch; - f32 x_stretch; - f32 y_stretch; - }; + bool stretch; + f32 x_stretch; + f32 y_stretch; +}; - // Bitfields Cohen Sutherland - enum eClipCode - { - CLIPCODE_EMPTY = 0, - CLIPCODE_BOTTOM = 1, - CLIPCODE_TOP = 2, - CLIPCODE_LEFT = 4, - CLIPCODE_RIGHT = 8 - }; +// Bitfields Cohen Sutherland +enum eClipCode +{ + CLIPCODE_EMPTY = 0, + CLIPCODE_BOTTOM = 1, + CLIPCODE_TOP = 2, + CLIPCODE_LEFT = 4, + CLIPCODE_RIGHT = 8 +}; -inline u32 GetClipCode( const AbsRectangle &r, const core::position2d &p ) +inline u32 GetClipCode(const AbsRectangle &r, const core::position2d &p) { u32 code = CLIPCODE_EMPTY; - if ( p.X < r.x0 ) + if (p.X < r.x0) code = CLIPCODE_LEFT; - else - if ( p.X > r.x1 ) + else if (p.X > r.x1) code = CLIPCODE_RIGHT; - if ( p.Y < r.y0 ) + if (p.Y < r.y0) code |= CLIPCODE_TOP; - else - if ( p.Y > r.y1 ) + else if (p.Y > r.y1) code |= CLIPCODE_BOTTOM; return code; } /* -*/ -inline void GetClip(AbsRectangle &clipping, video::IImage * t) + */ +inline void GetClip(AbsRectangle &clipping, video::IImage *t) { clipping.x0 = 0; clipping.y0 = 0; @@ -100,7 +98,7 @@ inline void GetClip(AbsRectangle &clipping, video::IImage * t) */ static inline u32 extractAlpha(const u32 c) { - return ( c >> 24 ) + ( c >> 31 ); + return (c >> 24) + (c >> 31); } /* @@ -112,7 +110,6 @@ static inline u32 packAlpha(const u32 c) return (c > 127 ? c - 1 : c) << 24; } - /*! Scale Color by (1/value) value 0 - 256 ( alpha ) @@ -126,7 +123,7 @@ inline u32 PixelLerp32(const u32 source, const u32 value) srcXG *= value; srcRB >>= 8; - //srcXG >>= 8; + // srcXG >>= 8; srcXG &= 0xFF00FF00; srcRB &= 0x00FF00FF; @@ -134,388 +131,329 @@ inline u32 PixelLerp32(const u32 source, const u32 value) return srcRB | srcXG; } - /*! -*/ -static void executeBlit_TextureCopy_x_to_x( const SBlitJob * job ) + */ +static void executeBlit_TextureCopy_x_to_x(const SBlitJob *job) { - if (job->stretch) - { + if (job->stretch) { const f18 wscale = f32_to_f18(job->x_stretch); const f18 hscale = f32_to_f18(job->y_stretch); f18 src_y = f18_zero; - if (job->srcPixelMul == 4) - { - const u32 *src = (u32*)(job->src); - u32 *dst = (u32*)(job->dst); + if (job->srcPixelMul == 4) { + const u32 *src = (u32 *)(job->src); + u32 *dst = (u32 *)(job->dst); - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - src = (u32*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + src = (u32 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { dst[dx] = src[f18_floor(src_x)]; } - dst = (u32*)((u8*)(dst)+job->dstPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } - } - else if (job->srcPixelMul == 2) - { - const u16 *src = (u16*)(job->src); - u16* dst = (u16*)(job->dst); + } else if (job->srcPixelMul == 2) { + const u16 *src = (u16 *)(job->src); + u16 *dst = (u16 *)(job->dst); - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - src = (u16*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + src = (u16 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { dst[dx] = src[f18_floor(src_x)]; } - dst = (u16*)((u8*)(dst)+job->dstPitch); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } - } - else - { + } else { const size_t widthPitch = job->width * job->dstPixelMul; - const void *src = (void*) job->src; - void *dst = (void*) job->dst; + const void *src = (void *)job->src; + void *dst = (void *)job->dst; - for ( u32 dy = 0; dy < job->height; ++dy ) - { - memcpy( dst, src, widthPitch); + for (u32 dy = 0; dy < job->height; ++dy) { + memcpy(dst, src, widthPitch); - src = (void*) ( (u8*) (src) + job->srcPitch ); - dst = (void*) ( (u8*) (dst) + job->dstPitch ); + src = (void *)((u8 *)(src) + job->srcPitch); + dst = (void *)((u8 *)(dst) + job->dstPitch); } } } /*! -*/ -static void executeBlit_TextureCopy_32_to_16( const SBlitJob * job ) + */ +static void executeBlit_TextureCopy_32_to_16(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u32 *src = static_cast(job->src); - u16 *dst = static_cast(job->dst); + const u32 *src = static_cast(job->src); + u16 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u32*) ( (u8*) (job->src) + job->srcPitch*src_y ); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u32 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = (u32)(dx*wscale); - //16 bit Blitter depends on pre-multiplied color - const u32 s = PixelLerp32( src[src_x] | 0xFF000000, extractAlpha( src[src_x] ) ); - dst[dx] = video::A8R8G8B8toA1R5G5B5( s ); + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = (u32)(dx * wscale); + // 16 bit Blitter depends on pre-multiplied color + const u32 s = PixelLerp32(src[src_x] | 0xFF000000, extractAlpha(src[src_x])); + dst[dx] = video::A8R8G8B8toA1R5G5B5(s); } - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { - //16 bit Blitter depends on pre-multiplied color - const u32 s = PixelLerp32( src[dx] | 0xFF000000, extractAlpha( src[dx] ) ); - dst[dx] = video::A8R8G8B8toA1R5G5B5( s ); + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { + // 16 bit Blitter depends on pre-multiplied color + const u32 s = PixelLerp32(src[dx] | 0xFF000000, extractAlpha(src[dx])); + dst[dx] = video::A8R8G8B8toA1R5G5B5(s); } - src = (u32*) ( (u8*) (src) + job->srcPitch ); - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + src = (u32 *)((u8 *)(src) + job->srcPitch); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } } /*! -*/ -static void executeBlit_TextureCopy_24_to_16( const SBlitJob * job ) + */ +static void executeBlit_TextureCopy_24_to_16(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u8 *src = static_cast(job->src); - u16 *dst = static_cast(job->dst); + const u8 *src = static_cast(job->src); + u16 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch * 3.f; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u8*)(job->src) + job->srcPitch*src_y; + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u8 *)(job->src) + job->srcPitch * src_y; - for ( u32 dx = 0; dx < w; ++dx ) - { - const u8* src_x = src+(u32)(dx*wscale); + for (u32 dx = 0; dx < w; ++dx) { + const u8 *src_x = src + (u32)(dx * wscale); dst[dx] = video::RGBA16(src_x[0], src_x[1], src_x[2]); } - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - const u8* s = src; - for ( u32 dx = 0; dx != w; ++dx ) - { + } else { + for (u32 dy = 0; dy != h; ++dy) { + const u8 *s = src; + for (u32 dx = 0; dx != w; ++dx) { dst[dx] = video::RGBA16(s[0], s[1], s[2]); s += 3; } - src = src+job->srcPitch; - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + src = src + job->srcPitch; + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } } - /*! -*/ -static void executeBlit_TextureCopy_16_to_32( const SBlitJob * job ) + */ +static void executeBlit_TextureCopy_16_to_32(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u16 *src = static_cast(job->src); - u32 *dst = static_cast(job->dst); + const u16 *src = static_cast(job->src); + u32 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u16*) ( (u8*) (job->src) + job->srcPitch*src_y ); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u16 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = (u32)(dx*wscale); + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = (u32)(dx * wscale); dst[dx] = video::A1R5G5B5toA8R8G8B8(src[src_x]); } - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { - dst[dx] = video::A1R5G5B5toA8R8G8B8( src[dx] ); + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { + dst[dx] = video::A1R5G5B5toA8R8G8B8(src[dx]); } - src = (u16*) ( (u8*) (src) + job->srcPitch ); - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + src = (u16 *)((u8 *)(src) + job->srcPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } } -static void executeBlit_TextureCopy_16_to_24( const SBlitJob * job ) +static void executeBlit_TextureCopy_16_to_24(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u16 *src = static_cast(job->src); - u8 *dst = static_cast(job->dst); + const u16 *src = static_cast(job->src); + u8 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u16*) ( (u8*) (job->src) + job->srcPitch*src_y ); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u16 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = (u32)(dx*wscale); + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = (u32)(dx * wscale); u32 color = video::A1R5G5B5toA8R8G8B8(src[src_x]); - u8 * writeTo = &dst[dx * 3]; - *writeTo++ = (color >> 16)& 0xFF; + u8 *writeTo = &dst[dx * 3]; + *writeTo++ = (color >> 16) & 0xFF; *writeTo++ = (color >> 8) & 0xFF; *writeTo++ = color & 0xFF; } dst += job->dstPitch; } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { u32 color = video::A1R5G5B5toA8R8G8B8(src[dx]); - u8 * writeTo = &dst[dx * 3]; - *writeTo++ = (color >> 16)& 0xFF; + u8 *writeTo = &dst[dx * 3]; + *writeTo++ = (color >> 16) & 0xFF; *writeTo++ = (color >> 8) & 0xFF; *writeTo++ = color & 0xFF; } - src = (u16*) ( (u8*) (src) + job->srcPitch ); + src = (u16 *)((u8 *)(src) + job->srcPitch); dst += job->dstPitch; } } } /*! -*/ -static void executeBlit_TextureCopy_24_to_32( const SBlitJob * job ) + */ +static void executeBlit_TextureCopy_24_to_32(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u8 *src = static_cast(job->src); - u32 *dst = static_cast(job->dst); + const u8 *src = static_cast(job->src); + u32 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch * 3.f; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (const u8*)job->src+(job->srcPitch*src_y); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (const u8 *)job->src + (job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u8* s = src+(u32)(dx*wscale); + for (u32 dx = 0; dx < w; ++dx) { + const u8 *s = src + (u32)(dx * wscale); dst[dx] = 0xFF000000 | s[0] << 16 | s[1] << 8 | s[2]; } - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } - } - else - { - for ( u32 dy = 0; dy < job->height; ++dy ) - { - const u8* s = src; + } else { + for (u32 dy = 0; dy < job->height; ++dy) { + const u8 *s = src; - for ( u32 dx = 0; dx < job->width; ++dx ) - { + for (u32 dx = 0; dx < job->width; ++dx) { dst[dx] = 0xFF000000 | s[0] << 16 | s[1] << 8 | s[2]; s += 3; } src = src + job->srcPitch; - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } } -static void executeBlit_TextureCopy_32_to_24( const SBlitJob * job ) +static void executeBlit_TextureCopy_32_to_24(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u32 *src = static_cast(job->src); - u8 *dst = static_cast(job->dst); + const u32 *src = static_cast(job->src); + u8 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u32*) ( (u8*) (job->src) + job->srcPitch*src_y); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u32 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = src[(u32)(dx*wscale)]; - u8 * writeTo = &dst[dx * 3]; - *writeTo++ = (src_x >> 16)& 0xFF; + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = src[(u32)(dx * wscale)]; + u8 *writeTo = &dst[dx * 3]; + *writeTo++ = (src_x >> 16) & 0xFF; *writeTo++ = (src_x >> 8) & 0xFF; *writeTo++ = src_x & 0xFF; } dst += job->dstPitch; } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { - u8 * writeTo = &dst[dx * 3]; - *writeTo++ = (src[dx] >> 16)& 0xFF; + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { + u8 *writeTo = &dst[dx * 3]; + *writeTo++ = (src[dx] >> 16) & 0xFF; *writeTo++ = (src[dx] >> 8) & 0xFF; *writeTo++ = src[dx] & 0xFF; } - src = (u32*) ( (u8*) (src) + job->srcPitch ); + src = (u32 *)((u8 *)(src) + job->srcPitch); dst += job->dstPitch; } } } /*! -*/ -static void executeBlit_TextureBlend_16_to_16( const SBlitJob * job ) + */ +static void executeBlit_TextureBlend_16_to_16(const SBlitJob *job) { const f18 wscale = f32_to_f18(job->x_stretch); const f18 hscale = f32_to_f18(job->y_stretch); f18 src_y = f18_zero; - u16 *dst = (u16*)job->dst; + u16 *dst = (u16 *)job->dst; - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - const u16* src = (u16*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + const u16 *src = (u16 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { dst[dx] = PixelBlend16(dst[dx], src[f18_floor(src_x)]); } - dst = (u16*)((u8*)(dst)+job->dstPitch); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_TextureBlend_32_to_32( const SBlitJob * job ) + */ +static void executeBlit_TextureBlend_32_to_32(const SBlitJob *job) { const f18 wscale = f32_to_f18(job->x_stretch); const f18 hscale = f32_to_f18(job->y_stretch); f18 src_y = f18_zero; - u32 *dst = (u32*)job->dst; - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - const u32* src = (u32*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + u32 *dst = (u32 *)job->dst; + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + const u32 *src = (u32 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { dst[dx] = PixelBlend32(dst[dx], src[f18_floor(src_x)]); } - dst = (u32*)((u8*)(dst)+job->dstPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_TextureBlendColor_16_to_16( const SBlitJob * job ) + */ +static void executeBlit_TextureBlendColor_16_to_16(const SBlitJob *job) { const u16 blend = video::A8R8G8B8toA1R5G5B5(job->argb); @@ -523,112 +461,100 @@ static void executeBlit_TextureBlendColor_16_to_16( const SBlitJob * job ) const f18 hscale = f32_to_f18(job->y_stretch); f18 src_y = f18_zero; - u16 *dst = (u16*)job->dst; - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - const u16* src = (u16*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + u16 *dst = (u16 *)job->dst; + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + const u16 *src = (u16 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { u16 c0 = src[f18_floor(src_x)]; if (0 == (c0 & 0x8000)) continue; dst[dx] = PixelMul16_2(c0, blend); } - dst = (u16*)((u8*)(dst)+job->dstPitch); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } - /*! -*/ -static void executeBlit_TextureBlendColor_32_to_32( const SBlitJob * job ) + */ +static void executeBlit_TextureBlendColor_32_to_32(const SBlitJob *job) { const f18 wscale = f32_to_f18(job->x_stretch); const f18 hscale = f32_to_f18(job->y_stretch); - u32* dst = (u32*)job->dst; + u32 *dst = (u32 *)job->dst; f18 src_y = f18_zero; - for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) - { - const u32* src = (u32*)((u8*)(job->src) + job->srcPitch*f18_floor(src_y)); + for (u32 dy = 0; dy < job->height; ++dy, src_y += hscale) { + const u32 *src = (u32 *)((u8 *)(job->src) + job->srcPitch * f18_floor(src_y)); f18 src_x = f18_zero; - for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) - { + for (u32 dx = 0; dx < job->width; ++dx, src_x += wscale) { dst[dx] = PixelBlend32(dst[dx], PixelMul32_2(src[f18_floor(src_x)], job->argb)); } - dst = (u32*)((u8*)(dst)+job->dstPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_Color_16_to_16( const SBlitJob * job ) + */ +static void executeBlit_Color_16_to_16(const SBlitJob *job) { const u16 c = video::A8R8G8B8toA1R5G5B5(job->argb); - u16 *dst = (u16*) job->dst; + u16 *dst = (u16 *)job->dst; - for ( u32 dy = 0; dy < job->height; ++dy ) - { + for (u32 dy = 0; dy < job->height; ++dy) { memset16(dst, c, job->srcPitch); - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_Color_32_to_32( const SBlitJob * job ) + */ +static void executeBlit_Color_32_to_32(const SBlitJob *job) { - u32 *dst = (u32*) job->dst; + u32 *dst = (u32 *)job->dst; - for ( u32 dy = 0; dy < job->height; ++dy ) - { - memset32( dst, job->argb, job->srcPitch ); - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + for (u32 dy = 0; dy < job->height; ++dy) { + memset32(dst, job->argb, job->srcPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_ColorAlpha_16_to_16( const SBlitJob * job ) + */ +static void executeBlit_ColorAlpha_16_to_16(const SBlitJob *job) { - u16 *dst = (u16*) job->dst; + u16 *dst = (u16 *)job->dst; - const u16 alpha = extractAlpha( job->argb ) >> 3; - if ( 0 == alpha ) + const u16 alpha = extractAlpha(job->argb) >> 3; + if (0 == alpha) return; - const u32 src = video::A8R8G8B8toA1R5G5B5( job->argb ); + const u32 src = video::A8R8G8B8toA1R5G5B5(job->argb); - for ( u32 dy = 0; dy != job->height; ++dy ) - { - for ( u32 dx = 0; dx != job->width; ++dx ) - { - dst[dx] = PixelBlend16( dst[dx], src, alpha ); + for (u32 dy = 0; dy != job->height; ++dy) { + for (u32 dx = 0; dx != job->width; ++dx) { + dst[dx] = PixelBlend16(dst[dx], src, alpha); } - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } /*! -*/ -static void executeBlit_ColorAlpha_32_to_32( const SBlitJob * job ) + */ +static void executeBlit_ColorAlpha_32_to_32(const SBlitJob *job) { - const u32 alpha = extractAlpha( job->argb ); + const u32 alpha = extractAlpha(job->argb); if (0 == alpha) return; - u32 *dst = (u32*)job->dst; - for ( u32 dy = 0; dy < job->height; ++dy ) - { - for ( u32 dx = 0; dx < job->width; ++dx ) - { - dst[dx] = PixelBlend32( dst[dx], job->argb, alpha ); + u32 *dst = (u32 *)job->dst; + for (u32 dy = 0; dy < job->height; ++dy) { + for (u32 dx = 0; dx < job->width; ++dx) { + dst[dx] = PixelBlend32(dst[dx], job->argb, alpha); } - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } - } /*! @@ -647,85 +573,76 @@ inline u16 PixelCombine16(const u16 c2, const u16 c1) /*! Combine alpha channels (increases alpha / reduces transparency) */ -static void executeBlit_TextureCombineColor_16_to_16( const SBlitJob * job ) +static void executeBlit_TextureCombineColor_16_to_16(const SBlitJob *job) { const u32 w = job->width * 2; const u32 h = job->height * 2; - u16* src = (u16*) job->src; - u16* dst = (u16*) job->dst; + u16 *src = (u16 *)job->src; + u16 *dst = (u16 *)job->dst; - const u16 jobColor = video::A8R8G8B8toA1R5G5B5( job->argb ); + const u16 jobColor = video::A8R8G8B8toA1R5G5B5(job->argb); /* Stretch not supported. */ - for ( u32 dy = 0; dy != h; dy++ ) - { - for ( u32 dx = 0; dx != w; dx++ ) - { + for (u32 dy = 0; dy != h; dy++) { + for (u32 dx = 0; dx != w; dx++) { const u16 src_x = src[dx]; const u16 dst_x = dst[dx]; - dst[dx] = PixelCombine16( dst_x, PixelMul16_2( src_x, jobColor ) ); + dst[dx] = PixelCombine16(dst_x, PixelMul16_2(src_x, jobColor)); } - src = (u16*) ( (u8*) (src) + job->srcPitch ); - dst = (u16*) ( (u8*) (dst) + job->dstPitch ); + src = (u16 *)((u8 *)(src) + job->srcPitch); + dst = (u16 *)((u8 *)(dst) + job->dstPitch); } } /*! Combine alpha channels (increases alpha / reduces transparency) */ -static void executeBlit_TextureCombineColor_16_to_24( const SBlitJob * job ) +static void executeBlit_TextureCombineColor_16_to_24(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u16 *src = static_cast(job->src); - u8 *dst = static_cast(job->dst); + const u16 *src = static_cast(job->src); + u8 *dst = static_cast(job->dst); - const u16 jobColor = video::A8R8G8B8toA1R5G5B5( job->argb ); + const u16 jobColor = video::A8R8G8B8toA1R5G5B5(job->argb); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u16*) ( (u8*) (job->src) + job->srcPitch*src_y ); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u16 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = (u32)(dx*wscale); - u32 color = PixelMul16_2( video::A1R5G5B5toA8R8G8B8(src[src_x]), jobColor); - u8 * writeTo = &dst[dx * 3]; - if ( video::getAlpha(src[src_x]) > 0 ) // only overlay if source has visible alpha (alpha == 1) + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = (u32)(dx * wscale); + u32 color = PixelMul16_2(video::A1R5G5B5toA8R8G8B8(src[src_x]), jobColor); + u8 *writeTo = &dst[dx * 3]; + if (video::getAlpha(src[src_x]) > 0) // only overlay if source has visible alpha (alpha == 1) { - *writeTo++ = (color >> 16)& 0xFF; + *writeTo++ = (color >> 16) & 0xFF; *writeTo++ = (color >> 8) & 0xFF; *writeTo++ = color & 0xFF; } } dst += job->dstPitch; } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { - u32 color = PixelMul16_2( video::A1R5G5B5toA8R8G8B8(src[dx]), jobColor); - u8 * writeTo = &dst[dx * 3]; - if ( video::getAlpha(src[dx]) > 0 ) // only overlay if source has visible alpha (alpha == 1) + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { + u32 color = PixelMul16_2(video::A1R5G5B5toA8R8G8B8(src[dx]), jobColor); + u8 *writeTo = &dst[dx * 3]; + if (video::getAlpha(src[dx]) > 0) // only overlay if source has visible alpha (alpha == 1) { - *writeTo++ = (color >> 16)& 0xFF; + *writeTo++ = (color >> 16) & 0xFF; *writeTo++ = (color >> 8) & 0xFF; *writeTo++ = color & 0xFF; } } - src = (u16*) ( (u8*) (src) + job->srcPitch ); + src = (u16 *)((u8 *)(src) + job->srcPitch); dst += job->dstPitch; } } @@ -745,8 +662,7 @@ inline u32 PixelCombine32(const u32 c2, const u32 c1) if (0 == alpha) return c2; - if (0xFF000000 == alpha) - { + if (0xFF000000 == alpha) { return c1; } @@ -762,7 +678,6 @@ inline u32 PixelCombine32(const u32 c2, const u32 c1) u32 dstRB = c2 & 0x00FF00FF; u32 dstXG = c2 & 0x0000FF00; - u32 rb = srcRB - dstRB; u32 xg = srcXG - dstXG; @@ -787,51 +702,44 @@ inline u32 PixelCombine32(const u32 c2, const u32 c1) Combine alpha channels (increases alpha / reduces transparency) Destination alpha is treated as full 255 */ -static void executeBlit_TextureCombineColor_32_to_24( const SBlitJob * job ) +static void executeBlit_TextureCombineColor_32_to_24(const SBlitJob *job) { const u32 w = job->width; const u32 h = job->height; - const u32 *src = static_cast(job->src); - u8 *dst = static_cast(job->dst); + const u32 *src = static_cast(job->src); + u8 *dst = static_cast(job->dst); - if (job->stretch) - { + if (job->stretch) { const float wscale = job->x_stretch; const float hscale = job->y_stretch; - for ( u32 dy = 0; dy < h; ++dy ) - { - const u32 src_y = (u32)(dy*hscale); - src = (u32*) ( (u8*) (job->src) + job->srcPitch*src_y); + for (u32 dy = 0; dy < h; ++dy) { + const u32 src_y = (u32)(dy * hscale); + src = (u32 *)((u8 *)(job->src) + job->srcPitch * src_y); - for ( u32 dx = 0; dx < w; ++dx ) - { - const u32 src_x = src[(u32)(dx*wscale)]; - u8* writeTo = &dst[dx * 3]; + for (u32 dx = 0; dx < w; ++dx) { + const u32 src_x = src[(u32)(dx * wscale)]; + u8 *writeTo = &dst[dx * 3]; const u32 dst_x = 0xFF000000 | writeTo[0] << 16 | writeTo[1] << 8 | writeTo[2]; - const u32 combo = PixelCombine32( dst_x, PixelMul32_2( src_x, job->argb ) ); + const u32 combo = PixelCombine32(dst_x, PixelMul32_2(src_x, job->argb)); *writeTo++ = (combo >> 16) & 0xFF; *writeTo++ = (combo >> 8) & 0xFF; *writeTo++ = combo & 0xFF; } dst += job->dstPitch; } - } - else - { - for ( u32 dy = 0; dy != h; ++dy ) - { - for ( u32 dx = 0; dx != w; ++dx ) - { - u8* writeTo = &dst[dx * 3]; + } else { + for (u32 dy = 0; dy != h; ++dy) { + for (u32 dx = 0; dx != w; ++dx) { + u8 *writeTo = &dst[dx * 3]; const u32 dst_x = 0xFF000000 | writeTo[0] << 16 | writeTo[1] << 8 | writeTo[2]; - const u32 combo = PixelCombine32( dst_x, PixelMul32_2( src[dx], job->argb ) ); + const u32 combo = PixelCombine32(dst_x, PixelMul32_2(src[dx], job->argb)); *writeTo++ = (combo >> 16) & 0xFF; *writeTo++ = (combo >> 8) & 0xFF; *writeTo++ = combo & 0xFF; } - src = (u32*) ( (u8*) (src) + job->srcPitch ); + src = (u32 *)((u8 *)(src) + job->srcPitch); dst += job->dstPitch; } } @@ -840,19 +748,17 @@ static void executeBlit_TextureCombineColor_32_to_24( const SBlitJob * job ) /*! Combine alpha channels (increases alpha / reduces transparency) */ -static void executeBlit_TextureCombineColor_32_to_32( const SBlitJob * job ) +static void executeBlit_TextureCombineColor_32_to_32(const SBlitJob *job) { - u32 *src = (u32*) job->src; - u32 *dst = (u32*) job->dst; + u32 *src = (u32 *)job->src; + u32 *dst = (u32 *)job->dst; - for ( u32 dy = 0; dy != job->height; ++dy ) - { - for (u32 dx = 0; dx != job->width; ++dx ) - { - dst[dx] = PixelCombine32( dst[dx], PixelMul32_2( src[dx], job->argb ) ); + for (u32 dy = 0; dy != job->height; ++dy) { + for (u32 dx = 0; dx != job->width; ++dx) { + dst[dx] = PixelCombine32(dst[dx], PixelMul32_2(src[dx], job->argb)); } - src = (u32*) ( (u8*) (src) + job->srcPitch ); - dst = (u32*) ( (u8*) (dst) + job->dstPitch ); + src = (u32 *)((u8 *)(src) + job->srcPitch); + dst = (u32 *)((u8 *)(dst) + job->dstPitch); } } @@ -868,11 +774,10 @@ enum eBlitter BLITTER_TEXTURE_COMBINE_ALPHA, }; -typedef void (*tExecuteBlit) ( const SBlitJob * job ); - +typedef void (*tExecuteBlit)(const SBlitJob *job); /*! -*/ + */ struct blitterTable { eBlitter operation; @@ -882,73 +787,63 @@ struct blitterTable }; static const blitterTable blitTable[] = -{ - { BLITTER_TEXTURE, -2, -2, executeBlit_TextureCopy_x_to_x }, - { BLITTER_TEXTURE, video::ECF_A1R5G5B5, video::ECF_A8R8G8B8, executeBlit_TextureCopy_32_to_16 }, - { BLITTER_TEXTURE, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16 }, - { BLITTER_TEXTURE, video::ECF_A8R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCopy_16_to_32 }, - { BLITTER_TEXTURE, video::ECF_A8R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_32 }, - { BLITTER_TEXTURE, video::ECF_R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCopy_16_to_24 }, - { BLITTER_TEXTURE, video::ECF_R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCopy_32_to_24 }, - { BLITTER_TEXTURE_ALPHA_BLEND, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureBlend_16_to_16 }, - { BLITTER_TEXTURE_ALPHA_BLEND, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureBlend_32_to_32 }, - { BLITTER_TEXTURE_ALPHA_COLOR_BLEND, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureBlendColor_16_to_16 }, - { BLITTER_TEXTURE_ALPHA_COLOR_BLEND, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureBlendColor_32_to_32 }, - { BLITTER_COLOR, video::ECF_A1R5G5B5, -1, executeBlit_Color_16_to_16 }, - { BLITTER_COLOR, video::ECF_A8R8G8B8, -1, executeBlit_Color_32_to_32 }, - { BLITTER_COLOR_ALPHA, video::ECF_A1R5G5B5, -1, executeBlit_ColorAlpha_16_to_16 }, - { BLITTER_COLOR_ALPHA, video::ECF_A8R8G8B8, -1, executeBlit_ColorAlpha_32_to_32 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCombineColor_32_to_32 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A8R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_32 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCombineColor_32_to_24 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_x_to_x }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureCombineColor_16_to_16 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16 }, - { BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCombineColor_16_to_24 }, - { BLITTER_INVALID, -1, -1, 0 } -}; - - -static inline tExecuteBlit getBlitter2( eBlitter operation,const video::IImage * dest,const video::IImage * source ) -{ - video::ECOLOR_FORMAT sourceFormat = (video::ECOLOR_FORMAT) ( source ? source->getColorFormat() : -1 ); - video::ECOLOR_FORMAT destFormat = (video::ECOLOR_FORMAT) ( dest ? dest->getColorFormat() : -1 ); - - const blitterTable * b = blitTable; - - while ( b->operation != BLITTER_INVALID ) - { - if ( b->operation == operation ) { - if (( b->destFormat == -1 || b->destFormat == destFormat ) && - ( b->sourceFormat == -1 || b->sourceFormat == sourceFormat ) ) - return b->func; - else - if ( b->destFormat == -2 && ( sourceFormat == destFormat ) ) - return b->func; + {BLITTER_TEXTURE, -2, -2, executeBlit_TextureCopy_x_to_x}, + {BLITTER_TEXTURE, video::ECF_A1R5G5B5, video::ECF_A8R8G8B8, executeBlit_TextureCopy_32_to_16}, + {BLITTER_TEXTURE, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16}, + {BLITTER_TEXTURE, video::ECF_A8R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCopy_16_to_32}, + {BLITTER_TEXTURE, video::ECF_A8R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_32}, + {BLITTER_TEXTURE, video::ECF_R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCopy_16_to_24}, + {BLITTER_TEXTURE, video::ECF_R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCopy_32_to_24}, + {BLITTER_TEXTURE_ALPHA_BLEND, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureBlend_16_to_16}, + {BLITTER_TEXTURE_ALPHA_BLEND, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureBlend_32_to_32}, + {BLITTER_TEXTURE_ALPHA_COLOR_BLEND, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureBlendColor_16_to_16}, + {BLITTER_TEXTURE_ALPHA_COLOR_BLEND, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureBlendColor_32_to_32}, + {BLITTER_COLOR, video::ECF_A1R5G5B5, -1, executeBlit_Color_16_to_16}, + {BLITTER_COLOR, video::ECF_A8R8G8B8, -1, executeBlit_Color_32_to_32}, + {BLITTER_COLOR_ALPHA, video::ECF_A1R5G5B5, -1, executeBlit_ColorAlpha_16_to_16}, + {BLITTER_COLOR_ALPHA, video::ECF_A8R8G8B8, -1, executeBlit_ColorAlpha_32_to_32}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A8R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCombineColor_32_to_32}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A8R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_32}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_A8R8G8B8, executeBlit_TextureCombineColor_32_to_24}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_R8G8B8, executeBlit_TextureCopy_x_to_x}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_A1R5G5B5, executeBlit_TextureCombineColor_16_to_16}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_A1R5G5B5, video::ECF_R8G8B8, executeBlit_TextureCopy_24_to_16}, + {BLITTER_TEXTURE_COMBINE_ALPHA, video::ECF_R8G8B8, video::ECF_A1R5G5B5, executeBlit_TextureCombineColor_16_to_24}, + {BLITTER_INVALID, -1, -1, 0}}; + +static inline tExecuteBlit getBlitter2(eBlitter operation, const video::IImage *dest, const video::IImage *source) +{ + video::ECOLOR_FORMAT sourceFormat = (video::ECOLOR_FORMAT)(source ? source->getColorFormat() : -1); + video::ECOLOR_FORMAT destFormat = (video::ECOLOR_FORMAT)(dest ? dest->getColorFormat() : -1); + + const blitterTable *b = blitTable; + + while (b->operation != BLITTER_INVALID) { + if (b->operation == operation) { + if ((b->destFormat == -1 || b->destFormat == destFormat) && + (b->sourceFormat == -1 || b->sourceFormat == sourceFormat)) + return b->func; + else if (b->destFormat == -2 && (sourceFormat == destFormat)) + return b->func; } b += 1; } return 0; } - // bounce clipping to texture inline void setClip(AbsRectangle &out, const core::rect *clip, - const video::IImage* tex, s32 passnative, const core::dimension2d* tex_org) + const video::IImage *tex, s32 passnative, const core::dimension2d *tex_org) { - if (0 == tex) - { - if (clip && passnative) - { + if (0 == tex) { + if (clip && passnative) { out.x0 = clip->UpperLeftCorner.X; out.x1 = clip->LowerRightCorner.X; out.y0 = clip->UpperLeftCorner.Y; out.y1 = clip->LowerRightCorner.Y; - } - else - { + } else { out.x0 = 0; out.x1 = 0; out.y0 = 0; @@ -960,46 +855,39 @@ inline void setClip(AbsRectangle &out, const core::rect *clip, const s32 w = tex->getDimension().Width; const s32 h = tex->getDimension().Height; - //driver could have changed texture size. - if (clip && tex_org && ((u32)w != tex_org->Width || (u32)h != tex_org->Height)) - { - out.x0 = core::s32_clamp((clip->UpperLeftCorner.X*w) / tex_org->Width, 0, w - 1); - out.x1 = core::s32_clamp((clip->LowerRightCorner.X*w) / tex_org->Width, out.x0, w); - out.y0 = core::s32_clamp((clip->UpperLeftCorner.Y*h) / tex_org->Height, 0, h - 1); - out.y1 = core::s32_clamp((clip->LowerRightCorner.Y*h) / tex_org->Height, out.y0, h); - } - else if (clip) - { - //y-1 to prevent starting on illegal memory (not ideal!). + // driver could have changed texture size. + if (clip && tex_org && ((u32)w != tex_org->Width || (u32)h != tex_org->Height)) { + out.x0 = core::s32_clamp((clip->UpperLeftCorner.X * w) / tex_org->Width, 0, w - 1); + out.x1 = core::s32_clamp((clip->LowerRightCorner.X * w) / tex_org->Width, out.x0, w); + out.y0 = core::s32_clamp((clip->UpperLeftCorner.Y * h) / tex_org->Height, 0, h - 1); + out.y1 = core::s32_clamp((clip->LowerRightCorner.Y * h) / tex_org->Height, out.y0, h); + } else if (clip) { + // y-1 to prevent starting on illegal memory (not ideal!). out.x0 = core::s32_clamp(clip->UpperLeftCorner.X, 0, w - 1); out.x1 = core::s32_clamp(clip->LowerRightCorner.X, passnative ? 0 : out.x0, w); out.y0 = core::s32_clamp(clip->UpperLeftCorner.Y, 0, h - 1); out.y1 = core::s32_clamp(clip->LowerRightCorner.Y, passnative ? 0 : out.y0, h); - } - else - { + } else { out.x0 = 0; out.y0 = 0; out.x1 = w; out.y1 = h; } - } /*! a generic 2D Blitter */ static s32 Blit(eBlitter operation, - video::IImage * dest, + video::IImage *dest, const core::rect *destClipping, const core::position2d *destPos, - video::IImage * const source, + video::IImage *const source, const core::rect *sourceClipping, u32 argb) { - tExecuteBlit blitter = getBlitter2( operation, dest, source ); - if ( 0 == blitter ) - { + tExecuteBlit blitter = getBlitter2(operation, dest, source); + if (0 == blitter) { return 0; } @@ -1010,23 +898,23 @@ static s32 Blit(eBlitter operation, SBlitJob job; - setClip ( sourceClip, sourceClipping, source, 1,0 ); - setClip ( destClip, destClipping, dest, 0,0 ); + setClip(sourceClip, sourceClipping, source, 1, 0); + setClip(destClip, destClipping, dest, 0, 0); v.x0 = destPos ? destPos->X : 0; v.y0 = destPos ? destPos->Y : 0; - v.x1 = v.x0 + ( sourceClip.x1 - sourceClip.x0 ); - v.y1 = v.y0 + ( sourceClip.y1 - sourceClip.y0 ); + v.x1 = v.x0 + (sourceClip.x1 - sourceClip.x0); + v.y1 = v.y0 + (sourceClip.y1 - sourceClip.y0); - if ( !intersect( job.Dest, destClip, v ) ) + if (!intersect(job.Dest, destClip, v)) return 0; job.width = job.Dest.x1 - job.Dest.x0; job.height = job.Dest.y1 - job.Dest.y0; - job.Source.x0 = sourceClip.x0 + ( job.Dest.x0 - v.x0 ); + job.Source.x0 = sourceClip.x0 + (job.Dest.x0 - v.x0); job.Source.x1 = job.Source.x0 + job.width; - job.Source.y0 = sourceClip.y0 + ( job.Dest.y0 - v.y0 ); + job.Source.y0 = sourceClip.y0 + (job.Dest.y0 - v.y0); job.Source.y1 = job.Source.y0 + job.height; job.argb = argb; @@ -1035,23 +923,20 @@ static s32 Blit(eBlitter operation, job.x_stretch = 1.f; job.y_stretch = 1.f; - if ( source ) - { + if (source) { job.srcPitch = source->getPitch(); job.srcPixelMul = source->getBytesPerPixel(); - job.src = (void*) ( (u8*) source->getData() + ( job.Source.y0 * job.srcPitch ) + ( job.Source.x0 * job.srcPixelMul ) ); - } - else - { + job.src = (void *)((u8 *)source->getData() + (job.Source.y0 * job.srcPitch) + (job.Source.x0 * job.srcPixelMul)); + } else { // use srcPitch for color operation on dest job.srcPitch = job.width * dest->getBytesPerPixel(); } job.dstPitch = dest->getPitch(); job.dstPixelMul = dest->getBytesPerPixel(); - job.dst = (void*) ( (u8*) dest->getData() + ( job.Dest.y0 * job.dstPitch ) + ( job.Dest.x0 * job.dstPixelMul ) ); + job.dst = (void *)((u8 *)dest->getData() + (job.Dest.y0 * job.dstPitch) + (job.Dest.x0 * job.dstPixelMul)); - blitter( &job ); + blitter(&job); return 1; } diff --git a/source/Irrlicht/CBoneSceneNode.cpp b/source/Irrlicht/CBoneSceneNode.cpp index 0df5b809..b9eb8892 100644 --- a/source/Irrlicht/CBoneSceneNode.cpp +++ b/source/Irrlicht/CBoneSceneNode.cpp @@ -12,25 +12,24 @@ namespace scene { //! constructor -CBoneSceneNode::CBoneSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - u32 boneIndex, const std::optional &boneName) -: IBoneSceneNode(parent, mgr, id), BoneIndex(boneIndex), - AnimationMode(EBAM_AUTOMATIC), SkinningSpace(EBSS_LOCAL) +CBoneSceneNode::CBoneSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + u32 boneIndex, const std::optional &boneName) : + IBoneSceneNode(parent, mgr, id), + BoneIndex(boneIndex), + AnimationMode(EBAM_AUTOMATIC), SkinningSpace(EBSS_LOCAL) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CBoneSceneNode"); - #endif +#endif setName(boneName); } - //! Returns the index of the bone u32 CBoneSceneNode::getBoneIndex() const { return BoneIndex; } - //! Sets the animation mode of the bone. Returns true if successful. bool CBoneSceneNode::setAnimationMode(E_BONE_ANIMATION_MODE mode) { @@ -38,21 +37,18 @@ bool CBoneSceneNode::setAnimationMode(E_BONE_ANIMATION_MODE mode) return true; } - //! Gets the current animation mode of the bone E_BONE_ANIMATION_MODE CBoneSceneNode::getAnimationMode() const { return AnimationMode; } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CBoneSceneNode::getBoundingBox() const +const core::aabbox3d &CBoneSceneNode::getBoundingBox() const { return Box; } - /* //! Returns the relative transformation of the scene node. core::matrix4 CBoneSceneNode::getRelativeTransformation() const @@ -61,13 +57,11 @@ core::matrix4 CBoneSceneNode::getRelativeTransformation() const } */ - void CBoneSceneNode::OnAnimate(u32 timeMs) { - if (IsVisible) - { + if (IsVisible) { // update absolute position - //updateAbsolutePosition(); + // updateAbsolutePosition(); // perform the post render process on all children ISceneNodeList::iterator it = Children.begin(); @@ -76,24 +70,20 @@ void CBoneSceneNode::OnAnimate(u32 timeMs) } } - void CBoneSceneNode::helper_updateAbsolutePositionOfAllChildren(ISceneNode *Node) { Node->updateAbsolutePosition(); ISceneNodeList::const_iterator it = Node->getChildren().begin(); - for (; it != Node->getChildren().end(); ++it) - { - helper_updateAbsolutePositionOfAllChildren( (*it) ); + for (; it != Node->getChildren().end(); ++it) { + helper_updateAbsolutePositionOfAllChildren((*it)); } } - void CBoneSceneNode::updateAbsolutePositionOfAllChildren() { - helper_updateAbsolutePositionOfAllChildren( this ); + helper_updateAbsolutePositionOfAllChildren(this); } - } // namespace scene } // namespace irr diff --git a/source/Irrlicht/CBoneSceneNode.h b/source/Irrlicht/CBoneSceneNode.h index 4b470951..8e1a0f7a 100644 --- a/source/Irrlicht/CBoneSceneNode.h +++ b/source/Irrlicht/CBoneSceneNode.h @@ -15,59 +15,56 @@ namespace irr namespace scene { - class CBoneSceneNode : public IBoneSceneNode - { - public: - - //! constructor - CBoneSceneNode(ISceneNode* parent, ISceneManager* mgr, - s32 id=-1, u32 boneIndex=0, +class CBoneSceneNode : public IBoneSceneNode +{ +public: + //! constructor + CBoneSceneNode(ISceneNode *parent, ISceneManager *mgr, + s32 id = -1, u32 boneIndex = 0, const std::optional &boneName = std::nullopt); - //! Returns the index of the bone - u32 getBoneIndex() const override; + //! Returns the index of the bone + u32 getBoneIndex() const override; - //! Sets the animation mode of the bone. Returns true if successful. - bool setAnimationMode(E_BONE_ANIMATION_MODE mode) override; + //! Sets the animation mode of the bone. Returns true if successful. + bool setAnimationMode(E_BONE_ANIMATION_MODE mode) override; - //! Gets the current animation mode of the bone - E_BONE_ANIMATION_MODE getAnimationMode() const override; + //! Gets the current animation mode of the bone + E_BONE_ANIMATION_MODE getAnimationMode() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - /* - //! Returns the relative transformation of the scene node. - //core::matrix4 getRelativeTransformation() const override; - */ + /* + //! Returns the relative transformation of the scene node. + //core::matrix4 getRelativeTransformation() const override; + */ - void OnAnimate(u32 timeMs) override; + void OnAnimate(u32 timeMs) override; - void updateAbsolutePositionOfAllChildren() override; + void updateAbsolutePositionOfAllChildren() override; - //! How the relative transformation of the bone is used - void setSkinningSpace(E_BONE_SKINNING_SPACE space) override - { - SkinningSpace=space; - } + //! How the relative transformation of the bone is used + void setSkinningSpace(E_BONE_SKINNING_SPACE space) override + { + SkinningSpace = space; + } - E_BONE_SKINNING_SPACE getSkinningSpace() const override - { - return SkinningSpace; - } + E_BONE_SKINNING_SPACE getSkinningSpace() const override + { + return SkinningSpace; + } - private: - void helper_updateAbsolutePositionOfAllChildren(ISceneNode *Node); +private: + void helper_updateAbsolutePositionOfAllChildren(ISceneNode *Node); - u32 BoneIndex; + u32 BoneIndex; - core::aabbox3d Box; - - E_BONE_ANIMATION_MODE AnimationMode; - E_BONE_SKINNING_SPACE SkinningSpace; - }; + core::aabbox3d Box; + E_BONE_ANIMATION_MODE AnimationMode; + E_BONE_SKINNING_SPACE SkinningSpace; +}; } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CCameraSceneNode.cpp b/source/Irrlicht/CCameraSceneNode.cpp index 95c83c23..e480a114 100644 --- a/source/Irrlicht/CCameraSceneNode.cpp +++ b/source/Irrlicht/CCameraSceneNode.cpp @@ -12,29 +12,27 @@ namespace irr namespace scene { - //! constructor -CCameraSceneNode::CCameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position, const core::vector3df& lookat) - : ICameraSceneNode(parent, mgr, id, position), - BoundingBox(core::vector3df(0, 0, 0)), // Camera has no size. Still not sure if FLT_MAX might be the better variant - Target(lookat), UpVector(0.0f, 1.0f, 0.0f), ZNear(1.0f), ZFar(3000.0f), - InputReceiverEnabled(true), TargetAndRotationAreBound(false) +CCameraSceneNode::CCameraSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position, const core::vector3df &lookat) : + ICameraSceneNode(parent, mgr, id, position), + BoundingBox(core::vector3df(0, 0, 0)), // Camera has no size. Still not sure if FLT_MAX might be the better variant + Target(lookat), UpVector(0.0f, 1.0f, 0.0f), ZNear(1.0f), ZFar(3000.0f), + InputReceiverEnabled(true), TargetAndRotationAreBound(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CCameraSceneNode"); - #endif +#endif // set default projection - Fovy = core::PI / 2.5f; // Field of view, in radians. + Fovy = core::PI / 2.5f; // Field of view, in radians. Aspect = 4.0f / 3.0f; // Aspect ratio. - const video::IVideoDriver* const d = mgr?mgr->getVideoDriver():0; - if (d) - { - if ( d->getCurrentRenderTargetSize().Height ) + const video::IVideoDriver *const d = mgr ? mgr->getVideoDriver() : 0; + if (d) { + if (d->getCurrentRenderTargetSize().Height) Aspect = (f32)d->getCurrentRenderTargetSize().Width / - (f32)d->getCurrentRenderTargetSize().Height; + (f32)d->getCurrentRenderTargetSize().Height; } ViewArea.setFarNearDistance(ZFar - ZNear); @@ -42,153 +40,134 @@ CCameraSceneNode::CCameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 i recalculateViewArea(); } - //! Disables or enables the camera to get key or mouse inputs. void CCameraSceneNode::setInputReceiverEnabled(bool enabled) { InputReceiverEnabled = enabled; } - //! Returns if the input receiver of the camera is currently enabled. bool CCameraSceneNode::isInputReceiverEnabled() const { return InputReceiverEnabled; } - //! Sets the projection matrix of the camera. /** The core::matrix4 class has some methods to build a projection matrix. e.g: core::matrix4::buildProjectionMatrixPerspectiveFovLH \param projection: The new projection matrix of the camera. */ -void CCameraSceneNode::setProjectionMatrix(const core::matrix4& projection, bool isOrthogonal) +void CCameraSceneNode::setProjectionMatrix(const core::matrix4 &projection, bool isOrthogonal) { IsOrthogonal = isOrthogonal; - ViewArea.getTransform ( video::ETS_PROJECTION ) = projection; + ViewArea.getTransform(video::ETS_PROJECTION) = projection; } - //! Gets the current projection matrix of the camera //! \return Returns the current projection matrix of the camera. -const core::matrix4& CCameraSceneNode::getProjectionMatrix() const +const core::matrix4 &CCameraSceneNode::getProjectionMatrix() const { - return ViewArea.getTransform ( video::ETS_PROJECTION ); + return ViewArea.getTransform(video::ETS_PROJECTION); } - //! Gets the current view matrix of the camera //! \return Returns the current view matrix of the camera. -const core::matrix4& CCameraSceneNode::getViewMatrix() const +const core::matrix4 &CCameraSceneNode::getViewMatrix() const { - return ViewArea.getTransform ( video::ETS_VIEW ); + return ViewArea.getTransform(video::ETS_VIEW); } - //! Sets a custom view matrix affector. The matrix passed here, will be //! multiplied with the view matrix when it gets updated. //! This allows for custom camera setups like, for example, a reflection camera. /** \param affector: The affector matrix. */ -void CCameraSceneNode::setViewMatrixAffector(const core::matrix4& affector) +void CCameraSceneNode::setViewMatrixAffector(const core::matrix4 &affector) { Affector = affector; } - //! Gets the custom view matrix affector. -const core::matrix4& CCameraSceneNode::getViewMatrixAffector() const +const core::matrix4 &CCameraSceneNode::getViewMatrixAffector() const { return Affector; } - //! It is possible to send mouse and key events to the camera. Most cameras //! may ignore this input, but camera scene nodes which are created for //! example with scene::ISceneManager::addMayaCameraSceneNode or //! scene::ISceneManager::addFPSCameraSceneNode, may want to get this input //! for changing their position, look at target or whatever. -bool CCameraSceneNode::OnEvent(const SEvent& event) +bool CCameraSceneNode::OnEvent(const SEvent &event) { // animators have been deleted; nothing happens here now! return false; } - //! sets the look at target of the camera //! \param pos: Look at target of the camera. -void CCameraSceneNode::setTarget(const core::vector3df& pos) +void CCameraSceneNode::setTarget(const core::vector3df &pos) { Target = pos; - if(TargetAndRotationAreBound) - { + if (TargetAndRotationAreBound) { const core::vector3df toTarget = Target - getAbsolutePosition(); ISceneNode::setRotation(toTarget.getHorizontalAngle()); } } - //! Sets the rotation of the node. /** This only modifies the relative rotation of the node. If the camera's target and rotation are bound ( @see bindTargetAndRotation() ) then calling this will also change the camera's target to match the rotation. \param rotation New rotation of the node in degrees. */ -void CCameraSceneNode::setRotation(const core::vector3df& rotation) +void CCameraSceneNode::setRotation(const core::vector3df &rotation) { - if(TargetAndRotationAreBound) + if (TargetAndRotationAreBound) Target = getAbsolutePosition() + rotation.rotationToDirection(); ISceneNode::setRotation(rotation); } - //! Gets the current look at target of the camera //! \return Returns the current look at target of the camera -const core::vector3df& CCameraSceneNode::getTarget() const +const core::vector3df &CCameraSceneNode::getTarget() const { return Target; } - //! sets the up vector of the camera //! \param pos: New upvector of the camera. -void CCameraSceneNode::setUpVector(const core::vector3df& pos) +void CCameraSceneNode::setUpVector(const core::vector3df &pos) { UpVector = pos; } - //! Gets the up vector of the camera. //! \return Returns the up vector of the camera. -const core::vector3df& CCameraSceneNode::getUpVector() const +const core::vector3df &CCameraSceneNode::getUpVector() const { return UpVector; } - f32 CCameraSceneNode::getNearValue() const { return ZNear; } - f32 CCameraSceneNode::getFarValue() const { return ZFar; } - f32 CCameraSceneNode::getAspectRatio() const { return Aspect; } - f32 CCameraSceneNode::getFOV() const { return Fovy; } - void CCameraSceneNode::setNearValue(f32 f) { ZNear = f; @@ -196,7 +175,6 @@ void CCameraSceneNode::setNearValue(f32 f) ViewArea.setFarNearDistance(ZFar - ZNear); } - void CCameraSceneNode::setFarValue(f32 f) { ZFar = f; @@ -204,48 +182,42 @@ void CCameraSceneNode::setFarValue(f32 f) ViewArea.setFarNearDistance(ZFar - ZNear); } - void CCameraSceneNode::setAspectRatio(f32 f) { Aspect = f; recalculateProjectionMatrix(); } - void CCameraSceneNode::setFOV(f32 f) { Fovy = f; recalculateProjectionMatrix(); } - void CCameraSceneNode::recalculateProjectionMatrix() { - ViewArea.getTransform ( video::ETS_PROJECTION ).buildProjectionMatrixPerspectiveFovLH(Fovy, Aspect, ZNear, ZFar, false); + ViewArea.getTransform(video::ETS_PROJECTION).buildProjectionMatrixPerspectiveFovLH(Fovy, Aspect, ZNear, ZFar, false); IsOrthogonal = false; } - //! prerender void CCameraSceneNode::OnRegisterSceneNode() { - if ( SceneManager->getActiveCamera () == this ) + if (SceneManager->getActiveCamera() == this) SceneManager->registerNodeForRendering(this, ESNRP_CAMERA); ISceneNode::OnRegisterSceneNode(); } - //! render void CCameraSceneNode::render() { updateMatrices(); - video::IVideoDriver* driver = SceneManager->getVideoDriver(); - if ( driver) - { - driver->setTransform(video::ETS_PROJECTION, ViewArea.getTransform ( video::ETS_PROJECTION) ); - driver->setTransform(video::ETS_VIEW, ViewArea.getTransform ( video::ETS_VIEW) ); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); + if (driver) { + driver->setTransform(video::ETS_PROJECTION, ViewArea.getTransform(video::ETS_PROJECTION)); + driver->setTransform(video::ETS_VIEW, ViewArea.getTransform(video::ETS_VIEW)); } } @@ -263,8 +235,7 @@ void CCameraSceneNode::updateMatrices() f32 dp = tgtv.dotProduct(up); - if ( core::equals(core::abs_(dp), 1.f) ) - { + if (core::equals(core::abs_(dp), 1.f)) { up.X += 0.5f; } @@ -274,46 +245,41 @@ void CCameraSceneNode::updateMatrices() } //! returns the axis aligned bounding box of this node -const core::aabbox3d& CCameraSceneNode::getBoundingBox() const +const core::aabbox3d &CCameraSceneNode::getBoundingBox() const { return BoundingBox; } - //! returns the view frustum. -const SViewFrustum* CCameraSceneNode::getViewFrustum() const +const SViewFrustum *CCameraSceneNode::getViewFrustum() const { return &ViewArea; } - void CCameraSceneNode::recalculateViewArea() { ViewArea.cameraPosition = getAbsolutePosition(); core::matrix4 m(core::matrix4::EM4CONST_NOTHING); m.setbyproduct_nocheck(ViewArea.getTransform(video::ETS_PROJECTION), - ViewArea.getTransform(video::ETS_VIEW)); + ViewArea.getTransform(video::ETS_VIEW)); ViewArea.setFrom(m, false); } - //! Set the binding between the camera's rotation adn target. void CCameraSceneNode::bindTargetAndRotation(bool bound) { TargetAndRotationAreBound = bound; } - //! Gets the binding between the camera's rotation and target. bool CCameraSceneNode::getTargetAndRotationBinding(void) const { return TargetAndRotationAreBound; } - //! Creates a clone of this scene node and its children. -ISceneNode* CCameraSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) +ISceneNode *CCameraSceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { ICameraSceneNode::clone(newParent, newManager); @@ -322,8 +288,8 @@ ISceneNode* CCameraSceneNode::clone(ISceneNode* newParent, ISceneManager* newMan if (!newManager) newManager = SceneManager; - CCameraSceneNode* nb = new CCameraSceneNode(newParent, - newManager, ID, RelativeTranslation, Target); + CCameraSceneNode *nb = new CCameraSceneNode(newParent, + newManager, ID, RelativeTranslation, Target); nb->ISceneNode::cloneMembers(this, newManager); nb->ICameraSceneNode::cloneMembers(this); @@ -339,12 +305,10 @@ ISceneNode* CCameraSceneNode::clone(ISceneNode* newParent, ISceneManager* newMan nb->InputReceiverEnabled = InputReceiverEnabled; nb->TargetAndRotationAreBound = TargetAndRotationAreBound; - if ( newParent ) + if (newParent) nb->drop(); return nb; } - } // end namespace } // end namespace - diff --git a/source/Irrlicht/CCameraSceneNode.h b/source/Irrlicht/CCameraSceneNode.h index 91939dae..ad21a965 100644 --- a/source/Irrlicht/CCameraSceneNode.h +++ b/source/Irrlicht/CCameraSceneNode.h @@ -12,156 +12,154 @@ namespace irr namespace scene { - class CCameraSceneNode : public ICameraSceneNode - { - public: +class CCameraSceneNode : public ICameraSceneNode +{ +public: + //! constructor + CCameraSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &lookat = core::vector3df(0, 0, 100)); - //! constructor - CCameraSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& lookat = core::vector3df(0,0,100)); + //! Sets the projection matrix of the camera. + /** The core::matrix4 class has some methods + to build a projection matrix. e.g: core::matrix4::buildProjectionMatrixPerspectiveFovLH. + Note that the matrix will only stay as set by this method until one of + the following Methods are called: setNearValue, setFarValue, setAspectRatio, setFOV. + \param projection The new projection matrix of the camera. + \param isOrthogonal Set this to true if the matrix is an orthogonal one (e.g. + from matrix4::buildProjectionMatrixOrthoLH(). */ + void setProjectionMatrix(const core::matrix4 &projection, bool isOrthogonal = false) override; - //! Sets the projection matrix of the camera. - /** The core::matrix4 class has some methods - to build a projection matrix. e.g: core::matrix4::buildProjectionMatrixPerspectiveFovLH. - Note that the matrix will only stay as set by this method until one of - the following Methods are called: setNearValue, setFarValue, setAspectRatio, setFOV. - \param projection The new projection matrix of the camera. - \param isOrthogonal Set this to true if the matrix is an orthogonal one (e.g. - from matrix4::buildProjectionMatrixOrthoLH(). */ - void setProjectionMatrix(const core::matrix4& projection, bool isOrthogonal = false) override; + //! Gets the current projection matrix of the camera + //! \return Returns the current projection matrix of the camera. + const core::matrix4 &getProjectionMatrix() const override; - //! Gets the current projection matrix of the camera - //! \return Returns the current projection matrix of the camera. - const core::matrix4& getProjectionMatrix() const override; + //! Gets the current view matrix of the camera + //! \return Returns the current view matrix of the camera. + const core::matrix4 &getViewMatrix() const override; - //! Gets the current view matrix of the camera - //! \return Returns the current view matrix of the camera. - const core::matrix4& getViewMatrix() const override; + //! Sets a custom view matrix affector. + /** \param affector: The affector matrix. */ + void setViewMatrixAffector(const core::matrix4 &affector) override; - //! Sets a custom view matrix affector. - /** \param affector: The affector matrix. */ - void setViewMatrixAffector(const core::matrix4& affector) override; + //! Gets the custom view matrix affector. + const core::matrix4 &getViewMatrixAffector() const override; - //! Gets the custom view matrix affector. - const core::matrix4& getViewMatrixAffector() const override; + //! It is possible to send mouse and key events to the camera. Most cameras + //! may ignore this input, but camera scene nodes which are created for + //! example with scene::ISceneManager::addMayaCameraSceneNode or + //! scene::ISceneManager::addMeshViewerCameraSceneNode, may want to get this input + //! for changing their position, look at target or whatever. + bool OnEvent(const SEvent &event) override; - //! It is possible to send mouse and key events to the camera. Most cameras - //! may ignore this input, but camera scene nodes which are created for - //! example with scene::ISceneManager::addMayaCameraSceneNode or - //! scene::ISceneManager::addMeshViewerCameraSceneNode, may want to get this input - //! for changing their position, look at target or whatever. - bool OnEvent(const SEvent& event) override; + //! Sets the look at target of the camera + /** If the camera's target and rotation are bound ( @see bindTargetAndRotation() ) + then calling this will also change the camera's scene node rotation to match the target. + \param pos: Look at target of the camera. */ + void setTarget(const core::vector3df &pos) override; - //! Sets the look at target of the camera - /** If the camera's target and rotation are bound ( @see bindTargetAndRotation() ) - then calling this will also change the camera's scene node rotation to match the target. - \param pos: Look at target of the camera. */ - void setTarget(const core::vector3df& pos) override; + //! Sets the rotation of the node. + /** This only modifies the relative rotation of the node. + If the camera's target and rotation are bound ( @see bindTargetAndRotation() ) + then calling this will also change the camera's target to match the rotation. + \param rotation New rotation of the node in degrees. */ + void setRotation(const core::vector3df &rotation) override; - //! Sets the rotation of the node. - /** This only modifies the relative rotation of the node. - If the camera's target and rotation are bound ( @see bindTargetAndRotation() ) - then calling this will also change the camera's target to match the rotation. - \param rotation New rotation of the node in degrees. */ - void setRotation(const core::vector3df& rotation) override; + //! Gets the current look at target of the camera + /** \return The current look at target of the camera */ + const core::vector3df &getTarget() const override; - //! Gets the current look at target of the camera - /** \return The current look at target of the camera */ - const core::vector3df& getTarget() const override; + //! Sets the up vector of the camera. + //! \param pos: New upvector of the camera. + void setUpVector(const core::vector3df &pos) override; - //! Sets the up vector of the camera. - //! \param pos: New upvector of the camera. - void setUpVector(const core::vector3df& pos) override; + //! Gets the up vector of the camera. + //! \return Returns the up vector of the camera. + const core::vector3df &getUpVector() const override; - //! Gets the up vector of the camera. - //! \return Returns the up vector of the camera. - const core::vector3df& getUpVector() const override; + //! Gets distance from the camera to the near plane. + //! \return Value of the near plane of the camera. + f32 getNearValue() const override; - //! Gets distance from the camera to the near plane. - //! \return Value of the near plane of the camera. - f32 getNearValue() const override; + //! Gets the distance from the camera to the far plane. + //! \return Value of the far plane of the camera. + f32 getFarValue() const override; - //! Gets the distance from the camera to the far plane. - //! \return Value of the far plane of the camera. - f32 getFarValue() const override; + //! Get the aspect ratio of the camera. + //! \return The aspect ratio of the camera. + f32 getAspectRatio() const override; - //! Get the aspect ratio of the camera. - //! \return The aspect ratio of the camera. - f32 getAspectRatio() const override; + //! Gets the field of view of the camera. + //! \return Field of view of the camera + f32 getFOV() const override; - //! Gets the field of view of the camera. - //! \return Field of view of the camera - f32 getFOV() const override; + //! Sets the value of the near clipping plane. (default: 1.0f) + void setNearValue(f32 zn) override; - //! Sets the value of the near clipping plane. (default: 1.0f) - void setNearValue(f32 zn) override; + //! Sets the value of the far clipping plane (default: 2000.0f) + void setFarValue(f32 zf) override; - //! Sets the value of the far clipping plane (default: 2000.0f) - void setFarValue(f32 zf) override; + //! Sets the aspect ratio (default: 4.0f / 3.0f) + void setAspectRatio(f32 aspect) override; - //! Sets the aspect ratio (default: 4.0f / 3.0f) - void setAspectRatio(f32 aspect) override; + //! Sets the field of view (Default: PI / 3.5f) + void setFOV(f32 fovy) override; - //! Sets the field of view (Default: PI / 3.5f) - void setFOV(f32 fovy) override; + //! PreRender event + void OnRegisterSceneNode() override; - //! PreRender event - void OnRegisterSceneNode() override; + //! Render + void render() override; - //! Render - void render() override; + //! Update + void updateMatrices() override; - //! Update - void updateMatrices() override; + //! Returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! Returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! Returns the view area. + const SViewFrustum *getViewFrustum() const override; - //! Returns the view area. - const SViewFrustum* getViewFrustum() const override; + //! Disables or enables the camera to get key or mouse inputs. + //! If this is set to true, the camera will respond to key inputs + //! otherwise not. + void setInputReceiverEnabled(bool enabled) override; - //! Disables or enables the camera to get key or mouse inputs. - //! If this is set to true, the camera will respond to key inputs - //! otherwise not. - void setInputReceiverEnabled(bool enabled) override; + //! Returns if the input receiver of the camera is currently enabled. + bool isInputReceiverEnabled() const override; - //! Returns if the input receiver of the camera is currently enabled. - bool isInputReceiverEnabled() const override; + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_CAMERA; } - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_CAMERA; } + //! Binds the camera scene node's rotation to its target position and vice versa, or unbinds them. + void bindTargetAndRotation(bool bound) override; - //! Binds the camera scene node's rotation to its target position and vice versa, or unbinds them. - void bindTargetAndRotation(bool bound) override; + //! Queries if the camera scene node's rotation and its target position are bound together. + bool getTargetAndRotationBinding(void) const override; - //! Queries if the camera scene node's rotation and its target position are bound together. - bool getTargetAndRotationBinding(void) const override; + //! Creates a clone of this scene node and its children. + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; - //! Creates a clone of this scene node and its children. - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; +protected: + void recalculateProjectionMatrix(); + void recalculateViewArea(); - protected: + core::aabbox3d BoundingBox; - void recalculateProjectionMatrix(); - void recalculateViewArea(); + core::vector3df Target; + core::vector3df UpVector; - core::aabbox3d BoundingBox; + f32 Fovy; // Field of view, in radians. + f32 Aspect; // Aspect ratio. + f32 ZNear; // value of the near view-plane. + f32 ZFar; // Z-value of the far view-plane. - core::vector3df Target; - core::vector3df UpVector; + SViewFrustum ViewArea; + core::matrix4 Affector; - f32 Fovy; // Field of view, in radians. - f32 Aspect; // Aspect ratio. - f32 ZNear; // value of the near view-plane. - f32 ZFar; // Z-value of the far view-plane. - - SViewFrustum ViewArea; - core::matrix4 Affector; - - bool InputReceiverEnabled; - bool TargetAndRotationAreBound; - }; + bool InputReceiverEnabled; + bool TargetAndRotationAreBound; +}; } // end namespace } // end namespace diff --git a/source/Irrlicht/CColorConverter.cpp b/source/Irrlicht/CColorConverter.cpp index 0e87d6c3..6f28fbe6 100644 --- a/source/Irrlicht/CColorConverter.cpp +++ b/source/Irrlicht/CColorConverter.cpp @@ -13,7 +13,7 @@ namespace video { //! converts a monochrome bitmap to A1R5G5B5 data -void CColorConverter::convert1BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, s32 linepad, bool flip) +void CColorConverter::convert1BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, s32 linepad, bool flip) { if (!in || !out) return; @@ -21,19 +21,17 @@ void CColorConverter::convert1BitTo16Bit(const u8* in, s16* out, s32 width, s32 if (flip) out += width * height; - for (s32 y=0; y>shift & 0x01 ? (s16)0xffff : (s16)0x8000; + for (s32 x = 0; x < width; ++x) { + out[x] = *in >> shift & 0x01 ? (s16)0xffff : (s16)0x8000; - if ((--shift)<0) // 8 pixel done + if ((--shift) < 0) // 8 pixel done { - shift=7; + shift = 7; ++in; } } @@ -47,33 +45,27 @@ void CColorConverter::convert1BitTo16Bit(const u8* in, s16* out, s32 width, s32 } } - - //! converts a 4 bit palettized image to A1R5G5B5 -void CColorConverter::convert4BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad, bool flip) +void CColorConverter::convert4BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, const s32 *palette, s32 linepad, bool flip) { if (!in || !out || !palette) return; if (flip) - out += width*height; + out += width * height; - for (s32 y=0; y> shift) & 0xf)]); - if (shift==0) - { + if (shift == 0) { shift = 4; ++in; - } - else + } else shift = 0; } @@ -86,10 +78,8 @@ void CColorConverter::convert4BitTo16Bit(const u8* in, s16* out, s32 width, s32 } } - - //! converts a 8 bit palettized image into A1R5G5B5 -void CColorConverter::convert8BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad, bool flip) +void CColorConverter::convert8BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, const s32 *palette, s32 linepad, bool flip) { if (!in || !out || !palette) return; @@ -97,12 +87,10 @@ void CColorConverter::convert8BitTo16Bit(const u8* in, s16* out, s32 width, s32 if (flip) out += width * height; - for (s32 y=0; y> 15)&0x1)<<31) | (((t >> 10)&0x1F)<<19) | - (((t >> 5)&0x1F)<<11) | (t&0x1F)<<3; - out[(s32)(y*newWidth + x)] = t; + for (s32 y = 0; y < newHeight; ++y) { + t = in[(s32)(((s32)sy) * currentWidth + x * sourceXStep)]; + t = (((t >> 15) & 0x1) << 31) | (((t >> 10) & 0x1F) << 19) | + (((t >> 5) & 0x1F) << 11) | (t & 0x1F) << 3; + out[(s32)(y * newWidth + x)] = t; - sy+=sourceYStep; + sy += sourceYStep; } } } - - //! copies X8R8G8B8 32 bit data -void CColorConverter::convert32BitTo32Bit(const s32* in, s32* out, s32 width, s32 height, s32 linepad, bool flip) +void CColorConverter::convert32BitTo32Bit(const s32 *in, s32 *out, s32 width, s32 height, s32 linepad, bool flip) { if (!in || !out) return; @@ -307,15 +267,14 @@ void CColorConverter::convert32BitTo32Bit(const s32* in, s32* out, s32 width, s3 if (flip) out += width * height; - for (s32 y=0; y> 7; dB[1] = (*sB & 0x03e0) >> 2; dB[0] = (*sB & 0x1f) << 3; @@ -342,13 +298,12 @@ void CColorConverter::convert_A1R5G5B5toR8G8B8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_A1R5G5B5toB8G8R8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A1R5G5B5toB8G8R8(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u8 * dB = (u8 *)dP; + u16 *sB = (u16 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { dB[0] = (*sB & 0x7c00) >> 7; dB[1] = (*sB & 0x03e0) >> 2; dB[2] = (*sB & 0x1f) << 3; @@ -358,48 +313,47 @@ void CColorConverter::convert_A1R5G5B5toB8G8R8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_A1R5G5B5toR5G5B5A1(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A1R5G5B5toR5G5B5A1(const void *sP, s32 sN, void *dP) { - const u16* sB = (const u16*)sP; - u16* dB = (u16*)dP; + const u16 *sB = (const u16 *)sP; + u16 *dB = (u16 *)dP; - for (s32 x = 0; x < sN; ++x) - { - *dB = (*sB<<1)|(*sB>>15); - ++sB; ++dB; + for (s32 x = 0; x < sN; ++x) { + *dB = (*sB << 1) | (*sB >> 15); + ++sB; + ++dB; } } -void CColorConverter::convert_A1R5G5B5toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A1R5G5B5toA8R8G8B8(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u32* dB = (u32*)dP; + u16 *sB = (u16 *)sP; + u32 *dB = (u32 *)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A1R5G5B5toA8R8G8B8(*sB++); } -void CColorConverter::convert_A1R5G5B5toA1R5G5B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A1R5G5B5toA1R5G5B5(const void *sP, s32 sN, void *dP) { memcpy(dP, sP, sN * 2); } -void CColorConverter::convert_A1R5G5B5toR5G6B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A1R5G5B5toR5G6B5(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u16* dB = (u16*)dP; + u16 *sB = (u16 *)sP; + u16 *dB = (u16 *)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A1R5G5B5toR5G6B5(*sB++); } -void CColorConverter::convert_A8R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toR8G8B8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8*)sP; - u8* dB = (u8*)dP; + u8 *sB = (u8 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { // sB[3] is alpha dB[0] = sB[2]; dB[1] = sB[1]; @@ -410,13 +364,12 @@ void CColorConverter::convert_A8R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_A8R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toB8G8R8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8*)sP; - u8* dB = (u8*)dP; + u8 *sB = (u8 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { // sB[3] is alpha dB[0] = sB[0]; dB[1] = sB[1]; @@ -427,27 +380,26 @@ void CColorConverter::convert_A8R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_A8R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toA8R8G8B8(const void *sP, s32 sN, void *dP) { memcpy(dP, sP, sN * 4); } -void CColorConverter::convert_A8R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toA1R5G5B5(const void *sP, s32 sN, void *dP) { - u32* sB = (u32*)sP; - u16* dB = (u16*)dP; + u32 *sB = (u32 *)sP; + u16 *dB = (u16 *)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A8R8G8B8toA1R5G5B5(*sB++); } -void CColorConverter::convert_A8R8G8B8toA1B5G5R5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toA1B5G5R5(const void *sP, s32 sN, void *dP) { - u8 * sB = (u8 *)sP; - u16* dB = (u16*)dP; + u8 *sB = (u8 *)sP; + u16 *dB = (u16 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { s32 r = sB[0] >> 3; s32 g = sB[1] >> 3; s32 b = sB[2] >> 3; @@ -460,13 +412,12 @@ void CColorConverter::convert_A8R8G8B8toA1B5G5R5(const void* sP, s32 sN, void* d } } -void CColorConverter::convert_A8R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toR5G6B5(const void *sP, s32 sN, void *dP) { - u8 * sB = (u8 *)sP; - u16* dB = (u16*)dP; + u8 *sB = (u8 *)sP; + u16 *dB = (u16 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { s32 r = sB[2] >> 3; s32 g = sB[1] >> 2; s32 b = sB[0] >> 3; @@ -478,13 +429,12 @@ void CColorConverter::convert_A8R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_A8R8G8B8toR3G3B2(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toR3G3B2(const void *sP, s32 sN, void *dP) { - u8* sB = (u8*)sP; - u8* dB = (u8*)dP; + u8 *sB = (u8 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { u8 r = sB[2] & 0xe0; u8 g = (sB[1] & 0xe0) >> 3; u8 b = (sB[0] & 0xc0) >> 6; @@ -496,32 +446,30 @@ void CColorConverter::convert_A8R8G8B8toR3G3B2(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R8G8B8toR8G8B8(const void *sP, s32 sN, void *dP) { memcpy(dP, sP, sN * 3); } -void CColorConverter::convert_R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R8G8B8toA8R8G8B8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8* )sP; - u32* dB = (u32*)dP; + u8 *sB = (u8 *)sP; + u32 *dB = (u32 *)dP; - for (s32 x = 0; x < sN; ++x) - { - *dB = 0xff000000 | (sB[0]<<16) | (sB[1]<<8) | sB[2]; + for (s32 x = 0; x < sN; ++x) { + *dB = 0xff000000 | (sB[0] << 16) | (sB[1] << 8) | sB[2]; sB += 3; ++dB; } } -void CColorConverter::convert_R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R8G8B8toA1R5G5B5(const void *sP, s32 sN, void *dP) { - u8 * sB = (u8 *)sP; - u16* dB = (u16*)dP; + u8 *sB = (u8 *)sP; + u16 *dB = (u16 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { s32 r = sB[0] >> 3; s32 g = sB[1] >> 3; s32 b = sB[2] >> 3; @@ -533,51 +481,47 @@ void CColorConverter::convert_R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_B8G8R8toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_B8G8R8toA8R8G8B8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8* )sP; - u32* dB = (u32*)dP; + u8 *sB = (u8 *)sP; + u32 *dB = (u32 *)dP; - for (s32 x = 0; x < sN; ++x) - { - *dB = 0xff000000 | (sB[2]<<16) | (sB[1]<<8) | sB[0]; + for (s32 x = 0; x < sN; ++x) { + *dB = 0xff000000 | (sB[2] << 16) | (sB[1] << 8) | sB[0]; sB += 3; ++dB; } } -void CColorConverter::convert_A8R8G8B8toR8G8B8A8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toR8G8B8A8(const void *sP, s32 sN, void *dP) { - const u32* sB = (const u32*)sP; - u32* dB = (u32*)dP; + const u32 *sB = (const u32 *)sP; + u32 *dB = (u32 *)dP; - for (s32 x = 0; x < sN; ++x) - { - *dB++ = (*sB<<8) | (*sB>>24); + for (s32 x = 0; x < sN; ++x) { + *dB++ = (*sB << 8) | (*sB >> 24); ++sB; } } -void CColorConverter::convert_A8R8G8B8toA8B8G8R8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_A8R8G8B8toA8B8G8R8(const void *sP, s32 sN, void *dP) { - const u32* sB = (const u32*)sP; - u32* dB = (u32*)dP; + const u32 *sB = (const u32 *)sP; + u32 *dB = (u32 *)dP; - for (s32 x = 0; x < sN; ++x) - { - *dB++ = (*sB&0xff00ff00)|((*sB&0x00ff0000)>>16)|((*sB&0x000000ff)<<16); + for (s32 x = 0; x < sN; ++x) { + *dB++ = (*sB & 0xff00ff00) | ((*sB & 0x00ff0000) >> 16) | ((*sB & 0x000000ff) << 16); ++sB; } } -void CColorConverter::convert_B8G8R8A8toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_B8G8R8A8toA8R8G8B8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8*)sP; - u8* dB = (u8*)dP; + u8 *sB = (u8 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { dB[0] = sB[3]; dB[1] = sB[2]; dB[2] = sB[1]; @@ -586,16 +530,14 @@ void CColorConverter::convert_B8G8R8A8toA8R8G8B8(const void* sP, s32 sN, void* d sB += 4; dB += 4; } - } -void CColorConverter::convert_R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R8G8B8toB8G8R8(const void *sP, s32 sN, void *dP) { - u8* sB = (u8*)sP; - u8* dB = (u8*)dP; + u8 *sB = (u8 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { dB[2] = sB[0]; dB[1] = sB[1]; dB[0] = sB[2]; @@ -605,13 +547,12 @@ void CColorConverter::convert_R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R8G8B8toR5G6B5(const void *sP, s32 sN, void *dP) { - u8 * sB = (u8 *)sP; - u16* dB = (u16*)dP; + u8 *sB = (u8 *)sP; + u16 *dB = (u16 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { s32 r = sB[0] >> 3; s32 g = sB[1] >> 2; s32 b = sB[2] >> 3; @@ -623,18 +564,17 @@ void CColorConverter::convert_R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_R5G6B5toR5G6B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R5G6B5toR5G6B5(const void *sP, s32 sN, void *dP) { memcpy(dP, sP, sN * 2); } -void CColorConverter::convert_R5G6B5toR8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R5G6B5toR8G8B8(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u8 * dB = (u8 *)dP; + u16 *sB = (u16 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { dB[0] = (*sB & 0xf800) >> 8; dB[1] = (*sB & 0x07e0) >> 3; dB[2] = (*sB & 0x001f) << 3; @@ -644,13 +584,12 @@ void CColorConverter::convert_R5G6B5toR8G8B8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_R5G6B5toB8G8R8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R5G6B5toB8G8R8(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u8 * dB = (u8 *)dP; + u16 *sB = (u16 *)sP; + u8 *dB = (u8 *)dP; - for (s32 x = 0; x < sN; ++x) - { + for (s32 x = 0; x < sN; ++x) { dB[2] = (*sB & 0xf800) >> 8; dB[1] = (*sB & 0x07e0) >> 3; dB[0] = (*sB & 0x001f) << 3; @@ -660,19 +599,19 @@ void CColorConverter::convert_R5G6B5toB8G8R8(const void* sP, s32 sN, void* dP) } } -void CColorConverter::convert_R5G6B5toA8R8G8B8(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R5G6B5toA8R8G8B8(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u32* dB = (u32*)dP; + u16 *sB = (u16 *)sP; + u32 *dB = (u32 *)dP; for (s32 x = 0; x < sN; ++x) *dB++ = R5G6B5toA8R8G8B8(*sB++); } -void CColorConverter::convert_R5G6B5toA1R5G5B5(const void* sP, s32 sN, void* dP) +void CColorConverter::convert_R5G6B5toA1R5G5B5(const void *sP, s32 sN, void *dP) { - u16* sB = (u16*)sP; - u16* dB = (u16*)dP; + u16 *sB = (u16 *)sP; + u16 *dB = (u16 *)dP; for (s32 x = 0; x < sN; ++x) *dB++ = R5G6B5toA1R5G5B5(*sB++); @@ -680,154 +619,143 @@ void CColorConverter::convert_R5G6B5toA1R5G5B5(const void* sP, s32 sN, void* dP) bool CColorConverter::canConvertFormat(ECOLOR_FORMAT sourceFormat, ECOLOR_FORMAT destFormat) { - switch (sourceFormat) - { + switch (sourceFormat) { + case ECF_A1R5G5B5: + switch (destFormat) { case ECF_A1R5G5B5: - switch (destFormat) - { - case ECF_A1R5G5B5: - case ECF_R5G6B5: - case ECF_A8R8G8B8: - case ECF_R8G8B8: - return true; - default: - break; - } - break; case ECF_R5G6B5: - switch (destFormat) - { - case ECF_A1R5G5B5: - case ECF_R5G6B5: - case ECF_A8R8G8B8: - case ECF_R8G8B8: - return true; - default: - break; - } - break; case ECF_A8R8G8B8: - switch (destFormat) - { - case ECF_A1R5G5B5: - case ECF_R5G6B5: - case ECF_A8R8G8B8: - case ECF_R8G8B8: - return true; - default: - break; - } - break; case ECF_R8G8B8: - switch (destFormat) - { - case ECF_A1R5G5B5: - case ECF_R5G6B5: - case ECF_A8R8G8B8: - case ECF_R8G8B8: - return true; - default: - break; - } - break; + return true; default: break; + } + break; + case ECF_R5G6B5: + switch (destFormat) { + case ECF_A1R5G5B5: + case ECF_R5G6B5: + case ECF_A8R8G8B8: + case ECF_R8G8B8: + return true; + default: + break; + } + break; + case ECF_A8R8G8B8: + switch (destFormat) { + case ECF_A1R5G5B5: + case ECF_R5G6B5: + case ECF_A8R8G8B8: + case ECF_R8G8B8: + return true; + default: + break; + } + break; + case ECF_R8G8B8: + switch (destFormat) { + case ECF_A1R5G5B5: + case ECF_R5G6B5: + case ECF_A8R8G8B8: + case ECF_R8G8B8: + return true; + default: + break; + } + break; + default: + break; } return false; } -void CColorConverter::convert_viaFormat(const void* sP, ECOLOR_FORMAT sF, s32 sN, - void* dP, ECOLOR_FORMAT dF) +void CColorConverter::convert_viaFormat(const void *sP, ECOLOR_FORMAT sF, s32 sN, + void *dP, ECOLOR_FORMAT dF) { // please also update can_convert_viaFormat when adding new conversions - switch (sF) - { + switch (sF) { + case ECF_A1R5G5B5: + switch (dF) { case ECF_A1R5G5B5: - switch (dF) - { - case ECF_A1R5G5B5: - convert_A1R5G5B5toA1R5G5B5(sP, sN, dP); - break; - case ECF_R5G6B5: - convert_A1R5G5B5toR5G6B5(sP, sN, dP); - break; - case ECF_A8R8G8B8: - convert_A1R5G5B5toA8R8G8B8(sP, sN, dP); - break; - case ECF_R8G8B8: - convert_A1R5G5B5toR8G8B8(sP, sN, dP); - break; - - default: - break; - } - break; + convert_A1R5G5B5toA1R5G5B5(sP, sN, dP); + break; case ECF_R5G6B5: - switch (dF) - { - case ECF_A1R5G5B5: - convert_R5G6B5toA1R5G5B5(sP, sN, dP); - break; - case ECF_R5G6B5: - convert_R5G6B5toR5G6B5(sP, sN, dP); - break; - case ECF_A8R8G8B8: - convert_R5G6B5toA8R8G8B8(sP, sN, dP); - break; - case ECF_R8G8B8: - convert_R5G6B5toR8G8B8(sP, sN, dP); - break; - - default: - break; - } - break; + convert_A1R5G5B5toR5G6B5(sP, sN, dP); + break; case ECF_A8R8G8B8: - switch (dF) - { - case ECF_A1R5G5B5: - convert_A8R8G8B8toA1R5G5B5(sP, sN, dP); - break; - case ECF_R5G6B5: - convert_A8R8G8B8toR5G6B5(sP, sN, dP); - break; - case ECF_A8R8G8B8: - convert_A8R8G8B8toA8R8G8B8(sP, sN, dP); - break; - case ECF_R8G8B8: - convert_A8R8G8B8toR8G8B8(sP, sN, dP); - break; - - default: - break; - } - break; + convert_A1R5G5B5toA8R8G8B8(sP, sN, dP); + break; case ECF_R8G8B8: - switch (dF) - { - case ECF_A1R5G5B5: - convert_R8G8B8toA1R5G5B5(sP, sN, dP); - break; - case ECF_R5G6B5: - convert_R8G8B8toR5G6B5(sP, sN, dP); - break; - case ECF_A8R8G8B8: - convert_R8G8B8toA8R8G8B8(sP, sN, dP); - break; - case ECF_R8G8B8: - convert_R8G8B8toR8G8B8(sP, sN, dP); - break; - - default: - break; - } - break; + convert_A1R5G5B5toR8G8B8(sP, sN, dP); + break; default: break; + } + break; + case ECF_R5G6B5: + switch (dF) { + case ECF_A1R5G5B5: + convert_R5G6B5toA1R5G5B5(sP, sN, dP); + break; + case ECF_R5G6B5: + convert_R5G6B5toR5G6B5(sP, sN, dP); + break; + case ECF_A8R8G8B8: + convert_R5G6B5toA8R8G8B8(sP, sN, dP); + break; + case ECF_R8G8B8: + convert_R5G6B5toR8G8B8(sP, sN, dP); + break; + + default: + break; + } + break; + case ECF_A8R8G8B8: + switch (dF) { + case ECF_A1R5G5B5: + convert_A8R8G8B8toA1R5G5B5(sP, sN, dP); + break; + case ECF_R5G6B5: + convert_A8R8G8B8toR5G6B5(sP, sN, dP); + break; + case ECF_A8R8G8B8: + convert_A8R8G8B8toA8R8G8B8(sP, sN, dP); + break; + case ECF_R8G8B8: + convert_A8R8G8B8toR8G8B8(sP, sN, dP); + break; + + default: + break; + } + break; + case ECF_R8G8B8: + switch (dF) { + case ECF_A1R5G5B5: + convert_R8G8B8toA1R5G5B5(sP, sN, dP); + break; + case ECF_R5G6B5: + convert_R8G8B8toR5G6B5(sP, sN, dP); + break; + case ECF_A8R8G8B8: + convert_R8G8B8toA8R8G8B8(sP, sN, dP); + break; + case ECF_R8G8B8: + convert_R8G8B8toR8G8B8(sP, sN, dP); + break; + + default: + break; + } + break; + + default: + break; } } - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CColorConverter.h b/source/Irrlicht/CColorConverter.h index 93d60efa..7f162829 100644 --- a/source/Irrlicht/CColorConverter.h +++ b/source/Irrlicht/CColorConverter.h @@ -15,37 +15,35 @@ namespace video class CColorConverter { public: - //! converts a monochrome bitmap to A1R5G5B5 - static void convert1BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, s32 linepad=0, bool flip=false); + static void convert1BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, s32 linepad = 0, bool flip = false); //! converts a 4 bit palettized image to A1R5G5B5 - static void convert4BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad=0, bool flip=false); + static void convert4BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, const s32 *palette, s32 linepad = 0, bool flip = false); //! converts a 8 bit palettized image to A1R5G5B5 - static void convert8BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad=0, bool flip=false); + static void convert8BitTo16Bit(const u8 *in, s16 *out, s32 width, s32 height, const s32 *palette, s32 linepad = 0, bool flip = false); //! converts a 8 bit palettized or non palettized image (A8) into R8G8B8 - static void convert8BitTo24Bit(const u8* in, u8* out, s32 width, s32 height, const u8* palette, s32 linepad = 0, bool flip=false); + static void convert8BitTo24Bit(const u8 *in, u8 *out, s32 width, s32 height, const u8 *palette, s32 linepad = 0, bool flip = false); //! converts a 8 bit palettized or non palettized image (A8) into A8R8G8B8 - static void convert8BitTo32Bit(const u8* in, u8* out, s32 width, s32 height, const u8* palette, s32 linepad = 0, bool flip=false); + static void convert8BitTo32Bit(const u8 *in, u8 *out, s32 width, s32 height, const u8 *palette, s32 linepad = 0, bool flip = false); //! converts R8G8B8 16 bit data to A1R5G5B5 data - static void convert16BitTo16Bit(const s16* in, s16* out, s32 width, s32 height, s32 linepad=0, bool flip=false); + static void convert16BitTo16Bit(const s16 *in, s16 *out, s32 width, s32 height, s32 linepad = 0, bool flip = false); //! copies R8G8B8 24 bit data to 24 data, and flips and //! mirrors the image during the process. - static void convert24BitTo24Bit(const u8* in, u8* out, s32 width, s32 height, s32 linepad=0, bool flip=false, bool bgr=false); + static void convert24BitTo24Bit(const u8 *in, u8 *out, s32 width, s32 height, s32 linepad = 0, bool flip = false, bool bgr = false); //! Resizes the surface to a new size and converts it at the same time //! to an A8R8G8B8 format, returning the pointer to the new buffer. - static void convert16bitToA8R8G8B8andResize(const s16* in, s32* out, s32 newWidth, s32 newHeight, s32 currentWidth, s32 currentHeight); + static void convert16bitToA8R8G8B8andResize(const s16 *in, s32 *out, s32 newWidth, s32 newHeight, s32 currentWidth, s32 currentHeight); //! copies X8R8G8B8 32 bit data, and flips and //! mirrors the image during the process. - static void convert32BitTo32Bit(const s32* in, s32* out, s32 width, s32 height, s32 linepad, bool flip=false); - + static void convert32BitTo32Bit(const s32 *in, s32 *out, s32 width, s32 height, s32 linepad, bool flip = false); //! Functions for converting one image format to another efficiently //! and hopefully correctly. @@ -56,43 +54,41 @@ public: //! \param sN number of source pixels to copy //! \param dP pointer to destination data buffer. must be big enough //! to hold sN pixels in the output format. - static void convert_A1R5G5B5toR8G8B8(const void* sP, s32 sN, void* dP); - static void convert_A1R5G5B5toB8G8R8(const void* sP, s32 sN, void* dP); - static void convert_A1R5G5B5toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_A1R5G5B5toA1R5G5B5(const void* sP, s32 sN, void* dP); - static void convert_A1R5G5B5toR5G5B5A1(const void* sP, s32 sN, void* dP); - static void convert_A1R5G5B5toR5G6B5(const void* sP, s32 sN, void* dP); + static void convert_A1R5G5B5toR8G8B8(const void *sP, s32 sN, void *dP); + static void convert_A1R5G5B5toB8G8R8(const void *sP, s32 sN, void *dP); + static void convert_A1R5G5B5toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_A1R5G5B5toA1R5G5B5(const void *sP, s32 sN, void *dP); + static void convert_A1R5G5B5toR5G5B5A1(const void *sP, s32 sN, void *dP); + static void convert_A1R5G5B5toR5G6B5(const void *sP, s32 sN, void *dP); - static void convert_A8R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toA1B5G5R5(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP); + static void convert_A8R8G8B8toR8G8B8(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toB8G8R8(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toA1R5G5B5(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toA1B5G5R5(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toR5G6B5(const void *sP, s32 sN, void *dP); - static void convert_A8R8G8B8toR3G3B2(const void* sP, s32 sN, void* dP); - static void convert_R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP); - static void convert_R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP); - static void convert_R8G8B8toB8G8R8(const void* sP, s32 sN, void* dP); - static void convert_R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP); - static void convert_B8G8R8toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_B8G8R8A8toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toR8G8B8A8(const void* sP, s32 sN, void* dP); - static void convert_A8R8G8B8toA8B8G8R8(const void* sP, s32 sN, void* dP); + static void convert_A8R8G8B8toR3G3B2(const void *sP, s32 sN, void *dP); + static void convert_R8G8B8toR8G8B8(const void *sP, s32 sN, void *dP); + static void convert_R8G8B8toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_R8G8B8toA1R5G5B5(const void *sP, s32 sN, void *dP); + static void convert_R8G8B8toB8G8R8(const void *sP, s32 sN, void *dP); + static void convert_R8G8B8toR5G6B5(const void *sP, s32 sN, void *dP); + static void convert_B8G8R8toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_B8G8R8A8toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toR8G8B8A8(const void *sP, s32 sN, void *dP); + static void convert_A8R8G8B8toA8B8G8R8(const void *sP, s32 sN, void *dP); - static void convert_R5G6B5toR5G6B5(const void* sP, s32 sN, void* dP); - static void convert_R5G6B5toR8G8B8(const void* sP, s32 sN, void* dP); - static void convert_R5G6B5toB8G8R8(const void* sP, s32 sN, void* dP); - static void convert_R5G6B5toA8R8G8B8(const void* sP, s32 sN, void* dP); - static void convert_R5G6B5toA1R5G5B5(const void* sP, s32 sN, void* dP); - static void convert_viaFormat(const void* sP, ECOLOR_FORMAT sF, s32 sN, - void* dP, ECOLOR_FORMAT dF); + static void convert_R5G6B5toR5G6B5(const void *sP, s32 sN, void *dP); + static void convert_R5G6B5toR8G8B8(const void *sP, s32 sN, void *dP); + static void convert_R5G6B5toB8G8R8(const void *sP, s32 sN, void *dP); + static void convert_R5G6B5toA8R8G8B8(const void *sP, s32 sN, void *dP); + static void convert_R5G6B5toA1R5G5B5(const void *sP, s32 sN, void *dP); + static void convert_viaFormat(const void *sP, ECOLOR_FORMAT sF, s32 sN, + void *dP, ECOLOR_FORMAT dF); // Check if convert_viaFormat is usable static bool canConvertFormat(ECOLOR_FORMAT sourceFormat, ECOLOR_FORMAT destFormat); }; - } // end namespace video } // end namespace irr - diff --git a/source/Irrlicht/CDummyTransformationSceneNode.cpp b/source/Irrlicht/CDummyTransformationSceneNode.cpp index 34920d7d..73953dd3 100644 --- a/source/Irrlicht/CDummyTransformationSceneNode.cpp +++ b/source/Irrlicht/CDummyTransformationSceneNode.cpp @@ -12,33 +12,30 @@ namespace scene //! constructor CDummyTransformationSceneNode::CDummyTransformationSceneNode( - ISceneNode* parent, ISceneManager* mgr, s32 id) - : IDummyTransformationSceneNode(parent, mgr, id) + ISceneNode *parent, ISceneManager *mgr, s32 id) : + IDummyTransformationSceneNode(parent, mgr, id) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CDummyTransformationSceneNode"); - #endif +#endif setAutomaticCulling(scene::EAC_OFF); } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CDummyTransformationSceneNode::getBoundingBox() const +const core::aabbox3d &CDummyTransformationSceneNode::getBoundingBox() const { return Box; } - //! Returns a reference to the current relative transformation matrix. //! This is the matrix, this scene node uses instead of scale, translation //! and rotation. -core::matrix4& CDummyTransformationSceneNode::getRelativeTransformationMatrix() +core::matrix4 &CDummyTransformationSceneNode::getRelativeTransformationMatrix() { return RelativeTransformationMatrix; } - //! Returns the relative transformation of the scene node. core::matrix4 CDummyTransformationSceneNode::getRelativeTransformation() const { @@ -46,56 +43,56 @@ core::matrix4 CDummyTransformationSceneNode::getRelativeTransformation() const } //! Creates a clone of this scene node and its children. -ISceneNode* CDummyTransformationSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) +ISceneNode *CDummyTransformationSceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { if (!newParent) newParent = Parent; if (!newManager) newManager = SceneManager; - CDummyTransformationSceneNode* nb = new CDummyTransformationSceneNode(newParent, - newManager, ID); + CDummyTransformationSceneNode *nb = new CDummyTransformationSceneNode(newParent, + newManager, ID); nb->cloneMembers(this, newManager); nb->RelativeTransformationMatrix = RelativeTransformationMatrix; nb->Box = Box; - if ( newParent ) + if (newParent) nb->drop(); return nb; } -const core::vector3df& CDummyTransformationSceneNode::getScale() const +const core::vector3df &CDummyTransformationSceneNode::getScale() const { os::Printer::log("CDummyTransformationSceneNode::getScale() does not contain the relative transformation.", ELL_DEBUG); return RelativeScale; } -void CDummyTransformationSceneNode::setScale(const core::vector3df& scale) +void CDummyTransformationSceneNode::setScale(const core::vector3df &scale) { os::Printer::log("CDummyTransformationSceneNode::setScale() does not affect the relative transformation.", ELL_DEBUG); RelativeScale = scale; } -const core::vector3df& CDummyTransformationSceneNode::getRotation() const +const core::vector3df &CDummyTransformationSceneNode::getRotation() const { os::Printer::log("CDummyTransformationSceneNode::getRotation() does not contain the relative transformation.", ELL_DEBUG); return RelativeRotation; } -void CDummyTransformationSceneNode::setRotation(const core::vector3df& rotation) +void CDummyTransformationSceneNode::setRotation(const core::vector3df &rotation) { os::Printer::log("CDummyTransformationSceneNode::setRotation() does not affect the relative transformation.", ELL_DEBUG); RelativeRotation = rotation; } -const core::vector3df& CDummyTransformationSceneNode::getPosition() const +const core::vector3df &CDummyTransformationSceneNode::getPosition() const { os::Printer::log("CDummyTransformationSceneNode::getPosition() does not contain the relative transformation.", ELL_DEBUG); return RelativeTranslation; } -void CDummyTransformationSceneNode::setPosition(const core::vector3df& newpos) +void CDummyTransformationSceneNode::setPosition(const core::vector3df &newpos) { os::Printer::log("CDummyTransformationSceneNode::setPosition() does not affect the relative transformation.", ELL_DEBUG); RelativeTranslation = newpos; diff --git a/source/Irrlicht/CDummyTransformationSceneNode.h b/source/Irrlicht/CDummyTransformationSceneNode.h index 8aa3b2b3..86fda363 100644 --- a/source/Irrlicht/CDummyTransformationSceneNode.h +++ b/source/Irrlicht/CDummyTransformationSceneNode.h @@ -11,49 +11,45 @@ namespace irr namespace scene { - class CDummyTransformationSceneNode : public IDummyTransformationSceneNode - { - public: +class CDummyTransformationSceneNode : public IDummyTransformationSceneNode +{ +public: + //! constructor + CDummyTransformationSceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id); - //! constructor - CDummyTransformationSceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id); + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! Returns a reference to the current relative transformation matrix. + //! This is the matrix, this scene node uses instead of scale, translation + //! and rotation. + core::matrix4 &getRelativeTransformationMatrix() override; - //! Returns a reference to the current relative transformation matrix. - //! This is the matrix, this scene node uses instead of scale, translation - //! and rotation. - core::matrix4& getRelativeTransformationMatrix() override; + //! Returns the relative transformation of the scene node. + core::matrix4 getRelativeTransformation() const override; - //! Returns the relative transformation of the scene node. - core::matrix4 getRelativeTransformation() const override; + //! does nothing. + void render() override {} - //! does nothing. - void render() override {} + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_DUMMY_TRANSFORMATION; } - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_DUMMY_TRANSFORMATION; } + //! Creates a clone of this scene node and its children. + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; - //! Creates a clone of this scene node and its children. - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; +private: + // TODO: We can add least add some warnings to find troubles faster until we have + // fixed bug id 2318691. + const core::vector3df &getScale() const override; + void setScale(const core::vector3df &scale) override; + const core::vector3df &getRotation() const override; + void setRotation(const core::vector3df &rotation) override; + const core::vector3df &getPosition() const override; + void setPosition(const core::vector3df &newpos) override; - - private: - - // TODO: We can add least add some warnings to find troubles faster until we have - // fixed bug id 2318691. - const core::vector3df& getScale() const override; - void setScale(const core::vector3df& scale) override; - const core::vector3df& getRotation() const override; - void setRotation(const core::vector3df& rotation) override; - const core::vector3df& getPosition() const override; - void setPosition(const core::vector3df& newpos) override; - - core::matrix4 RelativeTransformationMatrix; - core::aabbox3d Box; - }; + core::matrix4 RelativeTransformationMatrix; + core::aabbox3d Box; +}; } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CEGLManager.cpp b/source/Irrlicht/CEGLManager.cpp old mode 100755 new mode 100644 index 8d57140e..962a3b6b --- a/source/Irrlicht/CEGLManager.cpp +++ b/source/Irrlicht/CEGLManager.cpp @@ -4,8 +4,8 @@ #include "CEGLManager.h" -#ifdef _IRR_COMPILE_WITH_EGL_MANAGER_ - +#ifdef _IRR_COMPILE_WITH_EGL_MANAGER_ + #include "irrString.h" #include "irrArray.h" #include "os.h" @@ -19,32 +19,33 @@ namespace irr namespace video { -CEGLManager::CEGLManager() : IContextManager(), EglWindow(0), EglDisplay(EGL_NO_DISPLAY), - EglSurface(EGL_NO_SURFACE), EglContext(EGL_NO_CONTEXT), EglConfig(0), MajorVersion(0), MinorVersion(0) +CEGLManager::CEGLManager() : + IContextManager(), EglWindow(0), EglDisplay(EGL_NO_DISPLAY), + EglSurface(EGL_NO_SURFACE), EglContext(EGL_NO_CONTEXT), EglConfig(0), MajorVersion(0), MinorVersion(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CEGLManager"); - #endif +#endif } CEGLManager::~CEGLManager() { - destroyContext(); - destroySurface(); - terminate(); + destroyContext(); + destroySurface(); + terminate(); } -bool CEGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) +bool CEGLManager::initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) { // store new data - Params=params; - Data=data; + Params = params; + Data = data; if (EglWindow != 0 && EglDisplay != EGL_NO_DISPLAY) - return true; + return true; - // Window is depend on platform. -#if defined(_IRR_COMPILE_WITH_WINDOWS_DEVICE_) + // Window is depend on platform. +#if defined(_IRR_COMPILE_WITH_WINDOWS_DEVICE_) EglWindow = (NativeWindowType)Data.OpenGLWin32.HWnd; Data.OpenGLWin32.HDc = GetDC((HWND)EglWindow); EglDisplay = eglGetDisplay((NativeDisplayType)Data.OpenGLWin32.HDc); @@ -55,7 +56,7 @@ bool CEGLManager::initialize(const SIrrlichtCreationParameters& params, const SE EglWindow = (NativeWindowType)Data.OpenGLLinux.X11Window; EglDisplay = eglGetDisplay((NativeDisplayType)Data.OpenGLLinux.X11Display); #elif defined(_IRR_COMPILE_WITH_ANDROID_DEVICE_) - EglWindow = (ANativeWindow*)Data.OGLESAndroid.Window; + EglWindow = (ANativeWindow *)Data.OGLESAndroid.Window; EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); #elif defined(_IRR_COMPILE_WITH_FB_DEVICE_) EglWindow = (NativeWindowType)Data.OpenGLFB.Window; @@ -63,26 +64,23 @@ bool CEGLManager::initialize(const SIrrlichtCreationParameters& params, const SE #endif // We must check if EGL display is valid. - if (EglDisplay == EGL_NO_DISPLAY) - { + if (EglDisplay == EGL_NO_DISPLAY) { os::Printer::log("Could not get EGL display."); terminate(); - return false; - } + return false; + } // Initialize EGL here. - if (!eglInitialize(EglDisplay, &MajorVersion, &MinorVersion)) - { + if (!eglInitialize(EglDisplay, &MajorVersion, &MinorVersion)) { os::Printer::log("Could not initialize EGL display."); - EglDisplay = EGL_NO_DISPLAY; + EglDisplay = EGL_NO_DISPLAY; terminate(); - return false; - } - else - os::Printer::log("EGL version", core::stringc(MajorVersion+(MinorVersion*0.1f)).c_str()); + return false; + } else + os::Printer::log("EGL version", core::stringc(MajorVersion + (MinorVersion * 0.1f)).c_str()); - return true; + return true; } void CEGLManager::terminate() @@ -90,8 +88,7 @@ void CEGLManager::terminate() if (EglWindow == 0 && EglDisplay == EGL_NO_DISPLAY) return; - if (EglDisplay != EGL_NO_DISPLAY) - { + if (EglDisplay != EGL_NO_DISPLAY) { // We should unbind current EGL context before terminate EGL. eglMakeCurrent(EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); @@ -99,32 +96,31 @@ void CEGLManager::terminate() EglDisplay = EGL_NO_DISPLAY; } -#if defined(_IRR_COMPILE_WITH_WINDOWS_DEVICE_) - if (Data.OpenGLWin32.HDc) - { +#if defined(_IRR_COMPILE_WITH_WINDOWS_DEVICE_) + if (Data.OpenGLWin32.HDc) { ReleaseDC((HWND)EglWindow, (HDC)Data.OpenGLWin32.HDc); - Data.OpenGLWin32.HDc = 0; - } + Data.OpenGLWin32.HDc = 0; + } #endif - MajorVersion = 0; - MinorVersion = 0; + MajorVersion = 0; + MinorVersion = 0; } bool CEGLManager::generateSurface() { - if (EglDisplay == EGL_NO_DISPLAY) - return false; + if (EglDisplay == EGL_NO_DISPLAY) + return false; - if (EglSurface != EGL_NO_SURFACE) - return true; + if (EglSurface != EGL_NO_SURFACE) + return true; - // We should assign new WindowID on platforms, where WindowID may change at runtime, - // at this time only Android support this feature. - // this needs an update method instead! + // We should assign new WindowID on platforms, where WindowID may change at runtime, + // at this time only Android support this feature. + // this needs an update method instead! #if defined(_IRR_COMPILE_WITH_ANDROID_DEVICE_) - EglWindow = (ANativeWindow*)Data.OGLESAndroid.Window; + EglWindow = (ANativeWindow *)Data.OGLESAndroid.Window; #endif #if defined(_IRR_EMSCRIPTEN_PLATFORM_) @@ -135,18 +131,16 @@ bool CEGLManager::generateSurface() EglConfig = chooseConfig(ECS_EGL_CHOOSE_FIRST_LOWER_EXPECTATIONS); #endif - if ( EglConfig == 0 ) - { + if (EglConfig == 0) { os::Printer::log("Could not get config for EGL display."); return false; } - #if defined(_IRR_COMPILE_WITH_ANDROID_DEVICE_) - EGLint Format = 0; - eglGetConfigAttrib(EglDisplay, EglConfig, EGL_NATIVE_VISUAL_ID, &Format); + EGLint Format = 0; + eglGetConfigAttrib(EglDisplay, EglConfig, EGL_NATIVE_VISUAL_ID, &Format); - ANativeWindow_setBuffersGeometry(EglWindow, 0, 0, Format); + ANativeWindow_setBuffersGeometry(EglWindow, 0, 0, Format); #endif // Now we are able to create EGL surface. @@ -163,10 +157,10 @@ bool CEGLManager::generateSurface() eglBindAPI(EGL_OPENGL_ES_API); #endif - if (Params.Vsync) + if (Params.Vsync) eglSwapInterval(EglDisplay, 1); - return true; + return true; } EGLConfig CEGLManager::chooseConfig(EConfigStyle confStyle) @@ -175,8 +169,7 @@ EGLConfig CEGLManager::chooseConfig(EConfigStyle confStyle) // Find proper OpenGL BIT. EGLint eglOpenGLBIT = 0; - switch (Params.DriverType) - { + switch (Params.DriverType) { case EDT_OGLES1: eglOpenGLBIT = EGL_OPENGL_ES_BIT; break; @@ -188,96 +181,85 @@ EGLConfig CEGLManager::chooseConfig(EConfigStyle confStyle) break; } - if ( confStyle == ECS_EGL_CHOOSE_FIRST_LOWER_EXPECTATIONS ) - { + if (confStyle == ECS_EGL_CHOOSE_FIRST_LOWER_EXPECTATIONS) { EGLint Attribs[] = - { - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, Params.WithAlphaChannel ? 1:0, - EGL_BUFFER_SIZE, Params.Bits, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_DEPTH_SIZE, Params.ZBufferBits, - EGL_STENCIL_SIZE, Params.Stencilbuffer, - EGL_SAMPLE_BUFFERS, Params.AntiAlias ? 1:0, - EGL_SAMPLES, Params.AntiAlias, - #ifdef EGL_VERSION_1_3 - EGL_RENDERABLE_TYPE, eglOpenGLBIT, - #endif - EGL_NONE, 0 - }; + { + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, Params.WithAlphaChannel ? 1 : 0, + EGL_BUFFER_SIZE, Params.Bits, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_DEPTH_SIZE, Params.ZBufferBits, + EGL_STENCIL_SIZE, Params.Stencilbuffer, + EGL_SAMPLE_BUFFERS, Params.AntiAlias ? 1 : 0, + EGL_SAMPLES, Params.AntiAlias, +#ifdef EGL_VERSION_1_3 + EGL_RENDERABLE_TYPE, eglOpenGLBIT, +#endif + EGL_NONE, 0}; EGLint numConfigs = 0; u32 steps = 5; // Choose the best EGL config. - // TODO: We should also have a confStyle ECS_EGL_CHOOSE_CLOSEST - // which doesn't take first result of eglChooseConfigs, - // but the closest to requested parameters. eglChooseConfigs - // can return more than 1 result and first one might have - // "better" values than requested (more bits per pixel etc). - // So this returns the config which can do most, not the - // config which is closest to the requested parameters. + // TODO: We should also have a confStyle ECS_EGL_CHOOSE_CLOSEST + // which doesn't take first result of eglChooseConfigs, + // but the closest to requested parameters. eglChooseConfigs + // can return more than 1 result and first one might have + // "better" values than requested (more bits per pixel etc). + // So this returns the config which can do most, not the + // config which is closest to the requested parameters. // - while (!eglChooseConfig(EglDisplay, Attribs, &configResult, 1, &numConfigs) || !numConfigs) - { - switch (steps) - { - case 5: // samples - if (Attribs[19] > 2) // Params.AntiAlias + while (!eglChooseConfig(EglDisplay, Attribs, &configResult, 1, &numConfigs) || !numConfigs) { + switch (steps) { + case 5: // samples + if (Attribs[19] > 2) // Params.AntiAlias --Attribs[19]; - else - { - Attribs[17] = 0; // Params.Stencilbuffer - Attribs[19] = 0; // Params.AntiAlias + else { + Attribs[17] = 0; // Params.Stencilbuffer + Attribs[19] = 0; // Params.AntiAlias --steps; } break; - case 4: // alpha - if (Attribs[7]) // Params.WithAlphaChannel + case 4: // alpha + if (Attribs[7]) // Params.WithAlphaChannel { Attribs[7] = 0; - if (Params.AntiAlias) - { + if (Params.AntiAlias) { Attribs[17] = 1; Attribs[19] = Params.AntiAlias; steps = 5; } - } - else + } else --steps; break; - case 3: // stencil - if (Attribs[15]) // Params.Stencilbuffer + case 3: // stencil + if (Attribs[15]) // Params.Stencilbuffer { Attribs[15] = 0; - if (Params.AntiAlias) - { + if (Params.AntiAlias) { Attribs[17] = 1; Attribs[19] = Params.AntiAlias; steps = 5; } - } - else + } else --steps; break; - case 2: // depth size - if (Attribs[13] > 16) // Params.ZBufferBits + case 2: // depth size + if (Attribs[13] > 16) // Params.ZBufferBits { Attribs[13] -= 8; - } - else + } else --steps; break; - case 1: // buffer size - if (Attribs[9] > 16) // Params.Bits + case 1: // buffer size + if (Attribs[9] > 16) // Params.Bits { Attribs[9] -= 8; - } - else + } else --steps; break; default: @@ -299,47 +281,40 @@ EGLConfig CEGLManager::chooseConfig(EConfigStyle confStyle) if (Params.Bits > Attribs[9]) os::Printer::log("No full color buffer."); - } - else if ( confStyle == ECS_IRR_CHOOSE ) - { + } else if (confStyle == ECS_IRR_CHOOSE) { // find number of available configs EGLint numConfigs; - if ( eglGetConfigs( EglDisplay, NULL, 0, &numConfigs) == EGL_FALSE ) - { + if (eglGetConfigs(EglDisplay, NULL, 0, &numConfigs) == EGL_FALSE) { testEGLError(); return 0; } - if ( numConfigs <= 0 ) + if (numConfigs <= 0) return 0; // Get all available configs. - EGLConfig * configs = new EGLConfig[numConfigs]; - if ( eglGetConfigs( EglDisplay, configs, numConfigs, &numConfigs) == EGL_FALSE ) - { + EGLConfig *configs = new EGLConfig[numConfigs]; + if (eglGetConfigs(EglDisplay, configs, numConfigs, &numConfigs) == EGL_FALSE) { testEGLError(); return 0; } // Find the best one. core::array ratings((u32)numConfigs); - for ( u32 i=0; i < (u32)numConfigs; ++i ) - { + for (u32 i = 0; i < (u32)numConfigs; ++i) { SConfigRating r; r.config = configs[i]; r.rating = rateConfig(r.config, eglOpenGLBIT); - if ( r.rating >= 0 ) + if (r.rating >= 0) ratings.push_back(r); } - if ( ratings.size() > 0 ) - { + if (ratings.size() > 0) { ratings.sort(); configResult = ratings[0].config; - if ( ratings[0].rating != 0 ) - { + if (ratings[0].rating != 0) { // This is just to print some log info (it also rates again while doing that, but rating is cheap enough, so that doesn't matter here). rateConfig(ratings[0].config, eglOpenGLBIT, true); } @@ -356,19 +331,17 @@ irr::s32 CEGLManager::rateConfig(EGLConfig config, EGLint eglOpenGLBIT, bool log // some values must be there or we ignore the config #ifdef EGL_VERSION_1_3 EGLint attribRenderableType = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_RENDERABLE_TYPE, &attribRenderableType); - if ( attribRenderableType != eglOpenGLBIT ) - { - if ( log ) + eglGetConfigAttrib(EglDisplay, config, EGL_RENDERABLE_TYPE, &attribRenderableType); + if (attribRenderableType != eglOpenGLBIT) { + if (log) os::Printer::log("EGL_RENDERABLE_TYPE != eglOpenGLBIT"); return -1; } #endif EGLint attribSurfaceType = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_SURFACE_TYPE, &attribSurfaceType); - if ( attribSurfaceType != EGL_WINDOW_BIT ) - { - if ( log ) + eglGetConfigAttrib(EglDisplay, config, EGL_SURFACE_TYPE, &attribSurfaceType); + if (attribSurfaceType != EGL_WINDOW_BIT) { + if (log) os::Printer::log("EGL_SURFACE_TYPE!= EGL_WINDOW_BIT"); return -1; } @@ -380,124 +353,104 @@ irr::s32 CEGLManager::rateConfig(EGLConfig config, EGLint eglOpenGLBIT, bool log int rating = 0; EGLint attribBufferSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_BUFFER_SIZE, &attribBufferSize); - if ( attribBufferSize < Params.Bits ) - { - if ( log ) + eglGetConfigAttrib(EglDisplay, config, EGL_BUFFER_SIZE, &attribBufferSize); + if (attribBufferSize < Params.Bits) { + if (log) os::Printer::log("No full color buffer."); rating += 100; } - if ( attribBufferSize > Params.Bits ) - { - if ( log ) + if (attribBufferSize > Params.Bits) { + if (log) os::Printer::log("Larger color buffer.", ELL_DEBUG); ++rating; } EGLint attribRedSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_RED_SIZE, &attribRedSize); - if ( attribRedSize < 5 && Params.Bits >= 4 ) + eglGetConfigAttrib(EglDisplay, config, EGL_RED_SIZE, &attribRedSize); + if (attribRedSize < 5 && Params.Bits >= 4) rating += 100; - else if ( attribRedSize < 8 && Params.Bits >= 24) + else if (attribRedSize < 8 && Params.Bits >= 24) rating += 10; - else if ( attribRedSize >= 8 && Params.Bits < 24 ) - rating ++; + else if (attribRedSize >= 8 && Params.Bits < 24) + rating++; EGLint attribGreenSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_GREEN_SIZE, &attribGreenSize); - if ( attribGreenSize < 5 && Params.Bits >= 4 ) + eglGetConfigAttrib(EglDisplay, config, EGL_GREEN_SIZE, &attribGreenSize); + if (attribGreenSize < 5 && Params.Bits >= 4) rating += 100; - else if ( attribGreenSize < 8 && Params.Bits >= 24) + else if (attribGreenSize < 8 && Params.Bits >= 24) rating += 10; - else if ( attribGreenSize >= 8 && Params.Bits < 24 ) - rating ++; + else if (attribGreenSize >= 8 && Params.Bits < 24) + rating++; EGLint attribBlueSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_BLUE_SIZE, &attribBlueSize); - if ( attribBlueSize < 5 && Params.Bits >= 4 ) + eglGetConfigAttrib(EglDisplay, config, EGL_BLUE_SIZE, &attribBlueSize); + if (attribBlueSize < 5 && Params.Bits >= 4) rating += 100; - else if ( attribBlueSize < 8 && Params.Bits >= 24) + else if (attribBlueSize < 8 && Params.Bits >= 24) rating += 10; - else if ( attribBlueSize >= 8 && Params.Bits < 24 ) - rating ++; + else if (attribBlueSize >= 8 && Params.Bits < 24) + rating++; EGLint attribAlphaSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_ALPHA_SIZE, &attribAlphaSize); - if ( Params.WithAlphaChannel && attribAlphaSize == 0 ) - { - if ( log ) + eglGetConfigAttrib(EglDisplay, config, EGL_ALPHA_SIZE, &attribAlphaSize); + if (Params.WithAlphaChannel && attribAlphaSize == 0) { + if (log) os::Printer::log("No alpha."); rating += 10; - } - else if ( !Params.WithAlphaChannel && attribAlphaSize > 0 ) - { - if ( log ) + } else if (!Params.WithAlphaChannel && attribAlphaSize > 0) { + if (log) os::Printer::log("Got alpha (unrequested).", ELL_DEBUG); - rating ++; + rating++; } EGLint attribStencilSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_STENCIL_SIZE, &attribStencilSize); - if ( Params.Stencilbuffer && attribStencilSize == 0 ) - { - if ( log ) + eglGetConfigAttrib(EglDisplay, config, EGL_STENCIL_SIZE, &attribStencilSize); + if (Params.Stencilbuffer && attribStencilSize == 0) { + if (log) os::Printer::log("No stencil buffer."); rating += 10; - } - else if ( !Params.Stencilbuffer && attribStencilSize > 0 ) - { - if ( log ) + } else if (!Params.Stencilbuffer && attribStencilSize > 0) { + if (log) os::Printer::log("Got a stencil buffer (unrequested).", ELL_DEBUG); - rating ++; + rating++; } EGLint attribDepthSize = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_DEPTH_SIZE, &attribDepthSize); - if ( attribDepthSize < Params.ZBufferBits ) - { - if ( log ) - { + eglGetConfigAttrib(EglDisplay, config, EGL_DEPTH_SIZE, &attribDepthSize); + if (attribDepthSize < Params.ZBufferBits) { + if (log) { if (attribDepthSize > 0) os::Printer::log("No full depth buffer."); else os::Printer::log("No depth buffer."); } rating += 50; - } - else if ( attribDepthSize != Params.ZBufferBits ) - { - if ( log ) - { - if ( Params.ZBufferBits == 0 ) + } else if (attribDepthSize != Params.ZBufferBits) { + if (log) { + if (Params.ZBufferBits == 0) os::Printer::log("Got a depth buffer (unrequested).", ELL_DEBUG); else os::Printer::log("Got a larger depth buffer.", ELL_DEBUG); } - rating ++; + rating++; } - EGLint attribSampleBuffers=0, attribSamples = 0; - eglGetConfigAttrib( EglDisplay, config, EGL_SAMPLE_BUFFERS, &attribSampleBuffers); - eglGetConfigAttrib( EglDisplay, config, EGL_SAMPLES, &attribSamples); - if ( Params.AntiAlias && attribSampleBuffers == 0 ) - { - if ( log ) + EGLint attribSampleBuffers = 0, attribSamples = 0; + eglGetConfigAttrib(EglDisplay, config, EGL_SAMPLE_BUFFERS, &attribSampleBuffers); + eglGetConfigAttrib(EglDisplay, config, EGL_SAMPLES, &attribSamples); + if (Params.AntiAlias && attribSampleBuffers == 0) { + if (log) os::Printer::log("No multisampling."); rating += 20; - } - else if ( Params.AntiAlias && attribSampleBuffers && attribSamples < Params.AntiAlias ) - { - if ( log ) + } else if (Params.AntiAlias && attribSampleBuffers && attribSamples < Params.AntiAlias) { + if (log) os::Printer::log("Multisampling with less samples than requested.", ELL_DEBUG); rating += 10; - } - else if ( Params.AntiAlias && attribSampleBuffers && attribSamples > Params.AntiAlias ) - { - if ( log ) + } else if (Params.AntiAlias && attribSampleBuffers && attribSamples > Params.AntiAlias) { + if (log) os::Printer::log("Multisampling with more samples than requested.", ELL_DEBUG); rating += 5; - } - else if ( !Params.AntiAlias && attribSampleBuffers > 0 ) - { - if ( log ) + } else if (!Params.AntiAlias && attribSampleBuffers > 0) { + if (log) os::Printer::log("Got multisampling (unrequested).", ELL_DEBUG); rating += 3; } @@ -513,8 +466,8 @@ void CEGLManager::destroySurface() // We should unbind current EGL context before destroy EGL surface. eglMakeCurrent(EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglDestroySurface(EglDisplay, EglSurface); - EglSurface = EGL_NO_SURFACE; + eglDestroySurface(EglDisplay, EglSurface); + EglSurface = EGL_NO_SURFACE; } bool CEGLManager::generateContext() @@ -527,8 +480,7 @@ bool CEGLManager::generateContext() EGLint OpenGLESVersion = 0; - switch (Params.DriverType) - { + switch (Params.DriverType) { case EDT_OGLES1: OpenGLESVersion = 1; break; @@ -540,25 +492,23 @@ bool CEGLManager::generateContext() break; } - EGLint ContextAttrib[] = - { + EGLint ContextAttrib[] = + { #ifdef EGL_VERSION_1_3 - EGL_CONTEXT_CLIENT_VERSION, OpenGLESVersion, + EGL_CONTEXT_CLIENT_VERSION, OpenGLESVersion, #endif - EGL_NONE, 0 - }; + EGL_NONE, 0}; EglContext = eglCreateContext(EglDisplay, EglConfig, EGL_NO_CONTEXT, ContextAttrib); - if (testEGLError()) - { + if (testEGLError()) { os::Printer::log("Could not create EGL context.", ELL_ERROR); return false; } os::Printer::log("EGL context created with OpenGLESVersion: ", core::stringc((int)OpenGLESVersion), ELL_DEBUG); - return true; + return true; } void CEGLManager::destroyContext() @@ -570,34 +520,33 @@ void CEGLManager::destroyContext() eglMakeCurrent(EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(EglDisplay, EglContext); - EglContext = EGL_NO_CONTEXT; + EglContext = EGL_NO_CONTEXT; } -bool CEGLManager::activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) +bool CEGLManager::activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) { eglMakeCurrent(EglDisplay, EglSurface, EglSurface, EglContext); - if (testEGLError()) - { + if (testEGLError()) { os::Printer::log("Could not make EGL context current."); return false; } return true; } -const SExposedVideoData& CEGLManager::getContext() const +const SExposedVideoData &CEGLManager::getContext() const { return Data; } -void* CEGLManager::getProcAddress(const std::string &procName) +void *CEGLManager::getProcAddress(const std::string &procName) { - return (void*)eglGetProcAddress(procName.c_str()); + return (void *)eglGetProcAddress(procName.c_str()); } bool CEGLManager::swapBuffers() { - return (eglSwapBuffers(EglDisplay, EglSurface)==EGL_TRUE); + return (eglSwapBuffers(EglDisplay, EglSurface) == EGL_TRUE); } bool CEGLManager::testEGLError() @@ -605,54 +554,53 @@ bool CEGLManager::testEGLError() #if defined(EGL_VERSION_1_0) && defined(_DEBUG) EGLint status = eglGetError(); - switch (status) - { - case EGL_SUCCESS: - return false; - case EGL_NOT_INITIALIZED : - os::Printer::log("Not Initialized", ELL_ERROR); - break; - case EGL_BAD_ACCESS: - os::Printer::log("Bad Access", ELL_ERROR); - break; - case EGL_BAD_ALLOC: - os::Printer::log("Bad Alloc", ELL_ERROR); - break; - case EGL_BAD_ATTRIBUTE: - os::Printer::log("Bad Attribute", ELL_ERROR); - break; - case EGL_BAD_CONTEXT: - os::Printer::log("Bad Context", ELL_ERROR); - break; - case EGL_BAD_CONFIG: - os::Printer::log("Bad Config", ELL_ERROR); - break; - case EGL_BAD_CURRENT_SURFACE: - os::Printer::log("Bad Current Surface", ELL_ERROR); - break; - case EGL_BAD_DISPLAY: - os::Printer::log("Bad Display", ELL_ERROR); - break; - case EGL_BAD_SURFACE: - os::Printer::log("Bad Surface", ELL_ERROR); - break; - case EGL_BAD_MATCH: - os::Printer::log("Bad Match", ELL_ERROR); - break; - case EGL_BAD_PARAMETER: - os::Printer::log("Bad Parameter", ELL_ERROR); - break; - case EGL_BAD_NATIVE_PIXMAP: - os::Printer::log("Bad Native Pixmap", ELL_ERROR); - break; - case EGL_BAD_NATIVE_WINDOW: - os::Printer::log("Bad Native Window", ELL_ERROR); - break; - case EGL_CONTEXT_LOST: - os::Printer::log("Context Lost", ELL_ERROR); - break; - default: - break; + switch (status) { + case EGL_SUCCESS: + return false; + case EGL_NOT_INITIALIZED: + os::Printer::log("Not Initialized", ELL_ERROR); + break; + case EGL_BAD_ACCESS: + os::Printer::log("Bad Access", ELL_ERROR); + break; + case EGL_BAD_ALLOC: + os::Printer::log("Bad Alloc", ELL_ERROR); + break; + case EGL_BAD_ATTRIBUTE: + os::Printer::log("Bad Attribute", ELL_ERROR); + break; + case EGL_BAD_CONTEXT: + os::Printer::log("Bad Context", ELL_ERROR); + break; + case EGL_BAD_CONFIG: + os::Printer::log("Bad Config", ELL_ERROR); + break; + case EGL_BAD_CURRENT_SURFACE: + os::Printer::log("Bad Current Surface", ELL_ERROR); + break; + case EGL_BAD_DISPLAY: + os::Printer::log("Bad Display", ELL_ERROR); + break; + case EGL_BAD_SURFACE: + os::Printer::log("Bad Surface", ELL_ERROR); + break; + case EGL_BAD_MATCH: + os::Printer::log("Bad Match", ELL_ERROR); + break; + case EGL_BAD_PARAMETER: + os::Printer::log("Bad Parameter", ELL_ERROR); + break; + case EGL_BAD_NATIVE_PIXMAP: + os::Printer::log("Bad Native Pixmap", ELL_ERROR); + break; + case EGL_BAD_NATIVE_WINDOW: + os::Printer::log("Bad Native Window", ELL_ERROR); + break; + case EGL_CONTEXT_LOST: + os::Printer::log("Context Lost", ELL_ERROR); + break; + default: + break; }; return true; @@ -664,4 +612,4 @@ bool CEGLManager::testEGLError() } } -#endif +#endif diff --git a/source/Irrlicht/CEGLManager.h b/source/Irrlicht/CEGLManager.h old mode 100755 new mode 100644 index 3928043c..49371e46 --- a/source/Irrlicht/CEGLManager.h +++ b/source/Irrlicht/CEGLManager.h @@ -4,8 +4,8 @@ #pragma once -#ifdef _IRR_COMPILE_WITH_EGL_MANAGER_ - +#ifdef _IRR_COMPILE_WITH_EGL_MANAGER_ + #include #include "SIrrCreationParameters.h" @@ -16,99 +16,99 @@ namespace irr { namespace video { - // EGL manager. - class CEGLManager : public IContextManager +// EGL manager. +class CEGLManager : public IContextManager +{ +public: + //! Constructor. + CEGLManager(); + + //! Destructor. + virtual ~CEGLManager(); + + // Initialize EGL. + /* This method initialize EGLand create EGL display, anyway surface and context + aren't create. */ + bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) override; + + // Terminate EGL. + /* Terminate EGL context. This method break both existed surface and context. */ + void terminate() override; + + // Create EGL surface. + /* This method create EGL surface. On some platforms eg. Android, we must + recreate surface on each resume, because WindowID may change, so existed + surface may not be valid. If EGL context already exist, this method + automatically activates it. */ + bool generateSurface() override; + + // Destroy EGL surface. + /* This method destroy EGL. On some platforms eg. Android, we should call + this method on each pause, because after resume this surface may not be valid. + Hovewer this method doesn'r break EGL context. */ + void destroySurface() override; + + // Create EGL context. + /* This method create and activate EGL context. */ + bool generateContext() override; + + // Destroy EGL context. + /* This method destroy EGL context. */ + void destroyContext() override; + + const SExposedVideoData &getContext() const override; + + bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) override; + + // Get procedure address. + void *getProcAddress(const std::string &procName) override; + + // Swap buffers. + bool swapBuffers() override; + +protected: + enum EConfigStyle { - public: - //! Constructor. - CEGLManager(); + //! Get first result of eglChooseConfigs and if that fails try again by requesting simpler attributes + ECS_EGL_CHOOSE_FIRST_LOWER_EXPECTATIONS, - //! Destructor. - virtual ~CEGLManager(); - - // Initialize EGL. - /* This method initialize EGLand create EGL display, anyway surface and context - aren't create. */ - bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) override; - - // Terminate EGL. - /* Terminate EGL context. This method break both existed surface and context. */ - void terminate() override; - - // Create EGL surface. - /* This method create EGL surface. On some platforms eg. Android, we must - recreate surface on each resume, because WindowID may change, so existed - surface may not be valid. If EGL context already exist, this method - automatically activates it. */ - bool generateSurface() override; - - // Destroy EGL surface. - /* This method destroy EGL. On some platforms eg. Android, we should call - this method on each pause, because after resume this surface may not be valid. - Hovewer this method doesn'r break EGL context. */ - void destroySurface() override; - - // Create EGL context. - /* This method create and activate EGL context. */ - bool generateContext() override; - - // Destroy EGL context. - /* This method destroy EGL context. */ - void destroyContext() override; - - const SExposedVideoData& getContext() const override; - - bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) override; - - // Get procedure address. - void* getProcAddress(const std::string &procName) override; - - // Swap buffers. - bool swapBuffers() override; - - protected: - enum EConfigStyle - { - //! Get first result of eglChooseConfigs and if that fails try again by requesting simpler attributes - ECS_EGL_CHOOSE_FIRST_LOWER_EXPECTATIONS, - - //! We select our own best fit and avoid using eglChooseConfigs - ECS_IRR_CHOOSE, - }; - - EGLConfig chooseConfig(EConfigStyle confStyle); - - //! Check how close this config is to the parameters we requested - //! returns 0 is perfect, larger values are worse and < 0 is unusable. - irr::s32 rateConfig(EGLConfig config, EGLint eglOpenGLBIT, bool log=false); - - // Helper to sort EGLConfig's. (because we got no std::pair....) - struct SConfigRating - { - EGLConfig config; - irr::s32 rating; - bool operator<(const SConfigRating& other) const - { - return rating < other.rating; - } - }; - - private: - bool testEGLError(); - - NativeWindowType EglWindow; - EGLDisplay EglDisplay; - EGLSurface EglSurface; - EGLContext EglContext; - - EGLConfig EglConfig; - - SIrrlichtCreationParameters Params; - SExposedVideoData Data; - - EGLint MajorVersion; - EGLint MinorVersion; + //! We select our own best fit and avoid using eglChooseConfigs + ECS_IRR_CHOOSE, }; + + EGLConfig chooseConfig(EConfigStyle confStyle); + + //! Check how close this config is to the parameters we requested + //! returns 0 is perfect, larger values are worse and < 0 is unusable. + irr::s32 rateConfig(EGLConfig config, EGLint eglOpenGLBIT, bool log = false); + + // Helper to sort EGLConfig's. (because we got no std::pair....) + struct SConfigRating + { + EGLConfig config; + irr::s32 rating; + bool operator<(const SConfigRating &other) const + { + return rating < other.rating; + } + }; + +private: + bool testEGLError(); + + NativeWindowType EglWindow; + EGLDisplay EglDisplay; + EGLSurface EglSurface; + EGLContext EglContext; + + EGLConfig EglConfig; + + SIrrlichtCreationParameters Params; + SExposedVideoData Data; + + EGLint MajorVersion; + EGLint MinorVersion; +}; } } -#endif +#endif diff --git a/source/Irrlicht/CEmptySceneNode.cpp b/source/Irrlicht/CEmptySceneNode.cpp index bc18b331..2b965a19 100644 --- a/source/Irrlicht/CEmptySceneNode.cpp +++ b/source/Irrlicht/CEmptySceneNode.cpp @@ -11,17 +11,16 @@ namespace scene { //! constructor -CEmptySceneNode::CEmptySceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id) -: ISceneNode(parent, mgr, id) +CEmptySceneNode::CEmptySceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id) : + ISceneNode(parent, mgr, id) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CEmptySceneNode"); - #endif +#endif setAutomaticCulling(scene::EAC_OFF); } - //! pre render event void CEmptySceneNode::OnRegisterSceneNode() { @@ -31,40 +30,36 @@ void CEmptySceneNode::OnRegisterSceneNode() ISceneNode::OnRegisterSceneNode(); } - //! render void CEmptySceneNode::render() { // do nothing } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CEmptySceneNode::getBoundingBox() const +const core::aabbox3d &CEmptySceneNode::getBoundingBox() const { return Box; } - //! Creates a clone of this scene node and its children. -ISceneNode* CEmptySceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) +ISceneNode *CEmptySceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { if (!newParent) newParent = Parent; if (!newManager) newManager = SceneManager; - CEmptySceneNode* nb = new CEmptySceneNode(newParent, - newManager, ID); + CEmptySceneNode *nb = new CEmptySceneNode(newParent, + newManager, ID); nb->cloneMembers(this, newManager); nb->Box = Box; - if ( newParent ) + if (newParent) nb->drop(); return nb; } - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CEmptySceneNode.h b/source/Irrlicht/CEmptySceneNode.h index ecfd8fe6..c89ad59a 100644 --- a/source/Irrlicht/CEmptySceneNode.h +++ b/source/Irrlicht/CEmptySceneNode.h @@ -11,32 +11,30 @@ namespace irr namespace scene { - class CEmptySceneNode : public ISceneNode - { - public: +class CEmptySceneNode : public ISceneNode +{ +public: + //! constructor + CEmptySceneNode(ISceneNode *parent, ISceneManager *mgr, s32 id); - //! constructor - CEmptySceneNode(ISceneNode* parent, ISceneManager* mgr, s32 id); + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! This method is called just before the rendering process of the whole scene. + void OnRegisterSceneNode() override; - //! This method is called just before the rendering process of the whole scene. - void OnRegisterSceneNode() override; + //! does nothing. + void render() override; - //! does nothing. - void render() override; + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_EMPTY; } - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_EMPTY; } + //! Creates a clone of this scene node and its children. + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; - //! Creates a clone of this scene node and its children. - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; - - private: - - core::aabbox3d Box; - }; +private: + core::aabbox3d Box; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CFPSCounter.cpp b/source/Irrlicht/CFPSCounter.cpp index 4e965ec2..6717df5c 100644 --- a/source/Irrlicht/CFPSCounter.cpp +++ b/source/Irrlicht/CFPSCounter.cpp @@ -10,43 +10,36 @@ namespace irr namespace video { - -CFPSCounter::CFPSCounter() -: FPS(60), Primitive(0), StartTime(0), FramesCounted(0), - PrimitivesCounted(0), PrimitiveAverage(0), PrimitiveTotal(0) +CFPSCounter::CFPSCounter() : + FPS(60), Primitive(0), StartTime(0), FramesCounted(0), + PrimitivesCounted(0), PrimitiveAverage(0), PrimitiveTotal(0) { - } - //! returns current fps s32 CFPSCounter::getFPS() const { return FPS; } - //! returns current primitive count u32 CFPSCounter::getPrimitive() const { return Primitive; } - //! returns average primitive count of last period u32 CFPSCounter::getPrimitiveAverage() const { return PrimitiveAverage; } - //! returns accumulated primitive count since start u32 CFPSCounter::getPrimitiveTotal() const { return PrimitiveTotal; } - //! to be called every frame void CFPSCounter::registerFrame(u32 now, u32 primitivesDrawn) { @@ -57,12 +50,11 @@ void CFPSCounter::registerFrame(u32 now, u32 primitivesDrawn) const u32 milliseconds = now - StartTime; - if (milliseconds >= 1500 ) - { - const f32 invMilli = core::reciprocal ( (f32) milliseconds ); + if (milliseconds >= 1500) { + const f32 invMilli = core::reciprocal((f32)milliseconds); - FPS = core::ceil32 ( ( 1000 * FramesCounted ) * invMilli ); - PrimitiveAverage = core::ceil32 ( ( 1000 * PrimitivesCounted ) * invMilli ); + FPS = core::ceil32((1000 * FramesCounted) * invMilli); + PrimitiveAverage = core::ceil32((1000 * PrimitivesCounted) * invMilli); FramesCounted = 0; PrimitivesCounted = 0; @@ -70,7 +62,5 @@ void CFPSCounter::registerFrame(u32 now, u32 primitivesDrawn) } } - } // end namespace video } // end namespace irr - diff --git a/source/Irrlicht/CFPSCounter.h b/source/Irrlicht/CFPSCounter.h index dc1d9236..e73afb04 100644 --- a/source/Irrlicht/CFPSCounter.h +++ b/source/Irrlicht/CFPSCounter.h @@ -11,7 +11,6 @@ namespace irr namespace video { - class CFPSCounter { public: @@ -33,7 +32,6 @@ public: void registerFrame(u32 now, u32 primitive); private: - s32 FPS; u32 Primitive; u32 StartTime; @@ -44,6 +42,5 @@ private: u32 PrimitiveTotal; }; - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CFileList.cpp b/source/Irrlicht/CFileList.cpp index d643d12c..dde8e75a 100644 --- a/source/Irrlicht/CFileList.cpp +++ b/source/Irrlicht/CFileList.cpp @@ -15,12 +15,12 @@ namespace io static const io::path emptyFileListEntry; -CFileList::CFileList(const io::path& path, bool ignoreCase, bool ignorePaths) - : IgnorePaths(ignorePaths), IgnoreCase(ignoreCase), Path(path) +CFileList::CFileList(const io::path &path, bool ignoreCase, bool ignorePaths) : + IgnorePaths(ignorePaths), IgnoreCase(ignoreCase), Path(path) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CFileList"); - #endif +#endif Path.replace('\\', '/'); } @@ -40,7 +40,7 @@ void CFileList::sort() Files.sort(); } -const io::path& CFileList::getFileName(u32 index) const +const io::path &CFileList::getFileName(u32 index) const { if (index >= Files.size()) return emptyFileListEntry; @@ -48,9 +48,8 @@ const io::path& CFileList::getFileName(u32 index) const return Files[index].Name; } - //! Gets the full name of a file in the list, path included, based on an index. -const io::path& CFileList::getFullFileName(u32 index) const +const io::path &CFileList::getFullFileName(u32 index) const { if (index >= Files.size()) return emptyFileListEntry; @@ -59,10 +58,10 @@ const io::path& CFileList::getFullFileName(u32 index) const } //! adds a file or folder -u32 CFileList::addItem(const io::path& fullPath, u32 offset, u32 size, bool isDirectory, u32 id) +u32 CFileList::addItem(const io::path &fullPath, u32 offset, u32 size, bool isDirectory, u32 id) { SFileListEntry entry; - entry.ID = id ? id : Files.size(); + entry.ID = id ? id : Files.size(); entry.Offset = offset; entry.Size = size; entry.Name = fullPath; @@ -70,10 +69,9 @@ u32 CFileList::addItem(const io::path& fullPath, u32 offset, u32 size, bool isDi entry.IsDirectory = isDirectory; // remove trailing slash - if (entry.Name.lastChar() == '/') - { + if (entry.Name.lastChar() == '/') { entry.IsDirectory = true; - entry.Name[entry.Name.size()-1] = 0; + entry.Name[entry.Name.size() - 1] = 0; entry.Name.validate(); } @@ -87,7 +85,7 @@ u32 CFileList::addItem(const io::path& fullPath, u32 offset, u32 size, bool isDi if (IgnorePaths) entry.FullName = entry.Name; - //os::Printer::log(Path.c_str(), entry.FullName); + // os::Printer::log(Path.c_str(), entry.FullName); Files.push_back(entry); @@ -120,9 +118,8 @@ u32 CFileList::getFileOffset(u32 index) const return index < Files.size() ? Files[index].Offset : 0; } - //! Searches for a file or folder within the list, returns the index -s32 CFileList::findFile(const io::path& filename, bool isDirectory = false) const +s32 CFileList::findFile(const io::path &filename, bool isDirectory = false) const { SFileListEntry entry; // we only need FullName to be set for the search @@ -133,10 +130,9 @@ s32 CFileList::findFile(const io::path& filename, bool isDirectory = false) cons entry.FullName.replace('\\', '/'); // remove trailing slash - if (entry.FullName.lastChar() == '/') - { + if (entry.FullName.lastChar() == '/') { entry.IsDirectory = true; - entry.FullName[entry.FullName.size()-1] = 0; + entry.FullName[entry.FullName.size() - 1] = 0; entry.FullName.validate(); } @@ -149,14 +145,11 @@ s32 CFileList::findFile(const io::path& filename, bool isDirectory = false) cons return Files.binary_search(entry); } - //! Returns the base path of the file list -const io::path& CFileList::getPath() const +const io::path &CFileList::getPath() const { return Path; } - } // end namespace irr } // end namespace io - diff --git a/source/Irrlicht/CFileList.h b/source/Irrlicht/CFileList.h index 8ceddd73..1af975b2 100644 --- a/source/Irrlicht/CFileList.h +++ b/source/Irrlicht/CFileList.h @@ -8,7 +8,6 @@ #include "irrString.h" #include "irrArray.h" - namespace irr { namespace io @@ -42,7 +41,7 @@ struct SFileListEntry bool IsDirectory; //! The == operator is provided so that CFileList can slowly search the list! - bool operator ==(const struct SFileListEntry& other) const + bool operator==(const struct SFileListEntry &other) const { if (IsDirectory != other.IsDirectory) return false; @@ -51,7 +50,7 @@ struct SFileListEntry } //! The < operator is provided so that CFileList can sort and quickly search the list. - bool operator <(const struct SFileListEntry& other) const + bool operator<(const struct SFileListEntry &other) const { if (IsDirectory != other.IsDirectory) return IsDirectory; @@ -60,17 +59,15 @@ struct SFileListEntry } }; - //! Implementation of a file list class CFileList : public IFileList { public: - // CFileList methods //! Constructor /** \param path The path of this file archive */ - CFileList(const io::path& path, bool ignoreCase, bool ignorePaths); + CFileList(const io::path &path, bool ignoreCase, bool ignorePaths); //! Destructor virtual ~CFileList(); @@ -81,7 +78,7 @@ public: \param offset The offset where the file is stored in an archive \param size The size of the file in bytes. \param id The ID of the file in the archive which owns it */ - u32 addItem(const io::path& fullPath, u32 offset, u32 size, bool isDirectory, u32 id=0) override; + u32 addItem(const io::path &fullPath, u32 offset, u32 size, bool isDirectory, u32 id = 0) override; //! Sorts the file list. You should call this after adding any items to the file list void sort() override; @@ -90,10 +87,10 @@ public: u32 getFileCount() const override; //! Gets the name of a file in the list, based on an index. - const io::path& getFileName(u32 index) const override; + const io::path &getFileName(u32 index) const override; //! Gets the full name of a file in the list, path included, based on an index. - const io::path& getFullFileName(u32 index) const override; + const io::path &getFullFileName(u32 index) const override; //! Returns the ID of a file in the file list, based on an index. u32 getID(u32 index) const override; @@ -108,13 +105,12 @@ public: u32 getFileOffset(u32 index) const override; //! Searches for a file or folder within the list, returns the index - s32 findFile(const io::path& filename, bool isFolder) const override; + s32 findFile(const io::path &filename, bool isFolder) const override; //! Returns the base path of the file list - const io::path& getPath() const override; + const io::path &getPath() const override; protected: - //! Ignore paths when adding or searching for files bool IgnorePaths; @@ -128,6 +124,5 @@ protected: core::array Files; }; - } // end namespace irr } // end namespace io diff --git a/source/Irrlicht/CFileSystem.cpp b/source/Irrlicht/CFileSystem.cpp index afbcab0c..d569b109 100644 --- a/source/Irrlicht/CFileSystem.cpp +++ b/source/Irrlicht/CFileSystem.cpp @@ -2,7 +2,6 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h - #include "CFileSystem.h" #include "IReadFile.h" #include "IWriteFile.h" @@ -16,25 +15,25 @@ #include "CWriteFile.h" #include -#if defined (__STRICT_ANSI__) - #error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi. +#if defined(__STRICT_ANSI__) +#error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi. #endif -#if defined (_IRR_WINDOWS_API_) - #include // for _chdir - #include // for _access - #include +#if defined(_IRR_WINDOWS_API_) +#include // for _chdir +#include // for _access +#include #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_) || defined(_IRR_ANDROID_PLATFORM_)) - #include - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include +#include #elif defined(_IRR_EMSCRIPTEN_PLATFORM_) - #include +#include #endif namespace irr @@ -45,47 +44,41 @@ namespace io //! constructor CFileSystem::CFileSystem() { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CFileSystem"); - #endif +#endif setFileListSystem(FILESYSTEM_NATIVE); //! reset current working directory getWorkingDirectory(); ArchiveLoader.push_back(new CArchiveLoaderZIP(this)); - } - //! destructor CFileSystem::~CFileSystem() { u32 i; - for ( i=0; i < FileArchives.size(); ++i) - { + for (i = 0; i < FileArchives.size(); ++i) { FileArchives[i]->drop(); } - for ( i=0; i < ArchiveLoader.size(); ++i) - { + for (i = 0; i < ArchiveLoader.size(); ++i) { ArchiveLoader[i]->drop(); } } - //! opens a file for read access -IReadFile* CFileSystem::createAndOpenFile(const io::path& filename) +IReadFile *CFileSystem::createAndOpenFile(const io::path &filename) { - if ( filename.empty() ) + if (filename.empty()) return 0; - IReadFile* file = 0; + IReadFile *file = 0; u32 i; - for (i=0; i< FileArchives.size(); ++i) - { + for (i = 0; i < FileArchives.size(); ++i) { file = FileArchives[i]->createAndOpenFile(filename); if (file) return file; @@ -96,10 +89,9 @@ IReadFile* CFileSystem::createAndOpenFile(const io::path& filename) return CReadFile::createReadFile(getAbsolutePath(filename)); } - //! Creates an IReadFile interface for treating memory like a file. -IReadFile* CFileSystem::createMemoryReadFile(const void* memory, s32 len, - const io::path& fileName, bool deleteMemoryWhenDropped) +IReadFile *CFileSystem::createMemoryReadFile(const void *memory, s32 len, + const io::path &fileName, bool deleteMemoryWhenDropped) { if (!memory) return 0; @@ -107,10 +99,9 @@ IReadFile* CFileSystem::createMemoryReadFile(const void* memory, s32 len, return new CMemoryReadFile(memory, len, fileName, deleteMemoryWhenDropped); } - //! Creates an IReadFile interface for reading files inside files -IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName, - IReadFile* alreadyOpenedFile, long pos, long areaSize) +IReadFile *CFileSystem::createLimitReadFile(const io::path &fileName, + IReadFile *alreadyOpenedFile, long pos, long areaSize) { if (!alreadyOpenedFile) return 0; @@ -118,10 +109,9 @@ IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName, return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName); } - //! Creates an IReadFile interface for treating memory like a file. -IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len, - const io::path& fileName, bool deleteMemoryWhenDropped) +IWriteFile *CFileSystem::createMemoryWriteFile(void *memory, s32 len, + const io::path &fileName, bool deleteMemoryWhenDropped) { if (!memory) return 0; @@ -129,16 +119,14 @@ IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len, return new CMemoryWriteFile(memory, len, fileName, deleteMemoryWhenDropped); } - //! Opens a file for write access. -IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append) +IWriteFile *CFileSystem::createAndWriteFile(const io::path &filename, bool append) { return CWriteFile::createWriteFile(filename, append); } - //! Adds an external archive loader to the engine. -void CFileSystem::addArchiveLoader(IArchiveLoader* loader) +void CFileSystem::addArchiveLoader(IArchiveLoader *loader) { if (!loader) return; @@ -154,7 +142,7 @@ u32 CFileSystem::getArchiveLoaderCount() const } //! Gets the archive loader by index. -IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const +IArchiveLoader *CFileSystem::getArchiveLoader(u32 index) const { if (index < ArchiveLoader.size()) return ArchiveLoader[index]; @@ -166,13 +154,12 @@ IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative) { bool r = false; - const s32 dest = (s32) sourceIndex + relative; + const s32 dest = (s32)sourceIndex + relative; const s32 dir = relative < 0 ? -1 : 1; - const s32 sourceEnd = ((s32) FileArchives.size() ) - 1; + const s32 sourceEnd = ((s32)FileArchives.size()) - 1; IFileArchive *t; - for (s32 s = (s32) sourceIndex;s != dest; s += dir) - { + for (s32 s = (s32)sourceIndex; s != dest; s += dir) { if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd) continue; @@ -184,14 +171,13 @@ bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative) return r; } - //! Adds an archive to the file system. -bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase, - bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType, - const core::stringc& password, - IFileArchive** retArchive) +bool CFileSystem::addFileArchive(const io::path &filename, bool ignoreCase, + bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType, + const core::stringc &password, + IFileArchive **retArchive) { - IFileArchive* archive = 0; + IFileArchive *archive = 0; bool ret = false; // see if archive is already added @@ -199,13 +185,10 @@ bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase, s32 i; // do we know what type it should be? - if (archiveType == EFAT_UNKNOWN) - { + if (archiveType == EFAT_UNKNOWN) { // try to load archive based on file name - for (i = ArchiveLoader.size()-1; i >=0 ; --i) - { - if (ArchiveLoader[i]->isALoadableFileFormat(filename)) - { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { + if (ArchiveLoader[i]->isALoadableFileFormat(filename)) { archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths); if (archive) break; @@ -213,16 +196,12 @@ bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase, } // try to load archive based on content - if (!archive) - { - io::IReadFile* file = createAndOpenFile(filename); - if (file) - { - for (i = ArchiveLoader.size()-1; i >= 0; --i) - { + if (!archive) { + io::IReadFile *file = createAndOpenFile(filename); + if (file) { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { file->seek(0); - if (ArchiveLoader[i]->isALoadableFileFormat(file)) - { + if (ArchiveLoader[i]->isALoadableFileFormat(file)) { file->seek(0); archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths); if (archive) @@ -232,36 +211,28 @@ bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase, file->drop(); } } - } - else - { + } else { // try to open archive based on archive loader type - io::IReadFile* file = 0; + io::IReadFile *file = 0; - for (i = ArchiveLoader.size()-1; i >= 0; --i) - { - if (ArchiveLoader[i]->isALoadableFileFormat(archiveType)) - { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { + if (ArchiveLoader[i]->isALoadableFileFormat(archiveType)) { // attempt to open file if (!file) file = createAndOpenFile(filename); // is the file open? - if (file) - { + if (file) { // attempt to open archive file->seek(0); - if (ArchiveLoader[i]->isALoadableFileFormat(file)) - { + if (ArchiveLoader[i]->isALoadableFileFormat(file)) { file->seek(0); archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths); if (archive) break; } - } - else - { + } else { // couldn't open file break; } @@ -273,43 +244,35 @@ bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase, file->drop(); } - if (archive) - { + if (archive) { FileArchives.push_back(archive); if (password.size()) - archive->Password=password; + archive->Password = password; if (retArchive) *retArchive = archive; ret = true; - } - else - { + } else { os::Printer::log("Could not create archive for", filename, ELL_ERROR); } return ret; } - -bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase, +bool CFileSystem::addFileArchive(IReadFile *file, bool ignoreCase, bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType, - const core::stringc& password, IFileArchive** retArchive) + const core::stringc &password, IFileArchive **retArchive) { if (!file) return false; - if (file) - { - IFileArchive* archive = 0; + if (file) { + IFileArchive *archive = 0; s32 i; - if (archiveType == EFAT_UNKNOWN) - { + if (archiveType == EFAT_UNKNOWN) { // try to load archive based on file name - for (i = ArchiveLoader.size()-1; i >=0 ; --i) - { - if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName())) - { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { + if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName())) { archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths); if (archive) break; @@ -317,13 +280,10 @@ bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase, } // try to load archive based on content - if (!archive) - { - for (i = ArchiveLoader.size()-1; i >= 0; --i) - { + if (!archive) { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { file->seek(0); - if (ArchiveLoader[i]->isALoadableFileFormat(file)) - { + if (ArchiveLoader[i]->isALoadableFileFormat(file)) { file->seek(0); archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths); if (archive) @@ -331,18 +291,13 @@ bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase, } } } - } - else - { + } else { // try to open archive based on archive loader type - for (i = ArchiveLoader.size()-1; i >= 0; --i) - { - if (ArchiveLoader[i]->isALoadableFileFormat(archiveType)) - { + for (i = ArchiveLoader.size() - 1; i >= 0; --i) { + if (ArchiveLoader[i]->isALoadableFileFormat(archiveType)) { // attempt to open archive file->seek(0); - if (ArchiveLoader[i]->isALoadableFileFormat(file)) - { + if (ArchiveLoader[i]->isALoadableFileFormat(file)) { file->seek(0); archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths); if (archive) @@ -352,17 +307,14 @@ bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase, } } - if (archive) - { + if (archive) { FileArchives.push_back(archive); if (password.size()) - archive->Password=password; + archive->Password = password; if (retArchive) *retArchive = archive; return true; - } - else - { + } else { os::Printer::log("Could not create archive for", file->getFileName(), ELL_ERROR); } } @@ -370,16 +322,12 @@ bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase, return false; } - //! Adds an archive to the file system. -bool CFileSystem::addFileArchive(IFileArchive* archive) +bool CFileSystem::addFileArchive(IFileArchive *archive) { - if ( archive ) - { - for (u32 i=0; i < FileArchives.size(); ++i) - { - if (archive == FileArchives[i]) - { + if (archive) { + for (u32 i = 0; i < FileArchives.size(); ++i) { + if (archive == FileArchives[i]) { return false; } } @@ -392,13 +340,11 @@ bool CFileSystem::addFileArchive(IFileArchive* archive) return false; } - //! removes an archive from the file system. bool CFileSystem::removeFileArchive(u32 index) { bool ret = false; - if (index < FileArchives.size()) - { + if (index < FileArchives.size()) { FileArchives[index]->drop(); FileArchives.erase(index); ret = true; @@ -406,85 +352,72 @@ bool CFileSystem::removeFileArchive(u32 index) return ret; } - //! removes an archive from the file system. -bool CFileSystem::removeFileArchive(const io::path& filename) +bool CFileSystem::removeFileArchive(const io::path &filename) { const path absPath = getAbsolutePath(filename); - for (u32 i=0; i < FileArchives.size(); ++i) - { + for (u32 i = 0; i < FileArchives.size(); ++i) { if (absPath == FileArchives[i]->getFileList()->getPath()) return removeFileArchive(i); } return false; } - //! Removes an archive from the file system. -bool CFileSystem::removeFileArchive(const IFileArchive* archive) +bool CFileSystem::removeFileArchive(const IFileArchive *archive) { - for (u32 i=0; i < FileArchives.size(); ++i) - { - if (archive == FileArchives[i]) - { + for (u32 i = 0; i < FileArchives.size(); ++i) { + if (archive == FileArchives[i]) { return removeFileArchive(i); } } return false; } - //! gets an archive u32 CFileSystem::getFileArchiveCount() const { return FileArchives.size(); } - -IFileArchive* CFileSystem::getFileArchive(u32 index) +IFileArchive *CFileSystem::getFileArchive(u32 index) { return index < getFileArchiveCount() ? FileArchives[index] : 0; } - //! Returns the string of the current working directory -const io::path& CFileSystem::getWorkingDirectory() +const io::path &CFileSystem::getWorkingDirectory() { EFileSystemType type = FileSystemType; - if (type != FILESYSTEM_NATIVE) - { + if (type != FILESYSTEM_NATIVE) { type = FILESYSTEM_VIRTUAL; - } - else - { - #if defined(_IRR_WINDOWS_API_) - fschar_t tmp[_MAX_PATH]; - _getcwd(tmp, _MAX_PATH); - WorkingDirectory[FILESYSTEM_NATIVE] = tmp; - WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/'); - #endif + } else { +#if defined(_IRR_WINDOWS_API_) + fschar_t tmp[_MAX_PATH]; + _getcwd(tmp, _MAX_PATH); + WorkingDirectory[FILESYSTEM_NATIVE] = tmp; + WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/'); +#endif - #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) +#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) - // getting the CWD is rather complex as we do not know the size - // so try it until the call was successful - // Note that neither the first nor the second parameter may be 0 according to POSIX + // getting the CWD is rather complex as we do not know the size + // so try it until the call was successful + // Note that neither the first nor the second parameter may be 0 according to POSIX - u32 pathSize=256; - char *tmpPath = new char[pathSize]; - while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize))) - { - delete [] tmpPath; - pathSize *= 2; - tmpPath = new char[pathSize]; - } - if (tmpPath) - { - WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath; - delete [] tmpPath; - } - #endif + u32 pathSize = 256; + char *tmpPath = new char[pathSize]; + while ((pathSize < (1 << 16)) && !(getcwd(tmpPath, pathSize))) { + delete[] tmpPath; + pathSize *= 2; + tmpPath = new char[pathSize]; + } + if (tmpPath) { + WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath; + delete[] tmpPath; + } +#endif WorkingDirectory[type].validate(); } @@ -492,21 +425,17 @@ const io::path& CFileSystem::getWorkingDirectory() return WorkingDirectory[type]; } - //! Changes the current Working Directory to the given string. -bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory) +bool CFileSystem::changeWorkingDirectoryTo(const io::path &newDirectory) { - bool success=false; + bool success = false; - if (FileSystemType != FILESYSTEM_NATIVE) - { + if (FileSystemType != FILESYSTEM_NATIVE) { WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory; // is this empty string constant really intended? flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], _IRR_TEXT("")); success = true; - } - else - { + } else { WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory; #if defined(_MSC_VER) @@ -519,36 +448,33 @@ bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory) return success; } - -io::path CFileSystem::getAbsolutePath(const io::path& filename) const +io::path CFileSystem::getAbsolutePath(const io::path &filename) const { - if ( filename.empty() ) + if (filename.empty()) return filename; #if defined(_IRR_WINDOWS_API_) - fschar_t *p=0; + fschar_t *p = 0; fschar_t fpath[_MAX_PATH]; - p = _fullpath(fpath, filename.c_str(), _MAX_PATH); - core::stringc tmp(p); - tmp.replace('\\', '/'); + p = _fullpath(fpath, filename.c_str(), _MAX_PATH); + core::stringc tmp(p); + tmp.replace('\\', '/'); return tmp; #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) - c8* p=0; + c8 *p = 0; c8 fpath[4096]; - fpath[0]=0; + fpath[0] = 0; p = realpath(filename.c_str(), fpath); - if (!p) - { + if (!p) { // content in fpath is unclear at this point if (!fpath[0]) // seems like fpath wasn't altered, use our best guess { io::path tmp(filename); return flattenFilename(tmp); - } - else + } else return io::path(fpath); } - if (filename[filename.size()-1]=='/') - return io::path(p)+_IRR_TEXT("/"); + if (filename[filename.size() - 1] == '/') + return io::path(p) + _IRR_TEXT("/"); else return io::path(p); #else @@ -556,11 +482,10 @@ io::path CFileSystem::getAbsolutePath(const io::path& filename) const #endif } - //! returns the directory part of a filename, i.e. all until the first //! slash or backslash, excluding it. If no directory path is prefixed, a '.' //! is returned. -io::path CFileSystem::getFileDir(const io::path& filename) const +io::path CFileSystem::getFileDir(const io::path &filename) const { // find last forward or backslash s32 lastSlash = filename.findLast('/'); @@ -573,10 +498,9 @@ io::path CFileSystem::getFileDir(const io::path& filename) const return _IRR_TEXT("."); } - //! returns the base part of a filename, i.e. all except for the directory //! part. If no directory path is prefixed, the full name is returned. -io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const +io::path CFileSystem::getFileBasename(const io::path &filename, bool keepExtension) const { // find last forward or backslash s32 lastSlash = filename.findLast('/'); @@ -585,28 +509,26 @@ io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtensi // get number of chars after last dot s32 end = 0; - if (!keepExtension) - { + if (!keepExtension) { // take care to search only after last slash to check only for // dots in the filename end = filename.findLast('.'); if (end == -1 || end < lastSlash) - end=0; + end = 0; else - end = filename.size()-end; + end = filename.size() - end; } if ((u32)lastSlash < filename.size()) - return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end); + return filename.subString(lastSlash + 1, filename.size() - lastSlash - 1 - end); else if (end != 0) - return filename.subString(0, filename.size()-end); + return filename.subString(0, filename.size() - end); else return filename; } - //! flatten a path and file name for example: "/you/me/../." becomes "/you" -io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const +io::path &CFileSystem::flattenFilename(io::path &directory, const io::path &root) const { directory.replace('\\', '/'); if (directory.lastChar() != '/') @@ -617,33 +539,24 @@ io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root s32 lastpos = 0; s32 pos = 0; - bool lastWasRealDir=false; + bool lastWasRealDir = false; - while ((pos = directory.findNext('/', lastpos)) >= 0) - { + while ((pos = directory.findNext('/', lastpos)) >= 0) { subdir = directory.subString(lastpos, pos - lastpos + 1); - if (subdir == _IRR_TEXT("../")) - { - if (lastWasRealDir) - { + if (subdir == _IRR_TEXT("../")) { + if (lastWasRealDir) { deletePathFromPath(dir, 2); - lastWasRealDir=(dir.size()!=0); - } - else - { + lastWasRealDir = (dir.size() != 0); + } else { dir.append(subdir); - lastWasRealDir=false; + lastWasRealDir = false; } - } - else if (subdir == _IRR_TEXT("/")) - { + } else if (subdir == _IRR_TEXT("/")) { dir = root; - } - else if (subdir != _IRR_TEXT("./")) - { + } else if (subdir != _IRR_TEXT("./")) { dir.append(subdir); - lastWasRealDir=true; + lastWasRealDir = true; } lastpos = pos + 1; @@ -652,11 +565,10 @@ io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root return directory; } - //! Get the relative filename, relative to the given directory -path CFileSystem::getRelativeFilename(const path& filename, const path& directory) const +path CFileSystem::getRelativeFilename(const path &filename, const path &directory) const { - if ( filename.empty() || directory.empty() ) + if (filename.empty() || directory.empty()) return filename; io::path path1, file, ext; @@ -665,59 +577,53 @@ path CFileSystem::getRelativeFilename(const path& filename, const path& director std::list list1, list2; path1.split(list1, _IRR_TEXT("/\\"), 2); path2.split(list2, _IRR_TEXT("/\\"), 2); - std::list::const_iterator it1,it2; - it1=list1.begin(); - it2=list2.begin(); + std::list::const_iterator it1, it2; + it1 = list1.begin(); + it2 = list2.begin(); - #if defined (_IRR_WINDOWS_API_) +#if defined(_IRR_WINDOWS_API_) fschar_t partition1 = 0, partition2 = 0; io::path prefix1, prefix2; - if ( it1 != list1.end() ) + if (it1 != list1.end()) prefix1 = *it1; - if ( it2 != list2.end() ) + if (it2 != list2.end()) prefix2 = *it2; - if ( prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':') ) + if (prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':')) partition1 = core::locale_lower(prefix1[0]); - if ( prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':') ) + if (prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':')) partition2 = core::locale_lower(prefix2[0]); // must have the same prefix or we can't resolve it to a relative filename - if ( partition1 != partition2 ) - { + if (partition1 != partition2) { return filename; } - #endif - +#endif for (; it1 != list1.end() && it2 != list2.end() -#if defined (_IRR_WINDOWS_API_) - && (io::path(*it1).make_lower()==io::path(*it2).make_lower()) +#if defined(_IRR_WINDOWS_API_) + && (io::path(*it1).make_lower() == io::path(*it2).make_lower()) #else - && (*it1==*it2) + && (*it1 == *it2) #endif - ;) - { + ;) { ++it1; ++it2; } - path1=_IRR_TEXT(""); + path1 = _IRR_TEXT(""); for (; it2 != list2.end(); ++it2) path1 += _IRR_TEXT("../"); - while (it1 != list1.end()) - { + while (it1 != list1.end()) { path1 += *it1++; path1 += _IRR_TEXT('/'); } path1 += file; - if (ext.size()) - { + if (ext.size()) { path1 += _IRR_TEXT('.'); path1 += ext; } return path1; } - //! Sets the current file systen type EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType) { @@ -726,87 +632,74 @@ EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType) return current; } - //! Creates a list of files and directories in the current working directory -IFileList* CFileSystem::createFileList() +IFileList *CFileSystem::createFileList() { - CFileList* r = 0; + CFileList *r = 0; io::path Path = getWorkingDirectory(); Path.replace('\\', '/'); if (!Path.empty() && Path.lastChar() != '/') Path.append('/'); //! Construct from native filesystem - if (FileSystemType == FILESYSTEM_NATIVE) - { - // -------------------------------------------- - //! Windows version - #ifdef _IRR_WINDOWS_API_ + if (FileSystemType == FILESYSTEM_NATIVE) { +// -------------------------------------------- +//! Windows version +#ifdef _IRR_WINDOWS_API_ r = new CFileList(Path, true, false); - // intptr_t is optional but supported by MinGW since 2007 or earlier. + // intptr_t is optional but supported by MinGW since 2007 or earlier. intptr_t hFile; struct _tfinddata_t c_file; - if( (hFile = _tfindfirst( _T("*"), &c_file )) != (intptr_t)(-1L) ) - { - do - { + if ((hFile = _tfindfirst(_T("*"), &c_file)) != (intptr_t)(-1L)) { + do { r->addItem(Path + c_file.name, 0, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0); - } - while( _tfindnext( hFile, &c_file ) == 0 ); + } while (_tfindnext(hFile, &c_file) == 0); - _findclose( hFile ); + _findclose(hFile); } - #endif - - // -------------------------------------------- - //! Linux version - #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) +#endif +// -------------------------------------------- +//! Linux version +#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) r = new CFileList(Path, false, false); r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0); //! We use the POSIX compliant methods instead of scandir - DIR* dirHandle=opendir(Path.c_str()); - if (dirHandle) - { + DIR *dirHandle = opendir(Path.c_str()); + if (dirHandle) { struct dirent *dirEntry; - while ((dirEntry=readdir(dirHandle))) - { + while ((dirEntry = readdir(dirHandle))) { u32 size = 0; bool isDirectory = false; - if((strcmp(dirEntry->d_name, ".")==0) || - (strcmp(dirEntry->d_name, "..")==0)) - { + if ((strcmp(dirEntry->d_name, ".") == 0) || + (strcmp(dirEntry->d_name, "..") == 0)) { continue; } struct stat buf; - if (stat(dirEntry->d_name, &buf)==0) - { + if (stat(dirEntry->d_name, &buf) == 0) { size = buf.st_size; isDirectory = S_ISDIR(buf.st_mode); } - #if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__) && !defined(__HAIKU__) +#if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__) && !defined(__HAIKU__) // only available on some systems - else - { + else { isDirectory = dirEntry->d_type == DT_DIR; } - #endif +#endif r->addItem(Path + dirEntry->d_name, 0, size, isDirectory, 0); } closedir(dirHandle); } - #endif - } - else - { +#endif + } else { //! create file list for the virtual filesystem r = new CFileList(Path, false, false); @@ -821,14 +714,11 @@ IFileList* CFileSystem::createFileList() r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0); //! merge archives - for (u32 i=0; i < FileArchives.size(); ++i) - { + for (u32 i = 0; i < FileArchives.size(); ++i) { const IFileList *merge = FileArchives[i]->getFileList(); - for (u32 j=0; j < merge->getFileCount(); ++j) - { - if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0) - { + for (u32 j = 0; j < merge->getFileCount(); ++j) { + if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0) { r->addItem(merge->getFullFileName(j), merge->getFileOffset(j), merge->getFileSize(j), merge->isDirectory(j), 0); } } @@ -841,36 +731,33 @@ IFileList* CFileSystem::createFileList() } //! Creates an empty filelist -IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) +IFileList *CFileSystem::createEmptyFileList(const io::path &path, bool ignoreCase, bool ignorePaths) { return new CFileList(path, ignoreCase, ignorePaths); } - //! determines if a file exists and would be able to be opened. -bool CFileSystem::existFile(const io::path& filename) const +bool CFileSystem::existFile(const io::path &filename) const { - for (u32 i=0; i < FileArchives.size(); ++i) - if (FileArchives[i]->getFileList()->findFile(filename)!=-1) + for (u32 i = 0; i < FileArchives.size(); ++i) + if (FileArchives[i]->getFileList()->findFile(filename) != -1) return true; #if defined(_MSC_VER) - return (_access(filename.c_str(), 0) != -1); + return (_access(filename.c_str(), 0) != -1); #elif defined(F_OK) - return (access(filename.c_str(), F_OK) != -1); + return (access(filename.c_str(), F_OK) != -1); #else return (access(filename.c_str(), 0) != -1); #endif } - //! creates a filesystem which is able to open files from the ordinary file system, //! and out of zipfiles, which are able to be added to the filesystem. -IFileSystem* createFileSystem() +IFileSystem *createFileSystem() { return new CFileSystem(); } - } // end namespace irr } // end namespace io diff --git a/source/Irrlicht/CFileSystem.h b/source/Irrlicht/CFileSystem.h index 0c911a48..18bc7ff3 100644 --- a/source/Irrlicht/CFileSystem.h +++ b/source/Irrlicht/CFileSystem.h @@ -12,7 +12,7 @@ namespace irr namespace io { - class CZipReader; +class CZipReader; /*! FileSystem which uses normal files and one zipfile @@ -20,7 +20,6 @@ namespace io class CFileSystem : public IFileSystem { public: - //! constructor CFileSystem(); @@ -28,114 +27,112 @@ public: virtual ~CFileSystem(); //! opens a file for read access - IReadFile* createAndOpenFile(const io::path& filename) override; + IReadFile *createAndOpenFile(const io::path &filename) override; //! Creates an IReadFile interface for accessing memory like a file. - IReadFile* createMemoryReadFile(const void* memory, s32 len, const io::path& fileName, bool deleteMemoryWhenDropped = false) override; + IReadFile *createMemoryReadFile(const void *memory, s32 len, const io::path &fileName, bool deleteMemoryWhenDropped = false) override; //! Creates an IReadFile interface for accessing files inside files - IReadFile* createLimitReadFile(const io::path& fileName, IReadFile* alreadyOpenedFile, long pos, long areaSize) override; + IReadFile *createLimitReadFile(const io::path &fileName, IReadFile *alreadyOpenedFile, long pos, long areaSize) override; //! Creates an IWriteFile interface for accessing memory like a file. - IWriteFile* createMemoryWriteFile(void* memory, s32 len, const io::path& fileName, bool deleteMemoryWhenDropped=false) override; + IWriteFile *createMemoryWriteFile(void *memory, s32 len, const io::path &fileName, bool deleteMemoryWhenDropped = false) override; //! Opens a file for write access. - IWriteFile* createAndWriteFile(const io::path& filename, bool append=false) override; + IWriteFile *createAndWriteFile(const io::path &filename, bool append = false) override; //! Adds an archive to the file system. - virtual bool addFileArchive(const io::path& filename, + virtual bool addFileArchive(const io::path &filename, bool ignoreCase = true, bool ignorePaths = true, E_FILE_ARCHIVE_TYPE archiveType = EFAT_UNKNOWN, - const core::stringc& password="", - IFileArchive** retArchive = 0) override; + const core::stringc &password = "", + IFileArchive **retArchive = 0) override; //! Adds an archive to the file system. - virtual bool addFileArchive(IReadFile* file, bool ignoreCase=true, - bool ignorePaths=true, - E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN, - const core::stringc& password="", - IFileArchive** retArchive = 0) override; + virtual bool addFileArchive(IReadFile *file, bool ignoreCase = true, + bool ignorePaths = true, + E_FILE_ARCHIVE_TYPE archiveType = EFAT_UNKNOWN, + const core::stringc &password = "", + IFileArchive **retArchive = 0) override; //! Adds an archive to the file system. - bool addFileArchive(IFileArchive* archive) override; + bool addFileArchive(IFileArchive *archive) override; //! move the hirarchy of the filesystem. moves sourceIndex relative up or down bool moveFileArchive(u32 sourceIndex, s32 relative) override; //! Adds an external archive loader to the engine. - void addArchiveLoader(IArchiveLoader* loader) override; + void addArchiveLoader(IArchiveLoader *loader) override; //! Returns the total number of archive loaders added. u32 getArchiveLoaderCount() const override; //! Gets the archive loader by index. - IArchiveLoader* getArchiveLoader(u32 index) const override; + IArchiveLoader *getArchiveLoader(u32 index) const override; //! gets the file archive count u32 getFileArchiveCount() const override; //! gets an archive - IFileArchive* getFileArchive(u32 index) override; + IFileArchive *getFileArchive(u32 index) override; //! removes an archive from the file system. bool removeFileArchive(u32 index) override; //! removes an archive from the file system. - bool removeFileArchive(const io::path& filename) override; + bool removeFileArchive(const io::path &filename) override; //! Removes an archive from the file system. - bool removeFileArchive(const IFileArchive* archive) override; + bool removeFileArchive(const IFileArchive *archive) override; //! Returns the string of the current working directory - const io::path& getWorkingDirectory() override; + const io::path &getWorkingDirectory() override; //! Changes the current Working Directory to the string given. //! The string is operating system dependent. Under Windows it will look //! like this: "drive:\directory\sudirectory\" - bool changeWorkingDirectoryTo(const io::path& newDirectory) override; + bool changeWorkingDirectoryTo(const io::path &newDirectory) override; //! Converts a relative path to an absolute (unique) path, resolving symbolic links - io::path getAbsolutePath(const io::path& filename) const override; + io::path getAbsolutePath(const io::path &filename) const override; //! Returns the directory a file is located in. /** \param filename: The file to get the directory from */ - io::path getFileDir(const io::path& filename) const override; + io::path getFileDir(const io::path &filename) const override; //! Returns the base part of a filename, i.e. the name without the directory //! part. If no directory is prefixed, the full name is returned. /** \param filename: The file to get the basename from */ - io::path getFileBasename(const io::path& filename, bool keepExtension=true) const override; + io::path getFileBasename(const io::path &filename, bool keepExtension = true) const override; //! flatten a path and file name for example: "/you/me/../." becomes "/you" - io::path& flattenFilename( io::path& directory, const io::path& root = "/" ) const override; + io::path &flattenFilename(io::path &directory, const io::path &root = "/") const override; //! Get the relative filename, relative to the given directory - path getRelativeFilename(const path& filename, const path& directory) const override; + path getRelativeFilename(const path &filename, const path &directory) const override; EFileSystemType setFileListSystem(EFileSystemType listType) override; //! Creates a list of files and directories in the current working directory //! and returns it. - IFileList* createFileList() override; + IFileList *createFileList() override; //! Creates an empty filelist - IFileList* createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) override; + IFileList *createEmptyFileList(const io::path &path, bool ignoreCase, bool ignorePaths) override; //! determines if a file exists and would be able to be opened. - bool existFile(const io::path& filename) const override; + bool existFile(const io::path &filename) const override; private: - //! Currently used FileSystemType EFileSystemType FileSystemType; //! WorkingDirectory for Native and Virtual filesystems - io::path WorkingDirectory [2]; + io::path WorkingDirectory[2]; //! currently attached ArchiveLoaders - core::array ArchiveLoader; + core::array ArchiveLoader; //! currently attached Archives - core::array FileArchives; + core::array FileArchives; }; - } // end namespace irr } // end namespace io diff --git a/source/Irrlicht/CGLXManager.cpp b/source/Irrlicht/CGLXManager.cpp index 553ffe8b..08083bc7 100644 --- a/source/Irrlicht/CGLXManager.cpp +++ b/source/Irrlicht/CGLXManager.cpp @@ -20,83 +20,89 @@ namespace irr namespace video { -CGLXManager::CGLXManager(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata, int screennr) - : Params(params), PrimaryContext(videodata), VisualInfo(0), glxFBConfig(0), GlxWin(0) +CGLXManager::CGLXManager(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &videodata, int screennr) : + Params(params), PrimaryContext(videodata), VisualInfo(0), glxFBConfig(0), GlxWin(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGLXManager"); - #endif +#endif - CurrentContext.OpenGLLinux.X11Display=PrimaryContext.OpenGLLinux.X11Display; + CurrentContext.OpenGLLinux.X11Display = PrimaryContext.OpenGLLinux.X11Display; int major, minor; - Display* display = (Display*)PrimaryContext.OpenGLLinux.X11Display; - const bool isAvailableGLX=glXQueryExtension(display,&major,&minor); + Display *display = (Display *)PrimaryContext.OpenGLLinux.X11Display; + const bool isAvailableGLX = glXQueryExtension(display, &major, &minor); - if (isAvailableGLX && glXQueryVersion(display, &major, &minor)) - { + if (isAvailableGLX && glXQueryVersion(display, &major, &minor)) { #if defined(GLX_VERSION_1_3) - typedef GLXFBConfig * ( * PFNGLXCHOOSEFBCONFIGPROC) (Display *dpy, int screen, const int *attrib_list, int *nelements); + typedef GLXFBConfig *(*PFNGLXCHOOSEFBCONFIGPROC)(Display *dpy, int screen, const int *attrib_list, int *nelements); - PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress(reinterpret_cast("glXChooseFBConfig")); - if (major==1 && minor>2 && glxChooseFBConfig) - { -os::Printer::log("GLX >= 1.3", ELL_DEBUG); + PFNGLXCHOOSEFBCONFIGPROC glxChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress(reinterpret_cast("glXChooseFBConfig")); + if (major == 1 && minor > 2 && glxChooseFBConfig) { + os::Printer::log("GLX >= 1.3", ELL_DEBUG); // attribute array for the draw buffer int visualAttrBuffer[] = { - GLX_RENDER_TYPE, GLX_RGBA_BIT, - GLX_RED_SIZE, 4, - GLX_GREEN_SIZE, 4, - GLX_BLUE_SIZE, 4, - GLX_ALPHA_SIZE, Params.WithAlphaChannel?1:0, - GLX_DEPTH_SIZE, Params.ZBufferBits, //10,11 - GLX_DOUBLEBUFFER, Params.Doublebuffer?True:False, - GLX_STENCIL_SIZE, Params.Stencilbuffer?1:0, + GLX_RENDER_TYPE, + GLX_RGBA_BIT, + GLX_RED_SIZE, + 4, + GLX_GREEN_SIZE, + 4, + GLX_BLUE_SIZE, + 4, + GLX_ALPHA_SIZE, + Params.WithAlphaChannel ? 1 : 0, + GLX_DEPTH_SIZE, + Params.ZBufferBits, // 10,11 + GLX_DOUBLEBUFFER, + Params.Doublebuffer ? True : False, + GLX_STENCIL_SIZE, + Params.Stencilbuffer ? 1 : 0, #if defined(GLX_VERSION_1_4) && defined(GLX_SAMPLE_BUFFERS) // we need to check the extension string! - GLX_SAMPLE_BUFFERS, 1, - GLX_SAMPLES, Params.AntiAlias, // 18,19 + GLX_SAMPLE_BUFFERS, + 1, + GLX_SAMPLES, + Params.AntiAlias, // 18,19 #elif defined(GLX_ARB_multisample) - GLX_SAMPLE_BUFFERS_ARB, 1, - GLX_SAMPLES_ARB, Params.AntiAlias, // 18,19 + GLX_SAMPLE_BUFFERS_ARB, + 1, + GLX_SAMPLES_ARB, + Params.AntiAlias, // 18,19 #elif defined(GLX_SGIS_multisample) - GLX_SAMPLE_BUFFERS_SGIS, 1, - GLX_SAMPLES_SGIS, Params.AntiAlias, // 18,19 + GLX_SAMPLE_BUFFERS_SGIS, + 1, + GLX_SAMPLES_SGIS, + Params.AntiAlias, // 18,19 #endif - GLX_STEREO, Params.Stereobuffer?True:False, + GLX_STEREO, + Params.Stereobuffer ? True : False, None }; - GLXFBConfig *configList=0; - int nitems=0; - if (Params.AntiAlias<2) - { + GLXFBConfig *configList = 0; + int nitems = 0; + if (Params.AntiAlias < 2) { visualAttrBuffer[17] = 0; visualAttrBuffer[19] = 0; } // first round with unchanged values { - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (!configList && Params.AntiAlias) - { - while (!configList && (visualAttrBuffer[19]>1)) - { + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (!configList && Params.AntiAlias) { + while (!configList && (visualAttrBuffer[19] > 1)) { visualAttrBuffer[19] -= 1; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); } - if (!configList) - { + if (!configList) { visualAttrBuffer[17] = 0; visualAttrBuffer[19] = 0; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (configList) - { + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); - Params.AntiAlias=0; - } - else - { - //reenable multisampling + Params.AntiAlias = 0; + } else { + // reenable multisampling visualAttrBuffer[17] = 1; visualAttrBuffer[19] = Params.AntiAlias; } @@ -107,34 +113,27 @@ os::Printer::log("GLX >= 1.3", ELL_DEBUG); // If the first round was with stencil flag it's now without // Other way round also makes sense because some configs // only have depth buffer combined with stencil buffer - if (!configList) - { + if (!configList) { if (Params.Stencilbuffer) os::Printer::log("No stencilbuffer available, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = !Params.Stencilbuffer; - visualAttrBuffer[15]=Params.Stencilbuffer?1:0; + visualAttrBuffer[15] = Params.Stencilbuffer ? 1 : 0; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (!configList && Params.AntiAlias) - { - while (!configList && (visualAttrBuffer[19]>1)) - { + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (!configList && Params.AntiAlias) { + while (!configList && (visualAttrBuffer[19] > 1)) { visualAttrBuffer[19] -= 1; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); } - if (!configList) - { + if (!configList) { visualAttrBuffer[17] = 0; visualAttrBuffer[19] = 0; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (configList) - { + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); - Params.AntiAlias=0; - } - else - { - //reenable multisampling + Params.AntiAlias = 0; + } else { + // reenable multisampling visualAttrBuffer[17] = 1; visualAttrBuffer[19] = Params.AntiAlias; } @@ -142,91 +141,78 @@ os::Printer::log("GLX >= 1.3", ELL_DEBUG); } } // Next try without double buffer - if (!configList && Params.Doublebuffer) - { + if (!configList && Params.Doublebuffer) { os::Printer::log("No doublebuffering available.", ELL_WARNING); - Params.Doublebuffer=false; + Params.Doublebuffer = false; visualAttrBuffer[13] = GLX_DONT_CARE; Params.Stencilbuffer = false; - visualAttrBuffer[15]=0; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (!configList && Params.AntiAlias) - { - while (!configList && (visualAttrBuffer[19]>1)) - { + visualAttrBuffer[15] = 0; + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (!configList && Params.AntiAlias) { + while (!configList && (visualAttrBuffer[19] > 1)) { visualAttrBuffer[19] -= 1; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); } - if (!configList) - { + if (!configList) { visualAttrBuffer[17] = 0; visualAttrBuffer[19] = 0; - configList=glxChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); - if (configList) - { + configList = glxChooseFBConfig(display, screennr, visualAttrBuffer, &nitems); + if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); - Params.AntiAlias=0; - } - else - { - //reenable multisampling + Params.AntiAlias = 0; + } else { + // reenable multisampling visualAttrBuffer[17] = 1; visualAttrBuffer[19] = Params.AntiAlias; } } } } - if (configList) - { - glxFBConfig=configList[0]; + if (configList) { + glxFBConfig = configList[0]; XFree(configList); - typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config); - PFNGLXGETVISUALFROMFBCONFIGPROC glxGetVisualFromFBConfig= (PFNGLXGETVISUALFROMFBCONFIGPROC)glXGetProcAddress(reinterpret_cast("glXGetVisualFromFBConfig")); + typedef XVisualInfo *(*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display *dpy, GLXFBConfig config); + PFNGLXGETVISUALFROMFBCONFIGPROC glxGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC)glXGetProcAddress(reinterpret_cast("glXGetVisualFromFBConfig")); if (glxGetVisualFromFBConfig) - VisualInfo = glxGetVisualFromFBConfig(display,(GLXFBConfig)glxFBConfig); + VisualInfo = glxGetVisualFromFBConfig(display, (GLXFBConfig)glxFBConfig); } - } - else + } else #endif { // attribute array for the draw buffer int visualAttrBuffer[] = - { - GLX_RGBA, GLX_USE_GL, - GLX_RED_SIZE, 4, - GLX_GREEN_SIZE, 4, - GLX_BLUE_SIZE, 4, - GLX_ALPHA_SIZE, Params.WithAlphaChannel?1:0, - GLX_DEPTH_SIZE, Params.ZBufferBits, - GLX_STENCIL_SIZE, Params.Stencilbuffer?1:0, // 12,13 - // The following attributes have no flags, but are - // either present or not. As a no-op we use - // GLX_USE_GL, which is silently ignored by glXChooseVisual - Params.Doublebuffer?GLX_DOUBLEBUFFER:GLX_USE_GL, // 14 - Params.Stereobuffer?GLX_STEREO:GLX_USE_GL, // 15 - None - }; + { + GLX_RGBA, GLX_USE_GL, + GLX_RED_SIZE, 4, + GLX_GREEN_SIZE, 4, + GLX_BLUE_SIZE, 4, + GLX_ALPHA_SIZE, Params.WithAlphaChannel ? 1 : 0, + GLX_DEPTH_SIZE, Params.ZBufferBits, + GLX_STENCIL_SIZE, Params.Stencilbuffer ? 1 : 0, // 12,13 + // The following attributes have no flags, but are + // either present or not. As a no-op we use + // GLX_USE_GL, which is silently ignored by glXChooseVisual + Params.Doublebuffer ? GLX_DOUBLEBUFFER : GLX_USE_GL, // 14 + Params.Stereobuffer ? GLX_STEREO : GLX_USE_GL, // 15 + None}; - VisualInfo=glXChooseVisual(display, screennr, visualAttrBuffer); - if (!VisualInfo) - { + VisualInfo = glXChooseVisual(display, screennr, visualAttrBuffer); + if (!VisualInfo) { if (Params.Stencilbuffer) os::Printer::log("No stencilbuffer available, disabling.", ELL_WARNING); Params.Stencilbuffer = !Params.Stencilbuffer; - visualAttrBuffer[13]=Params.Stencilbuffer?1:0; + visualAttrBuffer[13] = Params.Stencilbuffer ? 1 : 0; - VisualInfo=glXChooseVisual(display, screennr, visualAttrBuffer); - if (!VisualInfo && Params.Doublebuffer) - { + VisualInfo = glXChooseVisual(display, screennr, visualAttrBuffer); + if (!VisualInfo && Params.Doublebuffer) { os::Printer::log("No doublebuffering available.", ELL_WARNING); - Params.Doublebuffer=false; + Params.Doublebuffer = false; visualAttrBuffer[14] = GLX_USE_GL; - VisualInfo=glXChooseVisual(display, screennr, visualAttrBuffer); + VisualInfo = glXChooseVisual(display, screennr, visualAttrBuffer); } } } - } - else + } else os::Printer::log("No GLX support available. OpenGL driver will not work.", ELL_WARNING); } @@ -234,19 +220,18 @@ CGLXManager::~CGLXManager() { } -bool CGLXManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata) +bool CGLXManager::initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &videodata) { // store params - Params=params; + Params = params; // set display - CurrentContext.OpenGLLinux.X11Display=videodata.OpenGLLinux.X11Display; + CurrentContext.OpenGLLinux.X11Display = videodata.OpenGLLinux.X11Display; // now get new window - CurrentContext.OpenGLLinux.X11Window=videodata.OpenGLLinux.X11Window; - if (!PrimaryContext.OpenGLLinux.X11Window) - { - PrimaryContext.OpenGLLinux.X11Window=CurrentContext.OpenGLLinux.X11Window; + CurrentContext.OpenGLLinux.X11Window = videodata.OpenGLLinux.X11Window; + if (!PrimaryContext.OpenGLLinux.X11Window) { + PrimaryContext.OpenGLLinux.X11Window = CurrentContext.OpenGLLinux.X11Window; } return true; @@ -254,25 +239,21 @@ bool CGLXManager::initialize(const SIrrlichtCreationParameters& params, const SE void CGLXManager::terminate() { - memset((void*)&CurrentContext, 0, sizeof(CurrentContext)); + memset((void *)&CurrentContext, 0, sizeof(CurrentContext)); } bool CGLXManager::generateSurface() { - if (glxFBConfig) - { - GlxWin=glXCreateWindow((Display*)CurrentContext.OpenGLLinux.X11Display,(GLXFBConfig)glxFBConfig,CurrentContext.OpenGLLinux.X11Window,NULL); - if (!GlxWin) - { + if (glxFBConfig) { + GlxWin = glXCreateWindow((Display *)CurrentContext.OpenGLLinux.X11Display, (GLXFBConfig)glxFBConfig, CurrentContext.OpenGLLinux.X11Window, NULL); + if (!GlxWin) { os::Printer::log("Could not create GLX window.", ELL_WARNING); return false; } - CurrentContext.OpenGLLinux.GLXWindow=GlxWin; - } - else - { - CurrentContext.OpenGLLinux.GLXWindow=CurrentContext.OpenGLLinux.X11Window; + CurrentContext.OpenGLLinux.GLXWindow = GlxWin; + } else { + CurrentContext.OpenGLLinux.GLXWindow = CurrentContext.OpenGLLinux.X11Window; } return true; } @@ -280,7 +261,7 @@ bool CGLXManager::generateSurface() void CGLXManager::destroySurface() { if (GlxWin) - glXDestroyWindow((Display*)CurrentContext.OpenGLLinux.X11Display, GlxWin); + glXDestroyWindow((Display *)CurrentContext.OpenGLLinux.X11Display, GlxWin); } #if defined(GLX_ARB_create_context) @@ -297,25 +278,21 @@ bool CGLXManager::generateContext() { GLXContext context = 0; - if (glxFBConfig) - { - if (GlxWin) - { + if (glxFBConfig) { + if (GlxWin) { #if defined(GLX_ARB_create_context) - PFNGLXCREATECONTEXTATTRIBSARBPROC glxCreateContextAttribsARB=(PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress(reinterpret_cast("glXCreateContextAttribsARB")); + PFNGLXCREATECONTEXTATTRIBSARBPROC glxCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress(reinterpret_cast("glXCreateContextAttribsARB")); - if (glxCreateContextAttribsARB) - { + if (glxCreateContextAttribsARB) { os::Printer::log("GLX with GLX_ARB_create_context", ELL_DEBUG); int contextAttrBuffer[] = { - GLX_CONTEXT_MAJOR_VERSION_ARB, 3, - GLX_CONTEXT_MINOR_VERSION_ARB, 0, - // GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, - None - }; + GLX_CONTEXT_MAJOR_VERSION_ARB, 3, + GLX_CONTEXT_MINOR_VERSION_ARB, 0, + // GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, + None}; XErrorHandler old = XSetErrorHandler(IrrIgnoreError); - context = glxCreateContextAttribsARB((Display*)CurrentContext.OpenGLLinux.X11Display, (GLXFBConfig)glxFBConfig, NULL, True, contextAttrBuffer); + context = glxCreateContextAttribsARB((Display *)CurrentContext.OpenGLLinux.X11Display, (GLXFBConfig)glxFBConfig, NULL, True, contextAttrBuffer); XSetErrorHandler(old); // transparently fall back to legacy call } @@ -323,78 +300,59 @@ bool CGLXManager::generateContext() #endif { // create glx context - context = glXCreateNewContext((Display*)CurrentContext.OpenGLLinux.X11Display, (GLXFBConfig)glxFBConfig, GLX_RGBA_TYPE, NULL, True); - if (!context) - { + context = glXCreateNewContext((Display *)CurrentContext.OpenGLLinux.X11Display, (GLXFBConfig)glxFBConfig, GLX_RGBA_TYPE, NULL, True); + if (!context) { os::Printer::log("Could not create GLX rendering context.", ELL_WARNING); return false; } } - } - else - { + } else { os::Printer::log("GLX window was not properly created.", ELL_WARNING); return false; } - } - else - { - context = glXCreateContext((Display*)CurrentContext.OpenGLLinux.X11Display, VisualInfo, NULL, True); - if (!context) - { + } else { + context = glXCreateContext((Display *)CurrentContext.OpenGLLinux.X11Display, VisualInfo, NULL, True); + if (!context) { os::Printer::log("Could not create GLX rendering context.", ELL_WARNING); return false; } } - CurrentContext.OpenGLLinux.X11Context=context; + CurrentContext.OpenGLLinux.X11Context = context; return true; } -const SExposedVideoData& CGLXManager::getContext() const +const SExposedVideoData &CGLXManager::getContext() const { return CurrentContext; } -bool CGLXManager::activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) +bool CGLXManager::activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) { - //TODO: handle restorePrimaryOnZero + // TODO: handle restorePrimaryOnZero - if (videoData.OpenGLLinux.X11Window) - { - if (videoData.OpenGLLinux.X11Display && videoData.OpenGLLinux.X11Context) - { - if (!glXMakeCurrent((Display*)videoData.OpenGLLinux.X11Display, videoData.OpenGLLinux.GLXWindow, (GLXContext)videoData.OpenGLLinux.X11Context)) - { + if (videoData.OpenGLLinux.X11Window) { + if (videoData.OpenGLLinux.X11Display && videoData.OpenGLLinux.X11Context) { + if (!glXMakeCurrent((Display *)videoData.OpenGLLinux.X11Display, videoData.OpenGLLinux.GLXWindow, (GLXContext)videoData.OpenGLLinux.X11Context)) { os::Printer::log("Context activation failed."); return false; - } - else - { + } else { CurrentContext.OpenGLLinux.GLXWindow = videoData.OpenGLLinux.GLXWindow; CurrentContext.OpenGLLinux.X11Window = videoData.OpenGLLinux.X11Window; CurrentContext.OpenGLLinux.X11Display = videoData.OpenGLLinux.X11Display; } - } - else - { + } else { // in case we only got a window ID, try with the existing values for display and context - if (!glXMakeCurrent((Display*)PrimaryContext.OpenGLLinux.X11Display, videoData.OpenGLLinux.GLXWindow, (GLXContext)PrimaryContext.OpenGLLinux.X11Context)) - { + if (!glXMakeCurrent((Display *)PrimaryContext.OpenGLLinux.X11Display, videoData.OpenGLLinux.GLXWindow, (GLXContext)PrimaryContext.OpenGLLinux.X11Context)) { os::Printer::log("Context activation failed."); return false; - } - else - { + } else { CurrentContext.OpenGLLinux.GLXWindow = videoData.OpenGLLinux.GLXWindow; CurrentContext.OpenGLLinux.X11Window = videoData.OpenGLLinux.X11Window; CurrentContext.OpenGLLinux.X11Display = PrimaryContext.OpenGLLinux.X11Display; } } - } - else if (!restorePrimaryOnZero && !videoData.OpenGLLinux.X11Window && !videoData.OpenGLLinux.X11Display) - { - if (!glXMakeCurrent((Display*)PrimaryContext.OpenGLLinux.X11Display, None, NULL)) - { + } else if (!restorePrimaryOnZero && !videoData.OpenGLLinux.X11Window && !videoData.OpenGLLinux.X11Display) { + if (!glXMakeCurrent((Display *)PrimaryContext.OpenGLLinux.X11Display, None, NULL)) { os::Printer::log("Render Context reset failed."); return false; } @@ -402,15 +360,11 @@ bool CGLXManager::activateContext(const SExposedVideoData& videoData, bool resto CurrentContext.OpenGLLinux.X11Display = 0; } // set back to main context - else if (CurrentContext.OpenGLLinux.X11Display != PrimaryContext.OpenGLLinux.X11Display) - { - if (!glXMakeCurrent((Display*)PrimaryContext.OpenGLLinux.X11Display, PrimaryContext.OpenGLLinux.X11Window, (GLXContext)PrimaryContext.OpenGLLinux.X11Context)) - { + else if (CurrentContext.OpenGLLinux.X11Display != PrimaryContext.OpenGLLinux.X11Display) { + if (!glXMakeCurrent((Display *)PrimaryContext.OpenGLLinux.X11Display, PrimaryContext.OpenGLLinux.X11Window, (GLXContext)PrimaryContext.OpenGLLinux.X11Context)) { os::Printer::log("Context activation failed."); return false; - } - else - { + } else { CurrentContext = PrimaryContext; } } @@ -419,30 +373,26 @@ bool CGLXManager::activateContext(const SExposedVideoData& videoData, bool resto void CGLXManager::destroyContext() { - if (CurrentContext.OpenGLLinux.X11Context) - { - if (GlxWin) - { - if (!glXMakeContextCurrent((Display*)CurrentContext.OpenGLLinux.X11Display, None, None, NULL)) + if (CurrentContext.OpenGLLinux.X11Context) { + if (GlxWin) { + if (!glXMakeContextCurrent((Display *)CurrentContext.OpenGLLinux.X11Display, None, None, NULL)) + os::Printer::log("Could not release glx context.", ELL_WARNING); + } else { + if (!glXMakeCurrent((Display *)CurrentContext.OpenGLLinux.X11Display, None, NULL)) os::Printer::log("Could not release glx context.", ELL_WARNING); } - else - { - if (!glXMakeCurrent((Display*)CurrentContext.OpenGLLinux.X11Display, None, NULL)) - os::Printer::log("Could not release glx context.", ELL_WARNING); - } - glXDestroyContext((Display*)CurrentContext.OpenGLLinux.X11Display, (GLXContext)CurrentContext.OpenGLLinux.X11Context); + glXDestroyContext((Display *)CurrentContext.OpenGLLinux.X11Display, (GLXContext)CurrentContext.OpenGLLinux.X11Context); } } -void* CGLXManager::getProcAddress(const std::string &procName) +void *CGLXManager::getProcAddress(const std::string &procName) { - return (void*)glXGetProcAddressARB(reinterpret_cast(procName.c_str())); + return (void *)glXGetProcAddressARB(reinterpret_cast(procName.c_str())); } bool CGLXManager::swapBuffers() { - glXSwapBuffers((Display*)CurrentContext.OpenGLLinux.X11Display, CurrentContext.OpenGLLinux.GLXWindow); + glXSwapBuffers((Display *)CurrentContext.OpenGLLinux.X11Display, CurrentContext.OpenGLLinux.GLXWindow); return true; } @@ -450,4 +400,3 @@ bool CGLXManager::swapBuffers() } #endif - diff --git a/source/Irrlicht/CGLXManager.h b/source/Irrlicht/CGLXManager.h index ee55c902..e39a0767 100644 --- a/source/Irrlicht/CGLXManager.h +++ b/source/Irrlicht/CGLXManager.h @@ -20,56 +20,56 @@ namespace irr { namespace video { - // GLX manager. - class CGLXManager : public IContextManager - { - public: - //! Constructor. - CGLXManager(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata, int screennr); +// GLX manager. +class CGLXManager : public IContextManager +{ +public: + //! Constructor. + CGLXManager(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &videodata, int screennr); - //! Destructor - ~CGLXManager(); + //! Destructor + ~CGLXManager(); - // Initialize - bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) override; + // Initialize + bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) override; - // Terminate - void terminate() override; + // Terminate + void terminate() override; - // Create surface. - bool generateSurface() override; + // Create surface. + bool generateSurface() override; - // Destroy surface. - void destroySurface() override; + // Destroy surface. + void destroySurface() override; - // Create context. - bool generateContext() override; + // Create context. + bool generateContext() override; - // Destroy context. - void destroyContext() override; + // Destroy context. + void destroyContext() override; - //! Get current context - const SExposedVideoData& getContext() const override; + //! Get current context + const SExposedVideoData &getContext() const override; - //! Change render context, disable old and activate new defined by videoData - bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) override; + //! Change render context, disable old and activate new defined by videoData + bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) override; - // Get procedure address. - void* getProcAddress(const std::string &procName) override; + // Get procedure address. + void *getProcAddress(const std::string &procName) override; - // Swap buffers. - bool swapBuffers() override; + // Swap buffers. + bool swapBuffers() override; - XVisualInfo* getVisual() const {return VisualInfo;} // return XVisualInfo + XVisualInfo *getVisual() const { return VisualInfo; } // return XVisualInfo - private: - SIrrlichtCreationParameters Params; - SExposedVideoData PrimaryContext; - SExposedVideoData CurrentContext; - XVisualInfo* VisualInfo; - void* glxFBConfig; // GLXFBConfig - XID GlxWin; // GLXWindow - }; +private: + SIrrlichtCreationParameters Params; + SExposedVideoData PrimaryContext; + SExposedVideoData CurrentContext; + XVisualInfo *VisualInfo; + void *glxFBConfig; // GLXFBConfig + XID GlxWin; // GLXWindow +}; } } diff --git a/source/Irrlicht/CGUIButton.cpp b/source/Irrlicht/CGUIButton.cpp index 1959cef9..f023024f 100644 --- a/source/Irrlicht/CGUIButton.cpp +++ b/source/Irrlicht/CGUIButton.cpp @@ -16,19 +16,19 @@ namespace gui { //! constructor -CGUIButton::CGUIButton(IGUIEnvironment* environment, IGUIElement* parent, - s32 id, core::rect rectangle, bool noclip) -: IGUIButton(environment, parent, id, rectangle), - SpriteBank(0), OverrideFont(0), - OverrideColorEnabled(false), OverrideColor(video::SColor(101,255,255,255)), - ClickTime(0), HoverTime(0), FocusTime(0), - ClickShiftState(false), ClickControlState(false), - IsPushButton(false), Pressed(false), - UseAlphaChannel(false), DrawBorder(true), ScaleImage(false) +CGUIButton::CGUIButton(IGUIEnvironment *environment, IGUIElement *parent, + s32 id, core::rect rectangle, bool noclip) : + IGUIButton(environment, parent, id, rectangle), + SpriteBank(0), OverrideFont(0), + OverrideColorEnabled(false), OverrideColor(video::SColor(101, 255, 255, 255)), + ClickTime(0), HoverTime(0), FocusTime(0), + ClickShiftState(false), ClickControlState(false), + IsPushButton(false), Pressed(false), + UseAlphaChannel(false), DrawBorder(true), ScaleImage(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIButton"); - #endif +#endif setNotClipped(noclip); // This element can be tabbed. @@ -36,7 +36,6 @@ CGUIButton::CGUIButton(IGUIEnvironment* environment, IGUIElement* parent, setTabOrder(-1); } - //! destructor CGUIButton::~CGUIButton() { @@ -47,29 +46,25 @@ CGUIButton::~CGUIButton() SpriteBank->drop(); } - //! Sets if the images should be scaled to fit the button void CGUIButton::setScaleImage(bool scaleImage) { ScaleImage = scaleImage; } - //! Returns whether the button scale the used images bool CGUIButton::isScalingImage() const { return ScaleImage; } - //! Sets if the button should use the skin to draw its border void CGUIButton::setDrawBorder(bool border) { DrawBorder = border; } - -void CGUIButton::setSpriteBank(IGUISpriteBank* sprites) +void CGUIButton::setSpriteBank(IGUISpriteBank *sprites) { if (sprites) sprites->grab(); @@ -80,12 +75,11 @@ void CGUIButton::setSpriteBank(IGUISpriteBank* sprites) SpriteBank = sprites; } - void CGUIButton::setSprite(EGUI_BUTTON_STATE state, s32 index, video::SColor color, bool loop, bool scale) { - ButtonSprites[(u32)state].Index = index; - ButtonSprites[(u32)state].Color = color; - ButtonSprites[(u32)state].Loop = loop; + ButtonSprites[(u32)state].Index = index; + ButtonSprites[(u32)state].Color = color; + ButtonSprites[(u32)state].Loop = loop; ButtonSprites[(u32)state].Scale = scale; } @@ -114,17 +108,15 @@ bool CGUIButton::getSpriteScale(EGUI_BUTTON_STATE state) const } //! called if an event happened. -bool CGUIButton::OnEvent(const SEvent& event) +bool CGUIButton::OnEvent(const SEvent &event) { if (!isEnabled()) return IGUIElement::OnEvent(event); - switch(event.EventType) - { + switch (event.EventType) { case EET_KEY_INPUT_EVENT: if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) - { + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { if (!IsPushButton) setPressed(true); else @@ -132,21 +124,16 @@ bool CGUIButton::OnEvent(const SEvent& event) return true; } - if (Pressed && !IsPushButton && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) - { + if (Pressed && !IsPushButton && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) { setPressed(false); return true; - } - else - if (!event.KeyInput.PressedDown && Pressed && - (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) - { + } else if (!event.KeyInput.PressedDown && Pressed && + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { if (!IsPushButton) setPressed(false); - if (Parent) - { + if (Parent) { ClickShiftState = event.KeyInput.Shift; ClickControlState = event.KeyInput.Control; @@ -161,39 +148,28 @@ bool CGUIButton::OnEvent(const SEvent& event) } break; case EET_GUI_EVENT: - if (event.GUIEvent.Caller == this) - { - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) - { + if (event.GUIEvent.Caller == this) { + if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (!IsPushButton) setPressed(false); FocusTime = os::Timer::getTime(); - } - else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED) - { + } else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED) { FocusTime = os::Timer::getTime(); - } - else if (event.GUIEvent.EventType == EGET_ELEMENT_HOVERED || event.GUIEvent.EventType == EGET_ELEMENT_LEFT) - { + } else if (event.GUIEvent.EventType == EGET_ELEMENT_HOVERED || event.GUIEvent.EventType == EGET_ELEMENT_LEFT) { HoverTime = os::Timer::getTime(); } } break; case EET_MOUSE_INPUT_EVENT: - if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) - { + if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { if (!IsPushButton) setPressed(true); return true; - } - else - if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) - { + } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { bool wasPressed = Pressed; - if ( !AbsoluteClippingRect.isPointInside( core::position2d(event.MouseInput.X, event.MouseInput.Y ) ) ) - { + if (!AbsoluteClippingRect.isPointInside(core::position2d(event.MouseInput.X, event.MouseInput.Y))) { if (!IsPushButton) setPressed(false); return true; @@ -201,14 +177,12 @@ bool CGUIButton::OnEvent(const SEvent& event) if (!IsPushButton) setPressed(false); - else - { + else { setPressed(!Pressed); } if ((!IsPushButton && wasPressed && Parent) || - (IsPushButton && wasPressed != Pressed)) - { + (IsPushButton && wasPressed != Pressed)) { ClickShiftState = event.MouseInput.Shift; ClickControlState = event.MouseInput.Control; @@ -230,70 +204,58 @@ bool CGUIButton::OnEvent(const SEvent& event) return Parent ? Parent->OnEvent(event) : false; } - //! draws the element and its children void CGUIButton::draw() { if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); - video::IVideoDriver* driver = Environment->getVideoDriver(); + IGUISkin *skin = Environment->getSkin(); + video::IVideoDriver *driver = Environment->getVideoDriver(); - if (DrawBorder) - { - if (!Pressed) - { + if (DrawBorder) { + if (!Pressed) { skin->draw3DButtonPaneStandard(this, AbsoluteRect, &AbsoluteClippingRect); - } - else - { + } else { skin->draw3DButtonPanePressed(this, AbsoluteRect, &AbsoluteClippingRect); } } - const core::position2di buttonCenter(AbsoluteRect.getCenter()); EGUI_BUTTON_IMAGE_STATE imageState = getImageState(Pressed); - if ( ButtonImages[(u32)imageState].Texture ) - { + if (ButtonImages[(u32)imageState].Texture) { core::position2d pos(buttonCenter); core::rect sourceRect(ButtonImages[(u32)imageState].SourceRect); - if ( sourceRect.getWidth() == 0 && sourceRect.getHeight() == 0 ) - sourceRect = core::rect(core::position2di(0,0), ButtonImages[(u32)imageState].Texture->getOriginalSize()); + if (sourceRect.getWidth() == 0 && sourceRect.getHeight() == 0) + sourceRect = core::rect(core::position2di(0, 0), ButtonImages[(u32)imageState].Texture->getOriginalSize()); pos.X -= sourceRect.getWidth() / 2; pos.Y -= sourceRect.getHeight() / 2; - if ( Pressed ) - { + if (Pressed) { // Create a pressed-down effect by moving the image when it looks identical to the unpressed state image EGUI_BUTTON_IMAGE_STATE unpressedState = getImageState(false); - if ( unpressedState == imageState || ButtonImages[(u32)imageState] == ButtonImages[(u32)unpressedState] ) - { + if (unpressedState == imageState || ButtonImages[(u32)imageState] == ButtonImages[(u32)unpressedState]) { pos.X += skin->getSize(EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X); pos.Y += skin->getSize(EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y); } } driver->draw2DImage(ButtonImages[(u32)imageState].Texture, - ScaleImage? AbsoluteRect : core::rect(pos, sourceRect.getSize()), + ScaleImage ? AbsoluteRect : core::rect(pos, sourceRect.getSize()), sourceRect, &AbsoluteClippingRect, 0, UseAlphaChannel); } - if (SpriteBank) - { + if (SpriteBank) { core::position2di pos(buttonCenter); - if ( Pressed ) - { + if (Pressed) { pos.X += skin->getSize(EGDS_BUTTON_PRESSED_SPRITE_OFFSET_X); pos.Y += skin->getSize(EGDS_BUTTON_PRESSED_SPRITE_OFFSET_Y); } - if (isEnabled()) - { + if (isEnabled()) { // pressed / unpressed animation EGUI_BUTTON_STATE state = Pressed ? EGBS_BUTTON_DOWN : EGBS_BUTTON_UP; drawSprite(state, ClickTime, pos); @@ -305,52 +267,44 @@ void CGUIButton::draw() // mouse over / off animation state = Environment->getHovered() == this ? EGBS_BUTTON_MOUSE_OVER : EGBS_BUTTON_MOUSE_OFF; drawSprite(state, HoverTime, pos); - } - else - { + } else { // draw disabled drawSprite(EGBS_BUTTON_DISABLED, 0, pos); } } - if (Text.size()) - { - IGUIFont* font = getActiveFont(); + if (Text.size()) { + IGUIFont *font = getActiveFont(); core::rect rect = AbsoluteRect; - if (Pressed) - { + if (Pressed) { rect.UpperLeftCorner.X += skin->getSize(EGDS_BUTTON_PRESSED_TEXT_OFFSET_X); rect.UpperLeftCorner.Y += skin->getSize(EGDS_BUTTON_PRESSED_TEXT_OFFSET_Y); } if (font) font->draw(Text.c_str(), rect, - getActiveColor(), - true, true, &AbsoluteClippingRect); + getActiveColor(), + true, true, &AbsoluteClippingRect); } IGUIElement::draw(); } -void CGUIButton::drawSprite(EGUI_BUTTON_STATE state, u32 startTime, const core::position2di& center) +void CGUIButton::drawSprite(EGUI_BUTTON_STATE state, u32 startTime, const core::position2di ¢er) { u32 stateIdx = (u32)state; - if (ButtonSprites[stateIdx].Index != -1) - { - if ( ButtonSprites[stateIdx].Scale ) - { - const video::SColor colors[] = {ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color}; + if (ButtonSprites[stateIdx].Index != -1) { + if (ButtonSprites[stateIdx].Scale) { + const video::SColor colors[] = {ButtonSprites[stateIdx].Color, ButtonSprites[stateIdx].Color, ButtonSprites[stateIdx].Color, ButtonSprites[stateIdx].Color}; SpriteBank->draw2DSprite(ButtonSprites[stateIdx].Index, AbsoluteRect, &AbsoluteClippingRect, colors, - os::Timer::getTime()-startTime, ButtonSprites[stateIdx].Loop); - } - else - { + os::Timer::getTime() - startTime, ButtonSprites[stateIdx].Loop); + } else { SpriteBank->draw2DSprite(ButtonSprites[stateIdx].Index, center, - &AbsoluteClippingRect, ButtonSprites[stateIdx].Color, startTime, os::Timer::getTime(), - ButtonSprites[stateIdx].Loop, true); + &AbsoluteClippingRect, ButtonSprites[stateIdx].Color, startTime, os::Timer::getTime(), + ButtonSprites[stateIdx].Loop, true); } } } @@ -360,27 +314,24 @@ EGUI_BUTTON_IMAGE_STATE CGUIButton::getImageState(bool pressed) const // figure state we should have EGUI_BUTTON_IMAGE_STATE state = EGBIS_IMAGE_DISABLED; bool focused = Environment->hasFocus(this); - bool mouseOver = static_cast(Environment->getHovered()) == this; // (static cast for Borland) - if (isEnabled()) - { - if ( pressed ) - { - if ( focused && mouseOver ) + bool mouseOver = static_cast(Environment->getHovered()) == this; // (static cast for Borland) + if (isEnabled()) { + if (pressed) { + if (focused && mouseOver) state = EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER; - else if ( focused ) + else if (focused) state = EGBIS_IMAGE_DOWN_FOCUSED; - else if ( mouseOver ) + else if (mouseOver) state = EGBIS_IMAGE_DOWN_MOUSEOVER; else state = EGBIS_IMAGE_DOWN; - } - else // !pressed + } else // !pressed { - if ( focused && mouseOver ) + if (focused && mouseOver) state = EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER; - else if ( focused ) + else if (focused) state = EGBIS_IMAGE_UP_FOCUSED; - else if ( mouseOver ) + else if (mouseOver) state = EGBIS_IMAGE_UP_MOUSEOVER; else state = EGBIS_IMAGE_UP; @@ -388,33 +339,31 @@ EGUI_BUTTON_IMAGE_STATE CGUIButton::getImageState(bool pressed) const } // find a compatible state that has images - while ( state != EGBIS_IMAGE_UP && !ButtonImages[(u32)state].Texture ) - { - switch ( state ) - { - case EGBIS_IMAGE_UP_FOCUSED: - state = EGBIS_IMAGE_UP_MOUSEOVER; - break; - case EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER: - state = EGBIS_IMAGE_UP_FOCUSED; - break; - case EGBIS_IMAGE_DOWN_MOUSEOVER: + while (state != EGBIS_IMAGE_UP && !ButtonImages[(u32)state].Texture) { + switch (state) { + case EGBIS_IMAGE_UP_FOCUSED: + state = EGBIS_IMAGE_UP_MOUSEOVER; + break; + case EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER: + state = EGBIS_IMAGE_UP_FOCUSED; + break; + case EGBIS_IMAGE_DOWN_MOUSEOVER: + state = EGBIS_IMAGE_DOWN; + break; + case EGBIS_IMAGE_DOWN_FOCUSED: + state = EGBIS_IMAGE_DOWN_MOUSEOVER; + break; + case EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER: + state = EGBIS_IMAGE_DOWN_FOCUSED; + break; + case EGBIS_IMAGE_DISABLED: + if (pressed) state = EGBIS_IMAGE_DOWN; - break; - case EGBIS_IMAGE_DOWN_FOCUSED: - state = EGBIS_IMAGE_DOWN_MOUSEOVER; - break; - case EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER: - state = EGBIS_IMAGE_DOWN_FOCUSED; - break; - case EGBIS_IMAGE_DISABLED: - if ( pressed ) - state = EGBIS_IMAGE_DOWN; - else - state = EGBIS_IMAGE_UP; - break; - default: + else state = EGBIS_IMAGE_UP; + break; + default: + state = EGBIS_IMAGE_UP; } } @@ -422,7 +371,7 @@ EGUI_BUTTON_IMAGE_STATE CGUIButton::getImageState(bool pressed) const } //! sets another skin independent font. if this is set to zero, the button uses the font of the skin. -void CGUIButton::setOverrideFont(IGUIFont* font) +void CGUIButton::setOverrideFont(IGUIFont *font) { if (OverrideFont == font) return; @@ -437,17 +386,17 @@ void CGUIButton::setOverrideFont(IGUIFont* font) } //! Gets the override font (if any) -IGUIFont * CGUIButton::getOverrideFont() const +IGUIFont *CGUIButton::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont* CGUIButton::getActiveFont() const +IGUIFont *CGUIButton::getActiveFont() const { - if ( OverrideFont ) + if (OverrideFont) return OverrideFont; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (skin) return skin->getFont(EGDF_BUTTON); return 0; @@ -467,9 +416,9 @@ video::SColor CGUIButton::getOverrideColor() const irr::video::SColor CGUIButton::getActiveColor() const { - if ( OverrideColorEnabled ) + if (OverrideColorEnabled) return OverrideColor; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (skin) return OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT); return OverrideColor; @@ -485,16 +434,16 @@ bool CGUIButton::isOverrideColorEnabled() const return OverrideColorEnabled; } -void CGUIButton::setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture* image, const core::rect& sourceRect) +void CGUIButton::setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture *image, const core::rect &sourceRect) { - if ( state >= EGBIS_COUNT ) + if (state >= EGBIS_COUNT) return; - if ( image ) + if (image) image->grab(); u32 stateIdx = (u32)state; - if ( ButtonImages[stateIdx].Texture ) + if (ButtonImages[stateIdx].Texture) ButtonImages[stateIdx].Texture->drop(); ButtonImages[stateIdx].Texture = image; @@ -509,51 +458,43 @@ void CGUIButton::setIsPushButton(bool isPushButton) IsPushButton = isPushButton; } - //! Returns if the button is currently pressed bool CGUIButton::isPressed() const { return Pressed; } - //! Sets the pressed state of the button if this is a pushbutton void CGUIButton::setPressed(bool pressed) { - if (Pressed != pressed) - { + if (Pressed != pressed) { ClickTime = os::Timer::getTime(); Pressed = pressed; } } - //! Returns whether the button is a push button bool CGUIButton::isPushButton() const { return IsPushButton; } - //! Sets if the alpha channel should be used for drawing images on the button (default is false) void CGUIButton::setUseAlphaChannel(bool useAlphaChannel) { UseAlphaChannel = useAlphaChannel; } - //! Returns if the alpha channel should be used for drawing images on the button bool CGUIButton::isAlphaChannelUsed() const { return UseAlphaChannel; } - bool CGUIButton::isDrawingBorder() const { return DrawBorder; } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIButton.h b/source/Irrlicht/CGUIButton.h index 02fbd4b4..8ff36c9a 100644 --- a/source/Irrlicht/CGUIButton.h +++ b/source/Irrlicht/CGUIButton.h @@ -14,228 +14,228 @@ namespace irr namespace gui { - class CGUIButton : public IGUIButton +class CGUIButton : public IGUIButton +{ +public: + //! constructor + CGUIButton(IGUIEnvironment *environment, IGUIElement *parent, + s32 id, core::rect rectangle, bool noclip = false); + + //! destructor + virtual ~CGUIButton(); + + //! called if an event happened. + bool OnEvent(const SEvent &event) override; + + //! draws the element and its children + void draw() override; + + //! sets another skin independent font. if this is set to zero, the button uses the font of the skin. + void setOverrideFont(IGUIFont *font = 0) override; + + //! Gets the override font (if any) + IGUIFont *getOverrideFont() const override; + + //! Get the font which is used right now for drawing + IGUIFont *getActiveFont() const override; + + //! Sets another color for the button text. + void setOverrideColor(video::SColor color) override; + + //! Gets the override color + video::SColor getOverrideColor(void) const override; + + //! Gets the currently used text color + video::SColor getActiveColor() const override; + + //! Sets if the button text should use the override color or the color in the gui skin. + void enableOverrideColor(bool enable) override; + + //! Checks if an override color is enabled + bool isOverrideColorEnabled(void) const override; + + //! Sets an image which should be displayed on the button when it is in the given state. + void setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture *image = 0, const core::rect &sourceRect = core::rect(0, 0, 0, 0)) override; + + //! Sets an image which should be displayed on the button when it is in normal state. + void setImage(video::ITexture *image = 0) override { - public: + setImage(EGBIS_IMAGE_UP, image); + } - //! constructor - CGUIButton(IGUIEnvironment* environment, IGUIElement* parent, - s32 id, core::rect rectangle, bool noclip=false); + //! Sets an image which should be displayed on the button when it is in normal state. + void setImage(video::ITexture *image, const core::rect &pos) override + { + setImage(EGBIS_IMAGE_UP, image, pos); + } - //! destructor - virtual ~CGUIButton(); + //! Sets an image which should be displayed on the button when it is in pressed state. + void setPressedImage(video::ITexture *image = 0) override + { + setImage(EGBIS_IMAGE_DOWN, image); + } - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! Sets an image which should be displayed on the button when it is in pressed state. + void setPressedImage(video::ITexture *image, const core::rect &pos) override + { + setImage(EGBIS_IMAGE_DOWN, image, pos); + } - //! draws the element and its children - void draw() override; + //! Sets the sprite bank used by the button + void setSpriteBank(IGUISpriteBank *bank = 0) override; - //! sets another skin independent font. if this is set to zero, the button uses the font of the skin. - void setOverrideFont(IGUIFont* font=0) override; + //! Sets the animated sprite for a specific button state + /** \param index: Number of the sprite within the sprite bank, use -1 for no sprite + \param state: State of the button to set the sprite for + \param index: The sprite number from the current sprite bank + \param color: The color of the sprite + */ + virtual void setSprite(EGUI_BUTTON_STATE state, s32 index, + video::SColor color = video::SColor(255, 255, 255, 255), + bool loop = false, bool scale = false) override; - //! Gets the override font (if any) - IGUIFont* getOverrideFont() const override; + //! Get the sprite-index for the given state or -1 when no sprite is set + s32 getSpriteIndex(EGUI_BUTTON_STATE state) const override; - //! Get the font which is used right now for drawing - IGUIFont* getActiveFont() const override; + //! Get the sprite color for the given state. Color is only used when a sprite is set. + video::SColor getSpriteColor(EGUI_BUTTON_STATE state) const override; - //! Sets another color for the button text. - void setOverrideColor(video::SColor color) override; + //! Returns if the sprite in the given state does loop + bool getSpriteLoop(EGUI_BUTTON_STATE state) const override; - //! Gets the override color - video::SColor getOverrideColor(void) const override; + //! Returns if the sprite in the given state is scaled + bool getSpriteScale(EGUI_BUTTON_STATE state) const override; - //! Gets the currently used text color - video::SColor getActiveColor() const override; + //! Sets if the button should behave like a push button. Which means it + //! can be in two states: Normal or Pressed. With a click on the button, + //! the user can change the state of the button. + void setIsPushButton(bool isPushButton = true) override; - //! Sets if the button text should use the override color or the color in the gui skin. - void enableOverrideColor(bool enable) override; + //! Checks whether the button is a push button + bool isPushButton() const override; - //! Checks if an override color is enabled - bool isOverrideColorEnabled(void) const override; + //! Sets the pressed state of the button if this is a pushbutton + void setPressed(bool pressed = true) override; - //! Sets an image which should be displayed on the button when it is in the given state. - void setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture* image=0, const core::rect& sourceRect=core::rect(0,0,0,0)) override; + //! Returns if the button is currently pressed + bool isPressed() const override; - //! Sets an image which should be displayed on the button when it is in normal state. - void setImage(video::ITexture* image=0) override + //! Sets if the button should use the skin to draw its border + void setDrawBorder(bool border = true) override; + + //! Checks if the button face and border are being drawn + bool isDrawingBorder() const override; + + //! Sets if the alpha channel should be used for drawing images on the button (default is false) + void setUseAlphaChannel(bool useAlphaChannel = true) override; + + //! Checks if the alpha channel should be used for drawing images on the button + bool isAlphaChannelUsed() const override; + + //! Sets if the button should scale the button images to fit + void setScaleImage(bool scaleImage = true) override; + + //! Checks whether the button scales the used images + bool isScalingImage() const override; + + //! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event + bool getClickShiftState() const override + { + return ClickShiftState; + } + + //! Get if the control key was pressed in last EGET_BUTTON_CLICKED event + bool getClickControlState() const override + { + return ClickControlState; + } + +protected: + void drawSprite(EGUI_BUTTON_STATE state, u32 startTime, const core::position2di ¢er); + EGUI_BUTTON_IMAGE_STATE getImageState(bool pressed) const; + +private: + struct ButtonSprite + { + ButtonSprite() : + Index(-1), Loop(false), Scale(false) { - setImage(EGBIS_IMAGE_UP, image); } - //! Sets an image which should be displayed on the button when it is in normal state. - void setImage(video::ITexture* image, const core::rect& pos) override + bool operator==(const ButtonSprite &other) const { - setImage(EGBIS_IMAGE_UP, image, pos); + return Index == other.Index && Color == other.Color && Loop == other.Loop && Scale == other.Scale; } - //! Sets an image which should be displayed on the button when it is in pressed state. - void setPressedImage(video::ITexture* image=0) override - { - setImage(EGBIS_IMAGE_DOWN, image); - } - - //! Sets an image which should be displayed on the button when it is in pressed state. - void setPressedImage(video::ITexture* image, const core::rect& pos) override - { - setImage(EGBIS_IMAGE_DOWN, image, pos); - } - - //! Sets the sprite bank used by the button - void setSpriteBank(IGUISpriteBank* bank=0) override; - - //! Sets the animated sprite for a specific button state - /** \param index: Number of the sprite within the sprite bank, use -1 for no sprite - \param state: State of the button to set the sprite for - \param index: The sprite number from the current sprite bank - \param color: The color of the sprite - */ - virtual void setSprite(EGUI_BUTTON_STATE state, s32 index, - video::SColor color=video::SColor(255,255,255,255), - bool loop=false, bool scale=false) override; - - //! Get the sprite-index for the given state or -1 when no sprite is set - s32 getSpriteIndex(EGUI_BUTTON_STATE state) const override; - - //! Get the sprite color for the given state. Color is only used when a sprite is set. - video::SColor getSpriteColor(EGUI_BUTTON_STATE state) const override; - - //! Returns if the sprite in the given state does loop - bool getSpriteLoop(EGUI_BUTTON_STATE state) const override; - - //! Returns if the sprite in the given state is scaled - bool getSpriteScale(EGUI_BUTTON_STATE state) const override; - - //! Sets if the button should behave like a push button. Which means it - //! can be in two states: Normal or Pressed. With a click on the button, - //! the user can change the state of the button. - void setIsPushButton(bool isPushButton=true) override; - - //! Checks whether the button is a push button - bool isPushButton() const override; - - //! Sets the pressed state of the button if this is a pushbutton - void setPressed(bool pressed=true) override; - - //! Returns if the button is currently pressed - bool isPressed() const override; - - //! Sets if the button should use the skin to draw its border - void setDrawBorder(bool border=true) override; - - //! Checks if the button face and border are being drawn - bool isDrawingBorder() const override; - - //! Sets if the alpha channel should be used for drawing images on the button (default is false) - void setUseAlphaChannel(bool useAlphaChannel=true) override; - - //! Checks if the alpha channel should be used for drawing images on the button - bool isAlphaChannelUsed() const override; - - //! Sets if the button should scale the button images to fit - void setScaleImage(bool scaleImage=true) override; - - //! Checks whether the button scales the used images - bool isScalingImage() const override; - - //! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event - bool getClickShiftState() const override - { - return ClickShiftState; - } - - //! Get if the control key was pressed in last EGET_BUTTON_CLICKED event - bool getClickControlState() const override - { - return ClickControlState; - } - - protected: - void drawSprite(EGUI_BUTTON_STATE state, u32 startTime, const core::position2di& center); - EGUI_BUTTON_IMAGE_STATE getImageState(bool pressed) const; - - private: - - struct ButtonSprite - { - ButtonSprite() : Index(-1), Loop(false), Scale(false) - { - } - - bool operator==(const ButtonSprite& other) const - { - return Index == other.Index && Color == other.Color && Loop == other.Loop && Scale == other.Scale; - } - - s32 Index; - video::SColor Color; - bool Loop; - bool Scale; - }; - - ButtonSprite ButtonSprites[EGBS_COUNT]; - IGUISpriteBank* SpriteBank; - - struct ButtonImage - { - ButtonImage() : Texture(0), SourceRect(core::rect(0,0,0,0)) - { - } - - ButtonImage(const ButtonImage& other) : Texture(0), SourceRect(core::rect(0,0,0,0)) - { - *this = other; - } - - ~ButtonImage() - { - if ( Texture ) - Texture->drop(); - } - - ButtonImage& operator=(const ButtonImage& other) - { - if ( this == &other ) - return *this; - - if (other.Texture) - other.Texture->grab(); - if ( Texture ) - Texture->drop(); - Texture = other.Texture; - SourceRect = other.SourceRect; - return *this; - } - - bool operator==(const ButtonImage& other) const - { - return Texture == other.Texture && SourceRect == other.SourceRect; - } - - - video::ITexture* Texture; - core::rect SourceRect; - }; - - ButtonImage ButtonImages[EGBIS_COUNT]; - - IGUIFont* OverrideFont; - - bool OverrideColorEnabled; - video::SColor OverrideColor; - - u32 ClickTime, HoverTime, FocusTime; - - bool ClickShiftState; - bool ClickControlState; - - bool IsPushButton; - bool Pressed; - bool UseAlphaChannel; - bool DrawBorder; - bool ScaleImage; + s32 Index; + video::SColor Color; + bool Loop; + bool Scale; }; + ButtonSprite ButtonSprites[EGBS_COUNT]; + IGUISpriteBank *SpriteBank; + + struct ButtonImage + { + ButtonImage() : + Texture(0), SourceRect(core::rect(0, 0, 0, 0)) + { + } + + ButtonImage(const ButtonImage &other) : + Texture(0), SourceRect(core::rect(0, 0, 0, 0)) + { + *this = other; + } + + ~ButtonImage() + { + if (Texture) + Texture->drop(); + } + + ButtonImage &operator=(const ButtonImage &other) + { + if (this == &other) + return *this; + + if (other.Texture) + other.Texture->grab(); + if (Texture) + Texture->drop(); + Texture = other.Texture; + SourceRect = other.SourceRect; + return *this; + } + + bool operator==(const ButtonImage &other) const + { + return Texture == other.Texture && SourceRect == other.SourceRect; + } + + video::ITexture *Texture; + core::rect SourceRect; + }; + + ButtonImage ButtonImages[EGBIS_COUNT]; + + IGUIFont *OverrideFont; + + bool OverrideColorEnabled; + video::SColor OverrideColor; + + u32 ClickTime, HoverTime, FocusTime; + + bool ClickShiftState; + bool ClickControlState; + + bool IsPushButton; + bool Pressed; + bool UseAlphaChannel; + bool DrawBorder; + bool ScaleImage; +}; + } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUICheckBox.cpp b/source/Irrlicht/CGUICheckBox.cpp index a7cd9d74..18dd6856 100644 --- a/source/Irrlicht/CGUICheckBox.cpp +++ b/source/Irrlicht/CGUICheckBox.cpp @@ -16,47 +16,35 @@ namespace gui { //! constructor -CGUICheckBox::CGUICheckBox(bool checked, IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) -: IGUICheckBox(environment, parent, id, rectangle), CheckTime(0), Pressed(false), Checked(checked) -, Border(false), Background(false) +CGUICheckBox::CGUICheckBox(bool checked, IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUICheckBox(environment, parent, id, rectangle), CheckTime(0), Pressed(false), Checked(checked), Border(false), Background(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUICheckBox"); - #endif +#endif // this element can be tabbed into setTabStop(true); setTabOrder(-1); } - //! called if an event happened. -bool CGUICheckBox::OnEvent(const SEvent& event) +bool CGUICheckBox::OnEvent(const SEvent &event) { - if (isEnabled()) - { - switch(event.EventType) - { + if (isEnabled()) { + switch (event.EventType) { case EET_KEY_INPUT_EVENT: if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) - { + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { Pressed = true; return true; - } - else - if (Pressed && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) - { + } else if (Pressed && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) { Pressed = false; return true; - } - else - if (!event.KeyInput.PressedDown && Pressed && - (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) - { + } else if (!event.KeyInput.PressedDown && Pressed && + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { Pressed = false; - if (Parent) - { + if (Parent) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; @@ -69,29 +57,22 @@ bool CGUICheckBox::OnEvent(const SEvent& event) } break; case EET_GUI_EVENT: - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) - { + if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == this) Pressed = false; } break; case EET_MOUSE_INPUT_EVENT: - if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) - { + if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { Pressed = true; CheckTime = os::Timer::getTime(); return true; - } - else - if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) - { + } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { bool wasPressed = Pressed; Pressed = false; - if (wasPressed && Parent) - { - if ( !AbsoluteClippingRect.isPointInside( core::position2d(event.MouseInput.X, event.MouseInput.Y) ) ) - { + if (wasPressed && Parent) { + if (!AbsoluteClippingRect.isPointInside(core::position2d(event.MouseInput.X, event.MouseInput.Y))) { Pressed = false; return true; } @@ -116,29 +97,25 @@ bool CGUICheckBox::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - //! draws the element and its children void CGUICheckBox::draw() { if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); - if (skin) - { - video::IVideoDriver* driver = Environment->getVideoDriver(); + IGUISkin *skin = Environment->getSkin(); + if (skin) { + video::IVideoDriver *driver = Environment->getVideoDriver(); core::rect frameRect(AbsoluteRect); // draw background - if (Background) - { + if (Background) { video::SColor bgColor = skin->getColor(gui::EGDC_3D_FACE); driver->draw2DRectangle(bgColor, frameRect, &AbsoluteClippingRect); } // draw the border - if (Border) - { + if (Border) { skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); frameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X); @@ -148,34 +125,31 @@ void CGUICheckBox::draw() // the rectangle around the "checked" area. core::rect checkRect(frameRect.UpperLeftCorner.X, - ((frameRect.getHeight() - height) / 2) + frameRect.UpperLeftCorner.Y, - 0, 0); + ((frameRect.getHeight() - height) / 2) + frameRect.UpperLeftCorner.Y, + 0, 0); checkRect.LowerRightCorner.X = checkRect.UpperLeftCorner.X + height; checkRect.LowerRightCorner.Y = checkRect.UpperLeftCorner.Y + height; EGUI_DEFAULT_COLOR col = EGDC_GRAY_EDITABLE; - if ( isEnabled() ) + if (isEnabled()) col = Pressed ? EGDC_FOCUSED_EDITABLE : EGDC_EDITABLE; skin->draw3DSunkenPane(this, skin->getColor(col), - false, true, checkRect, &AbsoluteClippingRect); + false, true, checkRect, &AbsoluteClippingRect); // the checked icon - if (Checked) - { + if (Checked) { skin->drawIcon(this, EGDI_CHECK_BOX_CHECKED, checkRect.getCenter(), - CheckTime, os::Timer::getTime(), false, &AbsoluteClippingRect); + CheckTime, os::Timer::getTime(), false, &AbsoluteClippingRect); } // associated text - if (Text.size()) - { + if (Text.size()) { checkRect = frameRect; checkRect.UpperLeftCorner.X += height + 5; - IGUIFont* font = skin->getFont(); - if (font) - { + IGUIFont *font = skin->getFont(); + if (font) { font->draw(Text.c_str(), checkRect, skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), false, true, &AbsoluteClippingRect); } @@ -184,14 +158,12 @@ void CGUICheckBox::draw() IGUIElement::draw(); } - //! set if box is checked void CGUICheckBox::setChecked(bool checked) { Checked = checked; } - //! returns if box is checked bool CGUICheckBox::isChecked() const { @@ -222,6 +194,5 @@ bool CGUICheckBox::isDrawBorderEnabled() const return Border; } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUICheckBox.h b/source/Irrlicht/CGUICheckBox.h index 88ac76ca..2c2a98f0 100644 --- a/source/Irrlicht/CGUICheckBox.h +++ b/source/Irrlicht/CGUICheckBox.h @@ -11,47 +11,45 @@ namespace irr namespace gui { - class CGUICheckBox : public IGUICheckBox - { - public: +class CGUICheckBox : public IGUICheckBox +{ +public: + //! constructor + CGUICheckBox(bool checked, IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle); - //! constructor - CGUICheckBox(bool checked, IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle); + //! set if box is checked + void setChecked(bool checked) override; - //! set if box is checked - void setChecked(bool checked) override; + //! returns if box is checked + bool isChecked() const override; - //! returns if box is checked - bool isChecked() const override; + //! Sets whether to draw the background + void setDrawBackground(bool draw) override; - //! Sets whether to draw the background - void setDrawBackground(bool draw) override; + //! Checks if background drawing is enabled + /** \return true if background drawing is enabled, false otherwise */ + bool isDrawBackgroundEnabled() const override; - //! Checks if background drawing is enabled - /** \return true if background drawing is enabled, false otherwise */ - bool isDrawBackgroundEnabled() const override; + //! Sets whether to draw the border + void setDrawBorder(bool draw) override; - //! Sets whether to draw the border - void setDrawBorder(bool draw) override; + //! Checks if border drawing is enabled + /** \return true if border drawing is enabled, false otherwise */ + bool isDrawBorderEnabled() const override; - //! Checks if border drawing is enabled - /** \return true if border drawing is enabled, false otherwise */ - bool isDrawBorderEnabled() const override; + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! draws the element and its children + void draw() override; - //! draws the element and its children - void draw() override; - - private: - - u32 CheckTime; - bool Pressed; - bool Checked; - bool Border; - bool Background; - }; +private: + u32 CheckTime; + bool Pressed; + bool Checked; + bool Border; + bool Background; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIComboBox.cpp b/source/Irrlicht/CGUIComboBox.cpp index 0e68263a..0088641b 100644 --- a/source/Irrlicht/CGUIComboBox.cpp +++ b/source/Irrlicht/CGUIComboBox.cpp @@ -19,22 +19,21 @@ namespace gui { //! constructor -CGUIComboBox::CGUIComboBox(IGUIEnvironment* environment, IGUIElement* parent, - s32 id, core::rect rectangle) - : IGUIComboBox(environment, parent, id, rectangle), - ListButton(nullptr), SelectedText(nullptr), ListBox(nullptr), LastFocus(nullptr), - Selected(-1), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_CENTER), MaxSelectionRows(5), HasFocus(false), - ActiveFont(nullptr) +CGUIComboBox::CGUIComboBox(IGUIEnvironment *environment, IGUIElement *parent, + s32 id, core::rect rectangle) : + IGUIComboBox(environment, parent, id, rectangle), + ListButton(nullptr), SelectedText(nullptr), ListBox(nullptr), LastFocus(nullptr), + Selected(-1), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_CENTER), MaxSelectionRows(5), HasFocus(false), + ActiveFont(nullptr) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIComboBox"); - #endif +#endif - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); - ListButton = Environment->addButton(core::recti(0,0,1,1), this, -1, L""); - if (skin && skin->getSpriteBank()) - { + ListButton = Environment->addButton(core::recti(0, 0, 1, 1), this, -1, L""); + if (skin && skin->getSpriteBank()) { ListButton->setSpriteBank(skin->getSpriteBank()); ListButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_DOWN), skin->getColor(EGDC_WINDOW_SYMBOL)); ListButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_DOWN), skin->getColor(EGDC_WINDOW_SYMBOL)); @@ -43,7 +42,7 @@ CGUIComboBox::CGUIComboBox(IGUIEnvironment* environment, IGUIElement* parent, ListButton->setSubElement(true); ListButton->setTabStop(false); - SelectedText = Environment->addStaticText(L"", core::recti(0,0,1,1), false, false, this, -1, false); + SelectedText = Environment->addStaticText(L"", core::recti(0, 0, 1, 1), false, false, this, -1, false); SelectedText->setSubElement(true); SelectedText->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); SelectedText->setTextAlignment(EGUIA_UPPERLEFT, EGUIA_CENTER); @@ -58,7 +57,6 @@ CGUIComboBox::CGUIComboBox(IGUIEnvironment* environment, IGUIElement* parent, setTabOrder(-1); } - void CGUIComboBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { HAlign = horizontal; @@ -66,15 +64,13 @@ void CGUIComboBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT ve SelectedText->setTextAlignment(horizontal, vertical); } - //! Set the maximal number of rows for the selection listbox void CGUIComboBox::setMaxSelectionRows(u32 max) { MaxSelectionRows = max; // force recalculation of open listbox - if (ListBox) - { + if (ListBox) { openCloseMenu(); openCloseMenu(); } @@ -86,16 +82,14 @@ u32 CGUIComboBox::getMaxSelectionRows() const return MaxSelectionRows; } - //! Returns amount of items in box u32 CGUIComboBox::getItemCount() const { return Items.size(); } - //! returns string of an item. the idx may be a value from 0 to itemCount-1 -const wchar_t* CGUIComboBox::getItem(u32 idx) const +const wchar_t *CGUIComboBox::getItem(u32 idx) const { if (idx >= Items.size()) return 0; @@ -113,17 +107,15 @@ u32 CGUIComboBox::getItemData(u32 idx) const } //! Returns index based on item data -s32 CGUIComboBox::getIndexForItemData(u32 data ) const +s32 CGUIComboBox::getIndexForItemData(u32 data) const { - for ( u32 i = 0; i < Items.size (); ++i ) - { - if ( Items[i].Data == data ) + for (u32 i = 0; i < Items.size(); ++i) { + if (Items[i].Data == data) return i; } return -1; } - //! Removes an item from the combo box. void CGUIComboBox::removeItem(u32 idx) { @@ -136,18 +128,16 @@ void CGUIComboBox::removeItem(u32 idx) Items.erase(idx); } - //! Returns caption of this element. -const wchar_t* CGUIComboBox::getText() const +const wchar_t *CGUIComboBox::getText() const { return getItem(Selected); } - //! adds an item and returns the index of it -u32 CGUIComboBox::addItem(const wchar_t* text, u32 data) +u32 CGUIComboBox::addItem(const wchar_t *text, u32 data) { - Items.push_back( SComboData ( text, data ) ); + Items.push_back(SComboData(text, data)); if (Selected == -1) setSelected(0); @@ -155,7 +145,6 @@ u32 CGUIComboBox::addItem(const wchar_t* text, u32 data) return Items.size() - 1; } - //! deletes all items in the combo box void CGUIComboBox::clear() { @@ -163,14 +152,12 @@ void CGUIComboBox::clear() setSelected(-1); } - //! returns id of selected item. returns -1 if no item is selected. s32 CGUIComboBox::getSelected() const { return Selected; } - //! sets the selected item. Set this to -1 if no item should be selected void CGUIComboBox::setSelected(s32 idx) { @@ -184,7 +171,6 @@ void CGUIComboBox::setSelected(s32 idx) SelectedText->setText(Items[Selected].Name.c_str()); } - //! Sets the selected item and emits a change event. /** Set this to -1 if no item should be selected */ void CGUIComboBox::setAndSendSelected(s32 idx) @@ -193,67 +179,54 @@ void CGUIComboBox::setAndSendSelected(s32 idx) sendSelectionChangedEvent(); } - //! called if an event happened. -bool CGUIComboBox::OnEvent(const SEvent& event) +bool CGUIComboBox::OnEvent(const SEvent &event) { - if (isEnabled()) - { - switch(event.EventType) - { + if (isEnabled()) { + switch (event.EventType) { case EET_KEY_INPUT_EVENT: - if (ListBox && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) - { + if (ListBox && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) { // hide list box openCloseMenu(); return true; - } - else - if (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE) - { - if (!event.KeyInput.PressedDown) - { + } else if (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE) { + if (!event.KeyInput.PressedDown) { openCloseMenu(); } ListButton->setPressed(ListBox == nullptr); return true; - } - else - if (event.KeyInput.PressedDown) - { + } else if (event.KeyInput.PressedDown) { s32 oldSelected = Selected; bool absorb = true; - switch (event.KeyInput.Key) - { - case KEY_DOWN: - setSelected(Selected+1); - break; - case KEY_UP: - setSelected(Selected-1); - break; - case KEY_HOME: - case KEY_PRIOR: - setSelected(0); - break; - case KEY_END: - case KEY_NEXT: - setSelected((s32)Items.size()-1); - break; - default: - absorb = false; + switch (event.KeyInput.Key) { + case KEY_DOWN: + setSelected(Selected + 1); + break; + case KEY_UP: + setSelected(Selected - 1); + break; + case KEY_HOME: + case KEY_PRIOR: + setSelected(0); + break; + case KEY_END: + case KEY_NEXT: + setSelected((s32)Items.size() - 1); + break; + default: + absorb = false; } - if (Selected <0) + if (Selected < 0) setSelected(0); if (Selected >= (s32)Items.size()) - setSelected((s32)Items.size() -1); + setSelected((s32)Items.size() - 1); - if (Selected != oldSelected) - { + if (Selected != oldSelected) { sendSelectionChangedEvent(); return true; } @@ -265,31 +238,27 @@ bool CGUIComboBox::OnEvent(const SEvent& event) case EET_GUI_EVENT: - switch(event.GUIEvent.EventType) - { + switch (event.GUIEvent.EventType) { case EGET_ELEMENT_FOCUS_LOST: if (ListBox && - (Environment->hasFocus(ListBox) || ListBox->isMyChild(event.GUIEvent.Caller) ) && - event.GUIEvent.Element != this && - !isMyChild(event.GUIEvent.Element) && - !ListBox->isMyChild(event.GUIEvent.Element)) - { + (Environment->hasFocus(ListBox) || ListBox->isMyChild(event.GUIEvent.Caller)) && + event.GUIEvent.Element != this && + !isMyChild(event.GUIEvent.Element) && + !ListBox->isMyChild(event.GUIEvent.Element)) { openCloseMenu(); } break; case EGET_BUTTON_CLICKED: - if (event.GUIEvent.Caller == ListButton) - { + if (event.GUIEvent.Caller == ListButton) { openCloseMenu(); return true; } break; case EGET_LISTBOX_SELECTED_AGAIN: case EGET_LISTBOX_CHANGED: - if (event.GUIEvent.Caller == ListBox) - { + if (event.GUIEvent.Caller == ListBox) { setSelected(ListBox->getSelected()); - if (Selected <0 || Selected >= (s32)Items.size()) + if (Selected < 0 || Selected >= (s32)Items.size()) setSelected(-1); openCloseMenu(); @@ -302,53 +271,48 @@ bool CGUIComboBox::OnEvent(const SEvent& event) break; case EET_MOUSE_INPUT_EVENT: - switch(event.MouseInput.Event) - { - case EMIE_LMOUSE_PRESSED_DOWN: - { - core::position2d p(event.MouseInput.X, event.MouseInput.Y); - - // send to list box - if (ListBox && ListBox->isPointInside(p) && ListBox->OnEvent(event)) - return true; + switch (event.MouseInput.Event) { + case EMIE_LMOUSE_PRESSED_DOWN: { + core::position2d p(event.MouseInput.X, event.MouseInput.Y); + // send to list box + if (ListBox && ListBox->isPointInside(p) && ListBox->OnEvent(event)) return true; - } - case EMIE_LMOUSE_LEFT_UP: - { - core::position2d p(event.MouseInput.X, event.MouseInput.Y); - // send to list box - if (!(ListBox && + return true; + } + case EMIE_LMOUSE_LEFT_UP: { + core::position2d p(event.MouseInput.X, event.MouseInput.Y); + + // send to list box + if (!(ListBox && ListBox->getAbsolutePosition().isPointInside(p) && - ListBox->OnEvent(event))) - { - openCloseMenu(); - } + ListBox->OnEvent(event))) { + openCloseMenu(); + } + return true; + } + case EMIE_MOUSE_WHEEL: { + // Try scrolling parent first + if (IGUIElement::OnEvent(event)) + return true; + + s32 oldSelected = Selected; + setSelected(Selected + ((event.MouseInput.Wheel < 0) ? 1 : -1)); + + if (Selected < 0) + setSelected(0); + + if (Selected >= (s32)Items.size()) + setSelected((s32)Items.size() - 1); + + if (Selected != oldSelected) { + sendSelectionChangedEvent(); return true; } - case EMIE_MOUSE_WHEEL: - { - // Try scrolling parent first - if (IGUIElement::OnEvent(event)) - return true; - s32 oldSelected = Selected; - setSelected( Selected + ((event.MouseInput.Wheel < 0) ? 1 : -1)); - - if (Selected <0) - setSelected(0); - - if (Selected >= (s32)Items.size()) - setSelected((s32)Items.size() -1); - - if (Selected != oldSelected) { - sendSelectionChangedEvent(); - return true; - } - - return false; - } + return false; + } default: break; } @@ -361,11 +325,9 @@ bool CGUIComboBox::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - void CGUIComboBox::sendSelectionChangedEvent() { - if (Parent) - { + if (Parent) { SEvent event; event.EventType = EET_GUI_EVENT; @@ -378,8 +340,7 @@ void CGUIComboBox::sendSelectionChangedEvent() void CGUIComboBox::updateListButtonWidth(s32 width) { - if (ListButton->getRelativePosition().getWidth() != width) - { + if (ListButton->getRelativePosition().getWidth() != width) { core::rect r; r.UpperLeftCorner.X = RelativeRect.getWidth() - width - 2; r.LowerRightCorner.X = RelativeRect.getWidth() - 2; @@ -401,65 +362,54 @@ void CGUIComboBox::draw() if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); updateListButtonWidth(skin->getSize(EGDS_SCROLLBAR_SIZE)); // font changed while the listbox is open? - if ( ActiveFont != skin->getFont() && ListBox ) - { + if (ActiveFont != skin->getFont() && ListBox) { // close and re-open to use new font-size openCloseMenu(); openCloseMenu(); } - IGUIElement *currentFocus = Environment->getFocus(); - if (currentFocus != LastFocus) - { + if (currentFocus != LastFocus) { HasFocus = currentFocus == this || isMyChild(currentFocus); LastFocus = currentFocus; } // set colors each time as skin-colors can be changed SelectedText->setBackgroundColor(skin->getColor(EGDC_HIGH_LIGHT)); - if(isEnabled()) - { + if (isEnabled()) { SelectedText->setDrawBackground(HasFocus); SelectedText->setOverrideColor(skin->getColor(HasFocus ? EGDC_HIGH_LIGHT_TEXT : EGDC_BUTTON_TEXT)); - } - else - { + } else { SelectedText->setDrawBackground(false); SelectedText->setOverrideColor(skin->getColor(EGDC_GRAY_TEXT)); } ListButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_DOWN), skin->getColor(isEnabled() ? EGDC_WINDOW_SYMBOL : EGDC_GRAY_WINDOW_SYMBOL)); ListButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_DOWN), skin->getColor(isEnabled() ? EGDC_WINDOW_SYMBOL : EGDC_GRAY_WINDOW_SYMBOL)); - core::rect frameRect(AbsoluteRect); // draw the border skin->draw3DSunkenPane(this, skin->getColor(EGDC_3D_HIGH_LIGHT), - true, true, frameRect, &AbsoluteClippingRect); + true, true, frameRect, &AbsoluteClippingRect); // draw children IGUIElement::draw(); } - void CGUIComboBox::openCloseMenu() { - if (ListBox) - { + if (ListBox) { // close list box Environment->setFocus(this); ListBox->remove(); ListBox = nullptr; - } - else - { + } else { if (Parent) { SEvent event; event.EventType = EET_GUI_EVENT; @@ -474,7 +424,7 @@ void CGUIComboBox::openCloseMenu() Parent->bringToFront(this); } - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); u32 h = Items.size(); if (h > getMaxSelectionRows()) @@ -488,7 +438,7 @@ void CGUIComboBox::openCloseMenu() // open list box core::rect r(0, AbsoluteRect.getHeight(), - AbsoluteRect.getWidth(), AbsoluteRect.getHeight() + h); + AbsoluteRect.getWidth(), AbsoluteRect.getHeight() + h); ListBox = new CGUIListBox(Environment, this, -1, r, false, true, true); ListBox->setSubElement(true); @@ -497,9 +447,9 @@ void CGUIComboBox::openCloseMenu() // ensure that list box is always completely visible if (ListBox->getAbsolutePosition().LowerRightCorner.Y > Environment->getRootGUIElement()->getAbsolutePosition().getHeight()) - ListBox->setRelativePosition( core::rect(0, -ListBox->getAbsolutePosition().getHeight(), AbsoluteRect.getWidth(), 0) ); + ListBox->setRelativePosition(core::rect(0, -ListBox->getAbsolutePosition().getHeight(), AbsoluteRect.getWidth(), 0)); - for (s32 i=0; i<(s32)Items.size(); ++i) + for (s32 i = 0; i < (s32)Items.size(); ++i) ListBox->addItem(Items[i].Name.c_str()); ListBox->setSelected(Selected); @@ -509,6 +459,5 @@ void CGUIComboBox::openCloseMenu() } } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIComboBox.h b/source/Irrlicht/CGUIComboBox.h index c076783b..77f1eca1 100644 --- a/source/Irrlicht/CGUIComboBox.h +++ b/source/Irrlicht/CGUIComboBox.h @@ -13,96 +13,92 @@ namespace irr { namespace gui { - class IGUIButton; - class IGUIListBox; +class IGUIButton; +class IGUIListBox; - //! Single line edit box for editing simple text. - class CGUIComboBox : public IGUIComboBox - { - public: - - //! constructor - CGUIComboBox(IGUIEnvironment* environment, IGUIElement* parent, +//! Single line edit box for editing simple text. +class CGUIComboBox : public IGUIComboBox +{ +public: + //! constructor + CGUIComboBox(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle); - //! Returns amount of items in box - u32 getItemCount() const override; + //! Returns amount of items in box + u32 getItemCount() const override; - //! returns string of an item. the idx may be a value from 0 to itemCount-1 - const wchar_t* getItem(u32 idx) const override; + //! returns string of an item. the idx may be a value from 0 to itemCount-1 + const wchar_t *getItem(u32 idx) const override; - //! Returns item data of an item. the idx may be a value from 0 to itemCount-1 - u32 getItemData(u32 idx) const override; + //! Returns item data of an item. the idx may be a value from 0 to itemCount-1 + u32 getItemData(u32 idx) const override; - //! Returns index based on item data - s32 getIndexForItemData( u32 data ) const override; + //! Returns index based on item data + s32 getIndexForItemData(u32 data) const override; - //! adds an item and returns the index of it - u32 addItem(const wchar_t* text, u32 data) override; + //! adds an item and returns the index of it + u32 addItem(const wchar_t *text, u32 data) override; - //! Removes an item from the combo box. - void removeItem(u32 id) override; + //! Removes an item from the combo box. + void removeItem(u32 id) override; - //! deletes all items in the combo box - void clear() override; + //! deletes all items in the combo box + void clear() override; - //! returns the text of the currently selected item - const wchar_t* getText() const override; + //! returns the text of the currently selected item + const wchar_t *getText() const override; - //! returns id of selected item. returns -1 if no item is selected. - s32 getSelected() const override; + //! returns id of selected item. returns -1 if no item is selected. + s32 getSelected() const override; - //! sets the selected item. Set this to -1 if no item should be selected - void setSelected(s32 idx) override; + //! sets the selected item. Set this to -1 if no item should be selected + void setSelected(s32 idx) override; - //! Sets the selected item and emits a change event. - /** Set this to -1 if no item should be selected */ - void setAndSendSelected(s32 idx) override; + //! Sets the selected item and emits a change event. + /** Set this to -1 if no item should be selected */ + void setAndSendSelected(s32 idx) override; - //! sets the text alignment of the text part - void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; + //! sets the text alignment of the text part + void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; - //! Set the maximal number of rows for the selection listbox - void setMaxSelectionRows(u32 max) override; + //! Set the maximal number of rows for the selection listbox + void setMaxSelectionRows(u32 max) override; - //! Get the maximal number of rows for the selection listbox - u32 getMaxSelectionRows() const override; + //! Get the maximal number of rows for the selection listbox + u32 getMaxSelectionRows() const override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! draws the element and its children - void draw() override; + //! draws the element and its children + void draw() override; - private: +private: + void openCloseMenu(); + void sendSelectionChangedEvent(); + void updateListButtonWidth(s32 width); - void openCloseMenu(); - void sendSelectionChangedEvent(); - void updateListButtonWidth(s32 width); + IGUIButton *ListButton; + IGUIStaticText *SelectedText; + IGUIListBox *ListBox; + IGUIElement *LastFocus; - IGUIButton* ListButton; - IGUIStaticText* SelectedText; - IGUIListBox* ListBox; - IGUIElement *LastFocus; + struct SComboData + { + SComboData(const wchar_t *text, u32 data) : + Name(text), Data(data) {} - - struct SComboData - { - SComboData ( const wchar_t * text, u32 data ) - : Name (text), Data ( data ) {} - - core::stringw Name; - u32 Data; - }; - core::array< SComboData > Items; - - s32 Selected; - EGUI_ALIGNMENT HAlign, VAlign; - u32 MaxSelectionRows; - bool HasFocus; - IGUIFont* ActiveFont; + core::stringw Name; + u32 Data; }; + core::array Items; + s32 Selected; + EGUI_ALIGNMENT HAlign, VAlign; + u32 MaxSelectionRows; + bool HasFocus; + IGUIFont *ActiveFont; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIEditBox.cpp b/source/Irrlicht/CGUIEditBox.cpp index 3a7e90ed..7dc50556 100644 --- a/source/Irrlicht/CGUIEditBox.cpp +++ b/source/Irrlicht/CGUIEditBox.cpp @@ -27,20 +27,21 @@ namespace gui { //! constructor -CGUIEditBox::CGUIEditBox(const wchar_t* text, bool border, - IGUIEnvironment* environment, IGUIElement* parent, s32 id, - const core::rect& rectangle) - : IGUIEditBox(environment, parent, id, rectangle), OverwriteMode(false), MouseMarking(false), - Border(border), Background(true), OverrideColorEnabled(false), MarkBegin(0), MarkEnd(0), - OverrideColor(video::SColor(101,255,255,255)), OverrideFont(0), LastBreakFont(0), - Operator(0), BlinkStartTime(0), CursorBlinkTime(350), CursorChar(L"_"), CursorPos(0), HScrollPos(0), VScrollPos(0), Max(0), - WordWrap(false), MultiLine(false), AutoScroll(true), PasswordBox(false), - PasswordChar(L'*'), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_CENTER), - CurrentTextRect(0,0,1,1), FrameRect(rectangle) +CGUIEditBox::CGUIEditBox(const wchar_t *text, bool border, + IGUIEnvironment *environment, IGUIElement *parent, s32 id, + const core::rect &rectangle) : + IGUIEditBox(environment, parent, id, rectangle), + OverwriteMode(false), MouseMarking(false), + Border(border), Background(true), OverrideColorEnabled(false), MarkBegin(0), MarkEnd(0), + OverrideColor(video::SColor(101, 255, 255, 255)), OverrideFont(0), LastBreakFont(0), + Operator(0), BlinkStartTime(0), CursorBlinkTime(350), CursorChar(L"_"), CursorPos(0), HScrollPos(0), VScrollPos(0), Max(0), + WordWrap(false), MultiLine(false), AutoScroll(true), PasswordBox(false), + PasswordChar(L'*'), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_CENTER), + CurrentTextRect(0, 0, 1, 1), FrameRect(rectangle) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIEditBox"); - #endif +#endif Text = text; @@ -60,7 +61,6 @@ CGUIEditBox::CGUIEditBox(const wchar_t* text, bool border, calculateScrollPos(); } - //! destructor CGUIEditBox::~CGUIEditBox() { @@ -71,9 +71,8 @@ CGUIEditBox::~CGUIEditBox() Operator->drop(); } - //! Sets another skin independent font. -void CGUIEditBox::setOverrideFont(IGUIFont* font) +void CGUIEditBox::setOverrideFont(IGUIFont *font) { if (OverrideFont == font) return; @@ -90,17 +89,17 @@ void CGUIEditBox::setOverrideFont(IGUIFont* font) } //! Gets the override font (if any) -IGUIFont * CGUIEditBox::getOverrideFont() const +IGUIFont *CGUIEditBox::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont* CGUIEditBox::getActiveFont() const +IGUIFont *CGUIEditBox::getActiveFont() const { - if ( OverrideFont ) + if (OverrideFont) return OverrideFont; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; @@ -113,13 +112,11 @@ void CGUIEditBox::setOverrideColor(video::SColor color) OverrideColorEnabled = true; } - video::SColor CGUIEditBox::getOverrideColor() const { return OverrideColor; } - //! Turns the border on or off void CGUIEditBox::setDrawBorder(bool border) { @@ -162,27 +159,23 @@ void CGUIEditBox::setWordWrap(bool enable) breakText(); } - void CGUIEditBox::updateAbsolutePosition() { core::rect oldAbsoluteRect(AbsoluteRect); IGUIElement::updateAbsolutePosition(); - if ( oldAbsoluteRect != AbsoluteRect ) - { + if (oldAbsoluteRect != AbsoluteRect) { calculateFrameRect(); breakText(); calculateScrollPos(); } } - //! Checks if word wrap is enabled bool CGUIEditBox::isWordWrapEnabled() const { return WordWrap; } - //! Enables or disables newlines. void CGUIEditBox::setMultiLine(bool enable) { @@ -190,19 +183,16 @@ void CGUIEditBox::setMultiLine(bool enable) breakText(); } - //! Checks if multi line editing is enabled bool CGUIEditBox::isMultiLineEnabled() const { return MultiLine; } - void CGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar) { PasswordBox = passwordBox; - if (PasswordBox) - { + if (PasswordBox) { PasswordChar = passwordChar; setMultiLine(false); setWordWrap(false); @@ -210,13 +200,11 @@ void CGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar) } } - bool CGUIEditBox::isPasswordBox() const { return PasswordBox; } - //! Sets text justification void CGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { @@ -224,22 +212,17 @@ void CGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT ver VAlign = vertical; } - //! called if an event happened. -bool CGUIEditBox::OnEvent(const SEvent& event) +bool CGUIEditBox::OnEvent(const SEvent &event) { - if (isEnabled()) - { + if (isEnabled()) { - switch(event.EventType) - { + switch (event.EventType) { case EET_GUI_EVENT: - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) - { - if (event.GUIEvent.Caller == this) - { + if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { + if (event.GUIEvent.Caller == this) { MouseMarking = false; - setTextMarkers(0,0); + setTextMarkers(0, 0); } } break; @@ -263,8 +246,7 @@ bool CGUIEditBox::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - -bool CGUIEditBox::processKey(const SEvent& event) +bool CGUIEditBox::processKey(const SEvent &event) { if (!event.KeyInput.PressedDown) return false; @@ -275,17 +257,14 @@ bool CGUIEditBox::processKey(const SEvent& event) // control shortcut handling - if (event.KeyInput.Control) - { + if (event.KeyInput.Control) { // german backlash '\' entered with control + '?' - if ( event.KeyInput.Char == '\\' ) - { + if (event.KeyInput.Char == '\\') { inputChar(event.KeyInput.Char); return true; } - switch(event.KeyInput.Key) - { + switch (event.KeyInput.Key) { case KEY_KEY_A: // select all newMarkBegin = 0; @@ -293,8 +272,7 @@ bool CGUIEditBox::processKey(const SEvent& event) break; case KEY_KEY_C: // copy to clipboard - if (!PasswordBox && Operator && MarkBegin != MarkEnd) - { + if (!PasswordBox && Operator && MarkBegin != MarkEnd) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; @@ -305,8 +283,7 @@ bool CGUIEditBox::processKey(const SEvent& event) break; case KEY_KEY_X: // cut to the clipboard - if (!PasswordBox && Operator && MarkBegin != MarkEnd) - { + if (!PasswordBox && Operator && MarkBegin != MarkEnd) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; @@ -315,12 +292,11 @@ bool CGUIEditBox::processKey(const SEvent& event) wStringToUTF8(sc, Text.subString(realmbgn, realmend - realmbgn)); Operator->copyToClipboard(sc.c_str()); - if (isEnabled()) - { + if (isEnabled()) { // delete core::stringw s; s = Text.subString(0, realmbgn); - s.append( Text.subString(realmend, Text.size()-realmend) ); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; CursorPos = realmbgn; @@ -331,45 +307,40 @@ bool CGUIEditBox::processKey(const SEvent& event) } break; case KEY_KEY_V: - if ( !isEnabled() ) + if (!isEnabled()) break; // paste from the clipboard - if (Operator) - { + if (Operator) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; // add the string const c8 *p = Operator->getTextFromClipboard(); - if (p) - { + if (p) { irr::core::stringw widep; core::utf8ToWString(widep, p); - if (MarkBegin == MarkEnd) - { + if (MarkBegin == MarkEnd) { // insert text core::stringw s = Text.subString(0, CursorPos); s.append(widep); - s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); + s.append(Text.subString(CursorPos, Text.size() - CursorPos)); - if (!Max || s.size()<=Max) // thx to Fish FH for fix + if (!Max || s.size() <= Max) // thx to Fish FH for fix { Text = s; s = widep; CursorPos += s.size(); } - } - else - { + } else { // replace text core::stringw s = Text.subString(0, realmbgn); s.append(widep); - s.append( Text.subString(realmend, Text.size()-realmend) ); + s.append(Text.subString(realmend, Text.size() - realmend)); - if (!Max || s.size()<=Max) // thx to Fish FH for fix + if (!Max || s.size() <= Max) // thx to Fish FH for fix { Text = s; s = widep; @@ -385,14 +356,11 @@ bool CGUIEditBox::processKey(const SEvent& event) break; case KEY_HOME: // move/highlight to start of text - if (event.KeyInput.Shift) - { + if (event.KeyInput.Shift) { newMarkEnd = CursorPos; newMarkBegin = 0; CursorPos = 0; - } - else - { + } else { CursorPos = 0; newMarkBegin = 0; newMarkEnd = 0; @@ -400,14 +368,11 @@ bool CGUIEditBox::processKey(const SEvent& event) break; case KEY_END: // move/highlight to end of text - if (event.KeyInput.Shift) - { + if (event.KeyInput.Shift) { newMarkBegin = CursorPos; newMarkEnd = Text.size(); CursorPos = 0; - } - else - { + } else { CursorPos = Text.size(); newMarkBegin = 0; newMarkEnd = 0; @@ -418,178 +383,143 @@ bool CGUIEditBox::processKey(const SEvent& event) } } // Some special keys - but only handle them if KeyInput.Char is null as on some systems (X11) they might have same key-code as ansi-keys otherwise - else if (event.KeyInput.Char == 0) - { - switch(event.KeyInput.Key) - { - case KEY_END: - { - s32 p = Text.size(); - if (WordWrap || MultiLine) - { - p = getLineFromPos(CursorPos); - p = BrokenTextPositions[p] + (s32)BrokenText[p].size(); - if (p > 0 && (Text[p-1] == L'\r' || Text[p-1] == L'\n' )) - p-=1; - } - - if (event.KeyInput.Shift) - { - if (MarkBegin == MarkEnd) - newMarkBegin = CursorPos; - - newMarkEnd = p; - } - else - { - newMarkBegin = 0; - newMarkEnd = 0; - } - CursorPos = p; - BlinkStartTime = os::Timer::getTime(); + else if (event.KeyInput.Char == 0) { + switch (event.KeyInput.Key) { + case KEY_END: { + s32 p = Text.size(); + if (WordWrap || MultiLine) { + p = getLineFromPos(CursorPos); + p = BrokenTextPositions[p] + (s32)BrokenText[p].size(); + if (p > 0 && (Text[p - 1] == L'\r' || Text[p - 1] == L'\n')) + p -= 1; } - break; - case KEY_HOME: - { - s32 p = 0; - if (WordWrap || MultiLine) - { - p = getLineFromPos(CursorPos); - p = BrokenTextPositions[p]; - } + if (event.KeyInput.Shift) { + if (MarkBegin == MarkEnd) + newMarkBegin = CursorPos; - if (event.KeyInput.Shift) - { - if (MarkBegin == MarkEnd) - newMarkBegin = CursorPos; - newMarkEnd = p; - } - else - { - newMarkBegin = 0; - newMarkEnd = 0; - } - CursorPos = p; - BlinkStartTime = os::Timer::getTime(); + newMarkEnd = p; + } else { + newMarkBegin = 0; + newMarkEnd = 0; } - break; + CursorPos = p; + BlinkStartTime = os::Timer::getTime(); + } break; + case KEY_HOME: { + + s32 p = 0; + if (WordWrap || MultiLine) { + p = getLineFromPos(CursorPos); + p = BrokenTextPositions[p]; + } + + if (event.KeyInput.Shift) { + if (MarkBegin == MarkEnd) + newMarkBegin = CursorPos; + newMarkEnd = p; + } else { + newMarkBegin = 0; + newMarkEnd = 0; + } + CursorPos = p; + BlinkStartTime = os::Timer::getTime(); + } break; case KEY_LEFT: - if (event.KeyInput.Shift) - { - if (CursorPos > 0) - { + if (event.KeyInput.Shift) { + if (CursorPos > 0) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; - newMarkEnd = CursorPos-1; + newMarkEnd = CursorPos - 1; } - } - else - { + } else { newMarkBegin = 0; newMarkEnd = 0; } - if (CursorPos > 0) CursorPos--; + if (CursorPos > 0) + CursorPos--; BlinkStartTime = os::Timer::getTime(); break; case KEY_RIGHT: - if (event.KeyInput.Shift) - { - if (Text.size() > (u32)CursorPos) - { + if (event.KeyInput.Shift) { + if (Text.size() > (u32)CursorPos) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; - newMarkEnd = CursorPos+1; + newMarkEnd = CursorPos + 1; } - } - else - { + } else { newMarkBegin = 0; newMarkEnd = 0; } - if (Text.size() > (u32)CursorPos) CursorPos++; + if (Text.size() > (u32)CursorPos) + CursorPos++; BlinkStartTime = os::Timer::getTime(); break; case KEY_UP: - if (MultiLine || (WordWrap && BrokenText.size() > 1) ) - { + if (MultiLine || (WordWrap && BrokenText.size() > 1)) { s32 lineNo = getLineFromPos(CursorPos); s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin > MarkEnd ? MarkBegin : MarkEnd); - if (lineNo > 0) - { + if (lineNo > 0) { s32 cp = CursorPos - BrokenTextPositions[lineNo]; - if ((s32)BrokenText[lineNo-1].size() < cp) - CursorPos = BrokenTextPositions[lineNo-1] + core::max_((u32)1, BrokenText[lineNo-1].size())-1; + if ((s32)BrokenText[lineNo - 1].size() < cp) + CursorPos = BrokenTextPositions[lineNo - 1] + core::max_((u32)1, BrokenText[lineNo - 1].size()) - 1; else - CursorPos = BrokenTextPositions[lineNo-1] + cp; + CursorPos = BrokenTextPositions[lineNo - 1] + cp; } - if (event.KeyInput.Shift) - { + if (event.KeyInput.Shift) { newMarkBegin = mb; newMarkEnd = CursorPos; - } - else - { + } else { newMarkBegin = 0; newMarkEnd = 0; } - } - else - { + } else { return false; } break; case KEY_DOWN: - if (MultiLine || (WordWrap && BrokenText.size() > 1) ) - { + if (MultiLine || (WordWrap && BrokenText.size() > 1)) { s32 lineNo = getLineFromPos(CursorPos); s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin < MarkEnd ? MarkBegin : MarkEnd); - if (lineNo < (s32)BrokenText.size()-1) - { + if (lineNo < (s32)BrokenText.size() - 1) { s32 cp = CursorPos - BrokenTextPositions[lineNo]; - if ((s32)BrokenText[lineNo+1].size() < cp) - CursorPos = BrokenTextPositions[lineNo+1] + core::max_((u32)1, BrokenText[lineNo+1].size())-1; + if ((s32)BrokenText[lineNo + 1].size() < cp) + CursorPos = BrokenTextPositions[lineNo + 1] + core::max_((u32)1, BrokenText[lineNo + 1].size()) - 1; else - CursorPos = BrokenTextPositions[lineNo+1] + cp; + CursorPos = BrokenTextPositions[lineNo + 1] + cp; } - if (event.KeyInput.Shift) - { + if (event.KeyInput.Shift) { newMarkBegin = mb; newMarkEnd = CursorPos; - } - else - { + } else { newMarkBegin = 0; newMarkEnd = 0; } - } - else - { + } else { return false; } break; case KEY_INSERT: - if ( !isEnabled() ) + if (!isEnabled()) break; OverwriteMode = !OverwriteMode; break; case KEY_DELETE: - if ( !isEnabled() ) + if (!isEnabled()) break; - if (keyDelete()) - { + if (keyDelete()) { BlinkStartTime = os::Timer::getTime(); newMarkBegin = 0; newMarkEnd = 0; @@ -599,52 +529,42 @@ bool CGUIEditBox::processKey(const SEvent& event) default: return false; } - } - else - { + } else { // default keyboard handling - switch(event.KeyInput.Key) - { + switch (event.KeyInput.Key) { case KEY_RETURN: - if (MultiLine) - { + if (MultiLine) { inputChar(L'\n'); - } - else - { + } else { calculateScrollPos(); - sendGuiEvent( EGET_EDITBOX_ENTER ); + sendGuiEvent(EGET_EDITBOX_ENTER); } return true; case KEY_BACK: - if ( !isEnabled() ) + if (!isEnabled()) break; - if (Text.size()) - { + if (Text.size()) { core::stringw s; - if (MarkBegin != MarkEnd) - { + if (MarkBegin != MarkEnd) { // delete marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); - s.append( Text.subString(realmend, Text.size()-realmend) ); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; CursorPos = realmbgn; - } - else - { + } else { // delete text behind cursor - if (CursorPos>0) - s = Text.subString(0, CursorPos-1); + if (CursorPos > 0) + s = Text.subString(0, CursorPos - 1); else s = L""; - s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); + s.append(Text.subString(CursorPos, Text.size() - CursorPos)); Text = s; --CursorPos; } @@ -663,22 +583,18 @@ bool CGUIEditBox::processKey(const SEvent& event) // At least on X11 we get a char with 127 when the delete key is pressed. // We get no char when the delete key on numkeys is pressed with numlock off (handled in the other case calling keyDelete as Char is then 0). // We get a keykode != 127 when delete key on numlock is pressed with numlock on. - if (event.KeyInput.Char == 127) - { - if ( !isEnabled() ) + if (event.KeyInput.Char == 127) { + if (!isEnabled()) break; - if (keyDelete()) - { + if (keyDelete()) { BlinkStartTime = os::Timer::getTime(); newMarkBegin = 0; newMarkEnd = 0; textChanged = true; } break; - } - else - { + } else { inputChar(event.KeyInput.Char); return true; } @@ -720,17 +636,14 @@ bool CGUIEditBox::processKey(const SEvent& event) } // Set new text markers - setTextMarkers( newMarkBegin, newMarkEnd ); + setTextMarkers(newMarkBegin, newMarkEnd); // break the text if it has changed - if (textChanged) - { + if (textChanged) { breakText(); calculateScrollPos(); sendGuiEvent(EGET_EDITBOX_CHANGED); - } - else - { + } else { calculateScrollPos(); } @@ -739,27 +652,23 @@ bool CGUIEditBox::processKey(const SEvent& event) bool CGUIEditBox::keyDelete() { - if (Text.size() != 0) - { + if (Text.size() != 0) { core::stringw s; - if (MarkBegin != MarkEnd) - { + if (MarkBegin != MarkEnd) { // delete marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); - s.append( Text.subString(realmend, Text.size()-realmend) ); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; CursorPos = realmbgn; - } - else - { + } else { // delete text before cursor s = Text.subString(0, CursorPos); - s.append( Text.subString(CursorPos+1, Text.size()-CursorPos-1) ); + s.append(Text.subString(CursorPos + 1, Text.size() - CursorPos - 1)); Text = s; } @@ -780,21 +689,19 @@ void CGUIEditBox::draw() const bool focus = Environment->hasFocus(this); - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (!skin) return; EGUI_DEFAULT_COLOR bgCol = EGDC_GRAY_EDITABLE; - if ( isEnabled() ) + if (isEnabled()) bgCol = focus ? EGDC_FOCUSED_EDITABLE : EGDC_EDITABLE; - if (!Border && Background) - { + if (!Border && Background) { skin->draw2DRectangle(this, skin->getColor(bgCol), AbsoluteRect, &AbsoluteClippingRect); } - if (Border) - { + if (Border) { // draw the border skin->draw3DSunkenPane(this, skin->getColor(bgCol), false, Background, AbsoluteRect, &AbsoluteClippingRect); @@ -806,15 +713,13 @@ void CGUIEditBox::draw() // draw the text - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); s32 cursorLine = 0; s32 charcursorpos = 0; - if (font) - { - if (LastBreakFont != font) - { + if (font) { + if (LastBreakFont != font) { breakText(); } @@ -838,16 +743,13 @@ void CGUIEditBox::draw() const bool prevOver = OverrideColorEnabled; const video::SColor prevColor = OverrideColor; - if (Text.size()) - { - if (!isEnabled() && !OverrideColorEnabled) - { + if (Text.size()) { + if (!isEnabled() && !OverrideColorEnabled) { OverrideColorEnabled = true; OverrideColor = skin->getColor(EGDC_GRAY_TEXT); } - for (s32 i=0; i < lineCount; ++i) - { + for (s32 i = 0; i < lineCount; ++i) { setTextRect(i); // clipping test - don't draw anything outside the visible area @@ -857,64 +759,53 @@ void CGUIEditBox::draw() continue; // get current line - if (PasswordBox) - { - if (BrokenText.size() != 1) - { + if (PasswordBox) { + if (BrokenText.size() != 1) { BrokenText.clear(); BrokenText.push_back(core::stringw()); } - if (BrokenText[0].size() != Text.size()) - { + if (BrokenText[0].size() != Text.size()) { BrokenText[0] = Text; - for (u32 q = 0; q < Text.size(); ++q) - { - BrokenText[0] [q] = PasswordChar; + for (u32 q = 0; q < Text.size(); ++q) { + BrokenText[0][q] = PasswordChar; } } txtLine = &BrokenText[0]; startPos = 0; - } - else - { + } else { txtLine = ml ? &BrokenText[i] : &Text; startPos = ml ? BrokenTextPositions[i] : 0; } - // draw normal text font->draw(txtLine->c_str(), CurrentTextRect, - OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &localClipRect); + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &localClipRect); // draw mark and marked text - if (focus && MarkBegin != MarkEnd && i >= hlineStart && i < hlineStart + hlineCount) - { + if (focus && MarkBegin != MarkEnd && i >= hlineStart && i < hlineStart + hlineCount) { s32 mbegin = 0, mend = 0; s32 lineStartPos = 0, lineEndPos = txtLine->size(); - if (i == hlineStart) - { + if (i == hlineStart) { // highlight start is on this line s = txtLine->subString(0, realmbgn - startPos); mbegin = font->getDimension(s.c_str()).Width; // deal with kerning mbegin += font->getKerningWidth( - &((*txtLine)[realmbgn - startPos]), - realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0); + &((*txtLine)[realmbgn - startPos]), + realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0); lineStartPos = realmbgn - startPos; } - if (i == hlineStart + hlineCount - 1) - { + if (i == hlineStart + hlineCount - 1) { // highlight end is on this line s2 = txtLine->subString(0, realmend - startPos); mend = font->getDimension(s2.c_str()).Width; lineEndPos = (s32)s2.size(); - } - else + } else mend = font->getDimension(txtLine->c_str()).Width; CurrentTextRect.UpperLeftCorner.X += mbegin; @@ -928,9 +819,8 @@ void CGUIEditBox::draw() if (s.size()) font->draw(s.c_str(), CurrentTextRect, - OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), - false, true, &localClipRect); - + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), + false, true, &localClipRect); } } @@ -940,41 +830,35 @@ void CGUIEditBox::draw() } // draw cursor - if ( isEnabled() ) - { - if (WordWrap || MultiLine) - { + if (isEnabled()) { + if (WordWrap || MultiLine) { cursorLine = getLineFromPos(CursorPos); txtLine = &BrokenText[cursorLine]; startPos = BrokenTextPositions[cursorLine]; } - s = txtLine->subString(0,CursorPos-startPos); + s = txtLine->subString(0, CursorPos - startPos); charcursorpos = font->getDimension(s.c_str()).Width + - font->getKerningWidth(CursorChar.c_str(), CursorPos-startPos > 0 ? &((*txtLine)[CursorPos-startPos-1]) : 0); + font->getKerningWidth(CursorChar.c_str(), CursorPos - startPos > 0 ? &((*txtLine)[CursorPos - startPos - 1]) : 0); - if (focus && (CursorBlinkTime == 0 || (os::Timer::getTime() - BlinkStartTime) % (2*CursorBlinkTime) < CursorBlinkTime)) - { + if (focus && (CursorBlinkTime == 0 || (os::Timer::getTime() - BlinkStartTime) % (2 * CursorBlinkTime) < CursorBlinkTime)) { setTextRect(cursorLine); CurrentTextRect.UpperLeftCorner.X += charcursorpos; - if ( OverwriteMode ) - { - core::stringw character = Text.subString(CursorPos,1); + if (OverwriteMode) { + core::stringw character = Text.subString(CursorPos, 1); s32 mend = font->getDimension(character.c_str()).Width; - //Make sure the cursor box has at least some width to it - if ( mend <= 0 ) + // Make sure the cursor box has at least some width to it + if (mend <= 0) mend = font->getDimension(CursorChar.c_str()).Width; CurrentTextRect.LowerRightCorner.X = CurrentTextRect.UpperLeftCorner.X + mend; skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), CurrentTextRect, &localClipRect); font->draw(character.c_str(), CurrentTextRect, - OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), - false, true, &localClipRect); - } - else - { + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), + false, true, &localClipRect); + } else { font->draw(CursorChar, CurrentTextRect, - OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &localClipRect); + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &localClipRect); } } } @@ -984,9 +868,8 @@ void CGUIEditBox::draw() IGUIElement::draw(); } - //! Sets the new caption of this element. -void CGUIEditBox::setText(const wchar_t* text) +void CGUIEditBox::setText(const wchar_t *text) { Text = text; if (u32(CursorPos) > Text.size()) @@ -995,7 +878,6 @@ void CGUIEditBox::setText(const wchar_t* text) breakText(); } - //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position void CGUIEditBox::setAutoScroll(bool enable) @@ -1003,7 +885,6 @@ void CGUIEditBox::setAutoScroll(bool enable) AutoScroll = enable; } - //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not bool CGUIEditBox::isAutoScrollEnabled() const @@ -1011,7 +892,6 @@ bool CGUIEditBox::isAutoScrollEnabled() const return AutoScroll; } - //! Gets the area of the text in the edit box //! \return Returns the size in pixels of the text core::dimension2du CGUIEditBox::getTextDimension() @@ -1021,8 +901,7 @@ core::dimension2du CGUIEditBox::getTextDimension() setTextRect(0); ret = CurrentTextRect; - for (u32 i=1; i < BrokenText.size(); ++i) - { + for (u32 i = 1; i < BrokenText.size(); ++i) { setTextRect(i); ret.addInternalPoint(CurrentTextRect.UpperLeftCorner); ret.addInternalPoint(CurrentTextRect.LowerRightCorner); @@ -1031,7 +910,6 @@ core::dimension2du CGUIEditBox::getTextDimension() return core::dimension2du(ret.getSize()); } - //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. @@ -1043,7 +921,6 @@ void CGUIEditBox::setMax(u32 max) Text = Text.subString(0, Max); } - //! Returns maximum amount of characters, previously set by setMax(); u32 CGUIEditBox::getMax() const { @@ -1075,53 +952,42 @@ irr::u32 CGUIEditBox::getCursorBlinkTime() const return CursorBlinkTime; } -bool CGUIEditBox::processMouse(const SEvent& event) +bool CGUIEditBox::processMouse(const SEvent &event) { - switch(event.MouseInput.Event) - { + switch (event.MouseInput.Event) { case irr::EMIE_LMOUSE_LEFT_UP: - if (Environment->hasFocus(this)) - { + if (Environment->hasFocus(this)) { CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - if (MouseMarking) - { - setTextMarkers( MarkBegin, CursorPos ); + if (MouseMarking) { + setTextMarkers(MarkBegin, CursorPos); } MouseMarking = false; calculateScrollPos(); return true; } break; - case irr::EMIE_MOUSE_MOVED: - { - if (MouseMarking) - { - CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - setTextMarkers( MarkBegin, CursorPos ); - calculateScrollPos(); - return true; - } + case irr::EMIE_MOUSE_MOVED: { + if (MouseMarking) { + CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); + setTextMarkers(MarkBegin, CursorPos); + calculateScrollPos(); + return true; } - break; + } break; case EMIE_LMOUSE_PRESSED_DOWN: - if (!Environment->hasFocus(this)) // can happen when events are manually send to the element + if (!Environment->hasFocus(this)) // can happen when events are manually send to the element { BlinkStartTime = os::Timer::getTime(); MouseMarking = true; CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - setTextMarkers(CursorPos, CursorPos ); + setTextMarkers(CursorPos, CursorPos); calculateScrollPos(); return true; - } - else - { + } else { if (!AbsoluteClippingRect.isPointInside( - core::position2d(event.MouseInput.X, event.MouseInput.Y))) - { + core::position2d(event.MouseInput.X, event.MouseInput.Y))) { return false; - } - else - { + } else { // move cursor CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); @@ -1130,7 +996,7 @@ bool CGUIEditBox::processMouse(const SEvent& event) newMarkBegin = CursorPos; MouseMarking = true; - setTextMarkers( newMarkBegin, CursorPos); + setTextMarkers(newMarkBegin, CursorPos); calculateScrollPos(); return true; } @@ -1170,28 +1036,25 @@ bool CGUIEditBox::processMouse(const SEvent& event) return false; } - s32 CGUIEditBox::getCursorPos(s32 x, s32 y) { - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1; - core::stringw *txtLine=0; - s32 startPos=0; - x+=3; + core::stringw *txtLine = 0; + s32 startPos = 0; + x += 3; - for (u32 i=0; i < lineCount; ++i) - { + for (u32 i = 0; i < lineCount; ++i) { setTextRect(i); if (i == 0 && y < CurrentTextRect.UpperLeftCorner.Y) y = CurrentTextRect.UpperLeftCorner.Y; - if (i == lineCount - 1 && y > CurrentTextRect.LowerRightCorner.Y ) + if (i == lineCount - 1 && y > CurrentTextRect.LowerRightCorner.Y) y = CurrentTextRect.LowerRightCorner.Y; // is it inside this region? - if (y >= CurrentTextRect.UpperLeftCorner.Y && y <= CurrentTextRect.LowerRightCorner.Y) - { + if (y >= CurrentTextRect.UpperLeftCorner.Y && y <= CurrentTextRect.LowerRightCorner.Y) { // we've found the clicked line txtLine = (WordWrap || MultiLine) ? &BrokenText[i] : &Text; startPos = (WordWrap || MultiLine) ? BrokenTextPositions[i] : 0; @@ -1202,7 +1065,7 @@ s32 CGUIEditBox::getCursorPos(s32 x, s32 y) if (x < CurrentTextRect.UpperLeftCorner.X) x = CurrentTextRect.UpperLeftCorner.X; - if ( !txtLine ) + if (!txtLine) return 0; s32 idx = font->getCharacterFromPos(txtLine->c_str(), x - CurrentTextRect.UpperLeftCorner.X); @@ -1215,7 +1078,6 @@ s32 CGUIEditBox::getCursorPos(s32 x, s32 y) return txtLine->size() + startPos; } - //! Breaks the single text line. void CGUIEditBox::breakText() { @@ -1225,7 +1087,7 @@ void CGUIEditBox::breakText() BrokenText.clear(); // need to reallocate :/ BrokenTextPositions.set_used(0); - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); if (!font) return; @@ -1240,8 +1102,7 @@ void CGUIEditBox::breakText() s32 elWidth = RelativeRect.getWidth() - 6; wchar_t c; - for (s32 i=0; i i ) + if (CursorPos > i) --CursorPos; } - } - else if (c == L'\n') // Unix breaks + } else if (c == L'\n') // Unix breaks { lineBreak = true; c = 0; @@ -1270,25 +1130,21 @@ void CGUIEditBox::breakText() if (!MultiLine) lineBreak = false; - if (c == L' ' || c == 0 || i == (size-1)) - { + if (c == L' ' || c == 0 || i == (size - 1)) { // here comes the next whitespace, look if // we can break the last word to the next line // We also break whitespace, otherwise cursor would vanish beside the right border. s32 whitelgth = font->getDimension(whitespace.c_str()).Width; s32 worldlgth = font->getDimension(word.c_str()).Width; - if (WordWrap && length + worldlgth + whitelgth > elWidth && line.size() > 0) - { + if (WordWrap && length + worldlgth + whitelgth > elWidth && line.size() > 0) { // break to next line length = worldlgth; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); lastLineStart = i - (s32)word.size(); line = word; - } - else - { + } else { // add word to line line += whitespace; line += word; @@ -1298,26 +1154,22 @@ void CGUIEditBox::breakText() word = L""; whitespace = L""; - - if ( c ) + if (c) whitespace += c; // compute line break - if (lineBreak) - { + if (lineBreak) { line += whitespace; line += word; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); - lastLineStart = i+1; + lastLineStart = i + 1; line = L""; word = L""; whitespace = L""; length = 0; } - } - else - { + } else { // yippee this is a word.. word += c; } @@ -1335,10 +1187,10 @@ void CGUIEditBox::breakText() // But please no one change this without also rewriting (and this time fucking testing!!!) autoscrolling (I noticed this when fixing the old autoscrolling). void CGUIEditBox::setTextRect(s32 line) { - if ( line < 0 ) + if (line < 0) return; - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); if (!font) return; @@ -1346,24 +1198,20 @@ void CGUIEditBox::setTextRect(s32 line) // get text dimension const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1; - if (WordWrap || MultiLine) - { + if (WordWrap || MultiLine) { d = font->getDimension(BrokenText[line].c_str()); - } - else - { + } else { d = font->getDimension(Text.c_str()); d.Height = AbsoluteRect.getHeight(); } d.Height += font->getKerningHeight(); // justification - switch (HAlign) - { + switch (HAlign) { case EGUIA_CENTER: // align to h centre - CurrentTextRect.UpperLeftCorner.X = (FrameRect.getWidth()/2) - (d.Width/2); - CurrentTextRect.LowerRightCorner.X = (FrameRect.getWidth()/2) + (d.Width/2); + CurrentTextRect.UpperLeftCorner.X = (FrameRect.getWidth() / 2) - (d.Width / 2); + CurrentTextRect.LowerRightCorner.X = (FrameRect.getWidth() / 2) + (d.Width / 2); break; case EGUIA_LOWERRIGHT: // align to right edge @@ -1374,53 +1222,47 @@ void CGUIEditBox::setTextRect(s32 line) // align to left edge CurrentTextRect.UpperLeftCorner.X = 0; CurrentTextRect.LowerRightCorner.X = d.Width; - } - switch (VAlign) - { + switch (VAlign) { case EGUIA_CENTER: // align to v centre CurrentTextRect.UpperLeftCorner.Y = - (FrameRect.getHeight()/2) - (lineCount*d.Height)/2 + d.Height*line; + (FrameRect.getHeight() / 2) - (lineCount * d.Height) / 2 + d.Height * line; break; case EGUIA_LOWERRIGHT: // align to bottom edge CurrentTextRect.UpperLeftCorner.Y = - FrameRect.getHeight() - lineCount*d.Height + d.Height*line; + FrameRect.getHeight() - lineCount * d.Height + d.Height * line; break; default: // align to top edge - CurrentTextRect.UpperLeftCorner.Y = d.Height*line; + CurrentTextRect.UpperLeftCorner.Y = d.Height * line; break; } - CurrentTextRect.UpperLeftCorner.X -= HScrollPos; + CurrentTextRect.UpperLeftCorner.X -= HScrollPos; CurrentTextRect.LowerRightCorner.X -= HScrollPos; - CurrentTextRect.UpperLeftCorner.Y -= VScrollPos; + CurrentTextRect.UpperLeftCorner.Y -= VScrollPos; CurrentTextRect.LowerRightCorner.Y = CurrentTextRect.UpperLeftCorner.Y + d.Height; CurrentTextRect += FrameRect.UpperLeftCorner; - } - s32 CGUIEditBox::getLineFromPos(s32 pos) { if (!WordWrap && !MultiLine) return 0; - s32 i=0; - while (i < (s32)BrokenTextPositions.size()) - { + s32 i = 0; + while (i < (s32)BrokenTextPositions.size()) { if (BrokenTextPositions[i] > pos) - return i-1; + return i - 1; ++i; } return (s32)BrokenTextPositions.size() - 1; } - void CGUIEditBox::inputChar(wchar_t c) { if (c == 0) @@ -1437,71 +1279,57 @@ void CGUIEditBox::inputString(const core::stringw &str) core::stringw s; u32 len = str.size(); - if (MarkBegin != MarkEnd) - { + if (MarkBegin != MarkEnd) { // replace marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); s.append(str); - s.append( Text.subString(realmend, Text.size()-realmend) ); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; - CursorPos = realmbgn+len; - } - else if ( OverwriteMode ) - { - //check to see if we are at the end of the text - if ( (u32)CursorPos+len < Text.size()) - { + CursorPos = realmbgn + len; + } else if (OverwriteMode) { + // check to see if we are at the end of the text + if ((u32)CursorPos + len < Text.size()) { bool isEOL = false; s32 EOLPos; - for (u32 i = CursorPos; i < CursorPos+len && i < Max; i++) - { - if (Text[i] == L'\n' || Text[i] == L'\r') - { + for (u32 i = CursorPos; i < CursorPos + len && i < Max; i++) { + if (Text[i] == L'\n' || Text[i] == L'\r') { isEOL = true; EOLPos = i; break; } } - if (!isEOL || Text.size()+len <= Max || Max == 0) - { + if (!isEOL || Text.size() + len <= Max || Max == 0) { s = Text.subString(0, CursorPos); s.append(str); - if ( isEOL ) - { - //just keep appending to the current line - //This follows the behavior of other gui libraries behaviors - s.append( Text.subString(EOLPos, Text.size()-EOLPos) ); - } - else - { - //replace the next character - s.append( Text.subString(CursorPos + len,Text.size() - CursorPos - len)); + if (isEOL) { + // just keep appending to the current line + // This follows the behavior of other gui libraries behaviors + s.append(Text.subString(EOLPos, Text.size() - EOLPos)); + } else { + // replace the next character + s.append(Text.subString(CursorPos + len, Text.size() - CursorPos - len)); } Text = s; - CursorPos+=len; + CursorPos += len; } - } - else if (Text.size()+len <= Max || Max == 0) - { + } else if (Text.size() + len <= Max || Max == 0) { // add new character because we are at the end of the string s = Text.subString(0, CursorPos); s.append(str); - s.append( Text.subString(CursorPos+len, Text.size()-CursorPos-len) ); + s.append(Text.subString(CursorPos + len, Text.size() - CursorPos - len)); Text = s; - CursorPos+=len; + CursorPos += len; } - } - else if (Text.size()+len <= Max || Max == 0) - { + } else if (Text.size() + len <= Max || Max == 0) { // add new character s = Text.subString(0, CursorPos); s.append(str); - s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); + s.append(Text.subString(CursorPos, Text.size() - CursorPos)); Text = s; - CursorPos+=len; + CursorPos += len; } BlinkStartTime = os::Timer::getTime(); @@ -1518,12 +1346,12 @@ void CGUIEditBox::calculateScrollPos() if (!AutoScroll) return; - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); if (!font) return; s32 cursLine = getLineFromPos(CursorPos); - if ( cursLine < 0 ) + if (cursLine < 0) return; setTextRect(cursLine); const bool hasBrokenText = MultiLine || WordWrap; @@ -1535,13 +1363,12 @@ void CGUIEditBox::calculateScrollPos() // get cursor area irr::u32 cursorWidth = font->getDimension(CursorChar.c_str()).Width; core::stringw *txtLine = hasBrokenText ? &BrokenText[cursLine] : &Text; - s32 cPos = hasBrokenText ? CursorPos - BrokenTextPositions[cursLine] : CursorPos; // column - s32 cStart = font->getDimension(txtLine->subString(0, cPos).c_str()).Width; // pixels from text-start + s32 cPos = hasBrokenText ? CursorPos - BrokenTextPositions[cursLine] : CursorPos; // column + s32 cStart = font->getDimension(txtLine->subString(0, cPos).c_str()).Width; // pixels from text-start s32 cEnd = cStart + cursorWidth; s32 txtWidth = font->getDimension(txtLine->c_str()).Width; - if ( txtWidth < FrameRect.getWidth() ) - { + if (txtWidth < FrameRect.getWidth()) { // TODO: Needs a clean left and right gap removal depending on HAlign, similar to vertical scrolling tests for top/bottom. // This check just fixes the case where it was most noticable (text smaller than clipping area). @@ -1549,81 +1376,66 @@ void CGUIEditBox::calculateScrollPos() setTextRect(cursLine); } - if ( CurrentTextRect.UpperLeftCorner.X+cStart < FrameRect.UpperLeftCorner.X ) - { + if (CurrentTextRect.UpperLeftCorner.X + cStart < FrameRect.UpperLeftCorner.X) { // cursor to the left of the clipping area - HScrollPos -= FrameRect.UpperLeftCorner.X-(CurrentTextRect.UpperLeftCorner.X+cStart); + HScrollPos -= FrameRect.UpperLeftCorner.X - (CurrentTextRect.UpperLeftCorner.X + cStart); setTextRect(cursLine); // TODO: should show more characters to the left when we're scrolling left // and the cursor reaches the border. - } - else if ( CurrentTextRect.UpperLeftCorner.X+cEnd > FrameRect.LowerRightCorner.X) - { + } else if (CurrentTextRect.UpperLeftCorner.X + cEnd > FrameRect.LowerRightCorner.X) { // cursor to the right of the clipping area - HScrollPos += (CurrentTextRect.UpperLeftCorner.X+cEnd)-FrameRect.LowerRightCorner.X; + HScrollPos += (CurrentTextRect.UpperLeftCorner.X + cEnd) - FrameRect.LowerRightCorner.X; setTextRect(cursLine); } } // calculate vertical scrolling - if (hasBrokenText) - { + if (hasBrokenText) { irr::u32 lineHeight = font->getDimension(L"A").Height + font->getKerningHeight(); // only up to 1 line fits? - if ( lineHeight >= (irr::u32)FrameRect.getHeight() ) - { + if (lineHeight >= (irr::u32)FrameRect.getHeight()) { VScrollPos = 0; setTextRect(cursLine); s32 unscrolledPos = CurrentTextRect.UpperLeftCorner.Y; s32 pivot = FrameRect.UpperLeftCorner.Y; - switch (VAlign) - { - case EGUIA_CENTER: - pivot += FrameRect.getHeight()/2; - unscrolledPos += lineHeight/2; - break; - case EGUIA_LOWERRIGHT: - pivot += FrameRect.getHeight(); - unscrolledPos += lineHeight; - break; - default: - break; + switch (VAlign) { + case EGUIA_CENTER: + pivot += FrameRect.getHeight() / 2; + unscrolledPos += lineHeight / 2; + break; + case EGUIA_LOWERRIGHT: + pivot += FrameRect.getHeight(); + unscrolledPos += lineHeight; + break; + default: + break; } - VScrollPos = unscrolledPos-pivot; + VScrollPos = unscrolledPos - pivot; setTextRect(cursLine); - } - else - { + } else { // First 2 checks are necessary when people delete lines setTextRect(0); - if ( CurrentTextRect.UpperLeftCorner.Y > FrameRect.UpperLeftCorner.Y && VAlign != EGUIA_LOWERRIGHT) - { + if (CurrentTextRect.UpperLeftCorner.Y > FrameRect.UpperLeftCorner.Y && VAlign != EGUIA_LOWERRIGHT) { // first line is leaving a gap on top VScrollPos = 0; - } - else if (VAlign != EGUIA_UPPERLEFT) - { - u32 lastLine = BrokenTextPositions.empty() ? 0 : BrokenTextPositions.size()-1; + } else if (VAlign != EGUIA_UPPERLEFT) { + u32 lastLine = BrokenTextPositions.empty() ? 0 : BrokenTextPositions.size() - 1; setTextRect(lastLine); - if ( CurrentTextRect.LowerRightCorner.Y < FrameRect.LowerRightCorner.Y) - { + if (CurrentTextRect.LowerRightCorner.Y < FrameRect.LowerRightCorner.Y) { // last line is leaving a gap on bottom - VScrollPos -= FrameRect.LowerRightCorner.Y-CurrentTextRect.LowerRightCorner.Y; + VScrollPos -= FrameRect.LowerRightCorner.Y - CurrentTextRect.LowerRightCorner.Y; } } setTextRect(cursLine); - if ( CurrentTextRect.UpperLeftCorner.Y < FrameRect.UpperLeftCorner.Y ) - { + if (CurrentTextRect.UpperLeftCorner.Y < FrameRect.UpperLeftCorner.Y) { // text above valid area - VScrollPos -= FrameRect.UpperLeftCorner.Y-CurrentTextRect.UpperLeftCorner.Y; + VScrollPos -= FrameRect.UpperLeftCorner.Y - CurrentTextRect.UpperLeftCorner.Y; setTextRect(cursLine); - } - else if ( CurrentTextRect.LowerRightCorner.Y > FrameRect.LowerRightCorner.Y) - { + } else if (CurrentTextRect.LowerRightCorner.Y > FrameRect.LowerRightCorner.Y) { // text below valid area - VScrollPos += CurrentTextRect.LowerRightCorner.Y-FrameRect.LowerRightCorner.Y; + VScrollPos += CurrentTextRect.LowerRightCorner.Y - FrameRect.LowerRightCorner.Y; setTextRect(cursLine); } } @@ -1636,20 +1448,18 @@ void CGUIEditBox::calculateFrameRect() IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); - if (Border && skin) - { - FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1; - FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; - FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1; - FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; + if (Border && skin) { + FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; + FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; + FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; + FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; } } //! set text markers void CGUIEditBox::setTextMarkers(s32 begin, s32 end) { - if ( begin != MarkBegin || end != MarkEnd ) - { + if (begin != MarkBegin || end != MarkEnd) { MarkBegin = begin; MarkEnd = end; @@ -1670,8 +1480,7 @@ void CGUIEditBox::setTextMarkers(s32 begin, s32 end) //! send some gui event to parent void CGUIEditBox::sendGuiEvent(EGUI_EVENT_TYPE type) { - if ( Parent ) - { + if (Parent) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; diff --git a/source/Irrlicht/CGUIEditBox.h b/source/Irrlicht/CGUIEditBox.h index 587cda0f..35ab5f73 100644 --- a/source/Irrlicht/CGUIEditBox.h +++ b/source/Irrlicht/CGUIEditBox.h @@ -12,187 +12,185 @@ namespace irr { namespace gui { - class CGUIEditBox : public IGUIEditBox - { - public: +class CGUIEditBox : public IGUIEditBox +{ +public: + //! constructor + CGUIEditBox(const wchar_t *text, bool border, IGUIEnvironment *environment, + IGUIElement *parent, s32 id, const core::rect &rectangle); - //! constructor - CGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, const core::rect& rectangle); + //! destructor + virtual ~CGUIEditBox(); - //! destructor - virtual ~CGUIEditBox(); + //! Sets another skin independent font. + void setOverrideFont(IGUIFont *font = 0) override; - //! Sets another skin independent font. - void setOverrideFont(IGUIFont* font=0) override; + //! Gets the override font (if any) + /** \return The override font (may be 0) */ + IGUIFont *getOverrideFont() const override; - //! Gets the override font (if any) - /** \return The override font (may be 0) */ - IGUIFont* getOverrideFont() const override; + //! Get the font which is used right now for drawing + /** Currently this is the override font when one is set and the + font of the active skin otherwise */ + IGUIFont *getActiveFont() const override; - //! Get the font which is used right now for drawing - /** Currently this is the override font when one is set and the - font of the active skin otherwise */ - IGUIFont* getActiveFont() const override; + //! Sets another color for the text. + void setOverrideColor(video::SColor color) override; - //! Sets another color for the text. - void setOverrideColor(video::SColor color) override; + //! Gets the override color + video::SColor getOverrideColor() const override; - //! Gets the override color - video::SColor getOverrideColor() const override; + //! Sets if the text should use the override color or the + //! color in the gui skin. + void enableOverrideColor(bool enable) override; - //! Sets if the text should use the override color or the - //! color in the gui skin. - void enableOverrideColor(bool enable) override; + //! Checks if an override color is enabled + /** \return true if the override color is enabled, false otherwise */ + bool isOverrideColorEnabled(void) const override; - //! Checks if an override color is enabled - /** \return true if the override color is enabled, false otherwise */ - bool isOverrideColorEnabled(void) const override; + //! Sets whether to draw the background + void setDrawBackground(bool draw) override; - //! Sets whether to draw the background - void setDrawBackground(bool draw) override; + //! Checks if background drawing is enabled + bool isDrawBackgroundEnabled() const override; - //! Checks if background drawing is enabled - bool isDrawBackgroundEnabled() const override; + //! Turns the border on or off + void setDrawBorder(bool border) override; - //! Turns the border on or off - void setDrawBorder(bool border) override; + //! Checks if border drawing is enabled + bool isDrawBorderEnabled() const override; - //! Checks if border drawing is enabled - bool isDrawBorderEnabled() const override; + //! Enables or disables word wrap for using the edit box as multiline text editor. + void setWordWrap(bool enable) override; - //! Enables or disables word wrap for using the edit box as multiline text editor. - void setWordWrap(bool enable) override; + //! Checks if word wrap is enabled + //! \return true if word wrap is enabled, false otherwise + bool isWordWrapEnabled() const override; - //! Checks if word wrap is enabled - //! \return true if word wrap is enabled, false otherwise - bool isWordWrapEnabled() const override; + //! Enables or disables newlines. + /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, + instead a newline character will be inserted. */ + void setMultiLine(bool enable) override; - //! Enables or disables newlines. - /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, - instead a newline character will be inserted. */ - void setMultiLine(bool enable) override; + //! Checks if multi line editing is enabled + //! \return true if mult-line is enabled, false otherwise + bool isMultiLineEnabled() const override; - //! Checks if multi line editing is enabled - //! \return true if mult-line is enabled, false otherwise - bool isMultiLineEnabled() const override; + //! Enables or disables automatic scrolling with cursor position + //! \param enable: If set to true, the text will move around with the cursor position + void setAutoScroll(bool enable) override; - //! Enables or disables automatic scrolling with cursor position - //! \param enable: If set to true, the text will move around with the cursor position - void setAutoScroll(bool enable) override; + //! Checks to see if automatic scrolling is enabled + //! \return true if automatic scrolling is enabled, false if not + bool isAutoScrollEnabled() const override; - //! Checks to see if automatic scrolling is enabled - //! \return true if automatic scrolling is enabled, false if not - bool isAutoScrollEnabled() const override; + //! Gets the size area of the text in the edit box + //! \return Returns the size in pixels of the text + core::dimension2du getTextDimension() override; - //! Gets the size area of the text in the edit box - //! \return Returns the size in pixels of the text - core::dimension2du getTextDimension() override; + //! Sets text justification + void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; - //! Sets text justification - void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! draws the element and its children + void draw() override; - //! draws the element and its children - void draw() override; + //! Sets the new caption of this element. + void setText(const wchar_t *text) override; - //! Sets the new caption of this element. - void setText(const wchar_t* text) override; + //! Sets the maximum amount of characters which may be entered in the box. + //! \param max: Maximum amount of characters. If 0, the character amount is + //! infinity. + void setMax(u32 max) override; - //! Sets the maximum amount of characters which may be entered in the box. - //! \param max: Maximum amount of characters. If 0, the character amount is - //! infinity. - void setMax(u32 max) override; + //! Returns maximum amount of characters, previously set by setMax(); + u32 getMax() const override; - //! Returns maximum amount of characters, previously set by setMax(); - u32 getMax() const override; + //! Set the character used for the cursor. + /** By default it's "_" */ + void setCursorChar(const wchar_t cursorChar) override; - //! Set the character used for the cursor. - /** By default it's "_" */ - void setCursorChar(const wchar_t cursorChar) override; + //! Get the character used for the cursor. + wchar_t getCursorChar() const override; - //! Get the character used for the cursor. - wchar_t getCursorChar() const override; + //! Set the blinktime for the cursor. 2x blinktime is one full cycle. + //** \param timeMs Blinktime in milliseconds. When set to 0 the cursor is constantly on without blinking */ + void setCursorBlinkTime(irr::u32 timeMs) override; - //! Set the blinktime for the cursor. 2x blinktime is one full cycle. - //** \param timeMs Blinktime in milliseconds. When set to 0 the cursor is constantly on without blinking */ - void setCursorBlinkTime(irr::u32 timeMs) override; + //! Get the cursor blinktime + irr::u32 getCursorBlinkTime() const override; - //! Get the cursor blinktime - irr::u32 getCursorBlinkTime() const override; + //! Sets whether the edit box is a password box. Setting this to true will + /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x + \param passwordBox: true to enable password, false to disable + \param passwordChar: the character that is displayed instead of letters */ + void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*') override; - //! Sets whether the edit box is a password box. Setting this to true will - /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x - \param passwordBox: true to enable password, false to disable - \param passwordChar: the character that is displayed instead of letters */ - void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*') override; + //! Returns true if the edit box is currently a password box. + bool isPasswordBox() const override; - //! Returns true if the edit box is currently a password box. - bool isPasswordBox() const override; + //! Updates the absolute position, splits text if required + void updateAbsolutePosition() override; - //! Updates the absolute position, splits text if required - void updateAbsolutePosition() override; + //! Returns whether the element takes input from the IME + bool acceptsIME() override; - //! Returns whether the element takes input from the IME - bool acceptsIME() override; +protected: + //! Breaks the single text line. + void breakText(); + //! sets the area of the given line + void setTextRect(s32 line); + //! returns the line number that the cursor is on + s32 getLineFromPos(s32 pos); + //! adds a letter to the edit box + void inputChar(wchar_t c); + //! adds a string to the edit box + void inputString(const core::stringw &str); + //! calculates the current scroll position + void calculateScrollPos(); + //! calculated the FrameRect + void calculateFrameRect(); + //! send some gui event to parent + void sendGuiEvent(EGUI_EVENT_TYPE type); + //! set text markers + void setTextMarkers(s32 begin, s32 end); + //! delete current selection or next char + bool keyDelete(); - protected: - //! Breaks the single text line. - void breakText(); - //! sets the area of the given line - void setTextRect(s32 line); - //! returns the line number that the cursor is on - s32 getLineFromPos(s32 pos); - //! adds a letter to the edit box - void inputChar(wchar_t c); - //! adds a string to the edit box - void inputString(const core::stringw &str); - //! calculates the current scroll position - void calculateScrollPos(); - //! calculated the FrameRect - void calculateFrameRect(); - //! send some gui event to parent - void sendGuiEvent(EGUI_EVENT_TYPE type); - //! set text markers - void setTextMarkers(s32 begin, s32 end); - //! delete current selection or next char - bool keyDelete(); + bool processKey(const SEvent &event); + bool processMouse(const SEvent &event); + s32 getCursorPos(s32 x, s32 y); - bool processKey(const SEvent& event); - bool processMouse(const SEvent& event); - s32 getCursorPos(s32 x, s32 y); + bool OverwriteMode; + bool MouseMarking; + bool Border; + bool Background; + bool OverrideColorEnabled; + s32 MarkBegin; + s32 MarkEnd; - bool OverwriteMode; - bool MouseMarking; - bool Border; - bool Background; - bool OverrideColorEnabled; - s32 MarkBegin; - s32 MarkEnd; + video::SColor OverrideColor; + gui::IGUIFont *OverrideFont, *LastBreakFont; + IOSOperator *Operator; - video::SColor OverrideColor; - gui::IGUIFont *OverrideFont, *LastBreakFont; - IOSOperator* Operator; + u32 BlinkStartTime; + irr::u32 CursorBlinkTime; + core::stringw CursorChar; // IGUIFont::draw needs stringw instead of wchar_t + s32 CursorPos; + s32 HScrollPos, VScrollPos; // scroll position in characters + u32 Max; - u32 BlinkStartTime; - irr::u32 CursorBlinkTime; - core::stringw CursorChar; // IGUIFont::draw needs stringw instead of wchar_t - s32 CursorPos; - s32 HScrollPos, VScrollPos; // scroll position in characters - u32 Max; + bool WordWrap, MultiLine, AutoScroll, PasswordBox; + wchar_t PasswordChar; + EGUI_ALIGNMENT HAlign, VAlign; - bool WordWrap, MultiLine, AutoScroll, PasswordBox; - wchar_t PasswordChar; - EGUI_ALIGNMENT HAlign, VAlign; - - core::array< core::stringw > BrokenText; - core::array< s32 > BrokenTextPositions; - - core::rect CurrentTextRect, FrameRect; // temporary values - }; + core::array BrokenText; + core::array BrokenTextPositions; + core::rect CurrentTextRect, FrameRect; // temporary values +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIEnvironment.cpp b/source/Irrlicht/CGUIEnvironment.cpp index 130f518c..0fc5e8ca 100644 --- a/source/Irrlicht/CGUIEnvironment.cpp +++ b/source/Irrlicht/CGUIEnvironment.cpp @@ -36,10 +36,10 @@ namespace gui const io::path CGUIEnvironment::DefaultFontName = "#DefaultFont"; //! constructor -CGUIEnvironment::CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* driver, IOSOperator* op) -: IGUIElement(EGUIET_ROOT, 0, 0, 0, core::rect(driver ? core::dimension2d(driver->getScreenSize()) : core::dimension2d(0,0))), - Driver(driver), Hovered(0), HoveredNoSubelement(0), Focus(0), LastHoveredMousePos(0,0), CurrentSkin(0), - FileSystem(fs), UserReceiver(0), Operator(op), FocusFlags(EFF_SET_ON_LMOUSE_DOWN|EFF_SET_ON_TAB) +CGUIEnvironment::CGUIEnvironment(io::IFileSystem *fs, video::IVideoDriver *driver, IOSOperator *op) : + IGUIElement(EGUIET_ROOT, 0, 0, 0, core::rect(driver ? core::dimension2d(driver->getScreenSize()) : core::dimension2d(0, 0))), + Driver(driver), Hovered(0), HoveredNoSubelement(0), Focus(0), LastHoveredMousePos(0, 0), CurrentSkin(0), + FileSystem(fs), UserReceiver(0), Operator(op), FocusFlags(EFF_SET_ON_LMOUSE_DOWN | EFF_SET_ON_TAB) { if (Driver) Driver->grab(); @@ -50,17 +50,17 @@ CGUIEnvironment::CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* drive if (Operator) Operator->grab(); - #ifdef _DEBUG +#ifdef _DEBUG IGUIEnvironment::setDebugName("CGUIEnvironment"); - #endif +#endif loadBuiltInFont(); - IGUISkin* skin = createSkin( gui::EGST_WINDOWS_METALLIC ); + IGUISkin *skin = createSkin(gui::EGST_WINDOWS_METALLIC); setSkin(skin); skin->drop(); - //set tooltip default + // set tooltip default ToolTip.LastTime = 0; ToolTip.EnterTime = 0; ToolTip.LaunchTime = 1000; @@ -72,39 +72,33 @@ CGUIEnvironment::CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* drive setTabGroup(true); } - //! destructor CGUIEnvironment::~CGUIEnvironment() { clearDeletionQueue(); - if ( HoveredNoSubelement && HoveredNoSubelement != this ) - { + if (HoveredNoSubelement && HoveredNoSubelement != this) { HoveredNoSubelement->drop(); HoveredNoSubelement = 0; } - if (Hovered && Hovered != this) - { + if (Hovered && Hovered != this) { Hovered->drop(); Hovered = 0; } - if (Focus) - { + if (Focus) { Focus->drop(); Focus = 0; } - if (ToolTip.Element) - { + if (ToolTip.Element) { ToolTip.Element->drop(); ToolTip.Element = 0; } // drop skin - if (CurrentSkin) - { + if (CurrentSkin) { CurrentSkin->drop(); CurrentSkin = 0; } @@ -112,43 +106,38 @@ CGUIEnvironment::~CGUIEnvironment() u32 i; // delete all sprite banks - for (i=0; idrop(); // delete all fonts - for (i=0; idrop(); - if (Operator) - { + if (Operator) { Operator->drop(); Operator = 0; } - if (FileSystem) - { + if (FileSystem) { FileSystem->drop(); FileSystem = 0; } - if (Driver) - { + if (Driver) { Driver->drop(); Driver = 0; } } - void CGUIEnvironment::loadBuiltInFont() { #ifdef IRR_ENABLE_BUILTIN_FONT - io::IReadFile* file = FileSystem->createMemoryReadFile(BuiltInFontData, - BuiltInFontDataSize, DefaultFontName, false); + io::IReadFile *file = FileSystem->createMemoryReadFile(BuiltInFontData, + BuiltInFontDataSize, DefaultFontName, false); - CGUIFont* font = new CGUIFont(this, DefaultFontName ); - if (!font->load(file)) - { + CGUIFont *font = new CGUIFont(this, DefaultFontName); + if (!font->load(file)) { os::Printer::log("Error: Could not load built-in Font.", ELL_ERROR); font->drop(); file->drop(); @@ -164,20 +153,16 @@ void CGUIEnvironment::loadBuiltInFont() #endif } - //! draws all gui elements void CGUIEnvironment::drawAll(bool useScreenSize) { - if (useScreenSize && Driver) - { + if (useScreenSize && Driver) { core::dimension2d dim(Driver->getScreenSize()); if (AbsoluteRect.LowerRightCorner.X != dim.Width || - AbsoluteRect.UpperLeftCorner.X != 0 || - AbsoluteRect.LowerRightCorner.Y != dim.Height || - AbsoluteRect.UpperLeftCorner.Y != 0 - ) - { - setRelativePosition(core::recti(0,0,dim.Width, dim.Height)); + AbsoluteRect.UpperLeftCorner.X != 0 || + AbsoluteRect.LowerRightCorner.Y != dim.Height || + AbsoluteRect.UpperLeftCorner.Y != 0) { + setRelativePosition(core::recti(0, 0, dim.Width, dim.Height)); } } @@ -186,17 +171,15 @@ void CGUIEnvironment::drawAll(bool useScreenSize) bringToFront(ToolTip.Element); draw(); - OnPostRender ( os::Timer::getTime () ); + OnPostRender(os::Timer::getTime()); clearDeletionQueue(); } - //! sets the focus to an element -bool CGUIEnvironment::setFocus(IGUIElement* element) +bool CGUIEnvironment::setFocus(IGUIElement *element) { - if (Focus == element) - { + if (Focus == element) { return false; } @@ -210,8 +193,7 @@ bool CGUIEnvironment::setFocus(IGUIElement* element) // focus may change or be removed in this call IGUIElement *currentFocus = 0; - if (Focus) - { + if (Focus) { currentFocus = Focus; currentFocus->grab(); SEvent e; @@ -219,8 +201,7 @@ bool CGUIEnvironment::setFocus(IGUIElement* element) e.GUIEvent.Caller = Focus; e.GUIEvent.Element = element; e.GUIEvent.EventType = EGET_ELEMENT_FOCUS_LOST; - if (Focus->OnEvent(e)) - { + if (Focus->OnEvent(e)) { if (element) element->drop(); currentFocus->drop(); @@ -230,8 +211,7 @@ bool CGUIEnvironment::setFocus(IGUIElement* element) currentFocus = 0; } - if (element) - { + if (element) { currentFocus = Focus; if (currentFocus) currentFocus->grab(); @@ -242,8 +222,7 @@ bool CGUIEnvironment::setFocus(IGUIElement* element) e.GUIEvent.Caller = element; e.GUIEvent.Element = Focus; e.GUIEvent.EventType = EGET_ELEMENT_FOCUSED; - if (element->OnEvent(e)) - { + if (element->OnEvent(e)) { if (element) element->drop(); if (currentFocus) @@ -264,37 +243,32 @@ bool CGUIEnvironment::setFocus(IGUIElement* element) return true; } - //! returns the element with the focus -IGUIElement* CGUIEnvironment::getFocus() const +IGUIElement *CGUIEnvironment::getFocus() const { return Focus; } //! returns the element last known to be under the mouse cursor -IGUIElement* CGUIEnvironment::getHovered() const +IGUIElement *CGUIEnvironment::getHovered() const { return Hovered; } - //! removes the focus from an element -bool CGUIEnvironment::removeFocus(IGUIElement* element) +bool CGUIEnvironment::removeFocus(IGUIElement *element) { - if (Focus && Focus==element) - { + if (Focus && Focus == element) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = Focus; e.GUIEvent.Element = 0; e.GUIEvent.EventType = EGET_ELEMENT_FOCUS_LOST; - if (Focus->OnEvent(e)) - { + if (Focus->OnEvent(e)) { return false; } } - if (Focus) - { + if (Focus) { Focus->drop(); Focus = 0; } @@ -302,65 +276,56 @@ bool CGUIEnvironment::removeFocus(IGUIElement* element) return true; } - //! Returns whether the element has focus -bool CGUIEnvironment::hasFocus(const IGUIElement* element, bool checkSubElements) const +bool CGUIEnvironment::hasFocus(const IGUIElement *element, bool checkSubElements) const { if (element == Focus) return true; - if ( !checkSubElements || !element ) + if (!checkSubElements || !element) return false; - IGUIElement* f = Focus; - while ( f && f->isSubElement() ) - { + IGUIElement *f = Focus; + while (f && f->isSubElement()) { f = f->getParent(); - if ( f == element ) + if (f == element) return true; } return false; } - //! returns the current video driver -video::IVideoDriver* CGUIEnvironment::getVideoDriver() const +video::IVideoDriver *CGUIEnvironment::getVideoDriver() const { return Driver; } - //! returns the current file system -io::IFileSystem* CGUIEnvironment::getFileSystem() const +io::IFileSystem *CGUIEnvironment::getFileSystem() const { return FileSystem; } - //! returns a pointer to the OS operator -IOSOperator* CGUIEnvironment::getOSOperator() const +IOSOperator *CGUIEnvironment::getOSOperator() const { return Operator; } - //! clear all GUI elements void CGUIEnvironment::clear() { // Remove the focus - if (Focus) - { + if (Focus) { Focus->drop(); Focus = 0; } - if (Hovered && Hovered != this) - { + if (Hovered && Hovered != this) { Hovered->drop(); Hovered = 0; } - if ( HoveredNoSubelement && HoveredNoSubelement != this) - { + if (HoveredNoSubelement && HoveredNoSubelement != this) { HoveredNoSubelement->drop(); HoveredNoSubelement = 0; } @@ -368,17 +333,12 @@ void CGUIEnvironment::clear() getRootGUIElement()->removeAllChildren(); } - //! called by ui if an event happened. -bool CGUIEnvironment::OnEvent(const SEvent& event) +bool CGUIEnvironment::OnEvent(const SEvent &event) { bool ret = false; - if (UserReceiver - && (event.EventType != EET_MOUSE_INPUT_EVENT) - && (event.EventType != EET_KEY_INPUT_EVENT) - && (event.EventType != EET_GUI_EVENT || event.GUIEvent.Caller != this)) - { + if (UserReceiver && (event.EventType != EET_MOUSE_INPUT_EVENT) && (event.EventType != EET_KEY_INPUT_EVENT) && (event.EventType != EET_GUI_EVENT || event.GUIEvent.Caller != this)) { ret = UserReceiver->OnEvent(event); } @@ -386,27 +346,24 @@ bool CGUIEnvironment::OnEvent(const SEvent& event) } // -void CGUIEnvironment::OnPostRender( u32 time ) +void CGUIEnvironment::OnPostRender(u32 time) { // launch tooltip - if ( ToolTip.Element == 0 && - HoveredNoSubelement && HoveredNoSubelement != this && - (time - ToolTip.EnterTime >= ToolTip.LaunchTime - || (time - ToolTip.LastTime >= ToolTip.RelaunchTime && time - ToolTip.LastTime < ToolTip.LaunchTime)) && - HoveredNoSubelement->getToolTipText().size() && - getSkin() && - getSkin()->getFont(EGDF_TOOLTIP) - ) - { + if (ToolTip.Element == 0 && + HoveredNoSubelement && HoveredNoSubelement != this && + (time - ToolTip.EnterTime >= ToolTip.LaunchTime || (time - ToolTip.LastTime >= ToolTip.RelaunchTime && time - ToolTip.LastTime < ToolTip.LaunchTime)) && + HoveredNoSubelement->getToolTipText().size() && + getSkin() && + getSkin()->getFont(EGDF_TOOLTIP)) { core::rect pos; pos.UpperLeftCorner = LastHoveredMousePos; core::dimension2du dim = getSkin()->getFont(EGDF_TOOLTIP)->getDimension(HoveredNoSubelement->getToolTipText().c_str()); - dim.Width += getSkin()->getSize(EGDS_TEXT_DISTANCE_X)*2; - dim.Height += getSkin()->getSize(EGDS_TEXT_DISTANCE_Y)*2; + dim.Width += getSkin()->getSize(EGDS_TEXT_DISTANCE_X) * 2; + dim.Height += getSkin()->getSize(EGDS_TEXT_DISTANCE_Y) * 2; - pos.UpperLeftCorner.Y -= dim.Height+1; - pos.LowerRightCorner.Y = pos.UpperLeftCorner.Y + dim.Height-1; + pos.UpperLeftCorner.Y -= dim.Height + 1; + pos.LowerRightCorner.Y = pos.UpperLeftCorner.Y + dim.Height - 1; pos.LowerRightCorner.X = pos.UpperLeftCorner.X + dim.Width; pos.constrainTo(getAbsolutePosition()); @@ -424,15 +381,14 @@ void CGUIEnvironment::OnPostRender( u32 time ) ToolTip.Element->setRelativePosition(pos); } - if (ToolTip.Element && ToolTip.Element->isVisible() ) // (isVisible() check only because we might use visibility for ToolTip one day) + if (ToolTip.Element && ToolTip.Element->isVisible()) // (isVisible() check only because we might use visibility for ToolTip one day) { ToolTip.LastTime = time; // got invisible or removed in the meantime? - if ( !HoveredNoSubelement || - !HoveredNoSubelement->isVisible() || - !HoveredNoSubelement->getParent() - ) // got invisible or removed in the meantime? + if (!HoveredNoSubelement || + !HoveredNoSubelement->isVisible() || + !HoveredNoSubelement->getParent()) // got invisible or removed in the meantime? { ToolTip.Element->remove(); ToolTip.Element->drop(); @@ -440,10 +396,10 @@ void CGUIEnvironment::OnPostRender( u32 time ) } } - IGUIElement::OnPostRender ( time ); + IGUIElement::OnPostRender(time); } -void CGUIEnvironment::addToDeletionQueue(IGUIElement* element) +void CGUIEnvironment::addToDeletionQueue(IGUIElement *element) { if (!element) return; @@ -457,8 +413,7 @@ void CGUIEnvironment::clearDeletionQueue() if (DeletionQueue.empty()) return; - for (u32 i=0; iremove(); DeletionQueue[i]->drop(); } @@ -469,14 +424,13 @@ void CGUIEnvironment::clearDeletionQueue() // void CGUIEnvironment::updateHoveredElement(core::position2d mousePos) { - IGUIElement* lastHovered = Hovered; - IGUIElement* lastHoveredNoSubelement = HoveredNoSubelement; + IGUIElement *lastHovered = Hovered; + IGUIElement *lastHoveredNoSubelement = HoveredNoSubelement; LastHoveredMousePos = mousePos; Hovered = getElementFromPoint(mousePos); - if ( ToolTip.Element && Hovered == ToolTip.Element ) - { + if (ToolTip.Element && Hovered == ToolTip.Element) { // When the mouse is over the ToolTip we remove that so it will be re-created at a new position. // Note that ToolTip.EnterTime does not get changed here, so it will be re-created at once. ToolTip.Element->remove(); @@ -489,49 +443,42 @@ void CGUIEnvironment::updateHoveredElement(core::position2d mousePos) // for tooltips we want the element itself and not some of it's subelements HoveredNoSubelement = Hovered; - while ( HoveredNoSubelement && HoveredNoSubelement->isSubElement() ) - { + while (HoveredNoSubelement && HoveredNoSubelement->isSubElement()) { HoveredNoSubelement = HoveredNoSubelement->getParent(); } if (Hovered && Hovered != this) Hovered->grab(); - if ( HoveredNoSubelement && HoveredNoSubelement != this) + if (HoveredNoSubelement && HoveredNoSubelement != this) HoveredNoSubelement->grab(); - if (Hovered != lastHovered) - { + if (Hovered != lastHovered) { SEvent event; event.EventType = EET_GUI_EVENT; - if (lastHovered) - { + if (lastHovered) { event.GUIEvent.Caller = lastHovered; event.GUIEvent.Element = 0; event.GUIEvent.EventType = EGET_ELEMENT_LEFT; lastHovered->OnEvent(event); } - if ( Hovered ) - { - event.GUIEvent.Caller = Hovered; + if (Hovered) { + event.GUIEvent.Caller = Hovered; event.GUIEvent.Element = Hovered; event.GUIEvent.EventType = EGET_ELEMENT_HOVERED; Hovered->OnEvent(event); } } - if ( lastHoveredNoSubelement != HoveredNoSubelement ) - { - if (ToolTip.Element) - { + if (lastHoveredNoSubelement != HoveredNoSubelement) { + if (ToolTip.Element) { ToolTip.Element->remove(); ToolTip.Element->drop(); ToolTip.Element = 0; } - if ( HoveredNoSubelement ) - { + if (HoveredNoSubelement) { u32 now = os::Timer::getTime(); ToolTip.EnterTime = now; } @@ -543,52 +490,42 @@ void CGUIEnvironment::updateHoveredElement(core::position2d mousePos) lastHoveredNoSubelement->drop(); } - //! This sets a new event receiver for gui events. Usually you do not have to //! use this method, it is used by the internal engine. -void CGUIEnvironment::setUserEventReceiver(IEventReceiver* evr) +void CGUIEnvironment::setUserEventReceiver(IEventReceiver *evr) { UserReceiver = evr; } - //! posts an input event to the environment -bool CGUIEnvironment::postEventFromUser(const SEvent& event) +bool CGUIEnvironment::postEventFromUser(const SEvent &event) { - switch(event.EventType) - { - case EET_GUI_EVENT: - { - // hey, why is the user sending gui events..? - } + switch (event.EventType) { + case EET_GUI_EVENT: { + // hey, why is the user sending gui events..? + } - break; + break; case EET_MOUSE_INPUT_EVENT: updateHoveredElement(core::position2d(event.MouseInput.X, event.MouseInput.Y)); - if ( Hovered != Focus ) - { - IGUIElement * focusCandidate = Hovered; + if (Hovered != Focus) { + IGUIElement *focusCandidate = Hovered; // Only allow enabled elements to be focused (unless EFF_CAN_FOCUS_DISABLED is set) - if ( Hovered && !Hovered->isEnabled() && !(FocusFlags & EFF_CAN_FOCUS_DISABLED)) - focusCandidate = NULL; // we still remove focus from the active element + if (Hovered && !Hovered->isEnabled() && !(FocusFlags & EFF_CAN_FOCUS_DISABLED)) + focusCandidate = NULL; // we still remove focus from the active element // Please don't merge this into a single if clause, it's easier to debug the way it is if (FocusFlags & EFF_SET_ON_LMOUSE_DOWN && - event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN ) - { + event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { setFocus(focusCandidate); - } - else if ( FocusFlags & EFF_SET_ON_RMOUSE_DOWN && - event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN ) - { + } else if (FocusFlags & EFF_SET_ON_RMOUSE_DOWN && + event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN) { setFocus(focusCandidate); - } - else if ( FocusFlags & EFF_SET_ON_MOUSE_OVER && - event.MouseInput.Event == EMIE_MOUSE_MOVED ) - { + } else if (FocusFlags & EFF_SET_ON_MOUSE_OVER && + event.MouseInput.Event == EMIE_MOUSE_MOVED) { setFocus(focusCandidate); } } @@ -598,33 +535,28 @@ bool CGUIEnvironment::postEventFromUser(const SEvent& event) return true; // focus could have died in last call - if (!Focus && Hovered) - { + if (!Focus && Hovered) { return Hovered->OnEvent(event); } break; - case EET_KEY_INPUT_EVENT: - { - if (Focus && Focus->OnEvent(event)) - return true; + case EET_KEY_INPUT_EVENT: { + if (Focus && Focus->OnEvent(event)) + return true; - // For keys we handle the event before changing focus to give elements the chance for catching the TAB - // Send focus changing event - // CAREFUL when changing - there's an identical check in CGUIModalScreen::OnEvent - if (FocusFlags & EFF_SET_ON_TAB && + // For keys we handle the event before changing focus to give elements the chance for catching the TAB + // Send focus changing event + // CAREFUL when changing - there's an identical check in CGUIModalScreen::OnEvent + if (FocusFlags & EFF_SET_ON_TAB && event.KeyInput.PressedDown && - event.KeyInput.Key == KEY_TAB) - { - IGUIElement *next = getNextElement(event.KeyInput.Shift, event.KeyInput.Control); - if (next && next != Focus) - { - if (setFocus(next)) - return true; - } + event.KeyInput.Key == KEY_TAB) { + IGUIElement *next = getNextElement(event.KeyInput.Shift, event.KeyInput.Control); + if (next && next != Focus) { + if (setFocus(next)) + return true; } } - break; + } break; case EET_STRING_INPUT_EVENT: if (Focus && Focus->OnEvent(event)) return true; @@ -636,18 +568,16 @@ bool CGUIEnvironment::postEventFromUser(const SEvent& event) return false; } - //! returns the current gui skin -IGUISkin* CGUIEnvironment::getSkin() const +IGUISkin *CGUIEnvironment::getSkin() const { return CurrentSkin; } - //! Sets a new GUI Skin -void CGUIEnvironment::setSkin(IGUISkin* skin) +void CGUIEnvironment::setSkin(IGUISkin *skin) { - if (CurrentSkin==skin) + if (CurrentSkin == skin) return; if (CurrentSkin) @@ -659,21 +589,20 @@ void CGUIEnvironment::setSkin(IGUISkin* skin) CurrentSkin->grab(); } - //! Creates a new GUI Skin based on a template. /** \return Returns a pointer to the created skin. If you no longer need the skin, you should call IGUISkin::drop(). See IReferenceCounted::drop() for more information. */ -IGUISkin* CGUIEnvironment::createSkin(EGUI_SKIN_TYPE type) +IGUISkin *CGUIEnvironment::createSkin(EGUI_SKIN_TYPE type) { - IGUISkin* skin = new CGUISkin(type, Driver); + IGUISkin *skin = new CGUISkin(type, Driver); - IGUIFont* builtinfont = getBuiltInFont(); - IGUIFontBitmap* bitfont = 0; + IGUIFont *builtinfont = getBuiltInFont(); + IGUIFontBitmap *bitfont = 0; if (builtinfont && builtinfont->getType() == EGFT_BITMAP) - bitfont = (IGUIFontBitmap*)builtinfont; + bitfont = (IGUIFontBitmap *)builtinfont; - IGUISpriteBank* bank = 0; + IGUISpriteBank *bank = 0; skin->setFont(builtinfont); if (bitfont) @@ -684,41 +613,38 @@ IGUISkin* CGUIEnvironment::createSkin(EGUI_SKIN_TYPE type) return skin; } - //! adds a button. The returned pointer must not be dropped. -IGUIButton* CGUIEnvironment::addButton(const core::rect& rectangle, IGUIElement* parent, s32 id, const wchar_t* text, const wchar_t *tooltiptext) +IGUIButton *CGUIEnvironment::addButton(const core::rect &rectangle, IGUIElement *parent, s32 id, const wchar_t *text, const wchar_t *tooltiptext) { - IGUIButton* button = new CGUIButton(this, parent ? parent : this, id, rectangle); + IGUIButton *button = new CGUIButton(this, parent ? parent : this, id, rectangle); if (text) button->setText(text); - if ( tooltiptext ) - button->setToolTipText ( tooltiptext ); + if (tooltiptext) + button->setToolTipText(tooltiptext); button->drop(); return button; } - //! adds a scrollbar. The returned pointer must not be dropped. -IGUIScrollBar* CGUIEnvironment::addScrollBar(bool horizontal, const core::rect& rectangle, IGUIElement* parent, s32 id) +IGUIScrollBar *CGUIEnvironment::addScrollBar(bool horizontal, const core::rect &rectangle, IGUIElement *parent, s32 id) { - IGUIScrollBar* bar = new CGUIScrollBar(horizontal, this, parent ? parent : this, id, rectangle); + IGUIScrollBar *bar = new CGUIScrollBar(horizontal, this, parent ? parent : this, id, rectangle); bar->drop(); return bar; } - //! Adds an image element. -IGUIImage* CGUIEnvironment::addImage(video::ITexture* image, core::position2d pos, - bool useAlphaChannel, IGUIElement* parent, s32 id, const wchar_t* text) +IGUIImage *CGUIEnvironment::addImage(video::ITexture *image, core::position2d pos, + bool useAlphaChannel, IGUIElement *parent, s32 id, const wchar_t *text) { - core::dimension2d sz(0,0); + core::dimension2d sz(0, 0); if (image) sz = core::dimension2d(image->getOriginalSize()); - IGUIImage* img = new CGUIImage(this, parent ? parent : this, - id, core::rect(pos, sz)); + IGUIImage *img = new CGUIImage(this, parent ? parent : this, + id, core::rect(pos, sz)); if (text) img->setText(text); @@ -733,29 +659,27 @@ IGUIImage* CGUIEnvironment::addImage(video::ITexture* image, core::position2d& rectangle, IGUIElement* parent, s32 id, const wchar_t* text, bool useAlphaChannel) +IGUIImage *CGUIEnvironment::addImage(const core::rect &rectangle, IGUIElement *parent, s32 id, const wchar_t *text, bool useAlphaChannel) { - IGUIImage* img = new CGUIImage(this, parent ? parent : this, - id, rectangle); + IGUIImage *img = new CGUIImage(this, parent ? parent : this, + id, rectangle); if (text) img->setText(text); - if ( useAlphaChannel ) + if (useAlphaChannel) img->setUseAlphaChannel(true); img->drop(); return img; } - //! adds a checkbox -IGUICheckBox* CGUIEnvironment::addCheckBox(bool checked, const core::rect& rectangle, IGUIElement* parent, s32 id, const wchar_t* text) +IGUICheckBox *CGUIEnvironment::addCheckBox(bool checked, const core::rect &rectangle, IGUIElement *parent, s32 id, const wchar_t *text) { - IGUICheckBox* b = new CGUICheckBox(checked, this, - parent ? parent : this , id , rectangle); + IGUICheckBox *b = new CGUICheckBox(checked, this, + parent ? parent : this, id, rectangle); if (text) b->setText(text); @@ -764,53 +688,47 @@ IGUICheckBox* CGUIEnvironment::addCheckBox(bool checked, const core::rect& return b; } - //! adds a list box -IGUIListBox* CGUIEnvironment::addListBox(const core::rect& rectangle, - IGUIElement* parent, s32 id, bool drawBackground) +IGUIListBox *CGUIEnvironment::addListBox(const core::rect &rectangle, + IGUIElement *parent, s32 id, bool drawBackground) { - IGUIListBox* b = new CGUIListBox(this, parent ? parent : this, id, rectangle, - true, drawBackground, false); + IGUIListBox *b = new CGUIListBox(this, parent ? parent : this, id, rectangle, + true, drawBackground, false); - if (CurrentSkin && CurrentSkin->getSpriteBank()) - { + if (CurrentSkin && CurrentSkin->getSpriteBank()) { b->setSpriteBank(CurrentSkin->getSpriteBank()); - } - else if (getBuiltInFont() && getBuiltInFont()->getType() == EGFT_BITMAP) - { - b->setSpriteBank( ((IGUIFontBitmap*)getBuiltInFont())->getSpriteBank()); + } else if (getBuiltInFont() && getBuiltInFont()->getType() == EGFT_BITMAP) { + b->setSpriteBank(((IGUIFontBitmap *)getBuiltInFont())->getSpriteBank()); } b->drop(); return b; } - //! adds a file open dialog. The returned pointer must not be dropped. -IGUIFileOpenDialog* CGUIEnvironment::addFileOpenDialog(const wchar_t* title, - bool modal, IGUIElement* parent, s32 id, - bool restoreCWD, io::path::char_type* startDir) +IGUIFileOpenDialog *CGUIEnvironment::addFileOpenDialog(const wchar_t *title, + bool modal, IGUIElement *parent, s32 id, + bool restoreCWD, io::path::char_type *startDir) { parent = parent ? parent : this; if (modal) return nullptr; - IGUIFileOpenDialog* d = new CGUIFileOpenDialog(title, this, parent, id, + IGUIFileOpenDialog *d = new CGUIFileOpenDialog(title, this, parent, id, restoreCWD, startDir); d->drop(); return d; } - //! adds a static text. The returned pointer must not be dropped. -IGUIStaticText* CGUIEnvironment::addStaticText(const wchar_t* text, - const core::rect& rectangle, - bool border, bool wordWrap, - IGUIElement* parent, s32 id, bool background) +IGUIStaticText *CGUIEnvironment::addStaticText(const wchar_t *text, + const core::rect &rectangle, + bool border, bool wordWrap, + IGUIElement *parent, s32 id, bool background) { - IGUIStaticText* d = new CGUIStaticText(text, border, this, + IGUIStaticText *d = new CGUIStaticText(text, border, this, parent ? parent : this, id, rectangle, background); d->setWordWrap(wordWrap); @@ -819,55 +737,50 @@ IGUIStaticText* CGUIEnvironment::addStaticText(const wchar_t* text, return d; } - //! Adds an edit box. The returned pointer must not be dropped. -IGUIEditBox* CGUIEnvironment::addEditBox(const wchar_t* text, - const core::rect& rectangle, bool border, - IGUIElement* parent, s32 id) +IGUIEditBox *CGUIEnvironment::addEditBox(const wchar_t *text, + const core::rect &rectangle, bool border, + IGUIElement *parent, s32 id) { - IGUIEditBox* d = new CGUIEditBox(text, border, this, + IGUIEditBox *d = new CGUIEditBox(text, border, this, parent ? parent : this, id, rectangle); d->drop(); return d; } - //! Adds a tab control to the environment. -IGUITabControl* CGUIEnvironment::addTabControl(const core::rect& rectangle, - IGUIElement* parent, bool fillbackground, bool border, s32 id) +IGUITabControl *CGUIEnvironment::addTabControl(const core::rect &rectangle, + IGUIElement *parent, bool fillbackground, bool border, s32 id) { - IGUITabControl* t = new CGUITabControl(this, parent ? parent : this, - rectangle, fillbackground, border, id); + IGUITabControl *t = new CGUITabControl(this, parent ? parent : this, + rectangle, fillbackground, border, id); t->drop(); return t; } - //! Adds tab to the environment. -IGUITab* CGUIEnvironment::addTab(const core::rect& rectangle, - IGUIElement* parent, s32 id) +IGUITab *CGUIEnvironment::addTab(const core::rect &rectangle, + IGUIElement *parent, s32 id) { - IGUITab* t = new CGUITab(this, parent ? parent : this, - rectangle, id); + IGUITab *t = new CGUITab(this, parent ? parent : this, + rectangle, id); t->drop(); return t; } - //! Adds a combo box to the environment. -IGUIComboBox* CGUIEnvironment::addComboBox(const core::rect& rectangle, - IGUIElement* parent, s32 id) +IGUIComboBox *CGUIEnvironment::addComboBox(const core::rect &rectangle, + IGUIElement *parent, s32 id) { - IGUIComboBox* t = new CGUIComboBox(this, parent ? parent : this, - id, rectangle); + IGUIComboBox *t = new CGUIComboBox(this, parent ? parent : this, + id, rectangle); t->drop(); return t; } - //! returns the font -IGUIFont* CGUIEnvironment::getFont(const io::path& filename) +IGUIFont *CGUIEnvironment::getFont(const io::path &filename) { // search existing font @@ -882,13 +795,12 @@ IGUIFont* CGUIEnvironment::getFont(const io::path& filename) // does the file exist? - if (!FileSystem->existFile(filename)) - { + if (!FileSystem->existFile(filename)) { os::Printer::log("Could not load font because the file does not exist", f.NamedPath.getPath(), ELL_ERROR); return 0; } - IGUIFont* ifont=0; + IGUIFont *ifont = 0; #if 0 { CGUIFont* font = new CGUIFont(this, filename); @@ -906,14 +818,11 @@ IGUIFont* CGUIEnvironment::getFont(const io::path& filename) } #endif + if (!ifont) { - if (!ifont) - { - - CGUIFont* font = new CGUIFont(this, f.NamedPath.getPath() ); - ifont = (IGUIFont*)font; - if (!font->load(f.NamedPath.getPath())) - { + CGUIFont *font = new CGUIFont(this, f.NamedPath.getPath()); + ifont = (IGUIFont *)font; + if (!font->load(f.NamedPath.getPath())) { font->drop(); return 0; } @@ -927,12 +836,10 @@ IGUIFont* CGUIEnvironment::getFont(const io::path& filename) return ifont; } - //! add an externally loaded font -IGUIFont* CGUIEnvironment::addFont(const io::path& name, IGUIFont* font) +IGUIFont *CGUIEnvironment::addFont(const io::path &name, IGUIFont *font) { - if (font) - { + if (font) { SFont f; f.NamedPath.setPath(name); s32 index = Fonts.binary_search(f); @@ -946,14 +853,12 @@ IGUIFont* CGUIEnvironment::addFont(const io::path& name, IGUIFont* font) } //! remove loaded font -void CGUIEnvironment::removeFont(IGUIFont* font) +void CGUIEnvironment::removeFont(IGUIFont *font) { - if ( !font ) + if (!font) return; - for ( u32 i=0; idrop(); Fonts.erase(i); return; @@ -962,7 +867,7 @@ void CGUIEnvironment::removeFont(IGUIFont* font) } //! returns default font -IGUIFont* CGUIEnvironment::getBuiltInFont() const +IGUIFont *CGUIEnvironment::getBuiltInFont() const { if (Fonts.empty()) return 0; @@ -970,8 +875,7 @@ IGUIFont* CGUIEnvironment::getBuiltInFont() const return Fonts[0].Font; } - -IGUISpriteBank* CGUIEnvironment::getSpriteBank(const io::path& filename) +IGUISpriteBank *CGUIEnvironment::getSpriteBank(const io::path &filename) { // search for the file name @@ -983,10 +887,8 @@ IGUISpriteBank* CGUIEnvironment::getSpriteBank(const io::path& filename) return Banks[index].Bank; // we don't have this sprite bank, we should load it - if (!FileSystem->existFile(b.NamedPath.getPath())) - { - if ( filename != DefaultFontName ) - { + if (!FileSystem->existFile(b.NamedPath.getPath())) { + if (filename != DefaultFontName) { os::Printer::log("Could not load sprite bank because the file does not exist", b.NamedPath.getPath(), ELL_DEBUG); } return 0; @@ -997,8 +899,7 @@ IGUISpriteBank* CGUIEnvironment::getSpriteBank(const io::path& filename) return 0; } - -IGUISpriteBank* CGUIEnvironment::addEmptySpriteBank(const io::path& name) +IGUISpriteBank *CGUIEnvironment::addEmptySpriteBank(const io::path &name) { // no duplicate names allowed @@ -1017,14 +918,12 @@ IGUISpriteBank* CGUIEnvironment::addEmptySpriteBank(const io::path& name) return b.Bank; } - //! Creates the image list from the given texture. -IGUIImageList* CGUIEnvironment::createImageList( video::ITexture* texture, - core::dimension2d imageSize, bool useAlphaChannel ) +IGUIImageList *CGUIEnvironment::createImageList(video::ITexture *texture, + core::dimension2d imageSize, bool useAlphaChannel) { - CGUIImageList* imageList = new CGUIImageList( Driver ); - if( !imageList->createImageList( texture, imageSize, useAlphaChannel ) ) - { + CGUIImageList *imageList = new CGUIImageList(Driver); + if (!imageList->createImageList(texture, imageSize, useAlphaChannel)) { imageList->drop(); return 0; } @@ -1033,39 +932,31 @@ IGUIImageList* CGUIEnvironment::createImageList( video::ITexture* texture, } //! Returns the root gui element. -IGUIElement* CGUIEnvironment::getRootGUIElement() +IGUIElement *CGUIEnvironment::getRootGUIElement() { return this; } - //! Returns the next element in the tab group starting at the focused element -IGUIElement* CGUIEnvironment::getNextElement(bool reverse, bool group) +IGUIElement *CGUIEnvironment::getNextElement(bool reverse, bool group) { // start the search at the root of the current tab group IGUIElement *startPos = Focus ? Focus->getTabGroup() : 0; s32 startOrder = -1; // if we're searching for a group - if (group && startPos) - { + if (group && startPos) { startOrder = startPos->getTabOrder(); - } - else - if (!group && Focus && !Focus->isTabGroup()) - { + } else if (!group && Focus && !Focus->isTabGroup()) { startOrder = Focus->getTabOrder(); - if (startOrder == -1) - { + if (startOrder == -1) { // this element is not part of the tab cycle, // but its parent might be... IGUIElement *el = Focus; - while (el && el->getParent() && startOrder == -1) - { + while (el && el->getParent() && startOrder == -1) { el = el->getParent(); startOrder = el->getTabOrder(); } - } } @@ -1098,13 +989,12 @@ u32 CGUIEnvironment::getFocusBehavior() const } //! creates an GUI Environment -IGUIEnvironment* createGUIEnvironment(io::IFileSystem* fs, - video::IVideoDriver* Driver, - IOSOperator* op) +IGUIEnvironment *createGUIEnvironment(io::IFileSystem *fs, + video::IVideoDriver *Driver, + IOSOperator *op) { return new CGUIEnvironment(fs, Driver, op); } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIEnvironment.h b/source/Irrlicht/CGUIEnvironment.h index 464d89ff..b03c6f0d 100644 --- a/source/Irrlicht/CGUIEnvironment.h +++ b/source/Irrlicht/CGUIEnvironment.h @@ -19,9 +19,8 @@ namespace gui class CGUIEnvironment : public IGUIEnvironment, public IGUIElement { public: - //! constructor - CGUIEnvironment(io::IFileSystem* fs, video::IVideoDriver* driver, IOSOperator* op); + CGUIEnvironment(io::IFileSystem *fs, video::IVideoDriver *driver, IOSOperator *op); //! destructor virtual ~CGUIEnvironment(); @@ -30,131 +29,131 @@ public: void drawAll(bool useScreenSize) override; //! returns the current video driver - video::IVideoDriver* getVideoDriver() const override; + video::IVideoDriver *getVideoDriver() const override; //! returns pointer to the filesystem - io::IFileSystem* getFileSystem() const override; + io::IFileSystem *getFileSystem() const override; //! returns a pointer to the OS operator - IOSOperator* getOSOperator() const override; + IOSOperator *getOSOperator() const override; //! posts an input event to the environment - bool postEventFromUser(const SEvent& event) override; + bool postEventFromUser(const SEvent &event) override; //! This sets a new event receiver for gui events. Usually you do not have to //! use this method, it is used by the internal engine. - void setUserEventReceiver(IEventReceiver* evr) override; + void setUserEventReceiver(IEventReceiver *evr) override; //! removes all elements from the environment void clear() override; //! called if an event happened. - bool OnEvent(const SEvent& event) override; + bool OnEvent(const SEvent &event) override; //! returns the current gui skin - IGUISkin* getSkin() const override; + IGUISkin *getSkin() const override; //! Sets a new GUI Skin - void setSkin(IGUISkin* skin) override; + void setSkin(IGUISkin *skin) override; //! Creates a new GUI Skin based on a template. /** \return Returns a pointer to the created skin. If you no longer need the skin, you should call IGUISkin::drop(). See IReferenceCounted::drop() for more information. */ - IGUISkin* createSkin(EGUI_SKIN_TYPE type) override; + IGUISkin *createSkin(EGUI_SKIN_TYPE type) override; //! Creates the image list from the given texture. - virtual IGUIImageList* createImageList(video::ITexture* texture, - core::dimension2d imageSize, bool useAlphaChannel) override; + virtual IGUIImageList *createImageList(video::ITexture *texture, + core::dimension2d imageSize, bool useAlphaChannel) override; //! returns the font - IGUIFont* getFont(const io::path& filename) override; + IGUIFont *getFont(const io::path &filename) override; //! add an externally loaded font - IGUIFont* addFont(const io::path& name, IGUIFont* font) override; + IGUIFont *addFont(const io::path &name, IGUIFont *font) override; //! remove loaded font - void removeFont(IGUIFont* font) override; + void removeFont(IGUIFont *font) override; //! returns default font - IGUIFont* getBuiltInFont() const override; + IGUIFont *getBuiltInFont() const override; //! returns the sprite bank - IGUISpriteBank* getSpriteBank(const io::path& filename) override; + IGUISpriteBank *getSpriteBank(const io::path &filename) override; //! returns the sprite bank - IGUISpriteBank* addEmptySpriteBank(const io::path& name) override; + IGUISpriteBank *addEmptySpriteBank(const io::path &name) override; //! adds an button. The returned pointer must not be dropped. - IGUIButton* addButton(const core::rect& rectangle, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0,const wchar_t* tooltiptext = 0) override; + IGUIButton *addButton(const core::rect &rectangle, IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0, const wchar_t *tooltiptext = 0) override; //! adds a scrollbar. The returned pointer must not be dropped. - virtual IGUIScrollBar* addScrollBar(bool horizontal, const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) override; + virtual IGUIScrollBar *addScrollBar(bool horizontal, const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) override; //! Adds an image element. - virtual IGUIImage* addImage(video::ITexture* image, core::position2d pos, - bool useAlphaChannel=true, IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0) override; + virtual IGUIImage *addImage(video::ITexture *image, core::position2d pos, + bool useAlphaChannel = true, IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0) override; //! adds an image. The returned pointer must not be dropped. - virtual IGUIImage* addImage(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0, bool useAlphaChannel=true) override; + virtual IGUIImage *addImage(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0, bool useAlphaChannel = true) override; //! adds a checkbox - virtual IGUICheckBox* addCheckBox(bool checked, const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, const wchar_t* text=0) override; + virtual IGUICheckBox *addCheckBox(bool checked, const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, const wchar_t *text = 0) override; //! adds a list box - virtual IGUIListBox* addListBox(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1, bool drawBackground=false) override; + virtual IGUIListBox *addListBox(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1, bool drawBackground = false) override; //! Adds a file open dialog. - virtual IGUIFileOpenDialog* addFileOpenDialog(const wchar_t* title = 0, - bool modal=true, IGUIElement* parent=0, s32 id=-1, - bool restoreCWD=false, io::path::char_type* startDir=0) override; + virtual IGUIFileOpenDialog *addFileOpenDialog(const wchar_t *title = 0, + bool modal = true, IGUIElement *parent = 0, s32 id = -1, + bool restoreCWD = false, io::path::char_type *startDir = 0) override; //! adds a static text. The returned pointer must not be dropped. - virtual IGUIStaticText* addStaticText(const wchar_t* text, const core::rect& rectangle, - bool border=false, bool wordWrap=true, IGUIElement* parent=0, s32 id=-1, bool drawBackground = false) override; + virtual IGUIStaticText *addStaticText(const wchar_t *text, const core::rect &rectangle, + bool border = false, bool wordWrap = true, IGUIElement *parent = 0, s32 id = -1, bool drawBackground = false) override; //! Adds an edit box. The returned pointer must not be dropped. - virtual IGUIEditBox* addEditBox(const wchar_t* text, const core::rect& rectangle, - bool border=false, IGUIElement* parent=0, s32 id=-1) override; + virtual IGUIEditBox *addEditBox(const wchar_t *text, const core::rect &rectangle, + bool border = false, IGUIElement *parent = 0, s32 id = -1) override; //! Adds a tab control to the environment. - virtual IGUITabControl* addTabControl(const core::rect& rectangle, - IGUIElement* parent=0, bool fillbackground=false, bool border=true, s32 id=-1) override; + virtual IGUITabControl *addTabControl(const core::rect &rectangle, + IGUIElement *parent = 0, bool fillbackground = false, bool border = true, s32 id = -1) override; //! Adds tab to the environment. - virtual IGUITab* addTab(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) override; + virtual IGUITab *addTab(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) override; //! Adds a combo box to the environment. - virtual IGUIComboBox* addComboBox(const core::rect& rectangle, - IGUIElement* parent=0, s32 id=-1) override; + virtual IGUIComboBox *addComboBox(const core::rect &rectangle, + IGUIElement *parent = 0, s32 id = -1) override; //! sets the focus to an element - bool setFocus(IGUIElement* element) override; + bool setFocus(IGUIElement *element) override; //! removes the focus from an element - bool removeFocus(IGUIElement* element) override; + bool removeFocus(IGUIElement *element) override; //! Returns if the element has focus - bool hasFocus(const IGUIElement* element, bool checkSubElements=false) const override; + bool hasFocus(const IGUIElement *element, bool checkSubElements = false) const override; //! Returns the element with the focus - IGUIElement* getFocus() const override; + IGUIElement *getFocus() const override; //! Returns the element last known to be under the mouse - IGUIElement* getHovered() const override; + IGUIElement *getHovered() const override; //! Returns the root gui element. - IGUIElement* getRootGUIElement() override; + IGUIElement *getRootGUIElement() override; - void OnPostRender( u32 time ) override; + void OnPostRender(u32 time) override; //! Find the next element which would be selected when pressing the tab-key - IGUIElement* getNextElement(bool reverse=false, bool group=false) override; + IGUIElement *getNextElement(bool reverse = false, bool group = false) override; //! Set the way the gui will handle focus changes void setFocusBehavior(u32 flags) override; @@ -163,10 +162,9 @@ public: u32 getFocusBehavior() const override; //! Adds a IGUIElement to deletion queue. - void addToDeletionQueue(IGUIElement* element) override; + void addToDeletionQueue(IGUIElement *element) override; private: - //! clears the deletion queue void clearDeletionQueue(); @@ -177,9 +175,9 @@ private: struct SFont { io::SNamedPath NamedPath; - IGUIFont* Font; + IGUIFont *Font; - bool operator < (const SFont& other) const + bool operator<(const SFont &other) const { return (NamedPath < other.NamedPath); } @@ -188,9 +186,9 @@ private: struct SSpriteBank { io::SNamedPath NamedPath; - IGUISpriteBank* Bank; + IGUISpriteBank *Bank; - bool operator < (const SSpriteBank& other) const + bool operator<(const SSpriteBank &other) const { return (NamedPath < other.NamedPath); } @@ -198,7 +196,7 @@ private: struct SToolTip { - IGUIStaticText* Element; + IGUIStaticText *Element; u32 LastTime; u32 EnterTime; u32 LaunchTime; @@ -209,17 +207,17 @@ private: core::array Fonts; core::array Banks; - video::IVideoDriver* Driver; - IGUIElement* Hovered; - IGUIElement* HoveredNoSubelement; // subelements replaced by their parent, so you only have 'real' elements here - IGUIElement* Focus; + video::IVideoDriver *Driver; + IGUIElement *Hovered; + IGUIElement *HoveredNoSubelement; // subelements replaced by their parent, so you only have 'real' elements here + IGUIElement *Focus; core::position2d LastHoveredMousePos; - IGUISkin* CurrentSkin; - io::IFileSystem* FileSystem; - IEventReceiver* UserReceiver; - IOSOperator* Operator; + IGUISkin *CurrentSkin; + io::IFileSystem *FileSystem; + IEventReceiver *UserReceiver; + IOSOperator *Operator; u32 FocusFlags; - core::array DeletionQueue; + core::array DeletionQueue; static const io::path DefaultFontName; }; diff --git a/source/Irrlicht/CGUIFileOpenDialog.cpp b/source/Irrlicht/CGUIFileOpenDialog.cpp index ef1bcbce..1e669b25 100644 --- a/source/Irrlicht/CGUIFileOpenDialog.cpp +++ b/source/Irrlicht/CGUIFileOpenDialog.cpp @@ -22,46 +22,41 @@ namespace gui const s32 FOD_WIDTH = 350; const s32 FOD_HEIGHT = 250; - //! constructor -CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t* title, - IGUIEnvironment* environment, IGUIElement* parent, s32 id, - bool restoreCWD, io::path::char_type* startDir) -: IGUIFileOpenDialog(environment, parent, id, - core::rect((parent->getAbsolutePosition().getWidth()-FOD_WIDTH)/2, - (parent->getAbsolutePosition().getHeight()-FOD_HEIGHT)/2, - (parent->getAbsolutePosition().getWidth()-FOD_WIDTH)/2+FOD_WIDTH, - (parent->getAbsolutePosition().getHeight()-FOD_HEIGHT)/2+FOD_HEIGHT)), - FileNameText(0), FileList(0), Dragging(false) +CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t *title, + IGUIEnvironment *environment, IGUIElement *parent, s32 id, + bool restoreCWD, io::path::char_type *startDir) : + IGUIFileOpenDialog(environment, parent, id, + core::rect((parent->getAbsolutePosition().getWidth() - FOD_WIDTH) / 2, + (parent->getAbsolutePosition().getHeight() - FOD_HEIGHT) / 2, + (parent->getAbsolutePosition().getWidth() - FOD_WIDTH) / 2 + FOD_WIDTH, + (parent->getAbsolutePosition().getHeight() - FOD_HEIGHT) / 2 + FOD_HEIGHT)), + FileNameText(0), FileList(0), Dragging(false) { - #ifdef _DEBUG +#ifdef _DEBUG IGUIElement::setDebugName("CGUIFileOpenDialog"); - #endif +#endif Text = title; - FileSystem = Environment?Environment->getFileSystem():0; + FileSystem = Environment ? Environment->getFileSystem() : 0; - if (FileSystem) - { + if (FileSystem) { FileSystem->grab(); if (restoreCWD) RestoreDirectory = FileSystem->getWorkingDirectory(); - if (startDir) - { + if (startDir) { StartDirectory = startDir; FileSystem->changeWorkingDirectoryTo(startDir); } - } - else + } else return; - IGUISpriteBank* sprites = 0; - video::SColor color(255,255,255,255); - IGUISkin* skin = Environment->getSkin(); - if (skin) - { + IGUISpriteBank *sprites = 0; + video::SColor color(255, 255, 255, 255); + IGUISkin *skin = Environment->getSkin(); + if (skin) { sprites = skin->getSpriteBank(); color = skin->getColor(EGDC_WINDOW_SYMBOL); } @@ -70,11 +65,10 @@ CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t* title, const s32 posx = RelativeRect.getWidth() - buttonw - 4; CloseButton = Environment->addButton(core::rect(posx, 3, posx + buttonw, 3 + buttonw), this, -1, - L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close"); + L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close"); CloseButton->setSubElement(true); CloseButton->setTabStop(false); - if (sprites && skin) - { + if (sprites && skin) { CloseButton->setSpriteBank(sprites); CloseButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_CLOSE), color); CloseButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_CLOSE), color); @@ -83,25 +77,25 @@ CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t* title, CloseButton->grab(); OKButton = Environment->addButton( - core::rect(RelativeRect.getWidth()-80, 30, RelativeRect.getWidth()-10, 50), - this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_OK) : L"OK"); + core::rect(RelativeRect.getWidth() - 80, 30, RelativeRect.getWidth() - 10, 50), + this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_OK) : L"OK"); OKButton->setSubElement(true); OKButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); OKButton->grab(); CancelButton = Environment->addButton( - core::rect(RelativeRect.getWidth()-80, 55, RelativeRect.getWidth()-10, 75), - this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_CANCEL) : L"Cancel"); + core::rect(RelativeRect.getWidth() - 80, 55, RelativeRect.getWidth() - 10, 75), + this, -1, skin ? skin->getDefaultText(EGDT_MSG_BOX_CANCEL) : L"Cancel"); CancelButton->setSubElement(true); CancelButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); CancelButton->grab(); - FileBox = Environment->addListBox(core::rect(10, 55, RelativeRect.getWidth()-90, 230), this, -1, true); + FileBox = Environment->addListBox(core::rect(10, 55, RelativeRect.getWidth() - 90, 230), this, -1, true); FileBox->setSubElement(true); FileBox->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); FileBox->grab(); - FileNameText = Environment->addEditBox(0, core::rect(10, 30, RelativeRect.getWidth()-90, 50), true, this); + FileNameText = Environment->addEditBox(0, core::rect(10, 30, RelativeRect.getWidth() - 90, 50), true, this); FileNameText->setSubElement(true); FileNameText->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); FileNameText->grab(); @@ -111,7 +105,6 @@ CGUIFileOpenDialog::CGUIFileOpenDialog(const wchar_t* title, fillListBox(); } - //! destructor CGUIFileOpenDialog::~CGUIFileOpenDialog() { @@ -130,8 +123,7 @@ CGUIFileOpenDialog::~CGUIFileOpenDialog() if (FileNameText) FileNameText->drop(); - if (FileSystem) - { + if (FileSystem) { // revert to original CWD if path was set in constructor if (RestoreDirectory.size()) FileSystem->changeWorkingDirectoryTo(RestoreDirectory); @@ -142,139 +134,114 @@ CGUIFileOpenDialog::~CGUIFileOpenDialog() FileList->drop(); } - //! returns the filename of the selected file. Returns NULL, if no file was selected. -const wchar_t* CGUIFileOpenDialog::getFileName() const +const wchar_t *CGUIFileOpenDialog::getFileName() const { return FileNameW.c_str(); } -const io::path& CGUIFileOpenDialog::getFileNameP() const +const io::path &CGUIFileOpenDialog::getFileNameP() const { return FileName; } //! Returns the directory of the selected file. Returns NULL, if no directory was selected. -const io::path& CGUIFileOpenDialog::getDirectoryName() const +const io::path &CGUIFileOpenDialog::getDirectoryName() const { return FileDirectoryFlat; } -const wchar_t* CGUIFileOpenDialog::getDirectoryNameW() const +const wchar_t *CGUIFileOpenDialog::getDirectoryNameW() const { return FileDirectoryFlatW.c_str(); } -void CGUIFileOpenDialog::setFileName(const irr::io::path& name) +void CGUIFileOpenDialog::setFileName(const irr::io::path &name) { FileName = name; pathToStringW(FileNameW, FileName); } -void CGUIFileOpenDialog::setDirectoryName(const irr::io::path& name) +void CGUIFileOpenDialog::setDirectoryName(const irr::io::path &name) { FileDirectory = name; FileDirectoryFlat = name; - FileSystem->flattenFilename (FileDirectoryFlat ); + FileSystem->flattenFilename(FileDirectoryFlat); pathToStringW(FileDirectoryFlatW, FileDirectoryFlat); } //! called if an event happened. -bool CGUIFileOpenDialog::OnEvent(const SEvent& event) +bool CGUIFileOpenDialog::OnEvent(const SEvent &event) { - if (isEnabled()) - { - switch(event.EventType) - { + if (isEnabled()) { + switch (event.EventType) { case EET_GUI_EVENT: - switch(event.GUIEvent.EventType) - { + switch (event.GUIEvent.EventType) { case EGET_ELEMENT_FOCUS_LOST: Dragging = false; break; case EGET_BUTTON_CLICKED: if (event.GUIEvent.Caller == CloseButton || - event.GUIEvent.Caller == CancelButton) - { + event.GUIEvent.Caller == CancelButton) { sendCancelEvent(); remove(); return true; - } - else - if (event.GUIEvent.Caller == OKButton ) - { - if ( FileDirectory != L"" ) - { - sendSelectedEvent( EGET_DIRECTORY_SELECTED ); + } else if (event.GUIEvent.Caller == OKButton) { + if (FileDirectory != L"") { + sendSelectedEvent(EGET_DIRECTORY_SELECTED); } - if ( FileName != L"" ) - { - sendSelectedEvent( EGET_FILE_SELECTED ); + if (FileName != L"") { + sendSelectedEvent(EGET_FILE_SELECTED); remove(); return true; } } break; - case EGET_LISTBOX_CHANGED: - { - s32 selected = FileBox->getSelected(); - if (FileList && FileSystem) - { - if (FileList->isDirectory(selected)) - { - setFileName(""); - setDirectoryName(FileList->getFullFileName(selected)); - } - else - { - setDirectoryName(""); - setFileName(FileList->getFullFileName(selected)); - } - return true; + case EGET_LISTBOX_CHANGED: { + s32 selected = FileBox->getSelected(); + if (FileList && FileSystem) { + if (FileList->isDirectory(selected)) { + setFileName(""); + setDirectoryName(FileList->getFullFileName(selected)); + } else { + setDirectoryName(""); + setFileName(FileList->getFullFileName(selected)); } + return true; } - break; + } break; - case EGET_LISTBOX_SELECTED_AGAIN: - { - const s32 selected = FileBox->getSelected(); - if (FileList && FileSystem) - { - if (FileList->isDirectory(selected)) - { - setDirectoryName(FileList->getFullFileName(selected)); - FileSystem->changeWorkingDirectoryTo(FileDirectory ); - fillListBox(); - setFileName(""); - } - else - { - setFileName(FileList->getFullFileName(selected)); - } - return true; + case EGET_LISTBOX_SELECTED_AGAIN: { + const s32 selected = FileBox->getSelected(); + if (FileList && FileSystem) { + if (FileList->isDirectory(selected)) { + setDirectoryName(FileList->getFullFileName(selected)); + FileSystem->changeWorkingDirectoryTo(FileDirectory); + fillListBox(); + setFileName(""); + } else { + setFileName(FileList->getFullFileName(selected)); } + return true; } - break; + } break; case EGET_EDITBOX_ENTER: - if (event.GUIEvent.Caller == FileNameText) - { - io::path dir( FileNameText->getText () ); - if ( FileSystem->changeWorkingDirectoryTo( dir ) ) - { + if (event.GUIEvent.Caller == FileNameText) { + io::path dir(FileNameText->getText()); + if (FileSystem->changeWorkingDirectoryTo(dir)) { fillListBox(); setFileName(""); } return true; } - break; + break; default: break; } break; case EET_MOUSE_INPUT_EVENT: - switch(event.MouseInput.Event) - { + switch (event.MouseInput.Event) { case EMIE_MOUSE_WHEEL: return FileBox->OnEvent(event); case EMIE_LMOUSE_PRESSED_DOWN: @@ -287,17 +254,16 @@ bool CGUIFileOpenDialog::OnEvent(const SEvent& event) return true; case EMIE_MOUSE_MOVED: - if ( !event.MouseInput.isLeftPressed () ) + if (!event.MouseInput.isLeftPressed()) Dragging = false; - if (Dragging) - { + if (Dragging) { // gui window should not be dragged outside its parent if (Parent) - if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 || - event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 || - event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 || - event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1) + if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X + 1 || + event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y + 1 || + event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X - 1 || + event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y - 1) return true; @@ -318,26 +284,24 @@ bool CGUIFileOpenDialog::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - //! draws the element and its children void CGUIFileOpenDialog::draw() { if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); core::rect rect = AbsoluteRect; rect = skin->draw3DWindowBackground(this, true, skin->getColor(EGDC_ACTIVE_BORDER), - rect, &AbsoluteClippingRect); + rect, &AbsoluteClippingRect); - if (Text.size()) - { + if (Text.size()) { rect.UpperLeftCorner.X += 2; rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5; - IGUIFont* font = skin->getFont(EGDF_WINDOW); + IGUIFont *font = skin->getFont(EGDF_WINDOW); if (font) font->draw(Text.c_str(), rect, skin->getColor(EGDC_ACTIVE_CAPTION), @@ -347,7 +311,7 @@ void CGUIFileOpenDialog::draw() IGUIElement::draw(); } -void CGUIFileOpenDialog::pathToStringW(irr::core::stringw& result, const irr::io::path& p) +void CGUIFileOpenDialog::pathToStringW(irr::core::stringw &result, const irr::io::path &p) { core::multibyteToWString(result, p); } @@ -368,17 +332,14 @@ void CGUIFileOpenDialog::fillListBox() FileList = FileSystem->createFileList(); core::stringw s; - if (FileList) - { - for (u32 i=0; i < FileList->getFileCount(); ++i) - { + if (FileList) { + for (u32 i = 0; i < FileList->getFileCount(); ++i) { pathToStringW(s, FileList->getFileName(i)); FileBox->addItem(s.c_str(), skin->getIcon(FileList->isDirectory(i) ? EGDI_DIRECTORY : EGDI_FILE)); } } - if (FileNameText) - { + if (FileNameText) { setDirectoryName(FileSystem->getWorkingDirectory()); pathToStringW(s, FileDirectory); FileNameText->setText(s.c_str()); @@ -386,7 +347,7 @@ void CGUIFileOpenDialog::fillListBox() } //! sends the event that the file has been selected. -void CGUIFileOpenDialog::sendSelectedEvent( EGUI_EVENT_TYPE type) +void CGUIFileOpenDialog::sendSelectedEvent(EGUI_EVENT_TYPE type) { SEvent event; event.EventType = EET_GUI_EVENT; @@ -396,7 +357,6 @@ void CGUIFileOpenDialog::sendSelectedEvent( EGUI_EVENT_TYPE type) Parent->OnEvent(event); } - //! sends the event that the file choose process has been cancelled void CGUIFileOpenDialog::sendCancelEvent() { diff --git a/source/Irrlicht/CGUIFileOpenDialog.h b/source/Irrlicht/CGUIFileOpenDialog.h index 5625bada..13350923 100644 --- a/source/Irrlicht/CGUIFileOpenDialog.h +++ b/source/Irrlicht/CGUIFileOpenDialog.h @@ -15,73 +15,70 @@ namespace irr namespace gui { - class CGUIFileOpenDialog : public IGUIFileOpenDialog - { - public: +class CGUIFileOpenDialog : public IGUIFileOpenDialog +{ +public: + //! constructor + CGUIFileOpenDialog(const wchar_t *title, IGUIEnvironment *environment, + IGUIElement *parent, s32 id, bool restoreCWD = false, + io::path::char_type *startDir = 0); - //! constructor - CGUIFileOpenDialog(const wchar_t* title, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, bool restoreCWD=false, - io::path::char_type* startDir=0); + //! destructor + virtual ~CGUIFileOpenDialog(); - //! destructor - virtual ~CGUIFileOpenDialog(); + //! returns the filename of the selected file. Returns NULL, if no file was selected. + const wchar_t *getFileName() const override; - //! returns the filename of the selected file. Returns NULL, if no file was selected. - const wchar_t* getFileName() const override; + //! Returns the filename of the selected file. Is empty if no file was selected. + const io::path &getFileNameP() const override; - //! Returns the filename of the selected file. Is empty if no file was selected. - const io::path& getFileNameP() const override; + //! Returns the directory of the selected file. Returns NULL, if no directory was selected. + const io::path &getDirectoryName() const override; - //! Returns the directory of the selected file. Returns NULL, if no directory was selected. - const io::path& getDirectoryName() const override; + //! Returns the directory of the selected file converted to wide characters. Returns NULL if no directory was selected. + const wchar_t *getDirectoryNameW() const override; - //! Returns the directory of the selected file converted to wide characters. Returns NULL if no directory was selected. - const wchar_t* getDirectoryNameW() const override; + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! draws the element and its children + void draw() override; - //! draws the element and its children - void draw() override; +protected: + void setFileName(const irr::io::path &name); + void setDirectoryName(const irr::io::path &name); - protected: + //! Ensure filenames are converted correct depending on wide-char settings + void pathToStringW(irr::core::stringw &result, const irr::io::path &p); - void setFileName(const irr::io::path& name); - void setDirectoryName(const irr::io::path& name); + //! fills the listbox with files. + void fillListBox(); - //! Ensure filenames are converted correct depending on wide-char settings - void pathToStringW(irr::core::stringw& result, const irr::io::path& p); + //! sends the event that the file has been selected. + void sendSelectedEvent(EGUI_EVENT_TYPE type); - //! fills the listbox with files. - void fillListBox(); + //! sends the event that the file choose process has been canceld + void sendCancelEvent(); - //! sends the event that the file has been selected. - void sendSelectedEvent( EGUI_EVENT_TYPE type ); - - //! sends the event that the file choose process has been canceld - void sendCancelEvent(); - - core::position2d DragStart; - io::path FileName; - core::stringw FileNameW; - io::path FileDirectory; - io::path FileDirectoryFlat; - core::stringw FileDirectoryFlatW; - io::path RestoreDirectory; - io::path StartDirectory; - - IGUIButton* CloseButton; - IGUIButton* OKButton; - IGUIButton* CancelButton; - IGUIListBox* FileBox; - IGUIEditBox* FileNameText; - IGUIElement* EventParent; - io::IFileSystem* FileSystem; - io::IFileList* FileList; - bool Dragging; - }; + core::position2d DragStart; + io::path FileName; + core::stringw FileNameW; + io::path FileDirectory; + io::path FileDirectoryFlat; + core::stringw FileDirectoryFlatW; + io::path RestoreDirectory; + io::path StartDirectory; + IGUIButton *CloseButton; + IGUIButton *OKButton; + IGUIButton *CancelButton; + IGUIListBox *FileBox; + IGUIEditBox *FileNameText; + IGUIElement *EventParent; + io::IFileSystem *FileSystem; + io::IFileList *FileList; + bool Dragging; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIFont.cpp b/source/Irrlicht/CGUIFont.cpp index 5f3f1ab7..5b3ea154 100644 --- a/source/Irrlicht/CGUIFont.cpp +++ b/source/Irrlicht/CGUIFont.cpp @@ -17,21 +17,20 @@ namespace gui { //! constructor -CGUIFont::CGUIFont(IGUIEnvironment *env, const io::path& filename) -: Driver(0), SpriteBank(0), Environment(env), WrongCharacter(0), - MaxHeight(0), GlobalKerningWidth(0), GlobalKerningHeight(0) +CGUIFont::CGUIFont(IGUIEnvironment *env, const io::path &filename) : + Driver(0), SpriteBank(0), Environment(env), WrongCharacter(0), + MaxHeight(0), GlobalKerningWidth(0), GlobalKerningHeight(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIFont"); - #endif +#endif - if (Environment) - { + if (Environment) { // don't grab environment, to avoid circular references Driver = Environment->getVideoDriver(); SpriteBank = Environment->getSpriteBank(filename); - if (!SpriteBank) // could be default-font which has no file + if (!SpriteBank) // could be default-font which has no file SpriteBank = Environment->addEmptySpriteBank(filename); if (SpriteBank) SpriteBank->grab(); @@ -40,18 +39,16 @@ CGUIFont::CGUIFont(IGUIEnvironment *env, const io::path& filename) if (Driver) Driver->grab(); - setInvisibleCharacters ( L" " ); + setInvisibleCharacters(L" "); } - //! destructor CGUIFont::~CGUIFont() { if (Driver) Driver->drop(); - if (SpriteBank) - { + if (SpriteBank) { SpriteBank->drop(); // TODO: spritebank still exists in gui-environment and should be removed here when it's // reference-count is 1. Just can't do that from here at the moment. @@ -60,7 +57,6 @@ CGUIFont::~CGUIFont() } } - #if 0 //! loads a font file from xml bool CGUIFont::load(io::IXMLReader* xml, const io::path& directory) @@ -196,25 +192,23 @@ bool CGUIFont::load(io::IXMLReader* xml, const io::path& directory) } #endif - void CGUIFont::setMaxHeight() { - if ( !SpriteBank ) + if (!SpriteBank) return; MaxHeight = 0; - core::array< core::rect >& p = SpriteBank->getPositions(); + core::array> &p = SpriteBank->getPositions(); - for (u32 i=0; iMaxHeight) + if (t > MaxHeight) MaxHeight = t; } } -void CGUIFont::pushTextureCreationFlags(bool(&flags)[3]) +void CGUIFont::pushTextureCreationFlags(bool (&flags)[3]) { flags[0] = Driver->getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2); flags[1] = Driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); @@ -225,7 +219,7 @@ void CGUIFont::pushTextureCreationFlags(bool(&flags)[3]) Driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true); } -void CGUIFont::popTextureCreationFlags(const bool(&flags)[3]) +void CGUIFont::popTextureCreationFlags(const bool (&flags)[3]) { Driver->setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, flags[0]); Driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flags[1]); @@ -233,51 +227,48 @@ void CGUIFont::popTextureCreationFlags(const bool(&flags)[3]) } //! loads a font file, native file needed, for texture parsing -bool CGUIFont::load(io::IReadFile* file) +bool CGUIFont::load(io::IReadFile *file) { if (!Driver) return false; return loadTexture(Driver->createImageFromFile(file), - file->getFileName()); + file->getFileName()); } - //! loads a font file, native file needed, for texture parsing -bool CGUIFont::load(const io::path& filename) +bool CGUIFont::load(const io::path &filename) { if (!Driver) return false; - return loadTexture(Driver->createImageFromFile( filename ), - filename); + return loadTexture(Driver->createImageFromFile(filename), + filename); } - //! load & prepare font from ITexture -bool CGUIFont::loadTexture(video::IImage* image, const io::path& name) +bool CGUIFont::loadTexture(video::IImage *image, const io::path &name) { if (!image || !SpriteBank) return false; s32 lowerRightPositions = 0; - video::IImage* tmpImage=image; - bool deleteTmpImage=false; - switch(image->getColorFormat()) - { + video::IImage *tmpImage = image; + bool deleteTmpImage = false; + switch (image->getColorFormat()) { case video::ECF_R5G6B5: - tmpImage = Driver->createImage(video::ECF_A1R5G5B5,image->getDimension()); + tmpImage = Driver->createImage(video::ECF_A1R5G5B5, image->getDimension()); image->copyTo(tmpImage); - deleteTmpImage=true; + deleteTmpImage = true; break; case video::ECF_A1R5G5B5: case video::ECF_A8R8G8B8: break; case video::ECF_R8G8B8: - tmpImage = Driver->createImage(video::ECF_A8R8G8B8,image->getDimension()); + tmpImage = Driver->createImage(video::ECF_A8R8G8B8, image->getDimension()); image->copyTo(tmpImage); - deleteTmpImage=true; + deleteTmpImage = true; break; default: os::Printer::log("Unknown texture format provided for CGUIFont::loadTexture", ELL_ERROR); @@ -290,14 +281,12 @@ bool CGUIFont::loadTexture(video::IImage* image, const io::path& name) // output warnings if (!lowerRightPositions || !SpriteBank->getSprites().size()) os::Printer::log("Either no upper or lower corner pixels in the font file. If this font was made using the new font tool, please load the XML file instead. If not, the font may be corrupted.", ELL_ERROR); - else - if (lowerRightPositions != (s32)SpriteBank->getPositions().size()) + else if (lowerRightPositions != (s32)SpriteBank->getPositions().size()) os::Printer::log("The amount of upper corner pixels and the lower corner pixels is not equal, font file may be corrupted.", ELL_ERROR); - bool ret = ( !SpriteBank->getSprites().empty() && lowerRightPositions ); + bool ret = (!SpriteBank->getSprites().empty() && lowerRightPositions); - if ( ret ) - { + if (ret) { bool flags[3]; pushTextureCreationFlags(flags); @@ -314,42 +303,34 @@ bool CGUIFont::loadTexture(video::IImage* image, const io::path& name) return ret; } - -void CGUIFont::readPositions(video::IImage* image, s32& lowerRightPositions) +void CGUIFont::readPositions(video::IImage *image, s32 &lowerRightPositions) { - if (!SpriteBank ) + if (!SpriteBank) return; const core::dimension2d size = image->getDimension(); - video::SColor colorTopLeft = image->getPixel(0,0); + video::SColor colorTopLeft = image->getPixel(0, 0); colorTopLeft.setAlpha(255); - image->setPixel(0,0,colorTopLeft); - video::SColor colorLowerRight = image->getPixel(1,0); - video::SColor colorBackGround = image->getPixel(2,0); + image->setPixel(0, 0, colorTopLeft); + video::SColor colorLowerRight = image->getPixel(1, 0); + video::SColor colorBackGround = image->getPixel(2, 0); video::SColor colorBackGroundTransparent = 0; - image->setPixel(1,0,colorBackGround); + image->setPixel(1, 0, colorBackGround); // start parsing - core::position2d pos(0,0); - for (pos.Y=0; pos.Y<(s32)size.Height; ++pos.Y) - { - for (pos.X=0; pos.X<(s32)size.Width; ++pos.X) - { + core::position2d pos(0, 0); + for (pos.Y = 0; pos.Y < (s32)size.Height; ++pos.Y) { + for (pos.X = 0; pos.X < (s32)size.Width; ++pos.X) { const video::SColor c = image->getPixel(pos.X, pos.Y); - if (c == colorTopLeft) - { + if (c == colorTopLeft) { image->setPixel(pos.X, pos.Y, colorBackGroundTransparent); SpriteBank->getPositions().push_back(core::rect(pos, pos)); - } - else - if (c == colorLowerRight) - { + } else if (c == colorLowerRight) { // too many lower right points - if (SpriteBank->getPositions().size()<=(u32)lowerRightPositions) - { + if (SpriteBank->getPositions().size() <= (u32)lowerRightPositions) { lowerRightPositions = 0; return; } @@ -376,33 +357,27 @@ void CGUIFont::readPositions(video::IImage* image, s32& lowerRightPositions) CharacterMap[ch] = lowerRightPositions; ++lowerRightPositions; - } - else - if (c == colorBackGround) + } else if (c == colorBackGround) image->setPixel(pos.X, pos.Y, colorBackGroundTransparent); } } } - //! set an Pixel Offset on Drawing ( scale position on width ) void CGUIFont::setKerningWidth(s32 kerning) { GlobalKerningWidth = kerning; } - //! set an Pixel Offset on Drawing ( scale position on width ) -s32 CGUIFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previousLetter) const +s32 CGUIFont::getKerningWidth(const wchar_t *thisLetter, const wchar_t *previousLetter) const { s32 ret = GlobalKerningWidth; - if (thisLetter) - { + if (thisLetter) { ret += Areas[getAreaFromCharacter(*thisLetter)].overhang; - if (previousLetter) - { + if (previousLetter) { ret += Areas[getAreaFromCharacter(*previousLetter)].underhang; } } @@ -410,28 +385,24 @@ s32 CGUIFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previous return ret; } - //! set an Pixel Offset on Drawing ( scale position on height ) void CGUIFont::setKerningHeight(s32 kerning) { GlobalKerningHeight = kerning; } - //! set an Pixel Offset on Drawing ( scale position on height ) -s32 CGUIFont::getKerningHeight () const +s32 CGUIFont::getKerningHeight() const { return GlobalKerningHeight; } - //! returns the sprite number from a given character u32 CGUIFont::getSpriteNoFromChar(const wchar_t *c) const { return Areas[getAreaFromCharacter(*c)].spriteno; } - s32 CGUIFont::getAreaFromCharacter(const wchar_t c) const { auto n = CharacterMap.find(c); @@ -441,33 +412,29 @@ s32 CGUIFont::getAreaFromCharacter(const wchar_t c) const return WrongCharacter; } -void CGUIFont::setInvisibleCharacters( const wchar_t *s ) +void CGUIFont::setInvisibleCharacters(const wchar_t *s) { Invisible = s; } - //! returns the dimension of text -core::dimension2d CGUIFont::getDimension(const wchar_t* text) const +core::dimension2d CGUIFont::getDimension(const wchar_t *text) const { core::dimension2d dim(0, 0); core::dimension2d thisLine(0, MaxHeight); - for (const wchar_t* p = text; *p; ++p) - { - bool lineBreak=false; + for (const wchar_t *p = text; *p; ++p) { + bool lineBreak = false; if (*p == L'\r') // Mac or Windows breaks { lineBreak = true; if (p[1] == L'\n') // Windows breaks ++p; - } - else if (*p == L'\n') // Unix breaks + } else if (*p == L'\n') // Unix breaks { lineBreak = true; } - if (lineBreak) - { + if (lineBreak) { dim.Height += thisLine.Height; if (dim.Width < thisLine.Width) dim.Width = thisLine.Width; @@ -489,15 +456,14 @@ core::dimension2d CGUIFont::getDimension(const wchar_t* text) const } //! draws some text and clips it to the specified rectangle if wanted -void CGUIFont::draw(const core::stringw& text, const core::rect& position, - video::SColor color, - bool hcenter, bool vcenter, const core::rect* clip - ) +void CGUIFont::draw(const core::stringw &text, const core::rect &position, + video::SColor color, + bool hcenter, bool vcenter, const core::rect *clip) { if (!Driver || !SpriteBank) return; - core::dimension2d textDimension; // NOTE: don't make this u32 or the >> later on can fail when the dimension width is < position width + core::dimension2d textDimension; // NOTE: don't make this u32 or the >> later on can fail when the dimension width is < position width core::position2d offset = position.UpperLeftCorner; if (hcenter || vcenter || clip) @@ -509,8 +475,7 @@ void CGUIFont::draw(const core::stringw& text, const core::rect& position, if (vcenter) offset.Y += (position.getHeight() - textDimension.Height) >> 1; - if (clip) - { + if (clip) { core::rect clippedRect(offset, textDimension); clippedRect.clipAgainst(*clip); if (!clippedRect.isValid()) @@ -520,39 +485,34 @@ void CGUIFont::draw(const core::stringw& text, const core::rect& position, core::array indices(text.size()); core::array offsets(text.size()); - for(u32 i = 0;i < text.size();i++) - { + for (u32 i = 0; i < text.size(); i++) { wchar_t c = text[i]; - bool lineBreak=false; - if ( c == L'\r') // Mac or Windows breaks + bool lineBreak = false; + if (c == L'\r') // Mac or Windows breaks { lineBreak = true; - if ( text[i + 1] == L'\n') // Windows breaks + if (text[i + 1] == L'\n') // Windows breaks c = text[++i]; - } - else if ( c == L'\n') // Unix breaks + } else if (c == L'\n') // Unix breaks { lineBreak = true; } - if (lineBreak) - { + if (lineBreak) { offset.Y += MaxHeight; offset.X = position.UpperLeftCorner.X; - if ( hcenter ) - { + if (hcenter) { offset.X += (position.getWidth() - textDimension.Width) >> 1; } continue; } - SFontArea& area = Areas[getAreaFromCharacter(c)]; + SFontArea &area = Areas[getAreaFromCharacter(c)]; offset.X += area.underhang; - if ( Invisible.findFirst ( c ) < 0 ) - { + if (Invisible.findFirst(c) < 0) { indices.push_back(area.spriteno); offsets.push_back(offset); } @@ -563,16 +523,14 @@ void CGUIFont::draw(const core::stringw& text, const core::rect& position, SpriteBank->draw2DSpriteBatch(indices, offsets, clip, color); } - //! Calculates the index of the character in the text which is on a specific position. -s32 CGUIFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const +s32 CGUIFont::getCharacterFromPos(const wchar_t *text, s32 pixel_x) const { s32 x = 0; s32 idx = 0; - while (text[idx]) - { - const SFontArea& a = Areas[getAreaFromCharacter(text[idx])]; + while (text[idx]) { + const SFontArea &a = Areas[getAreaFromCharacter(text[idx])]; x += a.width + a.overhang + a.underhang + GlobalKerningWidth; @@ -585,8 +543,7 @@ s32 CGUIFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const return -1; } - -IGUISpriteBank* CGUIFont::getSpriteBank() const +IGUISpriteBank *CGUIFont::getSpriteBank() const { return SpriteBank; } diff --git a/source/Irrlicht/CGUIFont.h b/source/Irrlicht/CGUIFont.h index 48180d5d..2f383a5f 100644 --- a/source/Irrlicht/CGUIFont.h +++ b/source/Irrlicht/CGUIFont.h @@ -15,91 +15,90 @@ namespace irr namespace video { - class IVideoDriver; - class IImage; +class IVideoDriver; +class IImage; } namespace gui { - class IGUIEnvironment; +class IGUIEnvironment; class CGUIFont : public IGUIFontBitmap { public: - //! constructor - CGUIFont(IGUIEnvironment* env, const io::path& filename); + CGUIFont(IGUIEnvironment *env, const io::path &filename); //! destructor virtual ~CGUIFont(); //! loads a font from a texture file - bool load(const io::path& filename); + bool load(const io::path &filename); //! loads a font from a texture file - bool load(io::IReadFile* file); + bool load(io::IReadFile *file); //! draws an text and clips it to the specified rectangle if wanted - virtual void draw(const core::stringw& text, const core::rect& position, - video::SColor color, bool hcenter=false, - bool vcenter=false, const core::rect* clip=0) override; + virtual void draw(const core::stringw &text, const core::rect &position, + video::SColor color, bool hcenter = false, + bool vcenter = false, const core::rect *clip = 0) override; //! returns the dimension of a text - core::dimension2d getDimension(const wchar_t* text) const override; + core::dimension2d getDimension(const wchar_t *text) const override; //! Calculates the index of the character in the text which is on a specific position. - s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const override; + s32 getCharacterFromPos(const wchar_t *text, s32 pixel_x) const override; //! Returns the type of this font EGUI_FONT_TYPE getType() const override { return EGFT_BITMAP; } //! set an Pixel Offset on Drawing ( scale position on width ) - void setKerningWidth (s32 kerning) override; - void setKerningHeight (s32 kerning) override; + void setKerningWidth(s32 kerning) override; + void setKerningHeight(s32 kerning) override; //! set an Pixel Offset on Drawing ( scale position on width ) - s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const override; + s32 getKerningWidth(const wchar_t *thisLetter = 0, const wchar_t *previousLetter = 0) const override; s32 getKerningHeight() const override; //! gets the sprite bank - IGUISpriteBank* getSpriteBank() const override; + IGUISpriteBank *getSpriteBank() const override; //! returns the sprite number from a given character u32 getSpriteNoFromChar(const wchar_t *c) const override; - void setInvisibleCharacters( const wchar_t *s ) override; + void setInvisibleCharacters(const wchar_t *s) override; private: - struct SFontArea { - SFontArea() : underhang(0), overhang(0), width(0), spriteno(0) {} - s32 underhang; - s32 overhang; - s32 width; - u32 spriteno; + SFontArea() : + underhang(0), overhang(0), width(0), spriteno(0) {} + s32 underhang; + s32 overhang; + s32 width; + u32 spriteno; }; //! load & prepare font from ITexture - bool loadTexture(video::IImage * image, const io::path& name); + bool loadTexture(video::IImage *image, const io::path &name); - void readPositions(video::IImage* texture, s32& lowerRightPositions); + void readPositions(video::IImage *texture, s32 &lowerRightPositions); - s32 getAreaFromCharacter (const wchar_t c) const; + s32 getAreaFromCharacter(const wchar_t c) const; void setMaxHeight(); - void pushTextureCreationFlags(bool(&flags)[3]); - void popTextureCreationFlags(const bool(&flags)[3]); + void pushTextureCreationFlags(bool (&flags)[3]); + void popTextureCreationFlags(const bool (&flags)[3]); - core::array Areas; - std::map CharacterMap; - video::IVideoDriver* Driver; - IGUISpriteBank* SpriteBank; - IGUIEnvironment* Environment; - u32 WrongCharacter; - s32 MaxHeight; - s32 GlobalKerningWidth, GlobalKerningHeight; + core::array Areas; + std::map CharacterMap; + video::IVideoDriver *Driver; + IGUISpriteBank *SpriteBank; + IGUIEnvironment *Environment; + u32 WrongCharacter; + s32 MaxHeight; + s32 GlobalKerningWidth, GlobalKerningHeight; core::stringw Invisible; }; diff --git a/source/Irrlicht/CGUIImage.cpp b/source/Irrlicht/CGUIImage.cpp index 458b233b..5f7bb8e2 100644 --- a/source/Irrlicht/CGUIImage.cpp +++ b/source/Irrlicht/CGUIImage.cpp @@ -13,18 +13,16 @@ namespace irr namespace gui { - //! constructor -CGUIImage::CGUIImage(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle) -: IGUIImage(environment, parent, id, rectangle), Texture(0), Color(255,255,255,255), - UseAlphaChannel(false), ScaleImage(false), DrawBounds(0.f, 0.f, 1.f, 1.f), DrawBackground(true) +CGUIImage::CGUIImage(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle) : + IGUIImage(environment, parent, id, rectangle), Texture(0), Color(255, 255, 255, 255), + UseAlphaChannel(false), ScaleImage(false), DrawBounds(0.f, 0.f, 1.f, 1.f), DrawBackground(true) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIImage"); - #endif +#endif } - //! destructor CGUIImage::~CGUIImage() { @@ -32,9 +30,8 @@ CGUIImage::~CGUIImage() Texture->drop(); } - //! sets an image -void CGUIImage::setImage(video::ITexture* image) +void CGUIImage::setImage(video::ITexture *image) { if (image == Texture) return; @@ -49,7 +46,7 @@ void CGUIImage::setImage(video::ITexture* image) } //! Gets the image texture -video::ITexture* CGUIImage::getImage() const +video::ITexture *CGUIImage::getImage() const { return Texture; } @@ -72,39 +69,32 @@ void CGUIImage::draw() if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); - video::IVideoDriver* driver = Environment->getVideoDriver(); + IGUISkin *skin = Environment->getSkin(); + video::IVideoDriver *driver = Environment->getVideoDriver(); - if (Texture) - { + if (Texture) { core::rect sourceRect(SourceRect); - if (sourceRect.getWidth() == 0 || sourceRect.getHeight() == 0) - { + if (sourceRect.getWidth() == 0 || sourceRect.getHeight() == 0) { sourceRect = core::rect(core::dimension2di(Texture->getOriginalSize())); } - if (ScaleImage) - { - const video::SColor Colors[] = {Color,Color,Color,Color}; + if (ScaleImage) { + const video::SColor Colors[] = {Color, Color, Color, Color}; core::rect clippingRect(AbsoluteClippingRect); checkBounds(clippingRect); driver->draw2DImage(Texture, AbsoluteRect, sourceRect, - &clippingRect, Colors, UseAlphaChannel); - } - else - { + &clippingRect, Colors, UseAlphaChannel); + } else { core::rect clippingRect(AbsoluteRect.UpperLeftCorner, sourceRect.getSize()); checkBounds(clippingRect); clippingRect.clipAgainst(AbsoluteClippingRect); driver->draw2DImage(Texture, AbsoluteRect.UpperLeftCorner, sourceRect, - &clippingRect, Color, UseAlphaChannel); + &clippingRect, Color, UseAlphaChannel); } - } - else if ( DrawBackground ) - { + } else if (DrawBackground) { core::rect clippingRect(AbsoluteClippingRect); checkBounds(clippingRect); @@ -114,21 +104,18 @@ void CGUIImage::draw() IGUIElement::draw(); } - //! sets if the image should use its alpha channel to draw itself void CGUIImage::setUseAlphaChannel(bool use) { UseAlphaChannel = use; } - //! sets if the image should use its alpha channel to draw itself void CGUIImage::setScaleImage(bool scale) { ScaleImage = scale; } - //! Returns true if the image is scaled to fit, false if not bool CGUIImage::isImageScaled() const { @@ -142,7 +129,7 @@ bool CGUIImage::isAlphaChannelUsed() const } //! Sets the source rectangle of the image. By default the full image is used. -void CGUIImage::setSourceRect(const core::rect& sourceRect) +void CGUIImage::setSourceRect(const core::rect &sourceRect) { SourceRect = sourceRect; } @@ -154,16 +141,16 @@ core::rect CGUIImage::getSourceRect() const } //! Restrict target drawing-area. -void CGUIImage::setDrawBounds(const core::rect& drawBoundUVs) +void CGUIImage::setDrawBounds(const core::rect &drawBoundUVs) { DrawBounds = drawBoundUVs; DrawBounds.UpperLeftCorner.X = core::clamp(DrawBounds.UpperLeftCorner.X, 0.f, 1.f); DrawBounds.UpperLeftCorner.Y = core::clamp(DrawBounds.UpperLeftCorner.Y, 0.f, 1.f); DrawBounds.LowerRightCorner.X = core::clamp(DrawBounds.LowerRightCorner.X, 0.f, 1.f); DrawBounds.LowerRightCorner.X = core::clamp(DrawBounds.LowerRightCorner.X, 0.f, 1.f); - if ( DrawBounds.UpperLeftCorner.X > DrawBounds.LowerRightCorner.X ) + if (DrawBounds.UpperLeftCorner.X > DrawBounds.LowerRightCorner.X) DrawBounds.UpperLeftCorner.X = DrawBounds.LowerRightCorner.X; - if ( DrawBounds.UpperLeftCorner.Y > DrawBounds.LowerRightCorner.Y ) + if (DrawBounds.UpperLeftCorner.Y > DrawBounds.LowerRightCorner.Y) DrawBounds.UpperLeftCorner.Y = DrawBounds.LowerRightCorner.Y; } @@ -173,6 +160,5 @@ core::rect CGUIImage::getDrawBounds() const return DrawBounds; } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIImage.h b/source/Irrlicht/CGUIImage.h index 3414c936..967ac40e 100644 --- a/source/Irrlicht/CGUIImage.h +++ b/source/Irrlicht/CGUIImage.h @@ -11,89 +11,87 @@ namespace irr namespace gui { - class CGUIImage : public IGUIImage +class CGUIImage : public IGUIImage +{ +public: + //! constructor + CGUIImage(IGUIEnvironment *environment, IGUIElement *parent, s32 id, core::rect rectangle); + + //! destructor + virtual ~CGUIImage(); + + //! sets an image + void setImage(video::ITexture *image) override; + + //! Gets the image texture + video::ITexture *getImage() const override; + + //! sets the color of the image + void setColor(video::SColor color) override; + + //! sets if the image should scale to fit the element + void setScaleImage(bool scale) override; + + //! draws the element and its children + void draw() override; + + //! sets if the image should use its alpha channel to draw itself + void setUseAlphaChannel(bool use) override; + + //! Gets the color of the image + video::SColor getColor() const override; + + //! Returns true if the image is scaled to fit, false if not + bool isImageScaled() const override; + + //! Returns true if the image is using the alpha channel, false if not + bool isAlphaChannelUsed() const override; + + //! Sets the source rectangle of the image. By default the full image is used. + void setSourceRect(const core::rect &sourceRect) override; + + //! Returns the customized source rectangle of the image to be used. + core::rect getSourceRect() const override; + + //! Restrict drawing-area. + void setDrawBounds(const core::rect &drawBoundUVs) override; + + //! Get drawing-area restrictions. + core::rect getDrawBounds() const override; + + //! Sets whether to draw a background color (EGDC_3D_DARK_SHADOW) when no texture is set + void setDrawBackground(bool draw) override { - public: + DrawBackground = draw; + } - //! constructor - CGUIImage(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect rectangle); + //! Checks if a background is drawn when no texture is set + bool isDrawBackgroundEnabled() const override + { + return DrawBackground; + } - //! destructor - virtual ~CGUIImage(); +protected: + void checkBounds(core::rect &rect) + { + f32 clipWidth = (f32)rect.getWidth(); + f32 clipHeight = (f32)rect.getHeight(); - //! sets an image - void setImage(video::ITexture* image) override; - - //! Gets the image texture - video::ITexture* getImage() const override; - - //! sets the color of the image - void setColor(video::SColor color) override; - - //! sets if the image should scale to fit the element - void setScaleImage(bool scale) override; - - //! draws the element and its children - void draw() override; - - //! sets if the image should use its alpha channel to draw itself - void setUseAlphaChannel(bool use) override; - - //! Gets the color of the image - video::SColor getColor() const override; - - //! Returns true if the image is scaled to fit, false if not - bool isImageScaled() const override; - - //! Returns true if the image is using the alpha channel, false if not - bool isAlphaChannelUsed() const override; - - //! Sets the source rectangle of the image. By default the full image is used. - void setSourceRect(const core::rect& sourceRect) override; - - //! Returns the customized source rectangle of the image to be used. - core::rect getSourceRect() const override; - - //! Restrict drawing-area. - void setDrawBounds(const core::rect& drawBoundUVs) override; - - //! Get drawing-area restrictions. - core::rect getDrawBounds() const override; - - //! Sets whether to draw a background color (EGDC_3D_DARK_SHADOW) when no texture is set - void setDrawBackground(bool draw) override - { - DrawBackground = draw; - } - - //! Checks if a background is drawn when no texture is set - bool isDrawBackgroundEnabled() const override - { - return DrawBackground; - } - - protected: - void checkBounds(core::rect& rect) - { - f32 clipWidth = (f32)rect.getWidth(); - f32 clipHeight = (f32)rect.getHeight(); - - rect.UpperLeftCorner.X += core::round32(DrawBounds.UpperLeftCorner.X*clipWidth); - rect.UpperLeftCorner.Y += core::round32(DrawBounds.UpperLeftCorner.Y*clipHeight); - rect.LowerRightCorner.X -= core::round32((1.f-DrawBounds.LowerRightCorner.X)*clipWidth); - rect.LowerRightCorner.Y -= core::round32((1.f-DrawBounds.LowerRightCorner.Y)*clipHeight); - } - - private: - video::ITexture* Texture; - video::SColor Color; - bool UseAlphaChannel; - bool ScaleImage; - core::rect SourceRect; - core::rect DrawBounds; - bool DrawBackground; - }; + rect.UpperLeftCorner.X += core::round32(DrawBounds.UpperLeftCorner.X * clipWidth); + rect.UpperLeftCorner.Y += core::round32(DrawBounds.UpperLeftCorner.Y * clipHeight); + rect.LowerRightCorner.X -= core::round32((1.f - DrawBounds.LowerRightCorner.X) * clipWidth); + rect.LowerRightCorner.Y -= core::round32((1.f - DrawBounds.LowerRightCorner.Y) * clipHeight); + } +private: + video::ITexture *Texture; + video::SColor Color; + bool UseAlphaChannel; + bool ScaleImage; + core::rect SourceRect; + core::rect DrawBounds; + bool DrawBackground; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIImageList.cpp b/source/Irrlicht/CGUIImageList.cpp index a2bb2fd3..3bd30d91 100644 --- a/source/Irrlicht/CGUIImageList.cpp +++ b/source/Irrlicht/CGUIImageList.cpp @@ -4,55 +4,47 @@ #include "CGUIImageList.h" - namespace irr { namespace gui { //! constructor -CGUIImageList::CGUIImageList( video::IVideoDriver* driver ) - : Driver( driver ), - Texture( 0 ), - ImageCount( 0 ), - ImageSize( 0, 0 ), - ImagesPerRow( 0 ), - UseAlphaChannel( false ) +CGUIImageList::CGUIImageList(video::IVideoDriver *driver) : + Driver(driver), + Texture(0), + ImageCount(0), + ImageSize(0, 0), + ImagesPerRow(0), + UseAlphaChannel(false) { - #ifdef _DEBUG - setDebugName( "CGUIImageList" ); - #endif +#ifdef _DEBUG + setDebugName("CGUIImageList"); +#endif - if( Driver ) - { + if (Driver) { Driver->grab(); } } - - //! destructor CGUIImageList::~CGUIImageList() { - if( Driver ) - { + if (Driver) { Driver->drop(); } - if( Texture ) - { + if (Texture) { Texture->drop(); } } - //! Creates the image list from texture. -bool CGUIImageList::createImageList(video::ITexture* texture, - core::dimension2d imageSize, - bool useAlphaChannel) +bool CGUIImageList::createImageList(video::ITexture *texture, + core::dimension2d imageSize, + bool useAlphaChannel) { - if( !texture ) - { + if (!texture) { return false; } @@ -70,23 +62,22 @@ bool CGUIImageList::createImageList(video::ITexture* texture, } //! Draws an image and clips it to the specified rectangle if wanted -void CGUIImageList::draw( s32 index, const core::position2d& destPos, - const core::rect* clip /*= 0*/ ) +void CGUIImageList::draw(s32 index, const core::position2d &destPos, + const core::rect *clip /*= 0*/) { core::rect sourceRect; - if( !Driver || index < 0 || index >= ImageCount ) - { + if (!Driver || index < 0 || index >= ImageCount) { return; } - sourceRect.UpperLeftCorner.X = ( index % ImagesPerRow ) * ImageSize.Width; - sourceRect.UpperLeftCorner.Y = ( index / ImagesPerRow ) * ImageSize.Height; + sourceRect.UpperLeftCorner.X = (index % ImagesPerRow) * ImageSize.Width; + sourceRect.UpperLeftCorner.Y = (index / ImagesPerRow) * ImageSize.Height; sourceRect.LowerRightCorner.X = sourceRect.UpperLeftCorner.X + ImageSize.Width; sourceRect.LowerRightCorner.Y = sourceRect.UpperLeftCorner.Y + ImageSize.Height; - Driver->draw2DImage( Texture, destPos, sourceRect, clip, - video::SColor( 255, 255, 255, 255 ), UseAlphaChannel ); + Driver->draw2DImage(Texture, destPos, sourceRect, clip, + video::SColor(255, 255, 255, 255), UseAlphaChannel); } } // end namespace gui diff --git a/source/Irrlicht/CGUIImageList.h b/source/Irrlicht/CGUIImageList.h index 910ef2df..afde14e0 100644 --- a/source/Irrlicht/CGUIImageList.h +++ b/source/Irrlicht/CGUIImageList.h @@ -14,9 +14,8 @@ namespace gui class CGUIImageList : public IGUIImageList { public: - //! constructor - CGUIImageList( video::IVideoDriver* Driver ); + CGUIImageList(video::IVideoDriver *Driver); //! destructor virtual ~CGUIImageList(); @@ -27,36 +26,39 @@ public: //! \param useAlphaChannel: true if the alpha channel from the texture should be used //! \return //! true if the image list was created - bool createImageList(video::ITexture* texture, - core::dimension2d imageSize, - bool useAlphaChannel); + bool createImageList(video::ITexture *texture, + core::dimension2d imageSize, + bool useAlphaChannel); //! Draws an image and clips it to the specified rectangle if wanted //! \param index: Index of the image //! \param destPos: Position of the image to draw //! \param clip: Optional pointer to a rectangle against which the text will be clipped. //! If the pointer is null, no clipping will be done. - virtual void draw( s32 index, const core::position2d& destPos, - const core::rect* clip = 0 ) override; + virtual void draw(s32 index, const core::position2d &destPos, + const core::rect *clip = 0) override; //! Returns the count of Images in the list. //! \return Returns the count of Images in the list. s32 getImageCount() const override - { return ImageCount; } + { + return ImageCount; + } //! Returns the size of the images in the list. //! \return Returns the size of the images in the list. core::dimension2d getImageSize() const override - { return ImageSize; } + { + return ImageSize; + } private: - - video::IVideoDriver* Driver; - video::ITexture* Texture; - s32 ImageCount; - core::dimension2d ImageSize; - s32 ImagesPerRow; - bool UseAlphaChannel; + video::IVideoDriver *Driver; + video::ITexture *Texture; + s32 ImageCount; + core::dimension2d ImageSize; + s32 ImagesPerRow; + bool UseAlphaChannel; }; } // end namespace gui diff --git a/source/Irrlicht/CGUIListBox.cpp b/source/Irrlicht/CGUIListBox.cpp index 5886b4ba..78cb96ec 100644 --- a/source/Irrlicht/CGUIListBox.cpp +++ b/source/Irrlicht/CGUIListBox.cpp @@ -19,24 +19,25 @@ namespace gui { //! constructor -CGUIListBox::CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent, - s32 id, core::rect rectangle, bool clip, - bool drawBack, bool moveOverSelect) -: IGUIListBox(environment, parent, id, rectangle), Selected(-1), - ItemHeight(0),ItemHeightOverride(0), - TotalItemHeight(0), ItemsIconWidth(0), Font(0), IconBank(0), - ScrollBar(0), selectTime(0), LastKeyTime(0), Selecting(false), DrawBack(drawBack), - MoveOverSelect(moveOverSelect), AutoScroll(true), HighlightWhenNotFocused(true) +CGUIListBox::CGUIListBox(IGUIEnvironment *environment, IGUIElement *parent, + s32 id, core::rect rectangle, bool clip, + bool drawBack, bool moveOverSelect) : + IGUIListBox(environment, parent, id, rectangle), + Selected(-1), + ItemHeight(0), ItemHeightOverride(0), + TotalItemHeight(0), ItemsIconWidth(0), Font(0), IconBank(0), + ScrollBar(0), selectTime(0), LastKeyTime(0), Selecting(false), DrawBack(drawBack), + MoveOverSelect(moveOverSelect), AutoScroll(true), HighlightWhenNotFocused(true) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIListBox"); - #endif +#endif - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); ScrollBar = new CGUIScrollBar(false, Environment, this, -1, - core::recti(0, 0, 1, 1), - !clip); + core::recti(0, 0, 1, 1), + !clip); ScrollBar->setSubElement(true); ScrollBar->setTabStop(false); ScrollBar->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); @@ -54,7 +55,6 @@ CGUIListBox::CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent, updateAbsolutePosition(); } - //! destructor CGUIListBox::~CGUIListBox() { @@ -68,53 +68,45 @@ CGUIListBox::~CGUIListBox() IconBank->drop(); } - //! returns amount of list items u32 CGUIListBox::getItemCount() const { return Items.size(); } - //! returns string of a list item. the may be a value from 0 to itemCount-1 -const wchar_t* CGUIListBox::getListItem(u32 id) const +const wchar_t *CGUIListBox::getListItem(u32 id) const { - if (id>=Items.size()) + if (id >= Items.size()) return 0; return Items[id].Text.c_str(); } - //! Returns the icon of an item s32 CGUIListBox::getIcon(u32 id) const { - if (id>=Items.size()) + if (id >= Items.size()) return -1; return Items[id].Icon; } - //! adds a list item, returns id of item -u32 CGUIListBox::addItem(const wchar_t* text) +u32 CGUIListBox::addItem(const wchar_t *text) { return addItem(text, -1); } - //! adds a list item, returns id of item void CGUIListBox::removeItem(u32 id) { if (id >= Items.size()) return; - if ((u32)Selected==id) - { + if ((u32)Selected == id) { Selected = -1; - } - else if ((u32)Selected > id) - { + } else if ((u32)Selected > id) { Selected -= 1; selectTime = os::Timer::getTime(); } @@ -124,19 +116,16 @@ void CGUIListBox::removeItem(u32 id) recalculateItemHeight(); } - s32 CGUIListBox::getItemAt(s32 xpos, s32 ypos) const { - if ( xpos < AbsoluteRect.UpperLeftCorner.X || xpos >= AbsoluteRect.LowerRightCorner.X - || ypos < AbsoluteRect.UpperLeftCorner.Y || ypos >= AbsoluteRect.LowerRightCorner.Y - ) + if (xpos < AbsoluteRect.UpperLeftCorner.X || xpos >= AbsoluteRect.LowerRightCorner.X || ypos < AbsoluteRect.UpperLeftCorner.Y || ypos >= AbsoluteRect.LowerRightCorner.Y) return -1; - if ( ItemHeight == 0 ) + if (ItemHeight == 0) return -1; s32 item = ((ypos - AbsoluteRect.UpperLeftCorner.Y - 1) + ScrollBar->getPos()) / ItemHeight; - if ( item < 0 || item >= (s32)Items.size()) + if (item < 0 || item >= (s32)Items.size()) return -1; return item; @@ -154,23 +143,20 @@ void CGUIListBox::clear() recalculateItemHeight(); } - void CGUIListBox::recalculateItemHeight() { - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); - if (Font != skin->getFont()) - { + if (Font != skin->getFont()) { if (Font) Font->drop(); Font = skin->getFont(); - if ( 0 == ItemHeightOverride ) + if (0 == ItemHeightOverride) ItemHeight = 0; - if (Font) - { - if ( 0 == ItemHeightOverride ) + if (Font) { + if (0 == ItemHeightOverride) ItemHeight = Font->getDimension(L"A").Height + 4; Font->grab(); @@ -178,12 +164,12 @@ void CGUIListBox::recalculateItemHeight() } TotalItemHeight = ItemHeight * Items.size(); - ScrollBar->setMax( core::max_(0, TotalItemHeight - AbsoluteRect.getHeight()) ); + ScrollBar->setMax(core::max_(0, TotalItemHeight - AbsoluteRect.getHeight())); s32 minItemHeight = ItemHeight > 0 ? ItemHeight : 1; - ScrollBar->setSmallStep ( minItemHeight ); - ScrollBar->setLargeStep ( 2*minItemHeight ); + ScrollBar->setSmallStep(minItemHeight); + ScrollBar->setLargeStep(2 * minItemHeight); - if ( TotalItemHeight <= AbsoluteRect.getHeight() ) + if (TotalItemHeight <= AbsoluteRect.getHeight()) ScrollBar->setVisible(false); else ScrollBar->setVisible(true); @@ -195,11 +181,10 @@ s32 CGUIListBox::getSelected() const return Selected; } - //! sets the selected item. Set this to -1 if no item should be selected void CGUIListBox::setSelected(s32 id) { - if ((u32)id>=Items.size()) + if ((u32)id >= Items.size()) Selected = -1; else Selected = id; @@ -214,69 +199,61 @@ void CGUIListBox::setSelected(const wchar_t *item) { s32 index = -1; - if ( item ) - { - for ( index = 0; index < (s32) Items.size(); ++index ) - { - if ( Items[index].Text == item ) + if (item) { + for (index = 0; index < (s32)Items.size(); ++index) { + if (Items[index].Text == item) break; } } - setSelected ( index ); + setSelected(index); } //! called if an event happened. -bool CGUIListBox::OnEvent(const SEvent& event) +bool CGUIListBox::OnEvent(const SEvent &event) { - if (isEnabled()) - { - switch(event.EventType) - { + if (isEnabled()) { + switch (event.EventType) { case EET_KEY_INPUT_EVENT: if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_DOWN || - event.KeyInput.Key == KEY_UP || - event.KeyInput.Key == KEY_HOME || - event.KeyInput.Key == KEY_END || - event.KeyInput.Key == KEY_NEXT || - event.KeyInput.Key == KEY_PRIOR ) ) - { + (event.KeyInput.Key == KEY_DOWN || + event.KeyInput.Key == KEY_UP || + event.KeyInput.Key == KEY_HOME || + event.KeyInput.Key == KEY_END || + event.KeyInput.Key == KEY_NEXT || + event.KeyInput.Key == KEY_PRIOR)) { s32 oldSelected = Selected; - switch (event.KeyInput.Key) - { - case KEY_DOWN: - Selected += 1; - break; - case KEY_UP: - Selected -= 1; - break; - case KEY_HOME: - Selected = 0; - break; - case KEY_END: - Selected = (s32)Items.size()-1; - break; - case KEY_NEXT: - Selected += AbsoluteRect.getHeight() / ItemHeight; - break; - case KEY_PRIOR: - Selected -= AbsoluteRect.getHeight() / ItemHeight; - break; - default: - break; + switch (event.KeyInput.Key) { + case KEY_DOWN: + Selected += 1; + break; + case KEY_UP: + Selected -= 1; + break; + case KEY_HOME: + Selected = 0; + break; + case KEY_END: + Selected = (s32)Items.size() - 1; + break; + case KEY_NEXT: + Selected += AbsoluteRect.getHeight() / ItemHeight; + break; + case KEY_PRIOR: + Selected -= AbsoluteRect.getHeight() / ItemHeight; + break; + default: + break; } - if (Selected<0) + if (Selected < 0) Selected = 0; if (Selected >= (s32)Items.size()) - Selected = Items.size() - 1; // will set Selected to -1 for empty listboxes which is correct - + Selected = Items.size() - 1; // will set Selected to -1 for empty listboxes which is correct recalculateScrollPos(); // post the news - if (oldSelected != Selected && Parent && !Selecting && !MoveOverSelect) - { + if (oldSelected != Selected && Parent && !Selecting && !MoveOverSelect) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; @@ -286,12 +263,8 @@ bool CGUIListBox::OnEvent(const SEvent& event) } return true; - } - else - if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE ) ) - { - if (Parent) - { + } else if (!event.KeyInput.PressedDown && (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { + if (Parent) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; @@ -300,27 +273,19 @@ bool CGUIListBox::OnEvent(const SEvent& event) Parent->OnEvent(e); } return true; - } - else if (event.KeyInput.Key == KEY_TAB ) - { + } else if (event.KeyInput.Key == KEY_TAB) { return false; - } - else if (event.KeyInput.PressedDown && event.KeyInput.Char) - { + } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed. u32 now = os::Timer::getTime(); - if (now - LastKeyTime < 500) - { + if (now - LastKeyTime < 500) { // add to key buffer if it isn't a key repeat - if (!(KeyBuffer.size() == 1 && KeyBuffer[0] == event.KeyInput.Char)) - { + if (!(KeyBuffer.size() == 1 && KeyBuffer[0] == event.KeyInput.Char)) { KeyBuffer += L" "; - KeyBuffer[KeyBuffer.size()-1] = event.KeyInput.Char; + KeyBuffer[KeyBuffer.size() - 1] = event.KeyInput.Char; } - } - else - { + } else { KeyBuffer = L" "; KeyBuffer[0] = event.KeyInput.Char; } @@ -329,22 +294,17 @@ bool CGUIListBox::OnEvent(const SEvent& event) // find the selected item, starting at the current selection s32 start = Selected; // dont change selection if the key buffer matches the current item - if (Selected > -1 && KeyBuffer.size() > 1) - { + if (Selected > -1 && KeyBuffer.size() > 1) { if (Items[Selected].Text.size() >= KeyBuffer.size() && - KeyBuffer.equals_ignore_case(Items[Selected].Text.subString(0,KeyBuffer.size()))) + KeyBuffer.equals_ignore_case(Items[Selected].Text.subString(0, KeyBuffer.size()))) return true; } s32 current; - for (current = start+1; current < (s32)Items.size(); ++current) - { - if (Items[current].Text.size() >= KeyBuffer.size()) - { - if (KeyBuffer.equals_ignore_case(Items[current].Text.subString(0,KeyBuffer.size()))) - { - if (Parent && Selected != current && !Selecting && !MoveOverSelect) - { + for (current = start + 1; current < (s32)Items.size(); ++current) { + if (Items[current].Text.size() >= KeyBuffer.size()) { + if (KeyBuffer.equals_ignore_case(Items[current].Text.subString(0, KeyBuffer.size()))) { + if (Parent && Selected != current && !Selecting && !MoveOverSelect) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; @@ -357,14 +317,10 @@ bool CGUIListBox::OnEvent(const SEvent& event) } } } - for (current = 0; current <= start; ++current) - { - if (Items[current].Text.size() >= KeyBuffer.size()) - { - if (KeyBuffer.equals_ignore_case(Items[current].Text.subString(0,KeyBuffer.size()))) - { - if (Parent && Selected != current && !Selecting && !MoveOverSelect) - { + for (current = 0; current <= start; ++current) { + if (Items[current].Text.size() >= KeyBuffer.size()) { + if (KeyBuffer.equals_ignore_case(Items[current].Text.subString(0, KeyBuffer.size()))) { + if (Parent && Selected != current && !Selecting && !MoveOverSelect) { Selected = current; SEvent e; e.EventType = EET_GUI_EVENT; @@ -384,62 +340,53 @@ bool CGUIListBox::OnEvent(const SEvent& event) break; case EET_GUI_EVENT: - switch(event.GUIEvent.EventType) - { + switch (event.GUIEvent.EventType) { case gui::EGET_SCROLL_BAR_CHANGED: if (event.GUIEvent.Caller == ScrollBar) return true; break; - case gui::EGET_ELEMENT_FOCUS_LOST: - { - if (event.GUIEvent.Caller == this) - Selecting = false; + case gui::EGET_ELEMENT_FOCUS_LOST: { + if (event.GUIEvent.Caller == this) + Selecting = false; + } + default: + break; + } + break; + + case EET_MOUSE_INPUT_EVENT: { + core::position2d p(event.MouseInput.X, event.MouseInput.Y); + + switch (event.MouseInput.Event) { + case EMIE_MOUSE_WHEEL: + ScrollBar->setPos(ScrollBar->getPos() + (event.MouseInput.Wheel < 0 ? -1 : 1) * -ItemHeight / 2); + return true; + + case EMIE_LMOUSE_PRESSED_DOWN: { + Selecting = true; + return true; + } + + case EMIE_LMOUSE_LEFT_UP: { + Selecting = false; + + if (isPointInside(p)) + selectNew(event.MouseInput.Y); + + return true; + } + + case EMIE_MOUSE_MOVED: + if (Selecting || MoveOverSelect) { + if (isPointInside(p)) { + selectNew(event.MouseInput.Y, true); + return true; + } } default: - break; - } - break; - - case EET_MOUSE_INPUT_EVENT: - { - core::position2d p(event.MouseInput.X, event.MouseInput.Y); - - switch(event.MouseInput.Event) - { - case EMIE_MOUSE_WHEEL: - ScrollBar->setPos(ScrollBar->getPos() + (event.MouseInput.Wheel < 0 ? -1 : 1)*-ItemHeight/2); - return true; - - case EMIE_LMOUSE_PRESSED_DOWN: - { - Selecting = true; - return true; - } - - case EMIE_LMOUSE_LEFT_UP: - { - Selecting = false; - - if (isPointInside(p)) - selectNew(event.MouseInput.Y); - - return true; - } - - case EMIE_MOUSE_MOVED: - if (Selecting || MoveOverSelect) - { - if (isPointInside(p)) - { - selectNew(event.MouseInput.Y, true); - return true; - } - } - default: break; - } } - break; + } break; default: break; } @@ -448,14 +395,13 @@ bool CGUIListBox::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - void CGUIListBox::selectNew(s32 ypos, bool onlyHover) { u32 now = os::Timer::getTime(); s32 oldSelected = Selected; Selected = getItemAt(AbsoluteRect.UpperLeftCorner.X, ypos); - if (Selected<0 && !Items.empty()) + if (Selected < 0 && !Items.empty()) Selected = 0; recalculateScrollPos(); @@ -463,8 +409,7 @@ void CGUIListBox::selectNew(s32 ypos, bool onlyHover) gui::EGUI_EVENT_TYPE eventType = (Selected == oldSelected && now < selectTime + 500) ? EGET_LISTBOX_SELECTED_AGAIN : EGET_LISTBOX_CHANGED; selectTime = now; // post the news - if (Parent && !onlyHover) - { + if (Parent && !onlyHover) { SEvent event; event.EventType = EET_GUI_EVENT; event.GUIEvent.Caller = this; @@ -474,7 +419,6 @@ void CGUIListBox::selectNew(s32 ypos, bool onlyHover) } } - //! Update the position and size of the listbox, and update the scrollbar void CGUIListBox::updateAbsolutePosition() { @@ -483,7 +427,6 @@ void CGUIListBox::updateAbsolutePosition() recalculateItemHeight(); } - //! draws the element and its children void CGUIListBox::draw() { @@ -492,10 +435,10 @@ void CGUIListBox::draw() recalculateItemHeight(); // if the font changed - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); updateScrollBarSize(skin->getSize(EGDS_SCROLLBAR_SIZE)); - core::rect* clipRect = 0; + core::rect *clipRect = 0; // draw background core::rect frameRect(AbsoluteRect); @@ -511,7 +454,7 @@ void CGUIListBox::draw() clientClip.clipAgainst(AbsoluteClippingRect); skin->draw3DSunkenPane(this, skin->getColor(EGDC_3D_HIGH_LIGHT), true, - DrawBack, frameRect, &AbsoluteClippingRect); + DrawBack, frameRect, &AbsoluteClippingRect); if (clipRect) clientClip.clipAgainst(*clipRect); @@ -528,57 +471,45 @@ void CGUIListBox::draw() bool hl = (HighlightWhenNotFocused || Environment->hasFocus(this) || Environment->hasFocus(ScrollBar)); - for (s32 i=0; i<(s32)Items.size(); ++i) - { + for (s32 i = 0; i < (s32)Items.size(); ++i) { if (frameRect.LowerRightCorner.Y >= AbsoluteRect.UpperLeftCorner.Y && - frameRect.UpperLeftCorner.Y <= AbsoluteRect.LowerRightCorner.Y) - { + frameRect.UpperLeftCorner.Y <= AbsoluteRect.LowerRightCorner.Y) { if (i == Selected && hl) skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), frameRect, &clientClip); core::rect textRect = frameRect; textRect.UpperLeftCorner.X += 3; - if (Font) - { - if (IconBank && (Items[i].Icon > -1)) - { + if (Font) { + if (IconBank && (Items[i].Icon > -1)) { core::position2di iconPos = textRect.UpperLeftCorner; iconPos.Y += textRect.getHeight() / 2; - iconPos.X += ItemsIconWidth/2; + iconPos.X += ItemsIconWidth / 2; - if ( i==Selected && hl ) - { - IconBank->draw2DSprite( (u32)Items[i].Icon, iconPos, &clientClip, - hasItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) ? - getItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_ICON_HIGHLIGHT), - selectTime, os::Timer::getTime(), false, true); - } - else - { - IconBank->draw2DSprite( (u32)Items[i].Icon, iconPos, &clientClip, - hasItemOverrideColor(i, EGUI_LBC_ICON) ? getItemOverrideColor(i, EGUI_LBC_ICON) : getItemDefaultColor(EGUI_LBC_ICON), - 0 , (i==Selected) ? os::Timer::getTime() : 0, false, true); + if (i == Selected && hl) { + IconBank->draw2DSprite((u32)Items[i].Icon, iconPos, &clientClip, + hasItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) ? getItemOverrideColor(i, EGUI_LBC_ICON_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_ICON_HIGHLIGHT), + selectTime, os::Timer::getTime(), false, true); + } else { + IconBank->draw2DSprite((u32)Items[i].Icon, iconPos, &clientClip, + hasItemOverrideColor(i, EGUI_LBC_ICON) ? getItemOverrideColor(i, EGUI_LBC_ICON) : getItemDefaultColor(EGUI_LBC_ICON), + 0, (i == Selected) ? os::Timer::getTime() : 0, false, true); } } - textRect.UpperLeftCorner.X += ItemsIconWidth+3; + textRect.UpperLeftCorner.X += ItemsIconWidth + 3; - if ( i==Selected && hl ) - { + if (i == Selected && hl) { Font->draw(Items[i].Text.c_str(), textRect, - hasItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) ? - getItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_TEXT_HIGHLIGHT), - false, true, &clientClip); - } - else - { + hasItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) ? getItemOverrideColor(i, EGUI_LBC_TEXT_HIGHLIGHT) : getItemDefaultColor(EGUI_LBC_TEXT_HIGHLIGHT), + false, true, &clientClip); + } else { Font->draw(Items[i].Text.c_str(), textRect, - hasItemOverrideColor(i, EGUI_LBC_TEXT) ? getItemOverrideColor(i, EGUI_LBC_TEXT) : getItemDefaultColor(EGUI_LBC_TEXT), - false, true, &clientClip); + hasItemOverrideColor(i, EGUI_LBC_TEXT) ? getItemOverrideColor(i, EGUI_LBC_TEXT) : getItemDefaultColor(EGUI_LBC_TEXT), + false, true, &clientClip); } - textRect.UpperLeftCorner.X -= ItemsIconWidth+3; + textRect.UpperLeftCorner.X -= ItemsIconWidth + 3; } } @@ -589,9 +520,8 @@ void CGUIListBox::draw() IGUIElement::draw(); } - //! adds an list item with an icon -u32 CGUIListBox::addItem(const wchar_t* text, s32 icon) +u32 CGUIListBox::addItem(const wchar_t *text, s32 icon) { ListItem i; i.Text = text; @@ -604,10 +534,9 @@ u32 CGUIListBox::addItem(const wchar_t* text, s32 icon) return Items.size() - 1; } - -void CGUIListBox::setSpriteBank(IGUISpriteBank* bank) +void CGUIListBox::setSpriteBank(IGUISpriteBank *bank) { - if ( bank == IconBank ) + if (bank == IconBank) return; if (IconBank) IconBank->drop(); @@ -617,7 +546,6 @@ void CGUIListBox::setSpriteBank(IGUISpriteBank* bank) IconBank->grab(); } - void CGUIListBox::recalculateScrollPos() { if (!AutoScroll) @@ -625,21 +553,16 @@ void CGUIListBox::recalculateScrollPos() const s32 selPos = (getSelected() == -1 ? TotalItemHeight : getSelected() * ItemHeight) - ScrollBar->getPos(); - if (selPos < 0) - { + if (selPos < 0) { ScrollBar->setPos(ScrollBar->getPos() + selPos); - } - else - if (selPos > AbsoluteRect.getHeight() - ItemHeight) - { + } else if (selPos > AbsoluteRect.getHeight() - ItemHeight) { ScrollBar->setPos(ScrollBar->getPos() + selPos - AbsoluteRect.getHeight() + ItemHeight); } } void CGUIListBox::updateScrollBarSize(s32 size) { - if ( size != ScrollBar->getRelativePosition().getWidth() ) - { + if (size != ScrollBar->getRelativePosition().getWidth()) { core::recti r(RelativeRect.getWidth() - size, 0, RelativeRect.getWidth(), RelativeRect.getHeight()); ScrollBar->setRelativePosition(r); } @@ -650,17 +573,14 @@ void CGUIListBox::setAutoScrollEnabled(bool scroll) AutoScroll = scroll; } - bool CGUIListBox::isAutoScrollEnabled() const { return AutoScroll; } - -bool CGUIListBox::getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc & useColorLabel, core::stringc & colorLabel) const +bool CGUIListBox::getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc &useColorLabel, core::stringc &colorLabel) const { - switch ( colorType ) - { + switch (colorType) { case EGUI_LBC_TEXT: useColorLabel = "UseColText"; colorLabel = "ColText"; @@ -683,16 +603,13 @@ bool CGUIListBox::getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::str return true; } - void CGUIListBox::recalculateItemWidth(s32 icon) { if (IconBank && icon > -1 && - IconBank->getSprites().size() > (u32)icon && - IconBank->getSprites()[(u32)icon].Frames.size()) - { + IconBank->getSprites().size() > (u32)icon && + IconBank->getSprites()[(u32)icon].Frames.size()) { u32 rno = IconBank->getSprites()[(u32)icon].Frames[0].rectNumber; - if (IconBank->getPositions().size() > rno) - { + if (IconBank->getPositions().size() > rno) { const s32 w = IconBank->getPositions()[rno].getWidth(); if (w > ItemsIconWidth) ItemsIconWidth = w; @@ -700,10 +617,9 @@ void CGUIListBox::recalculateItemWidth(s32 icon) } } - -void CGUIListBox::setItem(u32 index, const wchar_t* text, s32 icon) +void CGUIListBox::setItem(u32 index, const wchar_t *text, s32 icon) { - if ( index >= Items.size() ) + if (index >= Items.size()) return; Items[index].Text = text; @@ -713,10 +629,9 @@ void CGUIListBox::setItem(u32 index, const wchar_t* text, s32 icon) recalculateItemWidth(icon); } - //! Insert the item at the given index //! Return the index on success or -1 on failure. -s32 CGUIListBox::insertItem(u32 index, const wchar_t* text, s32 icon) +s32 CGUIListBox::insertItem(u32 index, const wchar_t *text, s32 icon) { ListItem i; i.Text = text; @@ -729,10 +644,9 @@ s32 CGUIListBox::insertItem(u32 index, const wchar_t* text, s32 icon) return index; } - void CGUIListBox::swapItems(u32 index1, u32 index2) { - if ( index1 >= Items.size() || index2 >= Items.size() ) + if (index1 >= Items.size() || index2 >= Items.size()) return; ListItem dummmy = Items[index1]; @@ -740,100 +654,89 @@ void CGUIListBox::swapItems(u32 index1, u32 index2) Items[index2] = dummmy; } - void CGUIListBox::setItemOverrideColor(u32 index, video::SColor color) { - for ( u32 c=0; c < EGUI_LBC_COUNT; ++c ) - { + for (u32 c = 0; c < EGUI_LBC_COUNT; ++c) { Items[index].OverrideColors[c].Use = true; Items[index].OverrideColors[c].Color = color; } } - void CGUIListBox::setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, video::SColor color) { - if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT ) + if (index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT) return; Items[index].OverrideColors[colorType].Use = true; Items[index].OverrideColors[colorType].Color = color; } - void CGUIListBox::clearItemOverrideColor(u32 index) { - for (u32 c=0; c < (u32)EGUI_LBC_COUNT; ++c ) - { + for (u32 c = 0; c < (u32)EGUI_LBC_COUNT; ++c) { Items[index].OverrideColors[c].Use = false; } } - void CGUIListBox::clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) { - if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT ) + if (index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT) return; Items[index].OverrideColors[colorType].Use = false; } - bool CGUIListBox::hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const { - if ( index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT ) + if (index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT) return false; return Items[index].OverrideColors[colorType].Use; } - video::SColor CGUIListBox::getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const { - if ( (u32)index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT ) + if ((u32)index >= Items.size() || colorType < 0 || colorType >= EGUI_LBC_COUNT) return video::SColor(); return Items[index].OverrideColors[colorType].Color; } - video::SColor CGUIListBox::getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const { - IGUISkin* skin = Environment->getSkin(); - if ( !skin ) + IGUISkin *skin = Environment->getSkin(); + if (!skin) return video::SColor(); - switch ( colorType ) - { - case EGUI_LBC_TEXT: - return skin->getColor(EGDC_BUTTON_TEXT); - case EGUI_LBC_TEXT_HIGHLIGHT: - return skin->getColor(EGDC_HIGH_LIGHT_TEXT); - case EGUI_LBC_ICON: - return skin->getColor(EGDC_ICON); - case EGUI_LBC_ICON_HIGHLIGHT: - return skin->getColor(EGDC_ICON_HIGH_LIGHT); - default: - return video::SColor(); + switch (colorType) { + case EGUI_LBC_TEXT: + return skin->getColor(EGDC_BUTTON_TEXT); + case EGUI_LBC_TEXT_HIGHLIGHT: + return skin->getColor(EGDC_HIGH_LIGHT_TEXT); + case EGUI_LBC_ICON: + return skin->getColor(EGDC_ICON); + case EGUI_LBC_ICON_HIGHLIGHT: + return skin->getColor(EGDC_ICON_HIGH_LIGHT); + default: + return video::SColor(); } } //! set global itemHeight -void CGUIListBox::setItemHeight( s32 height ) +void CGUIListBox::setItemHeight(s32 height) { ItemHeight = height; ItemHeightOverride = 1; } - //! Sets whether to draw the background void CGUIListBox::setDrawBackground(bool draw) { - DrawBack = draw; + DrawBack = draw; } //! Access the vertical scrollbar -IGUIScrollBar* CGUIListBox::getVerticalScrollBar() const +IGUIScrollBar *CGUIListBox::getVerticalScrollBar() const { return ScrollBar; } diff --git a/source/Irrlicht/CGUIListBox.h b/source/Irrlicht/CGUIListBox.h index 26cbdc5d..ea1eaebd 100644 --- a/source/Irrlicht/CGUIListBox.h +++ b/source/Irrlicht/CGUIListBox.h @@ -12,164 +12,162 @@ namespace irr namespace gui { - class IGUIFont; - class IGUIScrollBar; +class IGUIFont; +class IGUIScrollBar; - class CGUIListBox : public IGUIListBox +class CGUIListBox : public IGUIListBox +{ +public: + //! constructor + CGUIListBox(IGUIEnvironment *environment, IGUIElement *parent, + s32 id, core::rect rectangle, bool clip = true, + bool drawBack = false, bool moveOverSelect = false); + + //! destructor + virtual ~CGUIListBox(); + + //! returns amount of list items + u32 getItemCount() const override; + + //! returns string of a list item. the id may be a value from 0 to itemCount-1 + const wchar_t *getListItem(u32 id) const override; + + //! adds an list item, returns id of item + u32 addItem(const wchar_t *text) override; + + //! clears the list + void clear() override; + + //! returns id of selected item. returns -1 if no item is selected. + s32 getSelected() const override; + + //! sets the selected item. Set this to -1 if no item should be selected + void setSelected(s32 id) override; + + //! sets the selected item. Set this to -1 if no item should be selected + void setSelected(const wchar_t *item) override; + + //! called if an event happened. + bool OnEvent(const SEvent &event) override; + + //! draws the element and its children + void draw() override; + + //! adds an list item with an icon + //! \param text Text of list entry + //! \param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon + //! \return + //! returns the id of the new created item + u32 addItem(const wchar_t *text, s32 icon) override; + + //! Returns the icon of an item + s32 getIcon(u32 id) const override; + + //! removes an item from the list + void removeItem(u32 id) override; + + //! get the the id of the item at the given absolute coordinates + s32 getItemAt(s32 xpos, s32 ypos) const override; + + //! Sets the sprite bank which should be used to draw list icons. This font is set to the sprite bank of + //! the built-in-font by default. A sprite can be displayed in front of every list item. + //! An icon is an index within the icon sprite bank. Several default icons are available in the + //! skin through getIcon + void setSpriteBank(IGUISpriteBank *bank) override; + + //! set whether the listbox should scroll to newly selected items + void setAutoScrollEnabled(bool scroll) override; + + //! returns true if automatic scrolling is enabled, false if not. + bool isAutoScrollEnabled() const override; + + //! Update the position and size of the listbox, and update the scrollbar + void updateAbsolutePosition() override; + + //! set all item colors at given index to color + void setItemOverrideColor(u32 index, video::SColor color) override; + + //! set all item colors of specified type at given index to color + void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, video::SColor color) override; + + //! clear all item colors at index + void clearItemOverrideColor(u32 index) override; + + //! clear item color at index for given colortype + void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) override; + + //! has the item at index its color overwritten? + bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const override; + + //! return the overwrite color at given item index. + video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const override; + + //! return the default color which is used for the given colorType + video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const override; + + //! set the item at the given index + void setItem(u32 index, const wchar_t *text, s32 icon) override; + + //! Insert the item at the given index + //! Return the index on success or -1 on failure. + s32 insertItem(u32 index, const wchar_t *text, s32 icon) override; + + //! Swap the items at the given indices + void swapItems(u32 index1, u32 index2) override; + + //! set global itemHeight + void setItemHeight(s32 height) override; + + //! Sets whether to draw the background + void setDrawBackground(bool draw) override; + + //! Access the vertical scrollbar + IGUIScrollBar *getVerticalScrollBar() const override; + +private: + struct ListItem { - public: - //! constructor - CGUIListBox(IGUIEnvironment* environment, IGUIElement* parent, - s32 id, core::rect rectangle, bool clip=true, - bool drawBack=false, bool moveOverSelect=false); + core::stringw Text; + s32 Icon = -1; - //! destructor - virtual ~CGUIListBox(); - - //! returns amount of list items - u32 getItemCount() const override; - - //! returns string of a list item. the id may be a value from 0 to itemCount-1 - const wchar_t* getListItem(u32 id) const override; - - //! adds an list item, returns id of item - u32 addItem(const wchar_t* text) override; - - //! clears the list - void clear() override; - - //! returns id of selected item. returns -1 if no item is selected. - s32 getSelected() const override; - - //! sets the selected item. Set this to -1 if no item should be selected - void setSelected(s32 id) override; - - //! sets the selected item. Set this to -1 if no item should be selected - void setSelected(const wchar_t *item) override; - - //! called if an event happened. - bool OnEvent(const SEvent& event) override; - - //! draws the element and its children - void draw() override; - - //! adds an list item with an icon - //! \param text Text of list entry - //! \param icon Sprite index of the Icon within the current sprite bank. Set it to -1 if you want no icon - //! \return - //! returns the id of the new created item - u32 addItem(const wchar_t* text, s32 icon) override; - - //! Returns the icon of an item - s32 getIcon(u32 id) const override; - - //! removes an item from the list - void removeItem(u32 id) override; - - //! get the the id of the item at the given absolute coordinates - s32 getItemAt(s32 xpos, s32 ypos) const override; - - //! Sets the sprite bank which should be used to draw list icons. This font is set to the sprite bank of - //! the built-in-font by default. A sprite can be displayed in front of every list item. - //! An icon is an index within the icon sprite bank. Several default icons are available in the - //! skin through getIcon - void setSpriteBank(IGUISpriteBank* bank) override; - - //! set whether the listbox should scroll to newly selected items - void setAutoScrollEnabled(bool scroll) override; - - //! returns true if automatic scrolling is enabled, false if not. - bool isAutoScrollEnabled() const override; - - //! Update the position and size of the listbox, and update the scrollbar - void updateAbsolutePosition() override; - - //! set all item colors at given index to color - void setItemOverrideColor(u32 index, video::SColor color) override; - - //! set all item colors of specified type at given index to color - void setItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType, video::SColor color) override; - - //! clear all item colors at index - void clearItemOverrideColor(u32 index) override; - - //! clear item color at index for given colortype - void clearItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) override; - - //! has the item at index its color overwritten? - bool hasItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const override; - - //! return the overwrite color at given item index. - video::SColor getItemOverrideColor(u32 index, EGUI_LISTBOX_COLOR colorType) const override; - - //! return the default color which is used for the given colorType - video::SColor getItemDefaultColor(EGUI_LISTBOX_COLOR colorType) const override; - - //! set the item at the given index - void setItem(u32 index, const wchar_t* text, s32 icon) override; - - //! Insert the item at the given index - //! Return the index on success or -1 on failure. - s32 insertItem(u32 index, const wchar_t* text, s32 icon) override; - - //! Swap the items at the given indices - void swapItems(u32 index1, u32 index2) override; - - //! set global itemHeight - void setItemHeight( s32 height ) override; - - //! Sets whether to draw the background - void setDrawBackground(bool draw) override; - - //! Access the vertical scrollbar - IGUIScrollBar* getVerticalScrollBar() const override; - - private: - - struct ListItem + // A multicolor extension + struct ListItemOverrideColor { - core::stringw Text; - s32 Icon = -1; - - // A multicolor extension - struct ListItemOverrideColor - { - bool Use = false; - video::SColor Color; - }; - ListItemOverrideColor OverrideColors[EGUI_LBC_COUNT]{}; + bool Use = false; + video::SColor Color; }; - - void recalculateItemHeight(); - void selectNew(s32 ypos, bool onlyHover=false); - void recalculateScrollPos(); - void updateScrollBarSize(s32 size); - - // extracted that function to avoid copy&paste code - void recalculateItemWidth(s32 icon); - - // get labels used for serialization - bool getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc & useColorLabel, core::stringc & colorLabel) const; - - core::array< ListItem > Items; - s32 Selected; - s32 ItemHeight; - s32 ItemHeightOverride; - s32 TotalItemHeight; - s32 ItemsIconWidth; - gui::IGUIFont* Font; - gui::IGUISpriteBank* IconBank; - gui::IGUIScrollBar* ScrollBar; - u32 selectTime; - u32 LastKeyTime; - core::stringw KeyBuffer; - bool Selecting; - bool DrawBack; - bool MoveOverSelect; - bool AutoScroll; - bool HighlightWhenNotFocused; + ListItemOverrideColor OverrideColors[EGUI_LBC_COUNT]{}; }; + void recalculateItemHeight(); + void selectNew(s32 ypos, bool onlyHover = false); + void recalculateScrollPos(); + void updateScrollBarSize(s32 size); + + // extracted that function to avoid copy&paste code + void recalculateItemWidth(s32 icon); + + // get labels used for serialization + bool getSerializationLabels(EGUI_LISTBOX_COLOR colorType, core::stringc &useColorLabel, core::stringc &colorLabel) const; + + core::array Items; + s32 Selected; + s32 ItemHeight; + s32 ItemHeightOverride; + s32 TotalItemHeight; + s32 ItemsIconWidth; + gui::IGUIFont *Font; + gui::IGUISpriteBank *IconBank; + gui::IGUIScrollBar *ScrollBar; + u32 selectTime; + u32 LastKeyTime; + core::stringw KeyBuffer; + bool Selecting; + bool DrawBack; + bool MoveOverSelect; + bool AutoScroll; + bool HighlightWhenNotFocused; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIScrollBar.cpp b/source/Irrlicht/CGUIScrollBar.cpp index ad2af503..f9ebad09 100644 --- a/source/Irrlicht/CGUIScrollBar.cpp +++ b/source/Irrlicht/CGUIScrollBar.cpp @@ -17,20 +17,20 @@ namespace irr namespace gui { - //! constructor -CGUIScrollBar::CGUIScrollBar(bool horizontal, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, - core::rect rectangle, bool noclip) - : IGUIScrollBar(environment, parent, id, rectangle), UpButton(0), - DownButton(0), Dragging(false), Horizontal(horizontal), - DraggedBySlider(false), TrayClick(false), Pos(0), DrawPos(0), - DrawHeight(0), Min(0), Max(100), SmallStep(10), LargeStep(50), DesiredPos(0), - LastChange(0) +CGUIScrollBar::CGUIScrollBar(bool horizontal, IGUIEnvironment *environment, + IGUIElement *parent, s32 id, + core::rect rectangle, bool noclip) : + IGUIScrollBar(environment, parent, id, rectangle), + UpButton(0), + DownButton(0), Dragging(false), Horizontal(horizontal), + DraggedBySlider(false), TrayClick(false), Pos(0), DrawPos(0), + DrawHeight(0), Min(0), Max(100), SmallStep(10), LargeStep(50), DesiredPos(0), + LastChange(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIScrollBar"); - #endif +#endif refreshControls(); @@ -43,7 +43,6 @@ CGUIScrollBar::CGUIScrollBar(bool horizontal, IGUIEnvironment* environment, setPos(0); } - //! destructor CGUIScrollBar::~CGUIScrollBar() { @@ -54,48 +53,42 @@ CGUIScrollBar::~CGUIScrollBar() DownButton->drop(); } - //! called if an event happened. -bool CGUIScrollBar::OnEvent(const SEvent& event) +bool CGUIScrollBar::OnEvent(const SEvent &event) { - if (isEnabled()) - { + if (isEnabled()) { - switch(event.EventType) - { + switch (event.EventType) { case EET_KEY_INPUT_EVENT: - if (event.KeyInput.PressedDown) - { + if (event.KeyInput.PressedDown) { const s32 oldPos = Pos; bool absorb = true; - switch (event.KeyInput.Key) - { + switch (event.KeyInput.Key) { case KEY_LEFT: case KEY_UP: - setPos(Pos-SmallStep); + setPos(Pos - SmallStep); break; case KEY_RIGHT: case KEY_DOWN: - setPos(Pos+SmallStep); + setPos(Pos + SmallStep); break; case KEY_HOME: setPos(Min); break; case KEY_PRIOR: - setPos(Pos-LargeStep); + setPos(Pos - LargeStep); break; case KEY_END: setPos(Max); break; case KEY_NEXT: - setPos(Pos+LargeStep); + setPos(Pos + LargeStep); break; default: absorb = false; } - if (Pos != oldPos) - { + if (Pos != oldPos) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; @@ -108,13 +101,11 @@ bool CGUIScrollBar::OnEvent(const SEvent& event) } break; case EET_GUI_EVENT: - if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED) - { + if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED) { if (event.GUIEvent.Caller == UpButton) - setPos(Pos-SmallStep); - else - if (event.GUIEvent.Caller == DownButton) - setPos(Pos+SmallStep); + setPos(Pos - SmallStep); + else if (event.GUIEvent.Caller == DownButton) + setPos(Pos + SmallStep); SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; @@ -124,29 +115,22 @@ bool CGUIScrollBar::OnEvent(const SEvent& event) Parent->OnEvent(newEvent); return true; - } - else - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) - { + } else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == this) Dragging = false; } break; - case EET_MOUSE_INPUT_EVENT: - { + case EET_MOUSE_INPUT_EVENT: { const core::position2di p(event.MouseInput.X, event.MouseInput.Y); - bool isInside = isPointInside ( p ); - switch(event.MouseInput.Event) - { + bool isInside = isPointInside(p); + switch (event.MouseInput.Event) { case EMIE_MOUSE_WHEEL: - if (Environment->hasFocus(this)) - { + if (Environment->hasFocus(this)) { // thanks to a bug report by REAPER // thanks to tommi by tommi for another bugfix // everybody needs a little thanking. hallo niko!;-) - setPos( getPos() + - ( (event.MouseInput.Wheel < 0 ? -1 : 1) * SmallStep * (Horizontal ? 1 : -1 ) ) - ); + setPos(getPos() + + ((event.MouseInput.Wheel < 0 ? -1 : 1) * SmallStep * (Horizontal ? 1 : -1))); SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; @@ -157,10 +141,8 @@ bool CGUIScrollBar::OnEvent(const SEvent& event) return true; } break; - case EMIE_LMOUSE_PRESSED_DOWN: - { - if (isInside) - { + case EMIE_LMOUSE_PRESSED_DOWN: { + if (isInside) { Dragging = true; DraggedBySlider = SliderRect.isPointInside(p); TrayClick = !DraggedBySlider; @@ -170,55 +152,44 @@ bool CGUIScrollBar::OnEvent(const SEvent& event) break; } case EMIE_LMOUSE_LEFT_UP: - case EMIE_MOUSE_MOVED: - { - if ( !event.MouseInput.isLeftPressed () ) + case EMIE_MOUSE_MOVED: { + if (!event.MouseInput.isLeftPressed()) Dragging = false; - if ( !Dragging ) - { - if ( event.MouseInput.Event == EMIE_MOUSE_MOVED ) + if (!Dragging) { + if (event.MouseInput.Event == EMIE_MOUSE_MOVED) break; return isInside; } - if ( event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP ) + if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) Dragging = false; const s32 newPos = getPosFromMousePos(p); const s32 oldPos = Pos; - if (!DraggedBySlider) - { - if ( isInside ) - { + if (!DraggedBySlider) { + if (isInside) { DraggedBySlider = SliderRect.isPointInside(p); TrayClick = !DraggedBySlider; } - if (DraggedBySlider) - { + if (DraggedBySlider) { setPos(newPos); - } - else - { + } else { TrayClick = false; if (event.MouseInput.Event == EMIE_MOUSE_MOVED) return isInside; } } - if (DraggedBySlider) - { + if (DraggedBySlider) { setPos(newPos); - } - else - { + } else { DesiredPos = newPos; } - if (Pos != oldPos && Parent) - { + if (Pos != oldPos && Parent) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; @@ -243,23 +214,19 @@ bool CGUIScrollBar::OnEvent(const SEvent& event) void CGUIScrollBar::OnPostRender(u32 timeMs) { - if (Dragging && !DraggedBySlider && TrayClick && timeMs > LastChange + 200) - { + if (Dragging && !DraggedBySlider && TrayClick && timeMs > LastChange + 200) { LastChange = timeMs; const s32 oldPos = Pos; if (DesiredPos >= Pos + LargeStep) setPos(Pos + LargeStep); - else - if (DesiredPos <= Pos - LargeStep) + else if (DesiredPos <= Pos - LargeStep) setPos(Pos - LargeStep); - else - if (DesiredPos >= Pos - LargeStep && DesiredPos <= Pos + LargeStep) + else if (DesiredPos >= Pos - LargeStep && DesiredPos <= Pos + LargeStep) setPos(DesiredPos); - if (Pos != oldPos && Parent) - { + if (Pos != oldPos && Parent) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; @@ -268,7 +235,6 @@ void CGUIScrollBar::OnPostRender(u32 timeMs) Parent->OnEvent(newEvent); } } - } //! draws the element and its children @@ -277,34 +243,27 @@ void CGUIScrollBar::draw() if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (!skin) return; - video::SColor iconColor = skin->getColor(isEnabled() ? EGDC_WINDOW_SYMBOL : EGDC_GRAY_WINDOW_SYMBOL); - if ( iconColor != CurrentIconColor ) - { + if (iconColor != CurrentIconColor) { refreshControls(); } - SliderRect = AbsoluteRect; // draws the background skin->draw2DRectangle(this, skin->getColor(EGDC_SCROLLBAR), SliderRect, &AbsoluteClippingRect); - if ( core::isnotzero ( range() ) ) - { + if (core::isnotzero(range())) { // recalculate slider rectangle - if (Horizontal) - { - SliderRect.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X + DrawPos + RelativeRect.getHeight() - DrawHeight/2; + if (Horizontal) { + SliderRect.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X + DrawPos + RelativeRect.getHeight() - DrawHeight / 2; SliderRect.LowerRightCorner.X = SliderRect.UpperLeftCorner.X + DrawHeight; - } - else - { - SliderRect.UpperLeftCorner.Y = AbsoluteRect.UpperLeftCorner.Y + DrawPos + RelativeRect.getWidth() - DrawHeight/2; + } else { + SliderRect.UpperLeftCorner.Y = AbsoluteRect.UpperLeftCorner.Y + DrawPos + RelativeRect.getWidth() - DrawHeight / 2; SliderRect.LowerRightCorner.Y = SliderRect.UpperLeftCorner.Y + DrawHeight; } @@ -315,64 +274,53 @@ void CGUIScrollBar::draw() IGUIElement::draw(); } - void CGUIScrollBar::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); // todo: properly resize refreshControls(); - setPos ( Pos ); + setPos(Pos); } //! s32 CGUIScrollBar::getPosFromMousePos(const core::position2di &pos) const { f32 w, p; - if (Horizontal) - { - w = RelativeRect.getWidth() - f32(RelativeRect.getHeight())*3.0f; - p = pos.X - AbsoluteRect.UpperLeftCorner.X - RelativeRect.getHeight()*1.5f; + if (Horizontal) { + w = RelativeRect.getWidth() - f32(RelativeRect.getHeight()) * 3.0f; + p = pos.X - AbsoluteRect.UpperLeftCorner.X - RelativeRect.getHeight() * 1.5f; + } else { + w = RelativeRect.getHeight() - f32(RelativeRect.getWidth()) * 3.0f; + p = pos.Y - AbsoluteRect.UpperLeftCorner.Y - RelativeRect.getWidth() * 1.5f; } - else - { - w = RelativeRect.getHeight() - f32(RelativeRect.getWidth())*3.0f; - p = pos.Y - AbsoluteRect.UpperLeftCorner.Y - RelativeRect.getWidth()*1.5f; - } - return (s32) ( p/w * range() ) + Min; + return (s32)(p / w * range()) + Min; } - //! sets the position of the scrollbar void CGUIScrollBar::setPos(s32 pos) { - Pos = core::s32_clamp ( pos, Min, Max ); + Pos = core::s32_clamp(pos, Min, Max); - if ( core::isnotzero ( range() ) ) - { - if (Horizontal) - { - f32 f = (RelativeRect.getWidth() - ((f32)RelativeRect.getHeight()*3.0f)) / range(); - DrawPos = (s32)( ( ( Pos - Min ) * f) + ((f32)RelativeRect.getHeight() * 0.5f)); + if (core::isnotzero(range())) { + if (Horizontal) { + f32 f = (RelativeRect.getWidth() - ((f32)RelativeRect.getHeight() * 3.0f)) / range(); + DrawPos = (s32)(((Pos - Min) * f) + ((f32)RelativeRect.getHeight() * 0.5f)); DrawHeight = RelativeRect.getHeight(); - } - else - { - f32 f = (RelativeRect.getHeight() - ((f32)RelativeRect.getWidth()*3.0f)) / range(); + } else { + f32 f = (RelativeRect.getHeight() - ((f32)RelativeRect.getWidth() * 3.0f)) / range(); - DrawPos = (s32)( ( ( Pos - Min ) * f) + ((f32)RelativeRect.getWidth() * 0.5f)); + DrawPos = (s32)(((Pos - Min) * f) + ((f32)RelativeRect.getWidth() * 0.5f)); DrawHeight = RelativeRect.getWidth(); } } } - //! gets the small step value s32 CGUIScrollBar::getSmallStep() const { return SmallStep; } - //! sets the small step value void CGUIScrollBar::setSmallStep(s32 step) { @@ -382,14 +330,12 @@ void CGUIScrollBar::setSmallStep(s32 step) SmallStep = 10; } - //! gets the small step value s32 CGUIScrollBar::getLargeStep() const { return LargeStep; } - //! sets the small step value void CGUIScrollBar::setLargeStep(s32 step) { @@ -399,22 +345,20 @@ void CGUIScrollBar::setLargeStep(s32 step) LargeStep = 50; } - //! gets the maximum value of the scrollbar. s32 CGUIScrollBar::getMax() const { return Max; } - //! sets the maximum value of the scrollbar. void CGUIScrollBar::setMax(s32 max) { Max = max; - if ( Min > Max ) + if (Min > Max) Min = Max; - bool enable = core::isnotzero ( range() ); + bool enable = core::isnotzero(range()); UpButton->setEnabled(enable); DownButton->setEnabled(enable); setPos(Pos); @@ -426,107 +370,91 @@ s32 CGUIScrollBar::getMin() const return Min; } - //! sets the minimum value of the scrollbar. void CGUIScrollBar::setMin(s32 min) { Min = min; - if ( Max < Min ) + if (Max < Min) Max = Min; - - bool enable = core::isnotzero ( range() ); + bool enable = core::isnotzero(range()); UpButton->setEnabled(enable); DownButton->setEnabled(enable); setPos(Pos); } - //! gets the current position of the scrollbar s32 CGUIScrollBar::getPos() const { return Pos; } - //! refreshes the position and text on child buttons void CGUIScrollBar::refreshControls() { - CurrentIconColor = video::SColor(255,255,255,255); + CurrentIconColor = video::SColor(255, 255, 255, 255); - IGUISkin* skin = Environment->getSkin(); - IGUISpriteBank* sprites = 0; + IGUISkin *skin = Environment->getSkin(); + IGUISpriteBank *sprites = 0; - if (skin) - { + if (skin) { sprites = skin->getSpriteBank(); CurrentIconColor = skin->getColor(isEnabled() ? EGDC_WINDOW_SYMBOL : EGDC_GRAY_WINDOW_SYMBOL); } - if (Horizontal) - { + if (Horizontal) { const s32 h = RelativeRect.getHeight(); const s32 w = (h < RelativeRect.getWidth() / 2) ? h : RelativeRect.getWidth() / 2; - if (!UpButton) - { - UpButton = new CGUIButton(Environment, this, -1, core::rect(0,0, w, h), NoClip); + if (!UpButton) { + UpButton = new CGUIButton(Environment, this, -1, core::rect(0, 0, w, h), NoClip); UpButton->setSubElement(true); UpButton->setTabStop(false); } - if (sprites) - { + if (sprites) { UpButton->setSpriteBank(sprites); UpButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_LEFT), CurrentIconColor); UpButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_LEFT), CurrentIconColor); } - UpButton->setRelativePosition(core::rect(0,0, w, h)); + UpButton->setRelativePosition(core::rect(0, 0, w, h)); UpButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); - if (!DownButton) - { - DownButton = new CGUIButton(Environment, this, -1, core::rect(RelativeRect.getWidth()-w, 0, RelativeRect.getWidth(), h), NoClip); + if (!DownButton) { + DownButton = new CGUIButton(Environment, this, -1, core::rect(RelativeRect.getWidth() - w, 0, RelativeRect.getWidth(), h), NoClip); DownButton->setSubElement(true); DownButton->setTabStop(false); } - if (sprites) - { + if (sprites) { DownButton->setSpriteBank(sprites); DownButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_RIGHT), CurrentIconColor); DownButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_RIGHT), CurrentIconColor); } - DownButton->setRelativePosition(core::rect(RelativeRect.getWidth()-w, 0, RelativeRect.getWidth(), h)); + DownButton->setRelativePosition(core::rect(RelativeRect.getWidth() - w, 0, RelativeRect.getWidth(), h)); DownButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); - } - else - { + } else { const s32 w = RelativeRect.getWidth(); const s32 h = (w < RelativeRect.getHeight() / 2) ? w : RelativeRect.getHeight() / 2; - if (!UpButton) - { - UpButton = new CGUIButton(Environment, this, -1, core::rect(0,0, w, h), NoClip); + if (!UpButton) { + UpButton = new CGUIButton(Environment, this, -1, core::rect(0, 0, w, h), NoClip); UpButton->setSubElement(true); UpButton->setTabStop(false); } - if (sprites) - { + if (sprites) { UpButton->setSpriteBank(sprites); UpButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_UP), CurrentIconColor); UpButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_UP), CurrentIconColor); } - UpButton->setRelativePosition(core::rect(0,0, w, h)); + UpButton->setRelativePosition(core::rect(0, 0, w, h)); UpButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); - if (!DownButton) - { - DownButton = new CGUIButton(Environment, this, -1, core::rect(0,RelativeRect.getHeight()-h, w, RelativeRect.getHeight()), NoClip); + if (!DownButton) { + DownButton = new CGUIButton(Environment, this, -1, core::rect(0, RelativeRect.getHeight() - h, w, RelativeRect.getHeight()), NoClip); DownButton->setSubElement(true); DownButton->setTabStop(false); } - if (sprites) - { + if (sprites) { DownButton->setSpriteBank(sprites); DownButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_DOWN), CurrentIconColor); DownButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_DOWN), CurrentIconColor); } - DownButton->setRelativePosition(core::rect(0,RelativeRect.getHeight()-h, w, RelativeRect.getHeight())); + DownButton->setRelativePosition(core::rect(0, RelativeRect.getHeight() - h, w, RelativeRect.getHeight())); DownButton->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT); } } diff --git a/source/Irrlicht/CGUIScrollBar.h b/source/Irrlicht/CGUIScrollBar.h index 993bfd3a..82c5c5c2 100644 --- a/source/Irrlicht/CGUIScrollBar.h +++ b/source/Irrlicht/CGUIScrollBar.h @@ -12,87 +12,84 @@ namespace irr namespace gui { - class CGUIScrollBar : public IGUIScrollBar - { - public: +class CGUIScrollBar : public IGUIScrollBar +{ +public: + //! constructor + CGUIScrollBar(bool horizontal, IGUIEnvironment *environment, + IGUIElement *parent, s32 id, core::rect rectangle, + bool noclip = false); - //! constructor - CGUIScrollBar(bool horizontal, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, core::rect rectangle, - bool noclip=false); + //! destructor + virtual ~CGUIScrollBar(); - //! destructor - virtual ~CGUIScrollBar(); + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! draws the element and its children + void draw() override; - //! draws the element and its children - void draw() override; + void OnPostRender(u32 timeMs) override; - void OnPostRender(u32 timeMs) override; + //! gets the maximum value of the scrollbar. + s32 getMax() const override; + //! sets the maximum value of the scrollbar. + void setMax(s32 max) override; - //! gets the maximum value of the scrollbar. - s32 getMax() const override; + //! gets the minimum value of the scrollbar. + s32 getMin() const override; - //! sets the maximum value of the scrollbar. - void setMax(s32 max) override; + //! sets the minimum value of the scrollbar. + void setMin(s32 min) override; - //! gets the minimum value of the scrollbar. - s32 getMin() const override; + //! gets the small step value + s32 getSmallStep() const override; - //! sets the minimum value of the scrollbar. - void setMin(s32 min) override; + //! sets the small step value + void setSmallStep(s32 step) override; - //! gets the small step value - s32 getSmallStep() const override; + //! gets the large step value + s32 getLargeStep() const override; - //! sets the small step value - void setSmallStep(s32 step) override; + //! sets the large step value + void setLargeStep(s32 step) override; - //! gets the large step value - s32 getLargeStep() const override; + //! gets the current position of the scrollbar + s32 getPos() const override; - //! sets the large step value - void setLargeStep(s32 step) override; + //! sets the position of the scrollbar + void setPos(s32 pos) override; - //! gets the current position of the scrollbar - s32 getPos() const override; + //! updates the rectangle + void updateAbsolutePosition() override; - //! sets the position of the scrollbar - void setPos(s32 pos) override; +private: + void refreshControls(); + s32 getPosFromMousePos(const core::position2di &p) const; - //! updates the rectangle - void updateAbsolutePosition() override; + IGUIButton *UpButton; + IGUIButton *DownButton; - private: + core::rect SliderRect; - void refreshControls(); - s32 getPosFromMousePos(const core::position2di &p) const; + bool Dragging; + bool Horizontal; + bool DraggedBySlider; + bool TrayClick; + s32 Pos; + s32 DrawPos; + s32 DrawHeight; + s32 Min; + s32 Max; + s32 SmallStep; + s32 LargeStep; + s32 DesiredPos; + u32 LastChange; + video::SColor CurrentIconColor; - IGUIButton* UpButton; - IGUIButton* DownButton; - - core::rect SliderRect; - - bool Dragging; - bool Horizontal; - bool DraggedBySlider; - bool TrayClick; - s32 Pos; - s32 DrawPos; - s32 DrawHeight; - s32 Min; - s32 Max; - s32 SmallStep; - s32 LargeStep; - s32 DesiredPos; - u32 LastChange; - video::SColor CurrentIconColor; - - f32 range () const { return (f32) ( Max - Min ); } - }; + f32 range() const { return (f32)(Max - Min); } +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUISkin.cpp b/source/Irrlicht/CGUISkin.cpp index 79ae8c54..84976092 100644 --- a/source/Irrlicht/CGUISkin.cpp +++ b/source/Irrlicht/CGUISkin.cpp @@ -15,41 +15,39 @@ namespace irr namespace gui { -CGUISkin::CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver) -: SpriteBank(0), Driver(driver), Type(type) +CGUISkin::CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver *driver) : + SpriteBank(0), Driver(driver), Type(type) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUISkin"); - #endif - - if ((Type == EGST_WINDOWS_CLASSIC) || (Type == EGST_WINDOWS_METALLIC)) - { - Colors[EGDC_3D_DARK_SHADOW] = video::SColor(101,50,50,50); - Colors[EGDC_3D_SHADOW] = video::SColor(101,130,130,130); - Colors[EGDC_3D_FACE] = video::SColor(101,210,210,210); - Colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101,255,255,255); - Colors[EGDC_3D_LIGHT] = video::SColor(101,210,210,210); - Colors[EGDC_ACTIVE_BORDER] = video::SColor(101,16,14,115); - Colors[EGDC_ACTIVE_CAPTION] = video::SColor(255,255,255,255); - Colors[EGDC_APP_WORKSPACE] = video::SColor(101,100,100,100); - Colors[EGDC_BUTTON_TEXT] = video::SColor(240,10,10,10); - Colors[EGDC_GRAY_TEXT] = video::SColor(240,130,130,130); - Colors[EGDC_HIGH_LIGHT] = video::SColor(101,8,36,107); - Colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240,255,255,255); - Colors[EGDC_INACTIVE_BORDER] = video::SColor(101,165,165,165); - Colors[EGDC_INACTIVE_CAPTION] = video::SColor(255,30,30,30); - Colors[EGDC_TOOLTIP] = video::SColor(200,0,0,0); - Colors[EGDC_TOOLTIP_BACKGROUND] = video::SColor(200,255,255,225); - Colors[EGDC_SCROLLBAR] = video::SColor(101,230,230,230); - Colors[EGDC_WINDOW] = video::SColor(101,255,255,255); - Colors[EGDC_WINDOW_SYMBOL] = video::SColor(200,10,10,10); - Colors[EGDC_ICON] = video::SColor(200,255,255,255); - Colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200,8,36,107); - Colors[EGDC_GRAY_WINDOW_SYMBOL] = video::SColor(240,100,100,100); - Colors[EGDC_EDITABLE] = video::SColor(255,255,255,255); - Colors[EGDC_GRAY_EDITABLE] = video::SColor(255,120,120,120); - Colors[EGDC_FOCUSED_EDITABLE] = video::SColor(255,240,240,255); +#endif + if ((Type == EGST_WINDOWS_CLASSIC) || (Type == EGST_WINDOWS_METALLIC)) { + Colors[EGDC_3D_DARK_SHADOW] = video::SColor(101, 50, 50, 50); + Colors[EGDC_3D_SHADOW] = video::SColor(101, 130, 130, 130); + Colors[EGDC_3D_FACE] = video::SColor(101, 210, 210, 210); + Colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101, 255, 255, 255); + Colors[EGDC_3D_LIGHT] = video::SColor(101, 210, 210, 210); + Colors[EGDC_ACTIVE_BORDER] = video::SColor(101, 16, 14, 115); + Colors[EGDC_ACTIVE_CAPTION] = video::SColor(255, 255, 255, 255); + Colors[EGDC_APP_WORKSPACE] = video::SColor(101, 100, 100, 100); + Colors[EGDC_BUTTON_TEXT] = video::SColor(240, 10, 10, 10); + Colors[EGDC_GRAY_TEXT] = video::SColor(240, 130, 130, 130); + Colors[EGDC_HIGH_LIGHT] = video::SColor(101, 8, 36, 107); + Colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240, 255, 255, 255); + Colors[EGDC_INACTIVE_BORDER] = video::SColor(101, 165, 165, 165); + Colors[EGDC_INACTIVE_CAPTION] = video::SColor(255, 30, 30, 30); + Colors[EGDC_TOOLTIP] = video::SColor(200, 0, 0, 0); + Colors[EGDC_TOOLTIP_BACKGROUND] = video::SColor(200, 255, 255, 225); + Colors[EGDC_SCROLLBAR] = video::SColor(101, 230, 230, 230); + Colors[EGDC_WINDOW] = video::SColor(101, 255, 255, 255); + Colors[EGDC_WINDOW_SYMBOL] = video::SColor(200, 10, 10, 10); + Colors[EGDC_ICON] = video::SColor(200, 255, 255, 255); + Colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200, 8, 36, 107); + Colors[EGDC_GRAY_WINDOW_SYMBOL] = video::SColor(240, 100, 100, 100); + Colors[EGDC_EDITABLE] = video::SColor(255, 255, 255, 255); + Colors[EGDC_GRAY_EDITABLE] = video::SColor(255, 120, 120, 120); + Colors[EGDC_FOCUSED_EDITABLE] = video::SColor(255, 240, 240, 255); Sizes[EGDS_SCROLLBAR_SIZE] = 14; Sizes[EGDS_MENU_HEIGHT] = 30; @@ -65,36 +63,34 @@ CGUISkin::CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver) Sizes[EGDS_TITLEBARTEXT_DISTANCE_X] = 2; Sizes[EGDS_TITLEBARTEXT_DISTANCE_Y] = 0; - } - else - { - //0x80a6a8af - Colors[EGDC_3D_DARK_SHADOW] = 0x60767982; - //Colors[EGDC_3D_FACE] = 0xc0c9ccd4; // tab background - Colors[EGDC_3D_FACE] = 0xc0cbd2d9; // tab background - Colors[EGDC_3D_SHADOW] = 0x50e4e8f1; // tab background, and left-top highlight - Colors[EGDC_3D_HIGH_LIGHT] = 0x40c7ccdc; - Colors[EGDC_3D_LIGHT] = 0x802e313a; - Colors[EGDC_ACTIVE_BORDER] = 0x80404040; // window title - Colors[EGDC_ACTIVE_CAPTION] = 0xffd0d0d0; - Colors[EGDC_APP_WORKSPACE] = 0xc0646464; // unused - Colors[EGDC_BUTTON_TEXT] = 0xd0161616; - Colors[EGDC_GRAY_TEXT] = 0x3c141414; - Colors[EGDC_HIGH_LIGHT] = 0x6c606060; - Colors[EGDC_HIGH_LIGHT_TEXT] = 0xd0e0e0e0; - Colors[EGDC_INACTIVE_BORDER] = 0xf0a5a5a5; - Colors[EGDC_INACTIVE_CAPTION] = 0xffd2d2d2; - Colors[EGDC_TOOLTIP] = 0xf00f2033; - Colors[EGDC_TOOLTIP_BACKGROUND] = 0xc0cbd2d9; - Colors[EGDC_SCROLLBAR] = 0xf0e0e0e0; - Colors[EGDC_WINDOW] = 0xf0f0f0f0; - Colors[EGDC_WINDOW_SYMBOL] = 0xd0161616; - Colors[EGDC_ICON] = 0xd0161616; - Colors[EGDC_ICON_HIGH_LIGHT] = 0xd0606060; - Colors[EGDC_GRAY_WINDOW_SYMBOL] = 0x3c101010; - Colors[EGDC_EDITABLE] = 0xf0ffffff; - Colors[EGDC_GRAY_EDITABLE] = 0xf0cccccc; - Colors[EGDC_FOCUSED_EDITABLE] = 0xf0fffff0; + } else { + // 0x80a6a8af + Colors[EGDC_3D_DARK_SHADOW] = 0x60767982; + // Colors[EGDC_3D_FACE] = 0xc0c9ccd4; // tab background + Colors[EGDC_3D_FACE] = 0xc0cbd2d9; // tab background + Colors[EGDC_3D_SHADOW] = 0x50e4e8f1; // tab background, and left-top highlight + Colors[EGDC_3D_HIGH_LIGHT] = 0x40c7ccdc; + Colors[EGDC_3D_LIGHT] = 0x802e313a; + Colors[EGDC_ACTIVE_BORDER] = 0x80404040; // window title + Colors[EGDC_ACTIVE_CAPTION] = 0xffd0d0d0; + Colors[EGDC_APP_WORKSPACE] = 0xc0646464; // unused + Colors[EGDC_BUTTON_TEXT] = 0xd0161616; + Colors[EGDC_GRAY_TEXT] = 0x3c141414; + Colors[EGDC_HIGH_LIGHT] = 0x6c606060; + Colors[EGDC_HIGH_LIGHT_TEXT] = 0xd0e0e0e0; + Colors[EGDC_INACTIVE_BORDER] = 0xf0a5a5a5; + Colors[EGDC_INACTIVE_CAPTION] = 0xffd2d2d2; + Colors[EGDC_TOOLTIP] = 0xf00f2033; + Colors[EGDC_TOOLTIP_BACKGROUND] = 0xc0cbd2d9; + Colors[EGDC_SCROLLBAR] = 0xf0e0e0e0; + Colors[EGDC_WINDOW] = 0xf0f0f0f0; + Colors[EGDC_WINDOW_SYMBOL] = 0xd0161616; + Colors[EGDC_ICON] = 0xd0161616; + Colors[EGDC_ICON_HIGH_LIGHT] = 0xd0606060; + Colors[EGDC_GRAY_WINDOW_SYMBOL] = 0x3c101010; + Colors[EGDC_EDITABLE] = 0xf0ffffff; + Colors[EGDC_GRAY_EDITABLE] = 0xf0cccccc; + Colors[EGDC_FOCUSED_EDITABLE] = 0xf0fffff0; Sizes[EGDS_SCROLLBAR_SIZE] = 14; Sizes[EGDS_MENU_HEIGHT] = 48; @@ -159,18 +155,16 @@ CGUISkin::CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver) Icons[EGDI_FILE] = 245; Icons[EGDI_DIRECTORY] = 246; - for (u32 i=0; idrop(); } @@ -179,7 +173,6 @@ CGUISkin::~CGUISkin() SpriteBank->drop(); } - //! returns default color video::SColor CGUISkin::getColor(EGUI_DEFAULT_COLOR color) const { @@ -189,7 +182,6 @@ video::SColor CGUISkin::getColor(EGUI_DEFAULT_COLOR color) const return video::SColor(); } - //! sets a default color void CGUISkin::setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) { @@ -197,7 +189,6 @@ void CGUISkin::setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) Colors[which] = newColor; } - //! returns size for the given size type s32 CGUISkin::getSize(EGUI_DEFAULT_SIZE size) const { @@ -207,7 +198,6 @@ s32 CGUISkin::getSize(EGUI_DEFAULT_SIZE size) const return 0; } - //! sets a default size void CGUISkin::setSize(EGUI_DEFAULT_SIZE which, s32 size) { @@ -215,9 +205,8 @@ void CGUISkin::setSize(EGUI_DEFAULT_SIZE which, s32 size) Sizes[which] = size; } - //! returns the default font -IGUIFont* CGUISkin::getFont(EGUI_DEFAULT_FONT which) const +IGUIFont *CGUISkin::getFont(EGUI_DEFAULT_FONT which) const { if (((u32)which < EGDF_COUNT) && Fonts[which]) return Fonts[which]; @@ -225,15 +214,13 @@ IGUIFont* CGUISkin::getFont(EGUI_DEFAULT_FONT which) const return Fonts[EGDF_DEFAULT]; } - //! sets a default font -void CGUISkin::setFont(IGUIFont* font, EGUI_DEFAULT_FONT which) +void CGUISkin::setFont(IGUIFont *font, EGUI_DEFAULT_FONT which) { if ((u32)which >= EGDF_COUNT) return; - if (font) - { + if (font) { font->grab(); if (Fonts[which]) Fonts[which]->drop(); @@ -242,16 +229,14 @@ void CGUISkin::setFont(IGUIFont* font, EGUI_DEFAULT_FONT which) } } - //! gets the sprite bank stored -IGUISpriteBank* CGUISkin::getSpriteBank() const +IGUISpriteBank *CGUISkin::getSpriteBank() const { return SpriteBank; } - //! set a new sprite bank or remove one by passing 0 -void CGUISkin::setSpriteBank(IGUISpriteBank* bank) +void CGUISkin::setSpriteBank(IGUISpriteBank *bank) { if (bank) bank->grab(); @@ -262,7 +247,6 @@ void CGUISkin::setSpriteBank(IGUISpriteBank* bank) SpriteBank = bank; } - //! Returns a default icon u32 CGUISkin::getIcon(EGUI_DEFAULT_ICON icon) const { @@ -272,7 +256,6 @@ u32 CGUISkin::getIcon(EGUI_DEFAULT_ICON icon) const return 0; } - //! Sets a default icon void CGUISkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index) { @@ -280,10 +263,9 @@ void CGUISkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index) Icons[icon] = index; } - //! Returns a default text. For example for Message box button captions: //! "OK", "Cancel", "Yes", "No" and so on. -const wchar_t* CGUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const +const wchar_t *CGUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const { if ((u32)text < EGDT_COUNT) return Texts[text].c_str(); @@ -291,16 +273,14 @@ const wchar_t* CGUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const return Texts[0].c_str(); } - //! Sets a default text. For example for Message box button captions: //! "OK", "Cancel", "Yes", "No" and so on. -void CGUISkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText) +void CGUISkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t *newText) { if ((u32)which < EGDT_COUNT) Texts[which] = newText; } - //! draws a standard 3d button pane /** Used for drawing for example buttons in normal state. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -310,24 +290,22 @@ EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. \param element: Pointer to the element which wishes to draw this. This parameter is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. */ -void CGUISkin::draw3DButtonPaneStandard(IGUIElement* element, - const core::rect& r, - const core::rect* clip) +void CGUISkin::draw3DButtonPaneStandard(IGUIElement *element, + const core::rect &r, + const core::rect *clip) { if (!Driver) return; core::rect rect = r; - if ( Type == EGST_BURNING_SKIN ) - { + if (Type == EGST_BURNING_SKIN) { rect.UpperLeftCorner.X -= 1; rect.UpperLeftCorner.Y -= 1; rect.LowerRightCorner.X += 1; rect.LowerRightCorner.Y += 1; draw3DSunkenPane(element, - getColor( EGDC_WINDOW ).getInterpolated( 0xFFFFFFFF, 0.9f ) - ,false, true, rect, clip); + getColor(EGDC_WINDOW).getInterpolated(0xFFFFFFFF, 0.9f), false, true, rect, clip); return; } @@ -344,19 +322,15 @@ void CGUISkin::draw3DButtonPaneStandard(IGUIElement* element, rect.LowerRightCorner.X -= 1; rect.LowerRightCorner.Y -= 1; - if (!UseGradient) - { + if (!UseGradient) { Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip); - } - else - { + } else { const video::SColor c1 = getColor(EGDC_3D_FACE); const video::SColor c2 = c1.getInterpolated(getColor(EGDC_3D_DARK_SHADOW), 0.4f); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } - //! draws a pressed 3d button pane /** Used for drawing for example buttons in pressed state. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -366,9 +340,9 @@ EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. \param element: Pointer to the element which wishes to draw this. This parameter is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. */ -void CGUISkin::draw3DButtonPanePressed(IGUIElement* element, - const core::rect& r, - const core::rect* clip) +void CGUISkin::draw3DButtonPanePressed(IGUIElement *element, + const core::rect &r, + const core::rect *clip) { if (!Driver) return; @@ -387,19 +361,15 @@ void CGUISkin::draw3DButtonPanePressed(IGUIElement* element, rect.UpperLeftCorner.X += 1; rect.UpperLeftCorner.Y += 1; - if (!UseGradient) - { + if (!UseGradient) { Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip); - } - else - { + } else { const video::SColor c1 = getColor(EGDC_3D_FACE); const video::SColor c2 = c1.getInterpolated(getColor(EGDC_3D_DARK_SHADOW), 0.4f); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } - //! draws a sunken 3d pane /** Used for drawing the background of edit, combo or check boxes. \param element: Pointer to the element which wishes to draw this. This parameter @@ -410,10 +380,10 @@ implementations to find out how to draw the part exactly. deep into the ground. \param rect: Defining area where to draw. \param clip: Clip area. */ -void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, - bool flat, bool fillBackGround, - const core::rect& r, - const core::rect* clip) +void CGUISkin::draw3DSunkenPane(IGUIElement *element, video::SColor bgcolor, + bool flat, bool fillBackGround, + const core::rect &r, + const core::rect *clip) { if (!Driver) return; @@ -423,34 +393,31 @@ void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, if (fillBackGround) Driver->draw2DRectangle(bgcolor, rect, clip); - if (flat) - { + if (flat) { // draw flat sunken pane rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // top + Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // top ++rect.UpperLeftCorner.Y; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; - Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // left + Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // left rect = r; ++rect.UpperLeftCorner.Y; rect.UpperLeftCorner.X = rect.LowerRightCorner.X - 1; - Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // right + Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // right rect = r; ++rect.UpperLeftCorner.X; rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; --rect.LowerRightCorner.X; - Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // bottom - } - else - { + Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // bottom + } else { // draw deep sunken pane rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // top + Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // top ++rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -458,10 +425,10 @@ void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip); rect.UpperLeftCorner.X = r.UpperLeftCorner.X; - rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y+1; + rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y + 1; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; - Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // left + Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); // left ++rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; ++rect.LowerRightCorner.X; @@ -471,7 +438,7 @@ void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, rect = r; rect.UpperLeftCorner.X = rect.LowerRightCorner.X - 1; ++rect.UpperLeftCorner.Y; - Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // right + Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // right --rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -482,7 +449,7 @@ void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, ++rect.UpperLeftCorner.X; rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; --rect.LowerRightCorner.X; - Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // bottom + Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); // bottom ++rect.UpperLeftCorner.X; --rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -491,19 +458,16 @@ void CGUISkin::draw3DSunkenPane(IGUIElement* element, video::SColor bgcolor, } } - //! draws a window background // return where to draw title bar text. -core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, - bool drawTitleBar, video::SColor titleBarColor, - const core::rect& r, - const core::rect* clip, - core::rect* checkClientArea) +core::rect CGUISkin::draw3DWindowBackground(IGUIElement *element, + bool drawTitleBar, video::SColor titleBarColor, + const core::rect &r, + const core::rect *clip, + core::rect *checkClientArea) { - if (!Driver) - { - if ( checkClientArea ) - { + if (!Driver) { + if (checkClientArea) { *checkClientArea = r; } return r; @@ -513,16 +477,14 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, // top border rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); } // left border rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_HIGH_LIGHT), rect, clip); } @@ -531,8 +493,7 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, rect.LowerRightCorner.X = r.LowerRightCorner.X; rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip); } @@ -541,8 +502,7 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, rect.LowerRightCorner.X -= 1; rect.UpperLeftCorner.Y += 1; rect.LowerRightCorner.Y -= 1; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); } @@ -551,8 +511,7 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = r.LowerRightCorner.X; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), rect, clip); } @@ -561,37 +520,29 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, rect.LowerRightCorner.X -= 1; rect.UpperLeftCorner.Y -= 1; rect.LowerRightCorner.Y -= 1; - if ( !checkClientArea ) - { + if (!checkClientArea) { Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); } // client area for background rect = r; - rect.UpperLeftCorner.X +=1; - rect.UpperLeftCorner.Y +=1; + rect.UpperLeftCorner.X += 1; + rect.UpperLeftCorner.Y += 1; rect.LowerRightCorner.X -= 2; rect.LowerRightCorner.Y -= 2; - if (checkClientArea) - { + if (checkClientArea) { *checkClientArea = rect; } - if ( !checkClientArea ) - { - if (!UseGradient) - { + if (!checkClientArea) { + if (!UseGradient) { Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip); - } - else if ( Type == EGST_BURNING_SKIN ) - { - const video::SColor c1 = getColor(EGDC_WINDOW).getInterpolated ( 0xFFFFFFFF, 0.9f ); - const video::SColor c2 = getColor(EGDC_WINDOW).getInterpolated ( 0xFFFFFFFF, 0.8f ); + } else if (Type == EGST_BURNING_SKIN) { + const video::SColor c1 = getColor(EGDC_WINDOW).getInterpolated(0xFFFFFFFF, 0.9f); + const video::SColor c2 = getColor(EGDC_WINDOW).getInterpolated(0xFFFFFFFF, 0.8f); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); - } - else - { + } else { const video::SColor c2 = getColor(EGDC_3D_SHADOW); const video::SColor c1 = getColor(EGDC_3D_FACE); Driver->draw2DRectangle(rect, c1, c1, c1, c2, clip); @@ -605,26 +556,19 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, rect.LowerRightCorner.X -= 2; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + getSize(EGDS_WINDOW_BUTTON_WIDTH) + 2; - if (drawTitleBar ) - { - if (checkClientArea) - { + if (drawTitleBar) { + if (checkClientArea) { (*checkClientArea).UpperLeftCorner.Y = rect.LowerRightCorner.Y; - } - else - { + } else { // draw title bar - //if (!UseGradient) + // if (!UseGradient) // Driver->draw2DRectangle(titleBarColor, rect, clip); - //else - if ( Type == EGST_BURNING_SKIN ) - { - const video::SColor c = titleBarColor.getInterpolated( video::SColor(titleBarColor.getAlpha(),255,255,255), 0.8f); + // else + if (Type == EGST_BURNING_SKIN) { + const video::SColor c = titleBarColor.getInterpolated(video::SColor(titleBarColor.getAlpha(), 255, 255, 255), 0.8f); Driver->draw2DRectangle(rect, titleBarColor, titleBarColor, c, c, clip); - } - else - { - const video::SColor c = titleBarColor.getInterpolated(video::SColor(titleBarColor.getAlpha(),0,0,0), 0.2f); + } else { + const video::SColor c = titleBarColor.getInterpolated(video::SColor(titleBarColor.getAlpha(), 0, 0, 0), 0.2f); Driver->draw2DRectangle(rect, titleBarColor, c, titleBarColor, c, clip); } } @@ -633,7 +577,6 @@ core::rect CGUISkin::draw3DWindowBackground(IGUIElement* element, return rect; } - //! draws a standard 3d menu pane /** Used for drawing for menus and context menus. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -643,16 +586,15 @@ is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ -void CGUISkin::draw3DMenuPane(IGUIElement* element, - const core::rect& r, const core::rect* clip) +void CGUISkin::draw3DMenuPane(IGUIElement *element, + const core::rect &r, const core::rect *clip) { if (!Driver) return; core::rect rect = r; - if ( Type == EGST_BURNING_SKIN ) - { + if (Type == EGST_BURNING_SKIN) { rect.UpperLeftCorner.Y -= 3; draw3DButtonPaneStandard(element, rect, clip); return; @@ -698,22 +640,20 @@ void CGUISkin::draw3DMenuPane(IGUIElement* element, Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), rect, clip); rect = r; - rect.UpperLeftCorner.X +=1; - rect.UpperLeftCorner.Y +=1; + rect.UpperLeftCorner.X += 1; + rect.UpperLeftCorner.Y += 1; rect.LowerRightCorner.X -= 2; rect.LowerRightCorner.Y -= 2; if (!UseGradient) Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip); - else - { + else { const video::SColor c1 = getColor(EGDC_3D_FACE); const video::SColor c2 = getColor(EGDC_3D_SHADOW); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } - //! draws a standard 3d tool bar /** Used for drawing for toolbars and menus. \param element: Pointer to the element which wishes to draw this. This parameter @@ -721,9 +661,9 @@ is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ -void CGUISkin::draw3DToolBar(IGUIElement* element, - const core::rect& r, - const core::rect* clip) +void CGUISkin::draw3DToolBar(IGUIElement *element, + const core::rect &r, + const core::rect *clip) { if (!Driver) return; @@ -739,28 +679,21 @@ void CGUISkin::draw3DToolBar(IGUIElement* element, rect = r; rect.LowerRightCorner.Y -= 1; - if (!UseGradient) - { + if (!UseGradient) { Driver->draw2DRectangle(getColor(EGDC_3D_FACE), rect, clip); - } - else - if ( Type == EGST_BURNING_SKIN ) - { + } else if (Type == EGST_BURNING_SKIN) { const video::SColor c1 = 0xF0000000 | getColor(EGDC_3D_FACE).color; const video::SColor c2 = 0xF0000000 | getColor(EGDC_3D_SHADOW).color; rect.LowerRightCorner.Y += 1; Driver->draw2DRectangle(rect, c1, c2, c1, c2, clip); - } - else - { + } else { const video::SColor c1 = getColor(EGDC_3D_FACE); const video::SColor c2 = getColor(EGDC_3D_SHADOW); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } - //! draws a tab button /** Used for drawing for tab buttons on top of tabs. \param element: Pointer to the element which wishes to draw this. This parameter @@ -769,16 +702,15 @@ implementations to find out how to draw the part exactly. \param active: Specifies if the tab is currently active. \param rect: Defining area where to draw. \param clip: Clip area. */ -void CGUISkin::draw3DTabButton(IGUIElement* element, bool active, - const core::rect& frameRect, const core::rect* clip, EGUI_ALIGNMENT alignment) +void CGUISkin::draw3DTabButton(IGUIElement *element, bool active, + const core::rect &frameRect, const core::rect *clip, EGUI_ALIGNMENT alignment) { if (!Driver) return; core::rect tr = frameRect; - if ( alignment == EGUIA_UPPERLEFT ) - { + if (alignment == EGUIA_UPPERLEFT) { tr.LowerRightCorner.X -= 2; tr.LowerRightCorner.Y = tr.UpperLeftCorner.Y + 1; tr.UpperLeftCorner.X += 1; @@ -806,9 +738,7 @@ void CGUISkin::draw3DTabButton(IGUIElement* element, bool active, tr.UpperLeftCorner.X += 1; tr.UpperLeftCorner.Y += 1; Driver->draw2DRectangle(getColor(EGDC_3D_DARK_SHADOW), tr, clip); - } - else - { + } else { tr.LowerRightCorner.X -= 2; tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1; tr.UpperLeftCorner.X += 1; @@ -831,7 +761,7 @@ void CGUISkin::draw3DTabButton(IGUIElement* element, bool active, // draw right middle gray shadow tr.LowerRightCorner.X += 1; tr.UpperLeftCorner.X = tr.LowerRightCorner.X - 1; - //tr.LowerRightCorner.Y -= 1; + // tr.LowerRightCorner.Y -= 1; Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip); tr.LowerRightCorner.X += 1; @@ -841,7 +771,6 @@ void CGUISkin::draw3DTabButton(IGUIElement* element, bool active, } } - //! draws a tab control body /** \param element: Pointer to the element which wishes to draw this. This parameter is usually not used by ISkin, but can be used for example by more complex @@ -850,22 +779,20 @@ implementations to find out how to draw the part exactly. \param background: Specifies if the background should be drawn. \param rect: Defining area where to draw. \param clip: Clip area. */ -void CGUISkin::draw3DTabBody(IGUIElement* element, bool border, bool background, - const core::rect& rect, const core::rect* clip, s32 tabHeight, EGUI_ALIGNMENT alignment) +void CGUISkin::draw3DTabBody(IGUIElement *element, bool border, bool background, + const core::rect &rect, const core::rect *clip, s32 tabHeight, EGUI_ALIGNMENT alignment) { if (!Driver) return; core::rect tr = rect; - if ( tabHeight == -1 ) + if (tabHeight == -1) tabHeight = getSize(gui::EGDS_BUTTON_HEIGHT); // draw border. - if (border) - { - if ( alignment == EGUIA_UPPERLEFT ) - { + if (border) { + if (alignment == EGUIA_UPPERLEFT) { // draw left hightlight tr.UpperLeftCorner.Y += tabHeight + 2; tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1; @@ -880,9 +807,7 @@ void CGUISkin::draw3DTabBody(IGUIElement* element, bool border, bool background, tr = rect; tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1; Driver->draw2DRectangle(getColor(EGDC_3D_SHADOW), tr, clip); - } - else - { + } else { // draw left hightlight tr.LowerRightCorner.Y -= tabHeight + 2; tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1; @@ -900,30 +825,25 @@ void CGUISkin::draw3DTabBody(IGUIElement* element, bool border, bool background, } } - if (background) - { - if ( alignment == EGUIA_UPPERLEFT ) - { + if (background) { + if (alignment == EGUIA_UPPERLEFT) { tr = rect; tr.UpperLeftCorner.Y += tabHeight + 2; tr.LowerRightCorner.X -= 1; tr.UpperLeftCorner.X += 1; tr.LowerRightCorner.Y -= 1; - } - else - { + } else { tr = rect; tr.UpperLeftCorner.X += 1; tr.UpperLeftCorner.Y -= 1; tr.LowerRightCorner.X -= 1; tr.LowerRightCorner.Y -= tabHeight + 2; - //tr.UpperLeftCorner.X += 1; + // tr.UpperLeftCorner.X += 1; } if (!UseGradient) Driver->draw2DRectangle(getColor(EGDC_3D_FACE), tr, clip); - else - { + else { video::SColor c1 = getColor(EGDC_3D_FACE); video::SColor c2 = getColor(EGDC_3D_SHADOW); Driver->draw2DRectangle(tr, c1, c1, c2, c2, clip); @@ -931,7 +851,6 @@ void CGUISkin::draw3DTabBody(IGUIElement* element, bool border, bool background, } } - //! draws an icon, usually from the skin's sprite bank /** \param parent: Pointer to the element which wishes to draw this icon. This parameter is usually not used by IGUISkin, but can be used for example @@ -942,30 +861,28 @@ by more complex implementations to find out how to draw the part exactly. \param currenttime: The present time, used to calculate the frame number \param loop: Whether the animation should loop or not \param clip: Clip area. */ -void CGUISkin::drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, - const core::position2di position, - u32 starttime, u32 currenttime, - bool loop, const core::rect* clip) +void CGUISkin::drawIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, + const core::position2di position, + u32 starttime, u32 currenttime, + bool loop, const core::rect *clip) { if (!SpriteBank) return; bool gray = element && !element->isEnabled(); SpriteBank->draw2DSprite(Icons[icon], position, clip, - Colors[gray? EGDC_GRAY_WINDOW_SYMBOL : EGDC_WINDOW_SYMBOL], starttime, currenttime, loop, true); + Colors[gray ? EGDC_GRAY_WINDOW_SYMBOL : EGDC_WINDOW_SYMBOL], starttime, currenttime, loop, true); } - EGUI_SKIN_TYPE CGUISkin::getType() const { return Type; } - //! draws a 2d rectangle. -void CGUISkin::draw2DRectangle(IGUIElement* element, - const video::SColor &color, const core::rect& pos, - const core::rect* clip) +void CGUISkin::draw2DRectangle(IGUIElement *element, + const video::SColor &color, const core::rect &pos, + const core::rect *clip) { Driver->draw2DRectangle(color, pos, clip); } diff --git a/source/Irrlicht/CGUISkin.h b/source/Irrlicht/CGUISkin.h index f8004419..130e5fad 100644 --- a/source/Irrlicht/CGUISkin.h +++ b/source/Irrlicht/CGUISkin.h @@ -11,221 +11,216 @@ namespace irr { namespace video { - class IVideoDriver; +class IVideoDriver; } namespace gui { - class CGUISkin : public IGUISkin - { - public: +class CGUISkin : public IGUISkin +{ +public: + CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver *driver); - CGUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver); + //! destructor + virtual ~CGUISkin(); - //! destructor - virtual ~CGUISkin(); + //! returns default color + video::SColor getColor(EGUI_DEFAULT_COLOR color) const override; - //! returns default color - video::SColor getColor(EGUI_DEFAULT_COLOR color) const override; + //! sets a default color + void setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) override; - //! sets a default color - void setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) override; + //! returns size for the given size type + s32 getSize(EGUI_DEFAULT_SIZE size) const override; - //! returns size for the given size type - s32 getSize(EGUI_DEFAULT_SIZE size) const override; + //! sets a default size + void setSize(EGUI_DEFAULT_SIZE which, s32 size) override; - //! sets a default size - void setSize(EGUI_DEFAULT_SIZE which, s32 size) override; + //! returns the default font + IGUIFont *getFont(EGUI_DEFAULT_FONT which = EGDF_DEFAULT) const override; - //! returns the default font - IGUIFont* getFont(EGUI_DEFAULT_FONT which=EGDF_DEFAULT) const override; + //! sets a default font + void setFont(IGUIFont *font, EGUI_DEFAULT_FONT which = EGDF_DEFAULT) override; - //! sets a default font - void setFont(IGUIFont* font, EGUI_DEFAULT_FONT which=EGDF_DEFAULT) override; + //! sets the sprite bank used for drawing icons + void setSpriteBank(IGUISpriteBank *bank) override; - //! sets the sprite bank used for drawing icons - void setSpriteBank(IGUISpriteBank* bank) override; + //! gets the sprite bank used for drawing icons + IGUISpriteBank *getSpriteBank() const override; - //! gets the sprite bank used for drawing icons - IGUISpriteBank* getSpriteBank() const override; + //! Returns a default icon + /** Returns the sprite index within the sprite bank */ + u32 getIcon(EGUI_DEFAULT_ICON icon) const override; - //! Returns a default icon - /** Returns the sprite index within the sprite bank */ - u32 getIcon(EGUI_DEFAULT_ICON icon) const override; + //! Sets a default icon + /** Sets the sprite index used for drawing icons like arrows, + close buttons and ticks in checkboxes + \param icon: Enum specifying which icon to change + \param index: The sprite index used to draw this icon */ + void setIcon(EGUI_DEFAULT_ICON icon, u32 index) override; - //! Sets a default icon - /** Sets the sprite index used for drawing icons like arrows, - close buttons and ticks in checkboxes - \param icon: Enum specifying which icon to change - \param index: The sprite index used to draw this icon */ - void setIcon(EGUI_DEFAULT_ICON icon, u32 index) override; + //! Returns a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + const wchar_t *getDefaultText(EGUI_DEFAULT_TEXT text) const override; - //! Returns a default text. - /** For example for Message box button captions: - "OK", "Cancel", "Yes", "No" and so on. */ - const wchar_t* getDefaultText(EGUI_DEFAULT_TEXT text) const override; + //! Sets a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + void setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t *newText) override; - //! Sets a default text. - /** For example for Message box button captions: - "OK", "Cancel", "Yes", "No" and so on. */ - void setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText) override; + //! draws a standard 3d button pane + /** Used for drawing for example buttons in normal state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. */ + virtual void draw3DButtonPaneStandard(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) override; - //! draws a standard 3d button pane - /** Used for drawing for example buttons in normal state. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. */ - virtual void draw3DButtonPaneStandard(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) override; + //! draws a pressed 3d button pane + /** Used for drawing for example buttons in pressed state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. */ + virtual void draw3DButtonPanePressed(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) override; - //! draws a pressed 3d button pane - /** Used for drawing for example buttons in pressed state. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. */ - virtual void draw3DButtonPanePressed(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) override; + //! draws a sunken 3d pane + /** Used for drawing the background of edit, combo or check boxes. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param bgcolor: Background color. + \param flat: Specifies if the sunken pane should be flat or displayed as sunken + deep into the ground. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DSunkenPane(IGUIElement *element, + video::SColor bgcolor, bool flat, + bool fillBackGround, + const core::rect &rect, + const core::rect *clip = 0) override; - //! draws a sunken 3d pane - /** Used for drawing the background of edit, combo or check boxes. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param bgcolor: Background color. - \param flat: Specifies if the sunken pane should be flat or displayed as sunken - deep into the ground. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DSunkenPane(IGUIElement* element, - video::SColor bgcolor, bool flat, - bool fillBackGround, - const core::rect& rect, - const core::rect* clip=0) override; + //! draws a window background + /** Used for drawing the background of dialogs and windows. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param titleBarColor: Title color. + \param drawTitleBar: True to enable title drawing. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param checkClientArea: When set to non-null the function will not draw anything, + but will instead return the clientArea which can be used for drawing by the calling window. + That is the area without borders and without titlebar. + \return Returns rect where it would be good to draw title bar text. This will + work even when checkClientArea is set to a non-null value.*/ + virtual core::rect draw3DWindowBackground(IGUIElement *element, + bool drawTitleBar, video::SColor titleBarColor, + const core::rect &rect, + const core::rect *clip, + core::rect *checkClientArea) override; - //! draws a window background - /** Used for drawing the background of dialogs and windows. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param titleBarColor: Title color. - \param drawTitleBar: True to enable title drawing. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param checkClientArea: When set to non-null the function will not draw anything, - but will instead return the clientArea which can be used for drawing by the calling window. - That is the area without borders and without titlebar. - \return Returns rect where it would be good to draw title bar text. This will - work even when checkClientArea is set to a non-null value.*/ - virtual core::rect draw3DWindowBackground(IGUIElement* element, - bool drawTitleBar, video::SColor titleBarColor, - const core::rect& rect, - const core::rect* clip, - core::rect* checkClientArea) override; + //! draws a standard 3d menu pane + /** Used for drawing for menus and context menus. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DMenuPane(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) override; - //! draws a standard 3d menu pane - /** Used for drawing for menus and context menus. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DMenuPane(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) override; + //! draws a standard 3d tool bar + /** Used for drawing for toolbars and menus. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DToolBar(IGUIElement *element, + const core::rect &rect, + const core::rect *clip = 0) override; - //! draws a standard 3d tool bar - /** Used for drawing for toolbars and menus. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DToolBar(IGUIElement* element, - const core::rect& rect, - const core::rect* clip=0) override; + //! draws a tab button + /** Used for drawing for tab buttons on top of tabs. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param active: Specifies if the tab is currently active. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DTabButton(IGUIElement *element, bool active, + const core::rect &rect, const core::rect *clip = 0, + EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) override; - //! draws a tab button - /** Used for drawing for tab buttons on top of tabs. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param active: Specifies if the tab is currently active. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DTabButton(IGUIElement* element, bool active, - const core::rect& rect, const core::rect* clip=0, - EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT) override; + //! draws a tab control body + /** \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param border: Specifies if the border should be drawn. + \param background: Specifies if the background should be drawn. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DTabBody(IGUIElement *element, bool border, bool background, + const core::rect &rect, const core::rect *clip = 0, s32 tabHeight = -1, + EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) override; - //! draws a tab control body - /** \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param border: Specifies if the border should be drawn. - \param background: Specifies if the background should be drawn. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DTabBody(IGUIElement* element, bool border, bool background, - const core::rect& rect, const core::rect* clip=0, s32 tabHeight=-1, - EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT) override; + //! draws an icon, usually from the skin's sprite bank + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param icon: Specifies the icon to be drawn. + \param position: The position to draw the icon + \param starttime: The time at the start of the animation + \param currenttime: The present time, used to calculate the frame number + \param loop: Whether the animation should loop or not + \param clip: Clip area. */ + virtual void drawIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, + const core::position2di position, + u32 starttime = 0, u32 currenttime = 0, + bool loop = false, const core::rect *clip = 0) override; - //! draws an icon, usually from the skin's sprite bank - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param icon: Specifies the icon to be drawn. - \param position: The position to draw the icon - \param starttime: The time at the start of the animation - \param currenttime: The present time, used to calculate the frame number - \param loop: Whether the animation should loop or not - \param clip: Clip area. */ - virtual void drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, - const core::position2di position, - u32 starttime=0, u32 currenttime=0, - bool loop=false, const core::rect* clip=0) override; + //! draws a 2d rectangle. + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param color: Color of the rectangle to draw. The alpha component specifies how + transparent the rectangle will be. + \param pos: Position of the rectangle. + \param clip: Pointer to rectangle against which the rectangle will be clipped. + If the pointer is null, no clipping will be performed. */ + virtual void draw2DRectangle(IGUIElement *element, const video::SColor &color, + const core::rect &pos, const core::rect *clip = 0) override; + //! get the type of this skin + EGUI_SKIN_TYPE getType() const override; - //! draws a 2d rectangle. - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param color: Color of the rectangle to draw. The alpha component specifies how - transparent the rectangle will be. - \param pos: Position of the rectangle. - \param clip: Pointer to rectangle against which the rectangle will be clipped. - If the pointer is null, no clipping will be performed. */ - virtual void draw2DRectangle(IGUIElement* element, const video::SColor &color, - const core::rect& pos, const core::rect* clip = 0) override; - - - //! get the type of this skin - EGUI_SKIN_TYPE getType() const override; - - private: - - video::SColor Colors[EGDC_COUNT]; - s32 Sizes[EGDS_COUNT]; - u32 Icons[EGDI_COUNT]; - IGUIFont* Fonts[EGDF_COUNT]; - IGUISpriteBank* SpriteBank; - core::stringw Texts[EGDT_COUNT]; - video::IVideoDriver* Driver; - bool UseGradient; - - EGUI_SKIN_TYPE Type; - }; +private: + video::SColor Colors[EGDC_COUNT]; + s32 Sizes[EGDS_COUNT]; + u32 Icons[EGDI_COUNT]; + IGUIFont *Fonts[EGDF_COUNT]; + IGUISpriteBank *SpriteBank; + core::stringw Texts[EGDT_COUNT]; + video::IVideoDriver *Driver; + bool UseGradient; + EGUI_SKIN_TYPE Type; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUISpriteBank.cpp b/source/Irrlicht/CGUISpriteBank.cpp index ced8c6f6..fe0c087b 100644 --- a/source/Irrlicht/CGUISpriteBank.cpp +++ b/source/Irrlicht/CGUISpriteBank.cpp @@ -13,22 +13,20 @@ namespace irr namespace gui { -CGUISpriteBank::CGUISpriteBank(IGUIEnvironment* env) : - Environment(env), Driver(0) +CGUISpriteBank::CGUISpriteBank(IGUIEnvironment *env) : + Environment(env), Driver(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUISpriteBank"); - #endif +#endif - if (Environment) - { + if (Environment) { Driver = Environment->getVideoDriver(); if (Driver) Driver->grab(); } } - CGUISpriteBank::~CGUISpriteBank() { clear(); @@ -38,26 +36,22 @@ CGUISpriteBank::~CGUISpriteBank() Driver->drop(); } - -core::array< core::rect >& CGUISpriteBank::getPositions() +core::array> &CGUISpriteBank::getPositions() { return Rectangles; } - -core::array< SGUISprite >& CGUISpriteBank::getSprites() +core::array &CGUISpriteBank::getSprites() { return Sprites; } - u32 CGUISpriteBank::getTextureCount() const { return Textures.size(); } - -video::ITexture* CGUISpriteBank::getTexture(u32 index) const +video::ITexture *CGUISpriteBank::getTexture(u32 index) const { if (index < Textures.size()) return Textures[index]; @@ -65,8 +59,7 @@ video::ITexture* CGUISpriteBank::getTexture(u32 index) const return 0; } - -void CGUISpriteBank::addTexture(video::ITexture* texture) +void CGUISpriteBank::addTexture(video::ITexture *texture) { if (texture) texture->grab(); @@ -74,8 +67,7 @@ void CGUISpriteBank::addTexture(video::ITexture* texture) Textures.push_back(texture); } - -void CGUISpriteBank::setTexture(u32 index, video::ITexture* texture) +void CGUISpriteBank::setTexture(u32 index, video::ITexture *texture) { while (index >= Textures.size()) Textures.push_back(0); @@ -89,13 +81,11 @@ void CGUISpriteBank::setTexture(u32 index, video::ITexture* texture) Textures[index] = texture; } - //! clear everything void CGUISpriteBank::clear() { // drop textures - for (u32 i=0; idrop(); } @@ -105,16 +95,16 @@ void CGUISpriteBank::clear() } //! Add the texture and use it for a single non-animated sprite. -s32 CGUISpriteBank::addTextureAsSprite(video::ITexture* texture) +s32 CGUISpriteBank::addTextureAsSprite(video::ITexture *texture) { - if ( !texture ) + if (!texture) return -1; addTexture(texture); u32 textureIndex = getTextureCount() - 1; u32 rectangleIndex = Rectangles.size(); - Rectangles.push_back( core::rect(0,0, texture->getOriginalSize().Width, texture->getOriginalSize().Height) ); + Rectangles.push_back(core::rect(0, 0, texture->getOriginalSize().Width, texture->getOriginalSize().Height)); SGUISprite sprite; sprite.frameTime = 0; @@ -122,27 +112,26 @@ s32 CGUISpriteBank::addTextureAsSprite(video::ITexture* texture) SGUISpriteFrame frame; frame.textureNumber = textureIndex; frame.rectNumber = rectangleIndex; - sprite.Frames.push_back( frame ); + sprite.Frames.push_back(frame); - Sprites.push_back( sprite ); + Sprites.push_back(sprite); return Sprites.size() - 1; } // get FrameNr for time. return true on exisiting frame -inline bool CGUISpriteBank::getFrameNr(u32& frame,u32 index, u32 time, bool loop) const +inline bool CGUISpriteBank::getFrameNr(u32 &frame, u32 index, u32 time, bool loop) const { frame = 0; if (index >= Sprites.size()) return false; - const SGUISprite& sprite = Sprites[index]; + const SGUISprite &sprite = Sprites[index]; const u32 frameSize = sprite.Frames.size(); if (frameSize < 1) return false; - if (sprite.frameTime) - { + if (sprite.frameTime) { u32 f = (time / sprite.frameTime); if (loop) frame = f % frameSize; @@ -153,15 +142,15 @@ inline bool CGUISpriteBank::getFrameNr(u32& frame,u32 index, u32 time, bool loop } //! draws a sprite in 2d with scale and color -void CGUISpriteBank::draw2DSprite(u32 index, const core::position2di& pos, - const core::rect* clip, const video::SColor& color, +void CGUISpriteBank::draw2DSprite(u32 index, const core::position2di &pos, + const core::rect *clip, const video::SColor &color, u32 starttime, u32 currenttime, bool loop, bool center) { u32 frame = 0; if (!getFrameNr(frame, index, currenttime - starttime, loop)) return; - const video::ITexture* tex = getTexture(Sprites[index].Frames[frame].textureNumber); + const video::ITexture *tex = getTexture(Sprites[index].Frames[frame].textureNumber); if (!tex) return; @@ -169,24 +158,23 @@ void CGUISpriteBank::draw2DSprite(u32 index, const core::position2di& pos, if (rn >= Rectangles.size()) return; - const core::rect& r = Rectangles[rn]; + const core::rect &r = Rectangles[rn]; core::position2di p(pos); - if (center) - { + if (center) { p -= r.getSize() / 2; } Driver->draw2DImage(tex, p, r, clip, color, true); } -void CGUISpriteBank::draw2DSprite(u32 index, const core::rect& destRect, - const core::rect* clip, const video::SColor * const colors, +void CGUISpriteBank::draw2DSprite(u32 index, const core::rect &destRect, + const core::rect *clip, const video::SColor *const colors, u32 timeTicks, bool loop) { u32 frame = 0; - if (!getFrameNr(frame,index, timeTicks, loop)) + if (!getFrameNr(frame, index, timeTicks, loop)) return; - const video::ITexture* tex = getTexture(Sprites[index].Frames[frame].textureNumber); + const video::ITexture *tex = getTexture(Sprites[index].Frames[frame].textureNumber); if (!tex) return; @@ -197,27 +185,25 @@ void CGUISpriteBank::draw2DSprite(u32 index, const core::rect& destRect, Driver->draw2DImage(tex, destRect, Rectangles[rn], clip, colors, true); } -void CGUISpriteBank::draw2DSpriteBatch( const core::array& indices, - const core::array& pos, - const core::rect* clip, - const video::SColor& color, - u32 starttime, u32 currenttime, - bool loop, bool center) +void CGUISpriteBank::draw2DSpriteBatch(const core::array &indices, + const core::array &pos, + const core::rect *clip, + const video::SColor &color, + u32 starttime, u32 currenttime, + bool loop, bool center) { const irr::u32 drawCount = core::min_(indices.size(), pos.size()); if (!getTextureCount()) return; core::array drawBatches(getTextureCount()); - for (u32 i=0; i < Textures.size(); ++i) - { + for (u32 i = 0; i < Textures.size(); ++i) { drawBatches.push_back(SDrawBatch()); drawBatches[i].positions.reallocate(drawCount); drawBatches[i].sourceRects.reallocate(drawCount); } - for (u32 i = 0; i < drawCount; ++i) - { + for (u32 i = 0; i < drawCount; ++i) { const u32 index = indices[i]; // work out frame number @@ -226,38 +212,33 @@ void CGUISpriteBank::draw2DSpriteBatch( const core::array& indices, return; const u32 texNum = Sprites[index].Frames[frame].textureNumber; - if (texNum >= drawBatches.size()) - { + if (texNum >= drawBatches.size()) { continue; } - SDrawBatch& currentBatch = drawBatches[texNum]; + SDrawBatch ¤tBatch = drawBatches[texNum]; const u32 rn = Sprites[index].Frames[frame].rectNumber; if (rn >= Rectangles.size()) return; - const core::rect& r = Rectangles[rn]; + const core::rect &r = Rectangles[rn]; - if (center) - { + if (center) { core::position2di p = pos[i]; p -= r.getSize() / 2; currentBatch.positions.push_back(p); currentBatch.sourceRects.push_back(r); - } - else - { + } else { currentBatch.positions.push_back(pos[i]); currentBatch.sourceRects.push_back(r); } } - for(u32 i = 0;i < drawBatches.size();i++) - { - if(!drawBatches[i].positions.empty() && !drawBatches[i].sourceRects.empty()) + for (u32 i = 0; i < drawBatches.size(); i++) { + if (!drawBatches[i].positions.empty() && !drawBatches[i].sourceRects.empty()) Driver->draw2DImageBatch(getTexture(i), drawBatches[i].positions, - drawBatches[i].sourceRects, clip, color, true); + drawBatches[i].sourceRects, clip, color, true); } } diff --git a/source/Irrlicht/CGUISpriteBank.h b/source/Irrlicht/CGUISpriteBank.h index df4658f6..f46ca8b1 100644 --- a/source/Irrlicht/CGUISpriteBank.h +++ b/source/Irrlicht/CGUISpriteBank.h @@ -11,59 +11,57 @@ namespace irr namespace video { - class IVideoDriver; - class ITexture; +class IVideoDriver; +class ITexture; } namespace gui { - class IGUIEnvironment; +class IGUIEnvironment; //! Sprite bank interface. class CGUISpriteBank : public IGUISpriteBank { public: - - CGUISpriteBank(IGUIEnvironment* env); + CGUISpriteBank(IGUIEnvironment *env); virtual ~CGUISpriteBank(); - core::array< core::rect >& getPositions() override; - core::array< SGUISprite >& getSprites() override; + core::array> &getPositions() override; + core::array &getSprites() override; u32 getTextureCount() const override; - video::ITexture* getTexture(u32 index) const override; - void addTexture(video::ITexture* texture) override; - void setTexture(u32 index, video::ITexture* texture) override; + video::ITexture *getTexture(u32 index) const override; + void addTexture(video::ITexture *texture) override; + void setTexture(u32 index, video::ITexture *texture) override; //! Add the texture and use it for a single non-animated sprite. - s32 addTextureAsSprite(video::ITexture* texture) override; + s32 addTextureAsSprite(video::ITexture *texture) override; //! clears sprites, rectangles and textures void clear() override; //! Draws a sprite in 2d with position and color - virtual void draw2DSprite(u32 index, const core::position2di& pos, const core::rect* clip=0, - const video::SColor& color= video::SColor(255,255,255,255), - u32 starttime=0, u32 currenttime=0, bool loop=true, bool center=false) override; + virtual void draw2DSprite(u32 index, const core::position2di &pos, const core::rect *clip = 0, + const video::SColor &color = video::SColor(255, 255, 255, 255), + u32 starttime = 0, u32 currenttime = 0, bool loop = true, bool center = false) override; //! Draws a sprite in 2d with destination rectangle and colors - virtual void draw2DSprite(u32 index, const core::rect& destRect, - const core::rect* clip=0, - const video::SColor * const colors=0, + virtual void draw2DSprite(u32 index, const core::rect &destRect, + const core::rect *clip = 0, + const video::SColor *const colors = 0, u32 timeTicks = 0, - bool loop=true) override; + bool loop = true) override; //! Draws a sprite batch in 2d using an array of positions and a color - virtual void draw2DSpriteBatch(const core::array& indices, const core::array& pos, - const core::rect* clip=0, - const video::SColor& color= video::SColor(255,255,255,255), - u32 starttime=0, u32 currenttime=0, - bool loop=true, bool center=false) override; + virtual void draw2DSpriteBatch(const core::array &indices, const core::array &pos, + const core::rect *clip = 0, + const video::SColor &color = video::SColor(255, 255, 255, 255), + u32 starttime = 0, u32 currenttime = 0, + bool loop = true, bool center = false) override; protected: - - bool getFrameNr(u32& frameNr, u32 index, u32 time, bool loop) const; + bool getFrameNr(u32 &frameNr, u32 index, u32 time, bool loop) const; struct SDrawBatch { @@ -73,11 +71,10 @@ protected: }; core::array Sprites; - core::array< core::rect > Rectangles; - core::array Textures; - IGUIEnvironment* Environment; - video::IVideoDriver* Driver; - + core::array> Rectangles; + core::array Textures; + IGUIEnvironment *Environment; + video::IVideoDriver *Driver; }; } // end namespace gui diff --git a/source/Irrlicht/CGUIStaticText.cpp b/source/Irrlicht/CGUIStaticText.cpp index a22e0f60..26e34d0c 100644 --- a/source/Irrlicht/CGUIStaticText.cpp +++ b/source/Irrlicht/CGUIStaticText.cpp @@ -16,29 +16,27 @@ namespace gui { //! constructor -CGUIStaticText::CGUIStaticText(const wchar_t* text, bool border, - IGUIEnvironment* environment, IGUIElement* parent, - s32 id, const core::rect& rectangle, - bool background) -: IGUIStaticText(environment, parent, id, rectangle), - HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), - Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), - RestrainTextInside(true), RightToLeft(false), - OverrideColor(video::SColor(101,255,255,255)), BGColor(video::SColor(101,210,210,210)), - OverrideFont(0), LastBreakFont(0) +CGUIStaticText::CGUIStaticText(const wchar_t *text, bool border, + IGUIEnvironment *environment, IGUIElement *parent, + s32 id, const core::rect &rectangle, + bool background) : + IGUIStaticText(environment, parent, id, rectangle), + HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), + Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), + RestrainTextInside(true), RightToLeft(false), + OverrideColor(video::SColor(101, 255, 255, 255)), BGColor(video::SColor(101, 210, 210, 210)), + OverrideFont(0), LastBreakFont(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUIStaticText"); - #endif +#endif Text = text; - if (environment && environment->getSkin()) - { + if (environment && environment->getSkin()) { BGColor = environment->getSkin()->getColor(gui::EGDC_3D_FACE); } } - //! destructor CGUIStaticText::~CGUIStaticText() { @@ -46,25 +44,23 @@ CGUIStaticText::~CGUIStaticText() OverrideFont->drop(); } - //! draws the element and its children void CGUIStaticText::draw() { if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (!skin) return; - video::IVideoDriver* driver = Environment->getVideoDriver(); + video::IVideoDriver *driver = Environment->getVideoDriver(); core::rect frameRect(AbsoluteRect); // draw background - if (Background) - { - if ( !OverrideBGColorEnabled ) // skin-colors can change + if (Background) { + if (!OverrideBGColorEnabled) // skin-colors can change BGColor = skin->getColor(gui::EGDC_3D_FACE); driver->draw2DRectangle(BGColor, frameRect, &AbsoluteClippingRect); @@ -72,64 +68,51 @@ void CGUIStaticText::draw() // draw the border - if (Border) - { + if (Border) { skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); } // draw the text - if (Text.size()) - { - IGUIFont* font = getActiveFont(); + if (Text.size()) { + IGUIFont *font = getActiveFont(); - if (font) - { - if (!WordWrap) - { - if (VAlign == EGUIA_LOWERRIGHT) - { + if (font) { + if (!WordWrap) { + if (VAlign == EGUIA_LOWERRIGHT) { frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - - font->getDimension(L"A").Height - font->getKerningHeight(); + font->getDimension(L"A").Height - font->getKerningHeight(); } - if (HAlign == EGUIA_LOWERRIGHT) - { + if (HAlign == EGUIA_LOWERRIGHT) { frameRect.UpperLeftCorner.X = frameRect.LowerRightCorner.X - - font->getDimension(Text.c_str()).Width; + font->getDimension(Text.c_str()).Width; } font->draw(Text.c_str(), frameRect, - getActiveColor(), - HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); - } - else - { + getActiveColor(), + HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + } else { if (font != LastBreakFont) breakText(); core::rect r = frameRect; s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); s32 totalHeight = height * BrokenText.size(); - if (VAlign == EGUIA_CENTER) - { + if (VAlign == EGUIA_CENTER) { r.UpperLeftCorner.Y = r.getCenter().Y - (totalHeight / 2); - } - else if (VAlign == EGUIA_LOWERRIGHT) - { + } else if (VAlign == EGUIA_LOWERRIGHT) { r.UpperLeftCorner.Y = r.LowerRightCorner.Y - totalHeight; } - for (u32 i=0; igetDimension(BrokenText[i].c_str()).Width; + font->getDimension(BrokenText[i].c_str()).Width; } font->draw(BrokenText[i].c_str(), r, - getActiveColor(), - HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + getActiveColor(), + HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); r.LowerRightCorner.Y += height; r.UpperLeftCorner.Y += height; @@ -141,9 +124,8 @@ void CGUIStaticText::draw() IGUIElement::draw(); } - //! Sets another skin independent font. -void CGUIStaticText::setOverrideFont(IGUIFont* font) +void CGUIStaticText::setOverrideFont(IGUIFont *font) { if (OverrideFont == font) return; @@ -160,17 +142,17 @@ void CGUIStaticText::setOverrideFont(IGUIFont* font) } //! Gets the override font (if any) -IGUIFont * CGUIStaticText::getOverrideFont() const +IGUIFont *CGUIStaticText::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont* CGUIStaticText::getActiveFont() const +IGUIFont *CGUIStaticText::getActiveFont() const { - if ( OverrideFont ) + if (OverrideFont) return OverrideFont; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; @@ -183,7 +165,6 @@ void CGUIStaticText::setOverrideColor(video::SColor color) OverrideColorEnabled = true; } - //! Sets another color for the text. void CGUIStaticText::setBackgroundColor(video::SColor color) { @@ -192,72 +173,62 @@ void CGUIStaticText::setBackgroundColor(video::SColor color) Background = true; } - //! Sets whether to draw the background void CGUIStaticText::setDrawBackground(bool draw) { Background = draw; } - //! Gets the background color video::SColor CGUIStaticText::getBackgroundColor() const { return BGColor; } - //! Checks if background drawing is enabled bool CGUIStaticText::isDrawBackgroundEnabled() const { return Background; } - //! Sets whether to draw the border void CGUIStaticText::setDrawBorder(bool draw) { Border = draw; } - //! Checks if border drawing is enabled bool CGUIStaticText::isDrawBorderEnabled() const { return Border; } - void CGUIStaticText::setTextRestrainedInside(bool restrainTextInside) { RestrainTextInside = restrainTextInside; } - bool CGUIStaticText::isTextRestrainedInside() const { return RestrainTextInside; } - void CGUIStaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { HAlign = horizontal; VAlign = vertical; } - video::SColor CGUIStaticText::getOverrideColor() const { return OverrideColor; } - irr::video::SColor CGUIStaticText::getActiveColor() const { - if ( OverrideColorEnabled ) + if (OverrideColorEnabled) return OverrideColor; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (skin) return OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT); return OverrideColor; @@ -270,13 +241,11 @@ void CGUIStaticText::enableOverrideColor(bool enable) OverrideColorEnabled = enable; } - bool CGUIStaticText::isOverrideColorEnabled() const { return OverrideColorEnabled; } - //! Enables or disables word wrap for using the static text as //! multiline text control. void CGUIStaticText::setWordWrap(bool enable) @@ -285,29 +254,24 @@ void CGUIStaticText::setWordWrap(bool enable) breakText(); } - bool CGUIStaticText::isWordWrapEnabled() const { return WordWrap; } - void CGUIStaticText::setRightToLeft(bool rtl) { - if (RightToLeft != rtl) - { + if (RightToLeft != rtl) { RightToLeft = rtl; breakText(); } } - bool CGUIStaticText::isRightToLeft() const { return RightToLeft; } - //! Breaks the single text line. void CGUIStaticText::breakText() { @@ -316,8 +280,8 @@ void CGUIStaticText::breakText() BrokenText.clear(); - IGUISkin* skin = Environment->getSkin(); - IGUIFont* font = getActiveFont(); + IGUISkin *skin = Environment->getSkin(); + IGUIFont *font = getActiveFont(); if (!font) return; @@ -330,70 +294,60 @@ void CGUIStaticText::breakText() s32 length = 0; s32 elWidth = RelativeRect.getWidth(); if (Border) - elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); + elWidth -= 2 * skin->getSize(EGDS_TEXT_DISTANCE_X); wchar_t c; // We have to deal with right-to-left and left-to-right differently // However, most parts of the following code is the same, it's just // some order and boundaries which change. - if (!RightToLeft) - { + if (!RightToLeft) { // regular (left-to-right) - for (s32 i=0; igetDimension(whitespace.c_str()).Width; const s32 wordlgth = font->getDimension(word.c_str()).Width; - if (wordlgth > elWidth) - { + if (wordlgth > elWidth) { // This word is too long to fit in the available space, look for // the Unicode Soft HYphen (SHY / 00AD) character for a place to // break the word at - int where = word.findFirst( wchar_t(0x00AD) ); - if (where != -1) - { - core::stringw first = word.subString(0, where); + int where = word.findFirst(wchar_t(0x00AD)); + if (where != -1) { + core::stringw first = word.subString(0, where); core::stringw second = word.subString(where, word.size() - where); BrokenText.push_back(line + first + L"-"); const s32 secondLength = font->getDimension(second.c_str()).Width; length = secondLength; line = second; - } - else - { + } else { // No soft hyphen found, so there's nothing more we can do // break to next line if (length) @@ -401,16 +355,12 @@ void CGUIStaticText::breakText() length = wordlgth; line = word; } - } - else if (length && (length + wordlgth + whitelgth > elWidth)) - { + } else if (length && (length + wordlgth + whitelgth > elWidth)) { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; - } - else - { + } else { // add word to line line += whitespace; line += word; @@ -421,14 +371,12 @@ void CGUIStaticText::breakText() whitespace = L""; } - if ( isWhitespace ) - { + if (isWhitespace) { whitespace += c; } // compute line break - if (lineBreak) - { + if (lineBreak) { line += whitespace; line += word; BrokenText.push_back(line); @@ -443,49 +391,40 @@ void CGUIStaticText::breakText() line += whitespace; line += word; BrokenText.push_back(line); - } - else - { + } else { // right-to-left - for (s32 i=size; i>=0; --i) - { + for (s32 i = size; i >= 0; --i) { c = Text[i]; bool lineBreak = false; if (c == L'\r') // Mac or Windows breaks { lineBreak = true; - if ((i>0) && Text[i-1] == L'\n') // Windows breaks + if ((i > 0) && Text[i - 1] == L'\n') // Windows breaks { - Text.erase(i-1); + Text.erase(i - 1); --size; } c = '\0'; - } - else if (c == L'\n') // Unix breaks + } else if (c == L'\n') // Unix breaks { lineBreak = true; c = '\0'; } - if (c==L' ' || c==0 || i==0) - { - if (word.size()) - { + if (c == L' ' || c == 0 || i == 0) { + if (word.size()) { // here comes the next whitespace, look if // we must break the last word to the next line. const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; const s32 wordlgth = font->getDimension(word.c_str()).Width; - if (length && (length + wordlgth + whitelgth > elWidth)) - { + if (length && (length + wordlgth + whitelgth > elWidth)) { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; - } - else - { + } else { // add word to line line = whitespace + line; line = word + line; @@ -500,8 +439,7 @@ void CGUIStaticText::breakText() whitespace = core::stringw(&c, 1) + whitespace; // compute line break - if (lineBreak) - { + if (lineBreak) { line = whitespace + line; line = word + line; BrokenText.push_back(line); @@ -510,9 +448,7 @@ void CGUIStaticText::breakText() whitespace = L""; length = 0; } - } - else - { + } else { // yippee this is a word.. word = core::stringw(&c, 1) + word; } @@ -524,36 +460,30 @@ void CGUIStaticText::breakText() } } - //! Sets the new caption of this element. -void CGUIStaticText::setText(const wchar_t* text) +void CGUIStaticText::setText(const wchar_t *text) { IGUIElement::setText(text); breakText(); } - void CGUIStaticText::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); breakText(); } - //! Returns the height of the text in pixels when it is drawn. s32 CGUIStaticText::getTextHeight() const { - IGUIFont* font = getActiveFont(); + IGUIFont *font = getActiveFont(); if (!font) return 0; - if (WordWrap) - { + if (WordWrap) { s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); - return height* BrokenText.size(); - } - else - { + return height * BrokenText.size(); + } else { // TODO: Text can have multiple lines which are not in BrokenText // This is likely not correct. But as I have no time for further // investigation I just fix it for now by return the true height here. @@ -561,33 +491,27 @@ s32 CGUIStaticText::getTextHeight() const } } - s32 CGUIStaticText::getTextWidth() const { - IGUIFont * font = getActiveFont(); - if(!font) + IGUIFont *font = getActiveFont(); + if (!font) return 0; - if(WordWrap) - { + if (WordWrap) { s32 widest = 0; - for(u32 line = 0; line < BrokenText.size(); ++line) - { + for (u32 line = 0; line < BrokenText.size(); ++line) { s32 width = font->getDimension(BrokenText[line].c_str()).Width; - if(width > widest) + if (width > widest) widest = width; } return widest; - } - else - { + } else { return font->getDimension(Text.c_str()).Width; } } - } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUIStaticText.h b/source/Irrlicht/CGUIStaticText.h index 04a3c7ad..c127769f 100644 --- a/source/Irrlicht/CGUIStaticText.h +++ b/source/Irrlicht/CGUIStaticText.h @@ -11,123 +11,121 @@ namespace irr { namespace gui { - class CGUIStaticText : public IGUIStaticText - { - public: - - //! constructor - CGUIStaticText(const wchar_t* text, bool border, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, const core::rect& rectangle, +class CGUIStaticText : public IGUIStaticText +{ +public: + //! constructor + CGUIStaticText(const wchar_t *text, bool border, IGUIEnvironment *environment, + IGUIElement *parent, s32 id, const core::rect &rectangle, bool background = false); - //! destructor - virtual ~CGUIStaticText(); + //! destructor + virtual ~CGUIStaticText(); - //! draws the element and its children - void draw() override; + //! draws the element and its children + void draw() override; - //! Sets another skin independent font. - void setOverrideFont(IGUIFont* font=0) override; + //! Sets another skin independent font. + void setOverrideFont(IGUIFont *font = 0) override; - //! Gets the override font (if any) - IGUIFont* getOverrideFont() const override; + //! Gets the override font (if any) + IGUIFont *getOverrideFont() const override; - //! Get the font which is used right now for drawing - IGUIFont* getActiveFont() const override; + //! Get the font which is used right now for drawing + IGUIFont *getActiveFont() const override; - //! Sets another color for the text. - void setOverrideColor(video::SColor color) override; + //! Sets another color for the text. + void setOverrideColor(video::SColor color) override; - //! Sets another color for the background. - void setBackgroundColor(video::SColor color) override; + //! Sets another color for the background. + void setBackgroundColor(video::SColor color) override; - //! Sets whether to draw the background - void setDrawBackground(bool draw) override; + //! Sets whether to draw the background + void setDrawBackground(bool draw) override; - //! Gets the background color - video::SColor getBackgroundColor() const override; + //! Gets the background color + video::SColor getBackgroundColor() const override; - //! Checks if background drawing is enabled - bool isDrawBackgroundEnabled() const override; + //! Checks if background drawing is enabled + bool isDrawBackgroundEnabled() const override; - //! Sets whether to draw the border - void setDrawBorder(bool draw) override; + //! Sets whether to draw the border + void setDrawBorder(bool draw) override; - //! Checks if border drawing is enabled - bool isDrawBorderEnabled() const override; + //! Checks if border drawing is enabled + bool isDrawBorderEnabled() const override; - //! Sets alignment mode for text - void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; + //! Sets alignment mode for text + void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) override; - //! Gets the override color - video::SColor getOverrideColor() const override; + //! Gets the override color + video::SColor getOverrideColor() const override; - //! Gets the currently used text color - video::SColor getActiveColor() const override; + //! Gets the currently used text color + video::SColor getActiveColor() const override; - //! Sets if the static text should use the override color or the - //! color in the gui skin. - void enableOverrideColor(bool enable) override; + //! Sets if the static text should use the override color or the + //! color in the gui skin. + void enableOverrideColor(bool enable) override; - //! Checks if an override color is enabled - bool isOverrideColorEnabled() const override; + //! Checks if an override color is enabled + bool isOverrideColorEnabled() const override; - //! Set whether the text in this label should be clipped if it goes outside bounds - void setTextRestrainedInside(bool restrainedInside) override; + //! Set whether the text in this label should be clipped if it goes outside bounds + void setTextRestrainedInside(bool restrainedInside) override; - //! Checks if the text in this label should be clipped if it goes outside bounds - bool isTextRestrainedInside() const override; + //! Checks if the text in this label should be clipped if it goes outside bounds + bool isTextRestrainedInside() const override; - //! Enables or disables word wrap for using the static text as - //! multiline text control. - void setWordWrap(bool enable) override; + //! Enables or disables word wrap for using the static text as + //! multiline text control. + void setWordWrap(bool enable) override; - //! Checks if word wrap is enabled - bool isWordWrapEnabled() const override; + //! Checks if word wrap is enabled + bool isWordWrapEnabled() const override; - //! Sets the new caption of this element. - void setText(const wchar_t* text) override; + //! Sets the new caption of this element. + void setText(const wchar_t *text) override; - //! Returns the height of the text in pixels when it is drawn. - s32 getTextHeight() const override; + //! Returns the height of the text in pixels when it is drawn. + s32 getTextHeight() const override; - //! Returns the width of the current text, in the current font - s32 getTextWidth() const override; + //! Returns the width of the current text, in the current font + s32 getTextWidth() const override; - //! Updates the absolute position, splits text if word wrap is enabled - void updateAbsolutePosition() override; + //! Updates the absolute position, splits text if word wrap is enabled + void updateAbsolutePosition() override; - //! Set whether the string should be interpreted as right-to-left (RTL) text - /** \note This component does not implement the Unicode bidi standard, the - text of the component should be already RTL if you call this. The - main difference when RTL is enabled is that the linebreaks for multiline - elements are performed starting from the end. - */ - void setRightToLeft(bool rtl) override; + //! Set whether the string should be interpreted as right-to-left (RTL) text + /** \note This component does not implement the Unicode bidi standard, the + text of the component should be already RTL if you call this. The + main difference when RTL is enabled is that the linebreaks for multiline + elements are performed starting from the end. + */ + void setRightToLeft(bool rtl) override; - //! Checks if the text should be interpreted as right-to-left text - bool isRightToLeft() const override; + //! Checks if the text should be interpreted as right-to-left text + bool isRightToLeft() const override; - private: +private: + //! Breaks the single text line. + void breakText(); - //! Breaks the single text line. - void breakText(); + EGUI_ALIGNMENT HAlign, VAlign; + bool Border; + bool OverrideColorEnabled; + bool OverrideBGColorEnabled; + bool WordWrap; + bool Background; + bool RestrainTextInside; + bool RightToLeft; - EGUI_ALIGNMENT HAlign, VAlign; - bool Border; - bool OverrideColorEnabled; - bool OverrideBGColorEnabled; - bool WordWrap; - bool Background; - bool RestrainTextInside; - bool RightToLeft; + video::SColor OverrideColor, BGColor; + gui::IGUIFont *OverrideFont; + gui::IGUIFont *LastBreakFont; // stored because: if skin changes, line break must be recalculated. - video::SColor OverrideColor, BGColor; - gui::IGUIFont* OverrideFont; - gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. - - core::array< core::stringw > BrokenText; - }; + core::array BrokenText; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CGUITabControl.cpp b/source/Irrlicht/CGUITabControl.cpp index f4e1f990..2c477824 100644 --- a/source/Irrlicht/CGUITabControl.cpp +++ b/source/Irrlicht/CGUITabControl.cpp @@ -22,18 +22,18 @@ namespace gui // ------------------------------------------------------------------ //! constructor -CGUITab::CGUITab(IGUIEnvironment* environment, - IGUIElement* parent, const core::rect& rectangle, - s32 id) - : IGUITab(environment, parent, id, rectangle), - BackColor(0,0,0,0), OverrideTextColorEnabled(false), TextColor(255,0,0,0), +CGUITab::CGUITab(IGUIEnvironment *environment, + IGUIElement *parent, const core::rect &rectangle, + s32 id) : + IGUITab(environment, parent, id, rectangle), + BackColor(0, 0, 0, 0), OverrideTextColorEnabled(false), TextColor(255, 0, 0, 0), DrawBackground(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUITab"); - #endif +#endif - const IGUISkin* const skin = environment->getSkin(); + const IGUISkin *const skin = environment->getSkin(); if (skin) TextColor = skin->getColor(EGDC_BUTTON_TEXT); } @@ -52,21 +52,18 @@ void CGUITab::draw() IGUIElement::draw(); } - //! sets if the tab should draw its background void CGUITab::setDrawBackground(bool draw) { DrawBackground = draw; } - //! sets the color of the background, if it should be drawn. void CGUITab::setBackgroundColor(video::SColor c) { BackColor = c; } - //! sets the color of the text void CGUITab::setTextColor(video::SColor c) { @@ -74,10 +71,9 @@ void CGUITab::setTextColor(video::SColor c) TextColor = c; } - video::SColor CGUITab::getTextColor() const { - if ( OverrideTextColorEnabled ) + if (OverrideTextColorEnabled) return TextColor; else return Environment->getSkin()->getColor(EGDC_BUTTON_TEXT); @@ -89,45 +85,42 @@ bool CGUITab::isDrawingBackground() const return DrawBackground; } - //! returns the color of the background video::SColor CGUITab::getBackgroundColor() const { return BackColor; } - // ------------------------------------------------------------------ // Tabcontrol // ------------------------------------------------------------------ //! constructor -CGUITabControl::CGUITabControl(IGUIEnvironment* environment, - IGUIElement* parent, const core::rect& rectangle, - bool fillbackground, bool border, s32 id) - : IGUITabControl(environment, parent, id, rectangle), ActiveTabIndex(-1), - Border(border), FillBackground(fillbackground), ScrollControl(false), TabHeight(0), VerticalAlignment(EGUIA_UPPERLEFT), - UpButton(0), DownButton(0), TabMaxWidth(0), CurrentScrollTabIndex(0), TabExtraWidth(20) +CGUITabControl::CGUITabControl(IGUIEnvironment *environment, + IGUIElement *parent, const core::rect &rectangle, + bool fillbackground, bool border, s32 id) : + IGUITabControl(environment, parent, id, rectangle), + ActiveTabIndex(-1), + Border(border), FillBackground(fillbackground), ScrollControl(false), TabHeight(0), VerticalAlignment(EGUIA_UPPERLEFT), + UpButton(0), DownButton(0), TabMaxWidth(0), CurrentScrollTabIndex(0), TabExtraWidth(20) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CGUITabControl"); - #endif +#endif - IGUISkin* skin = Environment->getSkin(); - IGUISpriteBank* sprites = 0; + IGUISkin *skin = Environment->getSkin(); + IGUISpriteBank *sprites = 0; TabHeight = 32; - if (skin) - { + if (skin) { sprites = skin->getSpriteBank(); TabHeight = skin->getSize(gui::EGDS_BUTTON_HEIGHT) + 2; } - UpButton = Environment->addButton(core::rect(0,0,10,10), this); + UpButton = Environment->addButton(core::rect(0, 0, 10, 10), this); - if (UpButton) - { + if (UpButton) { UpButton->setSpriteBank(sprites); UpButton->setVisible(false); UpButton->setSubElement(true); @@ -136,10 +129,9 @@ CGUITabControl::CGUITabControl(IGUIEnvironment* environment, UpButton->grab(); } - DownButton = Environment->addButton(core::rect(0,0,10,10), this); + DownButton = Environment->addButton(core::rect(0, 0, 10, 10), this); - if (DownButton) - { + if (DownButton) { DownButton->setSpriteBank(sprites); DownButton->setVisible(false); DownButton->setSubElement(true); @@ -155,8 +147,7 @@ CGUITabControl::CGUITabControl(IGUIEnvironment* environment, //! destructor CGUITabControl::~CGUITabControl() { - for (u32 i=0; idrop(); } @@ -170,20 +161,17 @@ CGUITabControl::~CGUITabControl() void CGUITabControl::refreshSprites() { - video::SColor color(255,255,255,255); - IGUISkin* skin = Environment->getSkin(); - if (skin) - { + video::SColor color(255, 255, 255, 255); + IGUISkin *skin = Environment->getSkin(); + if (skin) { color = skin->getColor(isEnabled() ? EGDC_WINDOW_SYMBOL : EGDC_GRAY_WINDOW_SYMBOL); - if (UpButton) - { + if (UpButton) { UpButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_LEFT), color); UpButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_LEFT), color); } - if (DownButton) - { + if (DownButton) { DownButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_CURSOR_RIGHT), color); DownButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_CURSOR_RIGHT), color); } @@ -191,18 +179,17 @@ void CGUITabControl::refreshSprites() } //! Adds a tab -IGUITab* CGUITabControl::addTab(const wchar_t* caption, s32 id) +IGUITab *CGUITabControl::addTab(const wchar_t *caption, s32 id) { - CGUITab* tab = new CGUITab(Environment, this, calcTabPos(), id); + CGUITab *tab = new CGUITab(Environment, this, calcTabPos(), id); tab->setText(caption); tab->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); tab->setVisible(false); - Tabs.push_back(tab); // no grab as new already creates a reference + Tabs.push_back(tab); // no grab as new already creates a reference - if (ActiveTabIndex == -1) - { - ActiveTabIndex = Tabs.size()-1; + if (ActiveTabIndex == -1) { + ActiveTabIndex = Tabs.size() - 1; tab->setVisible(true); } @@ -211,33 +198,29 @@ IGUITab* CGUITabControl::addTab(const wchar_t* caption, s32 id) return tab; } - //! adds a tab which has been created elsewhere -s32 CGUITabControl::addTab(IGUITab* tab) +s32 CGUITabControl::addTab(IGUITab *tab) { - return insertTab( Tabs.size(), tab, false); + return insertTab(Tabs.size(), tab, false); } //! Insert the tab at the given index -IGUITab* CGUITabControl::insertTab(s32 idx, const wchar_t* caption, s32 id) +IGUITab *CGUITabControl::insertTab(s32 idx, const wchar_t *caption, s32 id) { - if ( idx < 0 || idx > (s32)Tabs.size() ) // idx == Tabs.size() is indeed OK here as core::array can handle that + if (idx < 0 || idx > (s32)Tabs.size()) // idx == Tabs.size() is indeed OK here as core::array can handle that return NULL; - CGUITab* tab = new CGUITab(Environment, this, calcTabPos(), id); + CGUITab *tab = new CGUITab(Environment, this, calcTabPos(), id); tab->setText(caption); tab->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); tab->setVisible(false); Tabs.insert(tab, (u32)idx); - if (ActiveTabIndex == -1) - { + if (ActiveTabIndex == -1) { ActiveTabIndex = (u32)idx; tab->setVisible(true); - } - else if ( idx <= ActiveTabIndex ) - { + } else if (idx <= ActiveTabIndex) { ++ActiveTabIndex; setVisibleTab(ActiveTabIndex); } @@ -247,51 +230,44 @@ IGUITab* CGUITabControl::insertTab(s32 idx, const wchar_t* caption, s32 id) return tab; } -s32 CGUITabControl::insertTab(s32 idx, IGUITab* tab, bool serializationMode) +s32 CGUITabControl::insertTab(s32 idx, IGUITab *tab, bool serializationMode) { if (!tab) return -1; - if ( idx > (s32)Tabs.size() && !serializationMode ) // idx == Tabs.size() is indeed OK here as core::array can handle that + if (idx > (s32)Tabs.size() && !serializationMode) // idx == Tabs.size() is indeed OK here as core::array can handle that return -1; // Not allowing to add same tab twice as it would make things complicated (serialization or setting active visible) - if ( getTabIndex(tab) >= 0 ) + if (getTabIndex(tab) >= 0) return -1; - if ( idx < 0 ) + if (idx < 0) idx = (s32)Tabs.size(); - if ( tab->getParent() != this ) + if (tab->getParent() != this) this->addChildToEnd(tab); tab->setVisible(false); tab->grab(); - if ( serializationMode) - { - while ( idx >= (s32)Tabs.size() ) - { + if (serializationMode) { + while (idx >= (s32)Tabs.size()) { Tabs.push_back(0); } Tabs[idx] = tab; - if ( idx == ActiveTabIndex) // in serialization that can happen for any index + if (idx == ActiveTabIndex) // in serialization that can happen for any index { setVisibleTab(ActiveTabIndex); tab->setVisible(true); } - } - else - { + } else { Tabs.insert(tab, (u32)idx); - if (ActiveTabIndex == -1) - { + if (ActiveTabIndex == -1) { ActiveTabIndex = idx; setVisibleTab(ActiveTabIndex); - } - else if ( idx <= ActiveTabIndex) - { + } else if (idx <= ActiveTabIndex) { ++ActiveTabIndex; setVisibleTab(ActiveTabIndex); } @@ -303,10 +279,10 @@ s32 CGUITabControl::insertTab(s32 idx, IGUITab* tab, bool serializationMode) } //! Removes a child. -void CGUITabControl::removeChild(IGUIElement* child) +void CGUITabControl::removeChild(IGUIElement *child) { s32 idx = getTabIndex(child); - if ( idx >= 0 ) + if (idx >= 0) removeTabButNotChild(idx); // remove real element @@ -315,11 +291,10 @@ void CGUITabControl::removeChild(IGUIElement* child) recalculateScrollBar(); } - //! Removes a tab from the tabcontrol void CGUITabControl::removeTab(s32 idx) { - if ( idx < 0 || idx >= (s32)Tabs.size() ) + if (idx < 0 || idx >= (s32)Tabs.size()) return; removeChild(Tabs[(u32)idx]); @@ -327,20 +302,17 @@ void CGUITabControl::removeTab(s32 idx) void CGUITabControl::removeTabButNotChild(s32 idx) { - if ( idx < 0 || idx >= (s32)Tabs.size() ) + if (idx < 0 || idx >= (s32)Tabs.size()) return; Tabs[(u32)idx]->drop(); Tabs.erase((u32)idx); - if ( idx < ActiveTabIndex ) - { + if (idx < ActiveTabIndex) { --ActiveTabIndex; setVisibleTab(ActiveTabIndex); - } - else if ( idx == ActiveTabIndex ) - { - if ( (u32)idx == Tabs.size() ) + } else if (idx == ActiveTabIndex) { + if ((u32)idx == Tabs.size()) --ActiveTabIndex; setVisibleTab(ActiveTabIndex); } @@ -349,10 +321,8 @@ void CGUITabControl::removeTabButNotChild(s32 idx) //! Clears the tabcontrol removing all tabs void CGUITabControl::clear() { - for (u32 i=0; idrop(); } @@ -368,9 +338,8 @@ s32 CGUITabControl::getTabCount() const return Tabs.size(); } - //! Returns a tab based on zero based index -IGUITab* CGUITabControl::getTab(s32 idx) const +IGUITab *CGUITabControl::getTab(s32 idx) const { if (idx < 0 || (u32)idx >= Tabs.size()) return 0; @@ -378,45 +347,35 @@ IGUITab* CGUITabControl::getTab(s32 idx) const return Tabs[idx]; } - //! called if an event happened. -bool CGUITabControl::OnEvent(const SEvent& event) +bool CGUITabControl::OnEvent(const SEvent &event) { - if (isEnabled()) - { - switch(event.EventType) - { + if (isEnabled()) { + switch (event.EventType) { case EET_GUI_EVENT: - switch(event.GUIEvent.EventType) - { + switch (event.GUIEvent.EventType) { case EGET_BUTTON_CLICKED: - if (event.GUIEvent.Caller == UpButton) - { + if (event.GUIEvent.Caller == UpButton) { scrollLeft(); return true; - } - else if (event.GUIEvent.Caller == DownButton) - { + } else if (event.GUIEvent.Caller == DownButton) { scrollRight(); return true; } - break; + break; default: - break; + break; } break; case EET_MOUSE_INPUT_EVENT: - switch(event.MouseInput.Event) - { - //case EMIE_LMOUSE_PRESSED_DOWN: + switch (event.MouseInput.Event) { + // case EMIE_LMOUSE_PRESSED_DOWN: // // todo: dragging tabs around // return true; - case EMIE_LMOUSE_LEFT_UP: - { + case EMIE_LMOUSE_LEFT_UP: { s32 idx = getTabAt(event.MouseInput.X, event.MouseInput.Y); - if ( idx >= 0 ) - { + if (idx >= 0) { setActiveTab(idx); return true; } @@ -434,32 +393,29 @@ bool CGUITabControl::OnEvent(const SEvent& event) return IGUIElement::OnEvent(event); } - void CGUITabControl::scrollLeft() { - if ( CurrentScrollTabIndex > 0 ) + if (CurrentScrollTabIndex > 0) --CurrentScrollTabIndex; recalculateScrollBar(); } - void CGUITabControl::scrollRight() { - if ( CurrentScrollTabIndex < (s32)(Tabs.size()) - 1 ) - { - if ( needScrollControl(CurrentScrollTabIndex, true) ) + if (CurrentScrollTabIndex < (s32)(Tabs.size()) - 1) { + if (needScrollControl(CurrentScrollTabIndex, true)) ++CurrentScrollTabIndex; } recalculateScrollBar(); } -s32 CGUITabControl::calcTabWidth(IGUIFont* font, const wchar_t* text) const +s32 CGUITabControl::calcTabWidth(IGUIFont *font, const wchar_t *text) const { - if ( !font ) + if (!font) return 0; s32 len = font->getDimension(text).Width + TabExtraWidth; - if ( TabMaxWidth > 0 && len > TabMaxWidth ) + if (TabMaxWidth > 0 && len > TabMaxWidth) len = TabMaxWidth; return len; @@ -467,14 +423,14 @@ s32 CGUITabControl::calcTabWidth(IGUIFont* font, const wchar_t* text) const bool CGUITabControl::needScrollControl(s32 startIndex, bool withScrollControl, s32 *pos_rightmost) { - if ( startIndex < 0 ) + if (startIndex < 0) startIndex = 0; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (!skin) return false; - IGUIFont* font = skin->getFont(); + IGUIFont *font = skin->getFont(); if (Tabs.empty()) return false; @@ -483,20 +439,16 @@ bool CGUITabControl::needScrollControl(s32 startIndex, bool withScrollControl, s return false; s32 pos = AbsoluteRect.UpperLeftCorner.X + 2; - const s32 pos_right = withScrollControl ? - UpButton->getAbsolutePosition().UpperLeftCorner.X - 2 : - AbsoluteRect.LowerRightCorner.X; + const s32 pos_right = withScrollControl ? UpButton->getAbsolutePosition().UpperLeftCorner.X - 2 : AbsoluteRect.LowerRightCorner.X; - for (s32 i = startIndex; i < (s32)Tabs.size(); ++i) - { + for (s32 i = startIndex; i < (s32)Tabs.size(); ++i) { // get Text - const wchar_t* text = 0; - if (Tabs[i]) - { + const wchar_t *text = 0; + if (Tabs[i]) { text = Tabs[i]->getText(); // get text length - s32 len = calcTabWidth(font, text); // always without withScrollControl here or len would be shortened + s32 len = calcTabWidth(font, text); // always without withScrollControl here or len would be shortened pos += len; } @@ -509,7 +461,6 @@ bool CGUITabControl::needScrollControl(s32 startIndex, bool withScrollControl, s return false; } - s32 CGUITabControl::calculateScrollIndexFromActive() { if (!ScrollControl || Tabs.empty()) @@ -566,27 +517,21 @@ core::rect CGUITabControl::calcTabPos() core::rect r; r.UpperLeftCorner.X = 0; r.LowerRightCorner.X = AbsoluteRect.getWidth(); - if ( Border ) - { + if (Border) { ++r.UpperLeftCorner.X; --r.LowerRightCorner.X; } - if ( VerticalAlignment == EGUIA_UPPERLEFT ) - { - r.UpperLeftCorner.Y = TabHeight+2; - r.LowerRightCorner.Y = AbsoluteRect.getHeight()-1; - if ( Border ) - { + if (VerticalAlignment == EGUIA_UPPERLEFT) { + r.UpperLeftCorner.Y = TabHeight + 2; + r.LowerRightCorner.Y = AbsoluteRect.getHeight() - 1; + if (Border) { --r.LowerRightCorner.Y; } - } - else - { + } else { r.UpperLeftCorner.Y = 0; - r.LowerRightCorner.Y = AbsoluteRect.getHeight()-(TabHeight+2); - if ( Border ) - { + r.LowerRightCorner.Y = AbsoluteRect.getHeight() - (TabHeight + 2); + if (Border) { ++r.UpperLeftCorner.Y; } } @@ -594,19 +539,18 @@ core::rect CGUITabControl::calcTabPos() return r; } - //! draws the element and its children void CGUITabControl::draw() { if (!IsVisible) return; - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); if (!skin) return; - IGUIFont* font = skin->getFont(); - video::IVideoDriver* driver = Environment->getVideoDriver(); + IGUIFont *font = skin->getFont(); + video::IVideoDriver *driver = Environment->getVideoDriver(); core::rect frameRect(AbsoluteRect); @@ -618,13 +562,10 @@ void CGUITabControl::draw() return; // tab button bar can be above or below the tabs - if ( VerticalAlignment == EGUIA_UPPERLEFT ) - { + if (VerticalAlignment == EGUIA_UPPERLEFT) { frameRect.UpperLeftCorner.Y += 2; frameRect.LowerRightCorner.Y = frameRect.UpperLeftCorner.Y + TabHeight; - } - else - { + } else { frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - TabHeight - 1; frameRect.LowerRightCorner.Y -= 2; } @@ -639,14 +580,13 @@ void CGUITabControl::draw() s32 left = 0; s32 right = 0; - //const wchar_t* activetext = 0; + // const wchar_t* activetext = 0; IGUITab *activeTab = 0; // Draw all tab-buttons except the active one - for (u32 i = CurrentScrollTabIndex; i < Tabs.size() && !needRightScroll; ++i) - { + for (u32 i = CurrentScrollTabIndex; i < Tabs.size() && !needRightScroll; ++i) { // get Text - const wchar_t* text = 0; + const wchar_t *text = 0; if (Tabs[i]) text = Tabs[i]->getText(); @@ -666,44 +606,39 @@ void CGUITabControl::draw() pos += len; - if ((s32)i == ActiveTabIndex) - { + if ((s32)i == ActiveTabIndex) { // for active button just remember values left = frameRect.UpperLeftCorner.X; right = frameRect.LowerRightCorner.X; - //activetext = text; + // activetext = text; activeTab = Tabs[i]; - } - else - { + } else { skin->draw3DTabButton(this, false, frameRect, &AbsoluteClippingRect, VerticalAlignment); // draw text - core::rect textClipRect(frameRect); // TODO: exact size depends on borders in draw3DTabButton which we don't get with current interface + core::rect textClipRect(frameRect); // TODO: exact size depends on borders in draw3DTabButton which we don't get with current interface textClipRect.clipAgainst(AbsoluteClippingRect); font->draw(text, frameRect, Tabs[i]->getTextColor(), - true, true, &textClipRect); + true, true, &textClipRect); } } // Draw active tab button // Drawn later than other buttons because it draw over the buttons before/after it. - if (left != 0 && right != 0 && activeTab != 0) - { + if (left != 0 && right != 0 && activeTab != 0) { // draw upper highlight frame - if ( VerticalAlignment == EGUIA_UPPERLEFT ) - { - frameRect.UpperLeftCorner.X = left-2; - frameRect.LowerRightCorner.X = right+2; + if (VerticalAlignment == EGUIA_UPPERLEFT) { + frameRect.UpperLeftCorner.X = left - 2; + frameRect.LowerRightCorner.X = right + 2; frameRect.UpperLeftCorner.Y -= 2; skin->draw3DTabButton(this, true, frameRect, &AbsoluteClippingRect, VerticalAlignment); // draw text - core::rect textClipRect(frameRect); // TODO: exact size depends on borders in draw3DTabButton which we don't get with current interface + core::rect textClipRect(frameRect); // TODO: exact size depends on borders in draw3DTabButton which we don't get with current interface textClipRect.clipAgainst(AbsoluteClippingRect); font->draw(activeTab->getText(), frameRect, activeTab->getTextColor(), - true, true, &textClipRect); + true, true, &textClipRect); tr.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X; tr.LowerRightCorner.X = left - 1; @@ -714,18 +649,16 @@ void CGUITabControl::draw() tr.UpperLeftCorner.X = right; tr.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X; driver->draw2DRectangle(skin->getColor(EGDC_3D_HIGH_LIGHT), tr, &AbsoluteClippingRect); - } - else - { - frameRect.UpperLeftCorner.X = left-2; - frameRect.LowerRightCorner.X = right+2; + } else { + frameRect.UpperLeftCorner.X = left - 2; + frameRect.LowerRightCorner.X = right + 2; frameRect.LowerRightCorner.Y += 2; skin->draw3DTabButton(this, true, frameRect, &AbsoluteClippingRect, VerticalAlignment); // draw text font->draw(activeTab->getText(), frameRect, activeTab->getTextColor(), - true, true, &frameRect); + true, true, &frameRect); tr.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X; tr.LowerRightCorner.X = left - 1; @@ -737,9 +670,7 @@ void CGUITabControl::draw() tr.LowerRightCorner.X = AbsoluteRect.LowerRightCorner.X; driver->draw2DRectangle(skin->getColor(EGDC_3D_DARK_SHADOW), tr, &AbsoluteClippingRect); } - } - else - { + } else { // No active tab // Draw a line separating button bar from tab area tr.UpperLeftCorner.X = AbsoluteRect.UpperLeftCorner.X; @@ -747,12 +678,9 @@ void CGUITabControl::draw() tr.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - 1; tr.LowerRightCorner.Y = frameRect.LowerRightCorner.Y; - if ( VerticalAlignment == EGUIA_UPPERLEFT ) - { + if (VerticalAlignment == EGUIA_UPPERLEFT) { driver->draw2DRectangle(skin->getColor(EGDC_3D_HIGH_LIGHT), tr, &AbsoluteClippingRect); - } - else - { + } else { tr.UpperLeftCorner.Y = frameRect.UpperLeftCorner.Y - 1; tr.LowerRightCorner.Y = frameRect.UpperLeftCorner.Y; driver->draw2DRectangle(skin->getColor(EGDC_3D_DARK_SHADOW), tr, &AbsoluteClippingRect); @@ -763,20 +691,19 @@ void CGUITabControl::draw() skin->draw3DTabBody(this, Border, FillBackground, AbsoluteRect, &AbsoluteClippingRect, TabHeight, VerticalAlignment); // enable scrollcontrols on need - if ( UpButton ) + if (UpButton) UpButton->setEnabled(needLeftScroll); - if ( DownButton ) + if (DownButton) DownButton->setEnabled(needRightScroll); refreshSprites(); IGUIElement::draw(); } - //! Set the height of the tabs -void CGUITabControl::setTabHeight( s32 height ) +void CGUITabControl::setTabHeight(s32 height) { - if ( height < 0 ) + if (height < 0) height = 0; TabHeight = height; @@ -785,7 +712,6 @@ void CGUITabControl::setTabHeight( s32 height ) recalculateScrollBar(); } - //! Get the height of the tabs s32 CGUITabControl::getTabHeight() const { @@ -793,7 +719,7 @@ s32 CGUITabControl::getTabHeight() const } //! set the maximal width of a tab. Per default width is 0 which means "no width restriction". -void CGUITabControl::setTabMaxWidth(s32 width ) +void CGUITabControl::setTabMaxWidth(s32 width) { TabMaxWidth = width; } @@ -804,11 +730,10 @@ s32 CGUITabControl::getTabMaxWidth() const return TabMaxWidth; } - //! Set the extra width added to tabs on each side of the text -void CGUITabControl::setTabExtraWidth( s32 extraWidth ) +void CGUITabControl::setTabExtraWidth(s32 extraWidth) { - if ( extraWidth < 0 ) + if (extraWidth < 0) extraWidth = 0; TabExtraWidth = extraWidth; @@ -816,14 +741,12 @@ void CGUITabControl::setTabExtraWidth( s32 extraWidth ) recalculateScrollBar(); } - //! Get the extra width added to tabs on each side of the text s32 CGUITabControl::getTabExtraWidth() const { return TabExtraWidth; } - void CGUITabControl::recalculateScrollBar() { // Down: to right, Up: to left @@ -832,23 +755,20 @@ void CGUITabControl::recalculateScrollBar() ScrollControl = needScrollControl() || CurrentScrollTabIndex > 0; - if (ScrollControl) - { - UpButton->setVisible( true ); - DownButton->setVisible( true ); - } - else - { - UpButton->setVisible( false ); - DownButton->setVisible( false ); + if (ScrollControl) { + UpButton->setVisible(true); + DownButton->setVisible(true); + } else { + UpButton->setVisible(false); + DownButton->setVisible(false); } - bringToFront( UpButton ); - bringToFront( DownButton ); + bringToFront(UpButton); + bringToFront(DownButton); } //! Set the alignment of the tabs -void CGUITabControl::setTabVerticalAlignment( EGUI_ALIGNMENT alignment ) +void CGUITabControl::setTabVerticalAlignment(EGUI_ALIGNMENT alignment) { VerticalAlignment = alignment; @@ -856,45 +776,40 @@ void CGUITabControl::setTabVerticalAlignment( EGUI_ALIGNMENT alignment ) recalculateScrollBar(); core::rect r(calcTabPos()); - for ( u32 i=0; isetRelativePosition(r); } } void CGUITabControl::recalculateScrollButtonPlacement() { - IGUISkin* skin = Environment->getSkin(); + IGUISkin *skin = Environment->getSkin(); s32 ButtonSize = 16; s32 ButtonHeight = TabHeight - 2; - if ( ButtonHeight < 0 ) + if (ButtonHeight < 0) ButtonHeight = TabHeight; - if (skin) - { + if (skin) { ButtonSize = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH); if (ButtonSize > TabHeight) ButtonSize = TabHeight; } - s32 ButtonX = RelativeRect.getWidth() - (s32)(2.5f*(f32)ButtonSize) - 1; + s32 ButtonX = RelativeRect.getWidth() - (s32)(2.5f * (f32)ButtonSize) - 1; s32 ButtonY = 0; - if (VerticalAlignment == EGUIA_UPPERLEFT) - { + if (VerticalAlignment == EGUIA_UPPERLEFT) { ButtonY = 2 + (TabHeight / 2) - (ButtonHeight / 2); UpButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); DownButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT); - } - else - { + } else { ButtonY = RelativeRect.getHeight() - (TabHeight / 2) - (ButtonHeight / 2) - 2; UpButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT); DownButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT); } - UpButton->setRelativePosition(core::rect(ButtonX, ButtonY, ButtonX+ButtonSize, ButtonY+ButtonHeight)); + UpButton->setRelativePosition(core::rect(ButtonX, ButtonY, ButtonX + ButtonSize, ButtonY + ButtonHeight)); ButtonX += ButtonSize + 1; - DownButton->setRelativePosition(core::rect(ButtonX, ButtonY, ButtonX+ButtonSize, ButtonY+ButtonHeight)); + DownButton->setRelativePosition(core::rect(ButtonX, ButtonY, ButtonX + ButtonSize, ButtonY + ButtonHeight)); } //! Get the alignment of the tabs @@ -903,22 +818,18 @@ EGUI_ALIGNMENT CGUITabControl::getTabVerticalAlignment() const return VerticalAlignment; } - s32 CGUITabControl::getTabAt(s32 xpos, s32 ypos) const { core::position2di p(xpos, ypos); - IGUISkin* skin = Environment->getSkin(); - IGUIFont* font = skin->getFont(); + IGUISkin *skin = Environment->getSkin(); + IGUIFont *font = skin->getFont(); core::rect frameRect(AbsoluteRect); - if ( VerticalAlignment == EGUIA_UPPERLEFT ) - { + if (VerticalAlignment == EGUIA_UPPERLEFT) { frameRect.UpperLeftCorner.Y += 2; frameRect.LowerRightCorner.Y = frameRect.UpperLeftCorner.Y + TabHeight; - } - else - { + } else { frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - TabHeight; } @@ -928,10 +839,9 @@ s32 CGUITabControl::getTabAt(s32 xpos, s32 ypos) const return -1; bool abort = false; - for (s32 i = CurrentScrollTabIndex; i < (s32)Tabs.size() && !abort; ++i) - { + for (s32 i = CurrentScrollTabIndex; i < (s32)Tabs.size() && !abort; ++i) { // get Text - const wchar_t* text = 0; + const wchar_t *text = 0; if (Tabs[i]) text = Tabs[i]->getText(); @@ -951,11 +861,9 @@ s32 CGUITabControl::getTabAt(s32 xpos, s32 ypos) const pos += len; - if (frameRect.isPointInside(p)) - { + if (frameRect.isPointInside(p)) { return i; } - } return -1; } @@ -966,7 +874,6 @@ s32 CGUITabControl::getActiveTab() const return ActiveTabIndex; } - //! Brings a tab to front. bool CGUITabControl::setActiveTab(s32 idx) { @@ -979,8 +886,7 @@ bool CGUITabControl::setActiveTab(s32 idx) setVisibleTab(ActiveTabIndex); - if (changed && Parent) - { + if (changed && Parent) { SEvent event; event.EventType = EET_GUI_EVENT; event.GUIEvent.Caller = this; @@ -999,12 +905,11 @@ bool CGUITabControl::setActiveTab(s32 idx) void CGUITabControl::setVisibleTab(s32 idx) { - for (u32 i=0; isetVisible( (s32)i == idx ); + Tabs[i]->setVisible((s32)i == idx); } - bool CGUITabControl::setActiveTab(IGUITab *tab) { return setActiveTab(getTabIndex(tab)); @@ -1012,7 +917,7 @@ bool CGUITabControl::setActiveTab(IGUITab *tab) s32 CGUITabControl::getTabIndex(const IGUIElement *tab) const { - for (u32 i=0; i& rectangle, +// A tab, onto which other gui elements could be added. +class CGUITab : public IGUITab +{ +public: + //! constructor + CGUITab(IGUIEnvironment *environment, + IGUIElement *parent, const core::rect &rectangle, s32 id); - //! draws the element and its children - void draw() override; + //! draws the element and its children + void draw() override; - //! sets if the tab should draw its background - void setDrawBackground(bool draw=true) override; + //! sets if the tab should draw its background + void setDrawBackground(bool draw = true) override; - //! sets the color of the background, if it should be drawn. - void setBackgroundColor(video::SColor c) override; + //! sets the color of the background, if it should be drawn. + void setBackgroundColor(video::SColor c) override; - //! sets the color of the text - void setTextColor(video::SColor c) override; + //! sets the color of the text + void setTextColor(video::SColor c) override; - //! returns true if the tab is drawing its background, false if not - bool isDrawingBackground() const override; + //! returns true if the tab is drawing its background, false if not + bool isDrawingBackground() const override; - //! returns the color of the background - video::SColor getBackgroundColor() const override; + //! returns the color of the background + video::SColor getBackgroundColor() const override; - video::SColor getTextColor() const override; + video::SColor getTextColor() const override; - private: +private: + video::SColor BackColor; + bool OverrideTextColorEnabled; + video::SColor TextColor; + bool DrawBackground; +}; - video::SColor BackColor; - bool OverrideTextColorEnabled; - video::SColor TextColor; - bool DrawBackground; - }; +//! A standard tab control +class CGUITabControl : public IGUITabControl +{ +public: + //! destructor + CGUITabControl(IGUIEnvironment *environment, + IGUIElement *parent, const core::rect &rectangle, + bool fillbackground = true, bool border = true, s32 id = -1); + //! destructor + virtual ~CGUITabControl(); - //! A standard tab control - class CGUITabControl : public IGUITabControl - { - public: + //! Adds a tab + IGUITab *addTab(const wchar_t *caption, s32 id = -1) override; - //! destructor - CGUITabControl(IGUIEnvironment* environment, - IGUIElement* parent, const core::rect& rectangle, - bool fillbackground=true, bool border=true, s32 id=-1); + //! Adds an existing tab + s32 addTab(IGUITab *tab) override; - //! destructor - virtual ~CGUITabControl(); + //! Insert the tab at the given index + IGUITab *insertTab(s32 idx, const wchar_t *caption, s32 id = -1) override; - //! Adds a tab - IGUITab* addTab(const wchar_t* caption, s32 id=-1) override; + //! Insert an existing tab + /** Note that it will also add the tab as a child of this TabControl. + \return Index of added tab (should be same as the one passed) or -1 for failure*/ + s32 insertTab(s32 idx, IGUITab *tab, bool serializationMode) override; - //! Adds an existing tab - s32 addTab(IGUITab* tab) override; + //! Removes a tab from the tabcontrol + void removeTab(s32 idx) override; - //! Insert the tab at the given index - IGUITab* insertTab(s32 idx, const wchar_t* caption, s32 id=-1) override; + //! Clears the tabcontrol removing all tabs + void clear() override; - //! Insert an existing tab - /** Note that it will also add the tab as a child of this TabControl. - \return Index of added tab (should be same as the one passed) or -1 for failure*/ - s32 insertTab(s32 idx, IGUITab* tab, bool serializationMode) override; + //! Returns amount of tabs in the tabcontrol + s32 getTabCount() const override; - //! Removes a tab from the tabcontrol - void removeTab(s32 idx) override; + //! Returns a tab based on zero based index + IGUITab *getTab(s32 idx) const override; - //! Clears the tabcontrol removing all tabs - void clear() override; + //! Brings a tab to front. + bool setActiveTab(s32 idx) override; - //! Returns amount of tabs in the tabcontrol - s32 getTabCount() const override; + //! Brings a tab to front. + bool setActiveTab(IGUITab *tab) override; - //! Returns a tab based on zero based index - IGUITab* getTab(s32 idx) const override; + //! For given given tab find it's zero-based index (or -1 for not found) + s32 getTabIndex(const IGUIElement *tab) const override; - //! Brings a tab to front. - bool setActiveTab(s32 idx) override; + //! Returns which tab is currently active + s32 getActiveTab() const override; - //! Brings a tab to front. - bool setActiveTab(IGUITab *tab) override; + //! get the the id of the tab at the given absolute coordinates + s32 getTabAt(s32 xpos, s32 ypos) const override; - //! For given given tab find it's zero-based index (or -1 for not found) - s32 getTabIndex(const IGUIElement *tab) const override; + //! called if an event happened. + bool OnEvent(const SEvent &event) override; - //! Returns which tab is currently active - s32 getActiveTab() const override; + //! draws the element and its children + void draw() override; - //! get the the id of the tab at the given absolute coordinates - s32 getTabAt(s32 xpos, s32 ypos) const override; + //! Removes a child. + void removeChild(IGUIElement *child) override; - //! called if an event happened. - bool OnEvent(const SEvent& event) override; + //! Set the height of the tabs + void setTabHeight(s32 height) override; - //! draws the element and its children - void draw() override; + //! Get the height of the tabs + s32 getTabHeight() const override; - //! Removes a child. - void removeChild(IGUIElement* child) override; + //! set the maximal width of a tab. Per default width is 0 which means "no width restriction". + void setTabMaxWidth(s32 width) override; - //! Set the height of the tabs - void setTabHeight( s32 height ) override; + //! get the maximal width of a tab + s32 getTabMaxWidth() const override; - //! Get the height of the tabs - s32 getTabHeight() const override; + //! Set the alignment of the tabs + //! note: EGUIA_CENTER is not an option + void setTabVerticalAlignment(gui::EGUI_ALIGNMENT alignment) override; - //! set the maximal width of a tab. Per default width is 0 which means "no width restriction". - void setTabMaxWidth(s32 width ) override; + //! Get the alignment of the tabs + gui::EGUI_ALIGNMENT getTabVerticalAlignment() const override; - //! get the maximal width of a tab - s32 getTabMaxWidth() const override; + //! Set the extra width added to tabs on each side of the text + void setTabExtraWidth(s32 extraWidth) override; - //! Set the alignment of the tabs - //! note: EGUIA_CENTER is not an option - void setTabVerticalAlignment( gui::EGUI_ALIGNMENT alignment ) override; + //! Get the extra width added to tabs on each side of the text + s32 getTabExtraWidth() const override; - //! Get the alignment of the tabs - gui::EGUI_ALIGNMENT getTabVerticalAlignment() const override; + //! Update the position of the element, decides scroll button status + void updateAbsolutePosition() override; - //! Set the extra width added to tabs on each side of the text - void setTabExtraWidth( s32 extraWidth ) override; +private: + void scrollLeft(); + void scrollRight(); + //! Indicates whether the tabs overflow in X direction + bool needScrollControl(s32 startIndex = 0, bool withScrollControl = false, s32 *pos_rightmost = nullptr); + //! Left index calculation based on the selected tab + s32 calculateScrollIndexFromActive(); + s32 calcTabWidth(IGUIFont *font, const wchar_t *text) const; + core::rect calcTabPos(); + void setVisibleTab(s32 idx); + void removeTabButNotChild(s32 idx); - //! Get the extra width added to tabs on each side of the text - s32 getTabExtraWidth() const override; - - //! Update the position of the element, decides scroll button status - void updateAbsolutePosition() override; - - private: - - void scrollLeft(); - void scrollRight(); - //! Indicates whether the tabs overflow in X direction - bool needScrollControl( s32 startIndex=0, bool withScrollControl=false, s32 *pos_rightmost=nullptr ); - //! Left index calculation based on the selected tab - s32 calculateScrollIndexFromActive(); - s32 calcTabWidth(IGUIFont* font, const wchar_t* text) const; - core::rect calcTabPos(); - void setVisibleTab(s32 idx); - void removeTabButNotChild(s32 idx); - - void recalculateScrollButtonPlacement(); - void recalculateScrollBar(); - void refreshSprites(); - - core::array Tabs; - s32 ActiveTabIndex; - bool Border; - bool FillBackground; - bool ScrollControl; - s32 TabHeight; - gui::EGUI_ALIGNMENT VerticalAlignment; - IGUIButton* UpButton; - IGUIButton* DownButton; - s32 TabMaxWidth; - s32 CurrentScrollTabIndex; - s32 TabExtraWidth; - }; + void recalculateScrollButtonPlacement(); + void recalculateScrollBar(); + void refreshSprites(); + core::array Tabs; + s32 ActiveTabIndex; + bool Border; + bool FillBackground; + bool ScrollControl; + s32 TabHeight; + gui::EGUI_ALIGNMENT VerticalAlignment; + IGUIButton *UpButton; + IGUIButton *DownButton; + s32 TabMaxWidth; + s32 CurrentScrollTabIndex; + s32 TabExtraWidth; +}; } // end namespace gui } // end namespace irr diff --git a/source/Irrlicht/CImage.cpp b/source/Irrlicht/CImage.cpp index dee8962d..20959017 100644 --- a/source/Irrlicht/CImage.cpp +++ b/source/Irrlicht/CImage.cpp @@ -15,100 +15,89 @@ namespace video { //! Constructor from raw data -CImage::CImage(ECOLOR_FORMAT format, const core::dimension2d& size, void* data, - bool ownForeignMemory, bool deleteMemory) : IImage(format, size, deleteMemory) +CImage::CImage(ECOLOR_FORMAT format, const core::dimension2d &size, void *data, + bool ownForeignMemory, bool deleteMemory) : + IImage(format, size, deleteMemory) { - if (ownForeignMemory) - { - Data = (u8*)data; - } - else - { + if (ownForeignMemory) { + Data = (u8 *)data; + } else { const u32 dataSize = getDataSizeFromFormat(Format, Size.Width, Size.Height); const u32 allocSize = align_next(dataSize, 16); // allocate as u32 to ensure enough alignment when casted - Data = reinterpret_cast(new u32[allocSize / 4]); + Data = reinterpret_cast(new u32[allocSize / 4]); memcpy(Data, data, dataSize); DeleteMemory = true; } } - //! Constructor of empty image -CImage::CImage(ECOLOR_FORMAT format, const core::dimension2d& size) : IImage(format, size, true) +CImage::CImage(ECOLOR_FORMAT format, const core::dimension2d &size) : + IImage(format, size, true) { const u32 dataSize = getDataSizeFromFormat(Format, Size.Width, Size.Height); const u32 allocSize = align_next(dataSize, 16); - Data = reinterpret_cast(new u32[allocSize / 4]); + Data = reinterpret_cast(new u32[allocSize / 4]); DeleteMemory = true; } - //! sets a pixel void CImage::setPixel(u32 x, u32 y, const SColor &color, bool blend) { if (x >= Size.Width || y >= Size.Height) return; - switch(Format) - { - case ECF_A1R5G5B5: - { - u16 * dest = (u16*) (Data + ( y * Pitch ) + ( x << 1 )); - *dest = video::A8R8G8B8toA1R5G5B5( color.color ); - } break; + switch (Format) { + case ECF_A1R5G5B5: { + u16 *dest = (u16 *)(Data + (y * Pitch) + (x << 1)); + *dest = video::A8R8G8B8toA1R5G5B5(color.color); + } break; - case ECF_R5G6B5: - { - u16 * dest = (u16*) (Data + ( y * Pitch ) + ( x << 1 )); - *dest = video::A8R8G8B8toR5G6B5( color.color ); - } break; + case ECF_R5G6B5: { + u16 *dest = (u16 *)(Data + (y * Pitch) + (x << 1)); + *dest = video::A8R8G8B8toR5G6B5(color.color); + } break; - case ECF_R8G8B8: - { - u8* dest = Data + ( y * Pitch ) + ( x * 3 ); - dest[0] = (u8)color.getRed(); - dest[1] = (u8)color.getGreen(); - dest[2] = (u8)color.getBlue(); - } break; + case ECF_R8G8B8: { + u8 *dest = Data + (y * Pitch) + (x * 3); + dest[0] = (u8)color.getRed(); + dest[1] = (u8)color.getGreen(); + dest[2] = (u8)color.getBlue(); + } break; - case ECF_A8R8G8B8: - { - u32 * dest = (u32*) (Data + ( y * Pitch ) + ( x << 2 )); - *dest = blend ? PixelBlend32 ( *dest, color.color ) : color.color; - } break; + case ECF_A8R8G8B8: { + u32 *dest = (u32 *)(Data + (y * Pitch) + (x << 2)); + *dest = blend ? PixelBlend32(*dest, color.color) : color.color; + } break; - case ECF_UNKNOWN: - os::Printer::log("IImage::setPixel unknown format.", ELL_WARNING); - return; + case ECF_UNKNOWN: + os::Printer::log("IImage::setPixel unknown format.", ELL_WARNING); + return; - default: - break; + default: + break; } } - //! returns a pixel SColor CImage::getPixel(u32 x, u32 y) const { if (x >= Size.Width || y >= Size.Height) return SColor(0); - switch(Format) - { + switch (Format) { case ECF_A1R5G5B5: - return A1R5G5B5toA8R8G8B8(((u16*)Data)[y*Size.Width + x]); + return A1R5G5B5toA8R8G8B8(((u16 *)Data)[y * Size.Width + x]); case ECF_R5G6B5: - return R5G6B5toA8R8G8B8(((u16*)Data)[y*Size.Width + x]); + return R5G6B5toA8R8G8B8(((u16 *)Data)[y * Size.Width + x]); case ECF_A8R8G8B8: - return ((u32*)Data)[y*Size.Width + x]; - case ECF_R8G8B8: - { - u8* p = Data+(y*3)*Size.Width + (x*3); - return SColor(255,p[0],p[1],p[2]); - } + return ((u32 *)Data)[y * Size.Width + x]; + case ECF_R8G8B8: { + u8 *p = Data + (y * 3) * Size.Width + (x * 3); + return SColor(255, p[0], p[1], p[2]); + } case ECF_UNKNOWN: os::Printer::log("IImage::getPixel unknown format.", ELL_WARNING); @@ -121,32 +110,26 @@ SColor CImage::getPixel(u32 x, u32 y) const return SColor(0); } - //! copies this surface into another at given position -void CImage::copyTo(IImage* target, const core::position2d& pos) +void CImage::copyTo(IImage *target, const core::position2d &pos) { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::copyTo method doesn't work with compressed images.", ELL_WARNING); return; } - if (!Blit(BLITTER_TEXTURE, target, 0, &pos, this, 0, 0) - && target && pos.X == 0 && pos.Y == 0 && - CColorConverter::canConvertFormat(Format, target->getColorFormat())) - { + if (!Blit(BLITTER_TEXTURE, target, 0, &pos, this, 0, 0) && target && pos.X == 0 && pos.Y == 0 && + CColorConverter::canConvertFormat(Format, target->getColorFormat())) { // No fast blitting, but copyToScaling uses other color conversions and might work irr::core::dimension2du dim(target->getDimension()); copyToScaling(target->getData(), dim.Width, dim.Height, target->getColorFormat(), target->getPitch()); } } - //! copies this surface partially into another at given position -void CImage::copyTo(IImage* target, const core::position2d& pos, const core::rect& sourceRect, const core::rect* clipRect) +void CImage::copyTo(IImage *target, const core::position2d &pos, const core::rect &sourceRect, const core::rect *clipRect) { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::copyTo method doesn't work with compressed images.", ELL_WARNING); return; } @@ -154,27 +137,23 @@ void CImage::copyTo(IImage* target, const core::position2d& pos, const core Blit(BLITTER_TEXTURE, target, clipRect, &pos, this, &sourceRect, 0); } - //! copies this surface into another, using the alpha mask, a cliprect and a color to add with -void CImage::copyToWithAlpha(IImage* target, const core::position2d& pos, const core::rect& sourceRect, const SColor &color, const core::rect* clipRect, bool combineAlpha) +void CImage::copyToWithAlpha(IImage *target, const core::position2d &pos, const core::rect &sourceRect, const SColor &color, const core::rect *clipRect, bool combineAlpha) { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::copyToWithAlpha method doesn't work with compressed images.", ELL_WARNING); return; } - eBlitter op = combineAlpha ? BLITTER_TEXTURE_COMBINE_ALPHA : - color.color == 0xFFFFFFFF ? BLITTER_TEXTURE_ALPHA_BLEND : BLITTER_TEXTURE_ALPHA_COLOR_BLEND; - Blit(op,target, clipRect, &pos, this, &sourceRect, color.color); + eBlitter op = combineAlpha ? BLITTER_TEXTURE_COMBINE_ALPHA : color.color == 0xFFFFFFFF ? BLITTER_TEXTURE_ALPHA_BLEND + : BLITTER_TEXTURE_ALPHA_COLOR_BLEND; + Blit(op, target, clipRect, &pos, this, &sourceRect, color.color); } - //! copies this surface into another, if it has the exact same size and format. bool CImage::copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format, u32 pitch) const { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::copyToNoScaling method doesn't work with compressed images.", ELL_WARNING); return false; } @@ -182,29 +161,25 @@ bool CImage::copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT if (!target || !width || !height || !Size.Width || !Size.Height) return false; - const u32 bpp=getBitsPerPixelFromFormat(format)/8; - if (0==pitch) - pitch = width*bpp; + const u32 bpp = getBitsPerPixelFromFormat(format) / 8; + if (0 == pitch) + pitch = width * bpp; - if (!(Format==format && Size.Width==width && Size.Height==height)) + if (!(Format == format && Size.Width == width && Size.Height == height)) return false; - if (pitch==Pitch) - { - memcpy(target, Data, (size_t)height*pitch); - } - else - { - u8* tgtpos = (u8*) target; - u8* srcpos = Data; - const u32 bwidth = width*bpp; - const u32 rest = pitch-bwidth; - for (u32 y=0; y 1 ? (f32)(Size.Width-1) / (f32)(width-1) : 0.f; - sourceXStart = 0.5f; // for rounding to nearest pixel + else { + sourceXStep = width > 1 ? (f32)(Size.Width - 1) / (f32)(width - 1) : 0.f; + sourceXStart = 0.5f; // for rounding to nearest pixel } if (height % Size.Height == 0) sourceYStep = (f32)(Size.Height) / (f32)(height); - else - { - sourceYStep = height > 1 ? (f32)(Size.Height-1) / (f32)(height-1) : 0.f; - sourceYStart = 0.5f; // for rounding to nearest pixel + else { + sourceYStep = height > 1 ? (f32)(Size.Height - 1) / (f32)(height - 1) : 0.f; + sourceYStart = 0.5f; // for rounding to nearest pixel } - s32 yval=0, syval=0; + s32 yval = 0, syval = 0; f32 sy = sourceYStart; - for (u32 y=0; y& targetSize = target->getDimension(); + const core::dimension2d &targetSize = target->getDimension(); - if (targetSize==Size) - { + if (targetSize == Size) { copyTo(target); return; } @@ -301,90 +267,78 @@ void CImage::copyToScaling(IImage* target) copyToScaling(target->getData(), targetSize.Width, targetSize.Height, target->getColorFormat()); } - //! copies this surface into another, scaling it to fit it. -void CImage::copyToScalingBoxFilter(IImage* target, s32 bias, bool blend) +void CImage::copyToScalingBoxFilter(IImage *target, s32 bias, bool blend) { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::copyToScalingBoxFilter method doesn't work with compressed images.", ELL_WARNING); return; } const core::dimension2d destSize = target->getDimension(); - const f32 sourceXStep = (f32) Size.Width / (f32) destSize.Width; - const f32 sourceYStep = (f32) Size.Height / (f32) destSize.Height; + const f32 sourceXStep = (f32)Size.Width / (f32)destSize.Width; + const f32 sourceYStep = (f32)Size.Height / (f32)destSize.Height; - s32 fx = core::ceil32( sourceXStep ); - s32 fy = core::ceil32( sourceYStep ); + s32 fx = core::ceil32(sourceXStep); + s32 fy = core::ceil32(sourceYStep); f32 sx; f32 sy; sy = 0.f; - for ( u32 y = 0; y != destSize.Height; ++y ) - { + for (u32 y = 0; y != destSize.Height; ++y) { sx = 0.f; - for ( u32 x = 0; x != destSize.Width; ++x ) - { - target->setPixel( x, y, - getPixelBox( core::floor32(sx), core::floor32(sy), fx, fy, bias ), blend ); + for (u32 x = 0; x != destSize.Width; ++x) { + target->setPixel(x, y, + getPixelBox(core::floor32(sx), core::floor32(sy), fx, fy, bias), blend); sx += sourceXStep; } sy += sourceYStep; } } - //! fills the surface with given color void CImage::fill(const SColor &color) { - if (IImage::isCompressedFormat(Format)) - { + if (IImage::isCompressedFormat(Format)) { os::Printer::log("IImage::fill method doesn't work with compressed images.", ELL_WARNING); return; } u32 c; - switch ( Format ) - { - case ECF_A1R5G5B5: - c = color.toA1R5G5B5(); - c |= c << 16; - break; - case ECF_R5G6B5: - c = video::A8R8G8B8toR5G6B5( color.color ); - c |= c << 16; - break; - case ECF_A8R8G8B8: - c = color.color; - break; - case ECF_R8G8B8: - { - u8 rgb[3]; - CColorConverter::convert_A8R8G8B8toR8G8B8(&color, 1, rgb); - const u32 size = getImageDataSizeInBytes(); - for (u32 i=0; i> sdiv ) + bias, 0, 255 ); - r = core::s32_clamp( ( r >> sdiv ) + bias, 0, 255 ); - g = core::s32_clamp( ( g >> sdiv ) + bias, 0, 255 ); - b = core::s32_clamp( ( b >> sdiv ) + bias, 0, 255 ); + a = core::s32_clamp((a >> sdiv) + bias, 0, 255); + r = core::s32_clamp((r >> sdiv) + bias, 0, 255); + g = core::s32_clamp((g >> sdiv) + bias, 0, 255); + b = core::s32_clamp((b >> sdiv) + bias, 0, 255); - c.set( a, r, g, b ); + c.set(a, r, g, b); return c; } - - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImage.h b/source/Irrlicht/CImage.h index 29cda2cd..955f8570 100644 --- a/source/Irrlicht/CImage.h +++ b/source/Irrlicht/CImage.h @@ -24,51 +24,50 @@ inline bool checkImageDimensions(u32 width, u32 height) class CImage : public IImage { public: - //! constructor from raw image data /** \param useForeignMemory: If true, the image will use the data pointer directly and own it from now on, which means it will also try to delete [] the data when the image will be destructed. If false, the memory will by copied. */ - CImage(ECOLOR_FORMAT format, const core::dimension2d& size, void* data, - bool ownForeignMemory = true, bool deleteMemory = true); + CImage(ECOLOR_FORMAT format, const core::dimension2d &size, void *data, + bool ownForeignMemory = true, bool deleteMemory = true); //! constructor for empty image - CImage(ECOLOR_FORMAT format, const core::dimension2d& size); + CImage(ECOLOR_FORMAT format, const core::dimension2d &size); //! returns a pixel SColor getPixel(u32 x, u32 y) const override; //! sets a pixel - void setPixel(u32 x, u32 y, const SColor &color, bool blend = false ) override; + void setPixel(u32 x, u32 y, const SColor &color, bool blend = false) override; //! copies this surface into another, if it has the exact same size and format. - bool copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format, u32 pitch=0) const override; + bool copyToNoScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format, u32 pitch = 0) const override; //! copies this surface into another, scaling it to fit. - void copyToScaling(void* target, u32 width, u32 height, ECOLOR_FORMAT format, u32 pitch=0) override; + void copyToScaling(void *target, u32 width, u32 height, ECOLOR_FORMAT format, u32 pitch = 0) override; //! copies this surface into another, scaling it to fit. - void copyToScaling(IImage* target) override; + void copyToScaling(IImage *target) override; //! copies this surface into another - void copyTo(IImage* target, const core::position2d& pos=core::position2d(0,0)) override; + void copyTo(IImage *target, const core::position2d &pos = core::position2d(0, 0)) override; //! copies this surface into another - void copyTo(IImage* target, const core::position2d& pos, const core::rect& sourceRect, const core::rect* clipRect=0) override; + void copyTo(IImage *target, const core::position2d &pos, const core::rect &sourceRect, const core::rect *clipRect = 0) override; //! copies this surface into another, using the alpha mask, an cliprect and a color to add with - virtual void copyToWithAlpha(IImage* target, const core::position2d& pos, - const core::rect& sourceRect, const SColor &color, - const core::rect* clipRect = 0, bool combineAlpha=false) override; + virtual void copyToWithAlpha(IImage *target, const core::position2d &pos, + const core::rect &sourceRect, const SColor &color, + const core::rect *clipRect = 0, bool combineAlpha = false) override; //! copies this surface into another, scaling it to fit, applying a box filter - void copyToScalingBoxFilter(IImage* target, s32 bias = 0, bool blend = false) override; + void copyToScalingBoxFilter(IImage *target, s32 bias = 0, bool blend = false) override; //! fills the surface with given color void fill(const SColor &color) override; private: - inline SColor getPixelBox ( s32 x, s32 y, s32 fx, s32 fy, s32 bias ) const; + inline SColor getPixelBox(s32 x, s32 y, s32 fx, s32 fy, s32 bias) const; }; } // end namespace video diff --git a/source/Irrlicht/CImageLoaderBMP.cpp b/source/Irrlicht/CImageLoaderBMP.cpp index 91ac0111..f278a8cf 100644 --- a/source/Irrlicht/CImageLoaderBMP.cpp +++ b/source/Irrlicht/CImageLoaderBMP.cpp @@ -16,26 +16,23 @@ namespace irr namespace video { - //! constructor CImageLoaderBMP::CImageLoaderBMP() { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CImageLoaderBMP"); - #endif +#endif } - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") -bool CImageLoaderBMP::isALoadableFileExtension(const io::path& filename) const +bool CImageLoaderBMP::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "bmp" ); + return core::hasFileExtension(filename, "bmp"); } - //! returns true if the file maybe is able to be loaded by this class -bool CImageLoaderBMP::isALoadableFileFormat(io::IReadFile* file) const +bool CImageLoaderBMP::isALoadableFileFormat(io::IReadFile *file) const { u16 headerID; file->read(&headerID, sizeof(u16)); @@ -49,71 +46,75 @@ bool CImageLoaderBMP::isALoadableFileFormat(io::IReadFile* file) const static inline bool overflowCheck(const void *base, size_t offset, const void *end) { auto baseI = reinterpret_cast(base), - endI = reinterpret_cast(end); + endI = reinterpret_cast(end); return baseI > endI || offset >= (endI - baseI); } // check whether &p[0] to &p[_off - 1] can be accessed -#define CHECKP(_off) if ((_off) < 0 || overflowCheck(p, _off, pEnd)) goto exit +#define CHECKP(_off) \ + if ((_off) < 0 || overflowCheck(p, _off, pEnd)) \ + goto exit // same for d -#define CHECKD(_off) if ((_off) < 0 || overflowCheck(d, _off, destEnd)) goto exit +#define CHECKD(_off) \ + if ((_off) < 0 || overflowCheck(d, _off, destEnd)) \ + goto exit -void CImageLoaderBMP::decompress8BitRLE(u8*& bmpData, s32 size, s32 width, s32 height, s32 pitch) const +void CImageLoaderBMP::decompress8BitRLE(u8 *&bmpData, s32 size, s32 width, s32 height, s32 pitch) const { - u8* p = bmpData; - const u8* pEnd = bmpData + size; - u8* newBmp = new u8[(width+pitch)*height]; - u8* d = newBmp; - const u8* destEnd = newBmp + (width+pitch)*height; + u8 *p = bmpData; + const u8 *pEnd = bmpData + size; + u8 *newBmp = new u8[(width + pitch) * height]; + u8 *d = newBmp; + const u8 *destEnd = newBmp + (width + pitch) * height; s32 line = 0; - while (p < pEnd && d < destEnd) - { - if (*p == 0) - { - ++p; CHECKP(1); + while (p < pEnd && d < destEnd) { + if (*p == 0) { + ++p; + CHECKP(1); - switch(*p) - { + switch (*p) { case 0: // end of line ++p; ++line; - d = newBmp + (line*(width+pitch)); + d = newBmp + (line * (width + pitch)); break; case 1: // end of bmp goto exit; case 2: - ++p; CHECKP(2); - d += (u8)*p; ++p; // delta - d += ((u8)*p)*(width+pitch); ++p; + ++p; + CHECKP(2); + d += (u8)*p; + ++p; // delta + d += ((u8)*p) * (width + pitch); + ++p; break; - default: - { - // absolute mode - s32 count = (u8)*p; ++p; - s32 readAdditional = ((2-(count%2))%2); + default: { + // absolute mode + s32 count = (u8)*p; + ++p; + s32 readAdditional = ((2 - (count % 2)) % 2); - CHECKP(count); CHECKD(count); - for (s32 i=0; i> readShift) & 0x0f; - readShift -= 4; - if (readShift < 0) - { - ++*p; // <- bug? - readShift = 4; - } - - u8 mask = 0x0f << shift; - *d = (*d & (~mask)) | ((color << shift) & mask); - - shift -= 4; - if (shift < 0) - { - shift = 4; - ++d; - } + case 2: { + ++p; + CHECKP(2); + s32 x = (u8)*p; + ++p; + s32 y = (u8)*p; + ++p; + d += x / 2 + y * lineWidth; + shift = x % 2 == 0 ? 4 : 0; + } break; + default: { + // absolute mode + s32 count = (u8)*p; + ++p; + s32 readAdditional = ((2 - ((count) % 2)) % 2); + s32 readShift = 4; + CHECKP(shiftedCount(count, readShift)); + CHECKD(shiftedCount(count, shift)); + for (s32 i = 0; i < count; ++i) { + s32 color = (((u8)*p) >> readShift) & 0x0f; + readShift -= 4; + if (readShift < 0) { + ++*p; // <- bug? + readShift = 4; } - CHECKP(readAdditional); - for (s32 i=0; i> 4) & 0x0f; + s32 color1 = (u8)*p; + color1 = color1 & 0x0f; + s32 color2 = (u8)*p; + color2 = (color2 >> 4) & 0x0f; ++p; CHECKD(shiftedCount(count, shift)); - for (s32 i=0; i 32 || !checkImageDimensions(header.Width, header.Height)) - { + if (header.BPP > 32 || !checkImageDimensions(header.Width, header.Height)) { os::Printer::log("Rejecting BMP with unreasonable size or BPP.", ELL_ERROR); return 0; } // adjust bitmap data size to dword boundary - header.BitmapDataSize += (4-(header.BitmapDataSize%4))%4; + header.BitmapDataSize += (4 - (header.BitmapDataSize % 4)) % 4; // read palette @@ -295,23 +289,21 @@ IImage* CImageLoaderBMP::loadImage(io::IReadFile* file) const s32 paletteSize = (header.BitmapDataOffset - pos) / 4; paletteSize = core::clamp(paletteSize, 0, paletteAllocSize); - s32* paletteData = 0; - if (paletteSize) - { + s32 *paletteData = 0; + if (paletteSize) { // always allocate an 8-bit palette to ensure enough space paletteData = new s32[paletteAllocSize]; memset(paletteData, 0, paletteAllocSize * sizeof(s32)); file->read(paletteData, paletteSize * sizeof(s32)); #ifdef __BIG_ENDIAN__ - for (s32 i=0; i(file->getSize()) - header.BitmapDataOffset; @@ -324,35 +316,33 @@ IImage* CImageLoaderBMP::loadImage(io::IReadFile* file) const f32 t = (header.Width) * (header.BPP / 8.0f); widthInBytes = (s32)t; t -= widthInBytes; - if (t!=0.0f) + if (t != 0.0f) ++widthInBytes; } - const s32 lineSize = widthInBytes + ((4-(widthInBytes%4)))%4; + const s32 lineSize = widthInBytes + ((4 - (widthInBytes % 4))) % 4; pitch = lineSize - widthInBytes; - u8* bmpData = new u8[header.BitmapDataSize]; + u8 *bmpData = new u8[header.BitmapDataSize]; file->read(bmpData, header.BitmapDataSize); // decompress data if needed - switch(header.Compression) - { + switch (header.Compression) { case 1: // 8 bit rle decompress8BitRLE(bmpData, header.BitmapDataSize, header.Width, header.Height, pitch); header.BitmapDataSize = (header.Width + pitch) * header.Height; break; case 2: // 4 bit rle decompress4BitRLE(bmpData, header.BitmapDataSize, header.Width, header.Height, pitch); - header.BitmapDataSize = ((header.Width+1)/2 + pitch) * header.Height; + header.BitmapDataSize = ((header.Width + 1) / 2 + pitch) * header.Height; break; } - if (header.BitmapDataSize < lineSize * header.Height) - { + if (header.BitmapDataSize < lineSize * header.Height) { os::Printer::log("Bitmap data is cut off.", ELL_ERROR); - delete [] paletteData; - delete [] bmpData; + delete[] paletteData; + delete[] bmpData; return 0; } @@ -361,56 +351,53 @@ IImage* CImageLoaderBMP::loadImage(io::IReadFile* file) const dim.Width = header.Width; dim.Height = header.Height; - IImage* image = 0; - switch(header.BPP) - { + IImage *image = 0; + switch (header.BPP) { case 1: image = new CImage(ECF_A1R5G5B5, dim); if (image) - CColorConverter::convert1BitTo16Bit(bmpData, (s16*)image->getData(), header.Width, header.Height, pitch, true); + CColorConverter::convert1BitTo16Bit(bmpData, (s16 *)image->getData(), header.Width, header.Height, pitch, true); break; case 4: image = new CImage(ECF_A1R5G5B5, dim); if (image) - CColorConverter::convert4BitTo16Bit(bmpData, (s16*)image->getData(), header.Width, header.Height, paletteData, pitch, true); + CColorConverter::convert4BitTo16Bit(bmpData, (s16 *)image->getData(), header.Width, header.Height, paletteData, pitch, true); break; case 8: image = new CImage(ECF_A1R5G5B5, dim); if (image) - CColorConverter::convert8BitTo16Bit(bmpData, (s16*)image->getData(), header.Width, header.Height, paletteData, pitch, true); + CColorConverter::convert8BitTo16Bit(bmpData, (s16 *)image->getData(), header.Width, header.Height, paletteData, pitch, true); break; case 16: image = new CImage(ECF_A1R5G5B5, dim); if (image) - CColorConverter::convert16BitTo16Bit((s16*)bmpData, (s16*)image->getData(), header.Width, header.Height, pitch, true); + CColorConverter::convert16BitTo16Bit((s16 *)bmpData, (s16 *)image->getData(), header.Width, header.Height, pitch, true); break; case 24: image = new CImage(ECF_R8G8B8, dim); if (image) - CColorConverter::convert24BitTo24Bit(bmpData, (u8*)image->getData(), header.Width, header.Height, pitch, true, true); + CColorConverter::convert24BitTo24Bit(bmpData, (u8 *)image->getData(), header.Width, header.Height, pitch, true, true); break; case 32: // thx to Reinhard Ostermeier image = new CImage(ECF_A8R8G8B8, dim); if (image) - CColorConverter::convert32BitTo32Bit((s32*)bmpData, (s32*)image->getData(), header.Width, header.Height, pitch, true); + CColorConverter::convert32BitTo32Bit((s32 *)bmpData, (s32 *)image->getData(), header.Width, header.Height, pitch, true); break; }; // clean up - delete [] paletteData; - delete [] bmpData; + delete[] paletteData; + delete[] bmpData; return image; } - //! creates a loader which is able to load windows bitmaps -IImageLoader* createImageLoaderBMP() +IImageLoader *createImageLoaderBMP() { return new CImageLoaderBMP; } - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImageLoaderBMP.h b/source/Irrlicht/CImageLoaderBMP.h index beb6c7ba..e7ef8ed2 100644 --- a/source/Irrlicht/CImageLoaderBMP.h +++ b/source/Irrlicht/CImageLoaderBMP.h @@ -6,7 +6,6 @@ #include "IImageLoader.h" - namespace irr { namespace video @@ -15,40 +14,40 @@ namespace video // byte-align structures #include "irrpack.h" - struct SBMPHeader - { - u16 Id; // BM - Windows 3.1x, 95, NT, 98, 2000, ME, XP - // BA - OS/2 Bitmap Array - // CI - OS/2 Color Icon - // CP - OS/2 Color Pointer - // IC - OS/2 Icon - // PT - OS/2 Pointer - u32 FileSize; - u32 Reserved; - u32 BitmapDataOffset; - u32 BitmapHeaderSize; // should be 28h for windows bitmaps or - // 0Ch for OS/2 1.x or F0h for OS/2 2.x - u32 Width; - u32 Height; - u16 Planes; - u16 BPP; // 1: Monochrome bitmap - // 4: 16 color bitmap - // 8: 256 color bitmap - // 16: 16bit (high color) bitmap - // 24: 24bit (true color) bitmap - // 32: 32bit (true color) bitmap +struct SBMPHeader +{ + u16 Id; // BM - Windows 3.1x, 95, NT, 98, 2000, ME, XP + // BA - OS/2 Bitmap Array + // CI - OS/2 Color Icon + // CP - OS/2 Color Pointer + // IC - OS/2 Icon + // PT - OS/2 Pointer + u32 FileSize; + u32 Reserved; + u32 BitmapDataOffset; + u32 BitmapHeaderSize; // should be 28h for windows bitmaps or + // 0Ch for OS/2 1.x or F0h for OS/2 2.x + u32 Width; + u32 Height; + u16 Planes; + u16 BPP; // 1: Monochrome bitmap + // 4: 16 color bitmap + // 8: 256 color bitmap + // 16: 16bit (high color) bitmap + // 24: 24bit (true color) bitmap + // 32: 32bit (true color) bitmap - u32 Compression; // 0: none (Also identified by BI_RGB) - // 1: RLE 8-bit / pixel (Also identified by BI_RLE4) - // 2: RLE 4-bit / pixel (Also identified by BI_RLE8) - // 3: Bitfields (Also identified by BI_BITFIELDS) + u32 Compression; // 0: none (Also identified by BI_RGB) + // 1: RLE 8-bit / pixel (Also identified by BI_RLE4) + // 2: RLE 4-bit / pixel (Also identified by BI_RLE8) + // 3: Bitfields (Also identified by BI_BITFIELDS) - u32 BitmapDataSize; // Size of the bitmap data in bytes. This number must be rounded to the next 4 byte boundary. - u32 PixelPerMeterX; - u32 PixelPerMeterY; - u32 Colors; - u32 ImportantColors; - } PACK_STRUCT; + u32 BitmapDataSize; // Size of the bitmap data in bytes. This number must be rounded to the next 4 byte boundary. + u32 PixelPerMeterX; + u32 PixelPerMeterY; + u32 Colors; + u32 ImportantColors; +} PACK_STRUCT; // Default alignment #include "irrunpack.h" @@ -59,27 +58,24 @@ namespace video class CImageLoaderBMP : public IImageLoader { public: - //! constructor CImageLoaderBMP(); //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! returns true if the file maybe is able to be loaded by this class - bool isALoadableFileFormat(io::IReadFile* file) const override; + bool isALoadableFileFormat(io::IReadFile *file) const override; //! creates a surface from the file - IImage* loadImage(io::IReadFile* file) const override; + IImage *loadImage(io::IReadFile *file) const override; private: + void decompress8BitRLE(u8 *&BmpData, s32 size, s32 width, s32 height, s32 pitch) const; - void decompress8BitRLE(u8*& BmpData, s32 size, s32 width, s32 height, s32 pitch) const; - - void decompress4BitRLE(u8*& BmpData, s32 size, s32 width, s32 height, s32 pitch) const; + void decompress4BitRLE(u8 *&BmpData, s32 size, s32 width, s32 height, s32 pitch) const; }; - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImageLoaderJPG.cpp b/source/Irrlicht/CImageLoaderJPG.cpp index 93b8de5f..e64c458e 100644 --- a/source/Irrlicht/CImageLoaderJPG.cpp +++ b/source/Irrlicht/CImageLoaderJPG.cpp @@ -17,25 +17,21 @@ namespace video //! constructor CImageLoaderJPG::CImageLoaderJPG() { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CImageLoaderJPG"); - #endif +#endif } - - //! destructor CImageLoaderJPG::~CImageLoaderJPG() { } - - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") -bool CImageLoaderJPG::isALoadableFileExtension(const io::path& filename) const +bool CImageLoaderJPG::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "jpg", "jpeg" ); + return core::hasFileExtension(filename, "jpg", "jpeg"); } // struct for handling jpeg errors @@ -48,58 +44,49 @@ struct irr_jpeg_error_mgr jmp_buf setjmp_buffer; // for having access to the filename when printing the error messages - core::stringc* filename; + core::stringc *filename; }; -void CImageLoaderJPG::init_source (j_decompress_ptr cinfo) +void CImageLoaderJPG::init_source(j_decompress_ptr cinfo) { // DO NOTHING } - - -boolean CImageLoaderJPG::fill_input_buffer (j_decompress_ptr cinfo) +boolean CImageLoaderJPG::fill_input_buffer(j_decompress_ptr cinfo) { // DO NOTHING return TRUE; } - - -void CImageLoaderJPG::skip_input_data (j_decompress_ptr cinfo, long count) +void CImageLoaderJPG::skip_input_data(j_decompress_ptr cinfo, long count) { - jpeg_source_mgr * src = cinfo->src; - if(count > 0) - { + jpeg_source_mgr *src = cinfo->src; + if (count > 0) { src->bytes_in_buffer -= count; src->next_input_byte += count; } } - - -void CImageLoaderJPG::term_source (j_decompress_ptr cinfo) +void CImageLoaderJPG::term_source(j_decompress_ptr cinfo) { // DO NOTHING } - -void CImageLoaderJPG::error_exit (j_common_ptr cinfo) +void CImageLoaderJPG::error_exit(j_common_ptr cinfo) { // unfortunately we need to use a goto rather than throwing an exception // as gcc crashes under linux crashes when using throw from within // extern c code // Always display the message - (*cinfo->err->output_message) (cinfo); + (*cinfo->err->output_message)(cinfo); // cinfo->err really points to a irr_error_mgr struct - irr_jpeg_error_mgr *myerr = (irr_jpeg_error_mgr*) cinfo->err; + irr_jpeg_error_mgr *myerr = (irr_jpeg_error_mgr *)cinfo->err; longjmp(myerr->setjmp_buffer, 1); } - void CImageLoaderJPG::output_message(j_common_ptr cinfo) { // display the error message. @@ -107,13 +94,13 @@ void CImageLoaderJPG::output_message(j_common_ptr cinfo) (*cinfo->err->format_message)(cinfo, temp1); core::stringc errMsg("JPEG FATAL ERROR in "); - irr_jpeg_error_mgr* myerr = (irr_jpeg_error_mgr*)cinfo->err; + irr_jpeg_error_mgr *myerr = (irr_jpeg_error_mgr *)cinfo->err; errMsg += *myerr->filename; - os::Printer::log(errMsg.c_str(),temp1, ELL_ERROR); + os::Printer::log(errMsg.c_str(), temp1, ELL_ERROR); } //! returns true if the file maybe is able to be loaded by this class -bool CImageLoaderJPG::isALoadableFileFormat(io::IReadFile* file) const +bool CImageLoaderJPG::isALoadableFileFormat(io::IReadFile *file) const { if (!(file && file->seek(0))) return false; @@ -123,25 +110,25 @@ bool CImageLoaderJPG::isALoadableFileFormat(io::IReadFile* file) const } //! creates a surface from the file -IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const +IImage *CImageLoaderJPG::loadImage(io::IReadFile *file) const { if (!file) return 0; core::stringc filename = file->getFileName(); - u8 **rowPtr=0; - u8* input = new u8[file->getSize()]; + u8 **rowPtr = 0; + u8 *input = new u8[file->getSize()]; file->read(input, file->getSize()); // allocate and initialize JPEG decompression object struct jpeg_decompress_struct cinfo; struct irr_jpeg_error_mgr jerr; - //We have to set up the error handler first, in case the initialization - //step fails. (Unlikely, but it could happen if you are out of memory.) - //This routine fills in the contents of struct jerr, and returns jerr's - //address which we place into the link field in cinfo. + // We have to set up the error handler first, in case the initialization + // step fails. (Unlikely, but it could happen if you are out of memory.) + // This routine fills in the contents of struct jerr, and returns jerr's + // address which we place into the link field in cinfo. cinfo.err = jpeg_std_error(&jerr.pub); cinfo.err->error_exit = error_exit; @@ -151,15 +138,14 @@ IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const // compatibility fudge: // we need to use setjmp/longjmp for error handling as gcc-linux // crashes when throwing within external c code - if (setjmp(jerr.setjmp_buffer)) - { + if (setjmp(jerr.setjmp_buffer)) { // If we get here, the JPEG code has signaled an error. // We need to clean up the JPEG object and return. jpeg_destroy_decompress(&cinfo); - delete [] input; - delete [] rowPtr; + delete[] input; + delete[] rowPtr; // return null pointer return 0; @@ -173,7 +159,7 @@ IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const // Set up data pointer jsrc.bytes_in_buffer = file->getSize(); - jsrc.next_input_byte = (JOCTET*)input; + jsrc.next_input_byte = (JOCTET *)input; cinfo.src = &jsrc; jsrc.init_source = init_source; @@ -190,20 +176,17 @@ IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const // read file parameters with jpeg_read_header() jpeg_read_header(&cinfo, TRUE); - bool useCMYK=false; - if (cinfo.jpeg_color_space==JCS_CMYK) - { - cinfo.out_color_space=JCS_CMYK; - cinfo.out_color_components=4; - useCMYK=true; + bool useCMYK = false; + if (cinfo.jpeg_color_space == JCS_CMYK) { + cinfo.out_color_space = JCS_CMYK; + cinfo.out_color_components = 4; + useCMYK = true; + } else { + cinfo.out_color_space = JCS_RGB; + cinfo.out_color_components = 3; } - else - { - cinfo.out_color_space=JCS_RGB; - cinfo.out_color_components=3; - } - cinfo.output_gamma=2.2; - cinfo.do_fancy_upsampling=FALSE; + cinfo.output_gamma = 2.2; + cinfo.do_fancy_upsampling = FALSE; // reject unreasonable sizes if (!checkImageDimensions(cinfo.image_width, cinfo.image_height)) @@ -218,22 +201,22 @@ IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const u32 height = cinfo.image_height; // Allocate memory for buffer - u8* output = new u8[rowspan * height]; + u8 *output = new u8[rowspan * height]; // Here we use the library's state variable cinfo.output_scanline as the // loop counter, so that we don't have to keep track ourselves. // Create array of row pointers for lib - rowPtr = new u8* [height]; + rowPtr = new u8 *[height]; - for( u32 i = 0; i < height; i++ ) - rowPtr[i] = &output[ i * rowspan ]; + for (u32 i = 0; i < height; i++) + rowPtr[i] = &output[i * rowspan]; u32 rowsRead = 0; - while( cinfo.output_scanline < cinfo.output_height ) - rowsRead += jpeg_read_scanlines( &cinfo, &rowPtr[rowsRead], cinfo.output_height - rowsRead ); + while (cinfo.output_scanline < cinfo.output_height) + rowsRead += jpeg_read_scanlines(&cinfo, &rowPtr[rowsRead], cinfo.output_height - rowsRead); - delete [] rowPtr; + delete[] rowPtr; // Finish decompression jpeg_finish_decompress(&cinfo); @@ -243,41 +226,35 @@ IImage* CImageLoaderJPG::loadImage(io::IReadFile* file) const jpeg_destroy_decompress(&cinfo); // convert image - IImage* image = 0; - if (useCMYK) - { + IImage *image = 0; + if (useCMYK) { image = new CImage(ECF_R8G8B8, core::dimension2d(width, height)); - const u32 size = 3*width*height; - u8* data = (u8*)image->getData(); - if (data) - { - for (u32 i=0,j=0; igetData(); + if (data) { + for (u32 i = 0, j = 0; i < size; i += 3, j += 4) { // Also works without K, but has more contrast with K multiplied in -// data[i+0] = output[j+2]; -// data[i+1] = output[j+1]; -// data[i+2] = output[j+0]; - data[i+0] = (char)(output[j+2]*(output[j+3]/255.f)); - data[i+1] = (char)(output[j+1]*(output[j+3]/255.f)); - data[i+2] = (char)(output[j+0]*(output[j+3]/255.f)); + // data[i+0] = output[j+2]; + // data[i+1] = output[j+1]; + // data[i+2] = output[j+0]; + data[i + 0] = (char)(output[j + 2] * (output[j + 3] / 255.f)); + data[i + 1] = (char)(output[j + 1] * (output[j + 3] / 255.f)); + data[i + 2] = (char)(output[j + 0] * (output[j + 3] / 255.f)); } } - delete [] output; - } - else + delete[] output; + } else image = new CImage(ECF_R8G8B8, core::dimension2d(width, height), output); - delete [] input; + delete[] input; return image; } - - //! creates a loader which is able to load jpeg images -IImageLoader* createImageLoaderJPG() +IImageLoader *createImageLoaderJPG() { return new CImageLoaderJPG(); } diff --git a/source/Irrlicht/CImageLoaderJPG.h b/source/Irrlicht/CImageLoaderJPG.h index ab2f8191..4d804de9 100644 --- a/source/Irrlicht/CImageLoaderJPG.h +++ b/source/Irrlicht/CImageLoaderJPG.h @@ -6,22 +6,19 @@ #include "IImageLoader.h" -#include // required for jpeglib.h +#include // required for jpeglib.h #include // use system lib #include - namespace irr { namespace video { - //! Surface Loader for JPG images class CImageLoaderJPG : public IImageLoader { public: - //! constructor CImageLoaderJPG(); @@ -30,13 +27,13 @@ public: //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! returns true if the file maybe is able to be loaded by this class - bool isALoadableFileFormat(io::IReadFile* file) const override; + bool isALoadableFileFormat(io::IReadFile *file) const override; //! creates a surface from the file - IImage* loadImage(io::IReadFile* file) const override; + IImage *loadImage(io::IReadFile *file) const override; private: // several methods used via function pointers by jpeglib @@ -49,7 +46,7 @@ private: default behavior. Note that if you continue processing, you should clean up the JPEG object with jpeg_abort() or jpeg_destroy(). */ - static void error_exit (j_common_ptr cinfo); + static void error_exit(j_common_ptr cinfo); /* output error messages via Irrlicht logger. */ static void output_message(j_common_ptr cinfo); @@ -58,7 +55,7 @@ private: data is actually read. Unlike init_destination(), it may leave bytes_in_buffer set to 0 (in which case a fill_input_buffer() call will occur immediately). */ - static void init_source (j_decompress_ptr cinfo); + static void init_source(j_decompress_ptr cinfo); /* This is called whenever bytes_in_buffer has reached zero and more data is wanted. In typical applications, it should read fresh data @@ -69,7 +66,7 @@ private: least one more byte. bytes_in_buffer MUST be set to a positive value if TRUE is returned. A FALSE return should only be used when I/O suspension is desired (this mode is discussed in the next section). */ - static boolean fill_input_buffer (j_decompress_ptr cinfo); + static boolean fill_input_buffer(j_decompress_ptr cinfo); /* Skip num_bytes worth of data. The buffer pointer and count should be advanced over num_bytes input bytes, refilling the buffer as @@ -79,13 +76,12 @@ private: but it's not clear that being smart is worth much trouble; large skips are uncommon. bytes_in_buffer may be zero on return. A zero or negative skip count should be treated as a no-op. */ - static void skip_input_data (j_decompress_ptr cinfo, long num_bytes); + static void skip_input_data(j_decompress_ptr cinfo, long num_bytes); /* Terminate source --- called by jpeg_finish_decompress() after all data has been read. Often a no-op. */ - static void term_source (j_decompress_ptr cinfo); + static void term_source(j_decompress_ptr cinfo); }; - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImageLoaderPNG.cpp b/source/Irrlicht/CImageLoaderPNG.cpp index 3a61e257..42cfc51d 100644 --- a/source/Irrlicht/CImageLoaderPNG.cpp +++ b/source/Irrlicht/CImageLoaderPNG.cpp @@ -34,25 +34,23 @@ void PNGAPI user_read_data_fcn(png_structp png_ptr, png_bytep data, png_size_t l png_size_t check; // changed by zola { - io::IReadFile* file=(io::IReadFile*)png_get_io_ptr(png_ptr); - check=(png_size_t) file->read((void*)data, length); + io::IReadFile *file = (io::IReadFile *)png_get_io_ptr(png_ptr); + check = (png_size_t)file->read((void *)data, length); // } if (check != length) png_error(png_ptr, "Read Error"); } - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") -bool CImageLoaderPng::isALoadableFileExtension(const io::path& filename) const +bool CImageLoaderPng::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "png" ); + return core::hasFileExtension(filename, "png"); } - //! returns true if the file maybe is able to be loaded by this class -bool CImageLoaderPng::isALoadableFileFormat(io::IReadFile* file) const +bool CImageLoaderPng::isALoadableFileFormat(io::IReadFile *file) const { if (!file) return false; @@ -66,54 +64,48 @@ bool CImageLoaderPng::isALoadableFileFormat(io::IReadFile* file) const return !png_sig_cmp(buffer, 0, 8); } - // load in the image data -IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const +IImage *CImageLoaderPng::loadImage(io::IReadFile *file) const { if (!file) return 0; - //Used to point to image rows - u8** RowPointers = 0; + // Used to point to image rows + u8 **RowPointers = 0; png_byte buffer[8]; // Read the first few bytes of the PNG file - if( file->read(buffer, 8) != 8 ) - { + if (file->read(buffer, 8) != 8) { os::Printer::log("LOAD PNG: can't read file (filesize < 8)", file->getFileName(), ELL_ERROR); return 0; } // Check if it really is a PNG file - if( png_sig_cmp(buffer, 0, 8) ) - { + if (png_sig_cmp(buffer, 0, 8)) { os::Printer::log("LOAD PNG: not really a png (wrong signature)", file->getFileName(), ELL_ERROR); return 0; } // Allocate the png read struct png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, - NULL, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warn); - if (!png_ptr) - { + NULL, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warn); + if (!png_ptr) { os::Printer::log("LOAD PNG: Internal PNG create read struct failure", file->getFileName(), ELL_ERROR); return 0; } // Allocate the png info struct png_infop info_ptr = png_create_info_struct(png_ptr); - if (!info_ptr) - { + if (!info_ptr) { os::Printer::log("LOAD PNG: Internal PNG create info struct failure", file->getFileName(), ELL_ERROR); png_destroy_read_struct(&png_ptr, NULL, NULL); return 0; } // for proper error handling - if (setjmp(png_jmpbuf(png_ptr))) - { + if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); - delete [] RowPointers; + delete[] RowPointers; return 0; } @@ -130,26 +122,25 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const s32 ColorType; { // Use temporary variables to avoid passing cast pointers - png_uint_32 w,h; + png_uint_32 w, h; // Extract info png_get_IHDR(png_ptr, info_ptr, - &w, &h, - &BitDepth, &ColorType, NULL, NULL, NULL); - Width=w; - Height=h; + &w, &h, + &BitDepth, &ColorType, NULL, NULL, NULL); + Width = w; + Height = h; } if (!checkImageDimensions(Width, Height)) png_cpexcept_error(png_ptr, "Unreasonable size"); // Convert palette color to true color - if (ColorType==PNG_COLOR_TYPE_PALETTE) + if (ColorType == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); // Convert low bit colors to 8 bit colors - if (BitDepth < 8) - { - if (ColorType==PNG_COLOR_TYPE_GRAY || ColorType==PNG_COLOR_TYPE_GRAY_ALPHA) + if (BitDepth < 8) { + if (ColorType == PNG_COLOR_TYPE_GRAY || ColorType == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_expand_gray_1_2_4_to_8(png_ptr); else png_set_packing(png_ptr); @@ -163,7 +154,7 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const png_set_strip_16(png_ptr); // Convert gray color to true color - if (ColorType==PNG_COLOR_TYPE_GRAY || ColorType==PNG_COLOR_TYPE_GRAY_ALPHA) + if (ColorType == PNG_COLOR_TYPE_GRAY || ColorType == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); int intent; @@ -171,8 +162,7 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const if (png_get_sRGB(png_ptr, info_ptr, &intent)) png_set_gamma(png_ptr, screen_gamma, 0.45455); - else - { + else { double image_gamma; if (png_get_gAMA(png_ptr, info_ptr, &image_gamma)) png_set_gamma(png_ptr, screen_gamma, image_gamma); @@ -185,18 +175,17 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const png_read_update_info(png_ptr, info_ptr); { // Use temporary variables to avoid passing cast pointers - png_uint_32 w,h; + png_uint_32 w, h; // Extract info png_get_IHDR(png_ptr, info_ptr, - &w, &h, - &BitDepth, &ColorType, NULL, NULL, NULL); - Width=w; - Height=h; + &w, &h, + &BitDepth, &ColorType, NULL, NULL, NULL); + Width = w; + Height = h; } // Convert RGBA to BGRA - if (ColorType==PNG_COLOR_TYPE_RGB_ALPHA) - { + if (ColorType == PNG_COLOR_TYPE_RGB_ALPHA) { #ifdef __BIG_ENDIAN__ png_set_swap_alpha(png_ptr); #else @@ -205,13 +194,12 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const } // Create the image structure to be filled by png data - video::IImage* image = 0; - if (ColorType==PNG_COLOR_TYPE_RGB_ALPHA) + video::IImage *image = 0; + if (ColorType == PNG_COLOR_TYPE_RGB_ALPHA) image = new CImage(ECF_A8R8G8B8, core::dimension2d(Width, Height)); else image = new CImage(ECF_R8G8B8, core::dimension2d(Width, Height)); - if (!image) - { + if (!image) { os::Printer::log("LOAD PNG: Internal PNG create image struct failure", file->getFileName(), ELL_ERROR); png_destroy_read_struct(&png_ptr, NULL, NULL); return 0; @@ -219,8 +207,7 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const // Create array of pointers to rows in image data RowPointers = new png_bytep[Height]; - if (!RowPointers) - { + if (!RowPointers) { os::Printer::log("LOAD PNG: Internal PNG create row pointers failure", file->getFileName(), ELL_ERROR); png_destroy_read_struct(&png_ptr, NULL, NULL); delete image; @@ -228,18 +215,16 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const } // Fill array of pointers to rows in image data - unsigned char* data = (unsigned char*)image->getData(); - for (u32 i=0; igetData(); + for (u32 i = 0; i < Height; ++i) { + RowPointers[i] = data; data += image->getPitch(); } // for proper error handling - if (setjmp(png_jmpbuf(png_ptr))) - { + if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); - delete [] RowPointers; + delete[] RowPointers; delete image; return 0; } @@ -248,18 +233,16 @@ IImage* CImageLoaderPng::loadImage(io::IReadFile* file) const png_read_image(png_ptr, RowPointers); png_read_end(png_ptr, NULL); - delete [] RowPointers; - png_destroy_read_struct(&png_ptr,&info_ptr, 0); // Clean up memory + delete[] RowPointers; + png_destroy_read_struct(&png_ptr, &info_ptr, 0); // Clean up memory return image; } - -IImageLoader* createImageLoaderPNG() +IImageLoader *createImageLoaderPNG() { return new CImageLoaderPng(); } - -}// end namespace irr -}//end namespace video +} // end namespace irr +} // end namespace video diff --git a/source/Irrlicht/CImageLoaderPNG.h b/source/Irrlicht/CImageLoaderPNG.h index 20232d84..f878320b 100644 --- a/source/Irrlicht/CImageLoaderPNG.h +++ b/source/Irrlicht/CImageLoaderPNG.h @@ -19,18 +19,16 @@ namespace video class CImageLoaderPng : public IImageLoader { public: - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".png") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! returns true if the file maybe is able to be loaded by this class - bool isALoadableFileFormat(io::IReadFile* file) const override; + bool isALoadableFileFormat(io::IReadFile *file) const override; //! creates a surface from the file - IImage* loadImage(io::IReadFile* file) const override; + IImage *loadImage(io::IReadFile *file) const override; }; - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImageLoaderTGA.cpp b/source/Irrlicht/CImageLoaderTGA.cpp index 9324f3db..4fe3ac1f 100644 --- a/source/Irrlicht/CImageLoaderTGA.cpp +++ b/source/Irrlicht/CImageLoaderTGA.cpp @@ -17,72 +17,58 @@ namespace irr namespace video { - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") -bool CImageLoaderTGA::isALoadableFileExtension(const io::path& filename) const +bool CImageLoaderTGA::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "tga" ); + return core::hasFileExtension(filename, "tga"); } - //! loads a compressed tga. -u8 *CImageLoaderTGA::loadCompressedImage(io::IReadFile *file, const STGAHeader& header) const +u8 *CImageLoaderTGA::loadCompressedImage(io::IReadFile *file, const STGAHeader &header) const { // This was written and sent in by Jon Pry, thank you very much! // I only changed the formatting a little bit. - const u32 bytesPerPixel = header.PixelDepth/8; - const u32 imageSize = header.ImageHeight * header.ImageWidth * bytesPerPixel; - u8* data = new u8[imageSize]; + const u32 bytesPerPixel = header.PixelDepth / 8; + const u32 imageSize = header.ImageHeight * header.ImageWidth * bytesPerPixel; + u8 *data = new u8[imageSize]; u32 currentByte = 0; - while(currentByte < imageSize) - { + while (currentByte < imageSize) { u8 chunkheader = 0; file->read(&chunkheader, sizeof(u8)); // Read The Chunk's Header - if(chunkheader < 128) // If The Chunk Is A 'RAW' Chunk + if (chunkheader < 128) // If The Chunk Is A 'RAW' Chunk { chunkheader++; // Add 1 To The Value To Get Total Number Of Raw Pixels const u32 bytesToRead = bytesPerPixel * chunkheader; - if ( currentByte+bytesToRead <= imageSize ) - { + if (currentByte + bytesToRead <= imageSize) { file->read(&data[currentByte], bytesToRead); currentByte += bytesToRead; - } - else - { + } else { os::Printer::log("Compressed TGA file RAW chunk tries writing beyond buffer", file->getFileName(), ELL_WARNING); break; } - } - else - { + } else { // thnx to neojzs for some fixes with this code // If It's An RLE Header chunkheader -= 127; // Subtract 127 To Get Rid Of The ID Bit u32 dataOffset = currentByte; - if ( dataOffset+bytesPerPixel < imageSize ) - { + if (dataOffset + bytesPerPixel < imageSize) { file->read(&data[dataOffset], bytesPerPixel); currentByte += bytesPerPixel; - } - else - { + } else { os::Printer::log("Compressed TGA file RLE headertries writing beyond buffer", file->getFileName(), ELL_WARNING); break; } - for(u32 counter = 1; counter < chunkheader; counter++) - { - if ( currentByte + bytesPerPixel <= imageSize ) - { - for(u32 elementCounter=0; elementCounter < bytesPerPixel; elementCounter++) - { + for (u32 counter = 1; counter < chunkheader; counter++) { + if (currentByte + bytesPerPixel <= imageSize) { + for (u32 elementCounter = 0; elementCounter < bytesPerPixel; elementCounter++) { data[currentByte + elementCounter] = data[dataOffset + elementCounter]; } } @@ -95,25 +81,21 @@ u8 *CImageLoaderTGA::loadCompressedImage(io::IReadFile *file, const STGAHeader& return data; } - - //! returns true if the file maybe is able to be loaded by this class -bool CImageLoaderTGA::isALoadableFileFormat(io::IReadFile* file) const +bool CImageLoaderTGA::isALoadableFileFormat(io::IReadFile *file) const { if (!file) return false; STGAFooter footer; memset(&footer, 0, sizeof(STGAFooter)); - file->seek(file->getSize()-sizeof(STGAFooter)); + file->seek(file->getSize() - sizeof(STGAFooter)); file->read(&footer, sizeof(STGAFooter)); - return (!strcmp(footer.Signature,"TRUEVISION-XFILE.")); // very old tgas are refused. + return (!strcmp(footer.Signature, "TRUEVISION-XFILE.")); // very old tgas are refused. } - - //! creates a surface from the file -IImage* CImageLoaderTGA::loadImage(io::IReadFile* file) const +IImage *CImageLoaderTGA::loadImage(io::IReadFile *file) const { STGAHeader header; u32 *palette = 0; @@ -126,8 +108,7 @@ IImage* CImageLoaderTGA::loadImage(io::IReadFile* file) const header.ImageHeight = os::Byteswap::byteswap(header.ImageHeight); #endif - if (!checkImageDimensions(header.ImageWidth, header.ImageHeight)) - { + if (!checkImageDimensions(header.ImageWidth, header.ImageHeight)) { os::Printer::log("Image dimensions too large in file", file->getFileName(), ELL_ERROR); return 0; } @@ -136,149 +117,132 @@ IImage* CImageLoaderTGA::loadImage(io::IReadFile* file) const if (header.IdLength) file->seek(header.IdLength, true); - if (header.ColorMapType) - { + if (header.ColorMapType) { // Create 32 bit palette // `core::max_()` is not used here because it takes its inputs as references. Since `header` is packed, use the macro `MAX()` instead: const irr::u16 paletteSize = MAX((u16)256u, header.ColorMapLength); // ColorMapLength can lie, but so far we only use palette for 8-bit, so ensure it has 256 entries palette = new u32[paletteSize]; - if( paletteSize > header.ColorMapLength ) - { + if (paletteSize > header.ColorMapLength) { // To catch images using palette colors with invalid indices - const irr::u32 errorCol = irr::video::SColor(255,255, 0, 205).color; // bright magenta - for ( irr::u16 i = header.ColorMapLength; i< paletteSize; ++i ) + const irr::u32 errorCol = irr::video::SColor(255, 255, 0, 205).color; // bright magenta + for (irr::u16 i = header.ColorMapLength; i < paletteSize; ++i) palette[i] = errorCol; } // read color map - u8 * colorMap = new u8[header.ColorMapEntrySize/8 * header.ColorMapLength]; - file->read(colorMap,header.ColorMapEntrySize/8 * header.ColorMapLength); + u8 *colorMap = new u8[header.ColorMapEntrySize / 8 * header.ColorMapLength]; + file->read(colorMap, header.ColorMapEntrySize / 8 * header.ColorMapLength); // convert to 32-bit palette - switch ( header.ColorMapEntrySize ) - { - case 16: - CColorConverter::convert_A1R5G5B5toA8R8G8B8(colorMap, header.ColorMapLength, palette); - break; - case 24: - CColorConverter::convert_B8G8R8toA8R8G8B8(colorMap, header.ColorMapLength, palette); - break; - case 32: - CColorConverter::convert_B8G8R8A8toA8R8G8B8(colorMap, header.ColorMapLength, palette); - break; + switch (header.ColorMapEntrySize) { + case 16: + CColorConverter::convert_A1R5G5B5toA8R8G8B8(colorMap, header.ColorMapLength, palette); + break; + case 24: + CColorConverter::convert_B8G8R8toA8R8G8B8(colorMap, header.ColorMapLength, palette); + break; + case 32: + CColorConverter::convert_B8G8R8A8toA8R8G8B8(colorMap, header.ColorMapLength, palette); + break; } - delete [] colorMap; + delete[] colorMap; } // read image - u8* data = 0; + u8 *data = 0; - if ( header.ImageType == 1 || // Uncompressed, color-mapped images. + if (header.ImageType == 1 || // Uncompressed, color-mapped images. header.ImageType == 2 || // Uncompressed, RGB images - header.ImageType == 3 // Uncompressed, black and white images - ) - { - const s32 imageSize = header.ImageHeight * header.ImageWidth * (header.PixelDepth/8); + header.ImageType == 3 // Uncompressed, black and white images + ) { + const s32 imageSize = header.ImageHeight * header.ImageWidth * (header.PixelDepth / 8); data = new u8[imageSize]; - file->read(data, imageSize); - } - else - if(header.ImageType == 10) - { + file->read(data, imageSize); + } else if (header.ImageType == 10) { // Runlength encoded RGB images data = loadCompressedImage(file, header); - } - else - { + } else { os::Printer::log("Unsupported TGA file type", file->getFileName(), ELL_ERROR); - delete [] palette; + delete[] palette; return 0; } - IImage* image = 0; + IImage *image = 0; - switch(header.PixelDepth) - { - case 8: + switch (header.PixelDepth) { + case 8: { + if (header.ImageType == 3) // grey image { - if (header.ImageType==3) // grey image - { - image = new CImage(ECF_R8G8B8, + image = new CImage(ECF_R8G8B8, core::dimension2d(header.ImageWidth, header.ImageHeight)); + if (image) + CColorConverter::convert8BitTo24Bit((u8 *)data, + (u8 *)image->getData(), + header.ImageWidth, header.ImageHeight, + 0, 0, (header.ImageDescriptor & 0x20) == 0); + } else { + switch (header.ColorMapEntrySize) { + case 16: + image = new CImage(ECF_A1R5G5B5, core::dimension2d(header.ImageWidth, header.ImageHeight)); if (image) - CColorConverter::convert8BitTo24Bit((u8*)data, - (u8*)image->getData(), - header.ImageWidth,header.ImageHeight, - 0, 0, (header.ImageDescriptor&0x20)==0); - } - else - { - switch ( header.ColorMapEntrySize ) - { - case 16: - image = new CImage(ECF_A1R5G5B5, core::dimension2d(header.ImageWidth, header.ImageHeight)); - if ( image ) - CColorConverter::convert8BitTo16Bit((u8*)data, - (s16*)image->getData(), - header.ImageWidth,header.ImageHeight, - (s32*) palette, 0, - (header.ImageDescriptor&0x20)==0); - break; - // Note: 24 bit with palette would need a 24 bit palette, too lazy doing that now (textures will prefer 32-bit later anyway) - default: - image = new CImage(ECF_A8R8G8B8, core::dimension2d(header.ImageWidth, header.ImageHeight)); - if ( image ) - CColorConverter::convert8BitTo32Bit((u8*)data, - (u8*)image->getData(), - header.ImageWidth,header.ImageHeight, - (u8*) palette, 0, - (header.ImageDescriptor&0x20)==0); - break; - } + CColorConverter::convert8BitTo16Bit((u8 *)data, + (s16 *)image->getData(), + header.ImageWidth, header.ImageHeight, + (s32 *)palette, 0, + (header.ImageDescriptor & 0x20) == 0); + break; + // Note: 24 bit with palette would need a 24 bit palette, too lazy doing that now (textures will prefer 32-bit later anyway) + default: + image = new CImage(ECF_A8R8G8B8, core::dimension2d(header.ImageWidth, header.ImageHeight)); + if (image) + CColorConverter::convert8BitTo32Bit((u8 *)data, + (u8 *)image->getData(), + header.ImageWidth, header.ImageHeight, + (u8 *)palette, 0, + (header.ImageDescriptor & 0x20) == 0); + break; } } - break; + } break; case 16: image = new CImage(ECF_A1R5G5B5, - core::dimension2d(header.ImageWidth, header.ImageHeight)); + core::dimension2d(header.ImageWidth, header.ImageHeight)); if (image) - CColorConverter::convert16BitTo16Bit((s16*)data, - (s16*)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor&0x20)==0); + CColorConverter::convert16BitTo16Bit((s16 *)data, + (s16 *)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor & 0x20) == 0); break; case 24: - image = new CImage(ECF_R8G8B8, + image = new CImage(ECF_R8G8B8, core::dimension2d(header.ImageWidth, header.ImageHeight)); - if (image) - CColorConverter::convert24BitTo24Bit( - (u8*)data, (u8*)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor&0x20)==0, true); + if (image) + CColorConverter::convert24BitTo24Bit( + (u8 *)data, (u8 *)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor & 0x20) == 0, true); break; case 32: - image = new CImage(ECF_A8R8G8B8, + image = new CImage(ECF_A8R8G8B8, core::dimension2d(header.ImageWidth, header.ImageHeight)); - if (image) - CColorConverter::convert32BitTo32Bit((s32*)data, - (s32*)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor&0x20)==0); + if (image) + CColorConverter::convert32BitTo32Bit((s32 *)data, + (s32 *)image->getData(), header.ImageWidth, header.ImageHeight, 0, (header.ImageDescriptor & 0x20) == 0); break; default: os::Printer::log("Unsupported TGA format", file->getFileName(), ELL_ERROR); break; } - delete [] data; - delete [] palette; + delete[] data; + delete[] palette; return image; } - //! creates a loader which is able to load tgas -IImageLoader* createImageLoaderTGA() +IImageLoader *createImageLoaderTGA() { return new CImageLoaderTGA(); } - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CImageLoaderTGA.h b/source/Irrlicht/CImageLoaderTGA.h index 12208225..18930da3 100644 --- a/source/Irrlicht/CImageLoaderTGA.h +++ b/source/Irrlicht/CImageLoaderTGA.h @@ -6,7 +6,6 @@ #include "IImageLoader.h" - namespace irr { namespace video @@ -15,28 +14,29 @@ namespace video // byte-align structures #include "irrpack.h" - // these structs are also used in the TGA writer - struct STGAHeader{ - u8 IdLength; - u8 ColorMapType; - u8 ImageType; - u8 FirstEntryIndex[2]; - u16 ColorMapLength; - u8 ColorMapEntrySize; - u8 XOrigin[2]; - u8 YOrigin[2]; - u16 ImageWidth; - u16 ImageHeight; - u8 PixelDepth; - u8 ImageDescriptor; - } PACK_STRUCT; +// these structs are also used in the TGA writer +struct STGAHeader +{ + u8 IdLength; + u8 ColorMapType; + u8 ImageType; + u8 FirstEntryIndex[2]; + u16 ColorMapLength; + u8 ColorMapEntrySize; + u8 XOrigin[2]; + u8 YOrigin[2]; + u16 ImageWidth; + u16 ImageHeight; + u8 PixelDepth; + u8 ImageDescriptor; +} PACK_STRUCT; - struct STGAFooter - { - u32 ExtensionOffset; - u32 DeveloperOffset; - c8 Signature[18]; - } PACK_STRUCT; +struct STGAFooter +{ + u32 ExtensionOffset; + u32 DeveloperOffset; + c8 Signature[18]; +} PACK_STRUCT; // Default alignment #include "irrunpack.h" @@ -47,21 +47,19 @@ namespace video class CImageLoaderTGA : public IImageLoader { public: - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! returns true if the file maybe is able to be loaded by this class - bool isALoadableFileFormat(io::IReadFile* file) const override; + bool isALoadableFileFormat(io::IReadFile *file) const override; //! creates a surface from the file - IImage* loadImage(io::IReadFile* file) const override; + IImage *loadImage(io::IReadFile *file) const override; private: - //! loads a compressed tga. Was written and sent in by Jon Pry, thank you very much! - u8* loadCompressedImage(io::IReadFile *file, const STGAHeader& header) const; + u8 *loadCompressedImage(io::IReadFile *file, const STGAHeader &header) const; }; } // end namespace video diff --git a/source/Irrlicht/CImageWriterJPG.cpp b/source/Irrlicht/CImageWriterJPG.cpp index 304ee13f..b590613e 100644 --- a/source/Irrlicht/CImageWriterJPG.cpp +++ b/source/Irrlicht/CImageWriterJPG.cpp @@ -11,13 +11,11 @@ #include "os.h" #include // required for jpeglib.h -extern "C" -{ - #include - #include +extern "C" { +#include +#include } - namespace irr { namespace video @@ -27,33 +25,30 @@ namespace video #define OUTPUT_BUF_SIZE 4096 typedef struct { - struct jpeg_destination_mgr pub;/* public fields */ + struct jpeg_destination_mgr pub; /* public fields */ - io::IWriteFile* file; /* target file */ - JOCTET buffer[OUTPUT_BUF_SIZE]; /* image buffer */ + io::IWriteFile *file; /* target file */ + JOCTET buffer[OUTPUT_BUF_SIZE]; /* image buffer */ } mem_destination_mgr; - -typedef mem_destination_mgr * mem_dest_ptr; - +typedef mem_destination_mgr *mem_dest_ptr; // init static void jpeg_init_destination(j_compress_ptr cinfo) { - mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest; + mem_dest_ptr dest = (mem_dest_ptr)cinfo->dest; dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } - // flush to disk and reset buffer static boolean jpeg_empty_output_buffer(j_compress_ptr cinfo) { - mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest; + mem_dest_ptr dest = (mem_dest_ptr)cinfo->dest; // for now just exit upon file error if (dest->file->write(dest->buffer, OUTPUT_BUF_SIZE) != OUTPUT_BUF_SIZE) - ERREXIT (cinfo, JERR_FILE_WRITE); + ERREXIT(cinfo, JERR_FILE_WRITE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; @@ -61,29 +56,25 @@ static boolean jpeg_empty_output_buffer(j_compress_ptr cinfo) return TRUE; } - static void jpeg_term_destination(j_compress_ptr cinfo) { - mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest; + mem_dest_ptr dest = (mem_dest_ptr)cinfo->dest; const size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; // for now just exit upon file error if (dest->file->write(dest->buffer, datacount) != datacount) - ERREXIT (cinfo, JERR_FILE_WRITE); + ERREXIT(cinfo, JERR_FILE_WRITE); } - // set up buffer data -static void jpeg_file_dest(j_compress_ptr cinfo, io::IWriteFile* file) +static void jpeg_file_dest(j_compress_ptr cinfo, io::IWriteFile *file) { - if (cinfo->dest == NULL) - { /* first time for this JPEG object? */ - cinfo->dest = (struct jpeg_destination_mgr *) - (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, - JPOOL_PERMANENT, - sizeof(mem_destination_mgr)); + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, + JPOOL_PERMANENT, + sizeof(mem_destination_mgr)); } - mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest; /* for casting */ + mem_dest_ptr dest = (mem_dest_ptr)cinfo->dest; /* for casting */ /* Initialize method pointers */ dest->pub.init_destination = jpeg_init_destination; @@ -94,33 +85,31 @@ static void jpeg_file_dest(j_compress_ptr cinfo, io::IWriteFile* file) dest->file = file; } - /* write_JPEG_memory: store JPEG compressed image into memory. -*/ -static bool writeJPEGFile(io::IWriteFile* file, IImage* image, u32 quality) + */ +static bool writeJPEGFile(io::IWriteFile *file, IImage *image, u32 quality) { - void (*format)(const void*, s32, void*) = 0; - switch( image->getColorFormat () ) - { - case ECF_R8G8B8: - format = CColorConverter::convert_R8G8B8toR8G8B8; - break; - case ECF_A8R8G8B8: - format = CColorConverter::convert_A8R8G8B8toR8G8B8; - break; - case ECF_A1R5G5B5: - format = CColorConverter::convert_A1R5G5B5toB8G8R8; - break; - case ECF_R5G6B5: - format = CColorConverter::convert_R5G6B5toR8G8B8; - break; - default: - os::Printer::log("writeJPEGFile does not support image format", ColorFormatNames[image->getColorFormat()], ELL_WARNING); - break; + void (*format)(const void *, s32, void *) = 0; + switch (image->getColorFormat()) { + case ECF_R8G8B8: + format = CColorConverter::convert_R8G8B8toR8G8B8; + break; + case ECF_A8R8G8B8: + format = CColorConverter::convert_A8R8G8B8toR8G8B8; + break; + case ECF_A1R5G5B5: + format = CColorConverter::convert_A1R5G5B5toB8G8R8; + break; + case ECF_R5G6B5: + format = CColorConverter::convert_R5G6B5toR8G8B8; + break; + default: + os::Printer::log("writeJPEGFile does not support image format", ColorFormatNames[image->getColorFormat()], ELL_WARNING); + break; } // couldn't find a color converter - if ( 0 == format ) + if (0 == format) return false; const core::dimension2du dim = image->getDimension(); @@ -138,31 +127,29 @@ static bool writeJPEGFile(io::IWriteFile* file, IImage* image, u32 quality) jpeg_set_defaults(&cinfo); - if ( 0 == quality ) + if (0 == quality) quality = 75; jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); - u8 * dest = new u8[dim.Width*3]; + u8 *dest = new u8[dim.Width * 3]; - if (dest) - { + if (dest) { const u32 pitch = image->getPitch(); - JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ + JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ row_pointer[0] = dest; - u8* src = (u8*)image->getData(); + u8 *src = (u8 *)image->getData(); - while (cinfo.next_scanline < cinfo.image_height) - { + while (cinfo.next_scanline < cinfo.image_height) { // convert next line - format( src, dim.Width, dest ); + format(src, dim.Width, dest); src += pitch; jpeg_write_scanlines(&cinfo, row_pointer, 1); } - delete [] dest; + delete[] dest; /* Step 6: Finish compression */ jpeg_finish_compress(&cinfo); @@ -174,18 +161,15 @@ static bool writeJPEGFile(io::IWriteFile* file, IImage* image, u32 quality) return (dest != 0); } - } // namespace video } // namespace irr - - namespace irr { namespace video { -IImageWriter* createImageWriterJPG() +IImageWriter *createImageWriterJPG() { return new CImageWriterJPG; } @@ -197,13 +181,11 @@ CImageWriterJPG::CImageWriterJPG() #endif } - -bool CImageWriterJPG::isAWriteableFileExtension(const io::path& filename) const +bool CImageWriterJPG::isAWriteableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "jpg", "jpeg" ); + return core::hasFileExtension(filename, "jpg", "jpeg"); } - bool CImageWriterJPG::writeImage(io::IWriteFile *file, IImage *image, u32 quality) const { return writeJPEGFile(file, image, quality); diff --git a/source/Irrlicht/CImageWriterJPG.h b/source/Irrlicht/CImageWriterJPG.h index bf917810..1d8dde53 100644 --- a/source/Irrlicht/CImageWriterJPG.h +++ b/source/Irrlicht/CImageWriterJPG.h @@ -18,7 +18,7 @@ public: CImageWriterJPG(); //! return true if this writer can write a file with the given extension - bool isAWriteableFileExtension(const io::path& filename) const override; + bool isAWriteableFileExtension(const io::path &filename) const override; //! write image to file bool writeImage(io::IWriteFile *file, IImage *image, u32 param) const override; diff --git a/source/Irrlicht/CImageWriterPNG.cpp b/source/Irrlicht/CImageWriterPNG.cpp index bb450400..1c8a840c 100644 --- a/source/Irrlicht/CImageWriterPNG.cpp +++ b/source/Irrlicht/CImageWriterPNG.cpp @@ -17,7 +17,7 @@ namespace irr namespace video { -IImageWriter* createImageWriterPNG() +IImageWriter *createImageWriterPNG() { return new CImageWriterPNG; } @@ -40,8 +40,8 @@ void PNGAPI user_write_data_fcn(png_structp png_ptr, png_bytep data, png_size_t { png_size_t check; - io::IWriteFile* file=(io::IWriteFile*)png_get_io_ptr(png_ptr); - check=(png_size_t) file->write((const void*)data, length); + io::IWriteFile *file = (io::IWriteFile *)png_get_io_ptr(png_ptr); + check = (png_size_t)file->write((const void *)data, length); if (check != length) png_error(png_ptr, "Write Error"); @@ -54,37 +54,34 @@ CImageWriterPNG::CImageWriterPNG() #endif } -bool CImageWriterPNG::isAWriteableFileExtension(const io::path& filename) const +bool CImageWriterPNG::isAWriteableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "png" ); + return core::hasFileExtension(filename, "png"); } -bool CImageWriterPNG::writeImage(io::IWriteFile* file, IImage* image,u32 param) const +bool CImageWriterPNG::writeImage(io::IWriteFile *file, IImage *image, u32 param) const { if (!file || !image) return false; // Allocate the png write struct png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, - NULL, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warning); - if (!png_ptr) - { + NULL, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warning); + if (!png_ptr) { os::Printer::log("PNGWriter: Internal PNG create write struct failure", file->getFileName(), ELL_ERROR); return false; } // Allocate the png info struct png_infop info_ptr = png_create_info_struct(png_ptr); - if (!info_ptr) - { + if (!info_ptr) { os::Printer::log("PNGWriter: Internal PNG create info struct failure", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, NULL); return false; } // for proper error handling - if (setjmp(png_jmpbuf(png_ptr))) - { + if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } @@ -92,107 +89,99 @@ bool CImageWriterPNG::writeImage(io::IWriteFile* file, IImage* image,u32 param) png_set_write_fn(png_ptr, file, user_write_data_fcn, NULL); // Set info - switch(image->getColorFormat()) - { - case ECF_A8R8G8B8: - case ECF_A1R5G5B5: - png_set_IHDR(png_ptr, info_ptr, + switch (image->getColorFormat()) { + case ECF_A8R8G8B8: + case ECF_A1R5G5B5: + png_set_IHDR(png_ptr, info_ptr, image->getDimension().Width, image->getDimension().Height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); break; - default: - png_set_IHDR(png_ptr, info_ptr, + default: + png_set_IHDR(png_ptr, info_ptr, image->getDimension().Width, image->getDimension().Height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); } s32 lineWidth = image->getDimension().Width; - switch(image->getColorFormat()) - { + switch (image->getColorFormat()) { case ECF_R8G8B8: case ECF_R5G6B5: - lineWidth*=3; + lineWidth *= 3; break; case ECF_A8R8G8B8: case ECF_A1R5G5B5: - lineWidth*=4; + lineWidth *= 4; break; // TODO: Error handling in case of unsupported color format default: break; } - u8* tmpImage = new u8[image->getDimension().Height*lineWidth]; - if (!tmpImage) - { + u8 *tmpImage = new u8[image->getDimension().Height * lineWidth]; + if (!tmpImage) { os::Printer::log("PNGWriter: Internal PNG create image failure", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, &info_ptr); return false; } - u8* data = (u8*)image->getData(); - switch(image->getColorFormat()) - { + u8 *data = (u8 *)image->getData(); + switch (image->getColorFormat()) { case ECF_R8G8B8: - CColorConverter::convert_R8G8B8toR8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); + CColorConverter::convert_R8G8B8toR8G8B8(data, image->getDimension().Height * image->getDimension().Width, tmpImage); break; case ECF_A8R8G8B8: - CColorConverter::convert_A8R8G8B8toA8R8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); + CColorConverter::convert_A8R8G8B8toA8R8G8B8(data, image->getDimension().Height * image->getDimension().Width, tmpImage); break; case ECF_R5G6B5: - CColorConverter::convert_R5G6B5toR8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); + CColorConverter::convert_R5G6B5toR8G8B8(data, image->getDimension().Height * image->getDimension().Width, tmpImage); break; case ECF_A1R5G5B5: - CColorConverter::convert_A1R5G5B5toA8R8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); + CColorConverter::convert_A1R5G5B5toA8R8G8B8(data, image->getDimension().Height * image->getDimension().Width, tmpImage); break; // TODO: Error handling in case of unsupported color format default: os::Printer::log("CImageWriterPNG does not support image format", ColorFormatNames[image->getColorFormat()], ELL_WARNING); png_destroy_write_struct(&png_ptr, &info_ptr); - delete [] tmpImage; + delete[] tmpImage; return false; } // Create array of pointers to rows in image data - //Used to point to image rows - u8** RowPointers = new png_bytep[image->getDimension().Height]; - if (!RowPointers) - { + // Used to point to image rows + u8 **RowPointers = new png_bytep[image->getDimension().Height]; + if (!RowPointers) { os::Printer::log("PNGWriter: Internal PNG create row pointers failure", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, &info_ptr); - delete [] tmpImage; + delete[] tmpImage; return false; } - data=tmpImage; + data = tmpImage; // Fill array of pointers to rows in image data - for (u32 i=0; igetDimension().Height; ++i) - { - RowPointers[i]=data; + for (u32 i = 0; i < image->getDimension().Height; ++i) { + RowPointers[i] = data; data += lineWidth; } // for proper error handling - if (setjmp(png_jmpbuf(png_ptr))) - { + if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); - delete [] RowPointers; - delete [] tmpImage; + delete[] RowPointers; + delete[] tmpImage; return false; } png_set_rows(png_ptr, info_ptr, RowPointers); - if (image->getColorFormat()==ECF_A8R8G8B8 || image->getColorFormat()==ECF_A1R5G5B5) + if (image->getColorFormat() == ECF_A8R8G8B8 || image->getColorFormat() == ECF_A1R5G5B5) png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL); - else - { + else { png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); } - delete [] RowPointers; - delete [] tmpImage; + delete[] RowPointers; + delete[] tmpImage; png_destroy_write_struct(&png_ptr, &info_ptr); return true; } diff --git a/source/Irrlicht/CImageWriterPNG.h b/source/Irrlicht/CImageWriterPNG.h index febd6311..b0f7348e 100644 --- a/source/Irrlicht/CImageWriterPNG.h +++ b/source/Irrlicht/CImageWriterPNG.h @@ -18,7 +18,7 @@ public: CImageWriterPNG(); //! return true if this writer can write a file with the given extension - bool isAWriteableFileExtension(const io::path& filename) const override; + bool isAWriteableFileExtension(const io::path &filename) const override; //! write image to file bool writeImage(io::IWriteFile *file, IImage *image, u32 param) const override; diff --git a/source/Irrlicht/CIrrDeviceLinux.cpp b/source/Irrlicht/CIrrDeviceLinux.cpp index cd1a95de..df5990b7 100644 --- a/source/Irrlicht/CIrrDeviceLinux.cpp +++ b/source/Irrlicht/CIrrDeviceLinux.cpp @@ -67,65 +67,65 @@ namespace irr { - namespace video - { +namespace video +{ #ifdef _IRR_COMPILE_WITH_OPENGL_ - IVideoDriver* createOpenGLDriver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOpenGLDriver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif #ifdef _IRR_COMPILE_WITH_OGLES1_ - IVideoDriver* createOGLES1Driver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOGLES1Driver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif #ifdef _IRR_COMPILE_WITH_OGLES2_ - IVideoDriver* createOGLES2Driver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOGLES2Driver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif #ifdef _IRR_COMPILE_WITH_WEBGL1_ - IVideoDriver* createWebGL1Driver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createWebGL1Driver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif - } +} } // end namespace irr namespace { - Atom X_ATOM_CLIPBOARD; - Atom X_ATOM_TARGETS; - Atom X_ATOM_UTF8_STRING; - Atom X_ATOM_UTF8_MIME_TYPE; - Atom X_ATOM_TEXT; - Atom X_ATOM_NETWM_MAXIMIZE_VERT; - Atom X_ATOM_NETWM_MAXIMIZE_HORZ; - Atom X_ATOM_NETWM_STATE; - Atom X_ATOM_NETWM_STATE_FULLSCREEN; +Atom X_ATOM_CLIPBOARD; +Atom X_ATOM_TARGETS; +Atom X_ATOM_UTF8_STRING; +Atom X_ATOM_UTF8_MIME_TYPE; +Atom X_ATOM_TEXT; +Atom X_ATOM_NETWM_MAXIMIZE_VERT; +Atom X_ATOM_NETWM_MAXIMIZE_HORZ; +Atom X_ATOM_NETWM_STATE; +Atom X_ATOM_NETWM_STATE_FULLSCREEN; - Atom X_ATOM_WM_DELETE_WINDOW; +Atom X_ATOM_WM_DELETE_WINDOW; #if defined(_IRR_LINUX_X11_XINPUT2_) - int XI_EXTENSIONS_OPCODE; +int XI_EXTENSIONS_OPCODE; #endif } namespace irr { //! constructor -CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters& param) - : CIrrDeviceStub(param), +CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters ¶m) : + CIrrDeviceStub(param), #ifdef _IRR_COMPILE_WITH_X11_ - XDisplay(0), VisualInfo(0), Screennr(0), XWindow(0), StdHints(0), - XInputMethod(0), XInputContext(0), - HasNetWM(false), + XDisplay(0), VisualInfo(0), Screennr(0), XWindow(0), StdHints(0), + XInputMethod(0), XInputContext(0), + HasNetWM(false), #endif #if defined(_IRR_LINUX_X11_XINPUT2_) - currentTouchedCount(0), + currentTouchedCount(0), #endif - Width(param.WindowSize.Width), Height(param.WindowSize.Height), - WindowHasFocus(false), WindowMinimized(false), WindowMaximized(param.WindowMaximized), - ExternalWindow(false), AutorepeatSupport(0) + Width(param.WindowSize.Width), Height(param.WindowSize.Height), + WindowHasFocus(false), WindowMinimized(false), WindowMaximized(param.WindowMaximized), + ExternalWindow(false), AutorepeatSupport(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CIrrDeviceLinux"); - #endif +#endif // print version, distribution etc. // thx to LynxLuna for pointing me to the uname function @@ -153,12 +153,11 @@ CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters& param) XInitThreads(); // create window - if (CreationParams.DriverType != video::EDT_NULL) - { + if (CreationParams.DriverType != video::EDT_NULL) { // create the window, only if we do not use the null device if (!createWindow()) return; - if (param.WindowResizable < 2 ) + if (param.WindowResizable < 2) setResizable(param.WindowResizable == 1 ? true : false); #ifdef _IRR_COMPILE_WITH_X11_ createInputContext(); @@ -182,7 +181,6 @@ CIrrDeviceLinux::CIrrDeviceLinux(const SIrrlichtCreationParameters& param) setupTopLevelXorgWindow(); } - //! destructor CIrrDeviceLinux::~CIrrDeviceLinux() { @@ -190,42 +188,35 @@ CIrrDeviceLinux::~CIrrDeviceLinux() if (StdHints) XFree(StdHints); // Disable cursor (it is drop'ed in stub) - if (CursorControl) - { + if (CursorControl) { CursorControl->setVisible(false); - static_cast(CursorControl)->clearCursors(); + static_cast(CursorControl)->clearCursors(); } // Must free OpenGL textures etc before destroying context, so can't wait for stub destructor - if ( GUIEnvironment ) - { + if (GUIEnvironment) { GUIEnvironment->drop(); GUIEnvironment = NULL; } - if ( SceneManager ) - { + if (SceneManager) { SceneManager->drop(); SceneManager = NULL; } - if ( VideoDriver ) - { + if (VideoDriver) { VideoDriver->drop(); VideoDriver = NULL; } destroyInputContext(); - if (XDisplay) - { - if (ContextManager) - { + if (XDisplay) { + if (ContextManager) { ContextManager->destroyContext(); ContextManager->destroySurface(); } - if (!ExternalWindow) - { - XDestroyWindow(XDisplay,XWindow); + if (!ExternalWindow) { + XDestroyWindow(XDisplay, XWindow); XCloseDisplay(XDisplay); } } @@ -235,17 +226,14 @@ CIrrDeviceLinux::~CIrrDeviceLinux() #endif // #ifdef _IRR_COMPILE_WITH_X11_ #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { - if (ActiveJoysticks[joystick].fd >= 0) - { + for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { + if (ActiveJoysticks[joystick].fd >= 0) { close(ActiveJoysticks[joystick].fd); } } #endif } - #if defined(_IRR_COMPILE_WITH_X11_) && defined(_DEBUG) int IrrPrintXError(Display *display, XErrorEvent *event) { @@ -261,16 +249,15 @@ int IrrPrintXError(Display *display, XErrorEvent *event) } #endif - bool CIrrDeviceLinux::switchToFullscreen() { if (!CreationParams.Fullscreen) return true; - if (!HasNetWM) - { + if (!HasNetWM) { os::Printer::log("NetWM support is required to allow Irrlicht to switch " - "to fullscreen mode. Running in windowed mode instead.", ELL_WARNING); + "to fullscreen mode. Running in windowed mode instead.", + ELL_WARNING); CreationParams.Fullscreen = false; return false; } @@ -290,7 +277,6 @@ bool CIrrDeviceLinux::switchToFullscreen() return true; } - void CIrrDeviceLinux::setupTopLevelXorgWindow() { #ifdef _IRR_COMPILE_WITH_X11_ @@ -326,7 +312,7 @@ void CIrrDeviceLinux::setupTopLevelXorgWindow() os::Printer::log("Setting Xorg window manager Properties", ELL_DEBUG); - XSetWMProperties (XDisplay, XWindow, NULL, NULL, NULL, 0, NULL, NULL, NULL); + XSetWMProperties(XDisplay, XWindow, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to @@ -341,7 +327,7 @@ void CIrrDeviceLinux::setupTopLevelXorgWindow() XChangeProperty(XDisplay, XWindow, NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, - reinterpret_cast(&pid),1); + reinterpret_cast(&pid), 1); // Set the WM_CLIENT_LEADER window property here. Minetest has only one // window and that window will always be the leader. @@ -350,44 +336,40 @@ void CIrrDeviceLinux::setupTopLevelXorgWindow() Atom WM_CLIENT_LEADER = XInternAtom(XDisplay, "WM_CLIENT_LEADER", false); - XChangeProperty (XDisplay, XWindow, WM_CLIENT_LEADER, - XA_WINDOW, 32, PropModeReplace, - reinterpret_cast(&XWindow), 1); + XChangeProperty(XDisplay, XWindow, WM_CLIENT_LEADER, + XA_WINDOW, 32, PropModeReplace, + reinterpret_cast(&XWindow), 1); #endif } - #if defined(_IRR_COMPILE_WITH_X11_) -void IrrPrintXGrabError(int grabResult, const c8 * grabCommand ) +void IrrPrintXGrabError(int grabResult, const c8 *grabCommand) { - if ( grabResult == GrabSuccess ) - { -// os::Printer::log(grabCommand, "GrabSuccess", ELL_INFORMATION); + if (grabResult == GrabSuccess) { + // os::Printer::log(grabCommand, "GrabSuccess", ELL_INFORMATION); return; } - switch ( grabResult ) - { - case AlreadyGrabbed: - os::Printer::log(grabCommand, "AlreadyGrabbed", ELL_WARNING); - break; - case GrabNotViewable: - os::Printer::log(grabCommand, "GrabNotViewable", ELL_WARNING); - break; - case GrabFrozen: - os::Printer::log(grabCommand, "GrabFrozen", ELL_WARNING); - break; - case GrabInvalidTime: - os::Printer::log(grabCommand, "GrabInvalidTime", ELL_WARNING); - break; - default: - os::Printer::log(grabCommand, "grab failed with unknown problem", ELL_WARNING); - break; + switch (grabResult) { + case AlreadyGrabbed: + os::Printer::log(grabCommand, "AlreadyGrabbed", ELL_WARNING); + break; + case GrabNotViewable: + os::Printer::log(grabCommand, "GrabNotViewable", ELL_WARNING); + break; + case GrabFrozen: + os::Printer::log(grabCommand, "GrabFrozen", ELL_WARNING); + break; + case GrabInvalidTime: + os::Printer::log(grabCommand, "GrabInvalidTime", ELL_WARNING); + break; + default: + os::Printer::log(grabCommand, "grab failed with unknown problem", ELL_WARNING); + break; } } #endif - bool CIrrDeviceLinux::createWindow() { #ifdef _IRR_COMPILE_WITH_X11_ @@ -397,8 +379,7 @@ bool CIrrDeviceLinux::createWindow() #endif XDisplay = XOpenDisplay(0); - if (!XDisplay) - { + if (!XDisplay) { os::Printer::log("Error: Need running XServer to start Irrlicht Engine.", ELL_ERROR); if (XDisplayName(0)[0]) os::Printer::log("Could not open display", XDisplayName(0), ELL_ERROR); @@ -419,38 +400,34 @@ bool CIrrDeviceLinux::createWindow() #if defined(_IRR_COMPILE_WITH_OPENGL_) // don't use the XVisual with OpenGL, because it ignores all requested // properties of the CreationParams - if (CreationParams.DriverType == video::EDT_OPENGL) - { + if (CreationParams.DriverType == video::EDT_OPENGL) { video::SExposedVideoData data; data.OpenGLLinux.X11Display = XDisplay; ContextManager = new video::CGLXManager(CreationParams, data, Screennr); - VisualInfo = ((video::CGLXManager*)ContextManager)->getVisual(); + VisualInfo = ((video::CGLXManager *)ContextManager)->getVisual(); } #endif - if (!VisualInfo) - { + if (!VisualInfo) { // create visual with standard X methods os::Printer::log("Using plain X visual"); - XVisualInfo visTempl; //Template to hold requested values - int visNumber; // Return value of available visuals + XVisualInfo visTempl; // Template to hold requested values + int visNumber; // Return value of available visuals visTempl.screen = Screennr; // ARGB visuals should be avoided for usual applications - visTempl.depth = CreationParams.WithAlphaChannel?32:24; - while ((!VisualInfo) && (visTempl.depth>=16)) - { - VisualInfo = XGetVisualInfo(XDisplay, VisualScreenMask|VisualDepthMask, - &visTempl, &visNumber); + visTempl.depth = CreationParams.WithAlphaChannel ? 32 : 24; + while ((!VisualInfo) && (visTempl.depth >= 16)) { + VisualInfo = XGetVisualInfo(XDisplay, VisualScreenMask | VisualDepthMask, + &visTempl, &visNumber); visTempl.depth -= 8; } } - if (!VisualInfo) - { + if (!VisualInfo) { os::Printer::log("Fatal error, could not get visual.", ELL_ERROR); XCloseDisplay(XDisplay); - XDisplay=0; + XDisplay = 0; return false; } #ifdef _DEBUG @@ -468,16 +445,14 @@ bool CIrrDeviceLinux::createWindow() WndAttributes.border_pixel = 0; WndAttributes.event_mask = StructureNotifyMask | FocusChangeMask | ExposureMask; WndAttributes.event_mask |= PointerMotionMask | - ButtonPressMask | KeyPressMask | - ButtonReleaseMask | KeyReleaseMask; + ButtonPressMask | KeyPressMask | + ButtonReleaseMask | KeyReleaseMask; - if (!CreationParams.WindowId) - { + if (!CreationParams.WindowId) { int x = 0; int y = 0; - if (!CreationParams.Fullscreen) - { + if (!CreationParams.Fullscreen) { if (CreationParams.WindowPosition.X > 0) x = CreationParams.WindowPosition.X; if (CreationParams.WindowPosition.Y > 0) @@ -494,22 +469,18 @@ bool CIrrDeviceLinux::createWindow() &WndAttributes); XMapRaised(XDisplay, XWindow); - CreationParams.WindowId = (void*)XWindow; + CreationParams.WindowId = (void *)XWindow; X_ATOM_WM_DELETE_WINDOW = XInternAtom(XDisplay, "WM_DELETE_WINDOW", True); XSetWMProtocols(XDisplay, XWindow, &X_ATOM_WM_DELETE_WINDOW, 1); - if (CreationParams.Fullscreen) - { + if (CreationParams.Fullscreen) { // Don't try to set window position - } - else if (CreationParams.WindowPosition.X >= 0 || CreationParams.WindowPosition.Y >= 0) // default is -1, -1 + } else if (CreationParams.WindowPosition.X >= 0 || CreationParams.WindowPosition.Y >= 0) // default is -1, -1 { // Window managers are free to ignore positions above, so give it another shot - XMoveWindow(XDisplay,XWindow,x,y); + XMoveWindow(XDisplay, XWindow, x, y); } - } - else - { + } else { // attach external window XWindow = (Window)CreationParams.WindowId; { @@ -540,12 +511,12 @@ bool CIrrDeviceLinux::createWindow() switchToFullscreen(); - WindowMinimized=false; + WindowMinimized = false; XkbSetDetectableAutoRepeat(XDisplay, True, &AutorepeatSupport); Window tmp; u32 borderWidth; - int x,y; + int x, y; unsigned int bits; XGetGeometry(XDisplay, XWindow, &tmp, &x, &y, &Width, &Height, &borderWidth, &bits); @@ -563,76 +534,74 @@ bool CIrrDeviceLinux::createWindow() return true; } - //! create the driver void CIrrDeviceLinux::createDriver() { - switch(CreationParams.DriverType) - { + switch (CreationParams.DriverType) { #ifdef _IRR_COMPILE_WITH_X11_ case video::EDT_OPENGL: #ifdef _IRR_COMPILE_WITH_OPENGL_ - { - video::SExposedVideoData data; - data.OpenGLLinux.X11Window = XWindow; - data.OpenGLLinux.X11Display = XDisplay; + { + video::SExposedVideoData data; + data.OpenGLLinux.X11Window = XWindow; + data.OpenGLLinux.X11Display = XDisplay; - ContextManager->initialize(CreationParams, data); + ContextManager->initialize(CreationParams, data); - VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); - } + VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); + } #else os::Printer::log("No OpenGL support compiled in.", ELL_ERROR); #endif - break; + break; case video::EDT_OGLES1: #ifdef _IRR_COMPILE_WITH_OGLES1_ - { - video::SExposedVideoData data; - data.OpenGLLinux.X11Window = XWindow; - data.OpenGLLinux.X11Display = XDisplay; + { + video::SExposedVideoData data; + data.OpenGLLinux.X11Window = XWindow; + data.OpenGLLinux.X11Display = XDisplay; - ContextManager = new video::CEGLManager(); - ContextManager->initialize(CreationParams, data); + ContextManager = new video::CEGLManager(); + ContextManager->initialize(CreationParams, data); - VideoDriver = video::createOGLES1Driver(CreationParams, FileSystem, ContextManager); - } + VideoDriver = video::createOGLES1Driver(CreationParams, FileSystem, ContextManager); + } #else os::Printer::log("No OpenGL-ES1 support compiled in.", ELL_ERROR); #endif - break; + break; case video::EDT_OGLES2: #ifdef _IRR_COMPILE_WITH_OGLES2_ - { - video::SExposedVideoData data; - data.OpenGLLinux.X11Window = XWindow; - data.OpenGLLinux.X11Display = XDisplay; + { + video::SExposedVideoData data; + data.OpenGLLinux.X11Window = XWindow; + data.OpenGLLinux.X11Display = XDisplay; - ContextManager = new video::CEGLManager(); - ContextManager->initialize(CreationParams, data); + ContextManager = new video::CEGLManager(); + ContextManager->initialize(CreationParams, data); - VideoDriver = video::createOGLES2Driver(CreationParams, FileSystem, ContextManager); - } + VideoDriver = video::createOGLES2Driver(CreationParams, FileSystem, ContextManager); + } #else os::Printer::log("No OpenGL-ES2 support compiled in.", ELL_ERROR); #endif - break; + break; case video::EDT_WEBGL1: #ifdef _IRR_COMPILE_WITH_WEBGL1_ - { - video::SExposedVideoData data; - data.OpenGLLinux.X11Window = XWindow; - data.OpenGLLinux.X11Display = XDisplay; + { + video::SExposedVideoData data; + data.OpenGLLinux.X11Window = XWindow; + data.OpenGLLinux.X11Display = XDisplay; - ContextManager = new video::CEGLManager(); - ContextManager->initialize(CreationParams, data); + ContextManager = new video::CEGLManager(); + ContextManager->initialize(CreationParams, data); - VideoDriver = video::createWebGL1Driver(CreationParams, FileSystem, ContextManager); - } + VideoDriver = video::createWebGL1Driver(CreationParams, FileSystem, ContextManager); + } #else os::Printer::log("No WebGL1 support compiled in.", ELL_ERROR); #endif - break; + break; case video::EDT_NULL: VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize); break; @@ -658,48 +627,43 @@ bool CIrrDeviceLinux::createInputContext() // So users would have to call it always or their input is broken badly. // We can restore immediately - so won't mess with anything in users apps. core::stringc oldLocale(setlocale(LC_CTYPE, NULL)); - setlocale(LC_CTYPE, ""); // use environment locale + setlocale(LC_CTYPE, ""); // use environment locale - if ( !XSupportsLocale() ) - { + if (!XSupportsLocale()) { os::Printer::log("Locale not supported. Falling back to non-i18n input.", ELL_WARNING); setlocale(LC_CTYPE, oldLocale.c_str()); return false; } // Load XMODIFIERS (e.g. for IMEs) - if (!XSetLocaleModifiers("")) - { + if (!XSetLocaleModifiers("")) { setlocale(LC_CTYPE, oldLocale.c_str()); os::Printer::log("XSetLocaleModifiers failed. Falling back to non-i18n input.", ELL_WARNING); return false; } XInputMethod = XOpenIM(XDisplay, NULL, NULL, NULL); - if ( !XInputMethod ) - { + if (!XInputMethod) { setlocale(LC_CTYPE, oldLocale.c_str()); os::Printer::log("XOpenIM failed to create an input method. Falling back to non-i18n input.", ELL_WARNING); return false; } XIMStyles *im_supported_styles; - XGetIMValues(XInputMethod, XNQueryInputStyle, &im_supported_styles, (char*)NULL); + XGetIMValues(XInputMethod, XNQueryInputStyle, &im_supported_styles, (char *)NULL); XIMStyle bestStyle = 0; XIMStyle supportedStyle = XIMPreeditNothing | XIMStatusNothing; - for(int i=0; i < im_supported_styles->count_styles; ++i) - { - XIMStyle style = im_supported_styles->supported_styles[i]; - if ((style & supportedStyle) == style) /* if we can handle it */ + for (int i = 0; i < im_supported_styles->count_styles; ++i) { + XIMStyle style = im_supported_styles->supported_styles[i]; + if ((style & supportedStyle) == style) /* if we can handle it */ { - bestStyle = style; + bestStyle = style; break; } - } + } XFree(im_supported_styles); - if ( !bestStyle ) - { + if (!bestStyle) { XDestroyIC(XInputContext); XInputContext = 0; @@ -709,11 +673,10 @@ bool CIrrDeviceLinux::createInputContext() } XInputContext = XCreateIC(XInputMethod, - XNInputStyle, bestStyle, - XNClientWindow, XWindow, - (char*)NULL); - if (!XInputContext ) - { + XNInputStyle, bestStyle, + XNClientWindow, XWindow, + (char *)NULL); + if (!XInputContext) { os::Printer::log("XInputContext failed to create an input context. Falling back to non-i18n input.", ELL_WARNING); setlocale(LC_CTYPE, oldLocale.c_str()); return false; @@ -725,14 +688,12 @@ bool CIrrDeviceLinux::createInputContext() void CIrrDeviceLinux::destroyInputContext() { - if ( XInputContext ) - { + if (XInputContext) { XUnsetICFocus(XInputContext); XDestroyIC(XInputContext); XInputContext = 0; } - if ( XInputMethod ) - { + if (XInputMethod) { XCloseIM(XInputMethod); XInputMethod = 0; } @@ -745,26 +706,19 @@ EKEY_CODE CIrrDeviceLinux::getKeyCode(XEvent &event) SKeyMap mp; mp.X11Key = XkbKeycodeToKeysym(XDisplay, event.xkey.keycode, 0, 0); const s32 idx = KeyMap.binary_search(mp); - if (idx != -1) - { + if (idx != -1) { keyCode = (EKEY_CODE)KeyMap[idx].Win32Key; } - if (keyCode == 0) - { + if (keyCode == 0) { keyCode = KEY_UNKNOWN; - if ( !mp.X11Key ) - { + if (!mp.X11Key) { os::Printer::log("No such X11Key, event keycode", core::stringc(event.xkey.keycode).c_str(), ELL_INFORMATION); - } - else if (idx == -1) - { + } else if (idx == -1) { os::Printer::log("EKEY_CODE not found, X11 keycode", core::stringc(mp.X11Key).c_str(), ELL_INFORMATION); - } - else - { + } else { os::Printer::log("EKEY_CODE is 0, X11 keycode", core::stringc(mp.X11Key).c_str(), ELL_INFORMATION); } - } + } return keyCode; } #endif @@ -776,28 +730,24 @@ bool CIrrDeviceLinux::run() #ifdef _IRR_COMPILE_WITH_X11_ - if ( CursorControl ) - static_cast(CursorControl)->update(); + if (CursorControl) + static_cast(CursorControl)->update(); - if ((CreationParams.DriverType != video::EDT_NULL) && XDisplay) - { + if ((CreationParams.DriverType != video::EDT_NULL) && XDisplay) { SEvent irrevent; irrevent.MouseInput.ButtonStates = 0xffffffff; - while (XPending(XDisplay) > 0 && !Close) - { + while (XPending(XDisplay) > 0 && !Close) { XEvent event; XNextEvent(XDisplay, &event); if (XFilterEvent(&event, None)) continue; - switch (event.type) - { + switch (event.type) { case ConfigureNotify: // check for changed window size - if ((event.xconfigure.width != (int) Width) || - (event.xconfigure.height != (int) Height)) - { + if ((event.xconfigure.width != (int)Width) || + (event.xconfigure.height != (int)Height)) { Width = event.xconfigure.width; Height = event.xconfigure.height; @@ -807,19 +757,19 @@ bool CIrrDeviceLinux::run() break; case MapNotify: - WindowMinimized=false; + WindowMinimized = false; break; case UnmapNotify: - WindowMinimized=true; + WindowMinimized = true; break; case FocusIn: - WindowHasFocus=true; + WindowHasFocus = true; break; case FocusOut: - WindowHasFocus=false; + WindowHasFocus = false; break; case MotionNotify: @@ -857,58 +807,50 @@ bool CIrrDeviceLinux::run() irrevent.MouseInput.Event = irr::EMIE_COUNT; - switch(event.xbutton.button) - { - case Button1: + switch (event.xbutton.button) { + case Button1: irrevent.MouseInput.Event = - (event.type == ButtonPress) ? irr::EMIE_LMOUSE_PRESSED_DOWN : irr::EMIE_LMOUSE_LEFT_UP; + (event.type == ButtonPress) ? irr::EMIE_LMOUSE_PRESSED_DOWN : irr::EMIE_LMOUSE_LEFT_UP; irrevent.MouseInput.ButtonStates ^= irr::EMBSM_LEFT; break; - case Button3: + case Button3: irrevent.MouseInput.Event = - (event.type == ButtonPress) ? irr::EMIE_RMOUSE_PRESSED_DOWN : irr::EMIE_RMOUSE_LEFT_UP; + (event.type == ButtonPress) ? irr::EMIE_RMOUSE_PRESSED_DOWN : irr::EMIE_RMOUSE_LEFT_UP; irrevent.MouseInput.ButtonStates ^= irr::EMBSM_RIGHT; break; - case Button2: + case Button2: irrevent.MouseInput.Event = - (event.type == ButtonPress) ? irr::EMIE_MMOUSE_PRESSED_DOWN : irr::EMIE_MMOUSE_LEFT_UP; + (event.type == ButtonPress) ? irr::EMIE_MMOUSE_PRESSED_DOWN : irr::EMIE_MMOUSE_LEFT_UP; irrevent.MouseInput.ButtonStates ^= irr::EMBSM_MIDDLE; break; - case Button4: - if (event.type == ButtonPress) - { + case Button4: + if (event.type == ButtonPress) { irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL; irrevent.MouseInput.Wheel = 1.0f; } break; - case Button5: - if (event.type == ButtonPress) - { + case Button5: + if (event.type == ButtonPress) { irrevent.MouseInput.Event = EMIE_MOUSE_WHEEL; irrevent.MouseInput.Wheel = -1.0f; } break; } - if (irrevent.MouseInput.Event != irr::EMIE_COUNT) - { + if (irrevent.MouseInput.Event != irr::EMIE_COUNT) { postEventFromUser(irrevent); - if ( irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN ) - { + if (irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN) { u32 clicks = checkSuccessiveClicks(irrevent.MouseInput.X, irrevent.MouseInput.Y, irrevent.MouseInput.Event); - if ( clicks == 2 ) - { - irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN); + if (clicks == 2) { + irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event - EMIE_LMOUSE_PRESSED_DOWN); postEventFromUser(irrevent); - } - else if ( clicks == 3 ) - { - irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN); + } else if (clicks == 3) { + irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event - EMIE_LMOUSE_PRESSED_DOWN); postEventFromUser(irrevent); } } @@ -916,20 +858,19 @@ bool CIrrDeviceLinux::run() break; case MappingNotify: - XRefreshKeyboardMapping (&event.xmapping) ; + XRefreshKeyboardMapping(&event.xmapping); break; case KeyRelease: - if (0 == AutorepeatSupport && (XPending( XDisplay ) > 0) ) - { + if (0 == AutorepeatSupport && (XPending(XDisplay) > 0)) { // check for Autorepeat manually // We'll do the same as Windows does: Only send KeyPressed // So every KeyRelease is a real release XEvent next_event; - XPeekEvent (event.xkey.display, &next_event); + XPeekEvent(event.xkey.display, &next_event); if ((next_event.type == KeyPress) && - (next_event.xkey.keycode == event.xkey.keycode) && - (next_event.xkey.time - event.xkey.time) < 2) // usually same time, but on some systems a difference of 1 is possible + (next_event.xkey.keycode == event.xkey.keycode) && + (next_event.xkey.time - event.xkey.time) < 2) // usually same time, but on some systems a difference of 1 is possible { // Ignore the key release event break; @@ -938,7 +879,7 @@ bool CIrrDeviceLinux::run() irrevent.EventType = irr::EET_KEY_INPUT_EVENT; irrevent.KeyInput.PressedDown = false; - irrevent.KeyInput.Char = 0; // on release that's undefined + irrevent.KeyInput.Char = 0; // on release that's undefined irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0; irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0; irrevent.KeyInput.Key = getKeyCode(event); @@ -946,37 +887,28 @@ bool CIrrDeviceLinux::run() postEventFromUser(irrevent); break; - case KeyPress: - { - SKeyMap mp; - if ( XInputContext ) - { - wchar_t buf[64]={0}; - Status status; - int strLen = XwcLookupString(XInputContext, &event.xkey, buf, sizeof(buf)/sizeof(wchar_t)-1, &mp.X11Key, &status); - if ( status == XBufferOverflow ) - { - os::Printer::log("XwcLookupString needs a larger buffer", ELL_INFORMATION); + case KeyPress: { + SKeyMap mp; + if (XInputContext) { + wchar_t buf[64] = {0}; + Status status; + int strLen = XwcLookupString(XInputContext, &event.xkey, buf, sizeof(buf) / sizeof(wchar_t) - 1, &mp.X11Key, &status); + if (status == XBufferOverflow) { + os::Printer::log("XwcLookupString needs a larger buffer", ELL_INFORMATION); + } + if (strLen > 0 && (status == XLookupChars || status == XLookupBoth)) { + if (strLen > 1) { + // Multiple characters: send string event + irrevent.EventType = irr::EET_STRING_INPUT_EVENT; + irrevent.StringInput.Str = new core::stringw(buf); + postEventFromUser(irrevent); + delete irrevent.StringInput.Str; + irrevent.StringInput.Str = NULL; + break; + } else { + irrevent.KeyInput.Char = buf[0]; } - if ( strLen > 0 && (status == XLookupChars || status == XLookupBoth) ) - { - if (strLen > 1) - { - // Multiple characters: send string event - irrevent.EventType = irr::EET_STRING_INPUT_EVENT; - irrevent.StringInput.Str = new core::stringw(buf); - postEventFromUser(irrevent); - delete irrevent.StringInput.Str; - irrevent.StringInput.Str = NULL; - break; - } - else - { - irrevent.KeyInput.Char = buf[0]; - } - } - else - { + } else { #if 0 // Most of those are fine - but useful to have the info when debugging Irrlicht itself. if ( status == XLookupNone ) os::Printer::log("XLookupNone", ELL_INFORMATION); @@ -989,177 +921,159 @@ bool CIrrDeviceLinux::run() else if ( strLen == 0 ) os::Printer::log("no string", ELL_INFORMATION); #endif - irrevent.KeyInput.Char = 0; - } + irrevent.KeyInput.Char = 0; } - else // Old version without InputContext. Does not support i18n, but good to have as fallback. + } else // Old version without InputContext. Does not support i18n, but good to have as fallback. + { + union { - union - { - char buf[8]; - wchar_t wbuf[2]; - } tmp = {{0}}; - XLookupString(&event.xkey, tmp.buf, sizeof(tmp.buf), &mp.X11Key, NULL); - irrevent.KeyInput.Char = tmp.wbuf[0]; - } + char buf[8]; + wchar_t wbuf[2]; + } tmp = {{0}}; + XLookupString(&event.xkey, tmp.buf, sizeof(tmp.buf), &mp.X11Key, NULL); + irrevent.KeyInput.Char = tmp.wbuf[0]; + } - irrevent.EventType = irr::EET_KEY_INPUT_EVENT; - irrevent.KeyInput.PressedDown = true; - irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0; - irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0; - irrevent.KeyInput.Key = getKeyCode(event); + irrevent.EventType = irr::EET_KEY_INPUT_EVENT; + irrevent.KeyInput.PressedDown = true; + irrevent.KeyInput.Control = (event.xkey.state & ControlMask) != 0; + irrevent.KeyInput.Shift = (event.xkey.state & ShiftMask) != 0; + irrevent.KeyInput.Key = getKeyCode(event); + postEventFromUser(irrevent); + } break; + + case ClientMessage: { + if (static_cast(event.xclient.data.l[0]) == X_ATOM_WM_DELETE_WINDOW && X_ATOM_WM_DELETE_WINDOW != None) { + os::Printer::log("Quit message received.", ELL_INFORMATION); + Close = true; + } else { + // we assume it's a user message + irrevent.EventType = irr::EET_USER_EVENT; + irrevent.UserEvent.UserData1 = static_cast(event.xclient.data.l[0]); + irrevent.UserEvent.UserData2 = static_cast(event.xclient.data.l[1]); postEventFromUser(irrevent); } - break; + } break; - case ClientMessage: - { - if (static_cast(event.xclient.data.l[0]) == X_ATOM_WM_DELETE_WINDOW && X_ATOM_WM_DELETE_WINDOW != None) - { - os::Printer::log("Quit message received.", ELL_INFORMATION); - Close = true; - } - else - { - // we assume it's a user message - irrevent.EventType = irr::EET_USER_EVENT; - irrevent.UserEvent.UserData1 = static_cast(event.xclient.data.l[0]); - irrevent.UserEvent.UserData2 = static_cast(event.xclient.data.l[1]); - postEventFromUser(irrevent); - } - } - break; + case SelectionRequest: { + XSelectionRequestEvent *req = &(event.xselectionrequest); - case SelectionRequest: - { - XSelectionRequestEvent *req = &(event.xselectionrequest); + auto send_response = [this, req](Atom property) { + XEvent response; + response.xselection.type = SelectionNotify; + response.xselection.display = req->display; + response.xselection.requestor = req->requestor; + response.xselection.selection = req->selection; + response.xselection.target = req->target; + response.xselection.property = property; + response.xselection.time = req->time; + XSendEvent(XDisplay, req->requestor, 0, 0, &response); + XFlush(XDisplay); + }; + auto send_response_refuse = [&send_response] { + send_response(None); + }; - auto send_response = [this, req](Atom property) { - XEvent response; - response.xselection.type = SelectionNotify; - response.xselection.display = req->display; - response.xselection.requestor = req->requestor; - response.xselection.selection = req->selection; - response.xselection.target = req->target; - response.xselection.property = property; - response.xselection.time = req->time; - XSendEvent (XDisplay, req->requestor, 0, 0, &response); - XFlush (XDisplay); - }; - auto send_response_refuse = [&send_response] { - send_response(None); - }; + // sets the required property to data of type type and + // sends the according response + auto set_property_and_notify = [this, req, &send_response](Atom type, int format, const void *data, u32 data_size) { + XChangeProperty(XDisplay, + req->requestor, + req->property, + type, + format, + PropModeReplace, + (const unsigned char *)data, + data_size); + send_response(req->property); + }; - // sets the required property to data of type type and - // sends the according response - auto set_property_and_notify = [this, req, &send_response] - (Atom type, int format, const void *data, u32 data_size) { - XChangeProperty(XDisplay, - req->requestor, - req->property, - type, - format, - PropModeReplace, - (const unsigned char *)data, - data_size); - send_response(req->property); - }; - - if ((req->selection != X_ATOM_CLIPBOARD && + if ((req->selection != X_ATOM_CLIPBOARD && req->selection != XA_PRIMARY) || - req->owner != XWindow) { - // we are not the owner, refuse request - send_response_refuse(); - break; - } - const core::stringc &text_buffer = req->selection == X_ATOM_CLIPBOARD ? - Clipboard : PrimarySelection; + req->owner != XWindow) { + // we are not the owner, refuse request + send_response_refuse(); + break; + } + const core::stringc &text_buffer = req->selection == X_ATOM_CLIPBOARD ? Clipboard : PrimarySelection; - // for debugging: - //~ { - //~ char *target_name = XGetAtomName(XDisplay, req->target); - //~ fprintf(stderr, "CIrrDeviceLinux::run: target: %s (=%ld)\n", - //~ target_name, req->target); - //~ XFree(target_name); - //~ } + // for debugging: + //~ { + //~ char *target_name = XGetAtomName(XDisplay, req->target); + //~ fprintf(stderr, "CIrrDeviceLinux::run: target: %s (=%ld)\n", + //~ target_name, req->target); + //~ XFree(target_name); + //~ } - if (req->property == None) { - // req is from obsolete client, use target as property name - // and X_ATOM_UTF8_STRING as type - // Note: this was not tested and might be incorrect - os::Printer::log("CIrrDeviceLinux::run: SelectionRequest from obsolete client", - ELL_WARNING); - XChangeProperty(XDisplay, - req->requestor, - req->target, X_ATOM_UTF8_STRING, - 8, // format = 8-bit - PropModeReplace, - (unsigned char *)text_buffer.c_str(), - text_buffer.size()); - send_response(req->target); - break; - } + if (req->property == None) { + // req is from obsolete client, use target as property name + // and X_ATOM_UTF8_STRING as type + // Note: this was not tested and might be incorrect + os::Printer::log("CIrrDeviceLinux::run: SelectionRequest from obsolete client", + ELL_WARNING); + XChangeProperty(XDisplay, + req->requestor, + req->target, X_ATOM_UTF8_STRING, + 8, // format = 8-bit + PropModeReplace, + (unsigned char *)text_buffer.c_str(), + text_buffer.size()); + send_response(req->target); + break; + } - if (req->target == X_ATOM_TARGETS) { - Atom data[] = { + if (req->target == X_ATOM_TARGETS) { + Atom data[] = { X_ATOM_TARGETS, X_ATOM_TEXT, X_ATOM_UTF8_STRING, - X_ATOM_UTF8_MIME_TYPE - }; - set_property_and_notify( - XA_ATOM, - 32, // Atom is long, we need to set 32 for longs - &data, - sizeof(data) / sizeof(*data) - ); + X_ATOM_UTF8_MIME_TYPE}; + set_property_and_notify( + XA_ATOM, + 32, // Atom is long, we need to set 32 for longs + &data, + sizeof(data) / sizeof(*data)); - } else if (req->target == X_ATOM_TEXT || - req->target == X_ATOM_UTF8_STRING || - req->target == X_ATOM_UTF8_MIME_TYPE) { - set_property_and_notify( - X_ATOM_UTF8_STRING, - 8, - text_buffer.c_str(), - text_buffer.size() - ); + } else if (req->target == X_ATOM_TEXT || + req->target == X_ATOM_UTF8_STRING || + req->target == X_ATOM_UTF8_MIME_TYPE) { + set_property_and_notify( + X_ATOM_UTF8_STRING, + 8, + text_buffer.c_str(), + text_buffer.size()); - } else { - // refuse the request - send_response_refuse(); - } + } else { + // refuse the request + send_response_refuse(); } - break; + } break; #if defined(_IRR_LINUX_X11_XINPUT2_) - case GenericEvent: - { - XGenericEventCookie *cookie = &event.xcookie; - if (XGetEventData(XDisplay, cookie) && cookie->extension == XI_EXTENSIONS_OPCODE && XI_EXTENSIONS_OPCODE - && (cookie->evtype == XI_TouchUpdate || cookie->evtype == XI_TouchBegin || cookie->evtype == XI_TouchEnd)) - { - XIDeviceEvent *de = (XIDeviceEvent *) cookie->data; + case GenericEvent: { + XGenericEventCookie *cookie = &event.xcookie; + if (XGetEventData(XDisplay, cookie) && cookie->extension == XI_EXTENSIONS_OPCODE && XI_EXTENSIONS_OPCODE && (cookie->evtype == XI_TouchUpdate || cookie->evtype == XI_TouchBegin || cookie->evtype == XI_TouchEnd)) { + XIDeviceEvent *de = (XIDeviceEvent *)cookie->data; - irrevent.EventType = EET_TOUCH_INPUT_EVENT; + irrevent.EventType = EET_TOUCH_INPUT_EVENT; - irrevent.TouchInput.Event = cookie->evtype == XI_TouchUpdate ? ETIE_MOVED : (cookie->evtype == XI_TouchBegin ? ETIE_PRESSED_DOWN : ETIE_LEFT_UP); + irrevent.TouchInput.Event = cookie->evtype == XI_TouchUpdate ? ETIE_MOVED : (cookie->evtype == XI_TouchBegin ? ETIE_PRESSED_DOWN : ETIE_LEFT_UP); - irrevent.TouchInput.ID = de->detail; - irrevent.TouchInput.X = de->event_x; - irrevent.TouchInput.Y = de->event_y; + irrevent.TouchInput.ID = de->detail; + irrevent.TouchInput.X = de->event_x; + irrevent.TouchInput.Y = de->event_y; - if (irrevent.TouchInput.Event == ETIE_PRESSED_DOWN) { - currentTouchedCount++; - } - irrevent.TouchInput.touchedCount = currentTouchedCount; - if (currentTouchedCount > 0 && irrevent.TouchInput.Event == ETIE_LEFT_UP) { - currentTouchedCount--; - } - - postEventFromUser(irrevent); + if (irrevent.TouchInput.Event == ETIE_PRESSED_DOWN) { + currentTouchedCount++; } + irrevent.TouchInput.touchedCount = currentTouchedCount; + if (currentTouchedCount > 0 && irrevent.TouchInput.Event == ETIE_LEFT_UP) { + currentTouchedCount--; + } + + postEventFromUser(irrevent); } - break; + } break; #endif default: @@ -1167,11 +1081,9 @@ bool CIrrDeviceLinux::run() } // end switch // Update IME information - if (XInputContext && GUIEnvironment) - { + if (XInputContext && GUIEnvironment) { gui::IGUIElement *elem = GUIEnvironment->getFocus(); - if (elem && elem->acceptsIME()) - { + if (elem && elem->acceptsIME()) { core::rect r = elem->getAbsolutePosition(); XPoint p; p.x = (short)r.UpperLeftCorner.X; @@ -1186,7 +1098,6 @@ bool CIrrDeviceLinux::run() } } // end while - } #endif //_IRR_COMPILE_WITH_X11_ @@ -1196,23 +1107,21 @@ bool CIrrDeviceLinux::run() return !Close; } - //! Pause the current process for the minimum time allowed only to allow other processes to execute void CIrrDeviceLinux::yield() { - struct timespec ts = {0,1}; + struct timespec ts = {0, 1}; nanosleep(&ts, NULL); } - //! Pause execution and let other processes to run for a specified amount of time. -void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer=false) +void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer = false) { const bool wasStopped = Timer ? Timer->isStopped() : true; struct timespec ts; - ts.tv_sec = (time_t) (timeMs / 1000); - ts.tv_nsec = (long) (timeMs % 1000) * 1000000; + ts.tv_sec = (time_t)(timeMs / 1000); + ts.tv_nsec = (long)(timeMs % 1000) * 1000000; if (pauseTimer && !wasStopped) Timer->stop(); @@ -1223,18 +1132,16 @@ void CIrrDeviceLinux::sleep(u32 timeMs, bool pauseTimer=false) Timer->start(); } - //! sets the caption of the window -void CIrrDeviceLinux::setWindowCaption(const wchar_t* text) +void CIrrDeviceLinux::setWindowCaption(const wchar_t *text) { #ifdef _IRR_COMPILE_WITH_X11_ if (CreationParams.DriverType == video::EDT_NULL) return; XTextProperty txt; - if (Success==XwcTextListToTextProperty(XDisplay, const_cast(&text), - 1, XStdICCTextStyle, &txt)) - { + if (Success == XwcTextListToTextProperty(XDisplay, const_cast(&text), + 1, XStdICCTextStyle, &txt)) { XSetWMName(XDisplay, XWindow, &txt); XSetWMIconName(XDisplay, XWindow, &txt); XFree(txt.value); @@ -1242,7 +1149,6 @@ void CIrrDeviceLinux::setWindowCaption(const wchar_t* text) #endif } - //! Sets the window icon. bool CIrrDeviceLinux::setWindowIcon(const video::IImage *img) { @@ -1286,42 +1192,36 @@ bool CIrrDeviceLinux::setWindowIcon(const video::IImage *img) return true; } - //! notifies the device that it should close itself void CIrrDeviceLinux::closeDevice() { Close = true; } - //! returns if window is active. if not, nothing need to be drawn bool CIrrDeviceLinux::isWindowActive() const { return (WindowHasFocus && !WindowMinimized); } - //! returns if window has focus. bool CIrrDeviceLinux::isWindowFocused() const { return WindowHasFocus; } - //! returns if window is minimized. bool CIrrDeviceLinux::isWindowMinimized() const { return WindowMinimized; } - //! returns last state from maximizeWindow() and restoreWindow() bool CIrrDeviceLinux::isWindowMaximized() const { return WindowMaximized; } - //! returns color format of the window. video::ECOLOR_FORMAT CIrrDeviceLinux::getColorFormat() const { @@ -1333,26 +1233,22 @@ video::ECOLOR_FORMAT CIrrDeviceLinux::getColorFormat() const return video::ECF_R5G6B5; } - //! Sets if the window should be resizable in windowed mode. void CIrrDeviceLinux::setResizable(bool resize) { #ifdef _IRR_COMPILE_WITH_X11_ - if (CreationParams.DriverType == video::EDT_NULL || CreationParams.Fullscreen ) + if (CreationParams.DriverType == video::EDT_NULL || CreationParams.Fullscreen) return; - if ( !resize ) - { + if (!resize) { // Must be heap memory because data size depends on X Server XSizeHints *hints = XAllocSizeHints(); - hints->flags=PSize|PMinSize|PMaxSize; - hints->min_width=hints->max_width=hints->base_width=Width; - hints->min_height=hints->max_height=hints->base_height=Height; + hints->flags = PSize | PMinSize | PMaxSize; + hints->min_width = hints->max_width = hints->base_width = Width; + hints->min_height = hints->max_height = hints->base_height = Height; XSetWMNormalHints(XDisplay, XWindow, hints); XFree(hints); - } - else - { + } else { XSetWMNormalHints(XDisplay, XWindow, StdHints); } XFlush(XDisplay); @@ -1360,10 +1256,10 @@ void CIrrDeviceLinux::setResizable(bool resize) } //! Resize the render window. -void CIrrDeviceLinux::setWindowSize(const irr::core::dimension2d& size) +void CIrrDeviceLinux::setWindowSize(const irr::core::dimension2d &size) { #ifdef _IRR_COMPILE_WITH_X11_ - if (CreationParams.DriverType == video::EDT_NULL || CreationParams.Fullscreen ) + if (CreationParams.DriverType == video::EDT_NULL || CreationParams.Fullscreen) return; XWindowChanges values; @@ -1374,7 +1270,6 @@ void CIrrDeviceLinux::setWindowSize(const irr::core::dimension2d& size) #endif // #ifdef _IRR_COMPILE_WITH_X11_ } - //! Minimize window void CIrrDeviceLinux::minimizeWindow() { @@ -1383,14 +1278,12 @@ void CIrrDeviceLinux::minimizeWindow() #endif } - //! Maximize window void CIrrDeviceLinux::maximizeWindow() { #ifdef _IRR_COMPILE_WITH_X11_ // Maximize is not implemented in bare X, it's a WM construct. - if (HasNetWM) - { + if (HasNetWM) { XEvent ev = {0}; ev.type = ClientMessage; @@ -1402,7 +1295,7 @@ void CIrrDeviceLinux::maximizeWindow() ev.xclient.data.l[2] = X_ATOM_NETWM_MAXIMIZE_HORZ; XSendEvent(XDisplay, DefaultRootWindow(XDisplay), false, - SubstructureNotifyMask|SubstructureRedirectMask, &ev); + SubstructureNotifyMask | SubstructureRedirectMask, &ev); } XMapWindow(XDisplay, XWindow); @@ -1411,14 +1304,12 @@ void CIrrDeviceLinux::maximizeWindow() #endif } - //! Restore original window size void CIrrDeviceLinux::restoreWindow() { #ifdef _IRR_COMPILE_WITH_X11_ // Maximize is not implemented in bare X, it's a WM construct. - if (HasNetWM) - { + if (HasNetWM) { XEvent ev = {0}; ev.type = ClientMessage; @@ -1430,7 +1321,7 @@ void CIrrDeviceLinux::restoreWindow() ev.xclient.data.l[2] = X_ATOM_NETWM_MAXIMIZE_HORZ; XSendEvent(XDisplay, DefaultRootWindow(XDisplay), false, - SubstructureNotifyMask|SubstructureRedirectMask, &ev); + SubstructureNotifyMask | SubstructureRedirectMask, &ev); } XMapWindow(XDisplay, XWindow); @@ -1545,22 +1436,22 @@ void CIrrDeviceLinux::createKeyMap() KeyMap.push_back(SKeyMap(XK_ISO_Level3_Shift, KEY_RMENU)); KeyMap.push_back(SKeyMap(XK_Menu, KEY_MENU)); KeyMap.push_back(SKeyMap(XK_space, KEY_SPACE)); - KeyMap.push_back(SKeyMap(XK_exclam, 0)); //? + KeyMap.push_back(SKeyMap(XK_exclam, 0)); //? KeyMap.push_back(SKeyMap(XK_quotedbl, 0)); //? - KeyMap.push_back(SKeyMap(XK_section, 0)); //? + KeyMap.push_back(SKeyMap(XK_section, 0)); //? KeyMap.push_back(SKeyMap(XK_numbersign, KEY_OEM_2)); - KeyMap.push_back(SKeyMap(XK_dollar, 0)); //? - KeyMap.push_back(SKeyMap(XK_percent, 0)); //? + KeyMap.push_back(SKeyMap(XK_dollar, 0)); //? + KeyMap.push_back(SKeyMap(XK_percent, 0)); //? KeyMap.push_back(SKeyMap(XK_ampersand, 0)); //? KeyMap.push_back(SKeyMap(XK_apostrophe, KEY_OEM_7)); - KeyMap.push_back(SKeyMap(XK_parenleft, 0)); //? - KeyMap.push_back(SKeyMap(XK_parenright, 0)); //? - KeyMap.push_back(SKeyMap(XK_asterisk, 0)); //? - KeyMap.push_back(SKeyMap(XK_plus, KEY_PLUS)); //? - KeyMap.push_back(SKeyMap(XK_comma, KEY_COMMA)); //? - KeyMap.push_back(SKeyMap(XK_minus, KEY_MINUS)); //? + KeyMap.push_back(SKeyMap(XK_parenleft, 0)); //? + KeyMap.push_back(SKeyMap(XK_parenright, 0)); //? + KeyMap.push_back(SKeyMap(XK_asterisk, 0)); //? + KeyMap.push_back(SKeyMap(XK_plus, KEY_PLUS)); //? + KeyMap.push_back(SKeyMap(XK_comma, KEY_COMMA)); //? + KeyMap.push_back(SKeyMap(XK_minus, KEY_MINUS)); //? KeyMap.push_back(SKeyMap(XK_period, KEY_PERIOD)); //? - KeyMap.push_back(SKeyMap(XK_slash, KEY_OEM_2)); //? + KeyMap.push_back(SKeyMap(XK_slash, KEY_OEM_2)); //? KeyMap.push_back(SKeyMap(XK_0, KEY_KEY_0)); KeyMap.push_back(SKeyMap(XK_1, KEY_KEY_1)); KeyMap.push_back(SKeyMap(XK_2, KEY_KEY_2)); @@ -1575,11 +1466,11 @@ void CIrrDeviceLinux::createKeyMap() KeyMap.push_back(SKeyMap(XK_semicolon, KEY_OEM_1)); KeyMap.push_back(SKeyMap(XK_less, KEY_OEM_102)); KeyMap.push_back(SKeyMap(XK_equal, KEY_PLUS)); - KeyMap.push_back(SKeyMap(XK_greater, 0)); //? - KeyMap.push_back(SKeyMap(XK_question, 0)); //? + KeyMap.push_back(SKeyMap(XK_greater, 0)); //? + KeyMap.push_back(SKeyMap(XK_question, 0)); //? KeyMap.push_back(SKeyMap(XK_at, KEY_KEY_2)); //? - KeyMap.push_back(SKeyMap(XK_mu, 0)); //? - KeyMap.push_back(SKeyMap(XK_EuroSign, 0)); //? + KeyMap.push_back(SKeyMap(XK_mu, 0)); //? + KeyMap.push_back(SKeyMap(XK_EuroSign, 0)); //? KeyMap.push_back(SKeyMap(XK_A, KEY_KEY_A)); KeyMap.push_back(SKeyMap(XK_B, KEY_KEY_B)); KeyMap.push_back(SKeyMap(XK_C, KEY_KEY_C)); @@ -1611,7 +1502,7 @@ void CIrrDeviceLinux::createKeyMap() KeyMap.push_back(SKeyMap(XK_bracketright, KEY_OEM_6)); KeyMap.push_back(SKeyMap(XK_asciicircum, KEY_OEM_5)); KeyMap.push_back(SKeyMap(XK_dead_circumflex, KEY_OEM_5)); - KeyMap.push_back(SKeyMap(XK_degree, 0)); //? + KeyMap.push_back(SKeyMap(XK_degree, 0)); //? KeyMap.push_back(SKeyMap(XK_underscore, KEY_MINUS)); //? KeyMap.push_back(SKeyMap(XK_grave, KEY_OEM_3)); KeyMap.push_back(SKeyMap(XK_dead_grave, KEY_OEM_3)); @@ -1654,15 +1545,14 @@ void CIrrDeviceLinux::createKeyMap() #endif } -bool CIrrDeviceLinux::activateJoysticks(core::array & joystickInfo) +bool CIrrDeviceLinux::activateJoysticks(core::array &joystickInfo) { -#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) joystickInfo.clear(); u32 joystick; - for (joystick = 0; joystick < 32; ++joystick) - { + for (joystick = 0; joystick < 32; ++joystick) { // The joystick device could be here... core::stringc devName = "/dev/js"; devName += joystick; @@ -1671,15 +1561,13 @@ bool CIrrDeviceLinux::activateJoysticks(core::array & joystickInf JoystickInfo info; info.fd = open(devName.c_str(), O_RDONLY); - if (-1 == info.fd) - { + if (-1 == info.fd) { // ...but Ubuntu and possibly other distros // create the devices in /dev/input devName = "/dev/input/js"; devName += joystick; info.fd = open(devName.c_str(), O_RDONLY); - if (-1 == info.fd) - { + if (-1 == info.fd) { // and BSD here devName = "/dev/joy"; devName += joystick; @@ -1691,12 +1579,12 @@ bool CIrrDeviceLinux::activateJoysticks(core::array & joystickInf continue; #ifdef __FreeBSD__ - info.axes=2; - info.buttons=2; + info.axes = 2; + info.buttons = 2; #else - ioctl( info.fd, JSIOCGAXES, &(info.axes) ); - ioctl( info.fd, JSIOCGBUTTONS, &(info.buttons) ); - fcntl( info.fd, F_SETFL, O_NONBLOCK ); + ioctl(info.fd, JSIOCGAXES, &(info.axes)); + ioctl(info.fd, JSIOCGBUTTONS, &(info.buttons)); + fcntl(info.fd, F_SETFL, O_NONBLOCK); #endif (void)memset(&info.persistentData, 0, sizeof(info.persistentData)); @@ -1716,19 +1604,18 @@ bool CIrrDeviceLinux::activateJoysticks(core::array & joystickInf #ifndef __FreeBSD__ char name[80]; - ioctl( info.fd, JSIOCGNAME(80), name); + ioctl(info.fd, JSIOCGNAME(80), name); returnInfo.Name = name; #endif joystickInfo.push_back(returnInfo); } - for (joystick = 0; joystick < joystickInfo.size(); ++joystick) - { + for (joystick = 0; joystick < joystickInfo.size(); ++joystick) { char logString[256]; snprintf_irr(logString, sizeof(logString), "Found joystick %d, %d axes, %d buttons '%s'", - joystick, joystickInfo[joystick].Axes, - joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); + joystick, joystickInfo[joystick].Axes, + joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); os::Printer::log(logString, ELL_INFORMATION); } @@ -1738,36 +1625,31 @@ bool CIrrDeviceLinux::activateJoysticks(core::array & joystickInf #endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ } - void CIrrDeviceLinux::pollJoysticks() { -#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) if (0 == ActiveJoysticks.size()) return; - for (u32 j= 0; j< ActiveJoysticks.size(); ++j) - { - JoystickInfo & info = ActiveJoysticks[j]; + for (u32 j = 0; j < ActiveJoysticks.size(); ++j) { + JoystickInfo &info = ActiveJoysticks[j]; #ifdef __FreeBSD__ struct joystick js; - if (read(info.fd, &js, sizeof(js)) == sizeof(js)) - { + if (read(info.fd, &js, sizeof(js)) == sizeof(js)) { info.persistentData.JoystickEvent.ButtonStates = js.b1 | (js.b2 << 1); /* should be a two-bit field */ - info.persistentData.JoystickEvent.Axis[0] = js.x; /* X axis */ - info.persistentData.JoystickEvent.Axis[1] = js.y; /* Y axis */ + info.persistentData.JoystickEvent.Axis[0] = js.x; /* X axis */ + info.persistentData.JoystickEvent.Axis[1] = js.y; /* Y axis */ } #else struct js_event event; - while (sizeof(event) == read(info.fd, &event, sizeof(event))) - { - switch(event.type & ~JS_EVENT_INIT) - { + while (sizeof(event) == read(info.fd, &event, sizeof(event))) { + switch (event.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: if (event.value) - info.persistentData.JoystickEvent.ButtonStates |= (1 << event.number); + info.persistentData.JoystickEvent.ButtonStates |= (1 << event.number); else - info.persistentData.JoystickEvent.ButtonStates &= ~(1 << event.number); + info.persistentData.JoystickEvent.ButtonStates &= ~(1 << event.number); break; case JS_EVENT_AXIS: @@ -1787,7 +1669,6 @@ void CIrrDeviceLinux::pollJoysticks() #endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ } - #if defined(_IRR_COMPILE_WITH_X11_) //! gets text from the clipboard //! \return Returns 0 if no string is in there, otherwise utf-8 text. @@ -1814,18 +1695,20 @@ const c8 *CIrrDeviceLinux::getTextFromSelection(Atom selection, core::stringc &t // wait for event via a blocking call XEvent event_ret; std::pair args(XWindow, selection); - XIfEvent(XDisplay, &event_ret, [](Display *_display, XEvent *event, XPointer arg) { - auto p = reinterpret_cast *>(arg); - return (Bool) (event->type == SelectionNotify && - event->xselection.requestor == p->first && - event->xselection.selection == p->second && - event->xselection.target == X_ATOM_UTF8_STRING); - }, (XPointer)&args); + XIfEvent( + XDisplay, &event_ret, [](Display *_display, XEvent *event, XPointer arg) { + auto p = reinterpret_cast *>(arg); + return (Bool)(event->type == SelectionNotify && + event->xselection.requestor == p->first && + event->xselection.selection == p->second && + event->xselection.target == X_ATOM_UTF8_STRING); + }, + (XPointer)&args); _IRR_DEBUG_BREAK_IF(!(event_ret.type == SelectionNotify && - event_ret.xselection.requestor == XWindow && - event_ret.xselection.selection == selection && - event_ret.xselection.target == X_ATOM_UTF8_STRING)); + event_ret.xselection.requestor == XWindow && + event_ret.xselection.selection == selection && + event_ret.xselection.target == X_ATOM_UTF8_STRING)); Atom property_set = event_ret.xselection.property; if (event_ret.xselection.property == None) { @@ -1838,17 +1721,17 @@ const c8 *CIrrDeviceLinux::getTextFromSelection(Atom selection, core::stringc &t int format; unsigned long numItems, bytesLeft, dummy; unsigned char *data = nullptr; - XGetWindowProperty (XDisplay, XWindow, - property_set, // property name - 0, // offset - 0, // length (we only check for data, so 0) - 0, // Delete 0==false + XGetWindowProperty(XDisplay, XWindow, + property_set, // property name + 0, // offset + 0, // length (we only check for data, so 0) + 0, // Delete 0==false AnyPropertyType, // AnyPropertyType or property identifier - &type, // return type - &format, // return format - &numItems, // number items - &bytesLeft, // remaining bytes for partial reads - &data); // data + &type, // return type + &format, // return format + &numItems, // number items + &bytesLeft, // remaining bytes for partial reads + &data); // data if (data) { XFree(data); data = nullptr; @@ -1856,10 +1739,10 @@ const c8 *CIrrDeviceLinux::getTextFromSelection(Atom selection, core::stringc &t // for debugging: //~ { - //~ char *type_name = XGetAtomName(XDisplay, type); - //~ fprintf(stderr, "CIrrDeviceLinux::getTextFromSelection: actual type: %s (=%ld)\n", - //~ type_name, type); - //~ XFree(type_name); + //~ char *type_name = XGetAtomName(XDisplay, type); + //~ fprintf(stderr, "CIrrDeviceLinux::getTextFromSelection: actual type: %s (=%ld)\n", + //~ type_name, type); + //~ XFree(type_name); //~ } if (type != X_ATOM_UTF8_STRING && type != X_ATOM_UTF8_MIME_TYPE) { @@ -1870,12 +1753,12 @@ const c8 *CIrrDeviceLinux::getTextFromSelection(Atom selection, core::stringc &t if (bytesLeft > 0) { // there is some data to get - int result = XGetWindowProperty (XDisplay, XWindow, property_set, 0, - bytesLeft, 0, AnyPropertyType, &type, &format, - &numItems, &dummy, &data); + int result = XGetWindowProperty(XDisplay, XWindow, property_set, 0, + bytesLeft, 0, AnyPropertyType, &type, &format, + &numItems, &dummy, &data); if (result == Success) text_buffer = (irr::c8 *)data; - XFree (data); + XFree(data); } // delete the property again, to inform the owner about the successful transfer @@ -1910,8 +1793,8 @@ const c8 *CIrrDeviceLinux::getTextFromPrimarySelection() const #if defined(_IRR_COMPILE_WITH_X11_) bool CIrrDeviceLinux::becomeSelectionOwner(Atom selection) const { - XSetSelectionOwner (XDisplay, selection, XWindow, CurrentTime); - XFlush (XDisplay); + XSetSelectionOwner(XDisplay, selection, XWindow, CurrentTime); + XFlush(XDisplay); Window owner = XGetSelectionOwner(XDisplay, selection); return owner == XWindow; } @@ -1945,9 +1828,8 @@ void CIrrDeviceLinux::copyToPrimarySelection(const c8 *text) const // return true if the passed event has the type passed in parameter arg Bool PredicateIsEventType(Display *display, XEvent *event, XPointer arg) { - if ( event && event->type == *(int*)arg ) - { -// os::Printer::log("remove event", core::stringc((int)arg).c_str(), ELL_INFORMATION); + if (event && event->type == *(int *)arg) { + // os::Printer::log("remove event", core::stringc((int)arg).c_str(), ELL_INFORMATION); return True; } return False; @@ -1958,19 +1840,23 @@ Bool PredicateIsEventType(Display *display, XEvent *event, XPointer arg) void CIrrDeviceLinux::clearSystemMessages() { #ifdef _IRR_COMPILE_WITH_X11_ - if (CreationParams.DriverType != video::EDT_NULL) - { + if (CreationParams.DriverType != video::EDT_NULL) { XEvent event; int usrArg = ButtonPress; - while ( XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {} + while (XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True) { + } usrArg = ButtonRelease; - while ( XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {} + while (XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True) { + } usrArg = MotionNotify; - while ( XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {} + while (XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True) { + } usrArg = KeyRelease; - while ( XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {} + while (XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True) { + } usrArg = KeyPress; - while ( XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True ) {} + while (XCheckIfEvent(XDisplay, &event, PredicateIsEventType, XPointer(&usrArg)) == True) { + } } #endif //_IRR_COMPILE_WITH_X11_ } @@ -2015,10 +1901,9 @@ void CIrrDeviceLinux::initXAtoms() void CIrrDeviceLinux::initXInput2() { #if defined(_IRR_LINUX_X11_XINPUT2_) - int ev=0; - int err=0; - if (!XQueryExtension(XDisplay, "XInputExtension", &XI_EXTENSIONS_OPCODE, &ev, &err)) - { + int ev = 0; + int err = 0; + if (!XQueryExtension(XDisplay, "XInputExtension", &XI_EXTENSIONS_OPCODE, &ev, &err)) { os::Printer::log("X Input extension not available.", ELL_WARNING); return; } @@ -2026,8 +1911,7 @@ void CIrrDeviceLinux::initXInput2() int major = 2; int minor = 3; int rc = XIQueryVersion(XDisplay, &major, &minor); - if ( rc != Success ) - { + if (rc != Success) { os::Printer::log("No XI2 support.", ELL_WARNING); return; } @@ -2048,26 +1932,25 @@ void CIrrDeviceLinux::initXInput2() #endif } - #ifdef _IRR_COMPILE_WITH_X11_ -Cursor CIrrDeviceLinux::TextureToMonochromeCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot) +Cursor CIrrDeviceLinux::TextureToMonochromeCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot) { - XImage * sourceImage = XCreateImage(XDisplay, VisualInfo->visual, - 1, // depth, - ZPixmap, // XYBitmap (depth=1), ZPixmap(depth=x) - 0, 0, sourceRect.getWidth(), sourceRect.getHeight(), - 32, // bitmap_pad, - 0// bytes_per_line (0 means continuous in memory) - ); + XImage *sourceImage = XCreateImage(XDisplay, VisualInfo->visual, + 1, // depth, + ZPixmap, // XYBitmap (depth=1), ZPixmap(depth=x) + 0, 0, sourceRect.getWidth(), sourceRect.getHeight(), + 32, // bitmap_pad, + 0 // bytes_per_line (0 means continuous in memory) + ); sourceImage->data = new char[sourceImage->height * sourceImage->bytes_per_line]; - XImage * maskImage = XCreateImage(XDisplay, VisualInfo->visual, - 1, // depth, - ZPixmap, - 0, 0, sourceRect.getWidth(), sourceRect.getHeight(), - 32, // bitmap_pad, - 0 // bytes_per_line - ); + XImage *maskImage = XCreateImage(XDisplay, VisualInfo->visual, + 1, // depth, + ZPixmap, + 0, 0, sourceRect.getWidth(), sourceRect.getHeight(), + 32, // bitmap_pad, + 0 // bytes_per_line + ); maskImage->data = new char[maskImage->height * maskImage->bytes_per_line]; // write texture into XImage @@ -2075,25 +1958,22 @@ Cursor CIrrDeviceLinux::TextureToMonochromeCursor(irr::video::ITexture * tex, co u32 bytesPerPixel = video::IImage::getBitsPerPixelFromFormat(format) / 8; u32 bytesLeftGap = sourceRect.UpperLeftCorner.X * bytesPerPixel; u32 bytesRightGap = tex->getPitch() - sourceRect.LowerRightCorner.X * bytesPerPixel; - const u8* data = (const u8*)tex->lock(video::ETLM_READ_ONLY, 0); - data += sourceRect.UpperLeftCorner.Y*tex->getPitch(); - for ( s32 y = 0; y < sourceRect.getHeight(); ++y ) - { + const u8 *data = (const u8 *)tex->lock(video::ETLM_READ_ONLY, 0); + data += sourceRect.UpperLeftCorner.Y * tex->getPitch(); + for (s32 y = 0; y < sourceRect.getHeight(); ++y) { data += bytesLeftGap; - for ( s32 x = 0; x < sourceRect.getWidth(); ++x ) - { + for (s32 x = 0; x < sourceRect.getWidth(); ++x) { video::SColor pixelCol; - pixelCol.setData((const void*)data, format); + pixelCol.setData((const void *)data, format); data += bytesPerPixel; - if ( pixelCol.getAlpha() == 0 ) // transparent + if (pixelCol.getAlpha() == 0) // transparent { XPutPixel(maskImage, x, y, 0); XPutPixel(sourceImage, x, y, 0); - } - else // color + } else // color { - if ( pixelCol.getAverage() >= 127 ) + if (pixelCol.getAverage() >= 127) XPutPixel(sourceImage, x, y, 1); else XPutPixel(sourceImage, x, y, 0); @@ -2110,7 +1990,7 @@ Cursor CIrrDeviceLinux::TextureToMonochromeCursor(irr::video::ITexture * tex, co XGCValues values; values.foreground = 1; values.background = 1; - GC gc = XCreateGC( XDisplay, sourcePixmap, GCForeground | GCBackground, &values ); + GC gc = XCreateGC(XDisplay, sourcePixmap, GCForeground | GCBackground, &values); XPutImage(XDisplay, sourcePixmap, gc, sourceImage, 0, 0, 0, 0, sourceImage->width, sourceImage->height); XPutImage(XDisplay, maskPixmap, gc, maskImage, 0, 0, 0, 0, maskImage->width, maskImage->height); @@ -2139,9 +2019,9 @@ Cursor CIrrDeviceLinux::TextureToMonochromeCursor(irr::video::ITexture * tex, co } #ifdef _IRR_LINUX_XCURSOR_ -Cursor CIrrDeviceLinux::TextureToARGBCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot) +Cursor CIrrDeviceLinux::TextureToARGBCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot) { - XcursorImage * image = XcursorImageCreate (sourceRect.getWidth(), sourceRect.getHeight()); + XcursorImage *image = XcursorImageCreate(sourceRect.getWidth(), sourceRect.getHeight()); image->xhot = hotspot.X; image->yhot = hotspot.Y; @@ -2150,16 +2030,14 @@ Cursor CIrrDeviceLinux::TextureToARGBCursor(irr::video::ITexture * tex, const co u32 bytesPerPixel = video::IImage::getBitsPerPixelFromFormat(format) / 8; u32 bytesLeftGap = sourceRect.UpperLeftCorner.X * bytesPerPixel; u32 bytesRightGap = tex->getPitch() - sourceRect.LowerRightCorner.X * bytesPerPixel; - XcursorPixel* target = image->pixels; - const u8* data = (const u8*)tex->lock(video::ETLM_READ_ONLY, 0); - data += sourceRect.UpperLeftCorner.Y*tex->getPitch(); - for ( s32 y = 0; y < sourceRect.getHeight(); ++y ) - { + XcursorPixel *target = image->pixels; + const u8 *data = (const u8 *)tex->lock(video::ETLM_READ_ONLY, 0); + data += sourceRect.UpperLeftCorner.Y * tex->getPitch(); + for (s32 y = 0; y < sourceRect.getHeight(); ++y) { data += bytesLeftGap; - for ( s32 x = 0; x < sourceRect.getWidth(); ++x ) - { + for (s32 x = 0; x < sourceRect.getWidth(); ++x) { video::SColor pixelCol; - pixelCol.setData((const void*)data, format); + pixelCol.setData((const void *)data, format); data += bytesPerPixel; *target = (XcursorPixel)pixelCol.color; @@ -2169,50 +2047,46 @@ Cursor CIrrDeviceLinux::TextureToARGBCursor(irr::video::ITexture * tex, const co } tex->unlock(); - Cursor cursorResult=XcursorImageLoadCursor(XDisplay, image); + Cursor cursorResult = XcursorImageLoadCursor(XDisplay, image); XcursorImageDestroy(image); - return cursorResult; } #endif // #ifdef _IRR_LINUX_XCURSOR_ -Cursor CIrrDeviceLinux::TextureToCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot) +Cursor CIrrDeviceLinux::TextureToCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot) { #ifdef _IRR_LINUX_XCURSOR_ - return TextureToARGBCursor( tex, sourceRect, hotspot ); + return TextureToARGBCursor(tex, sourceRect, hotspot); #else - return TextureToMonochromeCursor( tex, sourceRect, hotspot ); + return TextureToMonochromeCursor(tex, sourceRect, hotspot); #endif } -#endif // _IRR_COMPILE_WITH_X11_ +#endif // _IRR_COMPILE_WITH_X11_ - -CIrrDeviceLinux::CCursorControl::CCursorControl(CIrrDeviceLinux* dev, bool null) - : Device(dev) +CIrrDeviceLinux::CCursorControl::CCursorControl(CIrrDeviceLinux *dev, bool null) : + Device(dev) #ifdef _IRR_COMPILE_WITH_X11_ - , PlatformBehavior(gui::ECPB_NONE), LastQuery(0) + , + PlatformBehavior(gui::ECPB_NONE), LastQuery(0) #ifdef _IRR_LINUX_X11_XINPUT2_ - , DeviceId(0) + , + DeviceId(0) #endif #endif - , IsVisible(true), Null(null), UseReferenceRect(false) - , ActiveIcon(gui::ECI_NORMAL), ActiveIconStartTime(0) + , + IsVisible(true), Null(null), UseReferenceRect(false), ActiveIcon(gui::ECI_NORMAL), ActiveIconStartTime(0) { #ifdef _IRR_COMPILE_WITH_X11_ - if (!Null) - { + if (!Null) { #ifdef _IRR_LINUX_X11_XINPUT2_ // XIWarpPointer is entirely broken on multi-head setups (see also [1]), // but behaves better in other cases so we can't just disable it outright. // [1] https://developer.blender.org/rB165caafb99c6846e53d11c4e966990aaffc06cea - if (XScreenCount(Device->XDisplay) > 1) - { + if (XScreenCount(Device->XDisplay) > 1) { os::Printer::log("Detected classic multi-head setup, not using XIWarpPointer"); - } - else - { + } else { XIGetClientPointer(Device->XDisplay, Device->XWindow, &DeviceId); } #endif @@ -2225,20 +2099,19 @@ CIrrDeviceLinux::CCursorControl::CCursorControl(CIrrDeviceLinux* dev, bool null) // this code, for making the cursor invisible was sent in by // Sirshane, thank your very much! - Pixmap invisBitmap = XCreatePixmap(Device->XDisplay, Device->XWindow, 32, 32, 1); Pixmap maskBitmap = XCreatePixmap(Device->XDisplay, Device->XWindow, 32, 32, 1); - Colormap screen_colormap = DefaultColormap( Device->XDisplay, DefaultScreen( Device->XDisplay ) ); - XAllocNamedColor( Device->XDisplay, screen_colormap, "black", &fg, &fg ); - XAllocNamedColor( Device->XDisplay, screen_colormap, "white", &bg, &bg ); + Colormap screen_colormap = DefaultColormap(Device->XDisplay, DefaultScreen(Device->XDisplay)); + XAllocNamedColor(Device->XDisplay, screen_colormap, "black", &fg, &fg); + XAllocNamedColor(Device->XDisplay, screen_colormap, "white", &bg, &bg); - GC gc = XCreateGC( Device->XDisplay, invisBitmap, valuemask, &values ); + GC gc = XCreateGC(Device->XDisplay, invisBitmap, valuemask, &values); - XSetForeground( Device->XDisplay, gc, BlackPixel( Device->XDisplay, DefaultScreen( Device->XDisplay ) ) ); - XFillRectangle( Device->XDisplay, invisBitmap, gc, 0, 0, 32, 32 ); - XFillRectangle( Device->XDisplay, maskBitmap, gc, 0, 0, 32, 32 ); + XSetForeground(Device->XDisplay, gc, BlackPixel(Device->XDisplay, DefaultScreen(Device->XDisplay))); + XFillRectangle(Device->XDisplay, invisBitmap, gc, 0, 0, 32, 32); + XFillRectangle(Device->XDisplay, maskBitmap, gc, 0, 0, 32, 32); - InvisCursor = XCreatePixmapCursor( Device->XDisplay, invisBitmap, maskBitmap, &fg, &bg, 1, 1 ); + InvisCursor = XCreatePixmapCursor(Device->XDisplay, invisBitmap, maskBitmap, &fg, &bg, 1, 1); XFreeGC(Device->XDisplay, gc); XFreePixmap(Device->XDisplay, invisBitmap); XFreePixmap(Device->XDisplay, maskBitmap); @@ -2259,10 +2132,8 @@ void CIrrDeviceLinux::CCursorControl::clearCursors() { if (!Null) XFreeCursor(Device->XDisplay, InvisCursor); - for ( u32 i=0; i < Cursors.size(); ++i ) - { - for ( u32 f=0; f < Cursors[i].Frames.size(); ++f ) - { + for (u32 i = 0; i < Cursors.size(); ++i) { + for (u32 f = 0; f < Cursors[i].Frames.size(); ++f) { XFreeCursor(Device->XDisplay, Cursors[i].Frames[f].IconHW); } } @@ -2270,25 +2141,24 @@ void CIrrDeviceLinux::CCursorControl::clearCursors() void CIrrDeviceLinux::CCursorControl::initCursors() { - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_left_arrow)) ); // (or XC_arrow?) - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_crosshair)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_hand2)) ); // (or XC_hand1? ) - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_question_arrow)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_xterm)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_X_cursor)) ); // (or XC_pirate?) - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_watch)) ); // (or XC_clock?) - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_fleur)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_right_corner)) ); // NESW not available in X11 - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_left_corner)) ); // NWSE not available in X11 - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_v_double_arrow)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_h_double_arrow)) ); - Cursors.push_back( CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_up_arrow)) ); // (or XC_center_ptr?) + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_left_arrow))); // (or XC_arrow?) + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_crosshair))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_hand2))); // (or XC_hand1? ) + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_question_arrow))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_xterm))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_X_cursor))); // (or XC_pirate?) + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_watch))); // (or XC_clock?) + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_fleur))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_right_corner))); // NESW not available in X11 + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_top_left_corner))); // NWSE not available in X11 + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_v_double_arrow))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_h_double_arrow))); + Cursors.push_back(CursorX11(XCreateFontCursor(Device->XDisplay, XC_sb_up_arrow))); // (or XC_center_ptr?) } void CIrrDeviceLinux::CCursorControl::update() { - if ( (u32)ActiveIcon < Cursors.size() && !Cursors[ActiveIcon].Frames.empty() && Cursors[ActiveIcon].FrameTime ) - { + if ((u32)ActiveIcon < Cursors.size() && !Cursors[ActiveIcon].Frames.empty() && Cursors[ActiveIcon].FrameTime) { // update animated cursors. This could also be done by X11 in case someone wants to figure that out (this way was just easier to implement) u32 now = Device->getTimer()->getRealTime(); u32 frame = ((now - ActiveIconStartTime) / Cursors[ActiveIcon].FrameTime) % Cursors[ActiveIcon].Frames.size(); @@ -2301,10 +2171,10 @@ void CIrrDeviceLinux::CCursorControl::update() void CIrrDeviceLinux::CCursorControl::setActiveIcon(gui::ECURSOR_ICON iconId) { #ifdef _IRR_COMPILE_WITH_X11_ - if ( iconId >= (s32)Cursors.size() ) + if (iconId >= (s32)Cursors.size()) return; - if ( Cursors[iconId].Frames.size() ) + if (Cursors[iconId].Frames.size()) XDefineCursor(Device->XDisplay, Device->XWindow, Cursors[iconId].Frames[0].IconHW); ActiveIconStartTime = Device->getTimer()->getRealTime(); @@ -2312,25 +2182,22 @@ void CIrrDeviceLinux::CCursorControl::setActiveIcon(gui::ECURSOR_ICON iconId) #endif } - //! Add a custom sprite as cursor icon. -gui::ECURSOR_ICON CIrrDeviceLinux::CCursorControl::addIcon(const gui::SCursorSprite& icon) +gui::ECURSOR_ICON CIrrDeviceLinux::CCursorControl::addIcon(const gui::SCursorSprite &icon) { #ifdef _IRR_COMPILE_WITH_X11_ - if ( icon.SpriteId >= 0 ) - { + if (icon.SpriteId >= 0) { CursorX11 cX11; cX11.FrameTime = icon.SpriteBank->getSprites()[icon.SpriteId].frameTime; - for ( u32 i=0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i ) - { + for (u32 i = 0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i) { irr::u32 texId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].textureNumber; irr::u32 rectId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].rectNumber; irr::core::rect rectIcon = icon.SpriteBank->getPositions()[rectId]; Cursor cursor = Device->TextureToCursor(icon.SpriteBank->getTexture(texId), rectIcon, icon.HotSpot); - cX11.Frames.push_back( CursorFrameX11(cursor) ); + cX11.Frames.push_back(CursorFrameX11(cursor)); } - Cursors.push_back( cX11 ); + Cursors.push_back(cX11); return (gui::ECURSOR_ICON)(Cursors.size() - 1); } @@ -2339,26 +2206,24 @@ gui::ECURSOR_ICON CIrrDeviceLinux::CCursorControl::addIcon(const gui::SCursorSpr } //! replace the given cursor icon. -void CIrrDeviceLinux::CCursorControl::changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite& icon) +void CIrrDeviceLinux::CCursorControl::changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite &icon) { #ifdef _IRR_COMPILE_WITH_X11_ - if ( iconId >= (s32)Cursors.size() ) + if (iconId >= (s32)Cursors.size()) return; - for ( u32 i=0; i < Cursors[iconId].Frames.size(); ++i ) + for (u32 i = 0; i < Cursors[iconId].Frames.size(); ++i) XFreeCursor(Device->XDisplay, Cursors[iconId].Frames[i].IconHW); - if ( icon.SpriteId >= 0 ) - { + if (icon.SpriteId >= 0) { CursorX11 cX11; cX11.FrameTime = icon.SpriteBank->getSprites()[icon.SpriteId].frameTime; - for ( u32 i=0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i ) - { + for (u32 i = 0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i) { irr::u32 texId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].textureNumber; irr::u32 rectId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].rectNumber; irr::core::rect rectIcon = icon.SpriteBank->getPositions()[rectId]; Cursor cursor = Device->TextureToCursor(icon.SpriteBank->getTexture(texId), rectIcon, icon.HotSpot); - cX11.Frames.push_back( CursorFrameX11(cursor) ); + cX11.Frames.push_back(CursorFrameX11(cursor)); } Cursors[iconId] = cX11; @@ -2369,7 +2234,7 @@ void CIrrDeviceLinux::CCursorControl::changeIcon(gui::ECURSOR_ICON iconId, const irr::core::dimension2di CIrrDeviceLinux::CCursorControl::getSupportedIconSize() const { // this returns the closest match that is smaller or same size, so we just pass a value which should be large enough for cursors - unsigned int width=0, height=0; + unsigned int width = 0, height = 0; #ifdef _IRR_COMPILE_WITH_X11_ XQueryBestCursor(Device->XDisplay, Device->XWindow, 64, 64, &width, &height); #endif @@ -2379,4 +2244,3 @@ irr::core::dimension2di CIrrDeviceLinux::CCursorControl::getSupportedIconSize() } // end namespace #endif // _IRR_COMPILE_WITH_X11_DEVICE_ - diff --git a/source/Irrlicht/CIrrDeviceLinux.h b/source/Irrlicht/CIrrDeviceLinux.h index 9c0e7e6d..4aac1cf6 100644 --- a/source/Irrlicht/CIrrDeviceLinux.h +++ b/source/Irrlicht/CIrrDeviceLinux.h @@ -29,204 +29,197 @@ namespace irr { - class CIrrDeviceLinux : public CIrrDeviceStub +class CIrrDeviceLinux : public CIrrDeviceStub +{ +public: + //! constructor + CIrrDeviceLinux(const SIrrlichtCreationParameters ¶m); + + //! destructor + virtual ~CIrrDeviceLinux(); + + //! runs the device. Returns false if device wants to be deleted + bool run() override; + + //! Cause the device to temporarily pause execution and let other processes to run + // This should bring down processor usage without major performance loss for Irrlicht + void yield() override; + + //! Pause execution and let other processes to run for a specified amount of time. + void sleep(u32 timeMs, bool pauseTimer) override; + + //! sets the caption of the window + void setWindowCaption(const wchar_t *text) override; + + //! Sets the window icon. + bool setWindowIcon(const video::IImage *img) override; + + //! returns if window is active. if not, nothing need to be drawn + bool isWindowActive() const override; + + //! returns if window has focus. + bool isWindowFocused() const override; + + //! returns if window is minimized. + bool isWindowMinimized() const override; + + //! returns last state from maximizeWindow() and restoreWindow() + bool isWindowMaximized() const override; + + //! returns color format of the window. + video::ECOLOR_FORMAT getColorFormat() const override; + + //! notifies the device that it should close itself + void closeDevice() override; + + //! Sets if the window should be resizable in windowed mode. + void setResizable(bool resize = false) override; + + //! Resize the render window. + void setWindowSize(const irr::core::dimension2d &size) override; + + //! Minimizes the window. + void minimizeWindow() override; + + //! Maximizes the window. + void maximizeWindow() override; + + //! Restores the window size. + void restoreWindow() override; + + //! Get the position of this window on screen + core::position2di getWindowPosition() override; + + //! Activate any joysticks, and generate events for them. + bool activateJoysticks(core::array &joystickInfo) override; + + //! gets text from the clipboard + //! \return Returns 0 if no string is in there, otherwise utf-8 text. + virtual const c8 *getTextFromClipboard() const; + + //! gets text from the primary selection + //! \return Returns 0 if no string is in there, otherwise utf-8 text. + virtual const c8 *getTextFromPrimarySelection() const; + + //! copies text to the clipboard + //! This sets the clipboard selection and _not_ the primary selection. + //! @param text The text in utf-8 + virtual void copyToClipboard(const c8 *text) const; + + //! copies text to the primary selection + //! This sets the primary selection which you have on X on the middle mouse button. + //! @param text The text in utf-8 + virtual void copyToPrimarySelection(const c8 *text) const; + + //! Remove all messages pending in the system message loop + void clearSystemMessages() override; + + //! Get the device type + E_DEVICE_TYPE getType() const override + { + return EIDT_X11; + } + + //! Get the display density in dots per inch. + float getDisplayDensity() const override; + +#ifdef _IRR_COMPILE_WITH_X11_ + // convert an Irrlicht texture to a X11 cursor + Cursor TextureToCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot); + Cursor TextureToMonochromeCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot); +#ifdef _IRR_LINUX_XCURSOR_ + Cursor TextureToARGBCursor(irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot); +#endif +#endif + +private: + //! create the driver + void createDriver(); + + bool createWindow(); + + void createKeyMap(); + + void pollJoysticks(); + + void initXAtoms(); + + void initXInput2(); + + bool switchToFullscreen(); + + void setupTopLevelXorgWindow(); + +#ifdef _IRR_COMPILE_WITH_X11_ + bool createInputContext(); + void destroyInputContext(); + EKEY_CODE getKeyCode(XEvent &event); + + const c8 *getTextFromSelection(Atom selection, core::stringc &text_buffer) const; + bool becomeSelectionOwner(Atom selection) const; +#endif + + //! Implementation of the linux cursor control + class CCursorControl : public gui::ICursorControl { public: + CCursorControl(CIrrDeviceLinux *dev, bool null); - //! constructor - CIrrDeviceLinux(const SIrrlichtCreationParameters& param); + ~CCursorControl(); - //! destructor - virtual ~CIrrDeviceLinux(); - - //! runs the device. Returns false if device wants to be deleted - bool run() override; - - //! Cause the device to temporarily pause execution and let other processes to run - // This should bring down processor usage without major performance loss for Irrlicht - void yield() override; - - //! Pause execution and let other processes to run for a specified amount of time. - void sleep(u32 timeMs, bool pauseTimer) override; - - //! sets the caption of the window - void setWindowCaption(const wchar_t* text) override; - - //! Sets the window icon. - bool setWindowIcon(const video::IImage *img) override; - - //! returns if window is active. if not, nothing need to be drawn - bool isWindowActive() const override; - - //! returns if window has focus. - bool isWindowFocused() const override; - - //! returns if window is minimized. - bool isWindowMinimized() const override; - - //! returns last state from maximizeWindow() and restoreWindow() - bool isWindowMaximized() const override; - - //! returns color format of the window. - video::ECOLOR_FORMAT getColorFormat() const override; - - //! notifies the device that it should close itself - void closeDevice() override; - - //! Sets if the window should be resizable in windowed mode. - void setResizable(bool resize=false) override; - - //! Resize the render window. - void setWindowSize(const irr::core::dimension2d& size) override; - - //! Minimizes the window. - void minimizeWindow() override; - - //! Maximizes the window. - void maximizeWindow() override; - - //! Restores the window size. - void restoreWindow() override; - - //! Get the position of this window on screen - core::position2di getWindowPosition() override; - - //! Activate any joysticks, and generate events for them. - bool activateJoysticks(core::array & joystickInfo) override; - - //! gets text from the clipboard - //! \return Returns 0 if no string is in there, otherwise utf-8 text. - virtual const c8 *getTextFromClipboard() const; - - //! gets text from the primary selection - //! \return Returns 0 if no string is in there, otherwise utf-8 text. - virtual const c8 *getTextFromPrimarySelection() const; - - //! copies text to the clipboard - //! This sets the clipboard selection and _not_ the primary selection. - //! @param text The text in utf-8 - virtual void copyToClipboard(const c8 *text) const; - - //! copies text to the primary selection - //! This sets the primary selection which you have on X on the middle mouse button. - //! @param text The text in utf-8 - virtual void copyToPrimarySelection(const c8 *text) const; - - //! Remove all messages pending in the system message loop - void clearSystemMessages() override; - - //! Get the device type - E_DEVICE_TYPE getType() const override + //! Changes the visible state of the mouse cursor. + void setVisible(bool visible) override { - return EIDT_X11; + if (visible == IsVisible) + return; + IsVisible = visible; +#ifdef _IRR_COMPILE_WITH_X11_ + if (!Null) { + if (!IsVisible) + XDefineCursor(Device->XDisplay, Device->XWindow, InvisCursor); + else + XUndefineCursor(Device->XDisplay, Device->XWindow); + } +#endif } - //! Get the display density in dots per inch. - float getDisplayDensity() const override; - -#ifdef _IRR_COMPILE_WITH_X11_ - // convert an Irrlicht texture to a X11 cursor - Cursor TextureToCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot); - Cursor TextureToMonochromeCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot); -#ifdef _IRR_LINUX_XCURSOR_ - Cursor TextureToARGBCursor(irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot); -#endif -#endif - - private: - - //! create the driver - void createDriver(); - - bool createWindow(); - - void createKeyMap(); - - void pollJoysticks(); - - void initXAtoms(); - - void initXInput2(); - - bool switchToFullscreen(); - - void setupTopLevelXorgWindow(); - -#ifdef _IRR_COMPILE_WITH_X11_ - bool createInputContext(); - void destroyInputContext(); - EKEY_CODE getKeyCode(XEvent &event); - - const c8 *getTextFromSelection(Atom selection, core::stringc &text_buffer) const; - bool becomeSelectionOwner(Atom selection) const; -#endif - - //! Implementation of the linux cursor control - class CCursorControl : public gui::ICursorControl + //! Returns if the cursor is currently visible. + bool isVisible() const override { - public: + return IsVisible; + } - CCursorControl(CIrrDeviceLinux* dev, bool null); + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } - ~CCursorControl(); + //! Sets the new position of the cursor. + void setPosition(f32 x, f32 y) override + { + setPosition((s32)(x * Device->Width), (s32)(y * Device->Height)); + } - //! Changes the visible state of the mouse cursor. - void setVisible(bool visible) override - { - if (visible==IsVisible) - return; - IsVisible = visible; -#ifdef _IRR_COMPILE_WITH_X11_ - if (!Null) - { - if ( !IsVisible ) - XDefineCursor( Device->XDisplay, Device->XWindow, InvisCursor ); - else - XUndefineCursor( Device->XDisplay, Device->XWindow ); - } -#endif - } + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } - //! Returns if the cursor is currently visible. - bool isVisible() const override - { - return IsVisible; - } - - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(f32 x, f32 y) override - { - setPosition((s32)(x*Device->Width), (s32)(y*Device->Height)); - } - - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(s32 x, s32 y) override - { + //! Sets the new position of the cursor. + void setPosition(s32 x, s32 y) override + { #ifdef _IRR_COMPILE_WITH_X11_ - if (!Null) - { - if (UseReferenceRect) - { + if (!Null) { + if (UseReferenceRect) { // NOTE: XIWarpPointer works when X11 has set a coordinate transformation matrix for the mouse unlike XWarpPointer // which runs into a bug mentioned here: https://gitlab.freedesktop.org/xorg/xserver/-/issues/600 // So also workaround for Irrlicht bug #450 #ifdef _IRR_LINUX_X11_XINPUT2_ - if ( DeviceId != 0) - { - XIWarpPointer(Device->XDisplay, + if (DeviceId != 0) { + XIWarpPointer(Device->XDisplay, DeviceId, None, Device->XWindow, 0, 0, @@ -234,249 +227,242 @@ namespace irr Device->Height, ReferenceRect.UpperLeftCorner.X + x, ReferenceRect.UpperLeftCorner.Y + y); - } - else + } else #endif - { - XWarpPointer(Device->XDisplay, - None, - Device->XWindow, 0, 0, - Device->Width, - Device->Height, - ReferenceRect.UpperLeftCorner.X + x, - ReferenceRect.UpperLeftCorner.Y + y); - } - } - else { + XWarpPointer(Device->XDisplay, + None, + Device->XWindow, 0, 0, + Device->Width, + Device->Height, + ReferenceRect.UpperLeftCorner.X + x, + ReferenceRect.UpperLeftCorner.Y + y); + } + } else { #ifdef _IRR_LINUX_X11_XINPUT2_ - if ( DeviceId != 0) - { - XIWarpPointer(Device->XDisplay, + if (DeviceId != 0) { + XIWarpPointer(Device->XDisplay, DeviceId, None, Device->XWindow, 0, 0, Device->Width, Device->Height, x, y); - } - else + } else #endif - { - XWarpPointer(Device->XDisplay, + { + XWarpPointer(Device->XDisplay, None, Device->XWindow, 0, 0, Device->Width, Device->Height, x, y); - } } - XFlush(Device->XDisplay); } + XFlush(Device->XDisplay); + } #endif - CursorPos.X = x; - CursorPos.Y = y; - } + CursorPos.X = x; + CursorPos.Y = y; + } - //! Returns the current position of the mouse cursor. - const core::position2d& getPosition(bool updateCursor) override - { - if ( updateCursor ) - updateCursorPos(); - return CursorPos; - } + //! Returns the current position of the mouse cursor. + const core::position2d &getPosition(bool updateCursor) override + { + if (updateCursor) + updateCursorPos(); + return CursorPos; + } - //! Returns the current position of the mouse cursor. - core::position2d getRelativePosition(bool updateCursor) override - { - if ( updateCursor ) - updateCursorPos(); + //! Returns the current position of the mouse cursor. + core::position2d getRelativePosition(bool updateCursor) override + { + if (updateCursor) + updateCursorPos(); - if (!UseReferenceRect) - { - return core::position2d(CursorPos.X / (f32)Device->Width, + if (!UseReferenceRect) { + return core::position2d(CursorPos.X / (f32)Device->Width, CursorPos.Y / (f32)Device->Height); - } - - return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), - CursorPos.Y / (f32)ReferenceRect.getHeight()); } - void setReferenceRect(core::rect* rect=0) override - { - if (rect) - { - ReferenceRect = *rect; - UseReferenceRect = true; + return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), + CursorPos.Y / (f32)ReferenceRect.getHeight()); + } - // prevent division through zero and uneven sizes + void setReferenceRect(core::rect *rect = 0) override + { + if (rect) { + ReferenceRect = *rect; + UseReferenceRect = true; - if (!ReferenceRect.getHeight() || ReferenceRect.getHeight()%2) - ReferenceRect.LowerRightCorner.Y += 1; + // prevent division through zero and uneven sizes - if (!ReferenceRect.getWidth() || ReferenceRect.getWidth()%2) - ReferenceRect.LowerRightCorner.X += 1; - } - else - UseReferenceRect = false; - } + if (!ReferenceRect.getHeight() || ReferenceRect.getHeight() % 2) + ReferenceRect.LowerRightCorner.Y += 1; - //! Sets the active cursor icon - void setActiveIcon(gui::ECURSOR_ICON iconId) override; + if (!ReferenceRect.getWidth() || ReferenceRect.getWidth() % 2) + ReferenceRect.LowerRightCorner.X += 1; + } else + UseReferenceRect = false; + } - //! Gets the currently active icon - gui::ECURSOR_ICON getActiveIcon() const override - { - return ActiveIcon; - } + //! Sets the active cursor icon + void setActiveIcon(gui::ECURSOR_ICON iconId) override; - //! Add a custom sprite as cursor icon. - gui::ECURSOR_ICON addIcon(const gui::SCursorSprite& icon) override; + //! Gets the currently active icon + gui::ECURSOR_ICON getActiveIcon() const override + { + return ActiveIcon; + } - //! replace the given cursor icon. - void changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite& icon) override; + //! Add a custom sprite as cursor icon. + gui::ECURSOR_ICON addIcon(const gui::SCursorSprite &icon) override; - //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. - core::dimension2di getSupportedIconSize() const override; + //! replace the given cursor icon. + void changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite &icon) override; + + //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. + core::dimension2di getSupportedIconSize() const override; #ifdef _IRR_COMPILE_WITH_X11_ - //! Set platform specific behavior flags. - void setPlatformBehavior(gui::ECURSOR_PLATFORM_BEHAVIOR behavior) override {PlatformBehavior = behavior; } + //! Set platform specific behavior flags. + void setPlatformBehavior(gui::ECURSOR_PLATFORM_BEHAVIOR behavior) override { PlatformBehavior = behavior; } - //! Return platform specific behavior. - gui::ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const override { return PlatformBehavior; } + //! Return platform specific behavior. + gui::ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const override { return PlatformBehavior; } - void update(); - void clearCursors(); + void update(); + void clearCursors(); #endif - private: - - void updateCursorPos() - { + private: + void updateCursorPos() + { #ifdef _IRR_COMPILE_WITH_X11_ - if (Null) + if (Null) + return; + + if (PlatformBehavior & gui::ECPB_X11_CACHE_UPDATES && !os::Timer::isStopped()) { + u32 now = os::Timer::getTime(); + if (now <= LastQuery) return; + LastQuery = now; + } - if ( PlatformBehavior&gui::ECPB_X11_CACHE_UPDATES && !os::Timer::isStopped() ) - { - u32 now = os::Timer::getTime(); - if (now <= LastQuery) - return; - LastQuery = now; - } - - Window tmp; - int itmp1, itmp2; - unsigned int maskreturn; - XQueryPointer(Device->XDisplay, Device->XWindow, + Window tmp; + int itmp1, itmp2; + unsigned int maskreturn; + XQueryPointer(Device->XDisplay, Device->XWindow, &tmp, &tmp, &itmp1, &itmp2, &CursorPos.X, &CursorPos.Y, &maskreturn); #endif - } + } - CIrrDeviceLinux* Device; - core::position2d CursorPos; - core::rect ReferenceRect; + CIrrDeviceLinux *Device; + core::position2d CursorPos; + core::rect ReferenceRect; #ifdef _IRR_COMPILE_WITH_X11_ - gui::ECURSOR_PLATFORM_BEHAVIOR PlatformBehavior; - u32 LastQuery; - Cursor InvisCursor; + gui::ECURSOR_PLATFORM_BEHAVIOR PlatformBehavior; + u32 LastQuery; + Cursor InvisCursor; #ifdef _IRR_LINUX_X11_XINPUT2_ - int DeviceId; + int DeviceId; #endif - struct CursorFrameX11 - { - CursorFrameX11() : IconHW(0) {} - CursorFrameX11(Cursor icon) : IconHW(icon) {} - - Cursor IconHW; // hardware cursor - }; - - struct CursorX11 - { - CursorX11() {} - explicit CursorX11(Cursor iconHw, u32 frameTime=0) : FrameTime(frameTime) - { - Frames.push_back( CursorFrameX11(iconHw) ); - } - core::array Frames; - u32 FrameTime; - }; - - core::array Cursors; - - void initCursors(); -#endif - bool IsVisible; - bool Null; - bool UseReferenceRect; - gui::ECURSOR_ICON ActiveIcon; - u32 ActiveIconStartTime; - }; - - friend class CCursorControl; - -#ifdef _IRR_COMPILE_WITH_X11_ - friend class COpenGLDriver; - - Display *XDisplay; - XVisualInfo* VisualInfo; - int Screennr; - Window XWindow; - XSetWindowAttributes WndAttributes; - XSizeHints* StdHints; - XIM XInputMethod; - XIC XInputContext; - bool HasNetWM; - // text is utf-8 - mutable core::stringc Clipboard; - mutable core::stringc PrimarySelection; -#endif -#if defined(_IRR_LINUX_X11_XINPUT2_) - int currentTouchedCount; -#endif - u32 Width, Height; - bool WindowHasFocus; - bool WindowMinimized; - bool WindowMaximized; - bool ExternalWindow; - int AutorepeatSupport; - - struct SKeyMap + struct CursorFrameX11 { - SKeyMap() {} - SKeyMap(s32 x11, s32 win32) - : X11Key(x11), Win32Key(win32) - { - } + CursorFrameX11() : + IconHW(0) {} + CursorFrameX11(Cursor icon) : + IconHW(icon) {} - KeySym X11Key; - s32 Win32Key; - - bool operator<(const SKeyMap& o) const - { - return X11Key KeyMap; - -#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - struct JoystickInfo + struct CursorX11 { - int fd; - int axes; - int buttons; - - SEvent persistentData; - - JoystickInfo() : fd(-1), axes(0), buttons(0) { } + CursorX11() {} + explicit CursorX11(Cursor iconHw, u32 frameTime = 0) : + FrameTime(frameTime) + { + Frames.push_back(CursorFrameX11(iconHw)); + } + core::array Frames; + u32 FrameTime; }; - core::array ActiveJoysticks; + + core::array Cursors; + + void initCursors(); #endif + bool IsVisible; + bool Null; + bool UseReferenceRect; + gui::ECURSOR_ICON ActiveIcon; + u32 ActiveIconStartTime; }; + friend class CCursorControl; + +#ifdef _IRR_COMPILE_WITH_X11_ + friend class COpenGLDriver; + + Display *XDisplay; + XVisualInfo *VisualInfo; + int Screennr; + Window XWindow; + XSetWindowAttributes WndAttributes; + XSizeHints *StdHints; + XIM XInputMethod; + XIC XInputContext; + bool HasNetWM; + // text is utf-8 + mutable core::stringc Clipboard; + mutable core::stringc PrimarySelection; +#endif +#if defined(_IRR_LINUX_X11_XINPUT2_) + int currentTouchedCount; +#endif + u32 Width, Height; + bool WindowHasFocus; + bool WindowMinimized; + bool WindowMaximized; + bool ExternalWindow; + int AutorepeatSupport; + + struct SKeyMap + { + SKeyMap() {} + SKeyMap(s32 x11, s32 win32) : + X11Key(x11), Win32Key(win32) + { + } + + KeySym X11Key; + s32 Win32Key; + + bool operator<(const SKeyMap &o) const + { + return X11Key < o.X11Key; + } + }; + + core::array KeyMap; + +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) + struct JoystickInfo + { + int fd; + int axes; + int buttons; + + SEvent persistentData; + + JoystickInfo() : + fd(-1), axes(0), buttons(0) {} + }; + core::array ActiveJoysticks; +#endif +}; } // end namespace irr diff --git a/source/Irrlicht/CIrrDeviceOSX.h b/source/Irrlicht/CIrrDeviceOSX.h index fa9a95e7..f4f159aa 100644 --- a/source/Irrlicht/CIrrDeviceOSX.h +++ b/source/Irrlicht/CIrrDeviceOSX.h @@ -19,12 +19,12 @@ namespace irr { - class CIrrDeviceMacOSX; +class CIrrDeviceMacOSX; } @interface CIrrDelegateOSX : NSObject -- (id)initWithDevice:(irr::CIrrDeviceMacOSX*)device; +- (id)initWithDevice:(irr::CIrrDeviceMacOSX *)device; - (void)terminate:(id)sender; - (BOOL)isQuit; @@ -32,217 +32,206 @@ namespace irr namespace irr { - class CIrrDeviceMacOSX : public CIrrDeviceStub +class CIrrDeviceMacOSX : public CIrrDeviceStub +{ +public: + //! constructor + CIrrDeviceMacOSX(const SIrrlichtCreationParameters ¶ms); + + //! destructor + virtual ~CIrrDeviceMacOSX(); + + //! runs the device. Returns false if device wants to be deleted + bool run() override; + + //! Cause the device to temporarily pause execution and let other processes to run + // This should bring down processor usage without major performance loss for Irrlicht + void yield() override; + + //! Pause execution and let other processes to run for a specified amount of time. + void sleep(u32 timeMs, bool pauseTimer) override; + + //! sets the caption of the window + void setWindowCaption(const wchar_t *text) override; + + //! returns if window is active. if not, nothing need to be drawn + bool isWindowActive() const override; + + //! Checks if the Irrlicht window has focus + bool isWindowFocused() const override; + + //! Checks if the Irrlicht window is minimized + bool isWindowMinimized() const override; + + //! notifies the device that it should close itself + void closeDevice() override; + + //! Sets if the window should be resizable in windowed mode. + void setResizable(bool resize) override; + + //! Returns true if the window is resizable, false if not + virtual bool isResizable() const; + + //! Minimizes the window if possible + void minimizeWindow() override; + + //! Maximizes the window if possible. + void maximizeWindow() override; + + //! Restore the window to normal size if possible. + void restoreWindow() override; + + //! Get the position of this window on screen + core::position2di getWindowPosition() override; + + //! Activate any joysticks, and generate events for them. + bool activateJoysticks(core::array &joystickInfo) override; + + //! Get the device type + E_DEVICE_TYPE getType() const override + { + return EIDT_OSX; + } + + void setMouseLocation(int x, int y); + void setResize(int width, int height); + void setCursorVisible(bool visible); + void setWindow(NSWindow *window); + +private: + //! create the driver + void createDriver(); + + //! Implementation of the macos x cursor control + class CCursorControl : public gui::ICursorControl { public: - - //! constructor - CIrrDeviceMacOSX(const SIrrlichtCreationParameters& params); - - //! destructor - virtual ~CIrrDeviceMacOSX(); - - //! runs the device. Returns false if device wants to be deleted - bool run() override; - - //! Cause the device to temporarily pause execution and let other processes to run - // This should bring down processor usage without major performance loss for Irrlicht - void yield() override; - - //! Pause execution and let other processes to run for a specified amount of time. - void sleep(u32 timeMs, bool pauseTimer) override; - - //! sets the caption of the window - void setWindowCaption(const wchar_t* text) override; - - //! returns if window is active. if not, nothing need to be drawn - bool isWindowActive() const override; - - //! Checks if the Irrlicht window has focus - bool isWindowFocused() const override; - - //! Checks if the Irrlicht window is minimized - bool isWindowMinimized() const override; - - //! notifies the device that it should close itself - void closeDevice() override; - - //! Sets if the window should be resizable in windowed mode. - void setResizable(bool resize) override; - - //! Returns true if the window is resizable, false if not - virtual bool isResizable() const; - - //! Minimizes the window if possible - void minimizeWindow() override; - - //! Maximizes the window if possible. - void maximizeWindow() override; - - //! Restore the window to normal size if possible. - void restoreWindow() override; - - //! Get the position of this window on screen - core::position2di getWindowPosition() override; - - //! Activate any joysticks, and generate events for them. - bool activateJoysticks(core::array & joystickInfo) override; - - //! Get the device type - E_DEVICE_TYPE getType() const override + CCursorControl(const core::dimension2d &wsize, CIrrDeviceMacOSX *device) : + WindowSize(wsize), InvWindowSize(0.0f, 0.0f), Device(device), IsVisible(true), UseReferenceRect(false) { - return EIDT_OSX; + CursorPos.X = CursorPos.Y = 0; + if (WindowSize.Width != 0) + InvWindowSize.Width = 1.0f / WindowSize.Width; + if (WindowSize.Height != 0) + InvWindowSize.Height = 1.0f / WindowSize.Height; } - void setMouseLocation(int x, int y); - void setResize(int width, int height); - void setCursorVisible(bool visible); - void setWindow(NSWindow* window); + //! Changes the visible state of the mouse cursor. + void setVisible(bool visible) override + { + IsVisible = visible; + Device->setCursorVisible(visible); + } + + //! Returns if the cursor is currently visible. + bool isVisible() const override + { + return IsVisible; + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(f32 x, f32 y) override + { + setPosition((s32)(x * WindowSize.Width), (s32)(y * WindowSize.Height)); + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + if (CursorPos.X != pos.X || CursorPos.Y != pos.Y) + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(s32 x, s32 y) override + { + if (UseReferenceRect) { + Device->setMouseLocation(ReferenceRect.UpperLeftCorner.X + x, ReferenceRect.UpperLeftCorner.Y + y); + } else { + Device->setMouseLocation(x, y); + } + } + + //! Returns the current position of the mouse cursor. + const core::position2d &getPosition(bool updateCursor) override + { + return CursorPos; + } + + //! Returns the current position of the mouse cursor. + core::position2d getRelativePosition(bool updateCursor) override + { + if (!UseReferenceRect) { + return core::position2d(CursorPos.X * InvWindowSize.Width, + CursorPos.Y * InvWindowSize.Height); + } + + return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), + CursorPos.Y / (f32)ReferenceRect.getHeight()); + } + + //! Sets an absolute reference rect for calculating the cursor position. + void setReferenceRect(core::rect *rect = 0) override + { + if (rect) { + ReferenceRect = *rect; + UseReferenceRect = true; + + // prevent division through zero and uneven sizes + + if (!ReferenceRect.getHeight() || ReferenceRect.getHeight() % 2) + ReferenceRect.LowerRightCorner.Y += 1; + + if (!ReferenceRect.getWidth() || ReferenceRect.getWidth() % 2) + ReferenceRect.LowerRightCorner.X += 1; + } else + UseReferenceRect = false; + } + + //! Updates the internal cursor position + void updateInternalCursorPosition(int x, int y) + { + CursorPos.X = x; + CursorPos.Y = y; + } private: - - //! create the driver - void createDriver(); - - //! Implementation of the macos x cursor control - class CCursorControl : public gui::ICursorControl - { - public: - - CCursorControl(const core::dimension2d& wsize, CIrrDeviceMacOSX *device) - : WindowSize(wsize), InvWindowSize(0.0f, 0.0f), Device(device), IsVisible(true), UseReferenceRect(false) - { - CursorPos.X = CursorPos.Y = 0; - if (WindowSize.Width!=0) - InvWindowSize.Width = 1.0f / WindowSize.Width; - if (WindowSize.Height!=0) - InvWindowSize.Height = 1.0f / WindowSize.Height; - } - - //! Changes the visible state of the mouse cursor. - void setVisible(bool visible) override - { - IsVisible = visible; - Device->setCursorVisible(visible); - } - - //! Returns if the cursor is currently visible. - bool isVisible() const override - { - return IsVisible; - } - - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(f32 x, f32 y) override - { - setPosition((s32)(x*WindowSize.Width), (s32)(y*WindowSize.Height)); - } - - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - if (CursorPos.X != pos.X || CursorPos.Y != pos.Y) - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(s32 x, s32 y) override - { - if (UseReferenceRect) - { - Device->setMouseLocation(ReferenceRect.UpperLeftCorner.X + x, ReferenceRect.UpperLeftCorner.Y + y); - } - else - { - Device->setMouseLocation(x,y); - } - } - - //! Returns the current position of the mouse cursor. - const core::position2d& getPosition(bool updateCursor) override - { - return CursorPos; - } - - //! Returns the current position of the mouse cursor. - core::position2d getRelativePosition(bool updateCursor) override - { - if (!UseReferenceRect) - { - return core::position2d(CursorPos.X * InvWindowSize.Width, - CursorPos.Y * InvWindowSize.Height); - } - - return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), - CursorPos.Y / (f32)ReferenceRect.getHeight()); - } - - //! Sets an absolute reference rect for calculating the cursor position. - void setReferenceRect(core::rect* rect=0) override - { - if (rect) - { - ReferenceRect = *rect; - UseReferenceRect = true; - - // prevent division through zero and uneven sizes - - if (!ReferenceRect.getHeight() || ReferenceRect.getHeight()%2) - ReferenceRect.LowerRightCorner.Y += 1; - - if (!ReferenceRect.getWidth() || ReferenceRect.getWidth()%2) - ReferenceRect.LowerRightCorner.X += 1; - } - else - UseReferenceRect = false; - } - - //! Updates the internal cursor position - void updateInternalCursorPosition(int x,int y) - { - CursorPos.X = x; - CursorPos.Y = y; - } - - private: - - core::position2d CursorPos; - core::dimension2d WindowSize; - core::dimension2d InvWindowSize; - core::rect ReferenceRect; - CIrrDeviceMacOSX *Device; - bool IsVisible; - bool UseReferenceRect; - }; - - bool createWindow(); - void initKeycodes(); - void storeMouseLocation(); - void postMouseEvent(void *event, irr::SEvent &ievent); - void postKeyEvent(void *event, irr::SEvent &ievent, bool pressed); - void pollJoysticks(); - - NSWindow* Window; - CGDirectDisplayID Display; - std::map KeyCodes; - int DeviceWidth; - int DeviceHeight; - int ScreenWidth; - int ScreenHeight; - u32 MouseButtonStates; - bool IsFullscreen; - bool IsActive; - bool IsShiftDown; - bool IsControlDown; - bool IsResizable; + core::position2d CursorPos; + core::dimension2d WindowSize; + core::dimension2d InvWindowSize; + core::rect ReferenceRect; + CIrrDeviceMacOSX *Device; + bool IsVisible; + bool UseReferenceRect; }; + bool createWindow(); + void initKeycodes(); + void storeMouseLocation(); + void postMouseEvent(void *event, irr::SEvent &ievent); + void postKeyEvent(void *event, irr::SEvent &ievent, bool pressed); + void pollJoysticks(); + + NSWindow *Window; + CGDirectDisplayID Display; + std::map KeyCodes; + int DeviceWidth; + int DeviceHeight; + int ScreenWidth; + int ScreenHeight; + u32 MouseButtonStates; + bool IsFullscreen; + bool IsActive; + bool IsShiftDown; + bool IsControlDown; + bool IsResizable; +}; } // end namespace irr diff --git a/source/Irrlicht/CIrrDeviceOSX.mm b/source/Irrlicht/CIrrDeviceOSX.mm index 06a6d1ec..f21c2159 100644 --- a/source/Irrlicht/CIrrDeviceOSX.mm +++ b/source/Irrlicht/CIrrDeviceOSX.mm @@ -4,7 +4,6 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in Irrlicht.h - #ifdef _IRR_COMPILE_WITH_OSX_DEVICE_ #import @@ -40,22 +39,23 @@ struct JoystickComponent { IOHIDElementCookie cookie; // unique value which identifies element, will NOT change - long min; // reported min value possible - long max; // reported max value possible + long min; // reported min value possible + long max; // reported max value possible - long minRead; //min read value - long maxRead; //max read value + long minRead; // min read value + long maxRead; // max read value - JoystickComponent() : min(0), minRead(0), max(0), maxRead(0) + JoystickComponent() : + min(0), minRead(0), max(0), maxRead(0) { } }; struct JoystickInfo { - irr::core::array axisComp; - irr::core::array buttonComp; - irr::core::array hatComp; + irr::core::array axisComp; + irr::core::array buttonComp; + irr::core::array hatComp; int hats; int axes; @@ -64,13 +64,14 @@ struct JoystickInfo irr::SEvent persistentData; - IOHIDDeviceInterface ** interface; + IOHIDDeviceInterface **interface; bool removed; char joystickName[256]; - long usage; // usage page from IOUSBHID Parser.h which defines general usage + long usage; // usage page from IOUSBHID Parser.h which defines general usage long usagePage; // usage within above page from IOUSBHID Parser.h which defines specific usage - JoystickInfo() : hats(0), axes(0), buttons(0), interface(0), removed(false), usage(0), usagePage(0), numActiveJoysticks(0) + JoystickInfo() : + hats(0), axes(0), buttons(0), interface(0), removed(false), usage(0), usagePage(0), numActiveJoysticks(0) { interface = NULL; memset(joystickName, '\0', 256); @@ -85,22 +86,19 @@ struct JoystickInfo }; irr::core::array ActiveJoysticks; -//helper functions for init joystick -static IOReturn closeJoystickDevice (JoystickInfo* joyInfo) +// helper functions for init joystick +static IOReturn closeJoystickDevice(JoystickInfo *joyInfo) { IOReturn result = kIOReturnSuccess; - if (joyInfo && joyInfo->interface) - { + if (joyInfo && joyInfo->interface) { /* close the interface */ - result = (*(joyInfo->interface))->close (joyInfo->interface); - if (kIOReturnNotOpen == result) - { + result = (*(joyInfo->interface))->close(joyInfo->interface); + if (kIOReturnNotOpen == result) { /* do nothing as device was not opened, thus can't be closed */ - } - else if (kIOReturnSuccess != result) + } else if (kIOReturnSuccess != result) irr::os::Printer::log("IOHIDDeviceInterface failed to close", irr::ELL_ERROR); /* release the interface */ - result = (*(joyInfo->interface))->Release (joyInfo->interface); + result = (*(joyInfo->interface))->Release(joyInfo->interface); if (kIOReturnSuccess != result) irr::os::Printer::log("IOHIDDeviceInterface failed to release", irr::ELL_ERROR); joyInfo->interface = NULL; @@ -108,160 +106,141 @@ static IOReturn closeJoystickDevice (JoystickInfo* joyInfo) return result; } -static void addComponentInfo (CFTypeRef refElement, JoystickComponent *pComponent, int numActiveJoysticks) +static void addComponentInfo(CFTypeRef refElement, JoystickComponent *pComponent, int numActiveJoysticks) { long number; CFTypeRef refType; - refType = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementCookieKey)); - if (refType && CFNumberGetValue ((CFNumberRef)refType, kCFNumberLongType, &number)) - pComponent->cookie = (IOHIDElementCookie) number; - refType = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementMinKey)); - if (refType && CFNumberGetValue ((CFNumberRef)refType, kCFNumberLongType, &number)) + refType = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementCookieKey)); + if (refType && CFNumberGetValue((CFNumberRef)refType, kCFNumberLongType, &number)) + pComponent->cookie = (IOHIDElementCookie)number; + refType = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementMinKey)); + if (refType && CFNumberGetValue((CFNumberRef)refType, kCFNumberLongType, &number)) pComponent->minRead = pComponent->min = number; - refType = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementMaxKey)); - if (refType && CFNumberGetValue ((CFNumberRef)refType, kCFNumberLongType, &number)) + refType = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementMaxKey)); + if (refType && CFNumberGetValue((CFNumberRef)refType, kCFNumberLongType, &number)) pComponent->maxRead = pComponent->max = number; } -static void getJoystickComponentArrayHandler (const void * value, void * parameter); +static void getJoystickComponentArrayHandler(const void *value, void *parameter); -static void addJoystickComponent (CFTypeRef refElement, JoystickInfo* joyInfo) +static void addJoystickComponent(CFTypeRef refElement, JoystickInfo *joyInfo) { long elementType, usagePage, usage; - CFTypeRef refElementType = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementTypeKey)); - CFTypeRef refUsagePage = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementUsagePageKey)); - CFTypeRef refUsage = CFDictionaryGetValue ((CFDictionaryRef)refElement, CFSTR(kIOHIDElementUsageKey)); + CFTypeRef refElementType = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementTypeKey)); + CFTypeRef refUsagePage = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementUsagePageKey)); + CFTypeRef refUsage = CFDictionaryGetValue((CFDictionaryRef)refElement, CFSTR(kIOHIDElementUsageKey)); - if ((refElementType) && (CFNumberGetValue ((CFNumberRef)refElementType, kCFNumberLongType, &elementType))) - { + if ((refElementType) && (CFNumberGetValue((CFNumberRef)refElementType, kCFNumberLongType, &elementType))) { /* look at types of interest */ if ((elementType == kIOHIDElementTypeInput_Misc) || (elementType == kIOHIDElementTypeInput_Button) || - (elementType == kIOHIDElementTypeInput_Axis)) - { - if (refUsagePage && CFNumberGetValue ((CFNumberRef)refUsagePage, kCFNumberLongType, &usagePage) && - refUsage && CFNumberGetValue ((CFNumberRef)refUsage, kCFNumberLongType, &usage)) - { + (elementType == kIOHIDElementTypeInput_Axis)) { + if (refUsagePage && CFNumberGetValue((CFNumberRef)refUsagePage, kCFNumberLongType, &usagePage) && + refUsage && CFNumberGetValue((CFNumberRef)refUsage, kCFNumberLongType, &usage)) { switch (usagePage) /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */ { - case kHIDPage_GenericDesktop: + case kHIDPage_GenericDesktop: { + switch (usage) /* look at usage to determine function */ { - switch (usage) /* look at usage to determine function */ - { - case kHIDUsage_GD_X: - case kHIDUsage_GD_Y: - case kHIDUsage_GD_Z: - case kHIDUsage_GD_Rx: - case kHIDUsage_GD_Ry: - case kHIDUsage_GD_Rz: - case kHIDUsage_GD_Slider: - case kHIDUsage_GD_Dial: - case kHIDUsage_GD_Wheel: - { - joyInfo->axes++; - JoystickComponent newComponent; - addComponentInfo(refElement, &newComponent, joyInfo->numActiveJoysticks); - joyInfo->axisComp.push_back(newComponent); - } - break; - case kHIDUsage_GD_Hatswitch: - { - joyInfo->hats++; - JoystickComponent newComponent; - addComponentInfo(refElement, &newComponent, joyInfo->numActiveJoysticks); - joyInfo->hatComp.push_back(newComponent); - } - break; - } - } - break; - case kHIDPage_Button: - { - joyInfo->buttons++; + case kHIDUsage_GD_X: + case kHIDUsage_GD_Y: + case kHIDUsage_GD_Z: + case kHIDUsage_GD_Rx: + case kHIDUsage_GD_Ry: + case kHIDUsage_GD_Rz: + case kHIDUsage_GD_Slider: + case kHIDUsage_GD_Dial: + case kHIDUsage_GD_Wheel: { + joyInfo->axes++; JoystickComponent newComponent; addComponentInfo(refElement, &newComponent, joyInfo->numActiveJoysticks); - joyInfo->buttonComp.push_back(newComponent); + joyInfo->axisComp.push_back(newComponent); + } break; + case kHIDUsage_GD_Hatswitch: { + joyInfo->hats++; + JoystickComponent newComponent; + addComponentInfo(refElement, &newComponent, joyInfo->numActiveJoysticks); + joyInfo->hatComp.push_back(newComponent); + } break; } - break; - default: - break; + } break; + case kHIDPage_Button: { + joyInfo->buttons++; + JoystickComponent newComponent; + addComponentInfo(refElement, &newComponent, joyInfo->numActiveJoysticks); + joyInfo->buttonComp.push_back(newComponent); + } break; + default: + break; } } - } - else if (kIOHIDElementTypeCollection == elementType) - { - //get elements - CFTypeRef refElementTop = CFDictionaryGetValue ((CFMutableDictionaryRef) refElement, CFSTR(kIOHIDElementKey)); - if (refElementTop) - { - CFTypeID type = CFGetTypeID (refElementTop); - if (type == CFArrayGetTypeID()) - { - CFRange range = {0, CFArrayGetCount ((CFArrayRef)refElementTop)}; - CFArrayApplyFunction ((CFArrayRef)refElementTop, range, getJoystickComponentArrayHandler, joyInfo); + } else if (kIOHIDElementTypeCollection == elementType) { + // get elements + CFTypeRef refElementTop = CFDictionaryGetValue((CFMutableDictionaryRef)refElement, CFSTR(kIOHIDElementKey)); + if (refElementTop) { + CFTypeID type = CFGetTypeID(refElementTop); + if (type == CFArrayGetTypeID()) { + CFRange range = {0, CFArrayGetCount((CFArrayRef)refElementTop)}; + CFArrayApplyFunction((CFArrayRef)refElementTop, range, getJoystickComponentArrayHandler, joyInfo); } } } } } -static void getJoystickComponentArrayHandler (const void * value, void * parameter) +static void getJoystickComponentArrayHandler(const void *value, void *parameter) { - if (CFGetTypeID (value) == CFDictionaryGetTypeID ()) - addJoystickComponent ((CFTypeRef) value, (JoystickInfo *) parameter); + if (CFGetTypeID(value) == CFDictionaryGetTypeID()) + addJoystickComponent((CFTypeRef)value, (JoystickInfo *)parameter); } -static void joystickTopLevelElementHandler (const void * value, void * parameter) +static void joystickTopLevelElementHandler(const void *value, void *parameter) { CFTypeRef refCF = 0; - if (CFGetTypeID (value) != CFDictionaryGetTypeID ()) + if (CFGetTypeID(value) != CFDictionaryGetTypeID()) return; - refCF = CFDictionaryGetValue ((CFDictionaryRef)value, CFSTR(kIOHIDElementUsagePageKey)); - if (!CFNumberGetValue ((CFNumberRef)refCF, kCFNumberLongType, &((JoystickInfo *) parameter)->usagePage)) + refCF = CFDictionaryGetValue((CFDictionaryRef)value, CFSTR(kIOHIDElementUsagePageKey)); + if (!CFNumberGetValue((CFNumberRef)refCF, kCFNumberLongType, &((JoystickInfo *)parameter)->usagePage)) irr::os::Printer::log("CFNumberGetValue error retrieving JoystickInfo->usagePage", irr::ELL_ERROR); - refCF = CFDictionaryGetValue ((CFDictionaryRef)value, CFSTR(kIOHIDElementUsageKey)); - if (!CFNumberGetValue ((CFNumberRef)refCF, kCFNumberLongType, &((JoystickInfo *) parameter)->usage)) + refCF = CFDictionaryGetValue((CFDictionaryRef)value, CFSTR(kIOHIDElementUsageKey)); + if (!CFNumberGetValue((CFNumberRef)refCF, kCFNumberLongType, &((JoystickInfo *)parameter)->usage)) irr::os::Printer::log("CFNumberGetValue error retrieving JoystickInfo->usage", irr::ELL_ERROR); } -static void getJoystickDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef hidProperties, JoystickInfo *joyInfo) +static void getJoystickDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties, JoystickInfo *joyInfo) { CFMutableDictionaryRef usbProperties = 0; io_registry_entry_t parent1, parent2; /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also - * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties - */ - if ((KERN_SUCCESS == IORegistryEntryGetParentEntry (hidDevice, kIOServicePlane, &parent1)) && - (KERN_SUCCESS == IORegistryEntryGetParentEntry (parent1, kIOServicePlane, &parent2)) && - (KERN_SUCCESS == IORegistryEntryCreateCFProperties (parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) - { - if (usbProperties) - { + * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties + */ + if ((KERN_SUCCESS == IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1)) && + (KERN_SUCCESS == IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2)) && + (KERN_SUCCESS == IORegistryEntryCreateCFProperties(parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) { + if (usbProperties) { CFTypeRef refCF = 0; /* get device info - * try hid dictionary first, if fail then go to usb dictionary - */ + * try hid dictionary first, if fail then go to usb dictionary + */ /* get joystickName name */ - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductKey)); + refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey)); if (!refCF) - refCF = CFDictionaryGetValue (usbProperties, CFSTR("USB Product Name")); - if (refCF) - { - if (!CFStringGetCString ((CFStringRef)refCF, joyInfo->joystickName, 256, CFStringGetSystemEncoding ())) + refCF = CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name")); + if (refCF) { + if (!CFStringGetCString((CFStringRef)refCF, joyInfo->joystickName, 256, CFStringGetSystemEncoding())) irr::os::Printer::log("CFStringGetCString error getting joyInfo->joystickName", irr::ELL_ERROR); } /* get usage page and usage */ - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey)); - if (refCF) - { - if (!CFNumberGetValue ((CFNumberRef)refCF, kCFNumberLongType, &joyInfo->usagePage)) + refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey)); + if (refCF) { + if (!CFNumberGetValue((CFNumberRef)refCF, kCFNumberLongType, &joyInfo->usagePage)) irr::os::Printer::log("CFNumberGetValue error getting joyInfo->usagePage", irr::ELL_ERROR); - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsageKey)); + refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsageKey)); if (refCF) - if (!CFNumberGetValue ((CFNumberRef)refCF, kCFNumberLongType, &joyInfo->usage)) + if (!CFNumberGetValue((CFNumberRef)refCF, kCFNumberLongType, &joyInfo->usage)) irr::os::Printer::log("CFNumberGetValue error getting joyInfo->usage", irr::ELL_ERROR); } @@ -269,22 +248,21 @@ static void getJoystickDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef { /* use top level element instead */ CFTypeRef refCFTopElement = 0; - refCFTopElement = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey)); + refCFTopElement = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDElementKey)); { /* refCFTopElement points to an array of element dictionaries */ - CFRange range = {0, CFArrayGetCount ((CFArrayRef)refCFTopElement)}; - CFArrayApplyFunction ((CFArrayRef)refCFTopElement, range, joystickTopLevelElementHandler, joyInfo); + CFRange range = {0, CFArrayGetCount((CFArrayRef)refCFTopElement)}; + CFArrayApplyFunction((CFArrayRef)refCFTopElement, range, joystickTopLevelElementHandler, joyInfo); } } - CFRelease (usbProperties); - } - else + CFRelease(usbProperties); + } else irr::os::Printer::log("IORegistryEntryCreateCFProperties failed to create usbProperties", irr::ELL_ERROR); - if (kIOReturnSuccess != IOObjectRelease (parent2)) + if (kIOReturnSuccess != IOObjectRelease(parent2)) irr::os::Printer::log("IOObjectRelease failed to release parent2", irr::ELL_ERROR); - if (kIOReturnSuccess != IOObjectRelease (parent1)) + if (kIOReturnSuccess != IOObjectRelease(parent1)) irr::os::Printer::log("IOObjectRelease failed to release parent1", irr::ELL_ERROR); } } @@ -310,127 +288,129 @@ static void getJoystickDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef * in this case, pressing 'A' will generate a different virtual * keycode. */ -enum { - kVK_ANSI_A = 0x00, - kVK_ANSI_S = 0x01, - kVK_ANSI_D = 0x02, - kVK_ANSI_F = 0x03, - kVK_ANSI_H = 0x04, - kVK_ANSI_G = 0x05, - kVK_ANSI_Z = 0x06, - kVK_ANSI_X = 0x07, - kVK_ANSI_C = 0x08, - kVK_ANSI_V = 0x09, - kVK_ANSI_B = 0x0B, - kVK_ANSI_Q = 0x0C, - kVK_ANSI_W = 0x0D, - kVK_ANSI_E = 0x0E, - kVK_ANSI_R = 0x0F, - kVK_ANSI_Y = 0x10, - kVK_ANSI_T = 0x11, - kVK_ANSI_1 = 0x12, - kVK_ANSI_2 = 0x13, - kVK_ANSI_3 = 0x14, - kVK_ANSI_4 = 0x15, - kVK_ANSI_6 = 0x16, - kVK_ANSI_5 = 0x17, - kVK_ANSI_Equal = 0x18, - kVK_ANSI_9 = 0x19, - kVK_ANSI_7 = 0x1A, - kVK_ANSI_Minus = 0x1B, - kVK_ANSI_8 = 0x1C, - kVK_ANSI_0 = 0x1D, - kVK_ANSI_RightBracket = 0x1E, - kVK_ANSI_O = 0x1F, - kVK_ANSI_U = 0x20, - kVK_ANSI_LeftBracket = 0x21, - kVK_ANSI_I = 0x22, - kVK_ANSI_P = 0x23, - kVK_ANSI_L = 0x25, - kVK_ANSI_J = 0x26, - kVK_ANSI_Quote = 0x27, - kVK_ANSI_K = 0x28, - kVK_ANSI_Semicolon = 0x29, - kVK_ANSI_Backslash = 0x2A, - kVK_ANSI_Comma = 0x2B, - kVK_ANSI_Slash = 0x2C, - kVK_ANSI_N = 0x2D, - kVK_ANSI_M = 0x2E, - kVK_ANSI_Period = 0x2F, - kVK_ANSI_Grave = 0x32, - kVK_ANSI_KeypadDecimal = 0x41, +enum +{ + kVK_ANSI_A = 0x00, + kVK_ANSI_S = 0x01, + kVK_ANSI_D = 0x02, + kVK_ANSI_F = 0x03, + kVK_ANSI_H = 0x04, + kVK_ANSI_G = 0x05, + kVK_ANSI_Z = 0x06, + kVK_ANSI_X = 0x07, + kVK_ANSI_C = 0x08, + kVK_ANSI_V = 0x09, + kVK_ANSI_B = 0x0B, + kVK_ANSI_Q = 0x0C, + kVK_ANSI_W = 0x0D, + kVK_ANSI_E = 0x0E, + kVK_ANSI_R = 0x0F, + kVK_ANSI_Y = 0x10, + kVK_ANSI_T = 0x11, + kVK_ANSI_1 = 0x12, + kVK_ANSI_2 = 0x13, + kVK_ANSI_3 = 0x14, + kVK_ANSI_4 = 0x15, + kVK_ANSI_6 = 0x16, + kVK_ANSI_5 = 0x17, + kVK_ANSI_Equal = 0x18, + kVK_ANSI_9 = 0x19, + kVK_ANSI_7 = 0x1A, + kVK_ANSI_Minus = 0x1B, + kVK_ANSI_8 = 0x1C, + kVK_ANSI_0 = 0x1D, + kVK_ANSI_RightBracket = 0x1E, + kVK_ANSI_O = 0x1F, + kVK_ANSI_U = 0x20, + kVK_ANSI_LeftBracket = 0x21, + kVK_ANSI_I = 0x22, + kVK_ANSI_P = 0x23, + kVK_ANSI_L = 0x25, + kVK_ANSI_J = 0x26, + kVK_ANSI_Quote = 0x27, + kVK_ANSI_K = 0x28, + kVK_ANSI_Semicolon = 0x29, + kVK_ANSI_Backslash = 0x2A, + kVK_ANSI_Comma = 0x2B, + kVK_ANSI_Slash = 0x2C, + kVK_ANSI_N = 0x2D, + kVK_ANSI_M = 0x2E, + kVK_ANSI_Period = 0x2F, + kVK_ANSI_Grave = 0x32, + kVK_ANSI_KeypadDecimal = 0x41, kVK_ANSI_KeypadMultiply = 0x43, - kVK_ANSI_KeypadPlus = 0x45, - kVK_ANSI_KeypadClear = 0x47, - kVK_ANSI_KeypadDivide = 0x4B, - kVK_ANSI_KeypadEnter = 0x4C, - kVK_ANSI_KeypadMinus = 0x4E, - kVK_ANSI_KeypadEquals = 0x51, - kVK_ANSI_Keypad0 = 0x52, - kVK_ANSI_Keypad1 = 0x53, - kVK_ANSI_Keypad2 = 0x54, - kVK_ANSI_Keypad3 = 0x55, - kVK_ANSI_Keypad4 = 0x56, - kVK_ANSI_Keypad5 = 0x57, - kVK_ANSI_Keypad6 = 0x58, - kVK_ANSI_Keypad7 = 0x59, - kVK_ANSI_Keypad8 = 0x5B, - kVK_ANSI_Keypad9 = 0x5C + kVK_ANSI_KeypadPlus = 0x45, + kVK_ANSI_KeypadClear = 0x47, + kVK_ANSI_KeypadDivide = 0x4B, + kVK_ANSI_KeypadEnter = 0x4C, + kVK_ANSI_KeypadMinus = 0x4E, + kVK_ANSI_KeypadEquals = 0x51, + kVK_ANSI_Keypad0 = 0x52, + kVK_ANSI_Keypad1 = 0x53, + kVK_ANSI_Keypad2 = 0x54, + kVK_ANSI_Keypad3 = 0x55, + kVK_ANSI_Keypad4 = 0x56, + kVK_ANSI_Keypad5 = 0x57, + kVK_ANSI_Keypad6 = 0x58, + kVK_ANSI_Keypad7 = 0x59, + kVK_ANSI_Keypad8 = 0x5B, + kVK_ANSI_Keypad9 = 0x5C }; /* keycodes for keys that are independent of keyboard layout*/ -enum { - kVK_Return = 0x24, - kVK_Tab = 0x30, - kVK_Space = 0x31, - kVK_Delete = 0x33, - kVK_Escape = 0x35, - kVK_Command = 0x37, - kVK_Shift = 0x38, - kVK_CapsLock = 0x39, - kVK_Option = 0x3A, - kVK_Control = 0x3B, - kVK_RightShift = 0x3C, - kVK_RightOption = 0x3D, - kVK_RightControl = 0x3E, - kVK_Function = 0x3F, - kVK_F17 = 0x40, - kVK_VolumeUp = 0x48, - kVK_VolumeDown = 0x49, - kVK_Mute = 0x4A, - kVK_F18 = 0x4F, - kVK_F19 = 0x50, - kVK_F20 = 0x5A, - kVK_F5 = 0x60, - kVK_F6 = 0x61, - kVK_F7 = 0x62, - kVK_F3 = 0x63, - kVK_F8 = 0x64, - kVK_F9 = 0x65, - kVK_F11 = 0x67, - kVK_F13 = 0x69, - kVK_F16 = 0x6A, - kVK_F14 = 0x6B, - kVK_F10 = 0x6D, - kVK_F12 = 0x6F, - kVK_F15 = 0x71, - kVK_Help = 0x72, - kVK_Home = 0x73, - kVK_PageUp = 0x74, - kVK_ForwardDelete = 0x75, - kVK_F4 = 0x76, - kVK_End = 0x77, - kVK_F2 = 0x78, - kVK_PageDown = 0x79, - kVK_F1 = 0x7A, - kVK_LeftArrow = 0x7B, - kVK_RightArrow = 0x7C, - kVK_DownArrow = 0x7D, - kVK_UpArrow = 0x7E +enum +{ + kVK_Return = 0x24, + kVK_Tab = 0x30, + kVK_Space = 0x31, + kVK_Delete = 0x33, + kVK_Escape = 0x35, + kVK_Command = 0x37, + kVK_Shift = 0x38, + kVK_CapsLock = 0x39, + kVK_Option = 0x3A, + kVK_Control = 0x3B, + kVK_RightShift = 0x3C, + kVK_RightOption = 0x3D, + kVK_RightControl = 0x3E, + kVK_Function = 0x3F, + kVK_F17 = 0x40, + kVK_VolumeUp = 0x48, + kVK_VolumeDown = 0x49, + kVK_Mute = 0x4A, + kVK_F18 = 0x4F, + kVK_F19 = 0x50, + kVK_F20 = 0x5A, + kVK_F5 = 0x60, + kVK_F6 = 0x61, + kVK_F7 = 0x62, + kVK_F3 = 0x63, + kVK_F8 = 0x64, + kVK_F9 = 0x65, + kVK_F11 = 0x67, + kVK_F13 = 0x69, + kVK_F16 = 0x6A, + kVK_F14 = 0x6B, + kVK_F10 = 0x6D, + kVK_F12 = 0x6F, + kVK_F15 = 0x71, + kVK_Help = 0x72, + kVK_Home = 0x73, + kVK_PageUp = 0x74, + kVK_ForwardDelete = 0x75, + kVK_F4 = 0x76, + kVK_End = 0x77, + kVK_F2 = 0x78, + kVK_PageDown = 0x79, + kVK_F1 = 0x7A, + kVK_LeftArrow = 0x7B, + kVK_RightArrow = 0x7C, + kVK_DownArrow = 0x7D, + kVK_UpArrow = 0x7E }; //------------------------------------------------------------------------------------------ -Boolean GetDictionaryBoolean(CFDictionaryRef theDict, const void* key) +Boolean GetDictionaryBoolean(CFDictionaryRef theDict, const void *key) { // get a boolean from the dictionary Boolean value = false; @@ -441,7 +421,7 @@ Boolean GetDictionaryBoolean(CFDictionaryRef theDict, const void* key) return value; } //------------------------------------------------------------------------------------------ -long GetDictionaryLong(CFDictionaryRef theDict, const void* key) +long GetDictionaryLong(CFDictionaryRef theDict, const void *key) { // get a long from the dictionary long value = 0; @@ -454,89 +434,88 @@ long GetDictionaryLong(CFDictionaryRef theDict, const void* key) namespace irr { - namespace video - { - IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& param, io::IFileSystem* io, IContextManager* contextManager); - } +namespace video +{ +IVideoDriver *createOpenGLDriver(const SIrrlichtCreationParameters ¶m, io::IFileSystem *io, IContextManager *contextManager); +} } // end namespace irr static bool firstLaunch = true; -@implementation CIrrDelegateOSX -{ - irr::CIrrDeviceMacOSX* Device; - bool Quit; +@implementation CIrrDelegateOSX { + irr::CIrrDeviceMacOSX *Device; + bool Quit; } -- (id)initWithDevice:(irr::CIrrDeviceMacOSX*)device +- (id)initWithDevice:(irr::CIrrDeviceMacOSX *)device { - self = [super init]; + self = [super init]; - if (self) - Device = device; + if (self) + Device = device; - Quit = false; + Quit = false; - return (self); + return (self); } -- (void)applicationDidFinishLaunching:(NSNotification*)notification +- (void)applicationDidFinishLaunching:(NSNotification *)notification { - Quit = false; + Quit = false; } - (void)orderFrontStandardAboutPanel:(id)sender { - [NSApp orderFrontStandardAboutPanel:sender]; + [NSApp orderFrontStandardAboutPanel:sender]; } - (void)unhideAllApplications:(id)sender { - [NSApp unhideAllApplications:sender]; + [NSApp unhideAllApplications:sender]; } - (void)hide:(id)sender { - [NSApp hide:sender]; + [NSApp hide:sender]; } - (void)hideOtherApplications:(id)sender { - [NSApp hideOtherApplications:sender]; + [NSApp hideOtherApplications:sender]; } - (void)terminate:(id)sender { - Quit = true; + Quit = true; } - (void)windowWillClose:(id)sender { - Device->setWindow(nil); - Quit = true; + Device->setWindow(nil); + Quit = true; } - (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize { - if (Device->isResizable()) - return proposedFrameSize; - else - return [window frame].size; + if (Device->isResizable()) + return proposedFrameSize; + else + return [window frame].size; } - (void)windowDidResize:(NSNotification *)aNotification { - NSWindow *window; - NSRect frame; + NSWindow *window; + NSRect frame; - window = [aNotification object]; - frame = [window frame]; - Device->setResize((int)frame.size.width,(int)frame.size.height); + window = [aNotification object]; + frame = [window frame]; + Device->setResize((int)frame.size.width, (int)frame.size.height); } - (BOOL)isQuit { - return (Quit); + return (Quit); } @end @@ -544,11 +523,11 @@ static bool firstLaunch = true; namespace irr { //! constructor -CIrrDeviceMacOSX::CIrrDeviceMacOSX(const SIrrlichtCreationParameters& param) - : CIrrDeviceStub(param), Window(NULL), Display(NULL), - DeviceWidth(0), DeviceHeight(0), - ScreenWidth(0), ScreenHeight(0), MouseButtonStates(0), - IsActive(true), IsFullscreen(false), IsShiftDown(false), IsControlDown(false), IsResizable(false) +CIrrDeviceMacOSX::CIrrDeviceMacOSX(const SIrrlichtCreationParameters ¶m) : + CIrrDeviceStub(param), Window(NULL), Display(NULL), + DeviceWidth(0), DeviceHeight(0), + ScreenWidth(0), ScreenHeight(0), MouseButtonStates(0), + IsActive(true), IsFullscreen(false), IsShiftDown(false), IsControlDown(false), IsResizable(false) { struct utsname name; @@ -556,32 +535,30 @@ CIrrDeviceMacOSX::CIrrDeviceMacOSX(const SIrrlichtCreationParameters& param) setDebugName("CIrrDeviceMacOSX"); #endif - if (firstLaunch) - { + if (firstLaunch) { firstLaunch = false; - if (!CreationParams.WindowId) - { + if (!CreationParams.WindowId) { [[NSAutoreleasePool alloc] init]; [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; [[NSApplication sharedApplication] setDelegate:[[[CIrrDelegateOSX alloc] initWithDevice:this] autorelease]]; - // Create menu + // Create menu - NSString* bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; - if (bundleName == nil) - bundleName = @"Irrlicht"; + NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; + if (bundleName == nil) + bundleName = @"Irrlicht"; - NSMenu* mainMenu = [[[NSMenu alloc] initWithTitle:@"MainMenu"] autorelease]; - NSMenu* menu = [[[NSMenu alloc] initWithTitle:bundleName] autorelease]; - NSMenuItem* menuItem = [mainMenu addItemWithTitle:bundleName action:nil keyEquivalent:@""]; - [mainMenu setSubmenu:menu forItem:menuItem]; - menuItem = [menu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask]; + NSMenu *mainMenu = [[[NSMenu alloc] initWithTitle:@"MainMenu"] autorelease]; + NSMenu *menu = [[[NSMenu alloc] initWithTitle:bundleName] autorelease]; + NSMenuItem *menuItem = [mainMenu addItemWithTitle:bundleName action:nil keyEquivalent:@""]; + [mainMenu setSubmenu:menu forItem:menuItem]; + menuItem = [menu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask]; - [NSApp setMainMenu:mainMenu]; + [NSApp setMainMenu:mainMenu]; - [NSApp finishLaunching]; + [NSApp finishLaunching]; } NSString *path = [[NSBundle mainBundle] bundlePath]; @@ -594,7 +571,7 @@ CIrrDeviceMacOSX::CIrrDeviceMacOSX(const SIrrlichtCreationParameters& param) uname(&name); Operator = new COSOperator(name.version); - os::Printer::log(name.version,ELL_INFORMATION); + os::Printer::log(name.version, ELL_INFORMATION); initKeycodes(); @@ -619,8 +596,7 @@ CIrrDeviceMacOSX::~CIrrDeviceMacOSX() [NSApp setPresentationOptions:(NSApplicationPresentationDefault)]; closeDevice(); #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { + for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { if (ActiveJoysticks[joystick].interface) closeJoystickDevice(&ActiveJoysticks[joystick]); } @@ -629,8 +605,7 @@ CIrrDeviceMacOSX::~CIrrDeviceMacOSX() void CIrrDeviceMacOSX::closeDevice() { - if (Window != nil) - { + if (Window != nil) { [Window setIsVisible:FALSE]; [Window setReleasedWhenClosed:TRUE]; [Window release]; @@ -643,56 +618,53 @@ void CIrrDeviceMacOSX::closeDevice() bool CIrrDeviceMacOSX::createWindow() { - CGDisplayErr error; - bool result = false; - Display = CGMainDisplayID(); + CGDisplayErr error; + bool result = false; + Display = CGMainDisplayID(); - CGRect displayRect; - CGDisplayModeRef displaymode, olddisplaymode; + CGRect displayRect; + CGDisplayModeRef displaymode, olddisplaymode; - ScreenWidth = (int)CGDisplayPixelsWide(Display); - ScreenHeight = (int)CGDisplayPixelsHigh(Display); + ScreenWidth = (int)CGDisplayPixelsWide(Display); + ScreenHeight = (int)CGDisplayPixelsHigh(Display); - const NSBackingStoreType type = (CreationParams.DriverType == video::EDT_OPENGL) ? NSBackingStoreBuffered : NSBackingStoreNonretained; + const NSBackingStoreType type = (CreationParams.DriverType == video::EDT_OPENGL) ? NSBackingStoreBuffered : NSBackingStoreNonretained; - // TODO: fullscreen - //if (!CreationParams.Fullscreen) - { - if (!CreationParams.WindowId) //create another window when WindowId is null - { - int x = (CreationParams.WindowPosition.X > 0) ? CreationParams.WindowPosition.X : 0; - int y = (CreationParams.WindowPosition.Y > 0) ? CreationParams.WindowPosition.Y : 0; + // TODO: fullscreen + // if (!CreationParams.Fullscreen) + { + if (!CreationParams.WindowId) // create another window when WindowId is null + { + int x = (CreationParams.WindowPosition.X > 0) ? CreationParams.WindowPosition.X : 0; + int y = (CreationParams.WindowPosition.Y > 0) ? CreationParams.WindowPosition.Y : 0; - if (CreationParams.WindowPosition.Y > -1) - { - int screenHeight = [[[NSScreen screens] objectAtIndex:0] frame].size.height; - y = screenHeight - y - CreationParams.WindowSize.Height; - } + if (CreationParams.WindowPosition.Y > -1) { + int screenHeight = [[[NSScreen screens] objectAtIndex:0] frame].size.height; + y = screenHeight - y - CreationParams.WindowSize.Height; + } - Window = [[NSWindow alloc] initWithContentRect:NSMakeRect(x, y, CreationParams.WindowSize.Width,CreationParams.WindowSize.Height) styleMask:NSTitledWindowMask+NSClosableWindowMask+NSResizableWindowMask backing:type defer:FALSE]; + Window = [[NSWindow alloc] initWithContentRect:NSMakeRect(x, y, CreationParams.WindowSize.Width, CreationParams.WindowSize.Height) styleMask:NSTitledWindowMask + NSClosableWindowMask + NSResizableWindowMask backing:type defer:FALSE]; - if (CreationParams.WindowPosition.X == -1 && CreationParams.WindowPosition.Y == -1) - [Window center]; - } + if (CreationParams.WindowPosition.X == -1 && CreationParams.WindowPosition.Y == -1) + [Window center]; + } - DeviceWidth = CreationParams.WindowSize.Width; - DeviceHeight = CreationParams.WindowSize.Height; + DeviceWidth = CreationParams.WindowSize.Width; + DeviceHeight = CreationParams.WindowSize.Height; - result = true; - } + result = true; + } - if (result) - { - if (Window) - { - [Window setDelegate:(CIrrDelegateOSX *)[NSApp delegate]]; - [Window setAcceptsMouseMovedEvents:TRUE]; - [Window setIsVisible:TRUE]; - [Window makeKeyAndOrderFront:nil]; - } - } + if (result) { + if (Window) { + [Window setDelegate:(CIrrDelegateOSX *)[NSApp delegate]]; + [Window setAcceptsMouseMovedEvents:TRUE]; + [Window setIsVisible:TRUE]; + [Window makeKeyAndOrderFront:nil]; + } + } - return result; + return result; } void CIrrDeviceMacOSX::setResize(int width, int height) @@ -703,203 +675,190 @@ void CIrrDeviceMacOSX::setResize(int width, int height) #if defined(_IRR_COMPILE_WITH_OPENGL_) // update the size of the opengl rendering context - if (CreationParams.DriverType == video::EDT_OPENGL) - { - NSOpenGLContext* Context = (NSOpenGLContext*)ContextManager->getContext().OpenGLOSX.Context; + if (CreationParams.DriverType == video::EDT_OPENGL) { + NSOpenGLContext *Context = (NSOpenGLContext *)ContextManager->getContext().OpenGLOSX.Context; - if (Context) - [Context update]; - } + if (Context) + [Context update]; + } #endif // resize the driver to the inner pane size - if (Window) - { + if (Window) { NSRect driverFrame = [Window contentRectForFrameRect:[Window frame]]; - getVideoDriver()->OnResize(core::dimension2d( (s32)driverFrame.size.width, (s32)driverFrame.size.height)); + getVideoDriver()->OnResize(core::dimension2d((s32)driverFrame.size.width, (s32)driverFrame.size.height)); DeviceWidth = (s32)driverFrame.size.width; DeviceHeight = (s32)driverFrame.size.height; - } - else - getVideoDriver()->OnResize(core::dimension2d( (s32)width, (s32)height)); + } else + getVideoDriver()->OnResize(core::dimension2d((s32)width, (s32)height)); } - void CIrrDeviceMacOSX::createDriver() { - switch (CreationParams.DriverType) - { - case video::EDT_OPENGL: + switch (CreationParams.DriverType) { + case video::EDT_OPENGL: #ifdef _IRR_COMPILE_WITH_OPENGL_ - { - video::SExposedVideoData data; - data.OpenGLOSX.Window = Window; - ContextManager = new video::CNSOGLManager(); - ContextManager->initialize(CreationParams, data); - VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); - if (!VideoDriver) - { - os::Printer::log("Could not create OpenGL driver.", ELL_ERROR); - } + { + video::SExposedVideoData data; + data.OpenGLOSX.Window = Window; + ContextManager = new video::CNSOGLManager(); + ContextManager->initialize(CreationParams, data); + VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); + if (!VideoDriver) { + os::Printer::log("Could not create OpenGL driver.", ELL_ERROR); + } - if (Window) - { - [[Window contentView] setWantsBestResolutionOpenGLSurface:NO]; - [(NSOpenGLContext*)ContextManager->getContext().OpenGLOSX.Context setView:[Window contentView]]; - } - else - { - [(NSView*)CreationParams.WindowId setWantsBestResolutionOpenGLSurface:NO]; - [(NSOpenGLContext*)ContextManager->getContext().OpenGLOSX.Context setView:(NSView*)CreationParams.WindowId]; - } - } + if (Window) { + [[Window contentView] setWantsBestResolutionOpenGLSurface:NO]; + [(NSOpenGLContext *)ContextManager->getContext().OpenGLOSX.Context setView:[Window contentView]]; + } else { + [(NSView *)CreationParams.WindowId setWantsBestResolutionOpenGLSurface:NO]; + [(NSOpenGLContext *)ContextManager->getContext().OpenGLOSX.Context setView:(NSView *)CreationParams.WindowId]; + } + } #else - os::Printer::log("No OpenGL support compiled in.", ELL_ERROR); + os::Printer::log("No OpenGL support compiled in.", ELL_ERROR); #endif - break; + break; - case video::EDT_OGLES1: - case video::EDT_OGLES2: - os::Printer::log("This driver is not available in OSX. Try OpenGL or Software renderer.", ELL_ERROR); - break; + case video::EDT_OGLES1: + case video::EDT_OGLES2: + os::Printer::log("This driver is not available in OSX. Try OpenGL or Software renderer.", ELL_ERROR); + break; - case video::EDT_NULL: - VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize); - break; + case video::EDT_NULL: + VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize); + break; - default: - os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR); - break; + default: + os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR); + break; } } bool CIrrDeviceMacOSX::run() { - NSAutoreleasePool* Pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *Pool = [[NSAutoreleasePool alloc] init]; NSEvent *event; - irr::SEvent ievent; + irr::SEvent ievent; os::Timer::tick(); storeMouseLocation(); event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES]; - if (event != nil) - { - bzero(&ievent,sizeof(ievent)); + if (event != nil) { + bzero(&ievent, sizeof(ievent)); - switch([(NSEvent *)event type]) - { - case NSKeyDown: - postKeyEvent(event,ievent,true); - break; + switch ([(NSEvent *)event type]) { + case NSKeyDown: + postKeyEvent(event, ievent, true); + break; - case NSKeyUp: - postKeyEvent(event,ievent,false); - break; + case NSKeyUp: + postKeyEvent(event, ievent, false); + break; - case NSFlagsChanged: - ievent.EventType = irr::EET_KEY_INPUT_EVENT; - ievent.KeyInput.Shift = ([(NSEvent *)event modifierFlags] & NSShiftKeyMask) != 0; - ievent.KeyInput.Control = ([(NSEvent *)event modifierFlags] & NSControlKeyMask) != 0; + case NSFlagsChanged: + ievent.EventType = irr::EET_KEY_INPUT_EVENT; + ievent.KeyInput.Shift = ([(NSEvent *)event modifierFlags] & NSShiftKeyMask) != 0; + ievent.KeyInput.Control = ([(NSEvent *)event modifierFlags] & NSControlKeyMask) != 0; - if (IsShiftDown != ievent.KeyInput.Shift) - { - ievent.KeyInput.Char = irr::KEY_SHIFT; - ievent.KeyInput.Key = irr::KEY_SHIFT; - ievent.KeyInput.PressedDown = ievent.KeyInput.Shift; + if (IsShiftDown != ievent.KeyInput.Shift) { + ievent.KeyInput.Char = irr::KEY_SHIFT; + ievent.KeyInput.Key = irr::KEY_SHIFT; + ievent.KeyInput.PressedDown = ievent.KeyInput.Shift; - IsShiftDown = ievent.KeyInput.Shift; + IsShiftDown = ievent.KeyInput.Shift; - postEventFromUser(ievent); - } + postEventFromUser(ievent); + } - if (IsControlDown != ievent.KeyInput.Control) - { - ievent.KeyInput.Char = irr::KEY_CONTROL; - ievent.KeyInput.Key = irr::KEY_CONTROL; - ievent.KeyInput.PressedDown = ievent.KeyInput.Control; + if (IsControlDown != ievent.KeyInput.Control) { + ievent.KeyInput.Char = irr::KEY_CONTROL; + ievent.KeyInput.Key = irr::KEY_CONTROL; + ievent.KeyInput.PressedDown = ievent.KeyInput.Control; - IsControlDown = ievent.KeyInput.Control; + IsControlDown = ievent.KeyInput.Control; - postEventFromUser(ievent); - } + postEventFromUser(ievent); + } - [NSApp sendEvent:event]; - break; + [NSApp sendEvent:event]; + break; - case NSLeftMouseDown: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_LMOUSE_PRESSED_DOWN; - MouseButtonStates |= irr::EMBSM_LEFT; - ievent.MouseInput.ButtonStates = MouseButtonStates; - postMouseEvent(event,ievent); - break; + case NSLeftMouseDown: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_LMOUSE_PRESSED_DOWN; + MouseButtonStates |= irr::EMBSM_LEFT; + ievent.MouseInput.ButtonStates = MouseButtonStates; + postMouseEvent(event, ievent); + break; - case NSLeftMouseUp: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - MouseButtonStates &= !irr::EMBSM_LEFT; - ievent.MouseInput.ButtonStates = MouseButtonStates; - ievent.MouseInput.Event = irr::EMIE_LMOUSE_LEFT_UP; - postMouseEvent(event,ievent); - break; + case NSLeftMouseUp: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + MouseButtonStates &= !irr::EMBSM_LEFT; + ievent.MouseInput.ButtonStates = MouseButtonStates; + ievent.MouseInput.Event = irr::EMIE_LMOUSE_LEFT_UP; + postMouseEvent(event, ievent); + break; - case NSOtherMouseDown: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_MMOUSE_PRESSED_DOWN; - MouseButtonStates |= irr::EMBSM_MIDDLE; - ievent.MouseInput.ButtonStates = MouseButtonStates; - postMouseEvent(event,ievent); - break; + case NSOtherMouseDown: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_MMOUSE_PRESSED_DOWN; + MouseButtonStates |= irr::EMBSM_MIDDLE; + ievent.MouseInput.ButtonStates = MouseButtonStates; + postMouseEvent(event, ievent); + break; - case NSOtherMouseUp: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - MouseButtonStates &= !irr::EMBSM_MIDDLE; - ievent.MouseInput.ButtonStates = MouseButtonStates; - ievent.MouseInput.Event = irr::EMIE_MMOUSE_LEFT_UP; - postMouseEvent(event,ievent); - break; + case NSOtherMouseUp: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + MouseButtonStates &= !irr::EMBSM_MIDDLE; + ievent.MouseInput.ButtonStates = MouseButtonStates; + ievent.MouseInput.Event = irr::EMIE_MMOUSE_LEFT_UP; + postMouseEvent(event, ievent); + break; - case NSMouseMoved: - case NSLeftMouseDragged: - case NSRightMouseDragged: - case NSOtherMouseDragged: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_MOUSE_MOVED; - ievent.MouseInput.ButtonStates = MouseButtonStates; - postMouseEvent(event,ievent); - break; + case NSMouseMoved: + case NSLeftMouseDragged: + case NSRightMouseDragged: + case NSOtherMouseDragged: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_MOUSE_MOVED; + ievent.MouseInput.ButtonStates = MouseButtonStates; + postMouseEvent(event, ievent); + break; - case NSRightMouseDown: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_RMOUSE_PRESSED_DOWN; - MouseButtonStates |= irr::EMBSM_RIGHT; - ievent.MouseInput.ButtonStates = MouseButtonStates; - postMouseEvent(event,ievent); - break; + case NSRightMouseDown: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_RMOUSE_PRESSED_DOWN; + MouseButtonStates |= irr::EMBSM_RIGHT; + ievent.MouseInput.ButtonStates = MouseButtonStates; + postMouseEvent(event, ievent); + break; - case NSRightMouseUp: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_RMOUSE_LEFT_UP; - MouseButtonStates &= !irr::EMBSM_RIGHT; - ievent.MouseInput.ButtonStates = MouseButtonStates; - postMouseEvent(event,ievent); - break; + case NSRightMouseUp: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_RMOUSE_LEFT_UP; + MouseButtonStates &= !irr::EMBSM_RIGHT; + ievent.MouseInput.ButtonStates = MouseButtonStates; + postMouseEvent(event, ievent); + break; - case NSScrollWheel: - ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; - ievent.MouseInput.Event = irr::EMIE_MOUSE_WHEEL; - ievent.MouseInput.Wheel = [(NSEvent *)event deltaY]; - if (ievent.MouseInput.Wheel < 1.0f) - ievent.MouseInput.Wheel *= 10.0f; - else - ievent.MouseInput.Wheel *= 5.0f; - postMouseEvent(event,ievent); - break; + case NSScrollWheel: + ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; + ievent.MouseInput.Event = irr::EMIE_MOUSE_WHEEL; + ievent.MouseInput.Wheel = [(NSEvent *)event deltaY]; + if (ievent.MouseInput.Wheel < 1.0f) + ievent.MouseInput.Wheel *= 10.0f; + else + ievent.MouseInput.Wheel *= 5.0f; + postMouseEvent(event, ievent); + break; - default: - [NSApp sendEvent:event]; - break; + default: + [NSApp sendEvent:event]; + break; } } @@ -910,23 +869,21 @@ bool CIrrDeviceMacOSX::run() return (![[NSApp delegate] isQuit] && IsActive); } - //! Pause the current process for the minimum time allowed only to allow other processes to execute void CIrrDeviceMacOSX::yield() { - struct timespec ts = {0,0}; + struct timespec ts = {0, 0}; nanosleep(&ts, NULL); } - //! Pause execution and let other processes to run for a specified amount of time. -void CIrrDeviceMacOSX::sleep(u32 timeMs, bool pauseTimer=false) +void CIrrDeviceMacOSX::sleep(u32 timeMs, bool pauseTimer = false) { bool wasStopped = Timer ? Timer->isStopped() : true; struct timespec ts; - ts.tv_sec = (time_t) (timeMs / 1000); - ts.tv_nsec = (long) (timeMs % 1000) * 1000000; + ts.tv_sec = (time_t)(timeMs / 1000); + ts.tv_nsec = (long)(timeMs % 1000) * 1000000; if (pauseTimer && !wasStopped) Timer->stop(); @@ -937,13 +894,10 @@ void CIrrDeviceMacOSX::sleep(u32 timeMs, bool pauseTimer=false) Timer->start(); } - -void CIrrDeviceMacOSX::setWindowCaption(const wchar_t* text) +void CIrrDeviceMacOSX::setWindowCaption(const wchar_t *text) { - if (Window != NULL) - { - if ( text ) - { + if (Window != NULL) { + if (text) { size_t numBytes = wcslen(text) * sizeof(wchar_t); #ifdef __BIG_ENDIAN__ @@ -951,27 +905,22 @@ void CIrrDeviceMacOSX::setWindowCaption(const wchar_t* text) #else NSStringEncoding encode = sizeof(wchar_t) == 4 ? NSUTF32LittleEndianStringEncoding : NSUTF16LittleEndianStringEncoding; #endif - NSString* name = [[NSString alloc] initWithBytes:text length:numBytes encoding:encode]; - if ( name ) - { + NSString *name = [[NSString alloc] initWithBytes:text length:numBytes encoding:encode]; + if (name) { [Window setTitle:name]; [name release]; } - } - else - { + } else { [Window setTitle:@""]; } } } - bool CIrrDeviceMacOSX::isWindowActive() const { return (IsActive); } - bool CIrrDeviceMacOSX::isWindowFocused() const { if (Window != NULL) @@ -979,7 +928,6 @@ bool CIrrDeviceMacOSX::isWindowFocused() const return false; } - bool CIrrDeviceMacOSX::isWindowMinimized() const { if (Window != NULL) @@ -987,18 +935,16 @@ bool CIrrDeviceMacOSX::isWindowMinimized() const return false; } - -void CIrrDeviceMacOSX::postKeyEvent(void *event,irr::SEvent &ievent,bool pressed) +void CIrrDeviceMacOSX::postKeyEvent(void *event, irr::SEvent &ievent, bool pressed) { NSString *str; - std::map::const_iterator iter; - unsigned int c,mkey,mchar; + std::map::const_iterator iter; + unsigned int c, mkey, mchar; const unsigned char *cStr; BOOL skipCommand; str = [(NSEvent *)event characters]; - if ((str != nil) && ([str length] > 0)) - { + if ((str != nil) && ([str length] > 0)) { mkey = mchar = 0; skipCommand = false; c = [str characterAtIndex:0]; @@ -1007,27 +953,20 @@ void CIrrDeviceMacOSX::postKeyEvent(void *event,irr::SEvent &ievent,bool pressed iter = KeyCodes.find([(NSEvent *)event keyCode]); if (iter != KeyCodes.end()) mkey = (*iter).second; - else if ((iter = KeyCodes.find(c)) != KeyCodes.end()) + else if ((iter = KeyCodes.find(c)) != KeyCodes.end()) mkey = (*iter).second; - else - { + else { // workaround for period character - if (c == 0x2E) - { + if (c == 0x2E) { mkey = irr::KEY_PERIOD; mchar = '.'; - } - else - { + } else { cStr = (unsigned char *)[str cStringUsingEncoding:NSWindowsCP1252StringEncoding]; - if (cStr != NULL && strlen((char*)cStr) > 0) - { + if (cStr != NULL && strlen((char *)cStr) > 0) { mchar = cStr[0]; mkey = toupper(mchar); - if ([(NSEvent *)event modifierFlags] & NSCommandKeyMask) - { - if (mkey == 'C' || mkey == 'V' || mkey == 'X') - { + if ([(NSEvent *)event modifierFlags] & NSCommandKeyMask) { + if (mkey == 'C' || mkey == 'V' || mkey == 'X') { mchar = 0; skipCommand = true; } @@ -1052,21 +991,17 @@ void CIrrDeviceMacOSX::postKeyEvent(void *event,irr::SEvent &ievent,bool pressed } } - -void CIrrDeviceMacOSX::postMouseEvent(void *event,irr::SEvent &ievent) +void CIrrDeviceMacOSX::postMouseEvent(void *event, irr::SEvent &ievent) { bool post = true; - if (Window != NULL) - { + if (Window != NULL) { ievent.MouseInput.X = (int)[(NSEvent *)event locationInWindow].x; ievent.MouseInput.Y = DeviceHeight - (int)[(NSEvent *)event locationInWindow].y; if (ievent.MouseInput.Y < 0) post = false; - } - else - { + } else { CGEventRef ourEvent = CGEventCreate(NULL); CGPoint point = CGEventGetLocation(ourEvent); CFRelease(ourEvent); @@ -1078,8 +1013,7 @@ void CIrrDeviceMacOSX::postMouseEvent(void *event,irr::SEvent &ievent) post = false; } - if (post) - { + if (post) { ievent.MouseInput.Shift = ([(NSEvent *)event modifierFlags] & NSShiftKeyMask) != 0; ievent.MouseInput.Control = ([(NSEvent *)event modifierFlags] & NSControlKeyMask) != 0; @@ -1089,21 +1023,17 @@ void CIrrDeviceMacOSX::postMouseEvent(void *event,irr::SEvent &ievent) [NSApp sendEvent:(NSEvent *)event]; } - void CIrrDeviceMacOSX::storeMouseLocation() { - int x,y; + int x, y; - if (Window != NULL) - { - NSPoint p; + if (Window != NULL) { + NSPoint p; p = [NSEvent mouseLocation]; p = [Window convertScreenToBase:p]; x = (int)p.x; y = DeviceHeight - (int)p.y; - } - else - { + } else { // Do we still need this? CGEventRef ourEvent = CGEventCreate(NULL); CGPoint point = CGEventGetLocation(ourEvent); @@ -1112,9 +1042,8 @@ void CIrrDeviceMacOSX::storeMouseLocation() x = (int)point.x; y = (int)point.y; - const core::position2di& curr = ((CCursorControl *)CursorControl)->getPosition(true); - if (curr.X != x || curr.Y != y) - { + const core::position2di &curr = ((CCursorControl *)CursorControl)->getPosition(true); + if (curr.X != x || curr.Y != y) { irr::SEvent ievent; ievent.EventType = irr::EET_MOUSE_INPUT_EVENT; ievent.MouseInput.Event = irr::EMIE_MOUSE_MOVED; @@ -1124,27 +1053,23 @@ void CIrrDeviceMacOSX::storeMouseLocation() } } - ((CCursorControl *)CursorControl)->updateInternalCursorPosition(x,y); + ((CCursorControl *)CursorControl)->updateInternalCursorPosition(x, y); } - -void CIrrDeviceMacOSX::setMouseLocation(int x,int y) +void CIrrDeviceMacOSX::setMouseLocation(int x, int y) { - NSPoint p; - CGPoint c; + NSPoint p; + CGPoint c; - if (Window != NULL) - { + if (Window != NULL) { // Irrlicht window exists - p.x = (float) x; - p.y = (float) (DeviceHeight - y); + p.x = (float)x; + p.y = (float)(DeviceHeight - y); p = [Window convertBaseToScreen:p]; p.y = ScreenHeight - p.y; - } - else - { - p.x = (float) x; - p.y = (float) y + (ScreenHeight - DeviceHeight); + } else { + p.x = (float)x; + p.y = (float)y + (ScreenHeight - DeviceHeight); } c.x = p.x; @@ -1154,7 +1079,6 @@ void CIrrDeviceMacOSX::setMouseLocation(int x,int y) CGAssociateMouseAndMouseCursorPosition(YES); } - void CIrrDeviceMacOSX::setCursorVisible(bool visible) { if (visible) @@ -1163,41 +1087,39 @@ void CIrrDeviceMacOSX::setCursorVisible(bool visible) CGDisplayHideCursor(CGMainDisplayID()); } - -void CIrrDeviceMacOSX::setWindow(NSWindow* window) +void CIrrDeviceMacOSX::setWindow(NSWindow *window) { - Window = window; + Window = window; } - void CIrrDeviceMacOSX::initKeycodes() { KeyCodes[kVK_UpArrow] = irr::KEY_UP; KeyCodes[kVK_DownArrow] = irr::KEY_DOWN; KeyCodes[kVK_LeftArrow] = irr::KEY_LEFT; KeyCodes[kVK_RightArrow] = irr::KEY_RIGHT; - KeyCodes[kVK_F1] = irr::KEY_F1; - KeyCodes[kVK_F2] = irr::KEY_F2; - KeyCodes[kVK_F3] = irr::KEY_F3; - KeyCodes[kVK_F4] = irr::KEY_F4; - KeyCodes[kVK_F5] = irr::KEY_F5; - KeyCodes[kVK_F6] = irr::KEY_F6; - KeyCodes[kVK_F7] = irr::KEY_F7; - KeyCodes[kVK_F8] = irr::KEY_F8; - KeyCodes[kVK_F9] = irr::KEY_F9; - KeyCodes[kVK_F10] = irr::KEY_F10; - KeyCodes[kVK_F11] = irr::KEY_F11; - KeyCodes[kVK_F12] = irr::KEY_F12; - KeyCodes[kVK_F13] = irr::KEY_F13; - KeyCodes[kVK_F14] = irr::KEY_F14; - KeyCodes[kVK_F15] = irr::KEY_F15; - KeyCodes[kVK_F16] = irr::KEY_F16; - KeyCodes[kVK_F17] = irr::KEY_F17; - KeyCodes[kVK_F18] = irr::KEY_F18; - KeyCodes[kVK_F19] = irr::KEY_F19; - KeyCodes[kVK_F20] = irr::KEY_F20; - KeyCodes[kVK_Home] = irr::KEY_HOME; - KeyCodes[kVK_End] = irr::KEY_END; + KeyCodes[kVK_F1] = irr::KEY_F1; + KeyCodes[kVK_F2] = irr::KEY_F2; + KeyCodes[kVK_F3] = irr::KEY_F3; + KeyCodes[kVK_F4] = irr::KEY_F4; + KeyCodes[kVK_F5] = irr::KEY_F5; + KeyCodes[kVK_F6] = irr::KEY_F6; + KeyCodes[kVK_F7] = irr::KEY_F7; + KeyCodes[kVK_F8] = irr::KEY_F8; + KeyCodes[kVK_F9] = irr::KEY_F9; + KeyCodes[kVK_F10] = irr::KEY_F10; + KeyCodes[kVK_F11] = irr::KEY_F11; + KeyCodes[kVK_F12] = irr::KEY_F12; + KeyCodes[kVK_F13] = irr::KEY_F13; + KeyCodes[kVK_F14] = irr::KEY_F14; + KeyCodes[kVK_F15] = irr::KEY_F15; + KeyCodes[kVK_F16] = irr::KEY_F16; + KeyCodes[kVK_F17] = irr::KEY_F17; + KeyCodes[kVK_F18] = irr::KEY_F18; + KeyCodes[kVK_F19] = irr::KEY_F19; + KeyCodes[kVK_F20] = irr::KEY_F20; + KeyCodes[kVK_Home] = irr::KEY_HOME; + KeyCodes[kVK_End] = irr::KEY_END; KeyCodes[NSInsertFunctionKey] = irr::KEY_INSERT; KeyCodes[kVK_ForwardDelete] = irr::KEY_DELETE; KeyCodes[kVK_Help] = irr::KEY_HELP; @@ -1287,7 +1209,6 @@ void CIrrDeviceMacOSX::initKeycodes() KeyCodes[kVK_ANSI_RightBracket] = irr::KEY_OEM_6; } - //! Sets if the window should be resizable in windowed mode. void CIrrDeviceMacOSX::setResizable(bool resize) { @@ -1300,27 +1221,23 @@ void CIrrDeviceMacOSX::setResizable(bool resize) #endif } - bool CIrrDeviceMacOSX::isResizable() const { return IsResizable; } - void CIrrDeviceMacOSX::minimizeWindow() { if (Window != NULL) [Window miniaturize:[NSApp self]]; } - //! Maximizes the window if possible. void CIrrDeviceMacOSX::maximizeWindow() { // todo: implement } - //! get the window to normal size if possible. void CIrrDeviceMacOSX::restoreWindow() { @@ -1335,20 +1252,18 @@ core::position2di CIrrDeviceMacOSX::getWindowPosition() return core::position2di(rect.origin.x, screenHeight - rect.origin.y - rect.size.height); } - -#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) -static void joystickRemovalCallback(void * target, - IOReturn result, void * refcon, void * sender) +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) +static void joystickRemovalCallback(void *target, + IOReturn result, void *refcon, void *sender) { - JoystickInfo *joy = (JoystickInfo *) refcon; + JoystickInfo *joy = (JoystickInfo *)refcon; joy->removed = 1; } #endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ - -bool CIrrDeviceMacOSX::activateJoysticks(core::array & joystickInfo) +bool CIrrDeviceMacOSX::activateJoysticks(core::array &joystickInfo) { -#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) ActiveJoysticks.clear(); joystickInfo.clear(); @@ -1358,96 +1273,81 @@ bool CIrrDeviceMacOSX::activateJoysticks(core::array & joystickIn mach_port_t masterPort = 0; CFMutableDictionaryRef hidDictionaryRef = NULL; - result = IOMasterPort (bootstrap_port, &masterPort); - if (kIOReturnSuccess != result) - { + result = IOMasterPort(bootstrap_port, &masterPort); + if (kIOReturnSuccess != result) { os::Printer::log("initialiseJoysticks IOMasterPort failed", ELL_ERROR); return false; } - hidDictionaryRef = IOServiceMatching (kIOHIDDeviceKey); - if (!hidDictionaryRef) - { + hidDictionaryRef = IOServiceMatching(kIOHIDDeviceKey); + if (!hidDictionaryRef) { os::Printer::log("initialiseJoysticks IOServiceMatching failed", ELL_ERROR); return false; } - result = IOServiceGetMatchingServices (masterPort, hidDictionaryRef, &hidIterator); + result = IOServiceGetMatchingServices(masterPort, hidDictionaryRef, &hidIterator); - if (kIOReturnSuccess != result) - { + if (kIOReturnSuccess != result) { os::Printer::log("initialiseJoysticks IOServiceGetMatchingServices failed", ELL_ERROR); return false; } - //no joysticks just return + // no joysticks just return if (!hidIterator) return false; u32 jindex = 0u; - while ((hidObject = IOIteratorNext (hidIterator))) - { + while ((hidObject = IOIteratorNext(hidIterator))) { JoystickInfo info; // get dictionary for HID properties CFMutableDictionaryRef hidProperties = 0; - kern_return_t kern_result = IORegistryEntryCreateCFProperties (hidObject, &hidProperties, kCFAllocatorDefault, kNilOptions); - if ((kern_result == KERN_SUCCESS) && hidProperties) - { + kern_return_t kern_result = IORegistryEntryCreateCFProperties(hidObject, &hidProperties, kCFAllocatorDefault, kNilOptions); + if ((kern_result == KERN_SUCCESS) && hidProperties) { HRESULT plugInResult = S_OK; SInt32 score = 0; - IOCFPlugInInterface ** ppPlugInInterface = NULL; - result = IOCreatePlugInInterfaceForService (hidObject, kIOHIDDeviceUserClientTypeID, - kIOCFPlugInInterfaceID, &ppPlugInInterface, &score); - if (kIOReturnSuccess == result) - { - plugInResult = (*ppPlugInInterface)->QueryInterface (ppPlugInInterface, - CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), (void **) &(info.interface)); + IOCFPlugInInterface **ppPlugInInterface = NULL; + result = IOCreatePlugInInterfaceForService(hidObject, kIOHIDDeviceUserClientTypeID, + kIOCFPlugInInterfaceID, &ppPlugInInterface, &score); + if (kIOReturnSuccess == result) { + plugInResult = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void **)&(info.interface)); if (plugInResult != S_OK) os::Printer::log("initialiseJoysticks query HID class device interface failed", ELL_ERROR); (*ppPlugInInterface)->Release(ppPlugInInterface); - } - else + } else continue; - if (info.interface != NULL) - { - result = (*(info.interface))->open (info.interface, 0); - if (result == kIOReturnSuccess) - { - (*(info.interface))->setRemovalCallback (info.interface, joystickRemovalCallback, &info, &info); + if (info.interface != NULL) { + result = (*(info.interface))->open(info.interface, 0); + if (result == kIOReturnSuccess) { + (*(info.interface))->setRemovalCallback(info.interface, joystickRemovalCallback, &info, &info); getJoystickDeviceInfo(hidObject, hidProperties, &info); // get elements - CFTypeRef refElementTop = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey)); - if (refElementTop) - { - CFTypeID type = CFGetTypeID (refElementTop); - if (type == CFArrayGetTypeID()) - { - CFRange range = {0, CFArrayGetCount ((CFArrayRef)refElementTop)}; + CFTypeRef refElementTop = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDElementKey)); + if (refElementTop) { + CFTypeID type = CFGetTypeID(refElementTop); + if (type == CFArrayGetTypeID()) { + CFRange range = {0, CFArrayGetCount((CFArrayRef)refElementTop)}; info.numActiveJoysticks = ActiveJoysticks.size(); - CFArrayApplyFunction ((CFArrayRef)refElementTop, range, getJoystickComponentArrayHandler, &info); + CFArrayApplyFunction((CFArrayRef)refElementTop, range, getJoystickComponentArrayHandler, &info); } } - } - else - { - CFRelease (hidProperties); + } else { + CFRelease(hidProperties); os::Printer::log("initialiseJoysticks Open interface failed", ELL_ERROR); continue; } - CFRelease (hidProperties); + CFRelease(hidProperties); - result = IOObjectRelease (hidObject); + result = IOObjectRelease(hidObject); - if ( (info.usagePage != kHIDPage_GenericDesktop) || - ((info.usage != kHIDUsage_GD_Joystick && - info.usage != kHIDUsage_GD_GamePad && - info.usage != kHIDUsage_GD_MultiAxisController)) ) - { - closeJoystickDevice (&info); + if ((info.usagePage != kHIDPage_GenericDesktop) || + ((info.usage != kHIDUsage_GD_Joystick && + info.usage != kHIDUsage_GD_GamePad && + info.usage != kHIDUsage_GD_MultiAxisController))) { + closeJoystickDevice(&info); continue; } @@ -1459,27 +1359,25 @@ bool CIrrDeviceMacOSX::activateJoysticks(core::array & joystickIn SJoystickInfo returnInfo; returnInfo.Joystick = jindex; returnInfo.Axes = info.axes; - //returnInfo.Hats = info.hats; + // returnInfo.Hats = info.hats; returnInfo.Buttons = info.buttons; returnInfo.Name = info.joystickName; returnInfo.PovHat = SJoystickInfo::POV_HAT_UNKNOWN; - ++ jindex; + ++jindex; - //if (info.hatComp.size()) + // if (info.hatComp.size()) // returnInfo.PovHat = SJoystickInfo::POV_HAT_PRESENT; - //else + // else // returnInfo.PovHat = SJoystickInfo::POV_HAT_ABSENT; joystickInfo.push_back(returnInfo); } - } - else - { + } else { continue; } } - result = IOObjectRelease (hidIterator); + result = IOObjectRelease(hidIterator); return true; #endif // _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ @@ -1489,29 +1387,25 @@ bool CIrrDeviceMacOSX::activateJoysticks(core::array & joystickIn void CIrrDeviceMacOSX::pollJoysticks() { -#if defined (_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - if(0 == ActiveJoysticks.size()) +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) + if (0 == ActiveJoysticks.size()) return; u32 joystick; - for (joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { + for (joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { if (ActiveJoysticks[joystick].removed) continue; bool found = false; ActiveJoysticks[joystick].persistentData.JoystickEvent.Joystick = joystick; - if (ActiveJoysticks[joystick].interface) - { - for (u32 n = 0; n < ActiveJoysticks[joystick].axisComp.size(); n++) - { + if (ActiveJoysticks[joystick].interface) { + for (u32 n = 0; n < ActiveJoysticks[joystick].axisComp.size(); n++) { IOReturn result = kIOReturnSuccess; IOHIDEventStruct hidEvent; hidEvent.value = 0; result = (*(ActiveJoysticks[joystick].interface))->getElementValue(ActiveJoysticks[joystick].interface, ActiveJoysticks[joystick].axisComp[n].cookie, &hidEvent); - if (kIOReturnSuccess == result) - { + if (kIOReturnSuccess == result) { const f32 min = -32768.0f; const f32 max = 32767.0f; const f32 deviceScale = max - min; @@ -1529,43 +1423,41 @@ void CIrrDeviceMacOSX::pollJoysticks() found = true; ActiveJoysticks[joystick].persistentData.JoystickEvent.Axis[n] = (s16)hidEvent.value; } - }//axis check + } // axis check - for (u32 n = 0; n < ActiveJoysticks[joystick].buttonComp.size(); n++) - { + for (u32 n = 0; n < ActiveJoysticks[joystick].buttonComp.size(); n++) { IOReturn result = kIOReturnSuccess; IOHIDEventStruct hidEvent; hidEvent.value = 0; result = (*(ActiveJoysticks[joystick].interface))->getElementValue(ActiveJoysticks[joystick].interface, ActiveJoysticks[joystick].buttonComp[n].cookie, &hidEvent); - if (kIOReturnSuccess == result) - { - if (hidEvent.value && !((ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates & (1 << n)) ? true : false) ) - found = true; + if (kIOReturnSuccess == result) { + if (hidEvent.value && !((ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates & (1 << n)) ? true : false)) + found = true; else if (!hidEvent.value && ((ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates & (1 << n)) ? true : false)) - found = true; + found = true; if (hidEvent.value) - ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates |= (1 << n); + ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates |= (1 << n); else - ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates &= ~(1 << n); + ActiveJoysticks[joystick].persistentData.JoystickEvent.ButtonStates &= ~(1 << n); } - }//button check - //still ToDo..will be done soon :) -/* - for (u32 n = 0; n < ActiveJoysticks[joystick].hatComp.size(); n++) - { - IOReturn result = kIOReturnSuccess; - IOHIDEventStruct hidEvent; - hidEvent.value = 0; - result = (*(ActiveJoysticks[joystick].interface))->getElementValue(ActiveJoysticks[joystick].interface, ActiveJoysticks[joystick].hatComp[n].cookie, &hidEvent); - if (kIOReturnSuccess == result) - { - if (ActiveJoysticks[joystick].persistentData.JoystickEvent.POV != hidEvent.value) - found = true; - ActiveJoysticks[joystick].persistentData.JoystickEvent.POV = hidEvent.value; - } - }//hat check -*/ + } // button check + // still ToDo..will be done soon :) + /* + for (u32 n = 0; n < ActiveJoysticks[joystick].hatComp.size(); n++) + { + IOReturn result = kIOReturnSuccess; + IOHIDEventStruct hidEvent; + hidEvent.value = 0; + result = (*(ActiveJoysticks[joystick].interface))->getElementValue(ActiveJoysticks[joystick].interface, ActiveJoysticks[joystick].hatComp[n].cookie, &hidEvent); + if (kIOReturnSuccess == result) + { + if (ActiveJoysticks[joystick].persistentData.JoystickEvent.POV != hidEvent.value) + found = true; + ActiveJoysticks[joystick].persistentData.JoystickEvent.POV = hidEvent.value; + } + }//hat check + */ } if (found) @@ -1577,4 +1469,3 @@ void CIrrDeviceMacOSX::pollJoysticks() } // end namespace #endif // _IRR_COMPILE_WITH_OSX_DEVICE_ - diff --git a/source/Irrlicht/CIrrDeviceSDL.cpp b/source/Irrlicht/CIrrDeviceSDL.cpp index 735a89e4..bc4c9bb3 100644 --- a/source/Irrlicht/CIrrDeviceSDL.cpp +++ b/source/Irrlicht/CIrrDeviceSDL.cpp @@ -2,7 +2,6 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h - #ifdef _IRR_COMPILE_WITH_SDL_DEVICE_ #include "CIrrDeviceSDL.h" @@ -31,56 +30,55 @@ static int SDLDeviceInstances = 0; namespace irr { - namespace video - { - #ifdef _IRR_COMPILE_WITH_OPENGL_ - IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - #else - static IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("No OpenGL support compiled in.", ELL_ERROR); - return nullptr; - } - #endif +namespace video +{ +#ifdef _IRR_COMPILE_WITH_OPENGL_ +IVideoDriver *createOpenGLDriver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); +#else +static IVideoDriver *createOpenGLDriver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("No OpenGL support compiled in.", ELL_ERROR); + return nullptr; +} +#endif - #ifdef ENABLE_OPENGL3 - IVideoDriver* createOpenGL3Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - #else - static IVideoDriver* createOpenGL3Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("No OpenGL 3 support compiled in.", ELL_ERROR); - return nullptr; - } - #endif +#ifdef ENABLE_OPENGL3 +IVideoDriver *createOpenGL3Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); +#else +static IVideoDriver *createOpenGL3Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("No OpenGL 3 support compiled in.", ELL_ERROR); + return nullptr; +} +#endif - #ifdef _IRR_COMPILE_WITH_OGLES2_ - IVideoDriver* createOGLES2Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - #else - static IVideoDriver* createOGLES2Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("No OpenGL ES 2 support compiled in.", ELL_ERROR); - return nullptr; - } - #endif +#ifdef _IRR_COMPILE_WITH_OGLES2_ +IVideoDriver *createOGLES2Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); +#else +static IVideoDriver *createOGLES2Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("No OpenGL ES 2 support compiled in.", ELL_ERROR); + return nullptr; +} +#endif - #ifdef _IRR_COMPILE_WITH_WEBGL1_ - IVideoDriver* createWebGL1Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - #else - static IVideoDriver* createWebGL1Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("No WebGL 1 support compiled in.", ELL_ERROR); - return nullptr; - } - #endif - } // end namespace video +#ifdef _IRR_COMPILE_WITH_WEBGL1_ +IVideoDriver *createWebGL1Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); +#else +static IVideoDriver *createWebGL1Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("No WebGL 1 support compiled in.", ELL_ERROR); + return nullptr; +} +#endif +} // end namespace video } // end namespace irr - namespace irr { #ifdef _IRR_EMSCRIPTEN_PLATFORM_ -EM_BOOL CIrrDeviceSDL::MouseUpDownCallback(int eventType, const EmscriptenMouseEvent * event, void* userData) +EM_BOOL CIrrDeviceSDL::MouseUpDownCallback(int eventType, const EmscriptenMouseEvent *event, void *userData) { // We need this callback so far only because otherwise "emscripten_request_pointerlock" calls will // fail as their request are infinitely deferred. @@ -90,7 +88,7 @@ EM_BOOL CIrrDeviceSDL::MouseUpDownCallback(int eventType, const EmscriptenMouseE EM_BOOL CIrrDeviceSDL::MouseEnterCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) { - CIrrDeviceSDL * This = static_cast(userData); + CIrrDeviceSDL *This = static_cast(userData); SEvent irrevent; @@ -100,7 +98,7 @@ EM_BOOL CIrrDeviceSDL::MouseEnterCallback(int eventType, const EmscriptenMouseEv This->MouseY = irrevent.MouseInput.Y = mouseEvent->canvasY; This->MouseXRel = mouseEvent->movementX; // should be 0 I guess? Or can it enter while pointer is locked()? This->MouseYRel = mouseEvent->movementY; - irrevent.MouseInput.ButtonStates = This->MouseButtonStates; // TODO: not correct, but couldn't figure out the bitset of mouseEvent->buttons yet. + irrevent.MouseInput.ButtonStates = This->MouseButtonStates; // TODO: not correct, but couldn't figure out the bitset of mouseEvent->buttons yet. irrevent.MouseInput.Shift = mouseEvent->shiftKey; irrevent.MouseInput.Control = mouseEvent->ctrlKey; @@ -111,7 +109,7 @@ EM_BOOL CIrrDeviceSDL::MouseEnterCallback(int eventType, const EmscriptenMouseEv EM_BOOL CIrrDeviceSDL::MouseLeaveCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) { - CIrrDeviceSDL * This = static_cast(userData); + CIrrDeviceSDL *This = static_cast(userData); SEvent irrevent; @@ -121,7 +119,7 @@ EM_BOOL CIrrDeviceSDL::MouseLeaveCallback(int eventType, const EmscriptenMouseEv This->MouseY = irrevent.MouseInput.Y = mouseEvent->canvasY; This->MouseXRel = mouseEvent->movementX; // should be 0 I guess? Or can it enter while pointer is locked()? This->MouseYRel = mouseEvent->movementY; - irrevent.MouseInput.ButtonStates = This->MouseButtonStates; // TODO: not correct, but couldn't figure out the bitset of mouseEvent->buttons yet. + irrevent.MouseInput.ButtonStates = This->MouseButtonStates; // TODO: not correct, but couldn't figure out the bitset of mouseEvent->buttons yet. irrevent.MouseInput.Shift = mouseEvent->shiftKey; irrevent.MouseInput.Control = mouseEvent->ctrlKey; @@ -131,65 +129,63 @@ EM_BOOL CIrrDeviceSDL::MouseLeaveCallback(int eventType, const EmscriptenMouseEv } #endif - bool CIrrDeviceSDL::keyIsKnownSpecial(EKEY_CODE key) { - switch ( key ) - { - // keys which are known to have safe special character interpretation - // could need changes over time (removals and additions!) - case KEY_RETURN: - case KEY_PAUSE: - case KEY_ESCAPE: - case KEY_PRIOR: - case KEY_NEXT: - case KEY_HOME: - case KEY_END: - case KEY_LEFT: - case KEY_UP: - case KEY_RIGHT: - case KEY_DOWN: - case KEY_TAB: - case KEY_PRINT: - case KEY_SNAPSHOT: - case KEY_INSERT: - case KEY_BACK: - case KEY_DELETE: - case KEY_HELP: - case KEY_APPS: - case KEY_SLEEP: - case KEY_F1: - case KEY_F2: - case KEY_F3: - case KEY_F4: - case KEY_F5: - case KEY_F6: - case KEY_F7: - case KEY_F8: - case KEY_F9: - case KEY_F10: - case KEY_F11: - case KEY_F12: - case KEY_F13: - case KEY_F14: - case KEY_F15: - case KEY_F16: - case KEY_F17: - case KEY_F18: - case KEY_F19: - case KEY_F20: - case KEY_F21: - case KEY_F22: - case KEY_F23: - case KEY_F24: - case KEY_NUMLOCK: - case KEY_SCROLL: - case KEY_LCONTROL: - case KEY_RCONTROL: - return true; + switch (key) { + // keys which are known to have safe special character interpretation + // could need changes over time (removals and additions!) + case KEY_RETURN: + case KEY_PAUSE: + case KEY_ESCAPE: + case KEY_PRIOR: + case KEY_NEXT: + case KEY_HOME: + case KEY_END: + case KEY_LEFT: + case KEY_UP: + case KEY_RIGHT: + case KEY_DOWN: + case KEY_TAB: + case KEY_PRINT: + case KEY_SNAPSHOT: + case KEY_INSERT: + case KEY_BACK: + case KEY_DELETE: + case KEY_HELP: + case KEY_APPS: + case KEY_SLEEP: + case KEY_F1: + case KEY_F2: + case KEY_F3: + case KEY_F4: + case KEY_F5: + case KEY_F6: + case KEY_F7: + case KEY_F8: + case KEY_F9: + case KEY_F10: + case KEY_F11: + case KEY_F12: + case KEY_F13: + case KEY_F14: + case KEY_F15: + case KEY_F16: + case KEY_F17: + case KEY_F18: + case KEY_F19: + case KEY_F20: + case KEY_F21: + case KEY_F22: + case KEY_F23: + case KEY_F24: + case KEY_NUMLOCK: + case KEY_SCROLL: + case KEY_LCONTROL: + case KEY_RCONTROL: + return true; - default: - return false; + default: + return false; } } @@ -198,45 +194,44 @@ int CIrrDeviceSDL::findCharToPassToIrrlicht(int assumedChar, EKEY_CODE key) // special cases that always return a char regardless of how the SDL keycode // looks switch (key) { - case KEY_RETURN: - case KEY_ESCAPE: - return (int)key; - default: - break; + case KEY_RETURN: + case KEY_ESCAPE: + return (int)key; + default: + break; } // SDL in-place ORs values with no character representation with 1<<30 // https://wiki.libsdl.org/SDL2/SDLKeycodeLookup - if (assumedChar & (1<<30)) + if (assumedChar & (1 << 30)) return 0; switch (key) { - case KEY_PRIOR: - case KEY_NEXT: - case KEY_HOME: - case KEY_END: - case KEY_LEFT: - case KEY_UP: - case KEY_RIGHT: - case KEY_DOWN: - case KEY_NUMLOCK: - return 0; - default: - return assumedChar; + case KEY_PRIOR: + case KEY_NEXT: + case KEY_HOME: + case KEY_END: + case KEY_LEFT: + case KEY_UP: + case KEY_RIGHT: + case KEY_DOWN: + case KEY_NUMLOCK: + return 0; + default: + return assumedChar; } } -void CIrrDeviceSDL::resetReceiveTextInputEvents() { +void CIrrDeviceSDL::resetReceiveTextInputEvents() +{ gui::IGUIElement *elem = GUIEnvironment->getFocus(); - if (elem && elem->acceptsIME()) - { + if (elem && elem->acceptsIME()) { // IBus seems to have an issue where dead keys and compose keys do not // work (specifically, the individual characters in the sequence are // sent as text input events instead of the result) when // SDL_StartTextInput() is called on the same input box. core::rect pos = elem->getAbsolutePosition(); - if (!SDL_IsTextInputActive() || lastElemPos != pos) - { + if (!SDL_IsTextInputActive() || lastElemPos != pos) { lastElemPos = pos; SDL_Rect rect; rect.x = pos.UpperLeftCorner.X; @@ -246,40 +241,34 @@ void CIrrDeviceSDL::resetReceiveTextInputEvents() { SDL_SetTextInputRect(&rect); SDL_StartTextInput(); } - } - else - { + } else { SDL_StopTextInput(); } } //! constructor -CIrrDeviceSDL::CIrrDeviceSDL(const SIrrlichtCreationParameters& param) - : CIrrDeviceStub(param), - Window((SDL_Window*)param.WindowId), SDL_Flags(0), - MouseX(0), MouseY(0), MouseXRel(0), MouseYRel(0), MouseButtonStates(0), - Width(param.WindowSize.Width), Height(param.WindowSize.Height), - Resizable(param.WindowResizable == 1 ? true : false), CurrentTouchCount(0) +CIrrDeviceSDL::CIrrDeviceSDL(const SIrrlichtCreationParameters ¶m) : + CIrrDeviceStub(param), + Window((SDL_Window *)param.WindowId), SDL_Flags(0), + MouseX(0), MouseY(0), MouseXRel(0), MouseYRel(0), MouseButtonStates(0), + Width(param.WindowSize.Width), Height(param.WindowSize.Height), + Resizable(param.WindowResizable == 1 ? true : false), CurrentTouchCount(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CIrrDeviceSDL"); - #endif +#endif - if ( ++SDLDeviceInstances == 1 ) - { + if (++SDLDeviceInstances == 1) { u32 flags = SDL_INIT_TIMER | SDL_INIT_EVENTS; if (CreationParams.DriverType != video::EDT_NULL) flags |= SDL_INIT_VIDEO; #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) flags |= SDL_INIT_JOYSTICK; #endif - if (SDL_Init(flags) < 0) - { + if (SDL_Init(flags) < 0) { os::Printer::log("Unable to initialize SDL", SDL_GetError(), ELL_ERROR); Close = true; - } - else - { + } else { os::Printer::log("SDL initialized", ELL_INFORMATION); } } @@ -293,19 +282,17 @@ CIrrDeviceSDL::CIrrDeviceSDL(const SIrrlichtCreationParameters& param) createKeyMap(); // create window - if (CreationParams.DriverType != video::EDT_NULL) - { + if (CreationParams.DriverType != video::EDT_NULL) { if (!createWindow()) { Close = true; return; } } - SDL_VERSION(&Info.version); #ifndef _IRR_EMSCRIPTEN_PLATFORM_ - SDL_GetWindowWMInfo(Window,&Info); + SDL_GetWindowWMInfo(Window, &Info); #endif //_IRR_EMSCRIPTEN_PLATFORM_ core::stringc sdlversion = "SDL Version "; sdlversion += Info.version.major; @@ -331,19 +318,16 @@ CIrrDeviceSDL::CIrrDeviceSDL(const SIrrlichtCreationParameters& param) } } - //! destructor CIrrDeviceSDL::~CIrrDeviceSDL() { - if ( --SDLDeviceInstances == 0 ) - { + if (--SDLDeviceInstances == 0) { #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) const u32 numJoysticks = Joysticks.size(); - for (u32 i=0; i1) - { - SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); - SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, CreationParams.AntiAlias ); - } - else - { + if (CreationParams.AntiAlias > 1) { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, CreationParams.AntiAlias); + } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } @@ -432,38 +412,38 @@ bool CIrrDeviceSDL::createWindow() logAttributes(); // "#canvas" is for the opengl context - emscripten_set_mousedown_callback("#canvas", (void*)this, true, MouseUpDownCallback); - emscripten_set_mouseup_callback("#canvas", (void*)this, true, MouseUpDownCallback); - emscripten_set_mouseenter_callback("#canvas", (void*)this, false, MouseEnterCallback); - emscripten_set_mouseleave_callback("#canvas", (void*)this, false, MouseLeaveCallback); + emscripten_set_mousedown_callback("#canvas", (void *)this, true, MouseUpDownCallback); + emscripten_set_mouseup_callback("#canvas", (void *)this, true, MouseUpDownCallback); + emscripten_set_mouseenter_callback("#canvas", (void *)this, false, MouseEnterCallback); + emscripten_set_mouseleave_callback("#canvas", (void *)this, false, MouseLeaveCallback); return true; #else // !_IRR_EMSCRIPTEN_PLATFORM_ - if ( Close ) + if (Close) return false; switch (CreationParams.DriverType) { - case video::EDT_OPENGL: - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); - break; - case video::EDT_OPENGL3: - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); - break; - case video::EDT_OGLES1: - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); - break; - case video::EDT_OGLES2: - case video::EDT_WEBGL1: - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); - break; - default:; + case video::EDT_OPENGL: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); + break; + case video::EDT_OPENGL3: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); + break; + case video::EDT_OGLES1: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); + break; + case video::EDT_OGLES2: + case video::EDT_WEBGL1: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); + break; + default:; } #ifdef _DEBUG @@ -510,15 +490,13 @@ bool CIrrDeviceSDL::createWindow() } } - if ( !Window && CreationParams.Doublebuffer) - { + if (!Window && CreationParams.Doublebuffer) { // Try single buffer if (CreationParams.DriverType == video::EDT_OPENGL) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); Window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Width, Height, SDL_Flags); } - if ( !Window ) - { + if (!Window) { os::Printer::log("Could not initialize display", SDL_GetError(), ELL_ERROR); return false; } @@ -534,7 +512,6 @@ bool CIrrDeviceSDL::createWindow() #endif // !_IRR_EMSCRIPTEN_PLATFORM_ } - //! create the driver void CIrrDeviceSDL::createDriver() { @@ -544,19 +521,25 @@ void CIrrDeviceSDL::createDriver() } ContextManager = new video::CSDLManager(this); - switch(CreationParams.DriverType) - { - case video::EDT_OPENGL: VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); break; - case video::EDT_OPENGL3: VideoDriver = video::createOpenGL3Driver(CreationParams, FileSystem, ContextManager); break; - case video::EDT_OGLES2: VideoDriver = video::createOGLES2Driver(CreationParams, FileSystem, ContextManager); break; - case video::EDT_WEBGL1: VideoDriver = video::createWebGL1Driver(CreationParams, FileSystem, ContextManager); break; + switch (CreationParams.DriverType) { + case video::EDT_OPENGL: + VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, ContextManager); + break; + case video::EDT_OPENGL3: + VideoDriver = video::createOpenGL3Driver(CreationParams, FileSystem, ContextManager); + break; + case video::EDT_OGLES2: + VideoDriver = video::createOGLES2Driver(CreationParams, FileSystem, ContextManager); + break; + case video::EDT_WEBGL1: + VideoDriver = video::createWebGL1Driver(CreationParams, FileSystem, ContextManager); + break; default:; } if (!VideoDriver) os::Printer::log("Could not create video driver", ELL_ERROR); } - //! runs the device. Returns false if device wants to be deleted bool CIrrDeviceSDL::run() { @@ -565,12 +548,10 @@ bool CIrrDeviceSDL::run() SEvent irrevent; SDL_Event SDL_event; - while ( !Close && SDL_PollEvent( &SDL_event ) ) - { + while (!Close && SDL_PollEvent(&SDL_event)) { // os::Printer::log("event: ", core::stringc((int)SDL_event.type).c_str(), ELL_INFORMATION); // just for debugging - switch ( SDL_event.type ) - { + switch (SDL_event.type) { case SDL_MOUSEMOTION: { SDL_Keymod keymod = SDL_GetModState(); @@ -617,7 +598,6 @@ bool CIrrDeviceSDL::run() irrevent.MouseInput.Event = irr::EMIE_MOUSE_MOVED; - #ifdef _IRR_EMSCRIPTEN_PLATFORM_ // Handle mouselocking in emscripten in Windowed mode. // In fullscreen SDL will handle it. @@ -625,18 +605,13 @@ bool CIrrDeviceSDL::run() // we will lock the mouse-pointer if it should be invisible. // For security reasons this will be delayed until the next mouse-up event. // We do not pass on this event as we don't want the activation click to do anything. - if ( SDL_event.type == SDL_MOUSEBUTTONDOWN && !isFullscreen() ) - { + if (SDL_event.type == SDL_MOUSEBUTTONDOWN && !isFullscreen()) { EmscriptenPointerlockChangeEvent pointerlockStatus; // let's hope that test is not expensive ... - if ( emscripten_get_pointerlock_status(&pointerlockStatus) == EMSCRIPTEN_RESULT_SUCCESS ) - { - if ( CursorControl->isVisible() && pointerlockStatus.isActive ) - { + if (emscripten_get_pointerlock_status(&pointerlockStatus) == EMSCRIPTEN_RESULT_SUCCESS) { + if (CursorControl->isVisible() && pointerlockStatus.isActive) { emscripten_exit_pointerlock(); return !Close; - } - else if ( !CursorControl->isVisible() && !pointerlockStatus.isActive ) - { + } else if (!CursorControl->isVisible() && !pointerlockStatus.isActive) { emscripten_request_pointerlock(0, true); return !Close; } @@ -644,42 +619,32 @@ bool CIrrDeviceSDL::run() } #endif - switch(SDL_event.button.button) - { + switch (SDL_event.button.button) { case SDL_BUTTON_LEFT: - if (SDL_event.type == SDL_MOUSEBUTTONDOWN) - { + if (SDL_event.type == SDL_MOUSEBUTTONDOWN) { irrevent.MouseInput.Event = irr::EMIE_LMOUSE_PRESSED_DOWN; MouseButtonStates |= irr::EMBSM_LEFT; - } - else - { + } else { irrevent.MouseInput.Event = irr::EMIE_LMOUSE_LEFT_UP; MouseButtonStates &= ~irr::EMBSM_LEFT; } break; case SDL_BUTTON_RIGHT: - if (SDL_event.type == SDL_MOUSEBUTTONDOWN) - { + if (SDL_event.type == SDL_MOUSEBUTTONDOWN) { irrevent.MouseInput.Event = irr::EMIE_RMOUSE_PRESSED_DOWN; MouseButtonStates |= irr::EMBSM_RIGHT; - } - else - { + } else { irrevent.MouseInput.Event = irr::EMIE_RMOUSE_LEFT_UP; MouseButtonStates &= ~irr::EMBSM_RIGHT; } break; case SDL_BUTTON_MIDDLE: - if (SDL_event.type == SDL_MOUSEBUTTONDOWN) - { + if (SDL_event.type == SDL_MOUSEBUTTONDOWN) { irrevent.MouseInput.Event = irr::EMIE_MMOUSE_PRESSED_DOWN; MouseButtonStates |= irr::EMBSM_MIDDLE; - } - else - { + } else { irrevent.MouseInput.Event = irr::EMIE_MMOUSE_LEFT_UP; MouseButtonStates &= ~irr::EMBSM_MIDDLE; } @@ -688,21 +653,16 @@ bool CIrrDeviceSDL::run() irrevent.MouseInput.ButtonStates = MouseButtonStates; - if (irrevent.MouseInput.Event != irr::EMIE_MOUSE_MOVED) - { + if (irrevent.MouseInput.Event != irr::EMIE_MOUSE_MOVED) { postEventFromUser(irrevent); - if ( irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN ) - { + if (irrevent.MouseInput.Event >= EMIE_LMOUSE_PRESSED_DOWN && irrevent.MouseInput.Event <= EMIE_MMOUSE_PRESSED_DOWN) { u32 clicks = checkSuccessiveClicks(irrevent.MouseInput.X, irrevent.MouseInput.Y, irrevent.MouseInput.Event); - if ( clicks == 2 ) - { - irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN); + if (clicks == 2) { + irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_DOUBLE_CLICK + irrevent.MouseInput.Event - EMIE_LMOUSE_PRESSED_DOWN); postEventFromUser(irrevent); - } - else if ( clicks == 3 ) - { - irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event-EMIE_LMOUSE_PRESSED_DOWN); + } else if (clicks == 3) { + irrevent.MouseInput.Event = (EMOUSE_INPUT_EVENT)(EMIE_LMOUSE_TRIPLE_CLICK + irrevent.MouseInput.Event - EMIE_LMOUSE_PRESSED_DOWN); postEventFromUser(irrevent); } } @@ -710,57 +670,51 @@ bool CIrrDeviceSDL::run() break; } - case SDL_TEXTINPUT: - { - irrevent.EventType = irr::EET_STRING_INPUT_EVENT; - irrevent.StringInput.Str = new core::stringw(); - irr::core::utf8ToWString(*irrevent.StringInput.Str, SDL_event.text.text); - postEventFromUser(irrevent); - delete irrevent.StringInput.Str; - irrevent.StringInput.Str = NULL; - } - break; + case SDL_TEXTINPUT: { + irrevent.EventType = irr::EET_STRING_INPUT_EVENT; + irrevent.StringInput.Str = new core::stringw(); + irr::core::utf8ToWString(*irrevent.StringInput.Str, SDL_event.text.text); + postEventFromUser(irrevent); + delete irrevent.StringInput.Str; + irrevent.StringInput.Str = NULL; + } break; case SDL_KEYDOWN: - case SDL_KEYUP: - { - SKeyMap mp; - mp.SDLKey = SDL_event.key.keysym.sym; - s32 idx = KeyMap.binary_search(mp); + case SDL_KEYUP: { + SKeyMap mp; + mp.SDLKey = SDL_event.key.keysym.sym; + s32 idx = KeyMap.binary_search(mp); - EKEY_CODE key; - if (idx == -1) - key = (EKEY_CODE)0; - else - key = (EKEY_CODE)KeyMap[idx].Win32Key; + EKEY_CODE key; + if (idx == -1) + key = (EKEY_CODE)0; + else + key = (EKEY_CODE)KeyMap[idx].Win32Key; - if (key == (EKEY_CODE)0) - os::Printer::log("keycode not mapped", core::stringc(mp.SDLKey), ELL_DEBUG); + if (key == (EKEY_CODE)0) + os::Printer::log("keycode not mapped", core::stringc(mp.SDLKey), ELL_DEBUG); - // Make sure to only input special characters if something is in focus, as SDL_TEXTINPUT handles normal unicode already - if (SDL_IsTextInputActive() && !keyIsKnownSpecial(key) && (SDL_event.key.keysym.mod & KMOD_CTRL) == 0) - break; + // Make sure to only input special characters if something is in focus, as SDL_TEXTINPUT handles normal unicode already + if (SDL_IsTextInputActive() && !keyIsKnownSpecial(key) && (SDL_event.key.keysym.mod & KMOD_CTRL) == 0) + break; - irrevent.EventType = irr::EET_KEY_INPUT_EVENT; - irrevent.KeyInput.Key = key; - irrevent.KeyInput.PressedDown = (SDL_event.type == SDL_KEYDOWN); - irrevent.KeyInput.Shift = (SDL_event.key.keysym.mod & KMOD_SHIFT) != 0; - irrevent.KeyInput.Control = (SDL_event.key.keysym.mod & KMOD_CTRL ) != 0; - irrevent.KeyInput.Char = findCharToPassToIrrlicht(mp.SDLKey, key); - postEventFromUser(irrevent); - } - break; + irrevent.EventType = irr::EET_KEY_INPUT_EVENT; + irrevent.KeyInput.Key = key; + irrevent.KeyInput.PressedDown = (SDL_event.type == SDL_KEYDOWN); + irrevent.KeyInput.Shift = (SDL_event.key.keysym.mod & KMOD_SHIFT) != 0; + irrevent.KeyInput.Control = (SDL_event.key.keysym.mod & KMOD_CTRL) != 0; + irrevent.KeyInput.Char = findCharToPassToIrrlicht(mp.SDLKey, key); + postEventFromUser(irrevent); + } break; case SDL_QUIT: Close = true; break; case SDL_WINDOWEVENT: - switch (SDL_event.window.event) - { + switch (SDL_event.window.event) { case SDL_WINDOWEVENT_RESIZED: - if ((SDL_event.window.data1 != (int)Width) || (SDL_event.window.data2 != (int)Height)) - { + if ((SDL_event.window.data1 != (int)Width) || (SDL_event.window.data2 != (int)Height)) { Width = SDL_event.window.data1; Height = SDL_event.window.data2; if (VideoDriver) @@ -819,7 +773,7 @@ bool CIrrDeviceSDL::run() default: break; } // end switch - resetReceiveTextInputEvents(); + resetReceiveTextInputEvents(); } // end while #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) @@ -831,71 +785,65 @@ bool CIrrDeviceSDL::run() // we'll always send joystick input events... SEvent joyevent; joyevent.EventType = EET_JOYSTICK_INPUT_EVENT; - for (u32 i=0; i0) - { - switch (SDL_JoystickGetHat(joystick, 0)) - { - case SDL_HAT_UP: - joyevent.JoystickEvent.POV=0; - break; - case SDL_HAT_RIGHTUP: - joyevent.JoystickEvent.POV=4500; - break; - case SDL_HAT_RIGHT: - joyevent.JoystickEvent.POV=9000; - break; - case SDL_HAT_RIGHTDOWN: - joyevent.JoystickEvent.POV=13500; - break; - case SDL_HAT_DOWN: - joyevent.JoystickEvent.POV=18000; - break; - case SDL_HAT_LEFTDOWN: - joyevent.JoystickEvent.POV=22500; - break; - case SDL_HAT_LEFT: - joyevent.JoystickEvent.POV=27000; - break; - case SDL_HAT_LEFTUP: - joyevent.JoystickEvent.POV=31500; - break; - case SDL_HAT_CENTERED: - default: - joyevent.JoystickEvent.POV=65535; - break; + if (SDL_JoystickNumHats(joystick) > 0) { + switch (SDL_JoystickGetHat(joystick, 0)) { + case SDL_HAT_UP: + joyevent.JoystickEvent.POV = 0; + break; + case SDL_HAT_RIGHTUP: + joyevent.JoystickEvent.POV = 4500; + break; + case SDL_HAT_RIGHT: + joyevent.JoystickEvent.POV = 9000; + break; + case SDL_HAT_RIGHTDOWN: + joyevent.JoystickEvent.POV = 13500; + break; + case SDL_HAT_DOWN: + joyevent.JoystickEvent.POV = 18000; + break; + case SDL_HAT_LEFTDOWN: + joyevent.JoystickEvent.POV = 22500; + break; + case SDL_HAT_LEFT: + joyevent.JoystickEvent.POV = 27000; + break; + case SDL_HAT_LEFTUP: + joyevent.JoystickEvent.POV = 31500; + break; + case SDL_HAT_CENTERED: + default: + joyevent.JoystickEvent.POV = 65535; + break; } - } - else - { - joyevent.JoystickEvent.POV=65535; + } else { + joyevent.JoystickEvent.POV = 65535; } // we map the number directly - joyevent.JoystickEvent.Joystick=static_cast(i); + joyevent.JoystickEvent.Joystick = static_cast(i); // now post the event postEventFromUser(joyevent); // and close the joystick @@ -906,7 +854,7 @@ bool CIrrDeviceSDL::run() } //! Activate any joysticks, and generate events for them. -bool CIrrDeviceSDL::activateJoysticks(core::array & joystickInfo) +bool CIrrDeviceSDL::activateJoysticks(core::array &joystickInfo) { #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) joystickInfo.clear(); @@ -917,9 +865,8 @@ bool CIrrDeviceSDL::activateJoysticks(core::array & joystickInfo) joystickInfo.reallocate(numJoysticks); int joystick = 0; - for (; joystick & joystickInfo) info.Buttons = SDL_JoystickNumButtons(Joysticks[joystick]); info.Name = SDL_JoystickName(Joysticks[joystick]); info.PovHat = (SDL_JoystickNumHats(Joysticks[joystick]) > 0) - ? SJoystickInfo::POV_HAT_PRESENT : SJoystickInfo::POV_HAT_ABSENT; + ? SJoystickInfo::POV_HAT_PRESENT + : SJoystickInfo::POV_HAT_ABSENT; joystickInfo.push_back(info); } - for(joystick = 0; joystick < (int)joystickInfo.size(); ++joystick) - { + for (joystick = 0; joystick < (int)joystickInfo.size(); ++joystick) { char logString[256]; snprintf_irr(logString, sizeof(logString), "Found joystick %d, %d axes, %d buttons '%s'", - joystick, joystickInfo[joystick].Axes, - joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); + joystick, joystickInfo[joystick].Axes, + joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); os::Printer::log(logString, ELL_INFORMATION); } @@ -948,7 +895,6 @@ bool CIrrDeviceSDL::activateJoysticks(core::array & joystickInfo) return false; } - //! Get the display density in dots per inch. float CIrrDeviceSDL::getDisplayDensity() const { @@ -970,21 +916,17 @@ float CIrrDeviceSDL::getDisplayDensity() const return std::max(dpi_w, dpi_h); } - void CIrrDeviceSDL::SwapWindow() { SDL_GL_SwapWindow(Window); } - - //! pause execution temporarily void CIrrDeviceSDL::yield() { SDL_Delay(0); } - //! pause execution for a specified time void CIrrDeviceSDL::sleep(u32 timeMs, bool pauseTimer) { @@ -998,16 +940,14 @@ void CIrrDeviceSDL::sleep(u32 timeMs, bool pauseTimer) Timer->start(); } - //! sets the caption of the window -void CIrrDeviceSDL::setWindowCaption(const wchar_t* text) +void CIrrDeviceSDL::setWindowCaption(const wchar_t *text) { core::stringc textc; core::wStringToUTF8(textc, text); SDL_SetWindowTitle(Window, textc.c_str()); } - //! Sets the window icon. bool CIrrDeviceSDL::setWindowIcon(const video::IImage *img) { @@ -1042,21 +982,19 @@ bool CIrrDeviceSDL::setWindowIcon(const video::IImage *img) return true; } - //! notifies the device that it should close itself void CIrrDeviceSDL::closeDevice() { Close = true; } - //! Sets if the window should be resizable in windowed mode. void CIrrDeviceSDL::setResizable(bool resize) { #ifdef _IRR_EMSCRIPTEN_PLATFORM_ - os::Printer::log("Resizable not available on the web." , ELL_WARNING); + os::Printer::log("Resizable not available on the web.", ELL_WARNING); return; -#else // !_IRR_EMSCRIPTEN_PLATFORM_ +#else // !_IRR_EMSCRIPTEN_PLATFORM_ if (resize != Resizable) { if (resize) SDL_Flags |= SDL_WINDOW_RESIZABLE; @@ -1071,7 +1009,6 @@ void CIrrDeviceSDL::setResizable(bool resize) #endif // !_IRR_EMSCRIPTEN_PLATFORM_ } - //! Minimizes window if possible void CIrrDeviceSDL::minimizeWindow() { @@ -1079,7 +1016,6 @@ void CIrrDeviceSDL::minimizeWindow() SDL_MinimizeWindow(Window); } - //! Maximize window void CIrrDeviceSDL::maximizeWindow() { @@ -1090,10 +1026,9 @@ void CIrrDeviceSDL::maximizeWindow() //! Get the position of this window on screen core::position2di CIrrDeviceSDL::getWindowPosition() { - return core::position2di(-1, -1); + return core::position2di(-1, -1); } - //! Restore original window size void CIrrDeviceSDL::restoreWindow() { @@ -1116,7 +1051,6 @@ bool CIrrDeviceSDL::isFullscreen() const #endif } - //! returns if window is active. if not, nothing need to be drawn bool CIrrDeviceSDL::isWindowActive() const { @@ -1124,9 +1058,8 @@ bool CIrrDeviceSDL::isWindowActive() const // Hidden test only does something in some browsers (when tab in background or window is minimized) // In other browsers code automatically doesn't seem to be called anymore. EmscriptenVisibilityChangeEvent emVisibility; - if ( emscripten_get_visibility_status(&emVisibility) == EMSCRIPTEN_RESULT_SUCCESS) - { - if ( emVisibility.hidden ) + if (emscripten_get_visibility_status(&emVisibility) == EMSCRIPTEN_RESULT_SUCCESS) { + if (emVisibility.hidden) return false; } #endif @@ -1134,47 +1067,38 @@ bool CIrrDeviceSDL::isWindowActive() const return windowFlags & SDL_WINDOW_SHOWN && windowFlags & SDL_WINDOW_INPUT_FOCUS; } - //! returns if window has focus. bool CIrrDeviceSDL::isWindowFocused() const { return Window && (SDL_GetWindowFlags(Window) & SDL_WINDOW_INPUT_FOCUS) != 0; } - //! returns if window is minimized. bool CIrrDeviceSDL::isWindowMinimized() const { return Window && (SDL_GetWindowFlags(Window) & SDL_WINDOW_MINIMIZED) != 0; } - //! returns color format of the window. video::ECOLOR_FORMAT CIrrDeviceSDL::getColorFormat() const { - if (Window) - { + if (Window) { SDL_Surface *surface = SDL_GetWindowSurface(Window); - if (surface->format->BitsPerPixel == 16) - { + if (surface->format->BitsPerPixel == 16) { if (surface->format->Amask != 0) return video::ECF_A1R5G5B5; else return video::ECF_R5G6B5; - } - else - { + } else { if (surface->format->Amask != 0) return video::ECF_A8R8G8B8; else return video::ECF_R8G8B8; } - } - else + } else return CIrrDeviceStub::getColorFormat(); } - void CIrrDeviceSDL::createKeyMap() { // I don't know if this is the best method to create @@ -1280,15 +1204,15 @@ void CIrrDeviceSDL::createKeyMap() KeyMap.push_back(SKeyMap(SDLK_KP_PERIOD, KEY_DECIMAL)); KeyMap.push_back(SKeyMap(SDLK_KP_DIVIDE, KEY_DIVIDE)); - KeyMap.push_back(SKeyMap(SDLK_F1, KEY_F1)); - KeyMap.push_back(SKeyMap(SDLK_F2, KEY_F2)); - KeyMap.push_back(SKeyMap(SDLK_F3, KEY_F3)); - KeyMap.push_back(SKeyMap(SDLK_F4, KEY_F4)); - KeyMap.push_back(SKeyMap(SDLK_F5, KEY_F5)); - KeyMap.push_back(SKeyMap(SDLK_F6, KEY_F6)); - KeyMap.push_back(SKeyMap(SDLK_F7, KEY_F7)); - KeyMap.push_back(SKeyMap(SDLK_F8, KEY_F8)); - KeyMap.push_back(SKeyMap(SDLK_F9, KEY_F9)); + KeyMap.push_back(SKeyMap(SDLK_F1, KEY_F1)); + KeyMap.push_back(SKeyMap(SDLK_F2, KEY_F2)); + KeyMap.push_back(SKeyMap(SDLK_F3, KEY_F3)); + KeyMap.push_back(SKeyMap(SDLK_F4, KEY_F4)); + KeyMap.push_back(SKeyMap(SDLK_F5, KEY_F5)); + KeyMap.push_back(SKeyMap(SDLK_F6, KEY_F6)); + KeyMap.push_back(SKeyMap(SDLK_F7, KEY_F7)); + KeyMap.push_back(SKeyMap(SDLK_F8, KEY_F8)); + KeyMap.push_back(SKeyMap(SDLK_F9, KEY_F9)); KeyMap.push_back(SKeyMap(SDLK_F10, KEY_F10)); KeyMap.push_back(SKeyMap(SDLK_F11, KEY_F11)); KeyMap.push_back(SKeyMap(SDLK_F12, KEY_F12)); @@ -1301,14 +1225,14 @@ void CIrrDeviceSDL::createKeyMap() KeyMap.push_back(SKeyMap(SDLK_SCROLLLOCK, KEY_SCROLL)); KeyMap.push_back(SKeyMap(SDLK_LSHIFT, KEY_LSHIFT)); KeyMap.push_back(SKeyMap(SDLK_RSHIFT, KEY_RSHIFT)); - KeyMap.push_back(SKeyMap(SDLK_LCTRL, KEY_LCONTROL)); - KeyMap.push_back(SKeyMap(SDLK_RCTRL, KEY_RCONTROL)); - KeyMap.push_back(SKeyMap(SDLK_LALT, KEY_LMENU)); - KeyMap.push_back(SKeyMap(SDLK_RALT, KEY_RMENU)); + KeyMap.push_back(SKeyMap(SDLK_LCTRL, KEY_LCONTROL)); + KeyMap.push_back(SKeyMap(SDLK_RCTRL, KEY_RCONTROL)); + KeyMap.push_back(SKeyMap(SDLK_LALT, KEY_LMENU)); + KeyMap.push_back(SKeyMap(SDLK_RALT, KEY_RMENU)); - KeyMap.push_back(SKeyMap(SDLK_PLUS, KEY_PLUS)); - KeyMap.push_back(SKeyMap(SDLK_COMMA, KEY_COMMA)); - KeyMap.push_back(SKeyMap(SDLK_MINUS, KEY_MINUS)); + KeyMap.push_back(SKeyMap(SDLK_PLUS, KEY_PLUS)); + KeyMap.push_back(SKeyMap(SDLK_COMMA, KEY_COMMA)); + KeyMap.push_back(SKeyMap(SDLK_MINUS, KEY_MINUS)); KeyMap.push_back(SKeyMap(SDLK_PERIOD, KEY_PERIOD)); // some special keys missing @@ -1320,22 +1244,21 @@ void CIrrDeviceSDL::CCursorControl::initCursors() { Cursors.reserve(gui::ECI_COUNT); - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW)); // ECI_NORMAL + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW)); // ECI_NORMAL Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR)); // ECI_CROSS - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND)); // ECI_HAND - Cursors.emplace_back(nullptr); // ECI_HELP - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM)); // ECI_IBEAM - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO)); // ECI_NO - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT)); // ECI_WAIT + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND)); // ECI_HAND + Cursors.emplace_back(nullptr); // ECI_HELP + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM)); // ECI_IBEAM + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO)); // ECI_NO + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT)); // ECI_WAIT Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL)); // ECI_SIZEALL Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW)); // ECI_SIZENESW Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE)); // ECI_SIZENWSE - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS)); // ECI_SIZENS - Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE)); // ECI_SIZEWE - Cursors.emplace_back(nullptr); // ECI_UP + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS)); // ECI_SIZENS + Cursors.emplace_back(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE)); // ECI_SIZEWE + Cursors.emplace_back(nullptr); // ECI_UP } } // end namespace irr #endif // _IRR_COMPILE_WITH_SDL_DEVICE_ - diff --git a/source/Irrlicht/CIrrDeviceSDL.h b/source/Irrlicht/CIrrDeviceSDL.h index 7b5f0119..b1e2a785 100644 --- a/source/Irrlicht/CIrrDeviceSDL.h +++ b/source/Irrlicht/CIrrDeviceSDL.h @@ -28,306 +28,299 @@ namespace irr { - class CIrrDeviceSDL : public CIrrDeviceStub +class CIrrDeviceSDL : public CIrrDeviceStub +{ +public: + //! constructor + CIrrDeviceSDL(const SIrrlichtCreationParameters ¶m); + + //! destructor + virtual ~CIrrDeviceSDL(); + + //! runs the device. Returns false if device wants to be deleted + bool run() override; + + //! pause execution temporarily + void yield() override; + + //! pause execution for a specified time + void sleep(u32 timeMs, bool pauseTimer) override; + + //! sets the caption of the window + void setWindowCaption(const wchar_t *text) override; + + //! Sets the window icon. + bool setWindowIcon(const video::IImage *img) override; + + //! returns if window is active. if not, nothing need to be drawn + bool isWindowActive() const override; + + //! returns if window has focus. + bool isWindowFocused() const override; + + //! returns if window is minimized. + bool isWindowMinimized() const override; + + //! returns color format of the window. + video::ECOLOR_FORMAT getColorFormat() const override; + + //! notifies the device that it should close itself + void closeDevice() override; + + //! Sets if the window should be resizable in windowed mode. + void setResizable(bool resize = false) override; + + //! Minimizes the window. + void minimizeWindow() override; + + //! Maximizes the window. + void maximizeWindow() override; + + //! Restores the window size. + void restoreWindow() override; + + //! Checks if the window is maximized. + bool isWindowMaximized() const override; + + //! Checks if the Irrlicht window is running in fullscreen mode + /** \return True if window is fullscreen. */ + bool isFullscreen() const override; + + //! Get the position of this window on screen + core::position2di getWindowPosition() override; + + //! Activate any joysticks, and generate events for them. + bool activateJoysticks(core::array &joystickInfo) override; + + //! Get the device type + E_DEVICE_TYPE getType() const override + { + return EIDT_SDL; + } + + //! Get the display density in dots per inch. + float getDisplayDensity() const override; + + void SwapWindow(); + + //! Implementation of the linux cursor control + class CCursorControl : public gui::ICursorControl { public: - - //! constructor - CIrrDeviceSDL(const SIrrlichtCreationParameters& param); - - //! destructor - virtual ~CIrrDeviceSDL(); - - //! runs the device. Returns false if device wants to be deleted - bool run() override; - - //! pause execution temporarily - void yield() override; - - //! pause execution for a specified time - void sleep(u32 timeMs, bool pauseTimer) override; - - //! sets the caption of the window - void setWindowCaption(const wchar_t* text) override; - - //! Sets the window icon. - bool setWindowIcon(const video::IImage *img) override; - - //! returns if window is active. if not, nothing need to be drawn - bool isWindowActive() const override; - - //! returns if window has focus. - bool isWindowFocused() const override; - - //! returns if window is minimized. - bool isWindowMinimized() const override; - - //! returns color format of the window. - video::ECOLOR_FORMAT getColorFormat() const override; - - //! notifies the device that it should close itself - void closeDevice() override; - - //! Sets if the window should be resizable in windowed mode. - void setResizable(bool resize=false) override; - - //! Minimizes the window. - void minimizeWindow() override; - - //! Maximizes the window. - void maximizeWindow() override; - - //! Restores the window size. - void restoreWindow() override; - - //! Checks if the window is maximized. - bool isWindowMaximized() const override; - - //! Checks if the Irrlicht window is running in fullscreen mode - /** \return True if window is fullscreen. */ - bool isFullscreen() const override; - - //! Get the position of this window on screen - core::position2di getWindowPosition() override; - - //! Activate any joysticks, and generate events for them. - bool activateJoysticks(core::array & joystickInfo) override; - - //! Get the device type - E_DEVICE_TYPE getType() const override + CCursorControl(CIrrDeviceSDL *dev) : + Device(dev), IsVisible(true) { - return EIDT_SDL; + initCursors(); } - //! Get the display density in dots per inch. - float getDisplayDensity() const override; - - void SwapWindow(); - - //! Implementation of the linux cursor control - class CCursorControl : public gui::ICursorControl + //! Changes the visible state of the mouse cursor. + void setVisible(bool visible) override { - public: - - CCursorControl(CIrrDeviceSDL* dev) - : Device(dev), IsVisible(true) - { - initCursors(); + IsVisible = visible; + if (visible) + SDL_ShowCursor(SDL_ENABLE); + else { + SDL_ShowCursor(SDL_DISABLE); } + } - //! Changes the visible state of the mouse cursor. - void setVisible(bool visible) override - { - IsVisible = visible; - if ( visible ) - SDL_ShowCursor( SDL_ENABLE ); - else - { - SDL_ShowCursor( SDL_DISABLE ); - } + //! Returns if the cursor is currently visible. + bool isVisible() const override + { + return IsVisible; + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(f32 x, f32 y) override + { + setPosition((s32)(x * Device->Width), (s32)(y * Device->Height)); + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(s32 x, s32 y) override + { + SDL_WarpMouseInWindow(Device->Window, x, y); + + if (SDL_GetRelativeMouseMode()) { + // There won't be an event for this warp (details on libsdl-org/SDL/issues/6034) + Device->MouseX = x; + Device->MouseY = y; } + } - //! Returns if the cursor is currently visible. - bool isVisible() const override - { - return IsVisible; - } + //! Returns the current position of the mouse cursor. + const core::position2d &getPosition(bool updateCursor) override + { + if (updateCursor) + updateCursorPos(); + return CursorPos; + } - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(f32 x, f32 y) override - { - setPosition((s32)(x*Device->Width), (s32)(y*Device->Height)); - } - - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(s32 x, s32 y) override - { - SDL_WarpMouseInWindow(Device->Window, x, y); - - if (SDL_GetRelativeMouseMode()) { - // There won't be an event for this warp (details on libsdl-org/SDL/issues/6034) - Device->MouseX = x; - Device->MouseY = y; - } - } - - //! Returns the current position of the mouse cursor. - const core::position2d& getPosition(bool updateCursor) override - { - if ( updateCursor ) - updateCursorPos(); - return CursorPos; - } - - //! Returns the current position of the mouse cursor. - core::position2d getRelativePosition(bool updateCursor) override - { - if ( updateCursor ) - updateCursorPos(); - return core::position2d(CursorPos.X / (f32)Device->Width, + //! Returns the current position of the mouse cursor. + core::position2d getRelativePosition(bool updateCursor) override + { + if (updateCursor) + updateCursorPos(); + return core::position2d(CursorPos.X / (f32)Device->Width, CursorPos.Y / (f32)Device->Height); + } + + void setReferenceRect(core::rect *rect = 0) override + { + } + + virtual void setRelativeMode(bool relative) _IRR_OVERRIDE_ + { + // Only change it when necessary, as it flushes mouse motion when enabled + if (relative != SDL_GetRelativeMouseMode()) { + if (relative) + SDL_SetRelativeMouseMode(SDL_TRUE); + else + SDL_SetRelativeMouseMode(SDL_FALSE); } + } - void setReferenceRect(core::rect* rect=0) override - { + void setActiveIcon(gui::ECURSOR_ICON iconId) override + { + ActiveIcon = iconId; + if (iconId > Cursors.size() || !Cursors[iconId]) { + iconId = gui::ECI_NORMAL; + if (iconId > Cursors.size() || !Cursors[iconId]) + return; } + SDL_SetCursor(Cursors[iconId].get()); + } - virtual void setRelativeMode(bool relative) _IRR_OVERRIDE_ - { - // Only change it when necessary, as it flushes mouse motion when enabled - if ( relative != SDL_GetRelativeMouseMode()) { - if ( relative ) - SDL_SetRelativeMouseMode( SDL_TRUE ); - else - SDL_SetRelativeMouseMode( SDL_FALSE ); - } - } - - void setActiveIcon(gui::ECURSOR_ICON iconId) override - { - ActiveIcon = iconId; - if (iconId > Cursors.size() || !Cursors[iconId]) { - iconId = gui::ECI_NORMAL; - if (iconId > Cursors.size() || !Cursors[iconId]) - return; - } - SDL_SetCursor(Cursors[iconId].get()); - } - - gui::ECURSOR_ICON getActiveIcon() const override - { - return ActiveIcon; - } - - private: - - void updateCursorPos() - { -#ifdef _IRR_EMSCRIPTEN_PLATFORM_ - EmscriptenPointerlockChangeEvent pointerlockStatus; // let's hope that test is not expensive ... - if ( emscripten_get_pointerlock_status(&pointerlockStatus) == EMSCRIPTEN_RESULT_SUCCESS ) - { - if ( pointerlockStatus.isActive ) - { - CursorPos.X += Device->MouseXRel; - CursorPos.Y += Device->MouseYRel; - Device->MouseXRel = 0; - Device->MouseYRel = 0; - } - else - { - CursorPos.X = Device->MouseX; - CursorPos.Y = Device->MouseY; - } - } -#else - CursorPos.X = Device->MouseX; - CursorPos.Y = Device->MouseY; - - if (CursorPos.X < 0) - CursorPos.X = 0; - if (CursorPos.X > (s32)Device->Width) - CursorPos.X = Device->Width; - if (CursorPos.Y < 0) - CursorPos.Y = 0; - if (CursorPos.Y > (s32)Device->Height) - CursorPos.Y = Device->Height; -#endif - } - - void initCursors(); - - CIrrDeviceSDL* Device; - core::position2d CursorPos; - bool IsVisible; - - struct CursorDeleter { - void operator()(SDL_Cursor *ptr) { - if (ptr) - SDL_FreeCursor(ptr); - } - }; - std::vector> Cursors; - gui::ECURSOR_ICON ActiveIcon = gui::ECURSOR_ICON::ECI_NORMAL; - }; + gui::ECURSOR_ICON getActiveIcon() const override + { + return ActiveIcon; + } private: - + void updateCursorPos() + { #ifdef _IRR_EMSCRIPTEN_PLATFORM_ - static EM_BOOL MouseUpDownCallback(int eventType, const EmscriptenMouseEvent * event, void* userData); + EmscriptenPointerlockChangeEvent pointerlockStatus; // let's hope that test is not expensive ... + if (emscripten_get_pointerlock_status(&pointerlockStatus) == EMSCRIPTEN_RESULT_SUCCESS) { + if (pointerlockStatus.isActive) { + CursorPos.X += Device->MouseXRel; + CursorPos.Y += Device->MouseYRel; + Device->MouseXRel = 0; + Device->MouseYRel = 0; + } else { + CursorPos.X = Device->MouseX; + CursorPos.Y = Device->MouseY; + } + } +#else + CursorPos.X = Device->MouseX; + CursorPos.Y = Device->MouseY; + + if (CursorPos.X < 0) + CursorPos.X = 0; + if (CursorPos.X > (s32)Device->Width) + CursorPos.X = Device->Width; + if (CursorPos.Y < 0) + CursorPos.Y = 0; + if (CursorPos.Y > (s32)Device->Height) + CursorPos.Y = Device->Height; +#endif + } + + void initCursors(); + + CIrrDeviceSDL *Device; + core::position2d CursorPos; + bool IsVisible; + + struct CursorDeleter + { + void operator()(SDL_Cursor *ptr) + { + if (ptr) + SDL_FreeCursor(ptr); + } + }; + std::vector> Cursors; + gui::ECURSOR_ICON ActiveIcon = gui::ECURSOR_ICON::ECI_NORMAL; + }; + +private: +#ifdef _IRR_EMSCRIPTEN_PLATFORM_ + static EM_BOOL MouseUpDownCallback(int eventType, const EmscriptenMouseEvent *event, void *userData); static EM_BOOL MouseEnterCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); static EM_BOOL MouseLeaveCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); #endif - // Check if a key is a known special character with no side effects on text boxes. - static bool keyIsKnownSpecial(EKEY_CODE key); + // Check if a key is a known special character with no side effects on text boxes. + static bool keyIsKnownSpecial(EKEY_CODE key); - // Return the Char that should be sent to Irrlicht for the given key (either the one passed in or 0). - static int findCharToPassToIrrlicht(int assumedChar, EKEY_CODE key); + // Return the Char that should be sent to Irrlicht for the given key (either the one passed in or 0). + static int findCharToPassToIrrlicht(int assumedChar, EKEY_CODE key); - // Check if a text box is in focus. Enable or disable SDL_TEXTINPUT events only if in focus. - void resetReceiveTextInputEvents(); + // Check if a text box is in focus. Enable or disable SDL_TEXTINPUT events only if in focus. + void resetReceiveTextInputEvents(); - //! create the driver - void createDriver(); + //! create the driver + void createDriver(); - bool createWindow(); + bool createWindow(); - void createKeyMap(); + void createKeyMap(); - void logAttributes(); - SDL_GLContext Context; - SDL_Window *Window; - int SDL_Flags; + void logAttributes(); + SDL_GLContext Context; + SDL_Window *Window; + int SDL_Flags; #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - core::array Joysticks; + core::array Joysticks; #endif - s32 MouseX, MouseY; - s32 MouseXRel, MouseYRel; - u32 MouseButtonStates; + s32 MouseX, MouseY; + s32 MouseXRel, MouseYRel; + u32 MouseButtonStates; - u32 Width, Height; + u32 Width, Height; - bool Resizable; + bool Resizable; - core::rect lastElemPos; + core::rect lastElemPos; - struct SKeyMap + struct SKeyMap + { + SKeyMap() {} + SKeyMap(s32 x11, s32 win32) : + SDLKey(x11), Win32Key(win32) { - SKeyMap() {} - SKeyMap(s32 x11, s32 win32) - : SDLKey(x11), Win32Key(win32) - { - } + } - s32 SDLKey; - s32 Win32Key; + s32 SDLKey; + s32 Win32Key; - bool operator<(const SKeyMap& o) const - { - return SDLKey KeyMap; - SDL_SysWMinfo Info; - - s32 CurrentTouchCount; + bool operator<(const SKeyMap &o) const + { + return SDLKey < o.SDLKey; + } }; + core::array KeyMap; + SDL_SysWMinfo Info; + + s32 CurrentTouchCount; +}; + } // end namespace irr #endif // _IRR_COMPILE_WITH_SDL_DEVICE_ diff --git a/source/Irrlicht/CIrrDeviceStub.cpp b/source/Irrlicht/CIrrDeviceStub.cpp index 0d6809c3..2292db19 100644 --- a/source/Irrlicht/CIrrDeviceStub.cpp +++ b/source/Irrlicht/CIrrDeviceStub.cpp @@ -17,22 +17,19 @@ namespace irr { //! constructor -CIrrDeviceStub::CIrrDeviceStub(const SIrrlichtCreationParameters& params) -: IrrlichtDevice(), VideoDriver(0), GUIEnvironment(0), SceneManager(0), - Timer(0), CursorControl(0), UserReceiver(params.EventReceiver), - Logger(0), Operator(0), FileSystem(0), - InputReceivingSceneManager(0), ContextManager(0), - CreationParams(params), Close(false) +CIrrDeviceStub::CIrrDeviceStub(const SIrrlichtCreationParameters ¶ms) : + IrrlichtDevice(), VideoDriver(0), GUIEnvironment(0), SceneManager(0), + Timer(0), CursorControl(0), UserReceiver(params.EventReceiver), + Logger(0), Operator(0), FileSystem(0), + InputReceivingSceneManager(0), ContextManager(0), + CreationParams(params), Close(false) { Timer = new CTimer(); - if (os::Printer::Logger) - { + if (os::Printer::Logger) { os::Printer::Logger->grab(); - Logger = (CLogger*)os::Printer::Logger; + Logger = (CLogger *)os::Printer::Logger; Logger->setReceiver(UserReceiver); - } - else - { + } else { Logger = new CLogger(UserReceiver); os::Printer::Logger = Logger; } @@ -49,7 +46,6 @@ CIrrDeviceStub::CIrrDeviceStub(const SIrrlichtCreationParameters& params) checkVersion(params.SDK_version_do_not_use); } - CIrrDeviceStub::~CIrrDeviceStub() { if (GUIEnvironment) @@ -64,7 +60,7 @@ CIrrDeviceStub::~CIrrDeviceStub() if (ContextManager) ContextManager->drop(); - if ( FileSystem ) + if (FileSystem) FileSystem->drop(); if (InputReceivingSceneManager) @@ -85,7 +81,6 @@ CIrrDeviceStub::~CIrrDeviceStub() os::Printer::Logger = 0; } - void CIrrDeviceStub::createGUIAndScene() { // create gui environment @@ -97,76 +92,65 @@ void CIrrDeviceStub::createGUIAndScene() setEventReceiver(UserReceiver); } - //! returns the video driver -video::IVideoDriver* CIrrDeviceStub::getVideoDriver() +video::IVideoDriver *CIrrDeviceStub::getVideoDriver() { return VideoDriver; } - //! return file system -io::IFileSystem* CIrrDeviceStub::getFileSystem() +io::IFileSystem *CIrrDeviceStub::getFileSystem() { return FileSystem; } - - //! returns the gui environment -gui::IGUIEnvironment* CIrrDeviceStub::getGUIEnvironment() +gui::IGUIEnvironment *CIrrDeviceStub::getGUIEnvironment() { return GUIEnvironment; } - - //! returns the scene manager -scene::ISceneManager* CIrrDeviceStub::getSceneManager() +scene::ISceneManager *CIrrDeviceStub::getSceneManager() { return SceneManager; } - //! \return Returns a pointer to the ITimer object. With it the //! current Time can be received. -ITimer* CIrrDeviceStub::getTimer() +ITimer *CIrrDeviceStub::getTimer() { return Timer; } - //! Sets the window icon. bool CIrrDeviceStub::setWindowIcon(const video::IImage *img) { return false; } - //! Returns the version of the engine. -const char* CIrrDeviceStub::getVersion() const +const char *CIrrDeviceStub::getVersion() const { return IRRLICHT_SDK_VERSION; } //! \return Returns a pointer to the mouse cursor control interface. -gui::ICursorControl* CIrrDeviceStub::getCursorControl() +gui::ICursorControl *CIrrDeviceStub::getCursorControl() { return CursorControl; } - //! return the context manager -video::IContextManager* CIrrDeviceStub::getContextManager() +video::IContextManager *CIrrDeviceStub::getContextManager() { return ContextManager; } //! checks version of sdk and prints warning if there might be a problem -bool CIrrDeviceStub::checkVersion(const char* version) +bool CIrrDeviceStub::checkVersion(const char *version) { - if (strcmp(getVersion(), version)) - { + if (strcmp(getVersion(), version)) { core::stringc w; w = "Warning: The library version of the Irrlicht Engine ("; w += getVersion(); @@ -181,25 +165,16 @@ bool CIrrDeviceStub::checkVersion(const char* version) return true; } - //! Compares to the last call of this function to return double and triple clicks. -u32 CIrrDeviceStub::checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent ) +u32 CIrrDeviceStub::checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent) { const s32 MAX_MOUSEMOVE = 3; irr::u32 clickTime = getTimer()->getRealTime(); - if ( (clickTime-MouseMultiClicks.LastClickTime) < MouseMultiClicks.DoubleClickTime - && core::abs_(MouseMultiClicks.LastClick.X - mouseX ) <= MAX_MOUSEMOVE - && core::abs_(MouseMultiClicks.LastClick.Y - mouseY ) <= MAX_MOUSEMOVE - && MouseMultiClicks.CountSuccessiveClicks < 3 - && MouseMultiClicks.LastMouseInputEvent == inputEvent - ) - { + if ((clickTime - MouseMultiClicks.LastClickTime) < MouseMultiClicks.DoubleClickTime && core::abs_(MouseMultiClicks.LastClick.X - mouseX) <= MAX_MOUSEMOVE && core::abs_(MouseMultiClicks.LastClick.Y - mouseY) <= MAX_MOUSEMOVE && MouseMultiClicks.CountSuccessiveClicks < 3 && MouseMultiClicks.LastMouseInputEvent == inputEvent) { ++MouseMultiClicks.CountSuccessiveClicks; - } - else - { + } else { MouseMultiClicks.CountSuccessiveClicks = 1; } @@ -211,9 +186,8 @@ u32 CIrrDeviceStub::checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_E return MouseMultiClicks.CountSuccessiveClicks; } - //! send the event to the right receiver -bool CIrrDeviceStub::postEventFromUser(const SEvent& event) +bool CIrrDeviceStub::postEventFromUser(const SEvent &event) { bool absorbed = false; @@ -223,7 +197,7 @@ bool CIrrDeviceStub::postEventFromUser(const SEvent& event) if (!absorbed && GUIEnvironment) absorbed = GUIEnvironment->postEventFromUser(event); - scene::ISceneManager* inputReceiver = InputReceivingSceneManager; + scene::ISceneManager *inputReceiver = InputReceivingSceneManager; if (!inputReceiver) inputReceiver = SceneManager; @@ -233,9 +207,8 @@ bool CIrrDeviceStub::postEventFromUser(const SEvent& event) return absorbed; } - //! Sets a new event receiver to receive events -void CIrrDeviceStub::setEventReceiver(IEventReceiver* receiver) +void CIrrDeviceStub::setEventReceiver(IEventReceiver *receiver) { UserReceiver = receiver; Logger->setReceiver(receiver); @@ -243,30 +216,26 @@ void CIrrDeviceStub::setEventReceiver(IEventReceiver* receiver) GUIEnvironment->setUserEventReceiver(receiver); } - //! Returns poinhter to the current event receiver. Returns 0 if there is none. -IEventReceiver* CIrrDeviceStub::getEventReceiver() +IEventReceiver *CIrrDeviceStub::getEventReceiver() { return UserReceiver; } - //! \return Returns a pointer to the logger. -ILogger* CIrrDeviceStub::getLogger() +ILogger *CIrrDeviceStub::getLogger() { return Logger; } - //! Returns the operation system opertator object. -IOSOperator* CIrrDeviceStub::getOSOperator() +IOSOperator *CIrrDeviceStub::getOSOperator() { return Operator; } - //! Sets the input receiving scene manager. -void CIrrDeviceStub::setInputReceivingSceneManager(scene::ISceneManager* sceneManager) +void CIrrDeviceStub::setInputReceivingSceneManager(scene::ISceneManager *sceneManager) { if (sceneManager) sceneManager->grab(); @@ -276,21 +245,18 @@ void CIrrDeviceStub::setInputReceivingSceneManager(scene::ISceneManager* sceneMa InputReceivingSceneManager = sceneManager; } - //! Checks if the window is maximized. bool CIrrDeviceStub::isWindowMaximized() const { return false; } - //! Checks if the window is running in fullscreen mode bool CIrrDeviceStub::isFullscreen() const { return CreationParams.Fullscreen; } - //! returns color format video::ECOLOR_FORMAT CIrrDeviceStub::getColorFormat() const { @@ -298,7 +264,7 @@ video::ECOLOR_FORMAT CIrrDeviceStub::getColorFormat() const } //! No-op in this implementation -bool CIrrDeviceStub::activateJoysticks(core::array & joystickInfo) +bool CIrrDeviceStub::activateJoysticks(core::array &joystickInfo) { return false; } @@ -306,77 +272,77 @@ bool CIrrDeviceStub::activateJoysticks(core::array & joystickInfo //! No-op in this implementation bool CIrrDeviceStub::activateAccelerometer(float updateInterval) { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::deactivateAccelerometer() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isAccelerometerActive() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isAccelerometerAvailable() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::activateGyroscope(float updateInterval) { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::deactivateGyroscope() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isGyroscopeActive() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isGyroscopeAvailable() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::activateDeviceMotion(float updateInterval) { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::deactivateDeviceMotion() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isDeviceMotionActive() { - return false; + return false; } //! No-op in this implementation bool CIrrDeviceStub::isDeviceMotionAvailable() { - return false; + return false; } //! Set the maximal elapsed time between 2 clicks to generate doubleclicks for the mouse. It also affects tripleclick behavior. -void CIrrDeviceStub::setDoubleClickTime( u32 timeMs ) +void CIrrDeviceStub::setDoubleClickTime(u32 timeMs) { MouseMultiClicks.DoubleClickTime = timeMs; } @@ -407,6 +373,4 @@ bool CIrrDeviceStub::acceptsIME() return elem && elem->acceptsIME(); } - } // end namespace irr - diff --git a/source/Irrlicht/CIrrDeviceStub.h b/source/Irrlicht/CIrrDeviceStub.h index bbbb013a..163e44f3 100644 --- a/source/Irrlicht/CIrrDeviceStub.h +++ b/source/Irrlicht/CIrrDeviceStub.h @@ -10,198 +10,195 @@ namespace irr { - // lots of prototypes: - class ILogger; - class CLogger; +// lots of prototypes: +class ILogger; +class CLogger; - namespace gui +namespace gui +{ +class IGUIEnvironment; +IGUIEnvironment *createGUIEnvironment(io::IFileSystem *fs, + video::IVideoDriver *Driver, IOSOperator *op); +} + +namespace scene +{ +ISceneManager *createSceneManager(video::IVideoDriver *driver, gui::ICursorControl *cc); +} + +namespace io +{ +IFileSystem *createFileSystem(); +} + +namespace video +{ +IVideoDriver *createNullDriver(io::IFileSystem *io, const core::dimension2d &screenSize); +} + +//! Stub for an Irrlicht Device implementation +class CIrrDeviceStub : public IrrlichtDevice +{ +public: + //! constructor + CIrrDeviceStub(const SIrrlichtCreationParameters ¶m); + + //! destructor + virtual ~CIrrDeviceStub(); + + //! returns the video driver + video::IVideoDriver *getVideoDriver() override; + + //! return file system + io::IFileSystem *getFileSystem() override; + + //! returns the gui environment + gui::IGUIEnvironment *getGUIEnvironment() override; + + //! returns the scene manager + scene::ISceneManager *getSceneManager() override; + + //! \return Returns a pointer to the mouse cursor control interface. + gui::ICursorControl *getCursorControl() override; + + //! return the context manager + video::IContextManager *getContextManager() override; + + //! Returns a pointer to the ITimer object. With it the current Time can be received. + ITimer *getTimer() override; + + //! Sets the window icon. + bool setWindowIcon(const video::IImage *img) override; + + //! Returns the version of the engine. + const char *getVersion() const override; + + //! send the event to the right receiver + bool postEventFromUser(const SEvent &event) override; + + //! Sets a new event receiver to receive events + void setEventReceiver(IEventReceiver *receiver) override; + + //! Returns pointer to the current event receiver. Returns 0 if there is none. + IEventReceiver *getEventReceiver() override; + + //! Sets the input receiving scene manager. + /** If set to null, the main scene manager (returned by GetSceneManager()) will receive the input */ + void setInputReceivingSceneManager(scene::ISceneManager *sceneManager) override; + + //! Returns a pointer to the logger. + ILogger *getLogger() override; + + //! Returns the operation system opertator object. + IOSOperator *getOSOperator() override; + + //! Checks if the window is maximized. + bool isWindowMaximized() const override; + + //! Checks if the window is running in fullscreen mode. + bool isFullscreen() const override; + + //! get color format of the current window + video::ECOLOR_FORMAT getColorFormat() const override; + + //! Activate any joysticks, and generate events for them. + bool activateJoysticks(core::array &joystickInfo) override; + + //! Activate accelerometer. + bool activateAccelerometer(float updateInterval = 0.016666f) override; + + //! Deactivate accelerometer. + bool deactivateAccelerometer() override; + + //! Is accelerometer active. + bool isAccelerometerActive() override; + + //! Is accelerometer available. + bool isAccelerometerAvailable() override; + + //! Activate gyroscope. + bool activateGyroscope(float updateInterval = 0.016666f) override; + + //! Deactivate gyroscope. + bool deactivateGyroscope() override; + + //! Is gyroscope active. + bool isGyroscopeActive() override; + + //! Is gyroscope available. + bool isGyroscopeAvailable() override; + + //! Activate device motion. + bool activateDeviceMotion(float updateInterval = 0.016666f) override; + + //! Deactivate device motion. + bool deactivateDeviceMotion() override; + + //! Is device motion active. + bool isDeviceMotionActive() override; + + //! Is device motion available. + bool isDeviceMotionAvailable() override; + + //! Set the maximal elapsed time between 2 clicks to generate doubleclicks for the mouse. It also affects tripleclick behavior. + //! When set to 0 no double- and tripleclicks will be generated. + void setDoubleClickTime(u32 timeMs) override; + + //! Get the maximal elapsed time between 2 clicks to generate double- and tripleclicks for the mouse. + u32 getDoubleClickTime() const override; + + //! Remove all messages pending in the system message loop + void clearSystemMessages() override; + + //! Get the display density in dots per inch. + float getDisplayDensity() const override; + + //! Resize the render window. + void setWindowSize(const irr::core::dimension2d &size) override {} + +protected: + void createGUIAndScene(); + + //! checks version of SDK and prints warning if there might be a problem + bool checkVersion(const char *version); + + //! Compares to the last call of this function to return double and triple clicks. + /** Needed for win32 device event handling + \return Returns only 1,2 or 3. A 4th click will start with 1 again. + */ + virtual u32 checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent); + + //! Checks whether the input device should take input from the IME + bool acceptsIME(); + + video::IVideoDriver *VideoDriver; + gui::IGUIEnvironment *GUIEnvironment; + scene::ISceneManager *SceneManager; + ITimer *Timer; + gui::ICursorControl *CursorControl; + IEventReceiver *UserReceiver; + CLogger *Logger; + IOSOperator *Operator; + io::IFileSystem *FileSystem; + scene::ISceneManager *InputReceivingSceneManager; + + struct SMouseMultiClicks { - class IGUIEnvironment; - IGUIEnvironment* createGUIEnvironment(io::IFileSystem* fs, - video::IVideoDriver* Driver, IOSOperator* op); - } - - namespace scene - { - ISceneManager* createSceneManager(video::IVideoDriver* driver, gui::ICursorControl* cc); - } - - namespace io - { - IFileSystem* createFileSystem(); - } - - namespace video - { - IVideoDriver* createNullDriver(io::IFileSystem* io, const core::dimension2d& screenSize); - } - - - - //! Stub for an Irrlicht Device implementation - class CIrrDeviceStub : public IrrlichtDevice - { - public: - - //! constructor - CIrrDeviceStub(const SIrrlichtCreationParameters& param); - - //! destructor - virtual ~CIrrDeviceStub(); - - //! returns the video driver - video::IVideoDriver* getVideoDriver() override; - - //! return file system - io::IFileSystem* getFileSystem() override; - - //! returns the gui environment - gui::IGUIEnvironment* getGUIEnvironment() override; - - //! returns the scene manager - scene::ISceneManager* getSceneManager() override; - - //! \return Returns a pointer to the mouse cursor control interface. - gui::ICursorControl* getCursorControl() override; - - //! return the context manager - video::IContextManager* getContextManager() override; - - //! Returns a pointer to the ITimer object. With it the current Time can be received. - ITimer* getTimer() override; - - //! Sets the window icon. - bool setWindowIcon(const video::IImage *img) override; - - //! Returns the version of the engine. - const char* getVersion() const override; - - //! send the event to the right receiver - bool postEventFromUser(const SEvent& event) override; - - //! Sets a new event receiver to receive events - void setEventReceiver(IEventReceiver* receiver) override; - - //! Returns pointer to the current event receiver. Returns 0 if there is none. - IEventReceiver* getEventReceiver() override; - - //! Sets the input receiving scene manager. - /** If set to null, the main scene manager (returned by GetSceneManager()) will receive the input */ - void setInputReceivingSceneManager(scene::ISceneManager* sceneManager) override; - - //! Returns a pointer to the logger. - ILogger* getLogger() override; - - //! Returns the operation system opertator object. - IOSOperator* getOSOperator() override; - - //! Checks if the window is maximized. - bool isWindowMaximized() const override; - - //! Checks if the window is running in fullscreen mode. - bool isFullscreen() const override; - - //! get color format of the current window - video::ECOLOR_FORMAT getColorFormat() const override; - - //! Activate any joysticks, and generate events for them. - bool activateJoysticks(core::array & joystickInfo) override; - - //! Activate accelerometer. - bool activateAccelerometer(float updateInterval = 0.016666f) override; - - //! Deactivate accelerometer. - bool deactivateAccelerometer() override; - - //! Is accelerometer active. - bool isAccelerometerActive() override; - - //! Is accelerometer available. - bool isAccelerometerAvailable() override; - - //! Activate gyroscope. - bool activateGyroscope(float updateInterval = 0.016666f) override; - - //! Deactivate gyroscope. - bool deactivateGyroscope() override; - - //! Is gyroscope active. - bool isGyroscopeActive() override; - - //! Is gyroscope available. - bool isGyroscopeAvailable() override; - - //! Activate device motion. - bool activateDeviceMotion(float updateInterval = 0.016666f) override; - - //! Deactivate device motion. - bool deactivateDeviceMotion() override; - - //! Is device motion active. - bool isDeviceMotionActive() override; - - //! Is device motion available. - bool isDeviceMotionAvailable() override; - - //! Set the maximal elapsed time between 2 clicks to generate doubleclicks for the mouse. It also affects tripleclick behavior. - //! When set to 0 no double- and tripleclicks will be generated. - void setDoubleClickTime( u32 timeMs ) override; - - //! Get the maximal elapsed time between 2 clicks to generate double- and tripleclicks for the mouse. - u32 getDoubleClickTime() const override; - - //! Remove all messages pending in the system message loop - void clearSystemMessages() override; - - //! Get the display density in dots per inch. - float getDisplayDensity() const override; - - //! Resize the render window. - void setWindowSize(const irr::core::dimension2d& size) override {} - - protected: - - void createGUIAndScene(); - - //! checks version of SDK and prints warning if there might be a problem - bool checkVersion(const char* version); - - //! Compares to the last call of this function to return double and triple clicks. - /** Needed for win32 device event handling - \return Returns only 1,2 or 3. A 4th click will start with 1 again. - */ - virtual u32 checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent); - - //! Checks whether the input device should take input from the IME - bool acceptsIME(); - - video::IVideoDriver* VideoDriver; - gui::IGUIEnvironment* GUIEnvironment; - scene::ISceneManager* SceneManager; - ITimer* Timer; - gui::ICursorControl* CursorControl; - IEventReceiver* UserReceiver; - CLogger* Logger; - IOSOperator* Operator; - io::IFileSystem* FileSystem; - scene::ISceneManager* InputReceivingSceneManager; - - struct SMouseMultiClicks + SMouseMultiClicks() : + DoubleClickTime(500), CountSuccessiveClicks(0), LastClickTime(0), LastMouseInputEvent(EMIE_COUNT) { - SMouseMultiClicks() - : DoubleClickTime(500), CountSuccessiveClicks(0), LastClickTime(0), LastMouseInputEvent(EMIE_COUNT) - {} + } - u32 DoubleClickTime; - u32 CountSuccessiveClicks; - u32 LastClickTime; - core::position2di LastClick; - EMOUSE_INPUT_EVENT LastMouseInputEvent; - }; - SMouseMultiClicks MouseMultiClicks; - video::IContextManager* ContextManager; - SIrrlichtCreationParameters CreationParams; - bool Close; + u32 DoubleClickTime; + u32 CountSuccessiveClicks; + u32 LastClickTime; + core::position2di LastClick; + EMOUSE_INPUT_EVENT LastMouseInputEvent; }; + SMouseMultiClicks MouseMultiClicks; + video::IContextManager *ContextManager; + SIrrlichtCreationParameters CreationParams; + bool Close; +}; } // end namespace irr diff --git a/source/Irrlicht/CIrrDeviceWin32.cpp b/source/Irrlicht/CIrrDeviceWin32.cpp index e8e0e385..6301ab82 100644 --- a/source/Irrlicht/CIrrDeviceWin32.cpp +++ b/source/Irrlicht/CIrrDeviceWin32.cpp @@ -2,11 +2,10 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h +#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ -#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ - -#if defined (__STRICT_ANSI__) - #error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi. +#if defined(__STRICT_ANSI__) +#error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi. #endif #include "CIrrDeviceWin32.h" @@ -40,191 +39,178 @@ namespace irr { - namespace video - { +namespace video +{ #ifdef _IRR_COMPILE_WITH_OPENGL_ - IVideoDriver* createOpenGLDriver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOpenGLDriver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif #ifdef _IRR_COMPILE_WITH_OGLES1_ - IVideoDriver* createOGLES1Driver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOGLES1Driver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif #ifdef _IRR_COMPILE_WITH_OGLES2_ - IVideoDriver* createOGLES2Driver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); +IVideoDriver *createOGLES2Driver(const irr::SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); #endif - } +} } // end namespace irr namespace irr { - struct SJoystickWin32Control - { - CIrrDeviceWin32* Device; +struct SJoystickWin32Control +{ + CIrrDeviceWin32 *Device; - #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) - IDirectInput8* DirectInputDevice; - #endif - #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) - struct JoystickInfo - { - u32 Index; - #ifdef _IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_ - core::stringc Name; - GUID guid; - LPDIRECTINPUTDEVICE8 lpdijoy; - DIDEVCAPS devcaps; - u8 axisValid[8]; - #else - JOYCAPS Caps; - #endif - }; - core::array ActiveJoysticks; - #endif - - SJoystickWin32Control(CIrrDeviceWin32* dev); - ~SJoystickWin32Control(); - - #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) - static BOOL CALLBACK EnumJoysticks(LPCDIDEVICEINSTANCE lpddi, LPVOID cp); - void directInputAddJoystick(LPCDIDEVICEINSTANCE lpddi); - #endif - - void pollJoysticks(); - bool activateJoysticks(core::array & joystickInfo); - irr::core::stringc findJoystickName(int index, const JOYCAPS &caps) const; - }; - - - SJoystickWin32Control::SJoystickWin32Control(CIrrDeviceWin32* dev) : Device(dev) - { #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) - DirectInputDevice=0; - if (DI_OK != (DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DirectInputDevice, NULL))) - { - os::Printer::log("Could not create DirectInput8 Object", ELL_WARNING); - return; - } + IDirectInput8 *DirectInputDevice; #endif - } - - SJoystickWin32Control::~SJoystickWin32Control() +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) + struct JoystickInfo { -#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) - for(u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { - LPDIRECTINPUTDEVICE8 dev = ActiveJoysticks[joystick].lpdijoy; - if (dev) - { - dev->Unacquire(); - dev->Release(); - } - } - - if (DirectInputDevice) - DirectInputDevice->Release(); + u32 Index; +#ifdef _IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_ + core::stringc Name; + GUID guid; + LPDIRECTINPUTDEVICE8 lpdijoy; + DIDEVCAPS devcaps; + u8 axisValid[8]; +#else + JOYCAPS Caps; #endif - } + }; + core::array ActiveJoysticks; +#endif + + SJoystickWin32Control(CIrrDeviceWin32 *dev); + ~SJoystickWin32Control(); #if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) - BOOL CALLBACK SJoystickWin32Control::EnumJoysticks(LPCDIDEVICEINSTANCE lpddi, LPVOID cp) - { - SJoystickWin32Control* p=(SJoystickWin32Control*)cp; - p->directInputAddJoystick(lpddi); - return DIENUM_CONTINUE; + static BOOL CALLBACK EnumJoysticks(LPCDIDEVICEINSTANCE lpddi, LPVOID cp); + void directInputAddJoystick(LPCDIDEVICEINSTANCE lpddi); +#endif + + void pollJoysticks(); + bool activateJoysticks(core::array &joystickInfo); + irr::core::stringc findJoystickName(int index, const JOYCAPS &caps) const; +}; + +SJoystickWin32Control::SJoystickWin32Control(CIrrDeviceWin32 *dev) : + Device(dev) +{ +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) + DirectInputDevice = 0; + if (DI_OK != (DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&DirectInputDevice, NULL))) { + os::Printer::log("Could not create DirectInput8 Object", ELL_WARNING); + return; } - void SJoystickWin32Control::directInputAddJoystick(LPCDIDEVICEINSTANCE lpddi) - { - //Get the GUID of the joystuck - const GUID guid = lpddi->guidInstance; +#endif +} - JoystickInfo activeJoystick; - activeJoystick.Index=ActiveJoysticks.size(); - activeJoystick.guid=guid; - activeJoystick.Name=lpddi->tszProductName; - if (FAILED(DirectInputDevice->CreateDevice(guid, &activeJoystick.lpdijoy, NULL))) - { - os::Printer::log("Could not create DirectInput device", ELL_WARNING); - return; +SJoystickWin32Control::~SJoystickWin32Control() +{ +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) + for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { + LPDIRECTINPUTDEVICE8 dev = ActiveJoysticks[joystick].lpdijoy; + if (dev) { + dev->Unacquire(); + dev->Release(); } - - activeJoystick.devcaps.dwSize=sizeof(activeJoystick.devcaps); - if (FAILED(activeJoystick.lpdijoy->GetCapabilities(&activeJoystick.devcaps))) - { - os::Printer::log("Could not create DirectInput device", ELL_WARNING); - return; - } - - if (FAILED(activeJoystick.lpdijoy->SetCooperativeLevel(Device->HWnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE))) - { - os::Printer::log("Could not set DirectInput device cooperative level", ELL_WARNING); - return; - } - - if (FAILED(activeJoystick.lpdijoy->SetDataFormat(&c_dfDIJoystick2))) - { - os::Printer::log("Could not set DirectInput device data format", ELL_WARNING); - return; - } - - if (FAILED(activeJoystick.lpdijoy->Acquire())) - { - os::Printer::log("Could not set DirectInput cooperative level", ELL_WARNING); - return; - } - - DIJOYSTATE2 info; - if (FAILED(activeJoystick.lpdijoy->GetDeviceState(sizeof(info),&info))) - { - os::Printer::log("Could not read DirectInput device state", ELL_WARNING); - return; - } - - ZeroMemory(activeJoystick.axisValid,sizeof(activeJoystick.axisValid)); - activeJoystick.axisValid[0]= (info.lX!=0) ? 1 : 0; - activeJoystick.axisValid[1]= (info.lY!=0) ? 1 : 0; - activeJoystick.axisValid[2]= (info.lZ!=0) ? 1 : 0; - activeJoystick.axisValid[3]= (info.lRx!=0) ? 1 : 0; - activeJoystick.axisValid[4]= (info.lRy!=0) ? 1 : 0; - activeJoystick.axisValid[5]= (info.lRz!=0) ? 1 : 0; - - int caxis=0; - for (u8 i=0; i<6; i++) - { - if (activeJoystick.axisValid[i]) - caxis++; - } - - for (u8 i=0; i<(activeJoystick.devcaps.dwAxes)-caxis; i++) - { - if (i+caxis < 8) - activeJoystick.axisValid[i+caxis]=1; - } - - ActiveJoysticks.push_back(activeJoystick); } + + if (DirectInputDevice) + DirectInputDevice->Release(); +#endif +} + +#if defined(_IRR_COMPILE_WITH_JOYSTICK_EVENTS_) && defined(_IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_) +BOOL CALLBACK SJoystickWin32Control::EnumJoysticks(LPCDIDEVICEINSTANCE lpddi, LPVOID cp) +{ + SJoystickWin32Control *p = (SJoystickWin32Control *)cp; + p->directInputAddJoystick(lpddi); + return DIENUM_CONTINUE; +} +void SJoystickWin32Control::directInputAddJoystick(LPCDIDEVICEINSTANCE lpddi) +{ + // Get the GUID of the joystuck + const GUID guid = lpddi->guidInstance; + + JoystickInfo activeJoystick; + activeJoystick.Index = ActiveJoysticks.size(); + activeJoystick.guid = guid; + activeJoystick.Name = lpddi->tszProductName; + if (FAILED(DirectInputDevice->CreateDevice(guid, &activeJoystick.lpdijoy, NULL))) { + os::Printer::log("Could not create DirectInput device", ELL_WARNING); + return; + } + + activeJoystick.devcaps.dwSize = sizeof(activeJoystick.devcaps); + if (FAILED(activeJoystick.lpdijoy->GetCapabilities(&activeJoystick.devcaps))) { + os::Printer::log("Could not create DirectInput device", ELL_WARNING); + return; + } + + if (FAILED(activeJoystick.lpdijoy->SetCooperativeLevel(Device->HWnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE))) { + os::Printer::log("Could not set DirectInput device cooperative level", ELL_WARNING); + return; + } + + if (FAILED(activeJoystick.lpdijoy->SetDataFormat(&c_dfDIJoystick2))) { + os::Printer::log("Could not set DirectInput device data format", ELL_WARNING); + return; + } + + if (FAILED(activeJoystick.lpdijoy->Acquire())) { + os::Printer::log("Could not set DirectInput cooperative level", ELL_WARNING); + return; + } + + DIJOYSTATE2 info; + if (FAILED(activeJoystick.lpdijoy->GetDeviceState(sizeof(info), &info))) { + os::Printer::log("Could not read DirectInput device state", ELL_WARNING); + return; + } + + ZeroMemory(activeJoystick.axisValid, sizeof(activeJoystick.axisValid)); + activeJoystick.axisValid[0] = (info.lX != 0) ? 1 : 0; + activeJoystick.axisValid[1] = (info.lY != 0) ? 1 : 0; + activeJoystick.axisValid[2] = (info.lZ != 0) ? 1 : 0; + activeJoystick.axisValid[3] = (info.lRx != 0) ? 1 : 0; + activeJoystick.axisValid[4] = (info.lRy != 0) ? 1 : 0; + activeJoystick.axisValid[5] = (info.lRz != 0) ? 1 : 0; + + int caxis = 0; + for (u8 i = 0; i < 6; i++) { + if (activeJoystick.axisValid[i]) + caxis++; + } + + for (u8 i = 0; i < (activeJoystick.devcaps.dwAxes) - caxis; i++) { + if (i + caxis < 8) + activeJoystick.axisValid[i + caxis] = 1; + } + + ActiveJoysticks.push_back(activeJoystick); +} #endif void SJoystickWin32Control::pollJoysticks() { #if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ #ifdef _IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_ - if(0 == ActiveJoysticks.size()) + if (0 == ActiveJoysticks.size()) return; u32 joystick; DIJOYSTATE2 info; - for(joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { + for (joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { // needs to be reset for each joystick // request ALL values and POV as continuous if possible - const DIDEVCAPS & caps = ActiveJoysticks[joystick].devcaps; + const DIDEVCAPS &caps = ActiveJoysticks[joystick].devcaps; // if no POV is available don't ask for POV values - if (!FAILED(ActiveJoysticks[joystick].lpdijoy->GetDeviceState(sizeof(info),&info))) - { + if (!FAILED(ActiveJoysticks[joystick].lpdijoy->GetDeviceState(sizeof(info), &info))) { SEvent event; event.EventType = irr::EET_JOYSTICK_INPUT_EVENT; @@ -233,72 +219,69 @@ void SJoystickWin32Control::pollJoysticks() event.JoystickEvent.POV = (u16)info.rgdwPOV[0]; // set to undefined if no POV value was returned or the value // is out of range - if ((caps.dwPOVs==0) || (event.JoystickEvent.POV > 35900)) + if ((caps.dwPOVs == 0) || (event.JoystickEvent.POV > 35900)) event.JoystickEvent.POV = 65535; - for(int axis = 0; axis < SEvent::SJoystickEvent::NUMBER_OF_AXES; ++axis) + for (int axis = 0; axis < SEvent::SJoystickEvent::NUMBER_OF_AXES; ++axis) event.JoystickEvent.Axis[axis] = 0; - u16 dxAxis=0; - u16 irrAxis=0; + u16 dxAxis = 0; + u16 irrAxis = 0; - while (dxAxis < 6 && irrAxis 0) - axisFound=1; + if (ActiveJoysticks[joystick].axisValid[dxAxis] > 0) + axisFound = 1; - if (axisFound) - { - s32 val=axisValue - 32768; + if (axisFound) { + s32 val = axisValue - 32768; - if (val <-32767) val=-32767; - if (val > 32767) val=32767; - event.JoystickEvent.Axis[irrAxis]=(s16)(val); + if (val < -32767) + val = -32767; + if (val > 32767) + val = 32767; + event.JoystickEvent.Axis[irrAxis] = (s16)(val); irrAxis++; } dxAxis++; } - u32 buttons=0; - BYTE* bytebuttons=info.rgbButtons; - for (u16 i=0; i<32; i++) - { - if (bytebuttons[i] >0) - { + u32 buttons = 0; + BYTE *bytebuttons = info.rgbButtons; + for (u16 i = 0; i < 32; i++) { + if (bytebuttons[i] > 0) { buttons |= (1 << i); } } @@ -314,18 +297,16 @@ void SJoystickWin32Control::pollJoysticks() u32 joystick; JOYINFOEX info; - for(joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { + for (joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { // needs to be reset for each joystick // request ALL values and POV as continuous if possible info.dwSize = sizeof(info); - info.dwFlags = JOY_RETURNALL|JOY_RETURNPOVCTS; - const JOYCAPS & caps = ActiveJoysticks[joystick].Caps; + info.dwFlags = JOY_RETURNALL | JOY_RETURNPOVCTS; + const JOYCAPS &caps = ActiveJoysticks[joystick].Caps; // if no POV is available don't ask for POV values if (!(caps.wCaps & JOYCAPS_HASPOV)) - info.dwFlags &= ~(JOY_RETURNPOV|JOY_RETURNPOVCTS); - if(JOYERR_NOERROR == joyGetPosEx(ActiveJoysticks[joystick].Index, &info)) - { + info.dwFlags &= ~(JOY_RETURNPOV | JOY_RETURNPOVCTS); + if (JOYERR_NOERROR == joyGetPosEx(ActiveJoysticks[joystick].Index, &info)) { SEvent event; event.EventType = irr::EET_JOYSTICK_INPUT_EVENT; @@ -337,37 +318,36 @@ void SJoystickWin32Control::pollJoysticks() if (!(info.dwFlags & JOY_RETURNPOV) || (event.JoystickEvent.POV > 35900)) event.JoystickEvent.POV = 65535; - for(int axis = 0; axis < SEvent::SJoystickEvent::NUMBER_OF_AXES; ++axis) + for (int axis = 0; axis < SEvent::SJoystickEvent::NUMBER_OF_AXES; ++axis) event.JoystickEvent.Axis[axis] = 0; event.JoystickEvent.ButtonStates = info.dwButtons; - switch(caps.wNumAxes) - { + switch (caps.wNumAxes) { default: case 6: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_V] = - (s16)((65535 * (info.dwVpos - caps.wVmin)) / (caps.wVmax - caps.wVmin) - 32768); + (s16)((65535 * (info.dwVpos - caps.wVmin)) / (caps.wVmax - caps.wVmin) - 32768); case 5: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_U] = - (s16)((65535 * (info.dwUpos - caps.wUmin)) / (caps.wUmax - caps.wUmin) - 32768); + (s16)((65535 * (info.dwUpos - caps.wUmin)) / (caps.wUmax - caps.wUmin) - 32768); case 4: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_R] = - (s16)((65535 * (info.dwRpos - caps.wRmin)) / (caps.wRmax - caps.wRmin) - 32768); + (s16)((65535 * (info.dwRpos - caps.wRmin)) / (caps.wRmax - caps.wRmin) - 32768); case 3: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_Z] = - (s16)((65535 * (info.dwZpos - caps.wZmin)) / (caps.wZmax - caps.wZmin) - 32768); + (s16)((65535 * (info.dwZpos - caps.wZmin)) / (caps.wZmax - caps.wZmin) - 32768); case 2: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_Y] = - (s16)((65535 * (info.dwYpos - caps.wYmin)) / (caps.wYmax - caps.wYmin) - 32768); + (s16)((65535 * (info.dwYpos - caps.wYmin)) / (caps.wYmax - caps.wYmin) - 32768); case 1: event.JoystickEvent.Axis[SEvent::SJoystickEvent::AXIS_X] = - (s16)((65535 * (info.dwXpos - caps.wXmin)) / (caps.wXmax - caps.wXmin) - 32768); + (s16)((65535 * (info.dwXpos - caps.wXmin)) / (caps.wXmax - caps.wXmin) - 32768); } (void)Device->postEventFromUser(event); @@ -378,88 +358,84 @@ void SJoystickWin32Control::pollJoysticks() } /** This function is ported from SDL and released under zlib-license: - * Copyright (C) 1997-2014 Sam Lantinga */ + * Copyright (C) 1997-2014 Sam Lantinga */ irr::core::stringc SJoystickWin32Control::findJoystickName(int index, const JOYCAPS &caps) const { #if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ - // As a default use the name given in the joystick structure. - // It is always the same name, independent of joystick. - irr::core::stringc result(caps.szPname); + // As a default use the name given in the joystick structure. + // It is always the same name, independent of joystick. + irr::core::stringc result(caps.szPname); - core::stringc key = core::stringc(REGSTR_PATH_JOYCONFIG)+ "\\" + caps.szRegKey + "\\" + REGSTR_KEY_JOYCURR; - HKEY hTopKey = HKEY_LOCAL_MACHINE; - HKEY hKey; - long regresult = RegOpenKeyExA(hTopKey, key.c_str(), 0, KEY_READ, &hKey); - if (regresult != ERROR_SUCCESS) - { - hTopKey = HKEY_CURRENT_USER; - regresult = RegOpenKeyExA(hTopKey, key.c_str(), 0, KEY_READ, &hKey); - } - if (regresult != ERROR_SUCCESS) - return result; + core::stringc key = core::stringc(REGSTR_PATH_JOYCONFIG) + "\\" + caps.szRegKey + "\\" + REGSTR_KEY_JOYCURR; + HKEY hTopKey = HKEY_LOCAL_MACHINE; + HKEY hKey; + long regresult = RegOpenKeyExA(hTopKey, key.c_str(), 0, KEY_READ, &hKey); + if (regresult != ERROR_SUCCESS) { + hTopKey = HKEY_CURRENT_USER; + regresult = RegOpenKeyExA(hTopKey, key.c_str(), 0, KEY_READ, &hKey); + } + if (regresult != ERROR_SUCCESS) + return result; - /* find the registry key name for the joystick's properties */ - char regname[256]; - DWORD regsize = sizeof(regname); - core::stringc regvalue = core::stringc("Joystick")+core::stringc(index+1) + REGSTR_VAL_JOYOEMNAME; - regresult = RegQueryValueExA(hKey, regvalue.c_str(), 0, 0, (LPBYTE)regname, ®size); - RegCloseKey(hKey); - if (regresult != ERROR_SUCCESS) - return result; + /* find the registry key name for the joystick's properties */ + char regname[256]; + DWORD regsize = sizeof(regname); + core::stringc regvalue = core::stringc("Joystick") + core::stringc(index + 1) + REGSTR_VAL_JOYOEMNAME; + regresult = RegQueryValueExA(hKey, regvalue.c_str(), 0, 0, (LPBYTE)regname, ®size); + RegCloseKey(hKey); + if (regresult != ERROR_SUCCESS) + return result; - /* open that registry key */ - core::stringc regkey = core::stringc(REGSTR_PATH_JOYOEM) + "\\" + regname; - regresult = RegOpenKeyExA(hTopKey, regkey.c_str(), 0, KEY_READ, &hKey); - if (regresult != ERROR_SUCCESS) - return result; + /* open that registry key */ + core::stringc regkey = core::stringc(REGSTR_PATH_JOYOEM) + "\\" + regname; + regresult = RegOpenKeyExA(hTopKey, regkey.c_str(), 0, KEY_READ, &hKey); + if (regresult != ERROR_SUCCESS) + return result; - /* find the size for the OEM name text */ - regsize = sizeof(regvalue); - regresult = RegQueryValueEx(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, - NULL, ®size); - if (regresult == ERROR_SUCCESS) - { - char *name; - /* allocate enough memory for the OEM name text ... */ - name = new char[regsize]; - if (name) - { - /* ... and read it from the registry */ - regresult = RegQueryValueEx(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, - (LPBYTE)name, ®size ); - result = name; - } - delete[] name; - } - RegCloseKey(hKey); + /* find the size for the OEM name text */ + regsize = sizeof(regvalue); + regresult = RegQueryValueEx(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, + NULL, ®size); + if (regresult == ERROR_SUCCESS) { + char *name; + /* allocate enough memory for the OEM name text ... */ + name = new char[regsize]; + if (name) { + /* ... and read it from the registry */ + regresult = RegQueryValueEx(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, + (LPBYTE)name, ®size); + result = name; + } + delete[] name; + } + RegCloseKey(hKey); - return result; + return result; #endif return ""; } -bool SJoystickWin32Control::activateJoysticks(core::array & joystickInfo) +bool SJoystickWin32Control::activateJoysticks(core::array &joystickInfo) { #if defined _IRR_COMPILE_WITH_JOYSTICK_EVENTS_ joystickInfo.clear(); ActiveJoysticks.clear(); #ifdef _IRR_COMPILE_WITH_DIRECTINPUT_JOYSTICK_ - if (!DirectInputDevice || (DirectInputDevice->EnumDevices(DI8DEVCLASS_GAMECTRL, SJoystickWin32Control::EnumJoysticks, this, DIEDFL_ATTACHEDONLY ))) - { + if (!DirectInputDevice || (DirectInputDevice->EnumDevices(DI8DEVCLASS_GAMECTRL, SJoystickWin32Control::EnumJoysticks, this, DIEDFL_ATTACHEDONLY))) { os::Printer::log("Could not enum DirectInput8 controllers", ELL_WARNING); return false; } - for(u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) - { - JoystickInfo& activeJoystick = ActiveJoysticks[joystick]; + for (u32 joystick = 0; joystick < ActiveJoysticks.size(); ++joystick) { + JoystickInfo &activeJoystick = ActiveJoysticks[joystick]; SJoystickInfo info; - info.Axes=activeJoystick.devcaps.dwAxes; - info.Buttons=activeJoystick.devcaps.dwButtons; - info.Name=activeJoystick.Name; - info.PovHat = (activeJoystick.devcaps.dwPOVs != 0) - ? SJoystickInfo::POV_HAT_PRESENT : SJoystickInfo::POV_HAT_ABSENT; + info.Axes = activeJoystick.devcaps.dwAxes; + info.Buttons = activeJoystick.devcaps.dwButtons; + info.Name = activeJoystick.Name; + info.PovHat = (activeJoystick.devcaps.dwPOVs != 0) + ? SJoystickInfo::POV_HAT_PRESENT + : SJoystickInfo::POV_HAT_ABSENT; joystickInfo.push_back(info); } return true; @@ -476,14 +452,11 @@ bool SJoystickWin32Control::activateJoysticks(core::array & joyst ActiveJoysticks.reallocate(numberOfJoysticks); u32 joystick = 0; - for(; joystick < numberOfJoysticks; ++joystick) - { - if(JOYERR_NOERROR == joyGetPosEx(joystick, &info) - && - JOYERR_NOERROR == joyGetDevCaps(joystick, - &activeJoystick.Caps, - sizeof(activeJoystick.Caps))) - { + for (; joystick < numberOfJoysticks; ++joystick) { + if (JOYERR_NOERROR == joyGetPosEx(joystick, &info) && + JOYERR_NOERROR == joyGetDevCaps(joystick, + &activeJoystick.Caps, + sizeof(activeJoystick.Caps))) { activeJoystick.Index = joystick; ActiveJoysticks.push_back(activeJoystick); @@ -492,18 +465,18 @@ bool SJoystickWin32Control::activateJoysticks(core::array & joyst returnInfo.Buttons = activeJoystick.Caps.wNumButtons; returnInfo.Name = findJoystickName(joystick, activeJoystick.Caps); returnInfo.PovHat = ((activeJoystick.Caps.wCaps & JOYCAPS_HASPOV) == JOYCAPS_HASPOV) - ? SJoystickInfo::POV_HAT_PRESENT : SJoystickInfo::POV_HAT_ABSENT; + ? SJoystickInfo::POV_HAT_PRESENT + : SJoystickInfo::POV_HAT_ABSENT; joystickInfo.push_back(returnInfo); } } - for(joystick = 0; joystick < joystickInfo.size(); ++joystick) - { + for (joystick = 0; joystick < joystickInfo.size(); ++joystick) { char logString[256]; snprintf_irr(logString, sizeof(logString), "Found joystick %d, %d axes, %d buttons '%s'", - joystick, joystickInfo[joystick].Axes, - joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); + joystick, joystickInfo[joystick].Axes, + joystickInfo[joystick].Buttons, joystickInfo[joystick].Name.c_str()); os::Printer::log(logString, ELL_INFORMATION); } @@ -517,45 +490,42 @@ bool SJoystickWin32Control::activateJoysticks(core::array & joyst namespace { - struct SEnvMapper - { - HWND hWnd; - irr::CIrrDeviceWin32* irrDev; - }; - // NOTE: This is global. We can have more than one Irrlicht Device at same time. - irr::core::array EnvMap; +struct SEnvMapper +{ + HWND hWnd; + irr::CIrrDeviceWin32 *irrDev; +}; +// NOTE: This is global. We can have more than one Irrlicht Device at same time. +irr::core::array EnvMap; - HKL KEYBOARD_INPUT_HKL=0; +HKL KEYBOARD_INPUT_HKL = 0; } -irr::CIrrDeviceWin32* getDeviceFromHWnd(HWND hWnd) +irr::CIrrDeviceWin32 *getDeviceFromHWnd(HWND hWnd) { const irr::u32 end = EnvMap.size(); - for ( irr::u32 i=0; i < end; ++i ) - { - const SEnvMapper& env = EnvMap[i]; - if ( env.hWnd == hWnd ) + for (irr::u32 i = 0; i < end; ++i) { + const SEnvMapper &env = EnvMap[i]; + if (env.hWnd == hWnd) return env.irrDev; } return 0; } - LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - #ifndef WHEEL_DELTA - #define WHEEL_DELTA 120 - #endif +#ifndef WHEEL_DELTA +#define WHEEL_DELTA 120 +#endif - irr::CIrrDeviceWin32* dev = 0; + irr::CIrrDeviceWin32 *dev = 0; irr::SEvent event; - static irr::s32 ClickCount=0; + static irr::s32 ClickCount = 0; if (GetCapture() != hWnd && ClickCount > 0) ClickCount = 0; - struct messageMap { irr::s32 group; @@ -564,49 +534,44 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) }; static messageMap mouseMap[] = - { - {0, WM_LBUTTONDOWN, irr::EMIE_LMOUSE_PRESSED_DOWN}, - {1, WM_LBUTTONUP, irr::EMIE_LMOUSE_LEFT_UP}, - {0, WM_RBUTTONDOWN, irr::EMIE_RMOUSE_PRESSED_DOWN}, - {1, WM_RBUTTONUP, irr::EMIE_RMOUSE_LEFT_UP}, - {0, WM_MBUTTONDOWN, irr::EMIE_MMOUSE_PRESSED_DOWN}, - {1, WM_MBUTTONUP, irr::EMIE_MMOUSE_LEFT_UP}, - {2, WM_MOUSEMOVE, irr::EMIE_MOUSE_MOVED}, - {3, WM_MOUSEWHEEL, irr::EMIE_MOUSE_WHEEL}, - {-1, 0, 0} - }; + { + {0, WM_LBUTTONDOWN, irr::EMIE_LMOUSE_PRESSED_DOWN}, + {1, WM_LBUTTONUP, irr::EMIE_LMOUSE_LEFT_UP}, + {0, WM_RBUTTONDOWN, irr::EMIE_RMOUSE_PRESSED_DOWN}, + {1, WM_RBUTTONUP, irr::EMIE_RMOUSE_LEFT_UP}, + {0, WM_MBUTTONDOWN, irr::EMIE_MMOUSE_PRESSED_DOWN}, + {1, WM_MBUTTONUP, irr::EMIE_MMOUSE_LEFT_UP}, + {2, WM_MOUSEMOVE, irr::EMIE_MOUSE_MOVED}, + {3, WM_MOUSEWHEEL, irr::EMIE_MOUSE_WHEEL}, + {-1, 0, 0}}; // handle grouped events - messageMap * m = mouseMap; - while ( m->group >=0 && m->winMessage != message ) + messageMap *m = mouseMap; + while (m->group >= 0 && m->winMessage != message) m += 1; - if ( m->group >= 0 ) - { - if ( m->group == 0 ) // down + if (m->group >= 0) { + if (m->group == 0) // down { ClickCount++; SetCapture(hWnd); - } - else - if ( m->group == 1 ) // up + } else if (m->group == 1) // up { ClickCount--; - if (ClickCount<1) - { - ClickCount=0; + if (ClickCount < 1) { + ClickCount = 0; ReleaseCapture(); } } event.EventType = irr::EET_MOUSE_INPUT_EVENT; - event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT) m->irrMessage; + event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)m->irrMessage; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons - event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); + event.MouseInput.ButtonStates = wParam & (MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; @@ -617,10 +582,10 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) event.MouseInput.Wheel = 0.f; // wheel - if ( m->group == 3 ) - { + if (m->group == 3) { POINT p; // fixed by jox - p.x = 0; p.y = 0; + p.x = 0; + p.y = 0; ClientToScreen(hWnd, &p); event.MouseInput.X -= p.x; event.MouseInput.Y -= p.y; @@ -628,21 +593,16 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) } dev = getDeviceFromHWnd(hWnd); - if (dev) - { + if (dev) { dev->postEventFromUser(event); - if ( event.MouseInput.Event >= irr::EMIE_LMOUSE_PRESSED_DOWN && event.MouseInput.Event <= irr::EMIE_MMOUSE_PRESSED_DOWN ) - { + if (event.MouseInput.Event >= irr::EMIE_LMOUSE_PRESSED_DOWN && event.MouseInput.Event <= irr::EMIE_MMOUSE_PRESSED_DOWN) { irr::u32 clicks = dev->checkSuccessiveClicks(event.MouseInput.X, event.MouseInput.Y, event.MouseInput.Event); - if ( clicks == 2 ) - { - event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_DOUBLE_CLICK + event.MouseInput.Event-irr::EMIE_LMOUSE_PRESSED_DOWN); + if (clicks == 2) { + event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_DOUBLE_CLICK + event.MouseInput.Event - irr::EMIE_LMOUSE_PRESSED_DOWN); dev->postEventFromUser(event); - } - else if ( clicks == 3 ) - { - event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_TRIPLE_CLICK + event.MouseInput.Event-irr::EMIE_LMOUSE_PRESSED_DOWN); + } else if (clicks == 3) { + event.MouseInput.Event = (irr::EMOUSE_INPUT_EVENT)(irr::EMIE_LMOUSE_TRIPLE_CLICK + event.MouseInput.Event - irr::EMIE_LMOUSE_PRESSED_DOWN); dev->postEventFromUser(event); } } @@ -650,14 +610,12 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) return 0; } - switch (message) - { - case WM_PAINT: - { - PAINTSTRUCT ps; - BeginPaint(hWnd, &ps); - EndPaint(hWnd, &ps); - } + switch (message) { + case WM_PAINT: { + PAINTSTRUCT ps; + BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + } return 0; case WM_ERASEBKGND: @@ -666,67 +624,62 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_KEYDOWN: - case WM_KEYUP: - { - BYTE allKeys[256]; + case WM_KEYUP: { + BYTE allKeys[256]; - event.EventType = irr::EET_KEY_INPUT_EVENT; - event.KeyInput.Key = (irr::EKEY_CODE)wParam; - event.KeyInput.PressedDown = (message==WM_KEYDOWN || message == WM_SYSKEYDOWN); + event.EventType = irr::EET_KEY_INPUT_EVENT; + event.KeyInput.Key = (irr::EKEY_CODE)wParam; + event.KeyInput.PressedDown = (message == WM_KEYDOWN || message == WM_SYSKEYDOWN); - if ( event.KeyInput.Key == irr::KEY_SHIFT ) - { - event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MAPVK_VSC_TO_VK_EX ); - } - if ( event.KeyInput.Key == irr::KEY_CONTROL ) - { - event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MAPVK_VSC_TO_VK_EX ); - // some keyboards will just return LEFT for both - left and right keys. So also check extend bit. - if (lParam & 0x1000000) - event.KeyInput.Key = irr::KEY_RCONTROL; - } - if ( event.KeyInput.Key == irr::KEY_MENU ) - { - event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey( ((lParam>>16) & 255), MAPVK_VSC_TO_VK_EX ); - if (lParam & 0x1000000) - event.KeyInput.Key = irr::KEY_RMENU; - } - - GetKeyboardState(allKeys); - - event.KeyInput.Shift = ((allKeys[VK_SHIFT] & 0x80)!=0); - event.KeyInput.Control = ((allKeys[VK_CONTROL] & 0x80)!=0); - - // Handle unicode and deadkeys - WCHAR keyChars[2]; - UINT scanCode = HIWORD(lParam); - int conversionResult = ToUnicodeEx(static_cast(wParam),scanCode,allKeys,keyChars,2,0,KEYBOARD_INPUT_HKL); - if (conversionResult == 1) - event.KeyInput.Char = keyChars[0]; - else - event.KeyInput.Char = 0; - - // allow composing characters like '@' with Alt Gr on non-US keyboards - if ((allKeys[VK_MENU] & 0x80) != 0) - event.KeyInput.Control = 0; - - dev = getDeviceFromHWnd(hWnd); - if (dev) - dev->postEventFromUser(event); - - if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP) - return DefWindowProcW(hWnd, message, wParam, lParam); - else - return 0; + if (event.KeyInput.Key == irr::KEY_SHIFT) { + event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey(((lParam >> 16) & 255), MAPVK_VSC_TO_VK_EX); + } + if (event.KeyInput.Key == irr::KEY_CONTROL) { + event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey(((lParam >> 16) & 255), MAPVK_VSC_TO_VK_EX); + // some keyboards will just return LEFT for both - left and right keys. So also check extend bit. + if (lParam & 0x1000000) + event.KeyInput.Key = irr::KEY_RCONTROL; + } + if (event.KeyInput.Key == irr::KEY_MENU) { + event.KeyInput.Key = (irr::EKEY_CODE)MapVirtualKey(((lParam >> 16) & 255), MAPVK_VSC_TO_VK_EX); + if (lParam & 0x1000000) + event.KeyInput.Key = irr::KEY_RMENU; } - case WM_SIZE: - { - // resize - dev = getDeviceFromHWnd(hWnd); - if (dev) - dev->OnResized(); - } + GetKeyboardState(allKeys); + + event.KeyInput.Shift = ((allKeys[VK_SHIFT] & 0x80) != 0); + event.KeyInput.Control = ((allKeys[VK_CONTROL] & 0x80) != 0); + + // Handle unicode and deadkeys + WCHAR keyChars[2]; + UINT scanCode = HIWORD(lParam); + int conversionResult = ToUnicodeEx(static_cast(wParam), scanCode, allKeys, keyChars, 2, 0, KEYBOARD_INPUT_HKL); + if (conversionResult == 1) + event.KeyInput.Char = keyChars[0]; + else + event.KeyInput.Char = 0; + + // allow composing characters like '@' with Alt Gr on non-US keyboards + if ((allKeys[VK_MENU] & 0x80) != 0) + event.KeyInput.Control = 0; + + dev = getDeviceFromHWnd(hWnd); + if (dev) + dev->postEventFromUser(event); + + if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP) + return DefWindowProcW(hWnd, message, wParam, lParam); + else + return 0; + } + + case WM_SIZE: { + // resize + dev = getDeviceFromHWnd(hWnd); + if (dev) + dev->OnResized(); + } return 0; case WM_DESTROY: @@ -736,9 +689,8 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) case WM_SYSCOMMAND: // prevent screensaver or monitor powersave mode from starting if ((wParam & 0xFFF0) == SC_SCREENSAVE || - (wParam & 0xFFF0) == SC_MONITORPOWER || - (wParam & 0xFFF0) == SC_KEYMENU - ) + (wParam & 0xFFF0) == SC_MONITORPOWER || + (wParam & 0xFFF0) == SC_KEYMENU) return 0; break; @@ -757,10 +709,9 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) case WM_SETCURSOR: // because Windows forgot about that in the meantime dev = getDeviceFromHWnd(hWnd); - if (dev) - { - dev->getCursorControl()->setActiveIcon( dev->getCursorControl()->getActiveIcon() ); - dev->getCursorControl()->setVisible( dev->getCursorControl()->isVisible() ); + if (dev) { + dev->getCursorControl()->setActiveIcon(dev->getCursorControl()->getActiveIcon()); + dev->getCursorControl()->setVisible(dev->getCursorControl()->isVisible()); } break; @@ -772,19 +723,18 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) return DefWindowProcW(hWnd, message, wParam, lParam); } - namespace irr { //! constructor -CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) -: CIrrDeviceStub(params), HWnd(0), Resized(false), - ExternalWindow(false), Win32CursorControl(0), JoyControl(0), - WindowMaximized(params.WindowMaximized) +CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters ¶ms) : + CIrrDeviceStub(params), HWnd(0), Resized(false), + ExternalWindow(false), Win32CursorControl(0), JoyControl(0), + WindowMaximized(params.WindowMaximized) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CIrrDeviceWin32"); - #endif +#endif // get windows version and create OS operator core::stringc winversion; @@ -796,24 +746,23 @@ CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) HINSTANCE hInstance = GetModuleHandle(0); // create the window if we need to and we do not use the null device - if (!CreationParams.WindowId && CreationParams.DriverType != video::EDT_NULL) - { - const wchar_t* ClassName = L"CIrrDeviceWin32"; + if (!CreationParams.WindowId && CreationParams.DriverType != video::EDT_NULL) { + const wchar_t *ClassName = L"CIrrDeviceWin32"; // Register Class WNDCLASSEXW wcex; - wcex.cbSize = sizeof(WNDCLASSEXW); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = WndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hInstance; - wcex.hIcon = NULL; - wcex.hCursor = 0; // LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = 0; - wcex.lpszClassName = ClassName; - wcex.hIconSm = 0; + wcex.cbSize = sizeof(WNDCLASSEXW); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = NULL; + wcex.hCursor = 0; // LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wcex.lpszMenuName = 0; + wcex.lpszClassName = ClassName; + wcex.hIconSm = 0; RegisterClassExW(&wcex); @@ -831,35 +780,29 @@ CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; - s32 windowLeft = (CreationParams.WindowPosition.X == -1 ? - (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2 : - CreationParams.WindowPosition.X); - s32 windowTop = (CreationParams.WindowPosition.Y == -1 ? - (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2 : - CreationParams.WindowPosition.Y); + s32 windowLeft = (CreationParams.WindowPosition.X == -1 ? (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2 : CreationParams.WindowPosition.X); + s32 windowTop = (CreationParams.WindowPosition.Y == -1 ? (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2 : CreationParams.WindowPosition.Y); - if ( windowLeft < 0 ) + if (windowLeft < 0) windowLeft = 0; - if ( windowTop < 0 ) - windowTop = 0; // make sure window menus are in screen on creation + if (windowTop < 0) + windowTop = 0; // make sure window menus are in screen on creation - if (CreationParams.Fullscreen) - { + if (CreationParams.Fullscreen) { windowLeft = 0; windowTop = 0; } // create window - HWnd = CreateWindowW( ClassName, L"", style, windowLeft, windowTop, - realWidth, realHeight, NULL, NULL, hInstance, NULL); - if (!HWnd) - { + HWnd = CreateWindowW(ClassName, L"", style, windowLeft, windowTop, + realWidth, realHeight, NULL, NULL, hInstance, NULL); + if (!HWnd) { os::Printer::log("Window could not be created.", ELL_ERROR); } CreationParams.WindowId = HWnd; -// CreationParams.WindowSize.Width = realWidth; -// CreationParams.WindowSize.Height = realHeight; + // CreationParams.WindowSize.Width = realWidth; + // CreationParams.WindowSize.Height = realHeight; ShowWindow(HWnd, SW_SHOWNORMAL); UpdateWindow(HWnd); @@ -869,9 +812,7 @@ CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) // make sure everything gets updated to the real sizes Resized = true; - } - else if (CreationParams.WindowId) - { + } else if (CreationParams.WindowId) { // attach external window HWnd = static_cast(CreationParams.WindowId); RECT r; @@ -906,8 +847,7 @@ CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) EnvMap.push_back(em); // set this as active window - if (!ExternalWindow) - { + if (!ExternalWindow) { SetActiveWindow(HWnd); SetForegroundWindow(HWnd); } @@ -921,29 +861,24 @@ CIrrDeviceWin32::CIrrDeviceWin32(const SIrrlichtCreationParameters& params) maximizeWindow(); } - //! destructor CIrrDeviceWin32::~CIrrDeviceWin32() { delete JoyControl; // unregister environment - for (u32 i=0; i< EnvMap.size(); ++i) - { - if (EnvMap[i].hWnd == HWnd) - { + for (u32 i = 0; i < EnvMap.size(); ++i) { + if (EnvMap[i].hWnd == HWnd) { EnvMap.erase(i); break; } } } - //! create the driver void CIrrDeviceWin32::createDriver() { - switch(CreationParams.DriverType) - { + switch (CreationParams.DriverType) { case video::EDT_OPENGL: #ifdef _IRR_COMPILE_WITH_OPENGL_ switchToFullScreen(); @@ -1001,26 +936,24 @@ void CIrrDeviceWin32::createDriver() } } - //! runs the device. Returns false if device wants to be deleted bool CIrrDeviceWin32::run() { os::Timer::tick(); - static_cast(CursorControl)->update(); + static_cast(CursorControl)->update(); handleSystemMessages(); if (!Close) resizeIfNecessary(); - if(!Close && JoyControl) + if (!Close && JoyControl) JoyControl->pollJoysticks(); return !Close; } - //! Pause the current process for the minimum time allowed only to allow other processes to execute void CIrrDeviceWin32::yield() { @@ -1040,7 +973,6 @@ void CIrrDeviceWin32::sleep(u32 timeMs, bool pauseTimer) Timer->start(); } - void CIrrDeviceWin32::resizeIfNecessary() { if (!Resized || !getVideoDriver()) @@ -1051,13 +983,10 @@ void CIrrDeviceWin32::resizeIfNecessary() char tmp[255]; - if (r.right < 2 || r.bottom < 2) - { + if (r.right < 2 || r.bottom < 2) { snprintf_irr(tmp, sizeof(tmp), "Ignoring resize operation to (%ld %ld)", r.right, r.bottom); os::Printer::log(tmp); - } - else - { + } else { snprintf_irr(tmp, sizeof(tmp), "Resizing window (%ld %ld)", r.right, r.bottom); os::Printer::log(tmp); @@ -1068,20 +997,19 @@ void CIrrDeviceWin32::resizeIfNecessary() Resized = false; } - DWORD CIrrDeviceWin32::getWindowStyle(bool fullscreen, bool resizable) const { - if ( fullscreen ) + if (fullscreen) return WS_POPUP; - if ( resizable ) + if (resizable) return WS_THICKFRAME | WS_SYSMENU | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; return WS_BORDER | WS_SYSMENU | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; } //! sets the caption of the window -void CIrrDeviceWin32::setWindowCaption(const wchar_t* text) +void CIrrDeviceWin32::setWindowCaption(const wchar_t *text) { // We use SendMessage instead of SetText to ensure proper // function even in cases where the HWND was created in a different thread @@ -1091,7 +1019,6 @@ void CIrrDeviceWin32::setWindowCaption(const wchar_t* text) SMTO_ABORTIFHUNG, 2000, &dwResult); } - //! Sets the window icon. bool CIrrDeviceWin32::setWindowIcon(const video::IImage *img) { @@ -1099,7 +1026,7 @@ bool CIrrDeviceWin32::setWindowIcon(const video::IImage *img) // (This is minetest-specific!) const HICON hicon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(130) // The ID of the ICON defined in - // winresource.rc + // winresource.rc ); if (hicon) { @@ -1111,32 +1038,28 @@ bool CIrrDeviceWin32::setWindowIcon(const video::IImage *img) return false; } - //! notifies the device that it should close itself void CIrrDeviceWin32::closeDevice() { - if (!ExternalWindow) - { + if (!ExternalWindow) { MSG msg; PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE); PostQuitMessage(0); PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE); DestroyWindow(HWnd); - const wchar_t* ClassName = L"CIrrDeviceWin32"; + const wchar_t *ClassName = L"CIrrDeviceWin32"; HINSTANCE hInstance = GetModuleHandle(0); UnregisterClassW(ClassName, hInstance); } - Close=true; + Close = true; } - //! returns if window is active. if not, nothing needs to be drawn bool CIrrDeviceWin32::isWindowActive() const { return (GetActiveWindow() == HWnd); } - //! returns if window has focus bool CIrrDeviceWin32::isWindowFocused() const { @@ -1144,26 +1067,23 @@ bool CIrrDeviceWin32::isWindowFocused() const return ret; } - //! returns if window is minimized bool CIrrDeviceWin32::isWindowMinimized() const { WINDOWPLACEMENT plc; - plc.length=sizeof(WINDOWPLACEMENT); - bool ret=false; - if (GetWindowPlacement(HWnd,&plc)) + plc.length = sizeof(WINDOWPLACEMENT); + bool ret = false; + if (GetWindowPlacement(HWnd, &plc)) ret = plc.showCmd == SW_SHOWMINIMIZED; return ret; } - //! returns last state from maximizeWindow() and restoreWindow() bool CIrrDeviceWin32::isWindowMaximized() const { return WindowMaximized; } - //! switches to fullscreen bool CIrrDeviceWin32::switchToFullScreen() { @@ -1175,29 +1095,25 @@ bool CIrrDeviceWin32::switchToFullScreen() MONITORINFO mi; mi.cbSize = sizeof(mi); - if (GetMonitorInfo(MonitorFromWindow(HWnd,MONITOR_DEFAULTTOPRIMARY),&mi)) - { - UINT flags = SWP_NOCOPYBITS|SWP_NOOWNERZORDER|SWP_FRAMECHANGED; + if (GetMonitorInfo(MonitorFromWindow(HWnd, MONITOR_DEFAULTTOPRIMARY), &mi)) { + UINT flags = SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_FRAMECHANGED; SetWindowPos(HWnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, - mi.rcMonitor.right - mi.rcMonitor.left, - mi.rcMonitor.bottom - mi.rcMonitor.top, flags); - } - else - { + mi.rcMonitor.right - mi.rcMonitor.left, + mi.rcMonitor.bottom - mi.rcMonitor.top, flags); + } else { CreationParams.Fullscreen = false; } return CreationParams.Fullscreen; } - //! returns the win32 cursor control -CIrrDeviceWin32::CCursorControl* CIrrDeviceWin32::getWin32CursorControl() +CIrrDeviceWin32::CCursorControl *CIrrDeviceWin32::getWin32CursorControl() { return Win32CursorControl; } -void CIrrDeviceWin32::getWindowsVersion(core::stringc& out) +void CIrrDeviceWin32::getWindowsVersion(core::stringc &out) { OSVERSIONINFO osvi; @@ -1217,7 +1133,7 @@ void CIrrDeviceWin32::OnResized() } //! Resize the render window. -void CIrrDeviceWin32::setWindowSize(const irr::core::dimension2d& size) +void CIrrDeviceWin32::setWindowSize(const irr::core::dimension2d &size) { if (ExternalWindow || !getVideoDriver() || CreationParams.Fullscreen) return; @@ -1234,7 +1150,7 @@ void CIrrDeviceWin32::setWindowSize(const irr::core::dimension2d& size) const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; - UINT flags = SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOOWNERZORDER|SWP_NOZORDER; + UINT flags = SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER; SetWindowPos(HWnd, HWND_TOP, 0, 0, realWidth, realHeight, flags); } @@ -1263,12 +1179,11 @@ void CIrrDeviceWin32::setResizable(bool resize) const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2; SetWindowPos(HWnd, HWND_TOP, windowLeft, windowTop, realWidth, realHeight, - SWP_FRAMECHANGED | SWP_NOMOVE | SWP_SHOWWINDOW); + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_SHOWWINDOW); - static_cast(CursorControl)->updateBorderSize(CreationParams.Fullscreen, resize); + static_cast(CursorControl)->updateBorderSize(CreationParams.Fullscreen, resize); } - //! Minimizes the window. void CIrrDeviceWin32::minimizeWindow() { @@ -1279,7 +1194,6 @@ void CIrrDeviceWin32::minimizeWindow() SetWindowPlacement(HWnd, &wndpl); } - //! Maximizes the window. void CIrrDeviceWin32::maximizeWindow() { @@ -1292,7 +1206,6 @@ void CIrrDeviceWin32::maximizeWindow() WindowMaximized = true; } - //! Restores the window to its original size. void CIrrDeviceWin32::restoreWindow() { @@ -1309,20 +1222,17 @@ core::position2di CIrrDeviceWin32::getWindowPosition() { WINDOWPLACEMENT wndpl; wndpl.length = sizeof(WINDOWPLACEMENT); - if (GetWindowPlacement(HWnd, &wndpl)) - { + if (GetWindowPlacement(HWnd, &wndpl)) { return core::position2di((int)wndpl.rcNormalPosition.left, - (int)wndpl.rcNormalPosition.top); - } - else - { + (int)wndpl.rcNormalPosition.top); + } else { // No reason for this to happen os::Printer::log("Failed to retrieve window location", ELL_ERROR); return core::position2di(-1, -1); } } -bool CIrrDeviceWin32::activateJoysticks(core::array & joystickInfo) +bool CIrrDeviceWin32::activateJoysticks(core::array &joystickInfo) { if (JoyControl) return JoyControl->activateJoysticks(joystickInfo); @@ -1330,28 +1240,20 @@ bool CIrrDeviceWin32::activateJoysticks(core::array & joystickInf return false; } - //! Process system events void CIrrDeviceWin32::handleSystemMessages() { MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - if (ExternalWindow && msg.hwnd == HWnd) - { - if (msg.hwnd == HWnd) - { + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + if (ExternalWindow && msg.hwnd == HWnd) { + if (msg.hwnd == HWnd) { WndProc(HWnd, msg.message, msg.wParam, msg.lParam); - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - else - { + } else { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } else { // No message translation because we don't use WM_CHAR and it would conflict with our // deadkey handling. DispatchMessage(&msg); @@ -1362,18 +1264,16 @@ void CIrrDeviceWin32::handleSystemMessages() } } - //! Remove all messages pending in the system message loop void CIrrDeviceWin32::clearSystemMessages() { MSG msg; - while (PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) - {} - while (PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE)) - {} + while (PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) { + } + while (PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE)) { + } } - //! Get the display density in dots per inch. float CIrrDeviceWin32::getDisplayDensity() const { @@ -1383,10 +1283,9 @@ float CIrrDeviceWin32::getDisplayDensity() const return dpi; } - // Convert an Irrlicht texture to a Windows cursor // Based on http://www.codeguru.com/cpp/w-p/win32/cursors/article.php/c4529/ -HCURSOR CIrrDeviceWin32::TextureToCursor(HWND hwnd, irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot) +HCURSOR CIrrDeviceWin32::TextureToCursor(HWND hwnd, irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot) { // // create the bitmaps needed for cursors from the texture @@ -1400,30 +1299,26 @@ HCURSOR CIrrDeviceWin32::TextureToCursor(HWND hwnd, irr::video::ITexture * tex, HBITMAP oldAndBitmap = (HBITMAP)SelectObject(andDc, andBitmap); HBITMAP oldXorBitmap = (HBITMAP)SelectObject(xorDc, xorBitmap); - video::ECOLOR_FORMAT format = tex->getColorFormat(); u32 bytesPerPixel = video::IImage::getBitsPerPixelFromFormat(format) / 8; u32 bytesLeftGap = sourceRect.UpperLeftCorner.X * bytesPerPixel; u32 bytesRightGap = tex->getPitch() - sourceRect.LowerRightCorner.X * bytesPerPixel; - const u8* data = (const u8*)tex->lock(video::ETLM_READ_ONLY, 0); - data += sourceRect.UpperLeftCorner.Y*tex->getPitch(); - for ( s32 y = 0; y < sourceRect.getHeight(); ++y ) - { + const u8 *data = (const u8 *)tex->lock(video::ETLM_READ_ONLY, 0); + data += sourceRect.UpperLeftCorner.Y * tex->getPitch(); + for (s32 y = 0; y < sourceRect.getHeight(); ++y) { data += bytesLeftGap; - for ( s32 x = 0; x < sourceRect.getWidth(); ++x ) - { + for (s32 x = 0; x < sourceRect.getWidth(); ++x) { video::SColor pixelCol; - pixelCol.setData((const void*)data, format); + pixelCol.setData((const void *)data, format); data += bytesPerPixel; - if ( pixelCol.getAlpha() == 0 ) // transparent + if (pixelCol.getAlpha() == 0) // transparent { - SetPixel(andDc, x, y, RGB(255,255,255)); - SetPixel(xorDc, x, y, RGB(0,0,0)); - } - else // color + SetPixel(andDc, x, y, RGB(255, 255, 255)); + SetPixel(xorDc, x, y, RGB(0, 0, 0)); + } else // color { - SetPixel(andDc, x, y, RGB(0,0,0)); + SetPixel(andDc, x, y, RGB(0, 0, 0)); SetPixel(xorDc, x, y, RGB(pixelCol.getRed(), pixelCol.getGreen(), pixelCol.getBlue())); } } @@ -1442,7 +1337,7 @@ HCURSOR CIrrDeviceWin32::TextureToCursor(HWND hwnd, irr::video::ITexture * tex, // create the cursor ICONINFO iconinfo; - iconinfo.fIcon = false; // type is cursor not icon + iconinfo.fIcon = false; // type is cursor not icon iconinfo.xHotspot = hotspot.X; iconinfo.yHotspot = hotspot.Y; iconinfo.hbmMask = andBitmap; @@ -1456,17 +1351,15 @@ HCURSOR CIrrDeviceWin32::TextureToCursor(HWND hwnd, irr::video::ITexture * tex, return cursor; } - -CIrrDeviceWin32::CCursorControl::CCursorControl(CIrrDeviceWin32* device, const core::dimension2d& wsize, HWND hwnd, bool fullscreen) - : Device(device), WindowSize(wsize), InvWindowSize(0.0f, 0.0f), +CIrrDeviceWin32::CCursorControl::CCursorControl(CIrrDeviceWin32 *device, const core::dimension2d &wsize, HWND hwnd, bool fullscreen) : + Device(device), WindowSize(wsize), InvWindowSize(0.0f, 0.0f), HWnd(hwnd), BorderX(0), BorderY(0), - UseReferenceRect(false), IsVisible(true) - , ActiveIcon(gui::ECI_NORMAL), ActiveIconStartTime(0) + UseReferenceRect(false), IsVisible(true), ActiveIcon(gui::ECI_NORMAL), ActiveIconStartTime(0) { - if (WindowSize.Width!=0) + if (WindowSize.Width != 0) InvWindowSize.Width = 1.0f / WindowSize.Width; - if (WindowSize.Height!=0) + if (WindowSize.Height != 0) InvWindowSize.Height = 1.0f / WindowSize.Height; updateBorderSize(fullscreen, false); @@ -1475,111 +1368,99 @@ CIrrDeviceWin32::CCursorControl::CCursorControl(CIrrDeviceWin32* device, const c CIrrDeviceWin32::CCursorControl::~CCursorControl() { - for ( u32 i=0; i < Cursors.size(); ++i ) - { - for ( u32 f=0; f < Cursors[i].Frames.size(); ++f ) - { + for (u32 i = 0; i < Cursors.size(); ++i) { + for (u32 f = 0; f < Cursors[i].Frames.size(); ++f) { DestroyCursor(Cursors[i].Frames[f].IconHW); } } } - void CIrrDeviceWin32::CCursorControl::initCursors() { - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_ARROW)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_CROSS)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_HAND)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_HELP)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_IBEAM)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_NO)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_WAIT)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_SIZEALL)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_SIZENESW)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_SIZENWSE)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_SIZENS)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_SIZEWE)) ); - Cursors.push_back( CursorW32(LoadCursor(NULL, IDC_UPARROW)) ); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_ARROW))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_CROSS))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_HAND))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_HELP))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_IBEAM))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_NO))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_WAIT))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_SIZEALL))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_SIZENESW))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_SIZENWSE))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_SIZENS))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_SIZEWE))); + Cursors.push_back(CursorW32(LoadCursor(NULL, IDC_UPARROW))); } - void CIrrDeviceWin32::CCursorControl::update() { - if ( !Cursors[ActiveIcon].Frames.empty() && Cursors[ActiveIcon].FrameTime ) - { + if (!Cursors[ActiveIcon].Frames.empty() && Cursors[ActiveIcon].FrameTime) { // update animated cursors. This could also be done by X11 in case someone wants to figure that out (this way was just easier to implement) u32 now = Device->getTimer()->getRealTime(); u32 frame = ((now - ActiveIconStartTime) / Cursors[ActiveIcon].FrameTime) % Cursors[ActiveIcon].Frames.size(); - SetCursor( Cursors[ActiveIcon].Frames[frame].IconHW ); + SetCursor(Cursors[ActiveIcon].Frames[frame].IconHW); } } //! Sets the active cursor icon void CIrrDeviceWin32::CCursorControl::setActiveIcon(gui::ECURSOR_ICON iconId) { - if ( iconId >= (s32)Cursors.size() ) + if (iconId >= (s32)Cursors.size()) return; ActiveIcon = iconId; ActiveIconStartTime = Device->getTimer()->getRealTime(); - if ( Cursors[ActiveIcon].Frames.size() ) - SetCursor( Cursors[ActiveIcon].Frames[0].IconHW ); + if (Cursors[ActiveIcon].Frames.size()) + SetCursor(Cursors[ActiveIcon].Frames[0].IconHW); } - //! Add a custom sprite as cursor icon. -gui::ECURSOR_ICON CIrrDeviceWin32::CCursorControl::addIcon(const gui::SCursorSprite& icon) +gui::ECURSOR_ICON CIrrDeviceWin32::CCursorControl::addIcon(const gui::SCursorSprite &icon) { - if ( icon.SpriteId >= 0 ) - { + if (icon.SpriteId >= 0) { CursorW32 cW32; cW32.FrameTime = icon.SpriteBank->getSprites()[icon.SpriteId].frameTime; - for ( u32 i=0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i ) - { + for (u32 i = 0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i) { irr::u32 texId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].textureNumber; irr::u32 rectId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].rectNumber; irr::core::rect rectIcon = icon.SpriteBank->getPositions()[rectId]; HCURSOR hc = Device->TextureToCursor(HWnd, icon.SpriteBank->getTexture(texId), rectIcon, icon.HotSpot); - cW32.Frames.push_back( CursorFrameW32(hc) ); + cW32.Frames.push_back(CursorFrameW32(hc)); } - Cursors.push_back( cW32 ); + Cursors.push_back(cW32); return (gui::ECURSOR_ICON)(Cursors.size() - 1); } return gui::ECI_NORMAL; } - //! replace the given cursor icon. -void CIrrDeviceWin32::CCursorControl::changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite& icon) +void CIrrDeviceWin32::CCursorControl::changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite &icon) { - if ( iconId >= (s32)Cursors.size() ) + if (iconId >= (s32)Cursors.size()) return; - for ( u32 i=0; i < Cursors[iconId].Frames.size(); ++i ) + for (u32 i = 0; i < Cursors[iconId].Frames.size(); ++i) DestroyCursor(Cursors[iconId].Frames[i].IconHW); - if ( icon.SpriteId >= 0 ) - { + if (icon.SpriteId >= 0) { CursorW32 cW32; cW32.FrameTime = icon.SpriteBank->getSprites()[icon.SpriteId].frameTime; - for ( u32 i=0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i ) - { + for (u32 i = 0; i < icon.SpriteBank->getSprites()[icon.SpriteId].Frames.size(); ++i) { irr::u32 texId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].textureNumber; irr::u32 rectId = icon.SpriteBank->getSprites()[icon.SpriteId].Frames[i].rectNumber; irr::core::rect rectIcon = icon.SpriteBank->getPositions()[rectId]; HCURSOR hc = Device->TextureToCursor(HWnd, icon.SpriteBank->getTexture(texId), rectIcon, icon.HotSpot); - cW32.Frames.push_back( CursorFrameW32(hc) ); + cW32.Frames.push_back(CursorFrameW32(hc)); } Cursors[iconId] = cW32; } } - //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. core::dimension2di CIrrDeviceWin32::CCursorControl::getSupportedIconSize() const { @@ -1591,8 +1472,6 @@ core::dimension2di CIrrDeviceWin32::CCursorControl::getSupportedIconSize() const return result; } - - } // end namespace -#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_ +#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_ diff --git a/source/Irrlicht/CIrrDeviceWin32.h b/source/Irrlicht/CIrrDeviceWin32.h index f8c2861d..3ac36fd2 100644 --- a/source/Irrlicht/CIrrDeviceWin32.h +++ b/source/Irrlicht/CIrrDeviceWin32.h @@ -4,8 +4,8 @@ #pragma once -#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ - +#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ + #include "CIrrDeviceStub.h" #include "IrrlichtDevice.h" @@ -20,410 +20,386 @@ namespace irr { - struct SJoystickWin32Control; +struct SJoystickWin32Control; - class CIrrDeviceWin32 : public CIrrDeviceStub - { +class CIrrDeviceWin32 : public CIrrDeviceStub +{ friend struct SJoystickWin32Control; + +public: + //! constructor + CIrrDeviceWin32(const SIrrlichtCreationParameters ¶ms); + + //! destructor + virtual ~CIrrDeviceWin32(); + + //! runs the device. Returns false if device wants to be deleted + bool run() override; + + //! Cause the device to temporarily pause execution and let other processes to run + // This should bring down processor usage without major performance loss for Irrlicht + void yield() override; + + //! Pause execution and let other processes to run for a specified amount of time. + void sleep(u32 timeMs, bool pauseTimer) override; + + //! sets the caption of the window + void setWindowCaption(const wchar_t *text) override; + + //! Sets the window icon. + bool setWindowIcon(const video::IImage *img) override; + + //! returns if window is active. if not, nothing need to be drawn + bool isWindowActive() const override; + + //! returns if window has focus + bool isWindowFocused() const override; + + //! returns if window is minimized + bool isWindowMinimized() const override; + + //! returns last state from maximizeWindow() and restoreWindow() + bool isWindowMaximized() const override; + + //! notifies the device that it should close itself + void closeDevice() override; + + //! Notifies the device, that it has been resized + /** Must be publis as it is called from free function (event handler) */ + void OnResized(); + + //! Sets if the window should be resizable in windowed mode. + void setResizable(bool resize = false) override; + + //! Resize the render window. + void setWindowSize(const irr::core::dimension2d &size) override; + + //! Minimizes the window. + void minimizeWindow() override; + + //! Maximizes the window. + void maximizeWindow() override; + + //! Restores the window size. + void restoreWindow() override; + + //! Get the position of the window on screen + core::position2di getWindowPosition() override; + + //! Activate any joysticks, and generate events for them. + bool activateJoysticks(core::array &joystickInfo) override; + + //! Remove all messages pending in the system message loop + void clearSystemMessages() override; + + //! Get the device type + E_DEVICE_TYPE getType() const override + { + return EIDT_WIN32; + } + + //! Get the display density in dots per inch. + float getDisplayDensity() const override; + + //! Compares to the last call of this function to return double and triple clicks. + //! \return Returns only 1,2 or 3. A 4th click will start with 1 again. + u32 checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent) override + { + // we just have to make it public + return CIrrDeviceStub::checkSuccessiveClicks(mouseX, mouseY, inputEvent); + } + + //! Switch to fullscreen + bool switchToFullScreen(); + + // convert an Irrlicht texture to a windows cursor + HCURSOR TextureToCursor(HWND hwnd, irr::video::ITexture *tex, const core::rect &sourceRect, const core::position2d &hotspot); + + //! Implementation of the win32 cursor control + class CCursorControl : public gui::ICursorControl + { public: + CCursorControl(CIrrDeviceWin32 *device, const core::dimension2d &wsize, HWND hwnd, bool fullscreen); + ~CCursorControl(); - //! constructor - CIrrDeviceWin32(const SIrrlichtCreationParameters& params); - - //! destructor - virtual ~CIrrDeviceWin32(); - - //! runs the device. Returns false if device wants to be deleted - bool run() override; - - //! Cause the device to temporarily pause execution and let other processes to run - // This should bring down processor usage without major performance loss for Irrlicht - void yield() override; - - //! Pause execution and let other processes to run for a specified amount of time. - void sleep(u32 timeMs, bool pauseTimer) override; - - //! sets the caption of the window - void setWindowCaption(const wchar_t* text) override; - - //! Sets the window icon. - bool setWindowIcon(const video::IImage *img) override; - - //! returns if window is active. if not, nothing need to be drawn - bool isWindowActive() const override; - - //! returns if window has focus - bool isWindowFocused() const override; - - //! returns if window is minimized - bool isWindowMinimized() const override; - - //! returns last state from maximizeWindow() and restoreWindow() - bool isWindowMaximized() const override; - - //! notifies the device that it should close itself - void closeDevice() override; - - //! Notifies the device, that it has been resized - /** Must be publis as it is called from free function (event handler) */ - void OnResized(); - - //! Sets if the window should be resizable in windowed mode. - void setResizable(bool resize=false) override; - - //! Resize the render window. - void setWindowSize(const irr::core::dimension2d& size) override; - - //! Minimizes the window. - void minimizeWindow() override; - - //! Maximizes the window. - void maximizeWindow() override; - - //! Restores the window size. - void restoreWindow() override; - - //! Get the position of the window on screen - core::position2di getWindowPosition() override; - - //! Activate any joysticks, and generate events for them. - bool activateJoysticks(core::array & joystickInfo) override; - - //! Remove all messages pending in the system message loop - void clearSystemMessages() override; - - //! Get the device type - E_DEVICE_TYPE getType() const override + //! Changes the visible state of the mouse cursor. + void setVisible(bool visible) override { - return EIDT_WIN32; - } - - //! Get the display density in dots per inch. - float getDisplayDensity() const override; - - //! Compares to the last call of this function to return double and triple clicks. - //! \return Returns only 1,2 or 3. A 4th click will start with 1 again. - u32 checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent ) override - { - // we just have to make it public - return CIrrDeviceStub::checkSuccessiveClicks(mouseX, mouseY, inputEvent ); - } - - //! Switch to fullscreen - bool switchToFullScreen(); - - // convert an Irrlicht texture to a windows cursor - HCURSOR TextureToCursor(HWND hwnd, irr::video::ITexture * tex, const core::rect& sourceRect, const core::position2d &hotspot); - - //! Implementation of the win32 cursor control - class CCursorControl : public gui::ICursorControl - { - public: - - CCursorControl(CIrrDeviceWin32* device, const core::dimension2d& wsize, HWND hwnd, bool fullscreen); - ~CCursorControl(); - - //! Changes the visible state of the mouse cursor. - void setVisible(bool visible) override - { - CURSORINFO info; - info.cbSize = sizeof(CURSORINFO); - BOOL gotCursorInfo = GetCursorInfo(&info); - while ( gotCursorInfo ) - { + CURSORINFO info; + info.cbSize = sizeof(CURSORINFO); + BOOL gotCursorInfo = GetCursorInfo(&info); + while (gotCursorInfo) { #ifdef CURSOR_SUPPRESSED - // Since Windows 8 the cursor can be suppressed by a touch interface - if (visible && info.flags == CURSOR_SUPPRESSED) - { - break; - } + // Since Windows 8 the cursor can be suppressed by a touch interface + if (visible && info.flags == CURSOR_SUPPRESSED) { + break; + } #endif - if ( (visible && info.flags == CURSOR_SHOWING) || // visible - (!visible && info.flags == 0 ) ) // hidden - { - break; - } - // this only increases an internal - // display counter in windows, so it - // might have to be called some more - const int showResult = ShowCursor(visible); - // if result has correct sign we can - // stop here as well - if (( !visible && showResult < 0 ) || + if ((visible && info.flags == CURSOR_SHOWING) || // visible + (!visible && info.flags == 0)) // hidden + { + break; + } + // this only increases an internal + // display counter in windows, so it + // might have to be called some more + const int showResult = ShowCursor(visible); + // if result has correct sign we can + // stop here as well + if ((!visible && showResult < 0) || (visible && showResult >= 0)) - break; - // yes, it really must be set each time - info.cbSize = sizeof(CURSORINFO); - gotCursorInfo = GetCursorInfo(&info); + break; + // yes, it really must be set each time + info.cbSize = sizeof(CURSORINFO); + gotCursorInfo = GetCursorInfo(&info); #ifdef CURSOR_SUPPRESSED - // Not sure if a cursor which we tried to hide still can be suppressed. - // I have no touch-display for testing this and MSDN doesn't describe it. - // But adding this check shouldn't hurt and might prevent an endless loop. - if (!visible && info.flags == CURSOR_SUPPRESSED) - { - break; - } + // Not sure if a cursor which we tried to hide still can be suppressed. + // I have no touch-display for testing this and MSDN doesn't describe it. + // But adding this check shouldn't hurt and might prevent an endless loop. + if (!visible && info.flags == CURSOR_SUPPRESSED) { + break; + } #endif - } - IsVisible = visible; + } + IsVisible = visible; + } + + //! Returns if the cursor is currently visible. + bool isVisible() const override + { + return IsVisible; + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(f32 x, f32 y) override + { + if (!UseReferenceRect) + setPosition(core::round32(x * WindowSize.Width), core::round32(y * WindowSize.Height)); + else + setPosition(core::round32(x * ReferenceRect.getWidth()), core::round32(y * ReferenceRect.getHeight())); + } + + //! Sets the new position of the cursor. + void setPosition(const core::position2d &pos) override + { + setPosition(pos.X, pos.Y); + } + + //! Sets the new position of the cursor. + void setPosition(s32 x, s32 y) override + { + if (UseReferenceRect) { + SetCursorPos(ReferenceRect.UpperLeftCorner.X + x, + ReferenceRect.UpperLeftCorner.Y + y); + } else { + RECT rect; + if (GetWindowRect(HWnd, &rect)) + SetCursorPos(x + rect.left + BorderX, y + rect.top + BorderY); } - //! Returns if the cursor is currently visible. - bool isVisible() const override - { - return IsVisible; - } + CursorPos.X = x; + CursorPos.Y = y; + } - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } + //! Returns the current position of the mouse cursor. + const core::position2d &getPosition(bool updateCursor) override + { + if (updateCursor) + updateInternalCursorPosition(); + return CursorPos; + } - //! Sets the new position of the cursor. - void setPosition(f32 x, f32 y) override - { - if (!UseReferenceRect) - setPosition(core::round32(x*WindowSize.Width), core::round32(y*WindowSize.Height)); - else - setPosition(core::round32(x*ReferenceRect.getWidth()), core::round32(y*ReferenceRect.getHeight())); - } + //! Returns the current position of the mouse cursor. + core::position2d getRelativePosition(bool updateCursor) override + { + if (updateCursor) + updateInternalCursorPosition(); - //! Sets the new position of the cursor. - void setPosition(const core::position2d &pos) override - { - setPosition(pos.X, pos.Y); - } - - //! Sets the new position of the cursor. - void setPosition(s32 x, s32 y) override - { - if (UseReferenceRect) - { - SetCursorPos(ReferenceRect.UpperLeftCorner.X + x, - ReferenceRect.UpperLeftCorner.Y + y); - } - else - { - RECT rect; - if (GetWindowRect(HWnd, &rect)) - SetCursorPos(x + rect.left + BorderX, y + rect.top + BorderY); - } - - CursorPos.X = x; - CursorPos.Y = y; - } - - //! Returns the current position of the mouse cursor. - const core::position2d& getPosition(bool updateCursor) override - { - if ( updateCursor ) - updateInternalCursorPosition(); - return CursorPos; - } - - //! Returns the current position of the mouse cursor. - core::position2d getRelativePosition(bool updateCursor) override - { - if ( updateCursor ) - updateInternalCursorPosition(); - - if (!UseReferenceRect) - { - return core::position2d(CursorPos.X * InvWindowSize.Width, + if (!UseReferenceRect) { + return core::position2d(CursorPos.X * InvWindowSize.Width, CursorPos.Y * InvWindowSize.Height); - } - - return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), - CursorPos.Y / (f32)ReferenceRect.getHeight()); } - //! Sets an absolute reference rect for calculating the cursor position. - void setReferenceRect(core::rect* rect=0) override - { - if (rect) - { - ReferenceRect = *rect; - UseReferenceRect = true; + return core::position2d(CursorPos.X / (f32)ReferenceRect.getWidth(), + CursorPos.Y / (f32)ReferenceRect.getHeight()); + } - // prevent division through zero and uneven sizes + //! Sets an absolute reference rect for calculating the cursor position. + void setReferenceRect(core::rect *rect = 0) override + { + if (rect) { + ReferenceRect = *rect; + UseReferenceRect = true; - if (!ReferenceRect.getHeight() || ReferenceRect.getHeight()%2) - ReferenceRect.LowerRightCorner.Y += 1; + // prevent division through zero and uneven sizes - if (!ReferenceRect.getWidth() || ReferenceRect.getWidth()%2) - ReferenceRect.LowerRightCorner.X += 1; + if (!ReferenceRect.getHeight() || ReferenceRect.getHeight() % 2) + ReferenceRect.LowerRightCorner.Y += 1; + + if (!ReferenceRect.getWidth() || ReferenceRect.getWidth() % 2) + ReferenceRect.LowerRightCorner.X += 1; + } else + UseReferenceRect = false; + } + + /** Used to notify the cursor that the window was resized. */ + void OnResize(const core::dimension2d &size) + { + WindowSize = size; + if (size.Width != 0) + InvWindowSize.Width = 1.0f / size.Width; + else + InvWindowSize.Width = 0.f; + + if (size.Height != 0) + InvWindowSize.Height = 1.0f / size.Height; + else + InvWindowSize.Height = 0.f; + } + + /** Used to notify the cursor that the window resizable settings changed. */ + void updateBorderSize(bool fullscreen, bool resizable) + { + if (!fullscreen) { + s32 paddingBorder = 0; +#ifdef SM_CXPADDEDBORDER + paddingBorder = GetSystemMetrics(SM_CXPADDEDBORDER); +#endif + + if (resizable) { + BorderX = GetSystemMetrics(SM_CXSIZEFRAME) + paddingBorder; + BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYSIZEFRAME) + paddingBorder; + } else { + BorderX = GetSystemMetrics(SM_CXDLGFRAME) + paddingBorder; + BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYDLGFRAME) + paddingBorder; } - else - UseReferenceRect = false; + } else { + BorderX = BorderY = 0; } + } - /** Used to notify the cursor that the window was resized. */ - void OnResize(const core::dimension2d& size) - { - WindowSize = size; - if (size.Width!=0) - InvWindowSize.Width = 1.0f / size.Width; - else - InvWindowSize.Width = 0.f; + //! Sets the active cursor icon + void setActiveIcon(gui::ECURSOR_ICON iconId) override; - if (size.Height!=0) - InvWindowSize.Height = 1.0f / size.Height; - else - InvWindowSize.Height = 0.f; - } + //! Gets the currently active icon + gui::ECURSOR_ICON getActiveIcon() const override + { + return ActiveIcon; + } - /** Used to notify the cursor that the window resizable settings changed. */ - void updateBorderSize(bool fullscreen, bool resizable) - { - if (!fullscreen) - { - s32 paddingBorder = 0; - #ifdef SM_CXPADDEDBORDER - paddingBorder = GetSystemMetrics(SM_CXPADDEDBORDER); - #endif + //! Add a custom sprite as cursor icon. + gui::ECURSOR_ICON addIcon(const gui::SCursorSprite &icon) override; - if (resizable) - { - BorderX = GetSystemMetrics(SM_CXSIZEFRAME) + paddingBorder; - BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYSIZEFRAME) + paddingBorder; - } - else - { - BorderX = GetSystemMetrics(SM_CXDLGFRAME) + paddingBorder; - BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYDLGFRAME) + paddingBorder; - } - } - else - { - BorderX = BorderY = 0; - } - } + //! replace the given cursor icon. + void changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite &icon) override; + //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. + core::dimension2di getSupportedIconSize() const override; - //! Sets the active cursor icon - void setActiveIcon(gui::ECURSOR_ICON iconId) override; - - //! Gets the currently active icon - gui::ECURSOR_ICON getActiveIcon() const override - { - return ActiveIcon; - } - - //! Add a custom sprite as cursor icon. - gui::ECURSOR_ICON addIcon(const gui::SCursorSprite& icon) override; - - //! replace the given cursor icon. - void changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite& icon) override; - - //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. - core::dimension2di getSupportedIconSize() const override; - - void update(); - - private: - - //! Updates the internal cursor position - void updateInternalCursorPosition() - { - POINT p; - if (!GetCursorPos(&p)) - { - DWORD xy = GetMessagePos(); - p.x = GET_X_LPARAM(xy); - p.y = GET_Y_LPARAM(xy); - } - - if (UseReferenceRect) - { - CursorPos.X = p.x - ReferenceRect.UpperLeftCorner.X; - CursorPos.Y = p.y - ReferenceRect.UpperLeftCorner.Y; - } - else - { - RECT rect; - if (GetWindowRect(HWnd, &rect)) - { - CursorPos.X = p.x-rect.left-BorderX; - CursorPos.Y = p.y-rect.top-BorderY; - } - else - { - // window seems not to be existent, so set cursor to - // a negative value - CursorPos.X = -1; - CursorPos.Y = -1; - } - } - } - - CIrrDeviceWin32* Device; - core::position2d CursorPos; - core::dimension2d WindowSize; - core::dimension2d InvWindowSize; - HWND HWnd; - - s32 BorderX, BorderY; - core::rect ReferenceRect; - bool UseReferenceRect; - bool IsVisible; - - - struct CursorFrameW32 - { - CursorFrameW32() : IconHW(0) {} - CursorFrameW32(HCURSOR icon) : IconHW(icon) {} - - HCURSOR IconHW; // hardware cursor - }; - - struct CursorW32 - { - CursorW32() {} - explicit CursorW32(HCURSOR iconHw, u32 frameTime=0) : FrameTime(frameTime) - { - Frames.push_back( CursorFrameW32(iconHw) ); - } - core::array Frames; - u32 FrameTime; - }; - - core::array Cursors; - gui::ECURSOR_ICON ActiveIcon; - u32 ActiveIconStartTime; - - void initCursors(); - }; - - //! returns the win32 cursor control - CCursorControl* getWin32CursorControl(); + void update(); private: + //! Updates the internal cursor position + void updateInternalCursorPosition() + { + POINT p; + if (!GetCursorPos(&p)) { + DWORD xy = GetMessagePos(); + p.x = GET_X_LPARAM(xy); + p.y = GET_Y_LPARAM(xy); + } - //! create the driver - void createDriver(); - - //! Process system events - void handleSystemMessages(); - - void getWindowsVersion(core::stringc& version); - - void resizeIfNecessary(); - - DWORD getWindowStyle(bool fullscreen, bool resizable) const; + if (UseReferenceRect) { + CursorPos.X = p.x - ReferenceRect.UpperLeftCorner.X; + CursorPos.Y = p.y - ReferenceRect.UpperLeftCorner.Y; + } else { + RECT rect; + if (GetWindowRect(HWnd, &rect)) { + CursorPos.X = p.x - rect.left - BorderX; + CursorPos.Y = p.y - rect.top - BorderY; + } else { + // window seems not to be existent, so set cursor to + // a negative value + CursorPos.X = -1; + CursorPos.Y = -1; + } + } + } + CIrrDeviceWin32 *Device; + core::position2d CursorPos; + core::dimension2d WindowSize; + core::dimension2d InvWindowSize; HWND HWnd; - bool Resized; - bool ExternalWindow; - CCursorControl* Win32CursorControl; + s32 BorderX, BorderY; + core::rect ReferenceRect; + bool UseReferenceRect; + bool IsVisible; - SJoystickWin32Control* JoyControl; + struct CursorFrameW32 + { + CursorFrameW32() : + IconHW(0) {} + CursorFrameW32(HCURSOR icon) : + IconHW(icon) {} - bool WindowMaximized; + HCURSOR IconHW; // hardware cursor + }; + + struct CursorW32 + { + CursorW32() {} + explicit CursorW32(HCURSOR iconHw, u32 frameTime = 0) : + FrameTime(frameTime) + { + Frames.push_back(CursorFrameW32(iconHw)); + } + core::array Frames; + u32 FrameTime; + }; + + core::array Cursors; + gui::ECURSOR_ICON ActiveIcon; + u32 ActiveIconStartTime; + + void initCursors(); }; + //! returns the win32 cursor control + CCursorControl *getWin32CursorControl(); + +private: + //! create the driver + void createDriver(); + + //! Process system events + void handleSystemMessages(); + + void getWindowsVersion(core::stringc &version); + + void resizeIfNecessary(); + + DWORD getWindowStyle(bool fullscreen, bool resizable) const; + + HWND HWnd; + + bool Resized; + bool ExternalWindow; + CCursorControl *Win32CursorControl; + + SJoystickWin32Control *JoyControl; + + bool WindowMaximized; +}; + } // end namespace irr - -#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_ + +#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_ diff --git a/source/Irrlicht/CLimitReadFile.cpp b/source/Irrlicht/CLimitReadFile.cpp index b5f3f627..de9bf9ec 100644 --- a/source/Irrlicht/CLimitReadFile.cpp +++ b/source/Irrlicht/CLimitReadFile.cpp @@ -11,34 +11,31 @@ namespace irr namespace io { - -CLimitReadFile::CLimitReadFile(IReadFile* alreadyOpenedFile, long pos, - long areaSize, const io::path& name) - : Filename(name), AreaStart(0), AreaEnd(0), Pos(0), - File(alreadyOpenedFile) +CLimitReadFile::CLimitReadFile(IReadFile *alreadyOpenedFile, long pos, + long areaSize, const io::path &name) : + Filename(name), + AreaStart(0), AreaEnd(0), Pos(0), + File(alreadyOpenedFile) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CLimitReadFile"); - #endif +#endif - if (File) - { + if (File) { File->grab(); AreaStart = pos; AreaEnd = AreaStart + areaSize; } } - CLimitReadFile::~CLimitReadFile() { if (File) File->drop(); } - //! returns how much was read -size_t CLimitReadFile::read(void* buffer, size_t sizeToRead) +size_t CLimitReadFile::read(void *buffer, size_t sizeToRead) { if (0 == File) return 0; @@ -65,23 +62,19 @@ size_t CLimitReadFile::read(void* buffer, size_t sizeToRead) #endif } - //! changes position in file, returns true if successful bool CLimitReadFile::seek(long finalPos, bool relativeMovement) { #if 1 - Pos = core::s32_clamp(finalPos + (relativeMovement ? Pos : 0 ), 0, AreaEnd - AreaStart); + Pos = core::s32_clamp(finalPos + (relativeMovement ? Pos : 0), 0, AreaEnd - AreaStart); return true; #else const long pos = File->getPos(); - if (relativeMovement) - { + if (relativeMovement) { if (pos + finalPos > AreaEnd) finalPos = AreaEnd - pos; - } - else - { + } else { finalPos += AreaStart; if (finalPos > AreaEnd) return false; @@ -91,14 +84,12 @@ bool CLimitReadFile::seek(long finalPos, bool relativeMovement) #endif } - //! returns size of file long CLimitReadFile::getSize() const { return AreaEnd - AreaStart; } - //! returns where in the file we are. long CLimitReadFile::getPos() const { @@ -109,20 +100,16 @@ long CLimitReadFile::getPos() const #endif } - //! returns name of file -const io::path& CLimitReadFile::getFileName() const +const io::path &CLimitReadFile::getFileName() const { return Filename; } - -IReadFile* createLimitReadFile(const io::path& fileName, IReadFile* alreadyOpenedFile, long pos, long areaSize) +IReadFile *createLimitReadFile(const io::path &fileName, IReadFile *alreadyOpenedFile, long pos, long areaSize) { return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName); } - } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CLimitReadFile.h b/source/Irrlicht/CLimitReadFile.h index aae4647f..1594135e 100644 --- a/source/Irrlicht/CLimitReadFile.h +++ b/source/Irrlicht/CLimitReadFile.h @@ -9,56 +9,54 @@ namespace irr { - class CUnicodeConverter; +class CUnicodeConverter; namespace io { - /*! this is a read file, which is limited to some boundaries, - so that it may only start from a certain file position - and may only read until a certain file position. - This can be useful, for example for reading uncompressed files - in an archive (zip, tar). - !*/ - class CLimitReadFile : public IReadFile +/*! this is a read file, which is limited to some boundaries, + so that it may only start from a certain file position + and may only read until a certain file position. + This can be useful, for example for reading uncompressed files + in an archive (zip, tar). +!*/ +class CLimitReadFile : public IReadFile +{ +public: + CLimitReadFile(IReadFile *alreadyOpenedFile, long pos, long areaSize, const io::path &name); + + virtual ~CLimitReadFile(); + + //! returns how much was read + size_t read(void *buffer, size_t sizeToRead) override; + + //! changes position in file, returns true if successful + //! if relativeMovement==true, the pos is changed relative to current pos, + //! otherwise from begin of file + bool seek(long finalPos, bool relativeMovement = false) override; + + //! returns size of file + long getSize() const override; + + //! returns where in the file we are. + long getPos() const override; + + //! returns name of file + const io::path &getFileName() const override; + + //! Get the type of the class implementing this interface + EREAD_FILE_TYPE getType() const override { - public: + return ERFT_LIMIT_READ_FILE; + } - CLimitReadFile(IReadFile* alreadyOpenedFile, long pos, long areaSize, const io::path& name); - - virtual ~CLimitReadFile(); - - //! returns how much was read - size_t read(void* buffer, size_t sizeToRead) override; - - //! changes position in file, returns true if successful - //! if relativeMovement==true, the pos is changed relative to current pos, - //! otherwise from begin of file - bool seek(long finalPos, bool relativeMovement = false) override; - - //! returns size of file - long getSize() const override; - - //! returns where in the file we are. - long getPos() const override; - - //! returns name of file - const io::path& getFileName() const override; - - //! Get the type of the class implementing this interface - EREAD_FILE_TYPE getType() const override - { - return ERFT_LIMIT_READ_FILE; - } - - private: - - io::path Filename; - long AreaStart; - long AreaEnd; - long Pos; - IReadFile* File; - }; +private: + io::path Filename; + long AreaStart; + long AreaEnd; + long Pos; + IReadFile *File; +}; } // end namespace io } // end namespace irr diff --git a/source/Irrlicht/CLogger.cpp b/source/Irrlicht/CLogger.cpp index 5e3400e3..70d06b36 100644 --- a/source/Irrlicht/CLogger.cpp +++ b/source/Irrlicht/CLogger.cpp @@ -7,64 +7,60 @@ namespace irr { - CLogger::CLogger(IEventReceiver* r) - : LogLevel(ELL_INFORMATION), Receiver(r) - { - #ifdef _DEBUG - setDebugName("CLogger"); - #endif - } +CLogger::CLogger(IEventReceiver *r) : + LogLevel(ELL_INFORMATION), Receiver(r) +{ +#ifdef _DEBUG + setDebugName("CLogger"); +#endif +} - //! Returns the current set log level. - ELOG_LEVEL CLogger::getLogLevel() const - { - return LogLevel; - } +//! Returns the current set log level. +ELOG_LEVEL CLogger::getLogLevel() const +{ + return LogLevel; +} - //! Sets a new log level. - void CLogger::setLogLevel(ELOG_LEVEL ll) - { - LogLevel = ll; - } +//! Sets a new log level. +void CLogger::setLogLevel(ELOG_LEVEL ll) +{ + LogLevel = ll; +} - //! Prints out a text into the log - void CLogger::log(const c8* text, ELOG_LEVEL ll) - { - if (ll < LogLevel) +//! Prints out a text into the log +void CLogger::log(const c8 *text, ELOG_LEVEL ll) +{ + if (ll < LogLevel) + return; + + if (Receiver) { + SEvent event; + event.EventType = EET_LOG_TEXT_EVENT; + event.LogEvent.Text = text; + event.LogEvent.Level = ll; + if (Receiver->OnEvent(event)) return; - - if (Receiver) - { - SEvent event; - event.EventType = EET_LOG_TEXT_EVENT; - event.LogEvent.Text = text; - event.LogEvent.Level = ll; - if (Receiver->OnEvent(event)) - return; - } - - os::Printer::print(text); } + os::Printer::print(text); +} - //! Prints out a text into the log - void CLogger::log(const c8* text, const c8* hint, ELOG_LEVEL ll) - { - if (ll < LogLevel) - return; +//! Prints out a text into the log +void CLogger::log(const c8 *text, const c8 *hint, ELOG_LEVEL ll) +{ + if (ll < LogLevel) + return; - core::stringc s = text; - s += ": "; - s += hint; - log (s.c_str(), ll); - } - - //! Sets a new event receiver - void CLogger::setReceiver(IEventReceiver* r) - { - Receiver = r; - } + core::stringc s = text; + s += ": "; + s += hint; + log(s.c_str(), ll); +} +//! Sets a new event receiver +void CLogger::setReceiver(IEventReceiver *r) +{ + Receiver = r; +} } // end namespace irr - diff --git a/source/Irrlicht/CLogger.h b/source/Irrlicht/CLogger.h index c1f02c6f..e9cfae8f 100644 --- a/source/Irrlicht/CLogger.h +++ b/source/Irrlicht/CLogger.h @@ -16,8 +16,7 @@ namespace irr class CLogger : public ILogger { public: - - CLogger(IEventReceiver* r); + CLogger(IEventReceiver *r); //! Returns the current set log level. ELOG_LEVEL getLogLevel() const override; @@ -26,18 +25,17 @@ public: void setLogLevel(ELOG_LEVEL ll) override; //! Prints out a text into the log - void log(const c8* text, ELOG_LEVEL ll=ELL_INFORMATION) override; + void log(const c8 *text, ELOG_LEVEL ll = ELL_INFORMATION) override; //! Prints out a text into the log - void log(const c8* text, const c8* hint, ELOG_LEVEL ll=ELL_INFORMATION) override; + void log(const c8 *text, const c8 *hint, ELOG_LEVEL ll = ELL_INFORMATION) override; //! Sets a new event receiver - void setReceiver(IEventReceiver* r); + void setReceiver(IEventReceiver *r); private: - ELOG_LEVEL LogLevel; - IEventReceiver* Receiver; + IEventReceiver *Receiver; }; } // end namespace diff --git a/source/Irrlicht/CMemoryFile.cpp b/source/Irrlicht/CMemoryFile.cpp index 27509af5..6d7906b9 100644 --- a/source/Irrlicht/CMemoryFile.cpp +++ b/source/Irrlicht/CMemoryFile.cpp @@ -10,25 +10,22 @@ namespace irr namespace io { - -CMemoryReadFile::CMemoryReadFile(const void* memory, long len, const io::path& fileName, bool d) -: Buffer(memory), Len(len), Pos(0), Filename(fileName), deleteMemoryWhenDropped(d) +CMemoryReadFile::CMemoryReadFile(const void *memory, long len, const io::path &fileName, bool d) : + Buffer(memory), Len(len), Pos(0), Filename(fileName), deleteMemoryWhenDropped(d) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CMemoryReadFile"); - #endif +#endif } - CMemoryReadFile::~CMemoryReadFile() { if (deleteMemoryWhenDropped) - delete [] (c8*)Buffer; + delete[] (c8 *)Buffer; } - //! returns how much was read -size_t CMemoryReadFile::read(void* buffer, size_t sizeToRead) +size_t CMemoryReadFile::read(void *buffer, size_t sizeToRead) { long amount = static_cast(sizeToRead); if (Pos + amount > Len) @@ -37,7 +34,7 @@ size_t CMemoryReadFile::read(void* buffer, size_t sizeToRead) if (amount <= 0) return 0; - c8* p = (c8*)Buffer; + c8 *p = (c8 *)Buffer; memcpy(buffer, p + Pos, amount); Pos += amount; @@ -50,15 +47,12 @@ size_t CMemoryReadFile::read(void* buffer, size_t sizeToRead) //! otherwise from begin of file bool CMemoryReadFile::seek(long finalPos, bool relativeMovement) { - if (relativeMovement) - { + if (relativeMovement) { if (Pos + finalPos < 0 || Pos + finalPos > Len) return false; Pos += finalPos; - } - else - { + } else { if (finalPos < 0 || finalPos > Len) return false; @@ -68,46 +62,40 @@ bool CMemoryReadFile::seek(long finalPos, bool relativeMovement) return true; } - //! returns size of file long CMemoryReadFile::getSize() const { return Len; } - //! returns where in the file we are. long CMemoryReadFile::getPos() const { return Pos; } - //! returns name of file -const io::path& CMemoryReadFile::getFileName() const +const io::path &CMemoryReadFile::getFileName() const { return Filename; } - -CMemoryWriteFile::CMemoryWriteFile(void* memory, long len, const io::path& fileName, bool d) -: Buffer(memory), Len(len), Pos(0), Filename(fileName), deleteMemoryWhenDropped(d) +CMemoryWriteFile::CMemoryWriteFile(void *memory, long len, const io::path &fileName, bool d) : + Buffer(memory), Len(len), Pos(0), Filename(fileName), deleteMemoryWhenDropped(d) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CMemoryWriteFile"); - #endif +#endif } - CMemoryWriteFile::~CMemoryWriteFile() { if (deleteMemoryWhenDropped) - delete [] (c8*)Buffer; + delete[] (c8 *)Buffer; } - //! returns how much was written -size_t CMemoryWriteFile::write(const void* buffer, size_t sizeToWrite) +size_t CMemoryWriteFile::write(const void *buffer, size_t sizeToWrite) { long amount = (long)sizeToWrite; if (Pos + amount > Len) @@ -116,7 +104,7 @@ size_t CMemoryWriteFile::write(const void* buffer, size_t sizeToWrite) if (amount <= 0) return 0; - c8* p = (c8*)Buffer; + c8 *p = (c8 *)Buffer; memcpy(p + Pos, buffer, amount); Pos += amount; @@ -124,22 +112,17 @@ size_t CMemoryWriteFile::write(const void* buffer, size_t sizeToWrite) return (size_t)amount; } - - //! changes position in file, returns true if successful //! if relativeMovement==true, the pos is changed relative to current pos, //! otherwise from begin of file bool CMemoryWriteFile::seek(long finalPos, bool relativeMovement) { - if (relativeMovement) - { + if (relativeMovement) { if (Pos + finalPos < 0 || Pos + finalPos > Len) return false; Pos += finalPos; - } - else - { + } else { if (finalPos < 0 || finalPos > Len) return false; @@ -149,16 +132,14 @@ bool CMemoryWriteFile::seek(long finalPos, bool relativeMovement) return true; } - //! returns where in the file we are. long CMemoryWriteFile::getPos() const { return Pos; } - //! returns name of file -const io::path& CMemoryWriteFile::getFileName() const +const io::path &CMemoryWriteFile::getFileName() const { return Filename; } @@ -168,20 +149,17 @@ bool CMemoryWriteFile::flush() return true; // no buffering, so nothing to do } -IReadFile* createMemoryReadFile(const void* memory, long size, const io::path& fileName, bool deleteMemoryWhenDropped) +IReadFile *createMemoryReadFile(const void *memory, long size, const io::path &fileName, bool deleteMemoryWhenDropped) { - CMemoryReadFile* file = new CMemoryReadFile(memory, size, fileName, deleteMemoryWhenDropped); + CMemoryReadFile *file = new CMemoryReadFile(memory, size, fileName, deleteMemoryWhenDropped); return file; } - -IWriteFile* createMemoryWriteFile(void* memory, long size, const io::path& fileName, bool deleteMemoryWhenDropped) +IWriteFile *createMemoryWriteFile(void *memory, long size, const io::path &fileName, bool deleteMemoryWhenDropped) { - CMemoryWriteFile* file = new CMemoryWriteFile(memory, size, fileName, deleteMemoryWhenDropped); + CMemoryWriteFile *file = new CMemoryWriteFile(memory, size, fileName, deleteMemoryWhenDropped); return file; } - } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CMemoryFile.h b/source/Irrlicht/CMemoryFile.h index c6c7789c..3ce0e846 100644 --- a/source/Irrlicht/CMemoryFile.h +++ b/source/Irrlicht/CMemoryFile.h @@ -14,90 +14,86 @@ namespace irr namespace io { - /*! - Class for reading from memory. - */ - class CMemoryReadFile : public IMemoryReadFile +/*! + Class for reading from memory. +*/ +class CMemoryReadFile : public IMemoryReadFile +{ +public: + //! Constructor + CMemoryReadFile(const void *memory, long len, const io::path &fileName, bool deleteMemoryWhenDropped); + + //! Destructor + virtual ~CMemoryReadFile(); + + //! returns how much was read + size_t read(void *buffer, size_t sizeToRead) override; + + //! changes position in file, returns true if successful + bool seek(long finalPos, bool relativeMovement = false) override; + + //! returns size of file + long getSize() const override; + + //! returns where in the file we are. + long getPos() const override; + + //! returns name of file + const io::path &getFileName() const override; + + //! Get the type of the class implementing this interface + EREAD_FILE_TYPE getType() const override { - public: + return ERFT_MEMORY_READ_FILE; + } - //! Constructor - CMemoryReadFile(const void* memory, long len, const io::path& fileName, bool deleteMemoryWhenDropped); - - //! Destructor - virtual ~CMemoryReadFile(); - - //! returns how much was read - size_t read(void* buffer, size_t sizeToRead) override; - - //! changes position in file, returns true if successful - bool seek(long finalPos, bool relativeMovement = false) override; - - //! returns size of file - long getSize() const override; - - //! returns where in the file we are. - long getPos() const override; - - //! returns name of file - const io::path& getFileName() const override; - - //! Get the type of the class implementing this interface - EREAD_FILE_TYPE getType() const override - { - return ERFT_MEMORY_READ_FILE; - } - - //! Get direct access to internal buffer - const void *getBuffer() const override - { - return Buffer; - } - - private: - - const void *Buffer; - long Len; - long Pos; - io::path Filename; - bool deleteMemoryWhenDropped; - }; - - /*! - Class for writing to memory. - */ - class CMemoryWriteFile : public IWriteFile + //! Get direct access to internal buffer + const void *getBuffer() const override { - public: + return Buffer; + } - //! Constructor - CMemoryWriteFile(void* memory, long len, const io::path& fileName, bool deleteMemoryWhenDropped); +private: + const void *Buffer; + long Len; + long Pos; + io::path Filename; + bool deleteMemoryWhenDropped; +}; - //! Destructor - virtual ~CMemoryWriteFile(); +/*! + Class for writing to memory. +*/ +class CMemoryWriteFile : public IWriteFile +{ +public: + //! Constructor + CMemoryWriteFile(void *memory, long len, const io::path &fileName, bool deleteMemoryWhenDropped); - //! returns how much was written - size_t write(const void* buffer, size_t sizeToWrite) override; + //! Destructor + virtual ~CMemoryWriteFile(); - //! changes position in file, returns true if successful - bool seek(long finalPos, bool relativeMovement = false) override; + //! returns how much was written + size_t write(const void *buffer, size_t sizeToWrite) override; - //! returns where in the file we are. - long getPos() const override; + //! changes position in file, returns true if successful + bool seek(long finalPos, bool relativeMovement = false) override; - //! returns name of file - const io::path& getFileName() const override; + //! returns where in the file we are. + long getPos() const override; - bool flush() override; + //! returns name of file + const io::path &getFileName() const override; - private: + bool flush() override; - void *Buffer; - long Len; - long Pos; - io::path Filename; - bool deleteMemoryWhenDropped; - }; +private: + void *Buffer; + long Len; + long Pos; + io::path Filename; + bool deleteMemoryWhenDropped; +}; } // end namespace io } // end namespace irr diff --git a/source/Irrlicht/CMeshCache.cpp b/source/Irrlicht/CMeshCache.cpp index cb2a9419..4f7e1203 100644 --- a/source/Irrlicht/CMeshCache.cpp +++ b/source/Irrlicht/CMeshCache.cpp @@ -13,34 +13,29 @@ namespace scene static const io::SNamedPath emptyNamedPath; - CMeshCache::~CMeshCache() { clear(); } - //! adds a mesh to the list -void CMeshCache::addMesh(const io::path& filename, IAnimatedMesh* mesh) +void CMeshCache::addMesh(const io::path &filename, IAnimatedMesh *mesh) { mesh->grab(); - MeshEntry e ( filename ); + MeshEntry e(filename); e.Mesh = mesh; Meshes.push_back(e); } - //! Removes a mesh from the cache. -void CMeshCache::removeMesh(const IMesh* const mesh) +void CMeshCache::removeMesh(const IMesh *const mesh) { - if ( !mesh ) + if (!mesh) return; - for (u32 i=0; igetMesh(0) == mesh)) - { + for (u32 i = 0; i < Meshes.size(); ++i) { + if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh)) { Meshes[i].Mesh->drop(); Meshes.erase(i); return; @@ -48,19 +43,16 @@ void CMeshCache::removeMesh(const IMesh* const mesh) } } - //! Returns amount of loaded meshes u32 CMeshCache::getMeshCount() const { return Meshes.size(); } - //! Returns current number of the mesh -s32 CMeshCache::getMeshIndex(const IMesh* const mesh) const +s32 CMeshCache::getMeshIndex(const IMesh *const mesh) const { - for (u32 i=0; igetMesh(0) == mesh)) return (s32)i; } @@ -68,9 +60,8 @@ s32 CMeshCache::getMeshIndex(const IMesh* const mesh) const return -1; } - //! Returns a mesh based on its index number -IAnimatedMesh* CMeshCache::getMeshByIndex(u32 number) +IAnimatedMesh *CMeshCache::getMeshByIndex(u32 number) { if (number >= Meshes.size()) return 0; @@ -78,18 +69,16 @@ IAnimatedMesh* CMeshCache::getMeshByIndex(u32 number) return Meshes[number].Mesh; } - //! Returns a mesh based on its name. -IAnimatedMesh* CMeshCache::getMeshByName(const io::path& name) +IAnimatedMesh *CMeshCache::getMeshByName(const io::path &name) { - MeshEntry e ( name ); + MeshEntry e(name); s32 id = Meshes.binary_search(e); return (id != -1) ? Meshes[id].Mesh : 0; } - //! Get the name of a loaded mesh, based on its index. -const io::SNamedPath& CMeshCache::getMeshName(u32 index) const +const io::SNamedPath &CMeshCache::getMeshName(u32 index) const { if (index >= Meshes.size()) return emptyNamedPath; @@ -97,15 +86,13 @@ const io::SNamedPath& CMeshCache::getMeshName(u32 index) const return Meshes[index].NamedPath; } - //! Get the name of a loaded mesh, if there is any. -const io::SNamedPath& CMeshCache::getMeshName(const IMesh* const mesh) const +const io::SNamedPath &CMeshCache::getMeshName(const IMesh *const mesh) const { if (!mesh) return emptyNamedPath; - for (u32 i=0; igetMesh(0) == mesh)) return Meshes[i].NamedPath; } @@ -114,7 +101,7 @@ const io::SNamedPath& CMeshCache::getMeshName(const IMesh* const mesh) const } //! Renames a loaded mesh. -bool CMeshCache::renameMesh(u32 index, const io::path& name) +bool CMeshCache::renameMesh(u32 index, const io::path &name) { if (index >= Meshes.size()) return false; @@ -124,14 +111,11 @@ bool CMeshCache::renameMesh(u32 index, const io::path& name) return true; } - //! Renames a loaded mesh. -bool CMeshCache::renameMesh(const IMesh* const mesh, const io::path& name) +bool CMeshCache::renameMesh(const IMesh *const mesh, const io::path &name) { - for (u32 i=0; igetMesh(0) == mesh)) - { + for (u32 i = 0; i < Meshes.size(); ++i) { + if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh)) { Meshes[i].NamedPath.setPath(name); Meshes.sort(); return true; @@ -141,18 +125,16 @@ bool CMeshCache::renameMesh(const IMesh* const mesh, const io::path& name) return false; } - //! returns if a mesh already was loaded -bool CMeshCache::isMeshLoaded(const io::path& name) +bool CMeshCache::isMeshLoaded(const io::path &name) { return getMeshByName(name) != 0; } - //! Clears the whole mesh cache, removing all meshes. void CMeshCache::clear() { - for (u32 i=0; idrop(); Meshes.clear(); @@ -161,10 +143,8 @@ void CMeshCache::clear() //! Clears all meshes that are held in the mesh cache but not used anywhere else. void CMeshCache::clearUnusedMeshes() { - for (u32 i=0; igetReferenceCount() == 1) - { + for (u32 i = 0; i < Meshes.size(); ++i) { + if (Meshes[i].Mesh->getReferenceCount() == 1) { Meshes[i].Mesh->drop(); Meshes.erase(i); --i; @@ -172,7 +152,5 @@ void CMeshCache::clearUnusedMeshes() } } - } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CMeshCache.h b/source/Irrlicht/CMeshCache.h index ba9f235a..1c2b5268 100644 --- a/source/Irrlicht/CMeshCache.h +++ b/source/Irrlicht/CMeshCache.h @@ -12,108 +12,105 @@ namespace irr namespace scene { - class CMeshCache : public IMeshCache +class CMeshCache : public IMeshCache +{ +public: + virtual ~CMeshCache(); + + //! Adds a mesh to the internal list of loaded meshes. + /** Usually, ISceneManager::getMesh() is called to load a mesh from file. + That method searches the list of loaded meshes if a mesh has already been loaded and + returns a pointer to if it is in that list and already in memory. Otherwise it loads + the mesh. With IMeshCache::addMesh(), it is possible to pretend that a mesh already + has been loaded. This method can be used for example by mesh loaders who need to + load more than one mesh with one call. They can add additional meshes with this + method to the scene manager. The COLLADA loader for example uses this method. + \param filename: Filename of the mesh. When called ISceneManager::getMesh() with this + parameter, the method will return the mesh parameter given with this method. + \param mesh: Pointer to a mesh which will now be referenced by this name. */ + void addMesh(const io::path &filename, IAnimatedMesh *mesh) override; + + //! Removes a mesh from the cache. + /** After loading a mesh with getMesh(), the mesh can be removed from the cache + using this method, freeing a lot of memory. */ + void removeMesh(const IMesh *const mesh) override; + + //! Returns amount of loaded meshes in the cache. + /** You can load new meshes into the cache using getMesh() and addMesh(). + If you ever need to access the internal mesh cache, you can do this using + removeMesh(), getMeshNumber(), getMeshByIndex() and getMeshFilename() */ + u32 getMeshCount() const override; + + //! Returns current index number of the mesh, and -1 if it is not in the cache. + s32 getMeshIndex(const IMesh *const mesh) const override; + + //! Returns a mesh based on its index number. + /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. + Note that this number is only valid until a new mesh is loaded or removed * + \return Returns pointer to the mesh or 0 if there is none with this number. */ + IAnimatedMesh *getMeshByIndex(u32 index) override; + + //! Returns a mesh based on its name. + /** \param name Name of the mesh. Usually a filename. + \return Pointer to the mesh or 0 if there is none with this number. */ + IAnimatedMesh *getMeshByName(const io::path &name) override; + + //! Get the name of a loaded mesh, based on its index. + /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. + \return The name if mesh was found and has a name, else the path is empty. */ + const io::SNamedPath &getMeshName(u32 index) const override; + + //! Get the name of a loaded mesh, if there is any. + /** \param mesh Pointer to mesh to query. + \return The name if mesh was found and has a name, else the path is empty. */ + const io::SNamedPath &getMeshName(const IMesh *const mesh) const override; + + //! Renames a loaded mesh. + /** Note that renaming meshes might change the ordering of the + meshes, and so the index of the meshes as returned by + getMeshIndex() or taken by some methods will change. + \param index The index of the mesh in the cache. + \param name New name for the mesh. + \return True if mesh was renamed. */ + bool renameMesh(u32 index, const io::path &name) override; + + //! Renames a loaded mesh. + /** Note that renaming meshes might change the ordering of the + meshes, and so the index of the meshes as returned by + getMeshIndex() or taken by some methods will change. + \param mesh Mesh to be renamed. + \param name New name for the mesh. + \return True if mesh was renamed. */ + bool renameMesh(const IMesh *const mesh, const io::path &name) override; + + //! returns if a mesh already was loaded + bool isMeshLoaded(const io::path &name) override; + + //! Clears the whole mesh cache, removing all meshes. + void clear() override; + + //! Clears all meshes that are held in the mesh cache but not used anywhere else. + void clearUnusedMeshes() override; + +protected: + struct MeshEntry { - public: - - virtual ~CMeshCache(); - - //! Adds a mesh to the internal list of loaded meshes. - /** Usually, ISceneManager::getMesh() is called to load a mesh from file. - That method searches the list of loaded meshes if a mesh has already been loaded and - returns a pointer to if it is in that list and already in memory. Otherwise it loads - the mesh. With IMeshCache::addMesh(), it is possible to pretend that a mesh already - has been loaded. This method can be used for example by mesh loaders who need to - load more than one mesh with one call. They can add additional meshes with this - method to the scene manager. The COLLADA loader for example uses this method. - \param filename: Filename of the mesh. When called ISceneManager::getMesh() with this - parameter, the method will return the mesh parameter given with this method. - \param mesh: Pointer to a mesh which will now be referenced by this name. */ - void addMesh(const io::path& filename, IAnimatedMesh* mesh) override; - - //! Removes a mesh from the cache. - /** After loading a mesh with getMesh(), the mesh can be removed from the cache - using this method, freeing a lot of memory. */ - void removeMesh(const IMesh* const mesh) override; - - //! Returns amount of loaded meshes in the cache. - /** You can load new meshes into the cache using getMesh() and addMesh(). - If you ever need to access the internal mesh cache, you can do this using - removeMesh(), getMeshNumber(), getMeshByIndex() and getMeshFilename() */ - u32 getMeshCount() const override; - - //! Returns current index number of the mesh, and -1 if it is not in the cache. - s32 getMeshIndex(const IMesh* const mesh) const override; - - //! Returns a mesh based on its index number. - /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. - Note that this number is only valid until a new mesh is loaded or removed * - \return Returns pointer to the mesh or 0 if there is none with this number. */ - IAnimatedMesh* getMeshByIndex(u32 index) override; - - //! Returns a mesh based on its name. - /** \param name Name of the mesh. Usually a filename. - \return Pointer to the mesh or 0 if there is none with this number. */ - IAnimatedMesh* getMeshByName(const io::path& name) override; - - //! Get the name of a loaded mesh, based on its index. - /** \param index: Index of the mesh, number between 0 and getMeshCount()-1. - \return The name if mesh was found and has a name, else the path is empty. */ - const io::SNamedPath& getMeshName(u32 index) const override; - - //! Get the name of a loaded mesh, if there is any. - /** \param mesh Pointer to mesh to query. - \return The name if mesh was found and has a name, else the path is empty. */ - const io::SNamedPath& getMeshName(const IMesh* const mesh) const override; - - //! Renames a loaded mesh. - /** Note that renaming meshes might change the ordering of the - meshes, and so the index of the meshes as returned by - getMeshIndex() or taken by some methods will change. - \param index The index of the mesh in the cache. - \param name New name for the mesh. - \return True if mesh was renamed. */ - bool renameMesh(u32 index, const io::path& name) override; - - //! Renames a loaded mesh. - /** Note that renaming meshes might change the ordering of the - meshes, and so the index of the meshes as returned by - getMeshIndex() or taken by some methods will change. - \param mesh Mesh to be renamed. - \param name New name for the mesh. - \return True if mesh was renamed. */ - bool renameMesh(const IMesh* const mesh, const io::path& name) override; - - //! returns if a mesh already was loaded - bool isMeshLoaded(const io::path& name) override; - - //! Clears the whole mesh cache, removing all meshes. - void clear() override; - - //! Clears all meshes that are held in the mesh cache but not used anywhere else. - void clearUnusedMeshes() override; - - protected: - - struct MeshEntry + MeshEntry(const io::path &name) : + NamedPath(name) { - MeshEntry ( const io::path& name ) - : NamedPath ( name ) - { - } - io::SNamedPath NamedPath; - IAnimatedMesh* Mesh; + } + io::SNamedPath NamedPath; + IAnimatedMesh *Mesh; - bool operator < (const MeshEntry& other) const - { - return (NamedPath < other.NamedPath); - } - }; - - //! loaded meshes - core::array Meshes; + bool operator<(const MeshEntry &other) const + { + return (NamedPath < other.NamedPath); + } }; + //! loaded meshes + core::array Meshes; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CMeshManipulator.cpp b/source/Irrlicht/CMeshManipulator.cpp index 62ae97f4..3309fea3 100644 --- a/source/Irrlicht/CMeshManipulator.cpp +++ b/source/Irrlicht/CMeshManipulator.cpp @@ -14,9 +14,9 @@ namespace irr namespace scene { -static inline core::vector3df getAngleWeight(const core::vector3df& v1, - const core::vector3df& v2, - const core::vector3df& v3) +static inline core::vector3df getAngleWeight(const core::vector3df &v1, + const core::vector3df &v2, + const core::vector3df &v3) { // Calculate this triangle's weight for each of its three vertices // start by calculating the lengths of its sides @@ -29,199 +29,178 @@ static inline core::vector3df getAngleWeight(const core::vector3df& v1, // use them to find the angle at each vertex return core::vector3df( - acosf((b + c - a) / (2.f * bsqrt * csqrt)), - acosf((-b + c + a) / (2.f * asqrt * csqrt)), - acosf((b - c + a) / (2.f * bsqrt * asqrt))); + acosf((b + c - a) / (2.f * bsqrt * csqrt)), + acosf((-b + c + a) / (2.f * asqrt * csqrt)), + acosf((b - c + a) / (2.f * bsqrt * asqrt))); } - namespace { template -void recalculateNormalsT(IMeshBuffer* buffer, bool smooth, bool angleWeighted) +void recalculateNormalsT(IMeshBuffer *buffer, bool smooth, bool angleWeighted) { const u32 vtxcnt = buffer->getVertexCount(); const u32 idxcnt = buffer->getIndexCount(); - const T* idx = reinterpret_cast(buffer->getIndices()); + const T *idx = reinterpret_cast(buffer->getIndices()); - if (!smooth) - { - for (u32 i=0; igetPosition(idx[i+0]); - const core::vector3df& v2 = buffer->getPosition(idx[i+1]); - const core::vector3df& v3 = buffer->getPosition(idx[i+2]); + if (!smooth) { + for (u32 i = 0; i < idxcnt; i += 3) { + const core::vector3df &v1 = buffer->getPosition(idx[i + 0]); + const core::vector3df &v2 = buffer->getPosition(idx[i + 1]); + const core::vector3df &v3 = buffer->getPosition(idx[i + 2]); const core::vector3df normal = core::plane3d(v1, v2, v3).Normal; - buffer->getNormal(idx[i+0]) = normal; - buffer->getNormal(idx[i+1]) = normal; - buffer->getNormal(idx[i+2]) = normal; + buffer->getNormal(idx[i + 0]) = normal; + buffer->getNormal(idx[i + 1]) = normal; + buffer->getNormal(idx[i + 2]) = normal; } - } - else - { + } else { u32 i; - for ( i = 0; i!= vtxcnt; ++i ) + for (i = 0; i != vtxcnt; ++i) buffer->getNormal(i).set(0.f, 0.f, 0.f); - for ( i=0; igetPosition(idx[i+0]); - const core::vector3df& v2 = buffer->getPosition(idx[i+1]); - const core::vector3df& v3 = buffer->getPosition(idx[i+2]); + for (i = 0; i < idxcnt; i += 3) { + const core::vector3df &v1 = buffer->getPosition(idx[i + 0]); + const core::vector3df &v2 = buffer->getPosition(idx[i + 1]); + const core::vector3df &v3 = buffer->getPosition(idx[i + 2]); const core::vector3df normal = core::plane3d(v1, v2, v3).Normal; - core::vector3df weight(1.f,1.f,1.f); + core::vector3df weight(1.f, 1.f, 1.f); if (angleWeighted) - weight = irr::scene::getAngleWeight(v1,v2,v3); // writing irr::scene:: necessary for borland + weight = irr::scene::getAngleWeight(v1, v2, v3); // writing irr::scene:: necessary for borland - buffer->getNormal(idx[i+0]) += weight.X*normal; - buffer->getNormal(idx[i+1]) += weight.Y*normal; - buffer->getNormal(idx[i+2]) += weight.Z*normal; + buffer->getNormal(idx[i + 0]) += weight.X * normal; + buffer->getNormal(idx[i + 1]) += weight.Y * normal; + buffer->getNormal(idx[i + 2]) += weight.Z * normal; } - for ( i = 0; i!= vtxcnt; ++i ) + for (i = 0; i != vtxcnt; ++i) buffer->getNormal(i).normalize(); } } } - //! Recalculates all normals of the mesh buffer. /** \param buffer: Mesh buffer on which the operation is performed. */ -void CMeshManipulator::recalculateNormals(IMeshBuffer* buffer, bool smooth, bool angleWeighted) const +void CMeshManipulator::recalculateNormals(IMeshBuffer *buffer, bool smooth, bool angleWeighted) const { if (!buffer) return; - if (buffer->getIndexType()==video::EIT_16BIT) + if (buffer->getIndexType() == video::EIT_16BIT) recalculateNormalsT(buffer, smooth, angleWeighted); else recalculateNormalsT(buffer, smooth, angleWeighted); } - //! Recalculates all normals of the mesh. //! \param mesh: Mesh on which the operation is performed. -void CMeshManipulator::recalculateNormals(scene::IMesh* mesh, bool smooth, bool angleWeighted) const +void CMeshManipulator::recalculateNormals(scene::IMesh *mesh, bool smooth, bool angleWeighted) const { if (!mesh) return; - if (mesh->getMeshType() == EAMT_SKINNED) - { - ISkinnedMesh *smesh = (ISkinnedMesh *) mesh; + if (mesh->getMeshType() == EAMT_SKINNED) { + ISkinnedMesh *smesh = (ISkinnedMesh *)mesh; smesh->resetAnimation(); } const u32 bcount = mesh->getMeshBufferCount(); - for ( u32 b=0; bgetMeshBuffer(b), smooth, angleWeighted); - if (mesh->getMeshType() == EAMT_SKINNED) - { - ISkinnedMesh *smesh = (ISkinnedMesh *) mesh; + if (mesh->getMeshType() == EAMT_SKINNED) { + ISkinnedMesh *smesh = (ISkinnedMesh *)mesh; smesh->refreshJointCache(); } } - //! Clones a static IMesh into a modifyable SMesh. // not yet 32bit -SMesh* CMeshManipulator::createMeshCopy(scene::IMesh* mesh) const +SMesh *CMeshManipulator::createMeshCopy(scene::IMesh *mesh) const { if (!mesh) return 0; - SMesh* clone = new SMesh(); + SMesh *clone = new SMesh(); const u32 meshBufferCount = mesh->getMeshBufferCount(); - for ( u32 b=0; bgetMeshBuffer(b); - switch(mb->getVertexType()) - { - case video::EVT_STANDARD: - { - SMeshBuffer* buffer = new SMeshBuffer(); - buffer->Material = mb->getMaterial(); - const u32 vcount = mb->getVertexCount(); - buffer->Vertices.reallocate(vcount); - video::S3DVertex* vertices = (video::S3DVertex*)mb->getVertices(); - for (u32 i=0; i < vcount; ++i) - buffer->Vertices.push_back(vertices[i]); - const u32 icount = mb->getIndexCount(); - buffer->Indices.reallocate(icount); - const u16* indices = mb->getIndices(); - for (u32 i=0; i < icount; ++i) - buffer->Indices.push_back(indices[i]); - clone->addMeshBuffer(buffer); - buffer->drop(); - } - break; - case video::EVT_2TCOORDS: - { - SMeshBufferLightMap* buffer = new SMeshBufferLightMap(); - buffer->Material = mb->getMaterial(); - const u32 vcount = mb->getVertexCount(); - buffer->Vertices.reallocate(vcount); - video::S3DVertex2TCoords* vertices = (video::S3DVertex2TCoords*)mb->getVertices(); - for (u32 i=0; i < vcount; ++i) - buffer->Vertices.push_back(vertices[i]); - const u32 icount = mb->getIndexCount(); - buffer->Indices.reallocate(icount); - const u16* indices = mb->getIndices(); - for (u32 i=0; i < icount; ++i) - buffer->Indices.push_back(indices[i]); - clone->addMeshBuffer(buffer); - buffer->drop(); - } - break; - case video::EVT_TANGENTS: - { - SMeshBufferTangents* buffer = new SMeshBufferTangents(); - buffer->Material = mb->getMaterial(); - const u32 vcount = mb->getVertexCount(); - buffer->Vertices.reallocate(vcount); - video::S3DVertexTangents* vertices = (video::S3DVertexTangents*)mb->getVertices(); - for (u32 i=0; i < vcount; ++i) - buffer->Vertices.push_back(vertices[i]); - const u32 icount = mb->getIndexCount(); - buffer->Indices.reallocate(icount); - const u16* indices = mb->getIndices(); - for (u32 i=0; i < icount; ++i) - buffer->Indices.push_back(indices[i]); - clone->addMeshBuffer(buffer); - buffer->drop(); - } - break; - }// end switch + for (u32 b = 0; b < meshBufferCount; ++b) { + const IMeshBuffer *const mb = mesh->getMeshBuffer(b); + switch (mb->getVertexType()) { + case video::EVT_STANDARD: { + SMeshBuffer *buffer = new SMeshBuffer(); + buffer->Material = mb->getMaterial(); + const u32 vcount = mb->getVertexCount(); + buffer->Vertices.reallocate(vcount); + video::S3DVertex *vertices = (video::S3DVertex *)mb->getVertices(); + for (u32 i = 0; i < vcount; ++i) + buffer->Vertices.push_back(vertices[i]); + const u32 icount = mb->getIndexCount(); + buffer->Indices.reallocate(icount); + const u16 *indices = mb->getIndices(); + for (u32 i = 0; i < icount; ++i) + buffer->Indices.push_back(indices[i]); + clone->addMeshBuffer(buffer); + buffer->drop(); + } break; + case video::EVT_2TCOORDS: { + SMeshBufferLightMap *buffer = new SMeshBufferLightMap(); + buffer->Material = mb->getMaterial(); + const u32 vcount = mb->getVertexCount(); + buffer->Vertices.reallocate(vcount); + video::S3DVertex2TCoords *vertices = (video::S3DVertex2TCoords *)mb->getVertices(); + for (u32 i = 0; i < vcount; ++i) + buffer->Vertices.push_back(vertices[i]); + const u32 icount = mb->getIndexCount(); + buffer->Indices.reallocate(icount); + const u16 *indices = mb->getIndices(); + for (u32 i = 0; i < icount; ++i) + buffer->Indices.push_back(indices[i]); + clone->addMeshBuffer(buffer); + buffer->drop(); + } break; + case video::EVT_TANGENTS: { + SMeshBufferTangents *buffer = new SMeshBufferTangents(); + buffer->Material = mb->getMaterial(); + const u32 vcount = mb->getVertexCount(); + buffer->Vertices.reallocate(vcount); + video::S3DVertexTangents *vertices = (video::S3DVertexTangents *)mb->getVertices(); + for (u32 i = 0; i < vcount; ++i) + buffer->Vertices.push_back(vertices[i]); + const u32 icount = mb->getIndexCount(); + buffer->Indices.reallocate(icount); + const u16 *indices = mb->getIndices(); + for (u32 i = 0; i < icount; ++i) + buffer->Indices.push_back(indices[i]); + clone->addMeshBuffer(buffer); + buffer->drop(); + } break; + } // end switch - }// end for all mesh buffers + } // end for all mesh buffers clone->BoundingBox = mesh->getBoundingBox(); return clone; } - //! Returns amount of polygons in mesh. -s32 CMeshManipulator::getPolyCount(scene::IMesh* mesh) const +s32 CMeshManipulator::getPolyCount(scene::IMesh *mesh) const { if (!mesh) return 0; s32 trianglecount = 0; - for (u32 g=0; ggetMeshBufferCount(); ++g) + for (u32 g = 0; g < mesh->getMeshBufferCount(); ++g) trianglecount += mesh->getMeshBuffer(g)->getIndexCount() / 3; return trianglecount; } - //! Returns amount of polygons in mesh. -s32 CMeshManipulator::getPolyCount(scene::IAnimatedMesh* mesh) const +s32 CMeshManipulator::getPolyCount(scene::IAnimatedMesh *mesh) const { if (mesh && mesh->getFrameCount() != 0) return getPolyCount(mesh->getMesh(0)); @@ -229,14 +208,11 @@ s32 CMeshManipulator::getPolyCount(scene::IAnimatedMesh* mesh) const return 0; } - //! create a new AnimatedMesh and adds the mesh to it -IAnimatedMesh * CMeshManipulator::createAnimatedMesh(scene::IMesh* mesh, scene::E_ANIMATED_MESH_TYPE type) const +IAnimatedMesh *CMeshManipulator::createAnimatedMesh(scene::IMesh *mesh, scene::E_ANIMATED_MESH_TYPE type) const { return new SAnimatedMesh(mesh, type); } - } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CMeshManipulator.h b/source/Irrlicht/CMeshManipulator.h index 53ab2dcb..0377d6a3 100644 --- a/source/Irrlicht/CMeshManipulator.h +++ b/source/Irrlicht/CMeshManipulator.h @@ -22,24 +22,24 @@ public: //! Recalculates all normals of the mesh. /** \param mesh: Mesh on which the operation is performed. \param smooth: Whether to use smoothed normals. */ - void recalculateNormals(scene::IMesh* mesh, bool smooth = false, bool angleWeighted = false) const override; + void recalculateNormals(scene::IMesh *mesh, bool smooth = false, bool angleWeighted = false) const override; //! Recalculates all normals of the mesh buffer. /** \param buffer: Mesh buffer on which the operation is performed. \param smooth: Whether to use smoothed normals. */ - void recalculateNormals(IMeshBuffer* buffer, bool smooth = false, bool angleWeighted = false) const override; + void recalculateNormals(IMeshBuffer *buffer, bool smooth = false, bool angleWeighted = false) const override; //! Clones a static IMesh into a modifiable SMesh. - SMesh* createMeshCopy(scene::IMesh* mesh) const override; + SMesh *createMeshCopy(scene::IMesh *mesh) const override; //! Returns amount of polygons in mesh. - s32 getPolyCount(scene::IMesh* mesh) const override; + s32 getPolyCount(scene::IMesh *mesh) const override; //! Returns amount of polygons in mesh. - s32 getPolyCount(scene::IAnimatedMesh* mesh) const override; + s32 getPolyCount(scene::IAnimatedMesh *mesh) const override; //! create a new AnimatedMesh and adds the mesh to it - IAnimatedMesh * createAnimatedMesh(scene::IMesh* mesh,scene::E_ANIMATED_MESH_TYPE type) const override; + IAnimatedMesh *createAnimatedMesh(scene::IMesh *mesh, scene::E_ANIMATED_MESH_TYPE type) const override; }; } // end namespace scene diff --git a/source/Irrlicht/CMeshSceneNode.cpp b/source/Irrlicht/CMeshSceneNode.cpp index d034bb77..7ff6cad5 100644 --- a/source/Irrlicht/CMeshSceneNode.cpp +++ b/source/Irrlicht/CMeshSceneNode.cpp @@ -17,23 +17,21 @@ namespace irr namespace scene { - - //! constructor -CMeshSceneNode::CMeshSceneNode(IMesh* mesh, ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position, const core::vector3df& rotation, - const core::vector3df& scale) -: IMeshSceneNode(parent, mgr, id, position, rotation, scale), Mesh(0), - PassCount(0), ReadOnlyMaterials(false) +CMeshSceneNode::CMeshSceneNode(IMesh *mesh, ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position, const core::vector3df &rotation, + const core::vector3df &scale) : + IMeshSceneNode(parent, mgr, id, position, rotation, scale), + Mesh(0), + PassCount(0), ReadOnlyMaterials(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CMeshSceneNode"); - #endif +#endif setMesh(mesh); } - //! destructor CMeshSceneNode::~CMeshSceneNode() { @@ -41,18 +39,16 @@ CMeshSceneNode::~CMeshSceneNode() Mesh->drop(); } - //! frame void CMeshSceneNode::OnRegisterSceneNode() { - if (IsVisible && Mesh) - { + if (IsVisible && Mesh) { // because this node supports rendering of mixed mode meshes consisting of // transparent and solid material at the same time, we need to go through all // materials, check of what type they are and register this node for the right // render pass according to that. - video::IVideoDriver* driver = SceneManager->getVideoDriver(); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); PassCount = 0; int transparentCount = 0; @@ -60,11 +56,10 @@ void CMeshSceneNode::OnRegisterSceneNode() // count transparent and solid materials in this scene node const u32 numMaterials = ReadOnlyMaterials ? Mesh->getMeshBufferCount() : Materials.size(); - for (u32 i=0; igetMeshBuffer(i)->getMaterial() : Materials[i]; + for (u32 i = 0; i < numMaterials; ++i) { + const video::SMaterial &material = ReadOnlyMaterials ? Mesh->getMeshBuffer(i)->getMaterial() : Materials[i]; - if ( driver->needsTransparentRenderPass(material) ) + if (driver->needsTransparentRenderPass(material)) ++transparentCount; else ++solidCount; @@ -85,36 +80,32 @@ void CMeshSceneNode::OnRegisterSceneNode() } } - //! renders the node. void CMeshSceneNode::render() { - video::IVideoDriver* driver = SceneManager->getVideoDriver(); + video::IVideoDriver *driver = SceneManager->getVideoDriver(); if (!Mesh || !driver) return; const bool isTransparentPass = - SceneManager->getSceneNodeRenderPass() == scene::ESNRP_TRANSPARENT; + SceneManager->getSceneNodeRenderPass() == scene::ESNRP_TRANSPARENT; ++PassCount; driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); Box = Mesh->getBoundingBox(); - for (u32 i=0; igetMeshBufferCount(); ++i) - { - scene::IMeshBuffer* mb = Mesh->getMeshBuffer(i); - if (mb) - { - const video::SMaterial& material = ReadOnlyMaterials ? mb->getMaterial() : Materials[i]; + for (u32 i = 0; i < Mesh->getMeshBufferCount(); ++i) { + scene::IMeshBuffer *mb = Mesh->getMeshBuffer(i); + if (mb) { + const video::SMaterial &material = ReadOnlyMaterials ? mb->getMaterial() : Materials[i]; const bool transparent = driver->needsTransparentRenderPass(material); // only render transparent buffer if this is the transparent render pass // and solid only in solid pass - if (transparent == isTransparentPass) - { + if (transparent == isTransparentPass) { driver->setMaterial(material); driver->drawMeshBuffer(mb); } @@ -122,80 +113,68 @@ void CMeshSceneNode::render() } // for debug purposes only: - if (DebugDataVisible && PassCount==1) - { + if (DebugDataVisible && PassCount == 1) { video::SMaterial m; m.Lighting = false; - m.AntiAliasing=0; + m.AntiAliasing = 0; driver->setMaterial(m); - if (DebugDataVisible & scene::EDS_BBOX) - { - driver->draw3DBox(Box, video::SColor(255,255,255,255)); + if (DebugDataVisible & scene::EDS_BBOX) { + driver->draw3DBox(Box, video::SColor(255, 255, 255, 255)); } - if (DebugDataVisible & scene::EDS_BBOX_BUFFERS) - { - for (u32 g=0; ggetMeshBufferCount(); ++g) - { + if (DebugDataVisible & scene::EDS_BBOX_BUFFERS) { + for (u32 g = 0; g < Mesh->getMeshBufferCount(); ++g) { driver->draw3DBox( - Mesh->getMeshBuffer(g)->getBoundingBox(), - video::SColor(255,190,128,128)); + Mesh->getMeshBuffer(g)->getBoundingBox(), + video::SColor(255, 190, 128, 128)); } } - if (DebugDataVisible & scene::EDS_NORMALS) - { + if (DebugDataVisible & scene::EDS_NORMALS) { // draw normals const f32 debugNormalLength = 1.f; const video::SColor debugNormalColor = video::SColor(255, 34, 221, 221); const u32 count = Mesh->getMeshBufferCount(); - for (u32 i=0; i != count; ++i) - { + for (u32 i = 0; i != count; ++i) { driver->drawMeshBufferNormals(Mesh->getMeshBuffer(i), debugNormalLength, debugNormalColor); } } // show mesh - if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY) - { + if (DebugDataVisible & scene::EDS_MESH_WIRE_OVERLAY) { m.Wireframe = true; driver->setMaterial(m); - for (u32 g=0; ggetMeshBufferCount(); ++g) - { + for (u32 g = 0; g < Mesh->getMeshBufferCount(); ++g) { driver->drawMeshBuffer(Mesh->getMeshBuffer(g)); } } } } - //! Removes a child from this scene node. //! Implemented here, to be able to remove the shadow properly, if there is one, //! or to remove attached childs. -bool CMeshSceneNode::removeChild(ISceneNode* child) +bool CMeshSceneNode::removeChild(ISceneNode *child) { return ISceneNode::removeChild(child); } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CMeshSceneNode::getBoundingBox() const +const core::aabbox3d &CMeshSceneNode::getBoundingBox() const { return Mesh ? Mesh->getBoundingBox() : Box; } - //! returns the material based on the zero based index i. To get the amount //! of materials used by this scene node, use getMaterialCount(). //! This function is needed for inserting the node into the scene hierarchy on a //! optimal position for minimizing renderstate changes, but can also be used //! to directly modify the material of a scene node. -video::SMaterial& CMeshSceneNode::getMaterial(u32 i) +video::SMaterial &CMeshSceneNode::getMaterial(u32 i) { - if (Mesh && ReadOnlyMaterials && igetMeshBufferCount()) - { + if (Mesh && ReadOnlyMaterials && i < Mesh->getMeshBufferCount()) { ReadOnlyMaterial = Mesh->getMeshBuffer(i)->getMaterial(); return ReadOnlyMaterial; } @@ -206,7 +185,6 @@ video::SMaterial& CMeshSceneNode::getMaterial(u32 i) return Materials[i]; } - //! returns amount of materials used by this scene node. u32 CMeshSceneNode::getMaterialCount() const { @@ -216,12 +194,10 @@ u32 CMeshSceneNode::getMaterialCount() const return Materials.size(); } - //! Sets a new mesh -void CMeshSceneNode::setMesh(IMesh* mesh) +void CMeshSceneNode::setMesh(IMesh *mesh) { - if (mesh) - { + if (mesh) { mesh->grab(); if (Mesh) Mesh->drop(); @@ -231,18 +207,15 @@ void CMeshSceneNode::setMesh(IMesh* mesh) } } - void CMeshSceneNode::copyMaterials() { Materials.clear(); - if (Mesh) - { + if (Mesh) { video::SMaterial mat; - for (u32 i=0; igetMeshBufferCount(); ++i) - { - IMeshBuffer* mb = Mesh->getMeshBuffer(i); + for (u32 i = 0; i < Mesh->getMeshBufferCount(); ++i) { + IMeshBuffer *mb = Mesh->getMeshBuffer(i); if (mb) mat = mb->getMaterial(); @@ -251,7 +224,6 @@ void CMeshSceneNode::copyMaterials() } } - //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. /* In this way it is possible to change the materials a mesh causing all mesh scene nodes referencing this mesh to change too. */ @@ -260,24 +232,22 @@ void CMeshSceneNode::setReadOnlyMaterials(bool readonly) ReadOnlyMaterials = readonly; } - //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style bool CMeshSceneNode::isReadOnlyMaterials() const { return ReadOnlyMaterials; } - //! Creates a clone of this scene node and its children. -ISceneNode* CMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* newManager) +ISceneNode *CMeshSceneNode::clone(ISceneNode *newParent, ISceneManager *newManager) { if (!newParent) newParent = Parent; if (!newManager) newManager = SceneManager; - CMeshSceneNode* nb = new CMeshSceneNode(Mesh, newParent, - newManager, ID, RelativeTranslation, RelativeRotation, RelativeScale); + CMeshSceneNode *nb = new CMeshSceneNode(Mesh, newParent, + newManager, ID, RelativeTranslation, RelativeRotation, RelativeScale); nb->cloneMembers(this, newManager); nb->ReadOnlyMaterials = ReadOnlyMaterials; @@ -288,7 +258,5 @@ ISceneNode* CMeshSceneNode::clone(ISceneNode* newParent, ISceneManager* newManag return nb; } - } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CMeshSceneNode.h b/source/Irrlicht/CMeshSceneNode.h index f8e4adb2..a0092874 100644 --- a/source/Irrlicht/CMeshSceneNode.h +++ b/source/Irrlicht/CMeshSceneNode.h @@ -12,76 +12,74 @@ namespace irr namespace scene { - class CMeshSceneNode : public IMeshSceneNode - { - public: +class CMeshSceneNode : public IMeshSceneNode +{ +public: + //! constructor + CMeshSceneNode(IMesh *mesh, ISceneNode *parent, ISceneManager *mgr, s32 id, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f)); - //! constructor - CMeshSceneNode(IMesh* mesh, ISceneNode* parent, ISceneManager* mgr, s32 id, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)); + //! destructor + virtual ~CMeshSceneNode(); - //! destructor - virtual ~CMeshSceneNode(); + //! frame + void OnRegisterSceneNode() override; - //! frame - void OnRegisterSceneNode() override; + //! renders the node. + void render() override; - //! renders the node. - void render() override; + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! returns the material based on the zero based index i. To get the amount + //! of materials used by this scene node, use getMaterialCount(). + //! This function is needed for inserting the node into the scene hierarchy on a + //! optimal position for minimizing renderstate changes, but can also be used + //! to directly modify the material of a scene node. + video::SMaterial &getMaterial(u32 i) override; - //! returns the material based on the zero based index i. To get the amount - //! of materials used by this scene node, use getMaterialCount(). - //! This function is needed for inserting the node into the scene hierarchy on a - //! optimal position for minimizing renderstate changes, but can also be used - //! to directly modify the material of a scene node. - video::SMaterial& getMaterial(u32 i) override; + //! returns amount of materials used by this scene node. + u32 getMaterialCount() const override; - //! returns amount of materials used by this scene node. - u32 getMaterialCount() const override; + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_MESH; } - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_MESH; } + //! Sets a new mesh + void setMesh(IMesh *mesh) override; - //! Sets a new mesh - void setMesh(IMesh* mesh) override; + //! Returns the current mesh + IMesh *getMesh(void) override { return Mesh; } - //! Returns the current mesh - IMesh* getMesh(void) override { return Mesh; } + //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. + /* In this way it is possible to change the materials a mesh causing all mesh scene nodes + referencing this mesh to change too. */ + void setReadOnlyMaterials(bool readonly) override; - //! Sets if the scene node should not copy the materials of the mesh but use them in a read only style. - /* In this way it is possible to change the materials a mesh causing all mesh scene nodes - referencing this mesh to change too. */ - void setReadOnlyMaterials(bool readonly) override; + //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style + bool isReadOnlyMaterials() const override; - //! Returns if the scene node should not copy the materials of the mesh but use them in a read only style - bool isReadOnlyMaterials() const override; + //! Creates a clone of this scene node and its children. + ISceneNode *clone(ISceneNode *newParent = 0, ISceneManager *newManager = 0) override; - //! Creates a clone of this scene node and its children. - ISceneNode* clone(ISceneNode* newParent=0, ISceneManager* newManager=0) override; + //! Removes a child from this scene node. + //! Implemented here, to be able to remove the shadow properly, if there is one, + //! or to remove attached child. + bool removeChild(ISceneNode *child) override; - //! Removes a child from this scene node. - //! Implemented here, to be able to remove the shadow properly, if there is one, - //! or to remove attached child. - bool removeChild(ISceneNode* child) override; +protected: + void copyMaterials(); - protected: + core::array Materials; + core::aabbox3d Box; + video::SMaterial ReadOnlyMaterial; - void copyMaterials(); + IMesh *Mesh; - core::array Materials; - core::aabbox3d Box; - video::SMaterial ReadOnlyMaterial; - - IMesh* Mesh; - - s32 PassCount; - bool ReadOnlyMaterials; - }; + s32 PassCount; + bool ReadOnlyMaterials; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CNSOGLManager.h b/source/Irrlicht/CNSOGLManager.h index 9337e63e..cdbb221b 100644 --- a/source/Irrlicht/CNSOGLManager.h +++ b/source/Irrlicht/CNSOGLManager.h @@ -17,53 +17,53 @@ namespace irr { namespace video { - // NSOpenGL manager. - class CNSOGLManager : public IContextManager - { - public: - //! Constructor. - CNSOGLManager(); +// NSOpenGL manager. +class CNSOGLManager : public IContextManager +{ +public: + //! Constructor. + CNSOGLManager(); - //! Destructor - ~CNSOGLManager(); + //! Destructor + ~CNSOGLManager(); - // Initialize - bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) override; + // Initialize + bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) override; - // Terminate - void terminate() override; + // Terminate + void terminate() override; - // Create surface. - bool generateSurface() override; + // Create surface. + bool generateSurface() override; - // Destroy surface. - void destroySurface() override; + // Destroy surface. + void destroySurface() override; - // Create context. - bool generateContext() override; + // Create context. + bool generateContext() override; - // Destroy EGL context. - void destroyContext() override; + // Destroy EGL context. + void destroyContext() override; - //! Get current context - const SExposedVideoData& getContext() const; + //! Get current context + const SExposedVideoData &getContext() const; - //! Change render context, disable old and activate new defined by videoData - bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) override; + //! Change render context, disable old and activate new defined by videoData + bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) override; - // Get procedure address. - void* getProcAddress(const std::string &procName) override; + // Get procedure address. + void *getProcAddress(const std::string &procName) override; - // Swap buffers. - bool swapBuffers() override; + // Swap buffers. + bool swapBuffers() override; - private: - SIrrlichtCreationParameters Params; - SExposedVideoData PrimaryContext; - SExposedVideoData CurrentContext; +private: + SIrrlichtCreationParameters Params; + SExposedVideoData PrimaryContext; + SExposedVideoData CurrentContext; - NSOpenGLPixelFormat* PixelFormat; - }; + NSOpenGLPixelFormat *PixelFormat; +}; } } diff --git a/source/Irrlicht/CNSOGLManager.mm b/source/Irrlicht/CNSOGLManager.mm index fb780ef8..0988ef1c 100644 --- a/source/Irrlicht/CNSOGLManager.mm +++ b/source/Irrlicht/CNSOGLManager.mm @@ -14,8 +14,8 @@ namespace irr namespace video { -CNSOGLManager::CNSOGLManager() - : PrimaryContext(SExposedVideoData(0)), PixelFormat(nil) +CNSOGLManager::CNSOGLManager() : + PrimaryContext(SExposedVideoData(0)), PixelFormat(nil) { #ifdef _DEBUG setDebugName("CNSOGLManager"); @@ -26,11 +26,11 @@ CNSOGLManager::~CNSOGLManager() { } -bool CNSOGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata) +bool CNSOGLManager::initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &videodata) { Params = params; - return true; + return true; } void CNSOGLManager::terminate() @@ -39,138 +39,121 @@ void CNSOGLManager::terminate() bool CNSOGLManager::generateSurface() { - if (Params.DriverType == video::EDT_OPENGL) - { - int alphaSize = Params.WithAlphaChannel ? 4 : 0; - int depthSize = Params.ZBufferBits; + if (Params.DriverType == video::EDT_OPENGL) { + int alphaSize = Params.WithAlphaChannel ? 4 : 0; + int depthSize = Params.ZBufferBits; - if (Params.WithAlphaChannel && Params.Bits == 32) - alphaSize = 8; + if (Params.WithAlphaChannel && Params.Bits == 32) + alphaSize = 8; - NSOpenGLPixelFormatAttribute Attribs[] = - { - NSOpenGLPFANoRecovery, - NSOpenGLPFAAccelerated, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFADepthSize, static_cast(depthSize), - NSOpenGLPFAColorSize, Params.Bits, - NSOpenGLPFAAlphaSize, static_cast(alphaSize), - NSOpenGLPFASampleBuffers, 1, - NSOpenGLPFASamples, Params.AntiAlias, - NSOpenGLPFAStencilSize, static_cast(Params.Stencilbuffer ? 1 : 0), - //NSOpenGLPFAFullScreen, - 0 - }; + NSOpenGLPixelFormatAttribute Attribs[] = + { + NSOpenGLPFANoRecovery, + NSOpenGLPFAAccelerated, + NSOpenGLPFADoubleBuffer, + NSOpenGLPFADepthSize, static_cast(depthSize), + NSOpenGLPFAColorSize, Params.Bits, + NSOpenGLPFAAlphaSize, static_cast(alphaSize), + NSOpenGLPFASampleBuffers, 1, + NSOpenGLPFASamples, Params.AntiAlias, + NSOpenGLPFAStencilSize, static_cast(Params.Stencilbuffer ? 1 : 0), + // NSOpenGLPFAFullScreen, + 0}; - u32 Steps = 6; + u32 Steps = 6; - // Choose the best pixel format. - do - { - switch (Steps) - { - case 6: // decrease step. - --Steps; - break; - case 5: // samples - if (Attribs[12] > 2) - --Attribs[12]; - else - { - Attribs[10] = 0; - Attribs[12] = 0; - --Steps; - } - break; - case 4: // alpha - if (Attribs[8]) - { - Attribs[8] = 0; + // Choose the best pixel format. + do { + switch (Steps) { + case 6: // decrease step. + --Steps; + break; + case 5: // samples + if (Attribs[12] > 2) + --Attribs[12]; + else { + Attribs[10] = 0; + Attribs[12] = 0; + --Steps; + } + break; + case 4: // alpha + if (Attribs[8]) { + Attribs[8] = 0; - if (Params.AntiAlias) - { - Attribs[10] = 1; - Attribs[12] = Params.AntiAlias; - Steps = 5; - } - } - else - --Steps; - break; - case 3: // stencil - if (Attribs[14]) - { - Attribs[14] = 0; + if (Params.AntiAlias) { + Attribs[10] = 1; + Attribs[12] = Params.AntiAlias; + Steps = 5; + } + } else + --Steps; + break; + case 3: // stencil + if (Attribs[14]) { + Attribs[14] = 0; - if (Params.AntiAlias) - { - Attribs[10] = 1; - Attribs[12] = Params.AntiAlias; - Steps = 5; - } - } - else - --Steps; - break; - case 2: // depth size - if (Attribs[4] > 16) - { - Attribs[4] = Attribs[4] - 8; - } - else - --Steps; - break; - case 1: // buffer size - if (Attribs[6] > 16) - { - Attribs[6] = Attribs[6] - 8; - } - else - --Steps; - break; - default: - os::Printer::log("Could not get pixel format."); - return false; - } + if (Params.AntiAlias) { + Attribs[10] = 1; + Attribs[12] = Params.AntiAlias; + Steps = 5; + } + } else + --Steps; + break; + case 2: // depth size + if (Attribs[4] > 16) { + Attribs[4] = Attribs[4] - 8; + } else + --Steps; + break; + case 1: // buffer size + if (Attribs[6] > 16) { + Attribs[6] = Attribs[6] - 8; + } else + --Steps; + break; + default: + os::Printer::log("Could not get pixel format."); + return false; + } - PixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:Attribs]; - } - while (PixelFormat == nil); + PixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:Attribs]; + } while (PixelFormat == nil); - if (Params.AntiAlias && !Attribs[10]) - os::Printer::log("No multisampling."); + if (Params.AntiAlias && !Attribs[10]) + os::Printer::log("No multisampling."); - if (Params.WithAlphaChannel && !Attribs[8]) - os::Printer::log("No alpha."); + if (Params.WithAlphaChannel && !Attribs[8]) + os::Printer::log("No alpha."); - if (Params.Stencilbuffer && !Attribs[14]) - os::Printer::log("No stencil buffer."); + if (Params.Stencilbuffer && !Attribs[14]) + os::Printer::log("No stencil buffer."); - if (Params.ZBufferBits > Attribs[4]) - os::Printer::log("No full depth buffer."); + if (Params.ZBufferBits > Attribs[4]) + os::Printer::log("No full depth buffer."); - if (Params.Bits > Attribs[6]) - os::Printer::log("No full color buffer."); + if (Params.Bits > Attribs[6]) + os::Printer::log("No full color buffer."); } - return true; + return true; } void CNSOGLManager::destroySurface() { - [PixelFormat release]; - PixelFormat = nil; + [PixelFormat release]; + PixelFormat = nil; } bool CNSOGLManager::generateContext() { - NSOpenGLContext* Context = [[NSOpenGLContext alloc] initWithFormat:PixelFormat shareContext:nil]; + NSOpenGLContext *Context = [[NSOpenGLContext alloc] initWithFormat:PixelFormat shareContext:nil]; - GLint Vsync = Params.Vsync ? 1 : 0; - [Context setValues:&Vsync forParameter:NSOpenGLCPSwapInterval]; + GLint Vsync = Params.Vsync ? 1 : 0; + [Context setValues:&Vsync forParameter:NSOpenGLCPSwapInterval]; - if (Context == nil) - { + if (Context == nil) { os::Printer::log("Could not create OpenGL context.", ELL_ERROR); return false; } @@ -184,47 +167,42 @@ bool CNSOGLManager::generateContext() return true; } -const SExposedVideoData& CNSOGLManager::getContext() const +const SExposedVideoData &CNSOGLManager::getContext() const { return CurrentContext; } -bool CNSOGLManager::activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) +bool CNSOGLManager::activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) { - //TODO: handle restorePrimaryOnZero - if (videoData.OpenGLOSX.Context) - { - if ((NSOpenGLContext*)videoData.OpenGLOSX.Context != [NSOpenGLContext currentContext]) - { - [(NSOpenGLContext*)videoData.OpenGLOSX.Context makeCurrentContext]; + // TODO: handle restorePrimaryOnZero + if (videoData.OpenGLOSX.Context) { + if ((NSOpenGLContext *)videoData.OpenGLOSX.Context != [NSOpenGLContext currentContext]) { + [(NSOpenGLContext *)videoData.OpenGLOSX.Context makeCurrentContext]; - CurrentContext = videoData; - } - } - // set back to main context - else - { - if ((NSOpenGLContext*)PrimaryContext.OpenGLOSX.Context != [NSOpenGLContext currentContext]) - { - [(NSOpenGLContext*)PrimaryContext.OpenGLOSX.Context makeCurrentContext]; + CurrentContext = videoData; + } + } + // set back to main context + else { + if ((NSOpenGLContext *)PrimaryContext.OpenGLOSX.Context != [NSOpenGLContext currentContext]) { + [(NSOpenGLContext *)PrimaryContext.OpenGLOSX.Context makeCurrentContext]; - CurrentContext = PrimaryContext; - } - } + CurrentContext = PrimaryContext; + } + } return true; } void CNSOGLManager::destroyContext() { - if (CurrentContext.OpenGLOSX.Context) - { - if (PrimaryContext.OpenGLOSX.Context == CurrentContext.OpenGLOSX.Context) - PrimaryContext.OpenGLOSX.Context = nil; + if (CurrentContext.OpenGLOSX.Context) { + if (PrimaryContext.OpenGLOSX.Context == CurrentContext.OpenGLOSX.Context) + PrimaryContext.OpenGLOSX.Context = nil; - [(NSOpenGLContext*)CurrentContext.OpenGLOSX.Context makeCurrentContext]; - [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context clearDrawable]; - [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context release]; + [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context makeCurrentContext]; + [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context clearDrawable]; + [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context release]; [NSOpenGLContext clearCurrentContext]; CurrentContext.OpenGLOSX.Context = nil; @@ -233,7 +211,7 @@ void CNSOGLManager::destroyContext() // It appears that there is no separate GL proc address getter on OSX. // https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_entrypts/opengl_entrypts.html -void* CNSOGLManager::getProcAddress(const std::string &procName) +void *CNSOGLManager::getProcAddress(const std::string &procName) { NSSymbol symbol = NULL; // Allocate a buffer for the name, an underscore prefix, and a cstring terminator. @@ -245,7 +223,7 @@ void* CNSOGLManager::getProcAddress(const std::string &procName) bool CNSOGLManager::swapBuffers() { - [(NSOpenGLContext*)CurrentContext.OpenGLOSX.Context flushBuffer]; + [(NSOpenGLContext *)CurrentContext.OpenGLOSX.Context flushBuffer]; return true; } diff --git a/source/Irrlicht/CNullDriver.cpp b/source/Irrlicht/CNullDriver.cpp index e3bfb6d6..347569e6 100644 --- a/source/Irrlicht/CNullDriver.cpp +++ b/source/Irrlicht/CNullDriver.cpp @@ -17,63 +17,63 @@ #include "IReferenceCounted.h" #include "IRenderTarget.h" - namespace irr { namespace video { //! creates a loader which is able to load windows bitmaps -IImageLoader* createImageLoaderBMP(); +IImageLoader *createImageLoaderBMP(); //! creates a loader which is able to load jpeg images -IImageLoader* createImageLoaderJPG(); +IImageLoader *createImageLoaderJPG(); //! creates a loader which is able to load targa images -IImageLoader* createImageLoaderTGA(); +IImageLoader *createImageLoaderTGA(); //! creates a loader which is able to load png images -IImageLoader* createImageLoaderPNG(); +IImageLoader *createImageLoaderPNG(); //! creates a writer which is able to save jpg images -IImageWriter* createImageWriterJPG(); +IImageWriter *createImageWriterJPG(); //! creates a writer which is able to save png images -IImageWriter* createImageWriterPNG(); +IImageWriter *createImageWriterPNG(); -namespace { - //! no-op material renderer - class CDummyMaterialRenderer : public IMaterialRenderer { - public: - CDummyMaterialRenderer() {} - }; +namespace +{ +//! no-op material renderer +class CDummyMaterialRenderer : public IMaterialRenderer +{ +public: + CDummyMaterialRenderer() {} +}; } - //! constructor -CNullDriver::CNullDriver(io::IFileSystem* io, const core::dimension2d& screenSize) - : SharedRenderTarget(0), CurrentRenderTarget(0), CurrentRenderTargetSize(0, 0), FileSystem(io), MeshManipulator(0), - ViewPort(0, 0, 0, 0), ScreenSize(screenSize), PrimitivesDrawn(0), MinVertexCountForVBO(500), - TextureCreationFlags(0), OverrideMaterial2DEnabled(false), AllowZWriteOnTransparent(false) +CNullDriver::CNullDriver(io::IFileSystem *io, const core::dimension2d &screenSize) : + SharedRenderTarget(0), CurrentRenderTarget(0), CurrentRenderTargetSize(0, 0), FileSystem(io), MeshManipulator(0), + ViewPort(0, 0, 0, 0), ScreenSize(screenSize), PrimitivesDrawn(0), MinVertexCountForVBO(500), + TextureCreationFlags(0), OverrideMaterial2DEnabled(false), AllowZWriteOnTransparent(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CNullDriver"); - #endif +#endif DriverAttributes = new io::CAttributes(); DriverAttributes->addInt("MaxTextures", MATERIAL_MAX_TEXTURES); DriverAttributes->addInt("MaxSupportedTextures", MATERIAL_MAX_TEXTURES); DriverAttributes->addInt("MaxAnisotropy", 1); -// DriverAttributes->addInt("MaxUserClipPlanes", 0); -// DriverAttributes->addInt("MaxAuxBuffers", 0); + // DriverAttributes->addInt("MaxUserClipPlanes", 0); + // DriverAttributes->addInt("MaxAuxBuffers", 0); DriverAttributes->addInt("MaxMultipleRenderTargets", 1); DriverAttributes->addInt("MaxIndices", -1); DriverAttributes->addInt("MaxTextureSize", -1); -// DriverAttributes->addInt("MaxGeometryVerticesOut", 0); -// DriverAttributes->addFloat("MaxTextureLODBias", 0.f); + // DriverAttributes->addInt("MaxGeometryVerticesOut", 0); + // DriverAttributes->addFloat("MaxTextureLODBias", 0.f); DriverAttributes->addInt("Version", 1); -// DriverAttributes->addInt("ShaderLanguageVersion", 0); -// DriverAttributes->addInt("AntiAlias", 0); + // DriverAttributes->addInt("ShaderLanguageVersion", 0); + // DriverAttributes->addInt("AntiAlias", 0); setFog(); @@ -82,7 +82,7 @@ CNullDriver::CNullDriver(io::IFileSystem* io, const core::dimension2d& scre setTextureCreationFlag(ETCF_AUTO_GENERATE_MIP_MAPS, true); setTextureCreationFlag(ETCF_ALLOW_MEMORY_COPY, true); - ViewPort = core::rect(core::position2d(0,0), core::dimension2di(screenSize)); + ViewPort = core::rect(core::position2d(0, 0), core::dimension2di(screenSize)); // create manipulator MeshManipulator = new scene::CMeshManipulator(); @@ -99,18 +99,17 @@ CNullDriver::CNullDriver(io::IFileSystem* io, const core::dimension2d& scre SurfaceWriter.push_back(video::createImageWriterJPG()); SurfaceWriter.push_back(video::createImageWriterPNG()); - // set ExposedData to 0 - memset((void*)&ExposedData, 0, sizeof(ExposedData)); - for (u32 i=0; i& scre OverrideMaterial2D = InitMaterial2D; } - //! destructor CNullDriver::~CNullDriver() { @@ -140,10 +138,10 @@ CNullDriver::~CNullDriver() deleteAllTextures(); u32 i; - for (i=0; idrop(); - for (i=0; idrop(); // delete material renderers @@ -153,9 +151,8 @@ CNullDriver::~CNullDriver() removeAllHardwareBuffers(); } - //! Adds an external surface loader to the engine. -void CNullDriver::addExternalImageLoader(IImageLoader* loader) +void CNullDriver::addExternalImageLoader(IImageLoader *loader) { if (!loader) return; @@ -164,9 +161,8 @@ void CNullDriver::addExternalImageLoader(IImageLoader* loader) SurfaceLoader.push_back(loader); } - //! Adds an external surface writer to the engine. -void CNullDriver::addExternalImageWriter(IImageWriter* writer) +void CNullDriver::addExternalImageWriter(IImageWriter *writer) { if (!writer) return; @@ -175,39 +171,34 @@ void CNullDriver::addExternalImageWriter(IImageWriter* writer) SurfaceWriter.push_back(writer); } - //! Retrieve the number of image loaders u32 CNullDriver::getImageLoaderCount() const { return SurfaceLoader.size(); } - //! Retrieve the given image loader -IImageLoader* CNullDriver::getImageLoader(u32 n) +IImageLoader *CNullDriver::getImageLoader(u32 n) { if (n < SurfaceLoader.size()) return SurfaceLoader[n]; return 0; } - //! Retrieve the number of image writers u32 CNullDriver::getImageWriterCount() const { return SurfaceWriter.size(); } - //! Retrieve the given image writer -IImageWriter* CNullDriver::getImageWriter(u32 n) +IImageWriter *CNullDriver::getImageWriter(u32 n) { if (n < SurfaceWriter.size()) return SurfaceWriter[n]; return 0; } - //! deletes all textures void CNullDriver::deleteAllTextures() { @@ -217,12 +208,12 @@ void CNullDriver::deleteAllTextures() // reset render targets. - for (u32 i=0; isetTexture(0, 0); // remove textures. - for (u32 i=0; idrop(); Textures.clear(); @@ -230,7 +221,7 @@ void CNullDriver::deleteAllTextures() SharedDepthTextures.clear(); } -bool CNullDriver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) +bool CNullDriver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData &videoData, core::rect *sourceRect) { PrimitivesDrawn = 0; return true; @@ -244,50 +235,43 @@ bool CNullDriver::endScene() return true; } - //! Disable a feature of the driver. void CNullDriver::disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag) { - FeatureEnabled[feature]=!flag; + FeatureEnabled[feature] = !flag; } - //! queries the features of the driver, returns true if feature is available bool CNullDriver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const { return false; } - //! Get attributes of the actual video driver -const io::IAttributes& CNullDriver::getDriverAttributes() const +const io::IAttributes &CNullDriver::getDriverAttributes() const { return *DriverAttributes; } - //! sets transformation -void CNullDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) +void CNullDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) { } - //! Returns the transformation set by setTransform -const core::matrix4& CNullDriver::getTransform(E_TRANSFORMATION_STATE state) const +const core::matrix4 &CNullDriver::getTransform(E_TRANSFORMATION_STATE state) const { return TransformationMatrix; } - //! sets a material -void CNullDriver::setMaterial(const SMaterial& material) +void CNullDriver::setMaterial(const SMaterial &material) { } - //! Removes a texture from the texture cache and deletes it, freeing lot of //! memory. -void CNullDriver::removeTexture(ITexture* texture) +void CNullDriver::removeTexture(ITexture *texture) { if (!texture) return; @@ -307,43 +291,37 @@ void CNullDriver::removeTexture(ITexture* texture) } } - //! Removes all texture from the texture cache and deletes them, freeing lot of //! memory. void CNullDriver::removeAllTextures() { - setMaterial ( SMaterial() ); + setMaterial(SMaterial()); deleteAllTextures(); } - //! Returns amount of textures currently loaded u32 CNullDriver::getTextureCount() const { return Textures.size(); } - -ITexture* CNullDriver::addTexture(const core::dimension2d& size, const io::path& name, ECOLOR_FORMAT format) +ITexture *CNullDriver::addTexture(const core::dimension2d &size, const io::path &name, ECOLOR_FORMAT format) { - if (0 == name.size()) - { + if (0 == name.size()) { os::Printer::log("Could not create ITexture, texture needs to have a non-empty name.", ELL_WARNING); return 0; } - IImage* image = new CImage(format, size); - ITexture* t = 0; + IImage *image = new CImage(format, size); + ITexture *t = 0; - if (checkImage(image)) - { + if (checkImage(image)) { t = createDeviceDependentTexture(name, image); } image->drop(); - if (t) - { + if (t) { addTexture(t); t->drop(); } @@ -351,10 +329,9 @@ ITexture* CNullDriver::addTexture(const core::dimension2d& size, const io:: return t; } -ITexture* CNullDriver::addTexture(const io::path& name, IImage* image) +ITexture *CNullDriver::addTexture(const io::path &name, IImage *image) { - if (0 == name.size()) - { + if (0 == name.size()) { os::Printer::log("Could not create ITexture, texture needs to have a non-empty name.", ELL_WARNING); return 0; } @@ -362,15 +339,13 @@ ITexture* CNullDriver::addTexture(const io::path& name, IImage* image) if (!image) return 0; - ITexture* t = 0; + ITexture *t = 0; - if (checkImage(image)) - { + if (checkImage(image)) { t = createDeviceDependentTexture(name, image); } - if (t) - { + if (t) { addTexture(t); t->drop(); } @@ -378,15 +353,15 @@ ITexture* CNullDriver::addTexture(const io::path& name, IImage* image) return t; } -ITexture* CNullDriver::addTextureCubemap(const io::path& name, IImage* imagePosX, IImage* imageNegX, IImage* imagePosY, - IImage* imageNegY, IImage* imagePosZ, IImage* imageNegZ) +ITexture *CNullDriver::addTextureCubemap(const io::path &name, IImage *imagePosX, IImage *imageNegX, IImage *imagePosY, + IImage *imageNegY, IImage *imagePosZ, IImage *imageNegZ) { if (0 == name.size() || !imagePosX || !imageNegX || !imagePosY || !imageNegY || !imagePosZ || !imageNegZ) return 0; - ITexture* t = 0; + ITexture *t = 0; - core::array imageArray(6); + core::array imageArray(6); imageArray.push_back(imagePosX); imageArray.push_back(imageNegX); imageArray.push_back(imagePosY); @@ -394,13 +369,11 @@ ITexture* CNullDriver::addTextureCubemap(const io::path& name, IImage* imagePosX imageArray.push_back(imagePosZ); imageArray.push_back(imageNegZ); - if (checkImage(imageArray)) - { + if (checkImage(imageArray)) { t = createDeviceDependentTextureCubemap(name, imageArray); } - if (t) - { + if (t) { addTexture(t); t->drop(); } @@ -408,75 +381,67 @@ ITexture* CNullDriver::addTextureCubemap(const io::path& name, IImage* imagePosX return t; } -ITexture* CNullDriver::addTextureCubemap(const irr::u32 sideLen, const io::path& name, ECOLOR_FORMAT format) +ITexture *CNullDriver::addTextureCubemap(const irr::u32 sideLen, const io::path &name, ECOLOR_FORMAT format) { - if ( 0 == sideLen ) + if (0 == sideLen) return 0; - if (0 == name.size()) - { + if (0 == name.size()) { os::Printer::log("Could not create ITexture, texture needs to have a non-empty name.", ELL_WARNING); return 0; } - core::array imageArray(6); - for ( int i=0; i < 6; ++i ) + core::array imageArray(6); + for (int i = 0; i < 6; ++i) imageArray.push_back(new CImage(format, core::dimension2du(sideLen, sideLen))); - ITexture* t = 0; - if (checkImage(imageArray)) - { + ITexture *t = 0; + if (checkImage(imageArray)) { t = createDeviceDependentTextureCubemap(name, imageArray); - if (t) - { + if (t) { addTexture(t); t->drop(); } } - for ( int i=0; i < 6; ++i ) + for (int i = 0; i < 6; ++i) imageArray[i]->drop(); return t; } //! loads a Texture -ITexture* CNullDriver::getTexture(const io::path& filename) +ITexture *CNullDriver::getTexture(const io::path &filename) { // Identify textures by their absolute filenames if possible. const io::path absolutePath = FileSystem->getAbsolutePath(filename); - ITexture* texture = findTexture(absolutePath); - if (texture) - { + ITexture *texture = findTexture(absolutePath); + if (texture) { texture->updateSource(ETS_FROM_CACHE); return texture; } // Then try the raw filename, which might be in an Archive texture = findTexture(filename); - if (texture) - { + if (texture) { texture->updateSource(ETS_FROM_CACHE); return texture; } // Now try to open the file using the complete path. - io::IReadFile* file = FileSystem->createAndOpenFile(absolutePath); + io::IReadFile *file = FileSystem->createAndOpenFile(absolutePath); - if (!file) - { + if (!file) { // Try to open it using the raw filename. file = FileSystem->createAndOpenFile(filename); } - if (file) - { + if (file) { // Re-check name for actual archive names texture = findTexture(file->getFileName()); - if (texture) - { + if (texture) { texture->updateSource(ETS_FROM_CACHE); file->drop(); return texture; @@ -485,43 +450,35 @@ ITexture* CNullDriver::getTexture(const io::path& filename) texture = loadTextureFromFile(file); file->drop(); - if (texture) - { + if (texture) { texture->updateSource(ETS_FROM_FILE); addTexture(texture); texture->drop(); // drop it because we created it, one grab too much - } - else + } else os::Printer::log("Could not load texture", filename, ELL_ERROR); return texture; - } - else - { + } else { os::Printer::log("Could not open file of texture", filename, ELL_WARNING); return 0; } } - //! loads a Texture -ITexture* CNullDriver::getTexture(io::IReadFile* file) +ITexture *CNullDriver::getTexture(io::IReadFile *file) { - ITexture* texture = 0; + ITexture *texture = 0; - if (file) - { + if (file) { texture = findTexture(file->getFileName()); - if (texture) - { + if (texture) { texture->updateSource(ETS_FROM_CACHE); return texture; } texture = loadTextureFromFile(file); - if (texture) - { + if (texture) { texture->updateSource(ETS_FROM_FILE); addTexture(texture); texture->drop(); // drop it because we created it, one grab too much @@ -534,9 +491,8 @@ ITexture* CNullDriver::getTexture(io::IReadFile* file) return texture; } - //! opens the file and loads it into the surface -video::ITexture* CNullDriver::loadTextureFromFile(io::IReadFile* file, const io::path& hashName ) +video::ITexture *CNullDriver::loadTextureFromFile(io::IReadFile *file, const io::path &hashName) { ITexture *texture = nullptr; @@ -555,12 +511,10 @@ video::ITexture* CNullDriver::loadTextureFromFile(io::IReadFile* file, const io: return texture; } - //! adds a surface, not loaded or created by the Irrlicht Engine -void CNullDriver::addTexture(video::ITexture* texture) +void CNullDriver::addTexture(video::ITexture *texture) { - if (texture) - { + if (texture) { SSurface s; s.Surface = texture; texture->grab(); @@ -573,9 +527,8 @@ void CNullDriver::addTexture(video::ITexture* texture) } } - //! looks if the image is already loaded -video::ITexture* CNullDriver::findTexture(const io::path& filename) +video::ITexture *CNullDriver::findTexture(const io::path &filename) { SSurface s; SDummyTexture dummy(filename, ETT_2D); @@ -588,38 +541,35 @@ video::ITexture* CNullDriver::findTexture(const io::path& filename) return 0; } -ITexture* CNullDriver::createDeviceDependentTexture(const io::path& name, IImage* image) +ITexture *CNullDriver::createDeviceDependentTexture(const io::path &name, IImage *image) { - SDummyTexture* dummy = new SDummyTexture(name, ETT_2D); + SDummyTexture *dummy = new SDummyTexture(name, ETT_2D); dummy->setSize(image->getDimension()); return dummy; } -ITexture* CNullDriver::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) +ITexture *CNullDriver::createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) { return new SDummyTexture(name, ETT_CUBEMAP); } -bool CNullDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) +bool CNullDriver::setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) { return false; } -bool CNullDriver::setRenderTarget(ITexture* texture, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) +bool CNullDriver::setRenderTarget(ITexture *texture, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) { - if (texture) - { + if (texture) { // create render target if require. if (!SharedRenderTarget) SharedRenderTarget = addRenderTarget(); - ITexture* depthTexture = 0; + ITexture *depthTexture = 0; // try to find available depth texture with require size. - for (u32 i = 0; i < SharedDepthTextures.size(); ++i) - { - if (SharedDepthTextures[i]->getSize() == texture->getSize()) - { + for (u32 i = 0; i < SharedDepthTextures.size(); ++i) { + if (SharedDepthTextures[i]->getSize() == texture->getSize()) { depthTexture = SharedDepthTextures[i]; break; @@ -627,8 +577,7 @@ bool CNullDriver::setRenderTarget(ITexture* texture, u16 clearFlag, SColor clear } // create depth texture if require. - if (!depthTexture) - { + if (!depthTexture) { depthTexture = addRenderTargetTexture(texture->getSize(), "IRR_DEPTH_STENCIL", video::ECF_D24S8); SharedDepthTextures.push_back(depthTexture); } @@ -636,53 +585,46 @@ bool CNullDriver::setRenderTarget(ITexture* texture, u16 clearFlag, SColor clear SharedRenderTarget->setTexture(texture, depthTexture); return setRenderTargetEx(SharedRenderTarget, clearFlag, clearColor, clearDepth, clearStencil); - } - else - { + } else { return setRenderTargetEx(0, clearFlag, clearColor, clearDepth, clearStencil); } } //! sets a viewport -void CNullDriver::setViewPort(const core::rect& area) +void CNullDriver::setViewPort(const core::rect &area) { } - //! gets the area of the current viewport -const core::rect& CNullDriver::getViewPort() const +const core::rect &CNullDriver::getViewPort() const { return ViewPort; } - //! draws a vertex primitive list -void CNullDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) +void CNullDriver::drawVertexPrimitiveList(const void *vertices, u32 vertexCount, const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { - if ((iType==EIT_16BIT) && (vertexCount>65536)) + if ((iType == EIT_16BIT) && (vertexCount > 65536)) os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur."); PrimitivesDrawn += primitiveCount; } - //! draws a vertex primitive list in 2d -void CNullDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) +void CNullDriver::draw2DVertexPrimitiveList(const void *vertices, u32 vertexCount, const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { - if ((iType==EIT_16BIT) && (vertexCount>65536)) + if ((iType == EIT_16BIT) && (vertexCount > 65536)) os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur."); PrimitivesDrawn += primitiveCount; } - //! Draws a 3d line. -void CNullDriver::draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color) +void CNullDriver::draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color) { } - //! Draws a 3d axis aligned box. -void CNullDriver::draw3DBox(const core::aabbox3d& box, SColor color) +void CNullDriver::draw3DBox(const core::aabbox3d &box, SColor color) { core::vector3df edges[8]; box.getEdges(edges); @@ -703,109 +645,92 @@ void CNullDriver::draw3DBox(const core::aabbox3d& box, SColor color) draw3DLine(edges[5], edges[4], color); } - - //! draws an 2d image -void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, bool useAlphaChannelOfTexture) +void CNullDriver::draw2DImage(const video::ITexture *texture, const core::position2d &destPos, bool useAlphaChannelOfTexture) { if (!texture) return; - draw2DImage(texture,destPos, core::rect(core::position2d(0,0), - core::dimension2di(texture->getOriginalSize())), - 0, - SColor(255,255,255,255), - useAlphaChannelOfTexture - ); + draw2DImage(texture, destPos, core::rect(core::position2d(0, 0), core::dimension2di(texture->getOriginalSize())), + 0, + SColor(255, 255, 255, 255), + useAlphaChannelOfTexture); } - //! draws a set of 2d images, using a color and the alpha channel of the //! texture if desired. -void CNullDriver::draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) +void CNullDriver::draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, + bool useAlphaChannelOfTexture) { const irr::u32 drawCount = core::min_(positions.size(), sourceRects.size()); - for (u32 i=0; i& destRect, - const core::rect& sourceRect, const core::rect* clipRect, - const video::SColor* const colors, bool useAlphaChannelOfTexture) +void CNullDriver::draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect, + const video::SColor *const colors, bool useAlphaChannelOfTexture) { if (destRect.isValid()) draw2DImage(texture, core::position2d(destRect.UpperLeftCorner), - sourceRect, clipRect, colors?colors[0]:video::SColor(0xffffffff), + sourceRect, clipRect, colors ? colors[0] : video::SColor(0xffffffff), useAlphaChannelOfTexture); } - //! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted. -void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, - const core::rect* clipRect, SColor color, - bool useAlphaChannelOfTexture) +void CNullDriver::draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, + const core::rect *clipRect, SColor color, + bool useAlphaChannelOfTexture) { } - //! Draw a 2d rectangle -void CNullDriver::draw2DRectangle(SColor color, const core::rect& pos, const core::rect* clip) +void CNullDriver::draw2DRectangle(SColor color, const core::rect &pos, const core::rect *clip) { draw2DRectangle(pos, color, color, color, color, clip); } - - //! Draws a 2d rectangle with a gradient. -void CNullDriver::draw2DRectangle(const core::rect& pos, - SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip) +void CNullDriver::draw2DRectangle(const core::rect &pos, + SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip) { } - - //! Draws a 2d line. -void CNullDriver::draw2DLine(const core::position2d& start, - const core::position2d& end, SColor color) +void CNullDriver::draw2DLine(const core::position2d &start, + const core::position2d &end, SColor color) { } - //! returns color format ECOLOR_FORMAT CNullDriver::getColorFormat() const { return ECF_R5G6B5; } - //! returns screen size -const core::dimension2d& CNullDriver::getScreenSize() const +const core::dimension2d &CNullDriver::getScreenSize() const { return ScreenSize; } - //! get current render target -IRenderTarget* CNullDriver::getCurrentRenderTarget() const +IRenderTarget *CNullDriver::getCurrentRenderTarget() const { return CurrentRenderTarget; } - -const core::dimension2d& CNullDriver::getCurrentRenderTargetSize() const +const core::dimension2d &CNullDriver::getCurrentRenderTargetSize() const { if (CurrentRenderTargetSize.Width == 0) return ScreenSize; @@ -813,33 +738,29 @@ const core::dimension2d& CNullDriver::getCurrentRenderTargetSize() const return CurrentRenderTargetSize; } - // returns current frames per second value s32 CNullDriver::getFPS() const { return FPSCounter.getFPS(); } - - //! returns amount of primitives (mostly triangles) were drawn in the last frame. //! very useful method for statistics. -u32 CNullDriver::getPrimitiveCountDrawn( u32 param ) const +u32 CNullDriver::getPrimitiveCountDrawn(u32 param) const { - return (0 == param) ? FPSCounter.getPrimitive() : (1 == param) ? FPSCounter.getPrimitiveAverage() : FPSCounter.getPrimitiveTotal(); + return (0 == param) ? FPSCounter.getPrimitive() : (1 == param) ? FPSCounter.getPrimitiveAverage() + : FPSCounter.getPrimitiveTotal(); } - - //! Sets the dynamic ambient light color. The default color is //! (0,0,0,0) which means it is dark. //! \param color: New color of the ambient light. -void CNullDriver::setAmbientLight(const SColorf& color) +void CNullDriver::setAmbientLight(const SColorf &color) { AmbientLight = color; } -const SColorf& CNullDriver::getAmbientLight() const +const SColorf &CNullDriver::getAmbientLight() const { return AmbientLight; } @@ -847,32 +768,28 @@ const SColorf& CNullDriver::getAmbientLight() const //! \return Returns the name of the video driver. Example: In case of the DIRECT3D8 //! driver, it would return "Direct3D8". -const char* CNullDriver::getName() const +const char *CNullDriver::getName() const { return "Irrlicht NullDevice"; } - //! Creates a boolean alpha channel of the texture based of an color key. -void CNullDriver::makeColorKeyTexture(video::ITexture* texture, - video::SColor color) const +void CNullDriver::makeColorKeyTexture(video::ITexture *texture, + video::SColor color) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && - texture->getColorFormat() != ECF_A8R8G8B8 ) - { + texture->getColorFormat() != ECF_A8R8G8B8) { os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR); return; } - if (texture->getColorFormat() == ECF_A1R5G5B5) - { - u16 *p = (u16*)texture->lock(); + if (texture->getColorFormat() == ECF_A1R5G5B5) { + u16 *p = (u16 *)texture->lock(); - if (!p) - { + if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } @@ -885,24 +802,20 @@ void CNullDriver::makeColorKeyTexture(video::ITexture* texture, const u32 pixels = pitch * dim.Height; - for (u32 pixel = 0; pixel < pixels; ++ pixel) - { + for (u32 pixel = 0; pixel < pixels; ++pixel) { // If the color matches the reference color, ignoring alphas, // set the alpha to zero. - if(((*p) & 0x7fff) == refZeroAlpha) + if (((*p) & 0x7fff) == refZeroAlpha) (*p) = refZeroAlpha; ++p; } texture->unlock(); - } - else - { - u32 *p = (u32*)texture->lock(); + } else { + u32 *p = (u32 *)texture->lock(); - if (!p) - { + if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } @@ -914,12 +827,11 @@ void CNullDriver::makeColorKeyTexture(video::ITexture* texture, const u32 refZeroAlpha = 0x00ffffff & color.color; const u32 pixels = pitch * dim.Height; - for (u32 pixel = 0; pixel < pixels; ++ pixel) - { + for (u32 pixel = 0; pixel < pixels; ++pixel) { // If the color matches the reference color, ignoring alphas, // set the alpha to zero. - if(((*p) & 0x00ffffff) == refZeroAlpha) - (*p) = refZeroAlpha; + if (((*p) & 0x00ffffff) == refZeroAlpha) + (*p) = refZeroAlpha; ++p; } @@ -929,59 +841,50 @@ void CNullDriver::makeColorKeyTexture(video::ITexture* texture, texture->regenerateMipMapLevels(); } - - //! Creates an boolean alpha channel of the texture based of an color key position. -void CNullDriver::makeColorKeyTexture(video::ITexture* texture, - core::position2d colorKeyPixelPos) const +void CNullDriver::makeColorKeyTexture(video::ITexture *texture, + core::position2d colorKeyPixelPos) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && - texture->getColorFormat() != ECF_A8R8G8B8 ) - { + texture->getColorFormat() != ECF_A8R8G8B8) { os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR); return; } SColor colorKey; - if (texture->getColorFormat() == ECF_A1R5G5B5) - { - u16 *p = (u16*)texture->lock(ETLM_READ_ONLY); + if (texture->getColorFormat() == ECF_A1R5G5B5) { + u16 *p = (u16 *)texture->lock(ETLM_READ_ONLY); - if (!p) - { + if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 2; - const u16 key16Bit = 0x7fff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X]; + const u16 key16Bit = 0x7fff & p[colorKeyPixelPos.Y * pitch + colorKeyPixelPos.X]; colorKey = video::A1R5G5B5toA8R8G8B8(key16Bit); - } - else - { - u32 *p = (u32*)texture->lock(ETLM_READ_ONLY); + } else { + u32 *p = (u32 *)texture->lock(ETLM_READ_ONLY); - if (!p) - { + if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 4; - colorKey = 0x00ffffff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X]; + colorKey = 0x00ffffff & p[colorKeyPixelPos.Y * pitch + colorKeyPixelPos.X]; } texture->unlock(); makeColorKeyTexture(texture, colorKey); } - //! Returns the maximum amount of primitives (mostly vertices) which //! the device is able to render with one drawIndexedTriangleList //! call. @@ -990,14 +893,12 @@ u32 CNullDriver::getMaximalPrimitiveCount() const return 0xFFFFFFFF; } - //! checks triangle count and print warning if wrong bool CNullDriver::checkPrimitiveCount(u32 prmCount) const { const u32 m = getMaximalPrimitiveCount(); - if (prmCount > m) - { + if (prmCount > m) { char tmp[128]; snprintf_irr(tmp, sizeof(tmp), "Could not draw triangles, too many primitives(%u), maximum is %u.", prmCount, m); os::Printer::log(tmp, ELL_ERROR); @@ -1012,7 +913,7 @@ bool CNullDriver::checkImage(IImage *image) const return true; } -bool CNullDriver::checkImage(const core::array& image) const +bool CNullDriver::checkImage(const core::array &image) const { if (!image.size()) return false; @@ -1036,9 +937,7 @@ bool CNullDriver::checkImage(const core::array& image) const //! Enables or disables a texture creation flag. void CNullDriver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled) { - if (enabled && ((flag == ETCF_ALWAYS_16_BIT) || (flag == ETCF_ALWAYS_32_BIT) - || (flag == ETCF_OPTIMIZED_FOR_QUALITY) || (flag == ETCF_OPTIMIZED_FOR_SPEED))) - { + if (enabled && ((flag == ETCF_ALWAYS_16_BIT) || (flag == ETCF_ALWAYS_32_BIT) || (flag == ETCF_OPTIMIZED_FOR_QUALITY) || (flag == ETCF_OPTIMIZED_FOR_SPEED))) { // disable other formats setTextureCreationFlag(ETCF_ALWAYS_16_BIT, false); setTextureCreationFlag(ETCF_ALWAYS_32_BIT, false); @@ -1048,22 +947,21 @@ void CNullDriver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enab // set flag TextureCreationFlags = (TextureCreationFlags & (~flag)) | - ((((u32)!enabled)-1) & flag); + ((((u32)!enabled) - 1) & flag); } - //! Returns if a texture creation flag is enabled or disabled. bool CNullDriver::getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const { - return (TextureCreationFlags & flag)!=0; + return (TextureCreationFlags & flag) != 0; } -IImage *CNullDriver::createImageFromFile(const io::path& filename) +IImage *CNullDriver::createImageFromFile(const io::path &filename) { if (!filename.size()) return nullptr; - io::IReadFile* file = FileSystem->createAndOpenFile(filename); + io::IReadFile *file = FileSystem->createAndOpenFile(filename); if (!file) { os::Printer::log("Could not open file of image", filename, ELL_WARNING); return nullptr; @@ -1074,7 +972,7 @@ IImage *CNullDriver::createImageFromFile(const io::path& filename) return image; } -IImage *CNullDriver::createImageFromFile(io::IReadFile* file) +IImage *CNullDriver::createImageFromFile(io::IReadFile *file) { if (!file) return nullptr; @@ -1092,7 +990,7 @@ IImage *CNullDriver::createImageFromFile(io::IReadFile* file) // try to load file based on what is in it for (int i = SurfaceLoader.size() - 1; i >= 0; --i) { if (SurfaceLoader[i]->isALoadableFileExtension(file->getFileName())) - continue; // extension was tried above already + continue; // extension was tried above already file->seek(0); // dito if (!SurfaceLoader[i]->isALoadableFileFormat(file)) continue; @@ -1105,12 +1003,11 @@ IImage *CNullDriver::createImageFromFile(io::IReadFile* file) return nullptr; } - //! Writes the provided image to disk file -bool CNullDriver::writeImageToFile(IImage* image, const io::path& filename,u32 param) +bool CNullDriver::writeImageToFile(IImage *image, const io::path &filename, u32 param) { - io::IWriteFile* file = FileSystem->createAndWriteFile(filename); - if(!file) + io::IWriteFile *file = FileSystem->createAndWriteFile(filename); + if (!file) return false; bool result = writeImageToFile(image, file, param); @@ -1120,15 +1017,13 @@ bool CNullDriver::writeImageToFile(IImage* image, const io::path& filename,u32 p } //! Writes the provided image to a file. -bool CNullDriver::writeImageToFile(IImage* image, io::IWriteFile * file, u32 param) +bool CNullDriver::writeImageToFile(IImage *image, io::IWriteFile *file, u32 param) { - if(!file) + if (!file) return false; - for (s32 i=SurfaceWriter.size()-1; i>=0; --i) - { - if (SurfaceWriter[i]->isAWriteableFileExtension(file->getFileName())) - { + for (s32 i = SurfaceWriter.size() - 1; i >= 0; --i) { + if (SurfaceWriter[i]->isAWriteableFileExtension(file->getFileName())) { bool written = SurfaceWriter[i]->writeImage(file, image, param); if (written) return true; @@ -1137,54 +1032,47 @@ bool CNullDriver::writeImageToFile(IImage* image, io::IWriteFile * file, u32 par return false; // failed to write } - //! Creates a software image from a byte array. -IImage* CNullDriver::createImageFromData(ECOLOR_FORMAT format, - const core::dimension2d& size, void *data, bool ownForeignMemory, - bool deleteMemory) +IImage *CNullDriver::createImageFromData(ECOLOR_FORMAT format, + const core::dimension2d &size, void *data, bool ownForeignMemory, + bool deleteMemory) { return new CImage(format, size, data, ownForeignMemory, deleteMemory); } - //! Creates an empty software image. -IImage* CNullDriver::createImage(ECOLOR_FORMAT format, const core::dimension2d& size) +IImage *CNullDriver::createImage(ECOLOR_FORMAT format, const core::dimension2d &size) { return new CImage(format, size); } - //! Creates a software image from part of a texture. -IImage* CNullDriver::createImage(ITexture* texture, const core::position2d& pos, const core::dimension2d& size) +IImage *CNullDriver::createImage(ITexture *texture, const core::position2d &pos, const core::dimension2d &size) { - if ((pos==core::position2di(0,0)) && (size == texture->getSize())) - { - void * data = texture->lock(ETLM_READ_ONLY); - if ( !data) + if ((pos == core::position2di(0, 0)) && (size == texture->getSize())) { + void *data = texture->lock(ETLM_READ_ONLY); + if (!data) return 0; - IImage* image = new CImage(texture->getColorFormat(), size, data, false, false); + IImage *image = new CImage(texture->getColorFormat(), size, data, false, false); texture->unlock(); return image; - } - else - { + } else { // make sure to avoid buffer overruns // make the vector a separate variable for g++ 3.x const core::vector2d leftUpper(core::clamp(static_cast(pos.X), 0u, texture->getSize().Width), - core::clamp(static_cast(pos.Y), 0u, texture->getSize().Height)); + core::clamp(static_cast(pos.Y), 0u, texture->getSize().Height)); const core::rect clamped(leftUpper, - core::dimension2du(core::clamp(static_cast(size.Width), 0u, texture->getSize().Width), - core::clamp(static_cast(size.Height), 0u, texture->getSize().Height))); + core::dimension2du(core::clamp(static_cast(size.Width), 0u, texture->getSize().Width), + core::clamp(static_cast(size.Height), 0u, texture->getSize().Height))); if (!clamped.isValid()) return 0; - u8* src = static_cast(texture->lock(ETLM_READ_ONLY)); + u8 *src = static_cast(texture->lock(ETLM_READ_ONLY)); if (!src) return 0; - IImage* image = new CImage(texture->getColorFormat(), clamped.getSize()); - u8* dst = static_cast(image->getData()); + IImage *image = new CImage(texture->getColorFormat(), clamped.getSize()); + u8 *dst = static_cast(image->getData()); src += clamped.UpperLeftCorner.Y * texture->getPitch() + image->getBytesPerPixel() * clamped.UpperLeftCorner.X; - for (u32 i=0; igetColorFormat(), clamped.getWidth(), dst, image->getColorFormat()); src += texture->getPitch(); dst += image->getPitch(); @@ -1194,7 +1082,6 @@ IImage* CNullDriver::createImage(ITexture* texture, const core::position2d& } } - //! Sets the fog mode. void CNullDriver::setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, f32 density, bool pixelFog, bool rangeFog) @@ -1209,8 +1096,8 @@ void CNullDriver::setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, } //! Gets the fog mode. -void CNullDriver::getFog(SColor& color, E_FOG_TYPE& fogType, f32& start, f32& end, - f32& density, bool& pixelFog, bool& rangeFog) +void CNullDriver::getFog(SColor &color, E_FOG_TYPE &fogType, f32 &start, f32 &end, + f32 &density, bool &pixelFog, bool &rangeFog) { color = FogColor; fogType = FogType; @@ -1222,13 +1109,13 @@ void CNullDriver::getFog(SColor& color, E_FOG_TYPE& fogType, f32& start, f32& en } //! Draws a mesh buffer -void CNullDriver::drawMeshBuffer(const scene::IMeshBuffer* mb) +void CNullDriver::drawMeshBuffer(const scene::IMeshBuffer *mb) { if (!mb) return; - //IVertexBuffer and IIndexBuffer later - SHWBufferLink *HWBuffer=getBufferLink(mb); + // IVertexBuffer and IIndexBuffer later + SHWBufferLink *HWBuffer = getBufferLink(mb); if (HWBuffer) drawHardwareBuffer(HWBuffer); @@ -1236,39 +1123,35 @@ void CNullDriver::drawMeshBuffer(const scene::IMeshBuffer* mb) drawVertexPrimitiveList(mb->getVertices(), mb->getVertexCount(), mb->getIndices(), mb->getPrimitiveCount(), mb->getVertexType(), mb->getPrimitiveType(), mb->getIndexType()); } - //! Draws the normals of a mesh buffer -void CNullDriver::drawMeshBufferNormals(const scene::IMeshBuffer* mb, f32 length, SColor color) +void CNullDriver::drawMeshBufferNormals(const scene::IMeshBuffer *mb, f32 length, SColor color) { const u32 count = mb->getVertexCount(); const bool normalize = mb->getMaterial().NormalizeNormals; - for (u32 i=0; i < count; ++i) - { + for (u32 i = 0; i < count; ++i) { core::vector3df normalizedNormal = mb->getNormal(i); if (normalize) normalizedNormal.normalize(); - const core::vector3df& pos = mb->getPosition(i); + const core::vector3df &pos = mb->getPosition(i); draw3DLine(pos, pos + (normalizedNormal * length), color); } } - -CNullDriver::SHWBufferLink *CNullDriver::getBufferLink(const scene::IMeshBuffer* mb) +CNullDriver::SHWBufferLink *CNullDriver::getBufferLink(const scene::IMeshBuffer *mb) { if (!mb || !isHardwareBufferRecommend(mb)) return 0; - //search for hardware links - SHWBufferLink *HWBuffer = reinterpret_cast(mb->getHWBuffer()); + // search for hardware links + SHWBufferLink *HWBuffer = reinterpret_cast(mb->getHWBuffer()); if (HWBuffer) return HWBuffer; - return createHardwareBuffer(mb); //no hardware links, and mesh wants one, create it + return createHardwareBuffer(mb); // no hardware links, and mesh wants one, create it } - //! Update all hardware buffers, remove unused ones void CNullDriver::updateAllHardwareBuffers() { @@ -1282,7 +1165,6 @@ void CNullDriver::updateAllHardwareBuffers() } } - void CNullDriver::deleteHardwareBuffer(SHWBufferLink *HWBuffer) { if (!HWBuffer) @@ -1291,18 +1173,16 @@ void CNullDriver::deleteHardwareBuffer(SHWBufferLink *HWBuffer) delete HWBuffer; } - //! Remove hardware buffer -void CNullDriver::removeHardwareBuffer(const scene::IMeshBuffer* mb) +void CNullDriver::removeHardwareBuffer(const scene::IMeshBuffer *mb) { if (!mb) return; - SHWBufferLink *HWBuffer = reinterpret_cast(mb->getHWBuffer()); + SHWBufferLink *HWBuffer = reinterpret_cast(mb->getHWBuffer()); if (HWBuffer) deleteHardwareBuffer(HWBuffer); } - //! Remove all hardware buffers void CNullDriver::removeAllHardwareBuffers() { @@ -1310,173 +1190,150 @@ void CNullDriver::removeAllHardwareBuffers() deleteHardwareBuffer(HWBufferList.front()); } - -bool CNullDriver::isHardwareBufferRecommend(const scene::IMeshBuffer* mb) +bool CNullDriver::isHardwareBufferRecommend(const scene::IMeshBuffer *mb) { - if (!mb || (mb->getHardwareMappingHint_Index()==scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex()==scene::EHM_NEVER)) + if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) return false; - if (mb->getVertexCount()getVertexCount() < MinVertexCountForVBO) return false; return true; } - //! Create occlusion query. /** Use node for identification and mesh for occlusion test. */ -void CNullDriver::addOcclusionQuery(scene::ISceneNode* node, const scene::IMesh* mesh) +void CNullDriver::addOcclusionQuery(scene::ISceneNode *node, const scene::IMesh *mesh) { if (!node) return; - if (!mesh) - { + if (!mesh) { if ((node->getType() != scene::ESNT_MESH) && (node->getType() != scene::ESNT_ANIMATED_MESH)) return; else if (node->getType() == scene::ESNT_MESH) - mesh = static_cast(node)->getMesh(); + mesh = static_cast(node)->getMesh(); else - mesh = static_cast(node)->getMesh()->getMesh(0); + mesh = static_cast(node)->getMesh()->getMesh(0); if (!mesh) return; } - //search for query + // search for query s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index != -1) - { - if (OcclusionQueries[index].Mesh != mesh) - { + if (index != -1) { + if (OcclusionQueries[index].Mesh != mesh) { OcclusionQueries[index].Mesh->drop(); OcclusionQueries[index].Mesh = mesh; mesh->grab(); } - } - else - { + } else { OcclusionQueries.push_back(SOccQuery(node, mesh)); node->setAutomaticCulling(node->getAutomaticCulling() | scene::EAC_OCC_QUERY); } } - //! Remove occlusion query. -void CNullDriver::removeOcclusionQuery(scene::ISceneNode* node) +void CNullDriver::removeOcclusionQuery(scene::ISceneNode *node) { - //search for query + // search for query s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index != -1) - { + if (index != -1) { node->setAutomaticCulling(node->getAutomaticCulling() & ~scene::EAC_OCC_QUERY); OcclusionQueries.erase(index); } } - //! Remove all occlusion queries. void CNullDriver::removeAllOcclusionQueries() { - for (s32 i=OcclusionQueries.size()-1; i>=0; --i) - { + for (s32 i = OcclusionQueries.size() - 1; i >= 0; --i) { removeOcclusionQuery(OcclusionQueries[i].Node); } } - //! Run occlusion query. Draws mesh stored in query. /** If the mesh shall be rendered visible, use flag to enable the proper material setting. */ -void CNullDriver::runOcclusionQuery(scene::ISceneNode* node, bool visible) +void CNullDriver::runOcclusionQuery(scene::ISceneNode *node, bool visible) { - if(!node) + if (!node) return; s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index==-1) + if (index == -1) return; - OcclusionQueries[index].Run=0; - if (!visible) - { + OcclusionQueries[index].Run = 0; + if (!visible) { SMaterial mat; - mat.Lighting=false; - mat.AntiAliasing=0; - mat.ColorMask=ECP_NONE; - mat.GouraudShading=false; - mat.ZWriteEnable=EZW_OFF; + mat.Lighting = false; + mat.AntiAliasing = 0; + mat.ColorMask = ECP_NONE; + mat.GouraudShading = false; + mat.ZWriteEnable = EZW_OFF; setMaterial(mat); } setTransform(video::ETS_WORLD, node->getAbsoluteTransformation()); - const scene::IMesh* mesh = OcclusionQueries[index].Mesh; - for (u32 i=0; igetMeshBufferCount(); ++i) - { + const scene::IMesh *mesh = OcclusionQueries[index].Mesh; + for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) { if (visible) setMaterial(mesh->getMeshBuffer(i)->getMaterial()); drawMeshBuffer(mesh->getMeshBuffer(i)); } } - //! Run all occlusion queries. Draws all meshes stored in queries. /** If the meshes shall not be rendered visible, use overrideMaterial to disable the color and depth buffer. */ void CNullDriver::runAllOcclusionQueries(bool visible) { - for (u32 i=0; i1000) + if (OcclusionQueries[i].Run > 1000) removeOcclusionQuery(OcclusionQueries[i].Node); } } - //! Return query result. /** Return value is the number of visible pixels/fragments. The value is a safe approximation, i.e. can be larger then the actual value of pixels. */ -u32 CNullDriver::getOcclusionQueryResult(scene::ISceneNode* node) const +u32 CNullDriver::getOcclusionQueryResult(scene::ISceneNode *node) const { return ~0; } - //! Create render target. -IRenderTarget* CNullDriver::addRenderTarget() +IRenderTarget *CNullDriver::addRenderTarget() { return 0; } - //! Remove render target. -void CNullDriver::removeRenderTarget(IRenderTarget* renderTarget) +void CNullDriver::removeRenderTarget(IRenderTarget *renderTarget) { if (!renderTarget) return; - for (u32 i = 0; i < RenderTargets.size(); ++i) - { - if (RenderTargets[i] == renderTarget) - { + for (u32 i = 0; i < RenderTargets.size(); ++i) { + if (RenderTargets[i] == renderTarget) { RenderTargets[i]->drop(); RenderTargets.erase(i); @@ -1485,7 +1342,6 @@ void CNullDriver::removeRenderTarget(IRenderTarget* renderTarget) } } - //! Remove all render targets. void CNullDriver::removeAllRenderTargets() { @@ -1497,22 +1353,20 @@ void CNullDriver::removeAllRenderTargets() SharedRenderTarget = 0; } - //! Only used by the internal engine. Used to notify the driver that //! the window was resized. -void CNullDriver::OnResize(const core::dimension2d& size) +void CNullDriver::OnResize(const core::dimension2d &size) { if (ViewPort.getWidth() == (s32)ScreenSize.Width && - ViewPort.getHeight() == (s32)ScreenSize.Height) - ViewPort = core::rect(core::position2d(0,0), - core::dimension2di(size)); + ViewPort.getHeight() == (s32)ScreenSize.Height) + ViewPort = core::rect(core::position2d(0, 0), + core::dimension2di(size)); ScreenSize = size; } - // adds a material renderer and drops it afterwards. To be used for internal creation -s32 CNullDriver::addAndDropMaterialRenderer(IMaterialRenderer* m) +s32 CNullDriver::addAndDropMaterialRenderer(IMaterialRenderer *m) { s32 i = addMaterialRenderer(m); @@ -1522,9 +1376,8 @@ s32 CNullDriver::addAndDropMaterialRenderer(IMaterialRenderer* m) return i; } - //! Adds a new material renderer to the video device. -s32 CNullDriver::addMaterialRenderer(IMaterialRenderer* renderer, const char* name) +s32 CNullDriver::addMaterialRenderer(IMaterialRenderer *renderer, const char *name) { if (!renderer) return -1; @@ -1533,8 +1386,7 @@ s32 CNullDriver::addMaterialRenderer(IMaterialRenderer* renderer, const char* na r.Renderer = renderer; r.Name = name; - if (name == 0 && MaterialRenderers.size() < numBuiltInMaterials) - { + if (name == 0 && MaterialRenderers.size() < numBuiltInMaterials) { // set name of built in renderer so that we don't have to implement name // setting in all available renderers. r.Name = sBuiltInMaterialTypeNames[MaterialRenderers.size()]; @@ -1543,12 +1395,11 @@ s32 CNullDriver::addMaterialRenderer(IMaterialRenderer* renderer, const char* na MaterialRenderers.push_back(r); renderer->grab(); - return MaterialRenderers.size()-1; + return MaterialRenderers.size() - 1; } - //! Sets the name of a material renderer. -void CNullDriver::setMaterialRendererName(u32 idx, const char* name) +void CNullDriver::setMaterialRendererName(u32 idx, const char *name) { if (idx < numBuiltInMaterials || idx >= MaterialRenderers.size()) return; @@ -1558,153 +1409,137 @@ void CNullDriver::setMaterialRendererName(u32 idx, const char* name) void CNullDriver::swapMaterialRenderers(u32 idx1, u32 idx2, bool swapNames) { - if ( idx1 < MaterialRenderers.size() && idx2 < MaterialRenderers.size() ) - { + if (idx1 < MaterialRenderers.size() && idx2 < MaterialRenderers.size()) { irr::core::swap(MaterialRenderers[idx1].Renderer, MaterialRenderers[idx2].Renderer); - if ( swapNames ) + if (swapNames) irr::core::swap(MaterialRenderers[idx1].Name, MaterialRenderers[idx2].Name); } } - //! Returns driver and operating system specific data about the IVideoDriver. -const SExposedVideoData& CNullDriver::getExposedVideoData() +const SExposedVideoData &CNullDriver::getExposedVideoData() { return ExposedData; } - //! Returns type of video driver E_DRIVER_TYPE CNullDriver::getDriverType() const { return EDT_NULL; } - //! deletes all material renderers void CNullDriver::deleteMaterialRenders() { // delete material renderers - for (u32 i=0; idrop(); MaterialRenderers.clear(); } - //! Returns pointer to material renderer or null -IMaterialRenderer* CNullDriver::getMaterialRenderer(u32 idx) const +IMaterialRenderer *CNullDriver::getMaterialRenderer(u32 idx) const { - if ( idx < MaterialRenderers.size() ) + if (idx < MaterialRenderers.size()) return MaterialRenderers[idx].Renderer; else return 0; } - //! Returns amount of currently available material renderers. u32 CNullDriver::getMaterialRendererCount() const { return MaterialRenderers.size(); } - //! Returns name of the material renderer -const char* CNullDriver::getMaterialRendererName(u32 idx) const +const char *CNullDriver::getMaterialRendererName(u32 idx) const { - if ( idx < MaterialRenderers.size() ) + if (idx < MaterialRenderers.size()) return MaterialRenderers[idx].Name.c_str(); return 0; } - //! Returns pointer to the IGPUProgrammingServices interface. -IGPUProgrammingServices* CNullDriver::getGPUProgrammingServices() +IGPUProgrammingServices *CNullDriver::getGPUProgrammingServices() { return this; } - //! Adds a new material renderer to the VideoDriver, based on a high level shading language. s32 CNullDriver::addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, - E_GEOMETRY_SHADER_TYPE gsCompileTarget, - scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, + E_GEOMETRY_SHADER_TYPE gsCompileTarget, + scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, + u32 verticesOut, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) { os::Printer::log("High level shader materials not available (yet) in this driver, sorry"); return -1; } - s32 CNullDriver::addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFileName, - const c8* vertexShaderEntryPointName, + const io::path &vertexShaderProgramFileName, + const c8 *vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, - const io::path& pixelShaderProgramFileName, - const c8* pixelShaderEntryPointName, + const io::path &pixelShaderProgramFileName, + const c8 *pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, - const io::path& geometryShaderProgramFileName, - const c8* geometryShaderEntryPointName, + const io::path &geometryShaderProgramFileName, + const c8 *geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, - IShaderConstantSetCallBack* callback, + IShaderConstantSetCallBack *callback, E_MATERIAL_TYPE baseMaterial, s32 userData) { - io::IReadFile* vsfile = 0; - io::IReadFile* psfile = 0; - io::IReadFile* gsfile = 0; + io::IReadFile *vsfile = 0; + io::IReadFile *psfile = 0; + io::IReadFile *gsfile = 0; - if (vertexShaderProgramFileName.size() ) - { + if (vertexShaderProgramFileName.size()) { vsfile = FileSystem->createAndOpenFile(vertexShaderProgramFileName); - if (!vsfile) - { + if (!vsfile) { os::Printer::log("Could not open vertex shader program file", - vertexShaderProgramFileName, ELL_WARNING); + vertexShaderProgramFileName, ELL_WARNING); } } - if (pixelShaderProgramFileName.size() ) - { + if (pixelShaderProgramFileName.size()) { psfile = FileSystem->createAndOpenFile(pixelShaderProgramFileName); - if (!psfile) - { + if (!psfile) { os::Printer::log("Could not open pixel shader program file", - pixelShaderProgramFileName, ELL_WARNING); + pixelShaderProgramFileName, ELL_WARNING); } } - if (geometryShaderProgramFileName.size() ) - { + if (geometryShaderProgramFileName.size()) { gsfile = FileSystem->createAndOpenFile(geometryShaderProgramFileName); - if (!gsfile) - { + if (!gsfile) { os::Printer::log("Could not open geometry shader program file", - geometryShaderProgramFileName, ELL_WARNING); + geometryShaderProgramFileName, ELL_WARNING); } } s32 result = addHighLevelShaderMaterialFromFiles( - vsfile, vertexShaderEntryPointName, vsCompileTarget, - psfile, pixelShaderEntryPointName, psCompileTarget, - gsfile, geometryShaderEntryPointName, gsCompileTarget, - inType, outType, verticesOut, - callback, baseMaterial, userData); + vsfile, vertexShaderEntryPointName, vsCompileTarget, + psfile, pixelShaderEntryPointName, psCompileTarget, + gsfile, geometryShaderEntryPointName, gsCompileTarget, + inType, outType, verticesOut, + callback, baseMaterial, userData); if (psfile) psfile->drop(); @@ -1718,77 +1553,70 @@ s32 CNullDriver::addHighLevelShaderMaterialFromFiles( return result; } - s32 CNullDriver::addHighLevelShaderMaterialFromFiles( - io::IReadFile* vertexShaderProgram, - const c8* vertexShaderEntryPointName, + io::IReadFile *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, - io::IReadFile* pixelShaderProgram, - const c8* pixelShaderEntryPointName, + io::IReadFile *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, - io::IReadFile* geometryShaderProgram, - const c8* geometryShaderEntryPointName, + io::IReadFile *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, - IShaderConstantSetCallBack* callback, + IShaderConstantSetCallBack *callback, E_MATERIAL_TYPE baseMaterial, s32 userData) { - c8* vs = 0; - c8* ps = 0; - c8* gs = 0; + c8 *vs = 0; + c8 *ps = 0; + c8 *gs = 0; - if (vertexShaderProgram) - { + if (vertexShaderProgram) { const long size = vertexShaderProgram->getSize(); - if (size) - { - vs = new c8[size+1]; + if (size) { + vs = new c8[size + 1]; vertexShaderProgram->read(vs, size); vs[size] = 0; } } - if (pixelShaderProgram) - { + if (pixelShaderProgram) { const long size = pixelShaderProgram->getSize(); - if (size) - { + if (size) { // if both handles are the same we must reset the file - if (pixelShaderProgram==vertexShaderProgram) + if (pixelShaderProgram == vertexShaderProgram) pixelShaderProgram->seek(0); - ps = new c8[size+1]; + ps = new c8[size + 1]; pixelShaderProgram->read(ps, size); ps[size] = 0; } } - if (geometryShaderProgram) - { + if (geometryShaderProgram) { const long size = geometryShaderProgram->getSize(); - if (size) - { + if (size) { // if both handles are the same we must reset the file - if ((geometryShaderProgram==vertexShaderProgram) || - (geometryShaderProgram==pixelShaderProgram)) + if ((geometryShaderProgram == vertexShaderProgram) || + (geometryShaderProgram == pixelShaderProgram)) geometryShaderProgram->seek(0); - gs = new c8[size+1]; + gs = new c8[size + 1]; geometryShaderProgram->read(gs, size); gs[size] = 0; } } s32 result = this->addHighLevelShaderMaterial( - vs, vertexShaderEntryPointName, vsCompileTarget, - ps, pixelShaderEntryPointName, psCompileTarget, - gs, geometryShaderEntryPointName, gsCompileTarget, - inType, outType, verticesOut, - callback, baseMaterial, userData); + vs, vertexShaderEntryPointName, vsCompileTarget, + ps, pixelShaderEntryPointName, psCompileTarget, + gs, geometryShaderEntryPointName, gsCompileTarget, + inType, outType, verticesOut, + callback, baseMaterial, userData); - delete [] vs; - delete [] ps; - delete [] gs; + delete[] vs; + delete[] ps; + delete[] gs; return result; } @@ -1814,16 +1642,15 @@ void CNullDriver::deleteShaderMaterial(s32 material) ref.Name.clear(); } - //! Creates a render target texture. -ITexture* CNullDriver::addRenderTargetTexture(const core::dimension2d& size, - const io::path&name, const ECOLOR_FORMAT format) +ITexture *CNullDriver::addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format) { return 0; } -ITexture* CNullDriver::addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) +ITexture *CNullDriver::addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name, const ECOLOR_FORMAT format) { return 0; } @@ -1832,21 +1659,18 @@ void CNullDriver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) { } - //! Returns a pointer to the mesh manipulator. -scene::IMeshManipulator* CNullDriver::getMeshManipulator() +scene::IMeshManipulator *CNullDriver::getMeshManipulator() { return MeshManipulator; } - //! Returns an image created from the last rendered frame. -IImage* CNullDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) +IImage *CNullDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) { return 0; } - // prints renderer version void CNullDriver::printVersion() { @@ -1855,16 +1679,14 @@ void CNullDriver::printVersion() os::Printer::log(namePrint.c_str(), ELL_INFORMATION); } - //! creates a video driver -IVideoDriver* createNullDriver(io::IFileSystem* io, const core::dimension2d& screenSize) +IVideoDriver *createNullDriver(io::IFileSystem *io, const core::dimension2d &screenSize) { - CNullDriver* nullDriver = new CNullDriver(io, screenSize); + CNullDriver *nullDriver = new CNullDriver(io, screenSize); // create empty material renderers - for(u32 i=0; sBuiltInMaterialTypeNames[i]; ++i) - { - IMaterialRenderer* imr = new IMaterialRenderer(); + for (u32 i = 0; sBuiltInMaterialTypeNames[i]; ++i) { + IMaterialRenderer *imr = new IMaterialRenderer(); nullDriver->addMaterialRenderer(imr); imr->drop(); } @@ -1872,57 +1694,50 @@ IVideoDriver* createNullDriver(io::IFileSystem* io, const core::dimension2d return nullDriver; } - //! Set/unset a clipping plane. //! There are at least 6 clipping planes available for the user to set at will. //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. //! \param plane: The plane itself. //! \param enable: If true, enable the clipping plane else disable it. -bool CNullDriver::setClipPlane(u32 index, const core::plane3df& plane, bool enable) +bool CNullDriver::setClipPlane(u32 index, const core::plane3df &plane, bool enable) { return false; } - //! Enable/disable a clipping plane. void CNullDriver::enableClipPlane(u32 index, bool enable) { // not necessary } - void CNullDriver::setMinHardwareBufferVertexCount(u32 count) { MinVertexCountForVBO = count; } - -SOverrideMaterial& CNullDriver::getOverrideMaterial() +SOverrideMaterial &CNullDriver::getOverrideMaterial() { return OverrideMaterial; } - //! Get the 2d override material for altering its values -SMaterial& CNullDriver::getMaterial2D() +SMaterial &CNullDriver::getMaterial2D() { return OverrideMaterial2D; } - //! Enable the 2d override material void CNullDriver::enableMaterial2D(bool enable) { - OverrideMaterial2DEnabled=enable; + OverrideMaterial2DEnabled = enable; } - core::dimension2du CNullDriver::getMaxTextureSize() const { - return core::dimension2du(0x10000,0x10000); // maybe large enough + return core::dimension2du(0x10000, 0x10000); // maybe large enough } -bool CNullDriver::needsTransparentRenderPass(const irr::video::SMaterial& material) const +bool CNullDriver::needsTransparentRenderPass(const irr::video::SMaterial &material) const { // TODO: I suspect it would be nice if the material had an enum for further control. // Especially it probably makes sense to allow disabling transparent render pass as soon as material.ZWriteEnable is on. @@ -1931,7 +1746,7 @@ bool CNullDriver::needsTransparentRenderPass(const irr::video::SMaterial& materi // Be careful - this function is deeply connected to getWriteZBuffer as transparent render passes are usually about rendering with // zwrite disabled and getWriteZBuffer calls this function. - video::IMaterialRenderer* rnd = getMaterialRenderer(material.MaterialType); + video::IMaterialRenderer *rnd = getMaterialRenderer(material.MaterialType); // TODO: I suspect IMaterialRenderer::isTransparent also often could use SMaterial as parameter // We could for example then get rid of IsTransparent function in SMaterial and move that to the software material renderer. if (rnd && rnd->isTransparent()) @@ -1940,7 +1755,6 @@ bool CNullDriver::needsTransparentRenderPass(const irr::video::SMaterial& materi return false; } - //! Color conversion convenience function /** Convert an image (as array of pixels) from source to destination array, thereby converting the color format. The pixel size is @@ -1951,12 +1765,11 @@ determined by the color formats. \param dP Pointer to destination \param dF Color format of destination */ -void CNullDriver::convertColor(const void* sP, ECOLOR_FORMAT sF, s32 sN, - void* dP, ECOLOR_FORMAT dF) const +void CNullDriver::convertColor(const void *sP, ECOLOR_FORMAT sF, s32 sN, + void *dP, ECOLOR_FORMAT dF) const { video::CColorConverter::convert_viaFormat(sP, sF, sN, dP, dF); } - } // end namespace } // end namespace diff --git a/source/Irrlicht/CNullDriver.h b/source/Irrlicht/CNullDriver.h index 0f9a11d9..d47212c0 100644 --- a/source/Irrlicht/CNullDriver.h +++ b/source/Irrlicht/CNullDriver.h @@ -23,717 +23,720 @@ namespace irr { namespace io { - class IWriteFile; - class IReadFile; +class IWriteFile; +class IReadFile; } // end namespace io namespace video { - class IImageLoader; - class IImageWriter; +class IImageLoader; +class IImageWriter; - class CNullDriver : public IVideoDriver, public IGPUProgrammingServices - { - public: +class CNullDriver : public IVideoDriver, public IGPUProgrammingServices +{ +public: + //! constructor + CNullDriver(io::IFileSystem *io, const core::dimension2d &screenSize); - //! constructor - CNullDriver(io::IFileSystem* io, const core::dimension2d& screenSize); + //! destructor + virtual ~CNullDriver(); - //! destructor - virtual ~CNullDriver(); + virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) override; - virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255,0,0,0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; + bool endScene() override; - bool endScene() override; + //! Disable a feature of the driver. + void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag = true) override; - //! Disable a feature of the driver. - void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag=true) override; + //! queries the features of the driver, returns true if feature is available + bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override; - //! queries the features of the driver, returns true if feature is available - bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override; + //! Get attributes of the actual video driver + const io::IAttributes &getDriverAttributes() const override; - //! Get attributes of the actual video driver - const io::IAttributes& getDriverAttributes() const override; + //! sets transformation + void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) override; - //! sets transformation - void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; + //! Retrieve the number of image loaders + u32 getImageLoaderCount() const override; - //! Retrieve the number of image loaders - u32 getImageLoaderCount() const override; + //! Retrieve the given image loader + IImageLoader *getImageLoader(u32 n) override; - //! Retrieve the given image loader - IImageLoader* getImageLoader(u32 n) override; + //! Retrieve the number of image writers + u32 getImageWriterCount() const override; - //! Retrieve the number of image writers - u32 getImageWriterCount() const override; + //! Retrieve the given image writer + IImageWriter *getImageWriter(u32 n) override; - //! Retrieve the given image writer - IImageWriter* getImageWriter(u32 n) override; + //! sets a material + void setMaterial(const SMaterial &material) override; - //! sets a material - void setMaterial(const SMaterial& material) override; + //! loads a Texture + ITexture *getTexture(const io::path &filename) override; - //! loads a Texture - ITexture* getTexture(const io::path& filename) override; + //! loads a Texture + ITexture *getTexture(io::IReadFile *file) override; - //! loads a Texture - ITexture* getTexture(io::IReadFile* file) override; + //! Returns amount of textures currently loaded + u32 getTextureCount() const override; - //! Returns amount of textures currently loaded - u32 getTextureCount() const override; + ITexture *addTexture(const core::dimension2d &size, const io::path &name, ECOLOR_FORMAT format = ECF_A8R8G8B8) override; - ITexture* addTexture(const core::dimension2d& size, const io::path& name, ECOLOR_FORMAT format = ECF_A8R8G8B8) override; + ITexture *addTexture(const io::path &name, IImage *image) override; - ITexture* addTexture(const io::path& name, IImage* image) override; + virtual ITexture *addTextureCubemap(const io::path &name, IImage *imagePosX, IImage *imageNegX, IImage *imagePosY, + IImage *imageNegY, IImage *imagePosZ, IImage *imageNegZ) override; - virtual ITexture* addTextureCubemap(const io::path& name, IImage* imagePosX, IImage* imageNegX, IImage* imagePosY, - IImage* imageNegY, IImage* imagePosZ, IImage* imageNegZ) override; + ITexture *addTextureCubemap(const irr::u32 sideLen, const io::path &name, ECOLOR_FORMAT format = ECF_A8R8G8B8) override; - ITexture* addTextureCubemap(const irr::u32 sideLen, const io::path& name, ECOLOR_FORMAT format = ECF_A8R8G8B8) override; - - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255,0,0,0), + virtual bool setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0) override; - virtual bool setRenderTarget(ITexture* texture, u16 clearFlag, SColor clearColor = SColor(255,0,0,0), + virtual bool setRenderTarget(ITexture *texture, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0) override; - //! sets a viewport - void setViewPort(const core::rect& area) override; + //! sets a viewport + void setViewPort(const core::rect &area) override; - //! gets the area of the current viewport - const core::rect& getViewPort() const override; + //! gets the area of the current viewport + const core::rect &getViewPort() const override; - //! draws a vertex primitive list - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType=EVT_STANDARD, scene::E_PRIMITIVE_TYPE pType=scene::EPT_TRIANGLES, - E_INDEX_TYPE iType=EIT_16BIT) override; + //! draws a vertex primitive list + virtual void drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType = EVT_STANDARD, scene::E_PRIMITIVE_TYPE pType = scene::EPT_TRIANGLES, + E_INDEX_TYPE iType = EIT_16BIT) override; - //! draws a vertex primitive list in 2d - virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType=EVT_STANDARD, scene::E_PRIMITIVE_TYPE pType=scene::EPT_TRIANGLES, - E_INDEX_TYPE iType=EIT_16BIT) override; + //! draws a vertex primitive list in 2d + virtual void draw2DVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType = EVT_STANDARD, scene::E_PRIMITIVE_TYPE pType = scene::EPT_TRIANGLES, + E_INDEX_TYPE iType = EIT_16BIT) override; - //! Draws a 3d line. - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color = SColor(255,255,255,255)) override; + //! Draws a 3d line. + virtual void draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color = SColor(255, 255, 255, 255)) override; - //! Draws a 3d axis aligned box. - virtual void draw3DBox(const core::aabbox3d& box, - SColor color = SColor(255,255,255,255)) override; + //! Draws a 3d axis aligned box. + virtual void draw3DBox(const core::aabbox3d &box, + SColor color = SColor(255, 255, 255, 255)) override; - //! draws an 2d image - void draw2DImage(const video::ITexture* texture, const core::position2d& destPos, bool useAlphaChannelOfTexture) override; + //! draws an 2d image + void draw2DImage(const video::ITexture *texture, const core::position2d &destPos, bool useAlphaChannelOfTexture) override; - //! Draws a set of 2d images, using a color and the alpha channel of the texture. - /** All drawings are clipped against clipRect (if != 0). - The subtextures are defined by the array of sourceRects and are - positioned using the array of positions. - \param texture Texture to be drawn. - \param pos Array of upper left 2d destinations where the images - will be drawn. - \param sourceRects Source rectangles of the image. - \param clipRect Pointer to rectangle on the screen where the - images are clipped to. - If this pointer is 0 then the image is not clipped. - \param color Color with which the image is drawn. - Note that the alpha component is used. If alpha is other than - 255, the image will be transparent. - \param useAlphaChannelOfTexture: If true, the alpha channel of - the texture is used to draw the image. */ - virtual void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect=0, - SColor color=SColor(255,255,255,255), - bool useAlphaChannelOfTexture=false) override; + //! Draws a set of 2d images, using a color and the alpha channel of the texture. + /** All drawings are clipped against clipRect (if != 0). + The subtextures are defined by the array of sourceRects and are + positioned using the array of positions. + \param texture Texture to be drawn. + \param pos Array of upper left 2d destinations where the images + will be drawn. + \param sourceRects Source rectangles of the image. + \param clipRect Pointer to rectangle on the screen where the + images are clipped to. + If this pointer is 0 then the image is not clipped. + \param color Color with which the image is drawn. + Note that the alpha component is used. If alpha is other than + 255, the image will be transparent. + \param useAlphaChannelOfTexture: If true, the alpha channel of + the texture is used to draw the image. */ + virtual void draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), + bool useAlphaChannelOfTexture = false) override; - //! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted. - virtual void draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect = 0, - SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false) override; + //! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted. + virtual void draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; - //! Draws a part of the texture into the rectangle. - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect = 0, - const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false) override; + //! Draws a part of the texture into the rectangle. + virtual void draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect = 0, + const video::SColor *const colors = 0, bool useAlphaChannelOfTexture = false) override; - //! Draws a 2d rectangle - void draw2DRectangle(SColor color, const core::rect& pos, const core::rect* clip = 0) override; + //! Draws a 2d rectangle + void draw2DRectangle(SColor color, const core::rect &pos, const core::rect *clip = 0) override; - //! Draws a 2d rectangle with a gradient. - virtual void draw2DRectangle(const core::rect& pos, + //! Draws a 2d rectangle with a gradient. + virtual void draw2DRectangle(const core::rect &pos, SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip = 0) override; + const core::rect *clip = 0) override; - //! Draws a 2d line. - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color=SColor(255,255,255,255)) override; + //! Draws a 2d line. + virtual void draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color = SColor(255, 255, 255, 255)) override; - virtual void setFog(SColor color=SColor(0,255,255,255), - E_FOG_TYPE fogType=EFT_FOG_LINEAR, - f32 start=50.0f, f32 end=100.0f, f32 density=0.01f, - bool pixelFog=false, bool rangeFog=false) override; + virtual void setFog(SColor color = SColor(0, 255, 255, 255), + E_FOG_TYPE fogType = EFT_FOG_LINEAR, + f32 start = 50.0f, f32 end = 100.0f, f32 density = 0.01f, + bool pixelFog = false, bool rangeFog = false) override; - virtual void getFog(SColor& color, E_FOG_TYPE& fogType, - f32& start, f32& end, f32& density, - bool& pixelFog, bool& rangeFog) override; + virtual void getFog(SColor &color, E_FOG_TYPE &fogType, + f32 &start, f32 &end, f32 &density, + bool &pixelFog, bool &rangeFog) override; - //! get color format of the current color buffer - ECOLOR_FORMAT getColorFormat() const override; + //! get color format of the current color buffer + ECOLOR_FORMAT getColorFormat() const override; - //! get screen size - const core::dimension2d& getScreenSize() const override; + //! get screen size + const core::dimension2d &getScreenSize() const override; - //! get current render target - IRenderTarget* getCurrentRenderTarget() const; + //! get current render target + IRenderTarget *getCurrentRenderTarget() const; - //! get render target size - const core::dimension2d& getCurrentRenderTargetSize() const override; + //! get render target size + const core::dimension2d &getCurrentRenderTargetSize() const override; - // get current frames per second value - s32 getFPS() const override; + // get current frames per second value + s32 getFPS() const override; - //! returns amount of primitives (mostly triangles) were drawn in the last frame. - //! very useful method for statistics. - u32 getPrimitiveCountDrawn( u32 param = 0 ) const override; + //! returns amount of primitives (mostly triangles) were drawn in the last frame. + //! very useful method for statistics. + u32 getPrimitiveCountDrawn(u32 param = 0) const override; - //! \return Returns the name of the video driver. Example: In case of the DIRECT3D8 - //! driver, it would return "Direct3D8.1". - const char* getName() const override; + //! \return Returns the name of the video driver. Example: In case of the DIRECT3D8 + //! driver, it would return "Direct3D8.1". + const char *getName() const override; - //! Sets the dynamic ambient light color. The default color is - //! (0,0,0,0) which means it is dark. - //! \param color: New color of the ambient light. - void setAmbientLight(const SColorf& color) override; + //! Sets the dynamic ambient light color. The default color is + //! (0,0,0,0) which means it is dark. + //! \param color: New color of the ambient light. + void setAmbientLight(const SColorf &color) override; - //! Get the global ambient light currently used by the driver - const SColorf& getAmbientLight() const override; + //! Get the global ambient light currently used by the driver + const SColorf &getAmbientLight() const override; - //! Adds an external image loader to the engine. - void addExternalImageLoader(IImageLoader* loader) override; + //! Adds an external image loader to the engine. + void addExternalImageLoader(IImageLoader *loader) override; - //! Adds an external image writer to the engine. - void addExternalImageWriter(IImageWriter* writer) override; + //! Adds an external image writer to the engine. + void addExternalImageWriter(IImageWriter *writer) override; - //! Removes a texture from the texture cache and deletes it, freeing lot of - //! memory. - void removeTexture(ITexture* texture) override; + //! Removes a texture from the texture cache and deletes it, freeing lot of + //! memory. + void removeTexture(ITexture *texture) override; - //! Removes all texture from the texture cache and deletes them, freeing lot of - //! memory. - void removeAllTextures() override; + //! Removes all texture from the texture cache and deletes them, freeing lot of + //! memory. + void removeAllTextures() override; - //! Creates a render target texture. - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + //! Creates a render target texture. + virtual ITexture *addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; - //! Creates a render target texture for a cubemap - ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) override; + //! Creates a render target texture for a cubemap + ITexture *addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name, const ECOLOR_FORMAT format) override; - //! Creates an 1bit alpha channel of the texture based of an color key. - void makeColorKeyTexture(video::ITexture* texture, video::SColor color) const override; + //! Creates an 1bit alpha channel of the texture based of an color key. + void makeColorKeyTexture(video::ITexture *texture, video::SColor color) const override; - //! Creates an 1bit alpha channel of the texture based of an color key position. - virtual void makeColorKeyTexture(video::ITexture* texture, - core::position2d colorKeyPixelPos) const override; + //! Creates an 1bit alpha channel of the texture based of an color key position. + virtual void makeColorKeyTexture(video::ITexture *texture, + core::position2d colorKeyPixelPos) const override; - //! Returns the maximum amount of primitives (mostly vertices) which - //! the device is able to render with one drawIndexedTriangleList - //! call. - u32 getMaximalPrimitiveCount() const override; + //! Returns the maximum amount of primitives (mostly vertices) which + //! the device is able to render with one drawIndexedTriangleList + //! call. + u32 getMaximalPrimitiveCount() const override; - //! Enables or disables a texture creation flag. - void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled) override; + //! Enables or disables a texture creation flag. + void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled) override; - //! Returns if a texture creation flag is enabled or disabled. - bool getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const override; + //! Returns if a texture creation flag is enabled or disabled. + bool getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const override; - IImage *createImageFromFile(const io::path& filename) override; + IImage *createImageFromFile(const io::path &filename) override; - IImage *createImageFromFile(io::IReadFile* file) override; + IImage *createImageFromFile(io::IReadFile *file) override; - //! Creates a software image from a byte array. - /** \param useForeignMemory: If true, the image will use the data pointer - directly and own it from now on, which means it will also try to delete [] the - data when the image will be destructed. If false, the memory will by copied. */ - virtual IImage* createImageFromData(ECOLOR_FORMAT format, - const core::dimension2d& size, void *data, bool ownForeignMemory = false, + //! Creates a software image from a byte array. + /** \param useForeignMemory: If true, the image will use the data pointer + directly and own it from now on, which means it will also try to delete [] the + data when the image will be destructed. If false, the memory will by copied. */ + virtual IImage *createImageFromData(ECOLOR_FORMAT format, + const core::dimension2d &size, void *data, bool ownForeignMemory = false, bool deleteMemory = true) override; - //! Creates an empty software image. - IImage* createImage(ECOLOR_FORMAT format, const core::dimension2d& size) override; + //! Creates an empty software image. + IImage *createImage(ECOLOR_FORMAT format, const core::dimension2d &size) override; - //! Creates a software image from part of a texture. - virtual IImage* createImage(ITexture* texture, - const core::position2d& pos, - const core::dimension2d& size) override; + //! Creates a software image from part of a texture. + virtual IImage *createImage(ITexture *texture, + const core::position2d &pos, + const core::dimension2d &size) override; - //! Draws a mesh buffer - void drawMeshBuffer(const scene::IMeshBuffer* mb) override; + //! Draws a mesh buffer + void drawMeshBuffer(const scene::IMeshBuffer *mb) override; - //! Draws the normals of a mesh buffer - virtual void drawMeshBufferNormals(const scene::IMeshBuffer* mb, f32 length=10.f, - SColor color=0xffffffff) override; + //! Draws the normals of a mesh buffer + virtual void drawMeshBufferNormals(const scene::IMeshBuffer *mb, f32 length = 10.f, + SColor color = 0xffffffff) override; - //! Check if the driver supports creating textures with the given color format - bool queryTextureFormat(ECOLOR_FORMAT format) const override + //! Check if the driver supports creating textures with the given color format + bool queryTextureFormat(ECOLOR_FORMAT format) const override + { + return false; + } + +protected: + struct SHWBufferLink + { + SHWBufferLink(const scene::IMeshBuffer *_MeshBuffer) : + MeshBuffer(_MeshBuffer), + ChangedID_Vertex(0), ChangedID_Index(0), + Mapped_Vertex(scene::EHM_NEVER), Mapped_Index(scene::EHM_NEVER) { - return false; + if (MeshBuffer) { + MeshBuffer->grab(); + MeshBuffer->setHWBuffer(reinterpret_cast(this)); + } } - protected: - struct SHWBufferLink + virtual ~SHWBufferLink() { - SHWBufferLink(const scene::IMeshBuffer *_MeshBuffer) - :MeshBuffer(_MeshBuffer), - ChangedID_Vertex(0),ChangedID_Index(0), - Mapped_Vertex(scene::EHM_NEVER),Mapped_Index(scene::EHM_NEVER) - { - if (MeshBuffer) { - MeshBuffer->grab(); - MeshBuffer->setHWBuffer(reinterpret_cast(this)); - } + if (MeshBuffer) { + MeshBuffer->setHWBuffer(NULL); + MeshBuffer->drop(); } - - virtual ~SHWBufferLink() - { - if (MeshBuffer) { - MeshBuffer->setHWBuffer(NULL); - MeshBuffer->drop(); - } - } - - const scene::IMeshBuffer *MeshBuffer; - u32 ChangedID_Vertex; - u32 ChangedID_Index; - scene::E_HARDWARE_MAPPING Mapped_Vertex; - scene::E_HARDWARE_MAPPING Mapped_Index; - std::list::iterator listPosition; - }; - - //! Gets hardware buffer link from a meshbuffer (may create or update buffer) - virtual SHWBufferLink *getBufferLink(const scene::IMeshBuffer* mb); - - //! updates hardware buffer if needed (only some drivers can) - virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer) {return false;} - - //! Draw hardware buffer (only some drivers can) - virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer) {} - - //! Delete hardware buffer - virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer); - - //! Create hardware buffer from mesh (only some drivers can) - virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) {return 0;} - - public: - //! Remove hardware buffer - void removeHardwareBuffer(const scene::IMeshBuffer* mb) override; - - //! Remove all hardware buffers - void removeAllHardwareBuffers() override; - - //! Update all hardware buffers, remove unused ones - virtual void updateAllHardwareBuffers(); - - //! is vbo recommended on this mesh? - virtual bool isHardwareBufferRecommend(const scene::IMeshBuffer* mb); - - //! Create occlusion query. - /** Use node for identification and mesh for occlusion test. */ - virtual void addOcclusionQuery(scene::ISceneNode* node, - const scene::IMesh* mesh=0) override; - - //! Remove occlusion query. - void removeOcclusionQuery(scene::ISceneNode* node) override; - - //! Remove all occlusion queries. - void removeAllOcclusionQueries() override; - - //! Run occlusion query. Draws mesh stored in query. - /** If the mesh shall not be rendered visible, use - overrideMaterial to disable the color and depth buffer. */ - void runOcclusionQuery(scene::ISceneNode* node, bool visible=false) override; - - //! Run all occlusion queries. Draws all meshes stored in queries. - /** If the meshes shall not be rendered visible, use - overrideMaterial to disable the color and depth buffer. */ - void runAllOcclusionQueries(bool visible=false) override; - - //! Update occlusion query. Retrieves results from GPU. - /** If the query shall not block, set the flag to false. - Update might not occur in this case, though */ - void updateOcclusionQuery(scene::ISceneNode* node, bool block=true) override; - - //! Update all occlusion queries. Retrieves results from GPU. - /** If the query shall not block, set the flag to false. - Update might not occur in this case, though */ - void updateAllOcclusionQueries(bool block=true) override; - - //! Return query result. - /** Return value is the number of visible pixels/fragments. - The value is a safe approximation, i.e. can be larger than the - actual value of pixels. */ - u32 getOcclusionQueryResult(scene::ISceneNode* node) const override; - - //! Create render target. - IRenderTarget* addRenderTarget() override; - - //! Remove render target. - void removeRenderTarget(IRenderTarget* renderTarget) override; - - //! Remove all render targets. - void removeAllRenderTargets() override; - - //! Only used by the engine internally. - /** Used to notify the driver that the window was resized. */ - void OnResize(const core::dimension2d& size) override; - - //! Adds a new material renderer to the video device. - virtual s32 addMaterialRenderer(IMaterialRenderer* renderer, - const char* name = 0) override; - - //! Returns driver and operating system specific data about the IVideoDriver. - const SExposedVideoData& getExposedVideoData() override; - - //! Returns type of video driver - E_DRIVER_TYPE getDriverType() const override; - - //! Returns the transformation set by setTransform - const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; - - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* getGPUProgrammingServices() override; - - //! Returns pointer to material renderer or null - IMaterialRenderer* getMaterialRenderer(u32 idx) const override; - - //! Returns amount of currently available material renderers. - u32 getMaterialRendererCount() const override; - - //! Returns name of the material renderer - const char* getMaterialRendererName(u32 idx) const override; - - //! Adds a new material renderer to the VideoDriver, based on a high level shading language. - virtual s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName = 0, - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - const c8* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = 0, - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - const c8* geometryShaderProgram = 0, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) override; - - virtual s32 addHighLevelShaderMaterialFromFiles( - const io::path& vertexShaderProgramFile, - const c8* vertexShaderEntryPointName = "main", - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - const io::path& pixelShaderProgramFile = "", - const c8* pixelShaderEntryPointName = "main", - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - const io::path& geometryShaderProgramFileName="", - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) override; - - virtual s32 addHighLevelShaderMaterialFromFiles( - io::IReadFile* vertexShaderProgram, - const c8* vertexShaderEntryPointName = "main", - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - io::IReadFile* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = "main", - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - io::IReadFile* geometryShaderProgram= 0, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) override; - - virtual void deleteShaderMaterial(s32 material) override; - - //! Returns a pointer to the mesh manipulator. - scene::IMeshManipulator* getMeshManipulator() override; - - void clearBuffers(u16 flag, SColor color = SColor(255,0,0,0), f32 depth = 1.f, u8 stencil = 0) override; - - //! Returns an image created from the last rendered frame. - IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; - - //! Writes the provided image to disk file - bool writeImageToFile(IImage* image, const io::path& filename, u32 param = 0) override; - - //! Writes the provided image to a file. - bool writeImageToFile(IImage* image, io::IWriteFile * file, u32 param = 0) override; - - //! Sets the name of a material renderer. - void setMaterialRendererName(u32 idx, const char* name) override; - - //! Swap the material renderers used for certain id's - void swapMaterialRenderers(u32 idx1, u32 idx2, bool swapNames) override; - - //! looks if the image is already loaded - video::ITexture* findTexture(const io::path& filename) override; - - //! Set/unset a clipping plane. - //! There are at least 6 clipping planes available for the user to set at will. - //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. - //! \param plane: The plane itself. - //! \param enable: If true, enable the clipping plane else disable it. - bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false) override; - - //! Enable/disable a clipping plane. - //! There are at least 6 clipping planes available for the user to set at will. - //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. - //! \param enable: If true, enable the clipping plane else disable it. - void enableClipPlane(u32 index, bool enable) override; - - //! Returns the graphics card vendor name. - core::stringc getVendorInfo() override {return "Not available on this driver.";} - - //! Set the minimum number of vertices for which a hw buffer will be created - /** \param count Number of vertices to set as minimum. */ - void setMinHardwareBufferVertexCount(u32 count) override; - - //! Get the global Material, which might override local materials. - /** Depending on the enable flags, values from this Material - are used to override those of local materials of some - meshbuffer being rendered. */ - SOverrideMaterial& getOverrideMaterial() override; - - //! Get the 2d override material for altering its values - SMaterial& getMaterial2D() override; - - //! Enable the 2d override material - void enableMaterial2D(bool enable=true) override; - - //! Only used by the engine internally. - void setAllowZWriteOnTransparent(bool flag) override - { AllowZWriteOnTransparent=flag; } - - //! Returns the maximum texture size supported. - core::dimension2du getMaxTextureSize() const override; - - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; - - //! Color conversion convenience function - /** Convert an image (as array of pixels) from source to destination - array, thereby converting the color format. The pixel size is - determined by the color formats. - \param sP Pointer to source - \param sF Color format of source - \param sN Number of pixels to convert, both array must be large enough - \param dP Pointer to destination - \param dF Color format of destination - */ - virtual void convertColor(const void* sP, ECOLOR_FORMAT sF, s32 sN, - void* dP, ECOLOR_FORMAT dF) const override; - - bool checkDriverReset() override {return false;} - protected: - - //! deletes all textures - void deleteAllTextures(); - - //! opens the file and loads it into the surface - ITexture* loadTextureFromFile(io::IReadFile* file, const io::path& hashName = ""); - - //! adds a surface, not loaded or created by the Irrlicht Engine - void addTexture(ITexture* surface); - - virtual ITexture* createDeviceDependentTexture(const io::path& name, IImage* image); - - virtual ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image); - - //! checks triangle count and print warning if wrong - bool checkPrimitiveCount(u32 prmcnt) const; - - bool checkImage(IImage *image) const; - - bool checkImage(const core::array& image) const; - - // adds a material renderer and drops it afterwards. To be used for internal creation - s32 addAndDropMaterialRenderer(IMaterialRenderer* m); - - //! deletes all material renderers - void deleteMaterialRenders(); - - // prints renderer version - void printVersion(); - - inline bool getWriteZBuffer(const SMaterial& material) const - { - switch ( material.ZWriteEnable ) - { - case video::EZW_OFF: - return false; - case video::EZW_AUTO: - return AllowZWriteOnTransparent || ! needsTransparentRenderPass(material); - case video::EZW_ON: - return true; - } - return true; // never should get here, but some compilers don't know and complain } - struct SSurface - { - video::ITexture* Surface; - - bool operator < (const SSurface& other) const - { - return Surface->getName() < other.Surface->getName(); - } - }; - - struct SMaterialRenderer - { - core::stringc Name; - IMaterialRenderer* Renderer; - }; - - struct SDummyTexture : public ITexture - { - SDummyTexture(const io::path& name, E_TEXTURE_TYPE type) : ITexture(name, type) {}; - - void setSize(const core::dimension2d& size) { Size = OriginalSize = size; } - - void* lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel=0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) override { return 0; } - void unlock()override {} - void regenerateMipMapLevels(void* data = 0, u32 layer = 0) override {} - }; - core::array Textures; - - struct SOccQuery - { - SOccQuery(scene::ISceneNode* node, const scene::IMesh* mesh=0) : Node(node), Mesh(mesh), PID(0), Result(0xffffffff), Run(0xffffffff) - { - if (Node) - Node->grab(); - if (Mesh) - Mesh->grab(); - } - - SOccQuery(const SOccQuery& other) : Node(other.Node), Mesh(other.Mesh), PID(other.PID), Result(other.Result), Run(other.Run) - { - if (Node) - Node->grab(); - if (Mesh) - Mesh->grab(); - } - - ~SOccQuery() - { - if (Node) - Node->drop(); - if (Mesh) - Mesh->drop(); - } - - SOccQuery& operator=(const SOccQuery& other) - { - Node=other.Node; - Mesh=other.Mesh; - PID=other.PID; - Result=other.Result; - Run=other.Run; - if (Node) - Node->grab(); - if (Mesh) - Mesh->grab(); - return *this; - } - - bool operator==(const SOccQuery& other) const - { - return other.Node==Node; - } - - scene::ISceneNode* Node; - const scene::IMesh* Mesh; - union - { - void* PID; - unsigned int UID; - }; - u32 Result; - u32 Run; - }; - core::array OcclusionQueries; - - core::array RenderTargets; - - // Shared objects used with simplified IVideoDriver::setRenderTarget method with ITexture* param. - IRenderTarget* SharedRenderTarget; - core::array SharedDepthTextures; - - IRenderTarget* CurrentRenderTarget; - core::dimension2d CurrentRenderTargetSize; - - core::array SurfaceLoader; - core::array SurfaceWriter; - core::array MaterialRenderers; - - std::list HWBufferList; - - io::IFileSystem* FileSystem; - - //! mesh manipulator - scene::IMeshManipulator* MeshManipulator; - - core::rect ViewPort; - core::dimension2d ScreenSize; - core::matrix4 TransformationMatrix; - - CFPSCounter FPSCounter; - - u32 PrimitivesDrawn; - u32 MinVertexCountForVBO; - - u32 TextureCreationFlags; - - f32 FogStart; - f32 FogEnd; - f32 FogDensity; - SColor FogColor; - SExposedVideoData ExposedData; - - io::IAttributes* DriverAttributes; - - SOverrideMaterial OverrideMaterial; - SMaterial OverrideMaterial2D; - SMaterial InitMaterial2D; - bool OverrideMaterial2DEnabled; - - E_FOG_TYPE FogType; - bool PixelFog; - bool RangeFog; - bool AllowZWriteOnTransparent; - - bool FeatureEnabled[video::EVDF_COUNT]; - - SColorf AmbientLight; + const scene::IMeshBuffer *MeshBuffer; + u32 ChangedID_Vertex; + u32 ChangedID_Index; + scene::E_HARDWARE_MAPPING Mapped_Vertex; + scene::E_HARDWARE_MAPPING Mapped_Index; + std::list::iterator listPosition; }; + //! Gets hardware buffer link from a meshbuffer (may create or update buffer) + virtual SHWBufferLink *getBufferLink(const scene::IMeshBuffer *mb); + + //! updates hardware buffer if needed (only some drivers can) + virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer) { return false; } + + //! Draw hardware buffer (only some drivers can) + virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer) {} + + //! Delete hardware buffer + virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer); + + //! Create hardware buffer from mesh (only some drivers can) + virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer *mb) { return 0; } + +public: + //! Remove hardware buffer + void removeHardwareBuffer(const scene::IMeshBuffer *mb) override; + + //! Remove all hardware buffers + void removeAllHardwareBuffers() override; + + //! Update all hardware buffers, remove unused ones + virtual void updateAllHardwareBuffers(); + + //! is vbo recommended on this mesh? + virtual bool isHardwareBufferRecommend(const scene::IMeshBuffer *mb); + + //! Create occlusion query. + /** Use node for identification and mesh for occlusion test. */ + virtual void addOcclusionQuery(scene::ISceneNode *node, + const scene::IMesh *mesh = 0) override; + + //! Remove occlusion query. + void removeOcclusionQuery(scene::ISceneNode *node) override; + + //! Remove all occlusion queries. + void removeAllOcclusionQueries() override; + + //! Run occlusion query. Draws mesh stored in query. + /** If the mesh shall not be rendered visible, use + overrideMaterial to disable the color and depth buffer. */ + void runOcclusionQuery(scene::ISceneNode *node, bool visible = false) override; + + //! Run all occlusion queries. Draws all meshes stored in queries. + /** If the meshes shall not be rendered visible, use + overrideMaterial to disable the color and depth buffer. */ + void runAllOcclusionQueries(bool visible = false) override; + + //! Update occlusion query. Retrieves results from GPU. + /** If the query shall not block, set the flag to false. + Update might not occur in this case, though */ + void updateOcclusionQuery(scene::ISceneNode *node, bool block = true) override; + + //! Update all occlusion queries. Retrieves results from GPU. + /** If the query shall not block, set the flag to false. + Update might not occur in this case, though */ + void updateAllOcclusionQueries(bool block = true) override; + + //! Return query result. + /** Return value is the number of visible pixels/fragments. + The value is a safe approximation, i.e. can be larger than the + actual value of pixels. */ + u32 getOcclusionQueryResult(scene::ISceneNode *node) const override; + + //! Create render target. + IRenderTarget *addRenderTarget() override; + + //! Remove render target. + void removeRenderTarget(IRenderTarget *renderTarget) override; + + //! Remove all render targets. + void removeAllRenderTargets() override; + + //! Only used by the engine internally. + /** Used to notify the driver that the window was resized. */ + void OnResize(const core::dimension2d &size) override; + + //! Adds a new material renderer to the video device. + virtual s32 addMaterialRenderer(IMaterialRenderer *renderer, + const char *name = 0) override; + + //! Returns driver and operating system specific data about the IVideoDriver. + const SExposedVideoData &getExposedVideoData() override; + + //! Returns type of video driver + E_DRIVER_TYPE getDriverType() const override; + + //! Returns the transformation set by setTransform + const core::matrix4 &getTransform(E_TRANSFORMATION_STATE state) const override; + + //! Returns pointer to the IGPUProgrammingServices interface. + IGPUProgrammingServices *getGPUProgrammingServices() override; + + //! Returns pointer to material renderer or null + IMaterialRenderer *getMaterialRenderer(u32 idx) const override; + + //! Returns amount of currently available material renderers. + u32 getMaterialRendererCount() const override; + + //! Returns name of the material renderer + const char *getMaterialRendererName(u32 idx) const override; + + //! Adds a new material renderer to the VideoDriver, based on a high level shading language. + virtual s32 addHighLevelShaderMaterial( + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName = 0, + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const c8 *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = 0, + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + const c8 *geometryShaderProgram = 0, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) override; + + virtual s32 addHighLevelShaderMaterialFromFiles( + const io::path &vertexShaderProgramFile, + const c8 *vertexShaderEntryPointName = "main", + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const io::path &pixelShaderProgramFile = "", + const c8 *pixelShaderEntryPointName = "main", + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + const io::path &geometryShaderProgramFileName = "", + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) override; + + virtual s32 addHighLevelShaderMaterialFromFiles( + io::IReadFile *vertexShaderProgram, + const c8 *vertexShaderEntryPointName = "main", + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + io::IReadFile *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = "main", + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + io::IReadFile *geometryShaderProgram = 0, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) override; + + virtual void deleteShaderMaterial(s32 material) override; + + //! Returns a pointer to the mesh manipulator. + scene::IMeshManipulator *getMeshManipulator() override; + + void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; + + //! Returns an image created from the last rendered frame. + IImage *createScreenShot(video::ECOLOR_FORMAT format = video::ECF_UNKNOWN, video::E_RENDER_TARGET target = video::ERT_FRAME_BUFFER) override; + + //! Writes the provided image to disk file + bool writeImageToFile(IImage *image, const io::path &filename, u32 param = 0) override; + + //! Writes the provided image to a file. + bool writeImageToFile(IImage *image, io::IWriteFile *file, u32 param = 0) override; + + //! Sets the name of a material renderer. + void setMaterialRendererName(u32 idx, const char *name) override; + + //! Swap the material renderers used for certain id's + void swapMaterialRenderers(u32 idx1, u32 idx2, bool swapNames) override; + + //! looks if the image is already loaded + video::ITexture *findTexture(const io::path &filename) override; + + //! Set/unset a clipping plane. + //! There are at least 6 clipping planes available for the user to set at will. + //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. + //! \param plane: The plane itself. + //! \param enable: If true, enable the clipping plane else disable it. + bool setClipPlane(u32 index, const core::plane3df &plane, bool enable = false) override; + + //! Enable/disable a clipping plane. + //! There are at least 6 clipping planes available for the user to set at will. + //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. + //! \param enable: If true, enable the clipping plane else disable it. + void enableClipPlane(u32 index, bool enable) override; + + //! Returns the graphics card vendor name. + core::stringc getVendorInfo() override { return "Not available on this driver."; } + + //! Set the minimum number of vertices for which a hw buffer will be created + /** \param count Number of vertices to set as minimum. */ + void setMinHardwareBufferVertexCount(u32 count) override; + + //! Get the global Material, which might override local materials. + /** Depending on the enable flags, values from this Material + are used to override those of local materials of some + meshbuffer being rendered. */ + SOverrideMaterial &getOverrideMaterial() override; + + //! Get the 2d override material for altering its values + SMaterial &getMaterial2D() override; + + //! Enable the 2d override material + void enableMaterial2D(bool enable = true) override; + + //! Only used by the engine internally. + void setAllowZWriteOnTransparent(bool flag) override + { + AllowZWriteOnTransparent = flag; + } + + //! Returns the maximum texture size supported. + core::dimension2du getMaxTextureSize() const override; + + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + bool needsTransparentRenderPass(const irr::video::SMaterial &material) const override; + + //! Color conversion convenience function + /** Convert an image (as array of pixels) from source to destination + array, thereby converting the color format. The pixel size is + determined by the color formats. + \param sP Pointer to source + \param sF Color format of source + \param sN Number of pixels to convert, both array must be large enough + \param dP Pointer to destination + \param dF Color format of destination + */ + virtual void convertColor(const void *sP, ECOLOR_FORMAT sF, s32 sN, + void *dP, ECOLOR_FORMAT dF) const override; + + bool checkDriverReset() override { return false; } + +protected: + //! deletes all textures + void deleteAllTextures(); + + //! opens the file and loads it into the surface + ITexture *loadTextureFromFile(io::IReadFile *file, const io::path &hashName = ""); + + //! adds a surface, not loaded or created by the Irrlicht Engine + void addTexture(ITexture *surface); + + virtual ITexture *createDeviceDependentTexture(const io::path &name, IImage *image); + + virtual ITexture *createDeviceDependentTextureCubemap(const io::path &name, const core::array &image); + + //! checks triangle count and print warning if wrong + bool checkPrimitiveCount(u32 prmcnt) const; + + bool checkImage(IImage *image) const; + + bool checkImage(const core::array &image) const; + + // adds a material renderer and drops it afterwards. To be used for internal creation + s32 addAndDropMaterialRenderer(IMaterialRenderer *m); + + //! deletes all material renderers + void deleteMaterialRenders(); + + // prints renderer version + void printVersion(); + + inline bool getWriteZBuffer(const SMaterial &material) const + { + switch (material.ZWriteEnable) { + case video::EZW_OFF: + return false; + case video::EZW_AUTO: + return AllowZWriteOnTransparent || !needsTransparentRenderPass(material); + case video::EZW_ON: + return true; + } + return true; // never should get here, but some compilers don't know and complain + } + + struct SSurface + { + video::ITexture *Surface; + + bool operator<(const SSurface &other) const + { + return Surface->getName() < other.Surface->getName(); + } + }; + + struct SMaterialRenderer + { + core::stringc Name; + IMaterialRenderer *Renderer; + }; + + struct SDummyTexture : public ITexture + { + SDummyTexture(const io::path &name, E_TEXTURE_TYPE type) : + ITexture(name, type){}; + + void setSize(const core::dimension2d &size) { Size = OriginalSize = size; } + + void *lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel = 0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) override { return 0; } + void unlock() override {} + void regenerateMipMapLevels(void *data = 0, u32 layer = 0) override {} + }; + core::array Textures; + + struct SOccQuery + { + SOccQuery(scene::ISceneNode *node, const scene::IMesh *mesh = 0) : + Node(node), Mesh(mesh), PID(0), Result(0xffffffff), Run(0xffffffff) + { + if (Node) + Node->grab(); + if (Mesh) + Mesh->grab(); + } + + SOccQuery(const SOccQuery &other) : + Node(other.Node), Mesh(other.Mesh), PID(other.PID), Result(other.Result), Run(other.Run) + { + if (Node) + Node->grab(); + if (Mesh) + Mesh->grab(); + } + + ~SOccQuery() + { + if (Node) + Node->drop(); + if (Mesh) + Mesh->drop(); + } + + SOccQuery &operator=(const SOccQuery &other) + { + Node = other.Node; + Mesh = other.Mesh; + PID = other.PID; + Result = other.Result; + Run = other.Run; + if (Node) + Node->grab(); + if (Mesh) + Mesh->grab(); + return *this; + } + + bool operator==(const SOccQuery &other) const + { + return other.Node == Node; + } + + scene::ISceneNode *Node; + const scene::IMesh *Mesh; + union + { + void *PID; + unsigned int UID; + }; + u32 Result; + u32 Run; + }; + core::array OcclusionQueries; + + core::array RenderTargets; + + // Shared objects used with simplified IVideoDriver::setRenderTarget method with ITexture* param. + IRenderTarget *SharedRenderTarget; + core::array SharedDepthTextures; + + IRenderTarget *CurrentRenderTarget; + core::dimension2d CurrentRenderTargetSize; + + core::array SurfaceLoader; + core::array SurfaceWriter; + core::array MaterialRenderers; + + std::list HWBufferList; + + io::IFileSystem *FileSystem; + + //! mesh manipulator + scene::IMeshManipulator *MeshManipulator; + + core::rect ViewPort; + core::dimension2d ScreenSize; + core::matrix4 TransformationMatrix; + + CFPSCounter FPSCounter; + + u32 PrimitivesDrawn; + u32 MinVertexCountForVBO; + + u32 TextureCreationFlags; + + f32 FogStart; + f32 FogEnd; + f32 FogDensity; + SColor FogColor; + SExposedVideoData ExposedData; + + io::IAttributes *DriverAttributes; + + SOverrideMaterial OverrideMaterial; + SMaterial OverrideMaterial2D; + SMaterial InitMaterial2D; + bool OverrideMaterial2DEnabled; + + E_FOG_TYPE FogType; + bool PixelFog; + bool RangeFog; + bool AllowZWriteOnTransparent; + + bool FeatureEnabled[video::EVDF_COUNT]; + + SColorf AmbientLight; +}; + } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/COBJMeshFileLoader.cpp b/source/Irrlicht/COBJMeshFileLoader.cpp index 6649b7bc..8f47fbe0 100644 --- a/source/Irrlicht/COBJMeshFileLoader.cpp +++ b/source/Irrlicht/COBJMeshFileLoader.cpp @@ -24,34 +24,31 @@ namespace scene #endif //! Constructor -COBJMeshFileLoader::COBJMeshFileLoader(scene::ISceneManager* smgr) -: SceneManager(smgr) +COBJMeshFileLoader::COBJMeshFileLoader(scene::ISceneManager *smgr) : + SceneManager(smgr) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("COBJMeshFileLoader"); - #endif +#endif } - //! destructor COBJMeshFileLoader::~COBJMeshFileLoader() { } - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") -bool COBJMeshFileLoader::isALoadableFileExtension(const io::path& filename) const +bool COBJMeshFileLoader::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "obj" ); + return core::hasFileExtension(filename, "obj"); } - //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. -IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) +IAnimatedMesh *COBJMeshFileLoader::createMesh(io::IReadFile *file) { if (!file) return 0; @@ -66,108 +63,97 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) core::array normalsBuffer(1000); core::array textureCoordBuffer(1000); - SObjMtl * currMtl = new SObjMtl(); + SObjMtl *currMtl = new SObjMtl(); Materials.push_back(currMtl); - u32 smoothingGroup=0; + u32 smoothingGroup = 0; const io::path fullName = file->getFileName(); - c8* buf = new c8[filesize+1]; // plus null-terminator - memset(buf, 0, filesize+1); - file->read((void*)buf, filesize); - const c8* const bufEnd = buf+filesize; + c8 *buf = new c8[filesize + 1]; // plus null-terminator + memset(buf, 0, filesize + 1); + file->read((void *)buf, filesize); + const c8 *const bufEnd = buf + filesize; // Process obj information - const c8* bufPtr = buf; + const c8 *bufPtr = buf; core::stringc grpName, mtlName; - bool mtlChanged=false; + bool mtlChanged = false; bool useGroups = !SceneManager->getParameters()->getAttributeAsBool(OBJ_LOADER_IGNORE_GROUPS); bool useMaterials = !SceneManager->getParameters()->getAttributeAsBool(OBJ_LOADER_IGNORE_MATERIAL_FILES); - [[maybe_unused]] irr::u32 lineNr = 1; // only counts non-empty lines, still useful in debugging to locate errors + [[maybe_unused]] irr::u32 lineNr = 1; // only counts non-empty lines, still useful in debugging to locate errors core::array faceCorners; faceCorners.reallocate(32); // should be large enough const core::stringc TAG_OFF = "off"; irr::u32 degeneratedFaces = 0; - while(bufPtr != bufEnd) - { - switch(bufPtr[0]) + while (bufPtr != bufEnd) { + switch (bufPtr[0]) { + case 'm': // mtllib (material) { - case 'm': // mtllib (material) - { - if (useMaterials) - { + if (useMaterials) { c8 name[WORD_BUFFER_LENGTH]; bufPtr = goAndCopyNextWord(name, bufPtr, WORD_BUFFER_LENGTH, bufEnd); #ifdef _IRR_DEBUG_OBJ_LOADER_ - os::Printer::log("Ignoring material file",name); + os::Printer::log("Ignoring material file", name); #endif } - } - break; + } break; - case 'v': // v, vn, vt - switch(bufPtr[1]) + case 'v': // v, vn, vt + switch (bufPtr[1]) { + case ' ': // vertex { - case ' ': // vertex - { - core::vector3df vec; - bufPtr = readVec3(bufPtr, vec, bufEnd); - vertexBuffer.push_back(vec); - } - break; + core::vector3df vec; + bufPtr = readVec3(bufPtr, vec, bufEnd); + vertexBuffer.push_back(vec); + } break; - case 'n': // normal - { - core::vector3df vec; - bufPtr = readVec3(bufPtr, vec, bufEnd); - normalsBuffer.push_back(vec); - } - break; + case 'n': // normal + { + core::vector3df vec; + bufPtr = readVec3(bufPtr, vec, bufEnd); + normalsBuffer.push_back(vec); + } break; - case 't': // texcoord - { - core::vector2df vec; - bufPtr = readUV(bufPtr, vec, bufEnd); - textureCoordBuffer.push_back(vec); - } - break; + case 't': // texcoord + { + core::vector2df vec; + bufPtr = readUV(bufPtr, vec, bufEnd); + textureCoordBuffer.push_back(vec); + } break; } break; case 'g': // group name - { - c8 grp[WORD_BUFFER_LENGTH]; - bufPtr = goAndCopyNextWord(grp, bufPtr, WORD_BUFFER_LENGTH, bufEnd); + { + c8 grp[WORD_BUFFER_LENGTH]; + bufPtr = goAndCopyNextWord(grp, bufPtr, WORD_BUFFER_LENGTH, bufEnd); #ifdef _IRR_DEBUG_OBJ_LOADER_ - os::Printer::log("Loaded group start",grp, ELL_DEBUG); + os::Printer::log("Loaded group start", grp, ELL_DEBUG); #endif - if (useGroups) - { - if (0 != grp[0]) - grpName = grp; - else - grpName = "default"; - } - mtlChanged=true; + if (useGroups) { + if (0 != grp[0]) + grpName = grp; + else + grpName = "default"; } - break; + mtlChanged = true; + } break; case 's': // smoothing can be a group or off (equiv. to 0) - { - c8 smooth[WORD_BUFFER_LENGTH]; - bufPtr = goAndCopyNextWord(smooth, bufPtr, WORD_BUFFER_LENGTH, bufEnd); + { + c8 smooth[WORD_BUFFER_LENGTH]; + bufPtr = goAndCopyNextWord(smooth, bufPtr, WORD_BUFFER_LENGTH, bufEnd); #ifdef _IRR_DEBUG_OBJ_LOADER_ - os::Printer::log("Loaded smoothing group start",smooth, ELL_DEBUG); + os::Printer::log("Loaded smoothing group start", smooth, ELL_DEBUG); #endif - if (TAG_OFF==smooth) - smoothingGroup=0; - else - smoothingGroup=core::strtoul10(smooth); + if (TAG_OFF == smooth) + smoothingGroup = 0; + else + smoothingGroup = core::strtoul10(smooth); - (void)smoothingGroup; // disable unused variable warnings - } - break; + (void)smoothingGroup; // disable unused variable warnings + } break; case 'u': // usemtl // get name of material @@ -175,41 +161,39 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) c8 matName[WORD_BUFFER_LENGTH]; bufPtr = goAndCopyNextWord(matName, bufPtr, WORD_BUFFER_LENGTH, bufEnd); #ifdef _IRR_DEBUG_OBJ_LOADER_ - os::Printer::log("Loaded material start",matName, ELL_DEBUG); + os::Printer::log("Loaded material start", matName, ELL_DEBUG); #endif - mtlName=matName; - mtlChanged=true; + mtlName = matName; + mtlChanged = true; } break; - case 'f': // face + case 'f': // face { c8 vertexWord[WORD_BUFFER_LENGTH]; // for retrieving vertex data video::S3DVertex v; // Assign vertex color from currently active material's diffuse color - if (mtlChanged) - { + if (mtlChanged) { // retrieve the material SObjMtl *useMtl = findMtl(mtlName, grpName); // only change material if we found it if (useMtl) currMtl = useMtl; - mtlChanged=false; + mtlChanged = false; } if (currMtl) v.Color = currMtl->Meshbuffer->Material.DiffuseColor; // get all vertices data in this face (current line of obj file) const core::stringc wordBuffer = copyLine(bufPtr, bufEnd); - const c8* linePtr = wordBuffer.c_str(); - const c8* const endPtr = linePtr+wordBuffer.size(); + const c8 *linePtr = wordBuffer.c_str(); + const c8 *const endPtr = linePtr + wordBuffer.size(); faceCorners.set_used(0); // fast clear // read in all vertices linePtr = goNextWord(linePtr, endPtr); - while (0 != linePtr[0]) - { + while (0 != linePtr[0]) { // Array to communicate with retrieveVertexIndices() // sends the buffer sizes and gets the actual indices // if index not set returns -1 @@ -219,38 +203,33 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) // read in next vertex's data u32 wlength = copyWord(vertexWord, linePtr, WORD_BUFFER_LENGTH, endPtr); // this function will also convert obj's 1-based index to c++'s 0-based index - retrieveVertexIndices(vertexWord, Idx, vertexWord+wlength+1, vertexBuffer.size(), textureCoordBuffer.size(), normalsBuffer.size()); - if ( Idx[0] >= 0 && Idx[0] < (irr::s32)vertexBuffer.size() ) + retrieveVertexIndices(vertexWord, Idx, vertexWord + wlength + 1, vertexBuffer.size(), textureCoordBuffer.size(), normalsBuffer.size()); + if (Idx[0] >= 0 && Idx[0] < (irr::s32)vertexBuffer.size()) v.Pos = vertexBuffer[Idx[0]]; - else - { + else { os::Printer::log("Invalid vertex index in this line", wordBuffer.c_str(), ELL_ERROR); - delete [] buf; + delete[] buf; cleanUp(); return 0; } - if ( Idx[1] >= 0 && Idx[1] < (irr::s32)textureCoordBuffer.size() ) + if (Idx[1] >= 0 && Idx[1] < (irr::s32)textureCoordBuffer.size()) v.TCoords = textureCoordBuffer[Idx[1]]; else - v.TCoords.set(0.0f,0.0f); - if ( Idx[2] >= 0 && Idx[2] < (irr::s32)normalsBuffer.size() ) + v.TCoords.set(0.0f, 0.0f); + if (Idx[2] >= 0 && Idx[2] < (irr::s32)normalsBuffer.size()) v.Normal = normalsBuffer[Idx[2]]; - else - { - v.Normal.set(0.0f,0.0f,0.0f); - currMtl->RecalculateNormals=true; + else { + v.Normal.set(0.0f, 0.0f, 0.0f); + currMtl->RecalculateNormals = true; } int vertLocation; auto n = currMtl->VertMap.find(v); - if (n != currMtl->VertMap.end()) - { + if (n != currMtl->VertMap.end()) { vertLocation = n->second; - } - else - { + } else { currMtl->Meshbuffer->Vertices.push_back(v); - vertLocation = currMtl->Meshbuffer->Vertices.size() -1; + vertLocation = currMtl->Meshbuffer->Vertices.size() - 1; currMtl->VertMap.emplace(v, vertLocation); } @@ -260,70 +239,61 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) linePtr = goNextWord(linePtr, endPtr); } - if (faceCorners.size() < 3) - { + if (faceCorners.size() < 3) { os::Printer::log("Too few vertices in this line", wordBuffer.c_str(), ELL_ERROR); - delete [] buf; + delete[] buf; cleanUp(); return 0; } // triangulate the face const int c = faceCorners[0]; - for ( u32 i = 1; i < faceCorners.size() - 1; ++i ) - { + for (u32 i = 1; i < faceCorners.size() - 1; ++i) { // Add a triangle const int a = faceCorners[i + 1]; const int b = faceCorners[i]; - if (a != b && a != c && b != c) // ignore degenerated faces. We can get them when we merge vertices above in the VertMap. + if (a != b && a != c && b != c) // ignore degenerated faces. We can get them when we merge vertices above in the VertMap. { currMtl->Meshbuffer->Indices.push_back(a); currMtl->Meshbuffer->Indices.push_back(b); currMtl->Meshbuffer->Indices.push_back(c); - } - else - { + } else { ++degeneratedFaces; } } - } - break; + } break; case '#': // comment default: break; - } // end switch(bufPtr[0]) + } // end switch(bufPtr[0]) // eat up rest of line bufPtr = goNextLine(bufPtr, bufEnd); ++lineNr; - } // end while(bufPtr && (bufPtr-buf 0 ) - { + if (degeneratedFaces > 0) { irr::core::stringc log(degeneratedFaces); log += " degenerated faces removed in "; log += irr::core::stringc(fullName); os::Printer::log(log.c_str(), ELL_INFORMATION); } - SMesh* mesh = new SMesh(); + SMesh *mesh = new SMesh(); // Combine all the groups (meshbuffers) into the mesh - for ( u32 m = 0; m < Materials.size(); ++m ) - { - if ( Materials[m]->Meshbuffer->getIndexCount() > 0 ) - { + for (u32 m = 0; m < Materials.size(); ++m) { + if (Materials[m]->Meshbuffer->getIndexCount() > 0) { Materials[m]->Meshbuffer->recalculateBoundingBox(); if (Materials[m]->RecalculateNormals) SceneManager->getMeshManipulator()->recalculateNormals(Materials[m]->Meshbuffer); - mesh->addMeshBuffer( Materials[m]->Meshbuffer ); + mesh->addMeshBuffer(Materials[m]->Meshbuffer); } } // Create the Animated mesh if there's anything in the mesh - SAnimatedMesh* animMesh = 0; - if ( 0 != mesh->getMeshBufferCount() ) - { + SAnimatedMesh *animMesh = 0; + if (0 != mesh->getMeshBufferCount()) { mesh->recalculateBoundingBox(); animMesh = new SAnimatedMesh(); animMesh->Type = EAMT_OBJ; @@ -332,7 +302,7 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) } // Clean up the allocate obj file contents - delete [] buf; + delete[] buf; // more cleaning up cleanUp(); mesh->drop(); @@ -341,53 +311,50 @@ IAnimatedMesh* COBJMeshFileLoader::createMesh(io::IReadFile* file) } //! Read RGB color -const c8* COBJMeshFileLoader::readColor(const c8* bufPtr, video::SColor& color, const c8* const bufEnd) +const c8 *COBJMeshFileLoader::readColor(const c8 *bufPtr, video::SColor &color, const c8 *const bufEnd) { const u32 COLOR_BUFFER_LENGTH = 16; c8 colStr[COLOR_BUFFER_LENGTH]; bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd); - color.setRed((u32)core::round32(core::fast_atof(colStr)*255.f)); - bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd); - color.setGreen((u32)core::round32(core::fast_atof(colStr)*255.f)); - bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd); - color.setBlue((u32)core::round32(core::fast_atof(colStr)*255.f)); + color.setRed((u32)core::round32(core::fast_atof(colStr) * 255.f)); + bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd); + color.setGreen((u32)core::round32(core::fast_atof(colStr) * 255.f)); + bufPtr = goAndCopyNextWord(colStr, bufPtr, COLOR_BUFFER_LENGTH, bufEnd); + color.setBlue((u32)core::round32(core::fast_atof(colStr) * 255.f)); return bufPtr; } - //! Read 3d vector of floats -const c8* COBJMeshFileLoader::readVec3(const c8* bufPtr, core::vector3df& vec, const c8* const bufEnd) +const c8 *COBJMeshFileLoader::readVec3(const c8 *bufPtr, core::vector3df &vec, const c8 *const bufEnd) { const u32 WORD_BUFFER_LENGTH = 256; c8 wordBuffer[WORD_BUFFER_LENGTH]; bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd); - vec.X=-core::fast_atof(wordBuffer); // change handedness + vec.X = -core::fast_atof(wordBuffer); // change handedness bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd); - vec.Y=core::fast_atof(wordBuffer); + vec.Y = core::fast_atof(wordBuffer); bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd); - vec.Z=core::fast_atof(wordBuffer); + vec.Z = core::fast_atof(wordBuffer); return bufPtr; } - //! Read 2d vector of floats -const c8* COBJMeshFileLoader::readUV(const c8* bufPtr, core::vector2df& vec, const c8* const bufEnd) +const c8 *COBJMeshFileLoader::readUV(const c8 *bufPtr, core::vector2df &vec, const c8 *const bufEnd) { const u32 WORD_BUFFER_LENGTH = 256; c8 wordBuffer[WORD_BUFFER_LENGTH]; bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd); - vec.X=core::fast_atof(wordBuffer); + vec.X = core::fast_atof(wordBuffer); bufPtr = goAndCopyNextWord(wordBuffer, bufPtr, WORD_BUFFER_LENGTH, bufEnd); - vec.Y=1-core::fast_atof(wordBuffer); // change handedness + vec.Y = 1 - core::fast_atof(wordBuffer); // change handedness return bufPtr; } - //! Read boolean value represented as 'on' or 'off' -const c8* COBJMeshFileLoader::readBool(const c8* bufPtr, bool& tf, const c8* const bufEnd) +const c8 *COBJMeshFileLoader::readBool(const c8 *bufPtr, bool &tf, const c8 *const bufEnd) { const u32 BUFFER_LENGTH = 8; c8 tfStr[BUFFER_LENGTH]; @@ -397,32 +364,27 @@ const c8* COBJMeshFileLoader::readBool(const c8* bufPtr, bool& tf, const c8* con return bufPtr; } - -COBJMeshFileLoader::SObjMtl* COBJMeshFileLoader::findMtl(const core::stringc& mtlName, const core::stringc& grpName) +COBJMeshFileLoader::SObjMtl *COBJMeshFileLoader::findMtl(const core::stringc &mtlName, const core::stringc &grpName) { - COBJMeshFileLoader::SObjMtl* defMaterial = 0; + COBJMeshFileLoader::SObjMtl *defMaterial = 0; // search existing Materials for best match // exact match does return immediately, only name match means a new group - for (u32 i = 0; i < Materials.size(); ++i) - { - if ( Materials[i]->Name == mtlName ) - { - if ( Materials[i]->Group == grpName ) + for (u32 i = 0; i < Materials.size(); ++i) { + if (Materials[i]->Name == mtlName) { + if (Materials[i]->Group == grpName) return Materials[i]; else defMaterial = Materials[i]; } } // we found a partial match - if (defMaterial) - { + if (defMaterial) { Materials.push_back(new SObjMtl(*defMaterial)); Materials.getLast()->Group = grpName; return Materials.getLast(); } // we found a new group for a non-existent material - else if (grpName.size()) - { + else if (grpName.size()) { Materials.push_back(new SObjMtl(*Materials[0])); Materials.getLast()->Group = grpName; return Materials.getLast(); @@ -430,161 +392,138 @@ COBJMeshFileLoader::SObjMtl* COBJMeshFileLoader::findMtl(const core::stringc& mt return 0; } - //! skip space characters and stop on first non-space -const c8* COBJMeshFileLoader::goFirstWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines) +const c8 *COBJMeshFileLoader::goFirstWord(const c8 *buf, const c8 *const bufEnd, bool acrossNewlines) { // skip space characters if (acrossNewlines) - while((buf != bufEnd) && core::isspace(*buf)) + while ((buf != bufEnd) && core::isspace(*buf)) ++buf; else - while((buf != bufEnd) && core::isspace(*buf) && (*buf != '\n')) + while ((buf != bufEnd) && core::isspace(*buf) && (*buf != '\n')) ++buf; return buf; } - //! skip current word and stop at beginning of next one -const c8* COBJMeshFileLoader::goNextWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines) +const c8 *COBJMeshFileLoader::goNextWord(const c8 *buf, const c8 *const bufEnd, bool acrossNewlines) { // skip current word - while(( buf != bufEnd ) && !core::isspace(*buf)) + while ((buf != bufEnd) && !core::isspace(*buf)) ++buf; return goFirstWord(buf, bufEnd, acrossNewlines); } - //! Read until line break is reached and stop at the next non-space character -const c8* COBJMeshFileLoader::goNextLine(const c8* buf, const c8* const bufEnd) +const c8 *COBJMeshFileLoader::goNextLine(const c8 *buf, const c8 *const bufEnd) { // look for newline characters - while(buf != bufEnd) - { + while (buf != bufEnd) { // found it, so leave - if (*buf=='\n' || *buf=='\r') + if (*buf == '\n' || *buf == '\r') break; ++buf; } return goFirstWord(buf, bufEnd); } - -u32 COBJMeshFileLoader::copyWord(c8* outBuf, const c8* const inBuf, u32 outBufLength, const c8* const bufEnd) +u32 COBJMeshFileLoader::copyWord(c8 *outBuf, const c8 *const inBuf, u32 outBufLength, const c8 *const bufEnd) { if (!outBufLength) return 0; - if (!inBuf) - { + if (!inBuf) { *outBuf = 0; return 0; } u32 i = 0; - while(inBuf[i]) - { + while (inBuf[i]) { if (core::isspace(inBuf[i]) || &(inBuf[i]) == bufEnd) break; ++i; } - u32 length = core::min_(i, outBufLength-1); - for (u32 j=0; j= BUFFER_LENGTH ) - { + while (p != bufEnd) { + if (i >= BUFFER_LENGTH) { return false; } - if ( ( core::isdigit(*p)) || (*p == '-') ) - { + if ((core::isdigit(*p)) || (*p == '-')) { // build up the number word[i++] = *p; - } - else if ( *p == '/' || *p == ' ' || *p == '\0' ) - { + } else if (*p == '/' || *p == ' ' || *p == '\0') { // number is completed. Convert and store it word[i] = '\0'; // if no number was found index will become 0 and later on -1 by decrement idx[idxType] = core::strtol10(word); - if (idx[idxType]<0) - { - switch (idxType) - { - case 0: - idx[idxType] += vbsize; - break; - case 1: - idx[idxType] += vtsize; - break; - case 2: - idx[idxType] += vnsize; - break; + if (idx[idxType] < 0) { + switch (idxType) { + case 0: + idx[idxType] += vbsize; + break; + case 1: + idx[idxType] += vtsize; + break; + case 2: + idx[idxType] += vnsize; + break; } - } - else - idx[idxType]-=1; + } else + idx[idxType] -= 1; // reset the word word[0] = '\0'; i = 0; // go to the next kind of index type - if (*p == '/') - { - if ( ++idxType > 2 ) - { + if (*p == '/') { + if (++idxType > 2) { // error checking, shouldn't reach here unless file is wrong idxType = 0; } - } - else - { + } else { // set all missing values to disable (=-1) while (++idxType < 3) - idx[idxType]=-1; + idx[idxType] = -1; ++p; break; // while } @@ -597,11 +536,9 @@ bool COBJMeshFileLoader::retrieveVertexIndices(c8* vertexData, s32* idx, const c return true; } - void COBJMeshFileLoader::cleanUp() { - for (u32 i=0; i < Materials.size(); ++i ) - { + for (u32 i = 0; i < Materials.size(); ++i) { Materials[i]->Meshbuffer->drop(); delete Materials[i]; } @@ -609,6 +546,5 @@ void COBJMeshFileLoader::cleanUp() Materials.clear(); } - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/COBJMeshFileLoader.h b/source/Irrlicht/COBJMeshFileLoader.h index fb06e329..63e768e4 100644 --- a/source/Irrlicht/COBJMeshFileLoader.h +++ b/source/Irrlicht/COBJMeshFileLoader.h @@ -19,29 +19,28 @@ namespace scene class COBJMeshFileLoader : public IMeshLoader { public: - //! Constructor - COBJMeshFileLoader(scene::ISceneManager* smgr); + COBJMeshFileLoader(scene::ISceneManager *smgr); //! destructor virtual ~COBJMeshFileLoader(); //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".obj") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. - IAnimatedMesh* createMesh(io::IReadFile* file) override; + IAnimatedMesh *createMesh(io::IReadFile *file) override; private: - struct SObjMtl { - SObjMtl() : Meshbuffer(0), Bumpiness (1.0f), Illumination(0), - RecalculateNormals(false) + SObjMtl() : + Meshbuffer(0), Bumpiness(1.0f), Illumination(0), + RecalculateNormals(false) { Meshbuffer = new SMeshBuffer(); Meshbuffer->Material.Shininess = 0.0f; @@ -50,10 +49,10 @@ private: Meshbuffer->Material.SpecularColor = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f).toSColor(); } - SObjMtl(const SObjMtl& o) - : Name(o.Name), Group(o.Group), - Bumpiness(o.Bumpiness), Illumination(o.Illumination), - RecalculateNormals(false) + SObjMtl(const SObjMtl &o) : + Name(o.Name), Group(o.Group), + Bumpiness(o.Bumpiness), Illumination(o.Illumination), + RecalculateNormals(false) { Meshbuffer = new SMeshBuffer(); Meshbuffer->Material = o.Meshbuffer->Material; @@ -69,41 +68,41 @@ private: }; // returns a pointer to the first printable character available in the buffer - const c8* goFirstWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines=true); + const c8 *goFirstWord(const c8 *buf, const c8 *const bufEnd, bool acrossNewlines = true); // returns a pointer to the first printable character after the first non-printable - const c8* goNextWord(const c8* buf, const c8* const bufEnd, bool acrossNewlines=true); + const c8 *goNextWord(const c8 *buf, const c8 *const bufEnd, bool acrossNewlines = true); // returns a pointer to the next printable character after the first line break - const c8* goNextLine(const c8* buf, const c8* const bufEnd); + const c8 *goNextLine(const c8 *buf, const c8 *const bufEnd); // copies the current word from the inBuf to the outBuf - u32 copyWord(c8* outBuf, const c8* inBuf, u32 outBufLength, const c8* const pBufEnd); + u32 copyWord(c8 *outBuf, const c8 *inBuf, u32 outBufLength, const c8 *const pBufEnd); // copies the current line from the inBuf to the outBuf - core::stringc copyLine(const c8* inBuf, const c8* const bufEnd); + core::stringc copyLine(const c8 *inBuf, const c8 *const bufEnd); // combination of goNextWord followed by copyWord - const c8* goAndCopyNextWord(c8* outBuf, const c8* inBuf, u32 outBufLength, const c8* const pBufEnd); + const c8 *goAndCopyNextWord(c8 *outBuf, const c8 *inBuf, u32 outBufLength, const c8 *const pBufEnd); //! Find and return the material with the given name - SObjMtl* findMtl(const core::stringc& mtlName, const core::stringc& grpName); + SObjMtl *findMtl(const core::stringc &mtlName, const core::stringc &grpName); //! Read RGB color - const c8* readColor(const c8* bufPtr, video::SColor& color, const c8* const pBufEnd); + const c8 *readColor(const c8 *bufPtr, video::SColor &color, const c8 *const pBufEnd); //! Read 3d vector of floats - const c8* readVec3(const c8* bufPtr, core::vector3df& vec, const c8* const pBufEnd); + const c8 *readVec3(const c8 *bufPtr, core::vector3df &vec, const c8 *const pBufEnd); //! Read 2d vector of floats - const c8* readUV(const c8* bufPtr, core::vector2df& vec, const c8* const pBufEnd); + const c8 *readUV(const c8 *bufPtr, core::vector2df &vec, const c8 *const pBufEnd); //! Read boolean value represented as 'on' or 'off' - const c8* readBool(const c8* bufPtr, bool& tf, const c8* const bufEnd); + const c8 *readBool(const c8 *bufPtr, bool &tf, const c8 *const bufEnd); // reads and convert to integer the vertex indices in a line of obj file's face statement // -1 for the index if it doesn't exist // indices are changed to 0-based index instead of 1-based from the obj file - bool retrieveVertexIndices(c8* vertexData, s32* idx, const c8* bufEnd, u32 vbsize, u32 vtsize, u32 vnsize); + bool retrieveVertexIndices(c8 *vertexData, s32 *idx, const c8 *bufEnd, u32 vbsize, u32 vtsize, u32 vnsize); void cleanUp(); - scene::ISceneManager* SceneManager; + scene::ISceneManager *SceneManager; - core::array Materials; + core::array Materials; }; } // end namespace scene diff --git a/source/Irrlicht/COGLESCommon.h b/source/Irrlicht/COGLESCommon.h index 50a43307..24c96d14 100644 --- a/source/Irrlicht/COGLESCommon.h +++ b/source/Irrlicht/COGLESCommon.h @@ -13,7 +13,7 @@ #include #include typedef char GLchar; -#else // or only when defined(_IRR_COMPILE_WITH_ANDROID_DEVICE_) ? +#else // or only when defined(_IRR_COMPILE_WITH_ANDROID_DEVICE_) ? #include #include #include @@ -95,23 +95,23 @@ namespace irr namespace video { - // Forward declarations. +// Forward declarations. - class COpenGLCoreFeature; +class COpenGLCoreFeature; - template - class COpenGLCoreTexture; +template +class COpenGLCoreTexture; - template - class COpenGLCoreRenderTarget; +template +class COpenGLCoreRenderTarget; - template - class COpenGLCoreCacheHandler; +template +class COpenGLCoreCacheHandler; - class COGLES1Driver; - typedef COpenGLCoreTexture COGLES1Texture; - typedef COpenGLCoreRenderTarget COGLES1RenderTarget; - typedef COpenGLCoreCacheHandler COGLES1CacheHandler; +class COGLES1Driver; +typedef COpenGLCoreTexture COGLES1Texture; +typedef COpenGLCoreRenderTarget COGLES1RenderTarget; +typedef COpenGLCoreCacheHandler COGLES1CacheHandler; } } diff --git a/source/Irrlicht/COGLESCoreExtensionHandler.h b/source/Irrlicht/COGLESCoreExtensionHandler.h index 9a852fe9..c1619b6f 100644 --- a/source/Irrlicht/COGLESCoreExtensionHandler.h +++ b/source/Irrlicht/COGLESCoreExtensionHandler.h @@ -15,188 +15,176 @@ namespace irr namespace video { - class COGLESCoreExtensionHandler +class COGLESCoreExtensionHandler +{ +public: + // Enums used internally to check for ES extensions quickly. + // We buffer all extensions on start once in an array. + // All OpenGL ES versions share the same extensions (WebGL adds it's own extensions on top of ES2) + enum EOGLESFeatures { - public: - // Enums used internally to check for ES extensions quickly. - // We buffer all extensions on start once in an array. - // All OpenGL ES versions share the same extensions (WebGL adds it's own extensions on top of ES2) - enum EOGLESFeatures - { - // If you update this enum also update the corresponding OGLESFeatureStrings string-array - IRR_GL_APPLE_texture_2D_limited_npot, - IRR_GL_APPLE_texture_format_BGRA8888, - IRR_GL_EXT_blend_minmax, - IRR_GL_EXT_read_format_bgra, - IRR_GL_EXT_texture_filter_anisotropic, - IRR_GL_EXT_texture_format_BGRA8888, - IRR_GL_EXT_texture_lod_bias, - IRR_GL_EXT_texture_rg, - IRR_GL_IMG_read_format, - IRR_GL_IMG_texture_format_BGRA8888, - IRR_GL_IMG_user_clip_plane, - IRR_GL_OES_blend_func_separate, - IRR_GL_OES_blend_subtract, - IRR_GL_OES_depth_texture, - IRR_GL_OES_depth24, - IRR_GL_OES_depth32, - IRR_GL_OES_element_index_uint, - IRR_GL_OES_framebuffer_object, - IRR_GL_OES_packed_depth_stencil, - IRR_GL_OES_point_size_array, - IRR_GL_OES_point_sprite, - IRR_GL_OES_read_format, - IRR_GL_OES_stencil_wrap, - IRR_GL_OES_texture_float, - IRR_GL_OES_texture_half_float, - IRR_GL_OES_texture_mirrored_repeat, - IRR_GL_OES_texture_npot, + // If you update this enum also update the corresponding OGLESFeatureStrings string-array + IRR_GL_APPLE_texture_2D_limited_npot, + IRR_GL_APPLE_texture_format_BGRA8888, + IRR_GL_EXT_blend_minmax, + IRR_GL_EXT_read_format_bgra, + IRR_GL_EXT_texture_filter_anisotropic, + IRR_GL_EXT_texture_format_BGRA8888, + IRR_GL_EXT_texture_lod_bias, + IRR_GL_EXT_texture_rg, + IRR_GL_IMG_read_format, + IRR_GL_IMG_texture_format_BGRA8888, + IRR_GL_IMG_user_clip_plane, + IRR_GL_OES_blend_func_separate, + IRR_GL_OES_blend_subtract, + IRR_GL_OES_depth_texture, + IRR_GL_OES_depth24, + IRR_GL_OES_depth32, + IRR_GL_OES_element_index_uint, + IRR_GL_OES_framebuffer_object, + IRR_GL_OES_packed_depth_stencil, + IRR_GL_OES_point_size_array, + IRR_GL_OES_point_sprite, + IRR_GL_OES_read_format, + IRR_GL_OES_stencil_wrap, + IRR_GL_OES_texture_float, + IRR_GL_OES_texture_half_float, + IRR_GL_OES_texture_mirrored_repeat, + IRR_GL_OES_texture_npot, - IRR_OGLES_Feature_Count - }; - - COGLESCoreExtensionHandler() - : Version(0), MaxAnisotropy(1), MaxIndices(0xffff), - MaxTextureSize(1), MaxTextureLODBias(0.f), StencilBuffer(false) - { - for (u32 i = 0; i < IRR_OGLES_Feature_Count; ++i) - FeatureAvailable[i] = false; - - DimAliasedLine[0] = 1.f; - DimAliasedLine[1] = 1.f; - DimAliasedPoint[0] = 1.f; - DimAliasedPoint[1] = 1.f; - } - - virtual ~COGLESCoreExtensionHandler() {} - - const COpenGLCoreFeature& getFeature() const - { - return Feature; - } - - void dump() const - { - for (u32 i = 0; i < IRR_OGLES_Feature_Count; ++i) - os::Printer::log(getFeatureString(i), FeatureAvailable[i] ? " true" : " false"); - } - - bool queryGLESFeature(EOGLESFeatures feature) const - { - return FeatureAvailable[feature]; - } - - protected: - - const char* getFeatureString(size_t index) const - { - // One for each EOGLESFeatures - static const char* const OGLESFeatureStrings[IRR_OGLES_Feature_Count] = - { - "GL_APPLE_texture_2D_limited_npot", - "GL_APPLE_texture_format_BGRA8888", - "GL_EXT_blend_minmax", - "GL_EXT_read_format_bgra", - "GL_EXT_texture_filter_anisotropic", - "GL_EXT_texture_format_BGRA8888", - "GL_EXT_texture_lod_bias", - "GL_EXT_texture_rg", - "GL_IMG_read_format", - "GL_IMG_texture_format_BGRA8888", - "GL_IMG_user_clip_plane", - "GL_OES_blend_func_separate", - "GL_OES_blend_subtract", - "GL_OES_depth_texture", - "GL_OES_depth24", - "GL_OES_depth32", - "GL_OES_element_index_uint", - "GL_OES_framebuffer_object", - "GL_OES_packed_depth_stencil", - "GL_OES_point_size_array", - "GL_OES_point_sprite", - "GL_OES_read_format", - "GL_OES_stencil_wrap", - "GL_OES_texture_float", - "GL_OES_texture_half_float", - "GL_OES_texture_mirrored_repeat", - "GL_OES_texture_npot", - }; - - return OGLESFeatureStrings[index]; - } - - - void getGLVersion() - { - Version = 0; - s32 multiplier = 100; - - core::stringc version(glGetString(GL_VERSION)); - - for (u32 i = 0; i < version.size(); ++i) - { - if (version[i] >= '0' && version[i] <= '9') - { - if (multiplier > 1) - { - Version += static_cast(core::floor32(atof(&(version[i]))) * multiplier); - multiplier /= 10; - } - else - { - break; - } - } - } - } - - void getGLExtensions() - { - core::stringc extensions = glGetString(GL_EXTENSIONS); - os::Printer::log(extensions.c_str()); - - const u32 size = extensions.size() + 1; - c8* str = new c8[size]; - strncpy(str, extensions.c_str(), extensions.size()); - str[extensions.size()] = ' '; - c8* p = str; - - for (u32 i=0; i= '0' && version[i] <= '9') { + if (multiplier > 1) { + Version += static_cast(core::floor32(atof(&(version[i]))) * multiplier); + multiplier /= 10; + } else { + break; + } + } + } + } + + void getGLExtensions() + { + core::stringc extensions = glGetString(GL_EXTENSIONS); + os::Printer::log(extensions.c_str()); + + const u32 size = extensions.size() + 1; + c8 *str = new c8[size]; + strncpy(str, extensions.c_str(), extensions.size()); + str[extensions.size()] = ' '; + c8 *p = str; + + for (u32 i = 0; i < size; ++i) { + if (str[i] == ' ') { + str[i] = 0; + if (*p) + for (size_t j = 0; j < IRR_OGLES_Feature_Count; ++j) { + if (!strcmp(getFeatureString(j), p)) { + FeatureAvailable[j] = true; + break; + } + } + + p = p + strlen(p) + 1; + } + } + + delete[] str; + } + + COpenGLCoreFeature Feature; + + u16 Version; + u8 MaxAnisotropy; + u32 MaxIndices; + u32 MaxTextureSize; + f32 MaxTextureLODBias; + //! Minimal and maximal supported thickness for lines without smoothing + float DimAliasedLine[2]; + //! Minimal and maximal supported thickness for points without smoothing + float DimAliasedPoint[2]; + bool StencilBuffer; + bool FeatureAvailable[IRR_OGLES_Feature_Count]; +}; } } diff --git a/source/Irrlicht/COGLESDriver.cpp b/source/Irrlicht/COGLESDriver.cpp index 3e218d2f..a47f8876 100644 --- a/source/Irrlicht/COGLESDriver.cpp +++ b/source/Irrlicht/COGLESDriver.cpp @@ -28,16 +28,16 @@ namespace irr namespace video { -COGLES1Driver::COGLES1Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) : - CNullDriver(io, params.WindowSize), COGLES1ExtensionHandler(), CacheHandler(0), CurrentRenderMode(ERM_NONE), - ResetRenderStates(true), Transformation3DChanged(true), AntiAlias(params.AntiAlias), - ColorFormat(ECF_R8G8B8), Params(params), ContextManager(contextManager) +COGLES1Driver::COGLES1Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) : + CNullDriver(io, params.WindowSize), COGLES1ExtensionHandler(), CacheHandler(0), CurrentRenderMode(ERM_NONE), + ResetRenderStates(true), Transformation3DChanged(true), AntiAlias(params.AntiAlias), + ColorFormat(ECF_R8G8B8), Params(params), ContextManager(contextManager) { #ifdef _DEBUG setDebugName("COGLESDriver"); #endif - core::dimension2d windowSize(0, 0); + core::dimension2d windowSize(0, 0); if (!ContextManager) return; @@ -50,7 +50,7 @@ COGLES1Driver::COGLES1Driver(const SIrrlichtCreationParameters& params, io::IFil windowSize = params.WindowSize; - genericDriverInit(windowSize, params.Stencilbuffer); + genericDriverInit(windowSize, params.Stencilbuffer); } COGLES1Driver::~COGLES1Driver() @@ -66,8 +66,7 @@ COGLES1Driver::~COGLES1Driver() delete CacheHandler; - if (ContextManager) - { + if (ContextManager) { ContextManager->destroyContext(); ContextManager->destroySurface(); ContextManager->terminate(); @@ -79,9 +78,9 @@ COGLES1Driver::~COGLES1Driver() // METHODS // ----------------------------------------------------------------------- -bool COGLES1Driver::genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer) +bool COGLES1Driver::genericDriverInit(const core::dimension2d &screenSize, bool stencilBuffer) { - Name=glGetString(GL_VERSION); + Name = glGetString(GL_VERSION); printVersion(); // print renderer information @@ -111,8 +110,7 @@ bool COGLES1Driver::genericDriverInit(const core::dimension2d& screenSize, UserClipPlane.reallocate(MaxUserClipPlanes); UserClipPlaneEnabled.resize(MaxUserClipPlanes); - for (s32 i = 0; i < MaxUserClipPlanes; ++i) - { + for (s32 i = 0; i < MaxUserClipPlanes; ++i) { UserClipPlane.push_back(core::plane3df()); UserClipPlaneEnabled[i] = false; } @@ -150,7 +148,6 @@ bool COGLES1Driver::genericDriverInit(const core::dimension2d& screenSize, return true; } - void COGLES1Driver::createMaterialRenderers() { addAndDropMaterialRenderer(new COGLES1MaterialRenderer_SOLID(this)); @@ -160,7 +157,7 @@ void COGLES1Driver::createMaterialRenderers() addAndDropMaterialRenderer(new COGLES1MaterialRenderer_ONETEXTURE_BLEND(this)); } -bool COGLES1Driver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) +bool COGLES1Driver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData &videoData, core::rect *sourceRect) { CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); @@ -184,44 +181,37 @@ bool COGLES1Driver::endScene() return false; } - //! Returns the transformation set by setTransform -const core::matrix4& COGLES1Driver::getTransform(E_TRANSFORMATION_STATE state) const +const core::matrix4 &COGLES1Driver::getTransform(E_TRANSFORMATION_STATE state) const { return Matrices[state]; } - //! sets transformation -void COGLES1Driver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) +void COGLES1Driver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) { Matrices[state] = mat; Transformation3DChanged = true; - switch(state) - { + switch (state) { case ETS_VIEW: - case ETS_WORLD: - { - // OGLES1 only has a model matrix, view and world is not existent. so lets fake these two. - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf((Matrices[ETS_VIEW] * Matrices[ETS_WORLD]).pointer()); - // we have to update the clip planes to the latest view matrix - for (u32 i=0; iMeshBuffer; - const void* vertices=mb->getVertices(); - const u32 vertexCount=mb->getVertexCount(); - const E_VERTEX_TYPE vType=mb->getVertexType(); + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const u32 vertexCount = mb->getVertexCount(); + const E_VERTEX_TYPE vType = mb->getVertexType(); const u32 vertexSize = getVertexPitchFromType(vType); - //buffer vertex data, and convert colours... + // buffer vertex data, and convert colours... core::array buffer(vertexSize * vertexCount); buffer.set_used(vertexSize * vertexCount); memcpy(buffer.pointer(), vertices, vertexSize * vertexCount); // in order to convert the colors into opengl format (RGBA) - switch (vType) - { - case EVT_STANDARD: - { - S3DVertex* pb = reinterpret_cast(buffer.pointer()); - const S3DVertex* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertex *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color.color)); } - break; - case EVT_2TCOORDS: - { - S3DVertex2TCoords* pb = reinterpret_cast(buffer.pointer()); - const S3DVertex2TCoords* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertex2TCoords *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color.color)); } - break; - case EVT_TANGENTS: - { - S3DVertexTangents* pb = reinterpret_cast(buffer.pointer()); - const S3DVertexTangents* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertexTangents *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color.color)); } + } break; + default: { + return false; + } } - //get or create buffer - bool newBuffer=false; - if (!HWBuffer->vbo_verticesID) - { + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_verticesID) { glGenBuffers(1, &HWBuffer->vbo_verticesID); - if (!HWBuffer->vbo_verticesID) return false; - newBuffer=true; - } - else if (HWBuffer->vbo_verticesSize < vertexCount*vertexSize) - { - newBuffer=true; + if (!HWBuffer->vbo_verticesID) + return false; + newBuffer = true; + } else if (HWBuffer->vbo_verticesSize < vertexCount * vertexSize) { + newBuffer = true; } - glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID ); + glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); // copy data to graphics card if (!newBuffer) glBufferSubData(GL_ARRAY_BUFFER, 0, vertexCount * vertexSize, buffer.const_pointer()); - else - { - HWBuffer->vbo_verticesSize = vertexCount*vertexSize; + else { + HWBuffer->vbo_verticesSize = vertexCount * vertexSize; - if (HWBuffer->Mapped_Vertex==scene::EHM_STATIC) + if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC) glBufferData(GL_ARRAY_BUFFER, vertexCount * vertexSize, buffer.const_pointer(), GL_STATIC_DRAW); else glBufferData(GL_ARRAY_BUFFER, vertexCount * vertexSize, buffer.const_pointer(), GL_DYNAMIC_DRAW); @@ -315,48 +291,40 @@ bool COGLES1Driver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) return (!testGLError(__LINE__)); } - bool COGLES1Driver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) { if (!HWBuffer) return false; - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; - const void* indices=mb->getIndices(); - u32 indexCount= mb->getIndexCount(); + const void *indices = mb->getIndices(); + u32 indexCount = mb->getIndexCount(); GLenum indexSize; - switch (mb->getIndexType()) - { - case (EIT_16BIT): - { - indexSize=sizeof(u16); - break; - } - case (EIT_32BIT): - { - indexSize=sizeof(u32); - break; - } - default: - { - return false; - } + switch (mb->getIndexType()) { + case (EIT_16BIT): { + indexSize = sizeof(u16); + break; + } + case (EIT_32BIT): { + indexSize = sizeof(u32); + break; + } + default: { + return false; + } } - - //get or create buffer - bool newBuffer=false; - if (!HWBuffer->vbo_indicesID) - { + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_indicesID) { glGenBuffers(1, &HWBuffer->vbo_indicesID); - if (!HWBuffer->vbo_indicesID) return false; - newBuffer=true; - } - else if (HWBuffer->vbo_indicesSize < indexCount*indexSize) - { - newBuffer=true; + if (!HWBuffer->vbo_indicesID) + return false; + newBuffer = true; + } else if (HWBuffer->vbo_indicesSize < indexCount * indexSize) { + newBuffer = true; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); @@ -364,11 +332,10 @@ bool COGLES1Driver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) // copy data to graphics card if (!newBuffer) glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); - else - { - HWBuffer->vbo_indicesSize = indexCount*indexSize; + else { + HWBuffer->vbo_indicesSize = indexCount * indexSize; - if (HWBuffer->Mapped_Index==scene::EHM_STATIC) + if (HWBuffer->Mapped_Index == scene::EHM_STATIC) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW); else glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW); @@ -379,35 +346,28 @@ bool COGLES1Driver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) return (!testGLError(__LINE__)); } - //! updates hardware buffer if needed bool COGLES1Driver::updateHardwareBuffer(SHWBufferLink *HWBuffer) { if (!HWBuffer) return false; - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() - || !static_cast(HWBuffer)->vbo_verticesID) - { + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() || !static_cast(HWBuffer)->vbo_verticesID) { HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) + if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) return false; } } - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() - || !((SHWBufferLink_opengl*)HWBuffer)->vbo_indicesID) - { + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() || !((SHWBufferLink_opengl *)HWBuffer)->vbo_indicesID) { HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - if (!updateIndexHardwareBuffer(static_cast(HWBuffer))) + if (!updateIndexHardwareBuffer(static_cast(HWBuffer))) return false; } } @@ -415,29 +375,27 @@ bool COGLES1Driver::updateHardwareBuffer(SHWBufferLink *HWBuffer) return true; } - //! Create hardware buffer from meshbuffer -COGLES1Driver::SHWBufferLink *COGLES1Driver::createHardwareBuffer(const scene::IMeshBuffer* mb) +COGLES1Driver::SHWBufferLink *COGLES1Driver::createHardwareBuffer(const scene::IMeshBuffer *mb) { - if (!mb || (mb->getHardwareMappingHint_Index()==scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex()==scene::EHM_NEVER)) + if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) return 0; - SHWBufferLink_opengl *HWBuffer=new SHWBufferLink_opengl(mb); + SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); - //add to map + // add to map HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); - HWBuffer->ChangedID_Vertex=HWBuffer->MeshBuffer->getChangedID_Vertex(); - HWBuffer->ChangedID_Index=HWBuffer->MeshBuffer->getChangedID_Index(); - HWBuffer->Mapped_Vertex=mb->getHardwareMappingHint_Vertex(); - HWBuffer->Mapped_Index=mb->getHardwareMappingHint_Index(); - HWBuffer->vbo_verticesID=0; - HWBuffer->vbo_indicesID=0; - HWBuffer->vbo_verticesSize=0; - HWBuffer->vbo_indicesSize=0; + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); + HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); + HWBuffer->vbo_verticesID = 0; + HWBuffer->vbo_indicesID = 0; + HWBuffer->vbo_verticesSize = 0; + HWBuffer->vbo_indicesSize = 0; - if (!updateHardwareBuffer(HWBuffer)) - { + if (!updateHardwareBuffer(HWBuffer)) { deleteHardwareBuffer(HWBuffer); return 0; } @@ -445,86 +403,76 @@ COGLES1Driver::SHWBufferLink *COGLES1Driver::createHardwareBuffer(const scene::I return HWBuffer; } - void COGLES1Driver::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) { if (!_HWBuffer) return; - SHWBufferLink_opengl *HWBuffer=static_cast(_HWBuffer); - if (HWBuffer->vbo_verticesID) - { + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); + if (HWBuffer->vbo_verticesID) { glDeleteBuffers(1, &HWBuffer->vbo_verticesID); - HWBuffer->vbo_verticesID=0; + HWBuffer->vbo_verticesID = 0; } - if (HWBuffer->vbo_indicesID) - { + if (HWBuffer->vbo_indicesID) { glDeleteBuffers(1, &HWBuffer->vbo_indicesID); - HWBuffer->vbo_indicesID=0; + HWBuffer->vbo_indicesID = 0; } CNullDriver::deleteHardwareBuffer(_HWBuffer); } - //! Draw hardware buffer void COGLES1Driver::drawHardwareBuffer(SHWBufferLink *_HWBuffer) { if (!_HWBuffer) return; - SHWBufferLink_opengl *HWBuffer=static_cast(_HWBuffer); + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); - updateHardwareBuffer(HWBuffer); //check if update is needed + updateHardwareBuffer(HWBuffer); // check if update is needed - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void *vertices=mb->getVertices(); - const void *indexList=mb->getIndices(); + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const void *indexList = mb->getIndices(); - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) - { + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); - vertices=0; + vertices = 0; } - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) - { + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - indexList=0; + indexList = 0; } - drawVertexPrimitiveList(vertices, mb->getVertexCount(), indexList, mb->getPrimitiveCount(), mb->getVertexType(), mb->getPrimitiveType(), mb->getIndexType()); - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) glBindBuffer(GL_ARRAY_BUFFER, 0); - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } - -IRenderTarget* COGLES1Driver::addRenderTarget() +IRenderTarget *COGLES1Driver::addRenderTarget() { - COGLES1RenderTarget* renderTarget = new COGLES1RenderTarget(this); + COGLES1RenderTarget *renderTarget = new COGLES1RenderTarget(this); RenderTargets.push_back(renderTarget); return renderTarget; } - // small helper function to create vertex buffer object adress offsets -static inline u8* buffer_offset(const long offset) +static inline u8 *buffer_offset(const long offset) { - return ((u8*)0 + offset); + return ((u8 *)0 + offset); } - //! draws a vertex primitive list -void COGLES1Driver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, +void COGLES1Driver::drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { if (!checkPrimitiveCount(primitiveCount)) @@ -532,12 +480,11 @@ void COGLES1Driver::drawVertexPrimitiveList(const void* vertices, u32 vertexCoun setRenderStates3DMode(); - drawVertexPrimitiveList2d3d(vertices, vertexCount, (const u16*)indexList, primitiveCount, vType, pType, iType); + drawVertexPrimitiveList2d3d(vertices, vertexCount, (const u16 *)indexList, primitiveCount, vType, pType, iType); } - -void COGLES1Driver::drawVertexPrimitiveList2d3d(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, +void COGLES1Driver::drawVertexPrimitiveList2d3d(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType, bool threed) { if (!primitiveCount || !vertexCount) @@ -548,45 +495,34 @@ void COGLES1Driver::drawVertexPrimitiveList2d3d(const void* vertices, u32 vertex CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType); - if (vertices) - { + if (vertices) { // convert colors to gl color format. - vertexCount *= 4; //reused as color component count + vertexCount *= 4; // reused as color component count ColorBuffer.set_used(vertexCount); u32 i; - switch (vType) - { - case EVT_STANDARD: - { - const S3DVertex* p = static_cast(vertices); - for ( i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + switch (vType) { + case EVT_STANDARD: { + const S3DVertex *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; - case EVT_2TCOORDS: - { - const S3DVertex2TCoords* p = static_cast(vertices); - for ( i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + } break; + case EVT_2TCOORDS: { + const S3DVertex2TCoords *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; - case EVT_TANGENTS: - { - const S3DVertexTangents* p = static_cast(vertices); - for ( i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + } break; + case EVT_TANGENTS: { + const S3DVertexTangents *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; + } break; } } @@ -594,196 +530,174 @@ void COGLES1Driver::drawVertexPrimitiveList2d3d(const void* vertices, u32 vertex glClientActiveTexture(GL_TEXTURE0); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); - if ((pType!=scene::EPT_POINTS) && (pType!=scene::EPT_POINT_SPRITES)) + if ((pType != scene::EPT_POINTS) && (pType != scene::EPT_POINT_SPRITES)) glEnableClientState(GL_TEXTURE_COORD_ARRAY); #ifdef GL_OES_point_size_array - else if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_point_size_array] && (Material.Thickness==0.0f)) + else if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_point_size_array] && (Material.Thickness == 0.0f)) glEnableClientState(GL_POINT_SIZE_ARRAY_OES); #endif - if (threed && (pType!=scene::EPT_POINTS) && (pType!=scene::EPT_POINT_SPRITES)) + if (threed && (pType != scene::EPT_POINTS) && (pType != scene::EPT_POINT_SPRITES)) glEnableClientState(GL_NORMAL_ARRAY); if (vertices) glColorPointer(4, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); - switch (vType) - { - case EVT_STANDARD: + switch (vType) { + case EVT_STANDARD: + if (vertices) { + if (threed) + glNormalPointer(GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); + glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex), buffer_offset(12)); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), 0); + } + + if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache().get(1)) { + glClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - if (threed) - glNormalPointer(GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex), buffer_offset(12)); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), 0); - } + } + break; + case EVT_2TCOORDS: + if (vertices) { + if (threed) + glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); + glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(12)); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); + } - if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache().get(1)) - { - glClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - } - break; - case EVT_2TCOORDS: + if (Feature.MaxTextureUnits > 0) { + glClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - if (threed) - glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); - glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(12)); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); + } + break; + case EVT_TANGENTS: + if (vertices) { + if (threed) + glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); + glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(12)); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); + } - if (Feature.MaxTextureUnits > 0) - { - glClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); - } - break; - case EVT_TANGENTS: + if (Feature.MaxTextureUnits > 0) { + glClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - if (threed) - glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); - glVertexPointer((threed ? 3 : 2), GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Tangent); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(12)); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); - } + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(36)); - if (Feature.MaxTextureUnits > 0) - { - glClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Tangent); - else - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(36)); - - glClientActiveTexture(GL_TEXTURE0 + 2); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Binormal); - else - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(48)); - } - break; + glClientActiveTexture(GL_TEXTURE0 + 2); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + if (vertices) + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Binormal); + else + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(48)); + } + break; } - GLenum indexSize=0; + GLenum indexSize = 0; - switch (iType) - { - case (EIT_16BIT): - { - indexSize=GL_UNSIGNED_SHORT; - break; - } - case (EIT_32BIT): - { + switch (iType) { + case (EIT_16BIT): { + indexSize = GL_UNSIGNED_SHORT; + break; + } + case (EIT_32BIT): { #ifdef GL_OES_element_index_uint #ifndef GL_UNSIGNED_INT -#define GL_UNSIGNED_INT 0x1405 +#define GL_UNSIGNED_INT 0x1405 #endif - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) - indexSize=GL_UNSIGNED_INT; - else + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) + indexSize = GL_UNSIGNED_INT; + else #endif - indexSize=GL_UNSIGNED_SHORT; - break; - } + indexSize = GL_UNSIGNED_SHORT; + break; + } } - switch (pType) - { - case scene::EPT_POINTS: - case scene::EPT_POINT_SPRITES: - { + switch (pType) { + case scene::EPT_POINTS: + case scene::EPT_POINT_SPRITES: { #ifdef GL_OES_point_sprite - if (pType==scene::EPT_POINT_SPRITES && FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_point_sprite]) - glEnable(GL_POINT_SPRITE_OES); -#endif - // if ==0 we use the point size array - if (Material.Thickness!=0.f) - { - float quadratic[] = {0.0f, 0.0f, 10.01f}; - glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, quadratic); - float maxParticleSize=1.0f; - glGetFloatv(GL_POINT_SIZE_MAX, &maxParticleSize); -// maxParticleSize=maxParticleSize 0) - { - if (vType == EVT_TANGENTS) - { + if (Feature.MaxTextureUnits > 0) { + if (vType == EVT_TANGENTS) { glClientActiveTexture(GL_TEXTURE0 + 2); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } - if ((vType != EVT_STANDARD) || CacheHandler->getTextureCache().get(1)) - { + if ((vType != EVT_STANDARD) || CacheHandler->getTextureCache().get(1)) { glClientActiveTexture(GL_TEXTURE0 + 1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } @@ -791,7 +705,7 @@ void COGLES1Driver::drawVertexPrimitiveList2d3d(const void* vertices, u32 vertex } #ifdef GL_OES_point_size_array - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_point_size_array] && (Material.Thickness==0.0f)) + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_point_size_array] && (Material.Thickness == 0.0f)) glDisableClientState(GL_POINT_SIZE_ARRAY_OES); #endif @@ -801,13 +715,12 @@ void COGLES1Driver::drawVertexPrimitiveList2d3d(const void* vertices, u32 vertex glDisableClientState(GL_TEXTURE_COORD_ARRAY); } - //! draws a 2d image, using a color and the alpha channel of the texture -void COGLES1Driver::draw2DImage(const video::ITexture* texture, - const core::position2d& pos, - const core::rect& sourceRect, - const core::rect* clipRect, SColor color, - bool useAlphaChannelOfTexture) +void COGLES1Driver::draw2DImage(const video::ITexture *texture, + const core::position2d &pos, + const core::rect &sourceRect, + const core::rect *clipRect, SColor color, + bool useAlphaChannelOfTexture) { if (!texture) return; @@ -818,10 +731,8 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, core::position2d targetPos(pos); core::position2d sourcePos(sourceRect.UpperLeftCorner); core::dimension2d sourceSize(sourceRect.getSize()); - if (clipRect) - { - if (targetPos.X < clipRect->UpperLeftCorner.X) - { + if (clipRect) { + if (targetPos.X < clipRect->UpperLeftCorner.X) { sourceSize.Width += targetPos.X - clipRect->UpperLeftCorner.X; if (sourceSize.Width <= 0) return; @@ -830,15 +741,13 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, targetPos.X = clipRect->UpperLeftCorner.X; } - if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) - { + if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - clipRect->LowerRightCorner.X; if (sourceSize.Width <= 0) return; } - if (targetPos.Y < clipRect->UpperLeftCorner.Y) - { + if (targetPos.Y < clipRect->UpperLeftCorner.Y) { sourceSize.Height += targetPos.Y - clipRect->UpperLeftCorner.Y; if (sourceSize.Height <= 0) return; @@ -847,8 +756,7 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, targetPos.Y = clipRect->UpperLeftCorner.Y; } - if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) - { + if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - clipRect->LowerRightCorner.Y; if (sourceSize.Height <= 0) return; @@ -857,8 +765,7 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, // clip these coordinates - if (targetPos.X<0) - { + if (targetPos.X < 0) { sourceSize.Width += targetPos.X; if (sourceSize.Width <= 0) return; @@ -867,17 +774,15 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, targetPos.X = 0; } - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); - if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) - { + if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - renderTargetSize.Width; if (sourceSize.Width <= 0) return; } - if (targetPos.Y<0) - { + if (targetPos.Y < 0) { sourceSize.Height += targetPos.Y; if (sourceSize.Height <= 0) return; @@ -886,8 +791,7 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, targetPos.Y = 0; } - if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) - { + if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - renderTargetSize.Height; if (sourceSize.Height <= 0) return; @@ -898,92 +802,89 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, // texcoords need to be flipped horizontally for RTTs const bool isRTT = texture->isRenderTarget(); - const core::dimension2d& ss = texture->getOriginalSize(); + const core::dimension2d &ss = texture->getOriginalSize(); const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); const core::rect tcoords( sourcePos.X * invW, - (isRTT?(sourcePos.Y + sourceSize.Height):sourcePos.Y) * invH, + (isRTT ? (sourcePos.Y + sourceSize.Height) : sourcePos.Y) * invH, (sourcePos.X + sourceSize.Width) * invW, - (isRTT?sourcePos.Y:(sourcePos.Y + sourceSize.Height)) * invH); + (isRTT ? sourcePos.Y : (sourcePos.Y + sourceSize.Height)) * invH); const core::rect poss(targetPos, sourceSize); if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(color.getAlpha()<255, true, useAlphaChannelOfTexture); + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); - u16 indices[] = {0,1,2,3}; + u16 indices[] = {0, 1, 2, 3}; S3DVertex vertices[4]; - vertices[0] = S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0,0,1, color, tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); - vertices[1] = S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0,0,1, color, tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); - vertices[2] = S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0,0,1, color, tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); - vertices[3] = S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0,0,1, color, tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); + vertices[0] = S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0, 0, 1, color, tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); + vertices[1] = S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0, 0, 1, color, tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); + vertices[2] = S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0, 0, 1, color, tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); + vertices[3] = S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0, 0, 1, color, tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); drawVertexPrimitiveList2d3d(vertices, 4, indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT, false); } - //! The same, but with a four element array of colors, one for each vertex -void COGLES1Driver::draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect, - const video::SColor* const colors, bool useAlphaChannelOfTexture) +void COGLES1Driver::draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect, + const video::SColor *const colors, bool useAlphaChannelOfTexture) { if (!texture) return; // texcoords need to be flipped horizontally for RTTs const bool isRTT = texture->isRenderTarget(); - const core::dimension2du& ss = texture->getOriginalSize(); + const core::dimension2du &ss = texture->getOriginalSize(); const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); const core::rect tcoords( sourceRect.UpperLeftCorner.X * invW, - (isRTT?sourceRect.LowerRightCorner.Y:sourceRect.UpperLeftCorner.Y) * invH, + (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH, sourceRect.LowerRightCorner.X * invW, - (isRTT?sourceRect.UpperLeftCorner.Y:sourceRect.LowerRightCorner.Y) *invH); + (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) * invH); const video::SColor temp[4] = - { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF - }; + { + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF}; - const video::SColor* const useColor = colors ? colors : temp; + const video::SColor *const useColor = colors ? colors : temp; if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(useColor[0].getAlpha()<255 || useColor[1].getAlpha()<255 || - useColor[2].getAlpha()<255 || useColor[3].getAlpha()<255, + setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || + useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, true, useAlphaChannelOfTexture); - if (clipRect) - { + if (clipRect) { if (!clipRect->isValid()) return; glEnable(GL_SCISSOR_TEST); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height-clipRect->LowerRightCorner.Y, - clipRect->getWidth(), clipRect->getHeight()); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); + glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, + clipRect->getWidth(), clipRect->getHeight()); } - u16 indices[] = {0,1,2,3}; + u16 indices[] = {0, 1, 2, 3}; S3DVertex vertices[4]; - vertices[0] = S3DVertex((f32)destRect.UpperLeftCorner.X, (f32)destRect.UpperLeftCorner.Y, 0, 0,0,1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); - vertices[1] = S3DVertex((f32)destRect.LowerRightCorner.X, (f32)destRect.UpperLeftCorner.Y, 0, 0,0,1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); - vertices[2] = S3DVertex((f32)destRect.LowerRightCorner.X, (f32)destRect.LowerRightCorner.Y, 0, 0,0,1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); - vertices[3] = S3DVertex((f32)destRect.UpperLeftCorner.X, (f32)destRect.LowerRightCorner.Y, 0, 0,0,1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); + vertices[0] = S3DVertex((f32)destRect.UpperLeftCorner.X, (f32)destRect.UpperLeftCorner.Y, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); + vertices[1] = S3DVertex((f32)destRect.LowerRightCorner.X, (f32)destRect.UpperLeftCorner.Y, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); + vertices[2] = S3DVertex((f32)destRect.LowerRightCorner.X, (f32)destRect.LowerRightCorner.Y, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); + vertices[3] = S3DVertex((f32)destRect.UpperLeftCorner.X, (f32)destRect.LowerRightCorner.Y, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); drawVertexPrimitiveList2d3d(vertices, 4, indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT, false); if (clipRect) glDisable(GL_SCISSOR_TEST); } -void COGLES1Driver::draw2DImage(const video::ITexture* texture, u32 layer, bool flip) +void COGLES1Driver::draw2DImage(const video::ITexture *texture, u32 layer, bool flip) { if (!texture || !CacheHandler->getTextureCache().set(0, texture)) return; @@ -997,7 +898,7 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, u32 layer, bool Transformation3DChanged = true; - u16 indices[] = { 0,1,2,3 }; + u16 indices[] = {0, 1, 2, 3}; S3DVertex vertices[4]; vertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f); @@ -1020,14 +921,13 @@ void COGLES1Driver::draw2DImage(const video::ITexture* texture, u32 layer, bool drawVertexPrimitiveList2d3d(vertices, 4, indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT, false); } - //! draws a set of 2d images, using a color and the alpha channel of the texture if desired. -void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) +void COGLES1Driver::draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, + bool useAlphaChannelOfTexture) { if (!texture) return; @@ -1036,25 +936,24 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, if (!drawCount) return; - const core::dimension2d& ss = texture->getOriginalSize(); + const core::dimension2d &ss = texture->getOriginalSize(); if (!ss.Width || !ss.Height) return; const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(color.getAlpha()<255, true, useAlphaChannelOfTexture); + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); core::array vertices; core::array quadIndices; - vertices.reallocate(drawCount*4); - quadIndices.reallocate(drawCount*6); + vertices.reallocate(drawCount * 4); + quadIndices.reallocate(drawCount * 6); - for (u32 i=0; i sourcePos(sourceRects[i].UpperLeftCorner); // This needs to be signed as it may go negative. core::dimension2d sourceSize(sourceRects[i].getSize()); - if (clipRect) - { - if (targetPos.X < clipRect->UpperLeftCorner.X) - { + if (clipRect) { + if (targetPos.X < clipRect->UpperLeftCorner.X) { sourceSize.Width += targetPos.X - clipRect->UpperLeftCorner.X; if (sourceSize.Width <= 0) continue; @@ -1074,15 +971,13 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, targetPos.X = clipRect->UpperLeftCorner.X; } - if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) - { + if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - clipRect->LowerRightCorner.X; if (sourceSize.Width <= 0) continue; } - if (targetPos.Y < clipRect->UpperLeftCorner.Y) - { + if (targetPos.Y < clipRect->UpperLeftCorner.Y) { sourceSize.Height += targetPos.Y - clipRect->UpperLeftCorner.Y; if (sourceSize.Height <= 0) continue; @@ -1091,8 +986,7 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, targetPos.Y = clipRect->UpperLeftCorner.Y; } - if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) - { + if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - clipRect->LowerRightCorner.Y; if (sourceSize.Height <= 0) continue; @@ -1101,8 +995,7 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, // clip these coordinates - if (targetPos.X<0) - { + if (targetPos.X < 0) { sourceSize.Width += targetPos.X; if (sourceSize.Width <= 0) continue; @@ -1111,15 +1004,13 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, targetPos.X = 0; } - if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) - { + if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - renderTargetSize.Width; if (sourceSize.Width <= 0) continue; } - if (targetPos.Y<0) - { + if (targetPos.Y < 0) { sourceSize.Height += targetPos.Y; if (sourceSize.Height <= 0) continue; @@ -1128,8 +1019,7 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, targetPos.Y = 0; } - if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) - { + if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - renderTargetSize.Height; if (sourceSize.Height <= 0) continue; @@ -1147,29 +1037,28 @@ void COGLES1Driver::draw2DImageBatch(const video::ITexture* texture, const u32 vstart = vertices.size(); - vertices.push_back(S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0,0,1, color, tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); - vertices.push_back(S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0,0,1, color, tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); - vertices.push_back(S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0,0,1, color, tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); - vertices.push_back(S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0,0,1, color, tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); + vertices.push_back(S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0, 0, 1, color, tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); + vertices.push_back(S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.UpperLeftCorner.Y, 0, 0, 0, 1, color, tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); + vertices.push_back(S3DVertex((f32)poss.LowerRightCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0, 0, 1, color, tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); + vertices.push_back(S3DVertex((f32)poss.UpperLeftCorner.X, (f32)poss.LowerRightCorner.Y, 0, 0, 0, 1, color, tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); quadIndices.push_back(vstart); - quadIndices.push_back(vstart+1); - quadIndices.push_back(vstart+2); + quadIndices.push_back(vstart + 1); + quadIndices.push_back(vstart + 2); quadIndices.push_back(vstart); - quadIndices.push_back(vstart+2); - quadIndices.push_back(vstart+3); + quadIndices.push_back(vstart + 2); + quadIndices.push_back(vstart + 3); } if (vertices.size()) drawVertexPrimitiveList2d3d(vertices.pointer(), vertices.size(), - quadIndices.pointer(), vertices.size()/2, + quadIndices.pointer(), vertices.size() / 2, video::EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT, false); } - //! draw a 2d rectangle -void COGLES1Driver::draw2DRectangle(SColor color, const core::rect& position, - const core::rect* clip) +void COGLES1Driver::draw2DRectangle(SColor color, const core::rect &position, + const core::rect *clip) { setRenderStates2DMode(color.getAlpha() < 255, false, false); @@ -1181,20 +1070,19 @@ void COGLES1Driver::draw2DRectangle(SColor color, const core::rect& positio if (!pos.isValid()) return; - u16 indices[] = {0,1,2,3}; + u16 indices[] = {0, 1, 2, 3}; S3DVertex vertices[4]; - vertices[0] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0,0,1, color, 0,0); - vertices[1] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0,0,1, color, 0,0); - vertices[2] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0,0,1, color, 0,0); - vertices[3] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0,0,1, color, 0,0); + vertices[0] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0, 0, 1, color, 0, 0); + vertices[2] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0, 0, 1, color, 0, 0); + vertices[3] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0, 0, 1, color, 0, 0); drawVertexPrimitiveList2d3d(vertices, 4, indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT, false); } - //! draw an 2d rectangle -void COGLES1Driver::draw2DRectangle(const core::rect& position, - SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip) +void COGLES1Driver::draw2DRectangle(const core::rect &position, + SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip) { core::rect pos = position; @@ -1205,44 +1093,42 @@ void COGLES1Driver::draw2DRectangle(const core::rect& position, return; setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || - colorRightUp.getAlpha() < 255 || - colorLeftDown.getAlpha() < 255 || - colorRightDown.getAlpha() < 255, false, false); + colorRightUp.getAlpha() < 255 || + colorLeftDown.getAlpha() < 255 || + colorRightDown.getAlpha() < 255, + false, false); - u16 indices[] = {0,1,2,3}; + u16 indices[] = {0, 1, 2, 3}; S3DVertex vertices[4]; - vertices[0] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0,0,1, colorLeftUp, 0,0); - vertices[1] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0,0,1, colorRightUp, 0,0); - vertices[2] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0,0,1, colorRightDown, 0,0); - vertices[3] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0,0,1, colorLeftDown, 0,0); + vertices[0] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0, 0, 1, colorLeftUp, 0, 0); + vertices[1] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.UpperLeftCorner.Y, 0, 0, 0, 1, colorRightUp, 0, 0); + vertices[2] = S3DVertex((f32)pos.LowerRightCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0, 0, 1, colorRightDown, 0, 0); + vertices[3] = S3DVertex((f32)pos.UpperLeftCorner.X, (f32)pos.LowerRightCorner.Y, 0, 0, 0, 1, colorLeftDown, 0, 0); drawVertexPrimitiveList2d3d(vertices, 4, indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLE_FAN, EIT_16BIT, false); } - //! Draws a 2d line. -void COGLES1Driver::draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color) +void COGLES1Driver::draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color) { setRenderStates2DMode(color.getAlpha() < 255, false, false); - u16 indices[] = {0,1}; + u16 indices[] = {0, 1}; S3DVertex vertices[2]; - vertices[0] = S3DVertex((f32)start.X, (f32)start.Y, 0, 0,0,1, color, 0,0); - vertices[1] = S3DVertex((f32)end.X, (f32)end.Y, 0, 0,0,1, color, 1,1); + vertices[0] = S3DVertex((f32)start.X, (f32)start.Y, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex((f32)end.X, (f32)end.Y, 0, 0, 0, 1, color, 1, 1); drawVertexPrimitiveList2d3d(vertices, 2, indices, 1, video::EVT_STANDARD, scene::EPT_LINES, EIT_16BIT, false); } - //! creates a matrix in supplied GLfloat array to pass to OGLES1 -inline void COGLES1Driver::getGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m) +inline void COGLES1Driver::getGLMatrix(GLfloat gl_matrix[16], const core::matrix4 &m) { memcpy(gl_matrix, m.pointer(), 16 * sizeof(f32)); } - //! creates a opengltexturematrix from a D3D style texture matrix -inline void COGLES1Driver::getGLTextureMatrix(GLfloat *o, const core::matrix4& m) +inline void COGLES1Driver::getGLTextureMatrix(GLfloat *o, const core::matrix4 &m) { o[0] = m[0]; o[1] = m[1]; @@ -1265,25 +1151,25 @@ inline void COGLES1Driver::getGLTextureMatrix(GLfloat *o, const core::matrix4& m o[15] = 1.f; } -ITexture* COGLES1Driver::createDeviceDependentTexture(const io::path& name, IImage* image) +ITexture *COGLES1Driver::createDeviceDependentTexture(const io::path &name, IImage *image) { - core::array imageArray(1); + core::array imageArray(1); imageArray.push_back(image); - COGLES1Texture* texture = new COGLES1Texture(name, imageArray, ETT_2D, this); + COGLES1Texture *texture = new COGLES1Texture(name, imageArray, ETT_2D, this); return texture; } -ITexture* COGLES1Driver::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) +ITexture *COGLES1Driver::createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) { - COGLES1Texture* texture = new COGLES1Texture(name, image, ETT_CUBEMAP, this); + COGLES1Texture *texture = new COGLES1Texture(name, image, ETT_CUBEMAP, this); return texture; } //! Sets a material. All 3d drawing functions draw geometry now using this material. -void COGLES1Driver::setMaterial(const SMaterial& material) +void COGLES1Driver::setMaterial(const SMaterial &material) { Material = material; OverrideMaterial.apply(Material); @@ -1292,42 +1178,44 @@ void COGLES1Driver::setMaterial(const SMaterial& material) setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); } - //! prints error if an error happened. bool COGLES1Driver::testGLError(int code) { #ifdef _DEBUG GLenum g = glGetError(); - switch(g) - { + switch (g) { case GL_NO_ERROR: return false; case GL_INVALID_ENUM: - os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_INVALID_VALUE: - os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_INVALID_OPERATION: - os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_STACK_OVERFLOW: - os::Printer::log("GL_STACK_OVERFLOW", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_STACK_OVERFLOW", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_STACK_UNDERFLOW: - os::Printer::log("GL_STACK_UNDERFLOW", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_STACK_UNDERFLOW", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_OUT_OF_MEMORY: - os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); + break; }; -// _IRR_DEBUG_BREAK_IF(true); + // _IRR_DEBUG_BREAK_IF(true); return true; #else return false; #endif } - //! sets the needed renderstates void COGLES1Driver::setRenderStates3DMode() { - if (CurrentRenderMode != ERM_3D) - { + if (CurrentRenderMode != ERM_3D) { // Reset Texture Stages CacheHandler->setBlend(false); glDisable(GL_ALPHA_TEST); @@ -1346,8 +1234,7 @@ void COGLES1Driver::setRenderStates3DMode() ResetRenderStates = true; } - if ( ResetRenderStates || LastMaterial != Material) - { + if (ResetRenderStates || LastMaterial != Material) { // unset old material if (LastMaterial.MaterialType != Material.MaterialType && @@ -1357,7 +1244,7 @@ void COGLES1Driver::setRenderStates3DMode() // set new material. if (static_cast(Material.MaterialType) < MaterialRenderers.size()) MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( - Material, LastMaterial, ResetRenderStates, this); + Material, LastMaterial, ResetRenderStates, this); LastMaterial = Material; CacheHandler->correctCacheMaterial(LastMaterial); @@ -1370,56 +1257,52 @@ void COGLES1Driver::setRenderStates3DMode() CurrentRenderMode = ERM_3D; } - GLint COGLES1Driver::getTextureWrapMode(u8 clamp) const { - switch (clamp) - { - case ETC_CLAMP: - // return GL_CLAMP; not supported in ogl-es - return GL_CLAMP_TO_EDGE; - break; - case ETC_CLAMP_TO_EDGE: - return GL_CLAMP_TO_EDGE; - break; - case ETC_CLAMP_TO_BORDER: - // return GL_CLAMP_TO_BORDER; not supported in ogl-es - return GL_CLAMP_TO_EDGE; - break; - case ETC_MIRROR: + switch (clamp) { + case ETC_CLAMP: + // return GL_CLAMP; not supported in ogl-es + return GL_CLAMP_TO_EDGE; + break; + case ETC_CLAMP_TO_EDGE: + return GL_CLAMP_TO_EDGE; + break; + case ETC_CLAMP_TO_BORDER: + // return GL_CLAMP_TO_BORDER; not supported in ogl-es + return GL_CLAMP_TO_EDGE; + break; + case ETC_MIRROR: #ifdef GL_OES_texture_mirrored_repeat - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_texture_mirrored_repeat]) - return GL_MIRRORED_REPEAT_OES; - else + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_texture_mirrored_repeat]) + return GL_MIRRORED_REPEAT_OES; + else #endif return GL_REPEAT; - break; - // the next three are not yet supported at all - case ETC_MIRROR_CLAMP: - case ETC_MIRROR_CLAMP_TO_EDGE: - case ETC_MIRROR_CLAMP_TO_BORDER: + break; + // the next three are not yet supported at all + case ETC_MIRROR_CLAMP: + case ETC_MIRROR_CLAMP_TO_EDGE: + case ETC_MIRROR_CLAMP_TO_BORDER: #ifdef GL_OES_texture_mirrored_repeat - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_texture_mirrored_repeat]) - return GL_MIRRORED_REPEAT_OES; - else + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_texture_mirrored_repeat]) + return GL_MIRRORED_REPEAT_OES; + else #endif return GL_CLAMP_TO_EDGE; - break; - case ETC_REPEAT: - default: - return GL_REPEAT; - break; + break; + case ETC_REPEAT: + default: + return GL_REPEAT; + break; } } - //! Can be called by an IMaterialRenderer to make its work easier. -void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, - bool resetAllRenderStates) +void COGLES1Driver::setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, + bool resetAllRenderStates) { if (resetAllRenderStates || - lastmaterial.ColorMaterial != material.ColorMaterial) - { + lastmaterial.ColorMaterial != material.ColorMaterial) { // we only have diffuse_and_ambient in ogl-es if (material.ColorMaterial == ECM_DIFFUSE_AND_AMBIENT) glEnable(GL_COLOR_MATERIAL); @@ -1428,18 +1311,16 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } if (resetAllRenderStates || - lastmaterial.AmbientColor != material.AmbientColor || - lastmaterial.DiffuseColor != material.DiffuseColor || - lastmaterial.EmissiveColor != material.EmissiveColor || - lastmaterial.ColorMaterial != material.ColorMaterial) - { + lastmaterial.AmbientColor != material.AmbientColor || + lastmaterial.DiffuseColor != material.DiffuseColor || + lastmaterial.EmissiveColor != material.EmissiveColor || + lastmaterial.ColorMaterial != material.ColorMaterial) { GLfloat color[4]; const f32 inv = 1.0f / 255.0f; if ((material.ColorMaterial != video::ECM_AMBIENT) && - (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) - { + (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) { color[0] = material.AmbientColor.getRed() * inv; color[1] = material.AmbientColor.getGreen() * inv; color[2] = material.AmbientColor.getBlue() * inv; @@ -1448,8 +1329,7 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } if ((material.ColorMaterial != video::ECM_DIFFUSE) && - (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) - { + (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) { color[0] = material.DiffuseColor.getRed() * inv; color[1] = material.DiffuseColor.getGreen() * inv; color[2] = material.DiffuseColor.getBlue() * inv; @@ -1457,8 +1337,7 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color); } - if (material.ColorMaterial != video::ECM_EMISSIVE) - { + if (material.ColorMaterial != video::ECM_EMISSIVE) { color[0] = material.EmissiveColor.getRed() * inv; color[1] = material.EmissiveColor.getGreen() * inv; color[2] = material.EmissiveColor.getBlue() * inv; @@ -1468,16 +1347,14 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } if (resetAllRenderStates || - lastmaterial.SpecularColor != material.SpecularColor || - lastmaterial.Shininess != material.Shininess) - { - GLfloat color[]={0.f,0.f,0.f,1.f}; + lastmaterial.SpecularColor != material.SpecularColor || + lastmaterial.Shininess != material.Shininess) { + GLfloat color[] = {0.f, 0.f, 0.f, 1.f}; const f32 inv = 1.0f / 255.0f; // disable Specular colors if no shininess is set if ((material.Shininess != 0.0f) && - (material.ColorMaterial != video::ECM_SPECULAR)) - { + (material.ColorMaterial != video::ECM_SPECULAR)) { #ifdef GL_EXT_separate_specular_color if (FeatureAvailable[IRR_EXT_separate_specular_color]) glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); @@ -1490,20 +1367,18 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color); } #ifdef GL_EXT_separate_specular_color - else - if (FeatureAvailable[IRR_EXT_separate_specular_color]) - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); + else if (FeatureAvailable[IRR_EXT_separate_specular_color]) + glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); #endif } -// TODO ogl-es + // TODO ogl-es // fillmode -// if (resetAllRenderStates || (lastmaterial.Wireframe != material.Wireframe) || (lastmaterial.PointCloud != material.PointCloud)) -// glPolygonMode(GL_FRONT_AND_BACK, material.Wireframe ? GL_LINE : material.PointCloud? GL_POINT : GL_FILL); + // if (resetAllRenderStates || (lastmaterial.Wireframe != material.Wireframe) || (lastmaterial.PointCloud != material.PointCloud)) + // glPolygonMode(GL_FRONT_AND_BACK, material.Wireframe ? GL_LINE : material.PointCloud? GL_POINT : GL_FILL); // shademode - if (resetAllRenderStates || (lastmaterial.GouraudShading != material.GouraudShading)) - { + if (resetAllRenderStates || (lastmaterial.GouraudShading != material.GouraudShading)) { if (material.GouraudShading) glShadeModel(GL_SMOOTH); else @@ -1511,8 +1386,7 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } // lighting - if (resetAllRenderStates || (lastmaterial.Lighting != material.Lighting)) - { + if (resetAllRenderStates || (lastmaterial.Lighting != material.Lighting)) { if (material.Lighting) glEnable(GL_LIGHTING); else @@ -1520,85 +1394,70 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } // zbuffer - if (resetAllRenderStates || lastmaterial.ZBuffer != material.ZBuffer) - { - switch (material.ZBuffer) - { - case ECFN_DISABLED: - glDisable(GL_DEPTH_TEST); - break; - case ECFN_LESSEQUAL: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - break; - case ECFN_EQUAL: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_EQUAL); - break; - case ECFN_LESS: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LESS); - break; - case ECFN_NOTEQUAL: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_NOTEQUAL); - break; - case ECFN_GREATEREQUAL: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_GEQUAL); - break; - case ECFN_GREATER: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_GREATER); - break; - case ECFN_ALWAYS: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_ALWAYS); - break; - case ECFN_NEVER: - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_NEVER); - break; + if (resetAllRenderStates || lastmaterial.ZBuffer != material.ZBuffer) { + switch (material.ZBuffer) { + case ECFN_DISABLED: + glDisable(GL_DEPTH_TEST); + break; + case ECFN_LESSEQUAL: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + break; + case ECFN_EQUAL: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_EQUAL); + break; + case ECFN_LESS: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + break; + case ECFN_NOTEQUAL: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_NOTEQUAL); + break; + case ECFN_GREATEREQUAL: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_GEQUAL); + break; + case ECFN_GREATER: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_GREATER); + break; + case ECFN_ALWAYS: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_ALWAYS); + break; + case ECFN_NEVER: + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_NEVER); + break; } } // zwrite - if (getWriteZBuffer(material)) - { + if (getWriteZBuffer(material)) { glDepthMask(GL_TRUE); - } - else - { + } else { glDepthMask(GL_FALSE); } // back face culling - if (resetAllRenderStates || (lastmaterial.FrontfaceCulling != material.FrontfaceCulling) || (lastmaterial.BackfaceCulling != material.BackfaceCulling)) - { - if ((material.FrontfaceCulling) && (material.BackfaceCulling)) - { + if (resetAllRenderStates || (lastmaterial.FrontfaceCulling != material.FrontfaceCulling) || (lastmaterial.BackfaceCulling != material.BackfaceCulling)) { + if ((material.FrontfaceCulling) && (material.BackfaceCulling)) { glCullFace(GL_FRONT_AND_BACK); glEnable(GL_CULL_FACE); - } - else - if (material.BackfaceCulling) - { + } else if (material.BackfaceCulling) { glCullFace(GL_BACK); glEnable(GL_CULL_FACE); - } - else - if (material.FrontfaceCulling) - { + } else if (material.FrontfaceCulling) { glCullFace(GL_FRONT); glEnable(GL_CULL_FACE); - } - else + } else glDisable(GL_CULL_FACE); } // fog - if (resetAllRenderStates || lastmaterial.FogEnable != material.FogEnable) - { + if (resetAllRenderStates || lastmaterial.FogEnable != material.FogEnable) { if (material.FogEnable) glEnable(GL_FOG); else @@ -1606,8 +1465,7 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } // normalization - if (resetAllRenderStates || lastmaterial.NormalizeNormals != material.NormalizeNormals) - { + if (resetAllRenderStates || lastmaterial.NormalizeNormals != material.NormalizeNormals) { if (material.NormalizeNormals) glEnable(GL_NORMALIZE); else @@ -1615,26 +1473,22 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } // Color Mask - if (resetAllRenderStates || lastmaterial.ColorMask != material.ColorMask) - { + if (resetAllRenderStates || lastmaterial.ColorMask != material.ColorMask) { glColorMask( - (material.ColorMask & ECP_RED)?GL_TRUE:GL_FALSE, - (material.ColorMask & ECP_GREEN)?GL_TRUE:GL_FALSE, - (material.ColorMask & ECP_BLUE)?GL_TRUE:GL_FALSE, - (material.ColorMask & ECP_ALPHA)?GL_TRUE:GL_FALSE); + (material.ColorMask & ECP_RED) ? GL_TRUE : GL_FALSE, + (material.ColorMask & ECP_GREEN) ? GL_TRUE : GL_FALSE, + (material.ColorMask & ECP_BLUE) ? GL_TRUE : GL_FALSE, + (material.ColorMask & ECP_ALPHA) ? GL_TRUE : GL_FALSE); } // Blend Equation if (material.BlendOperation == EBO_NONE) CacheHandler->setBlend(false); - else - { + else { CacheHandler->setBlend(true); - if (queryFeature(EVDF_BLEND_OPERATIONS)) - { - switch (material.BlendOperation) - { + if (queryFeature(EVDF_BLEND_OPERATIONS)) { + switch (material.BlendOperation) { case EBO_ADD: #if defined(GL_OES_blend_subtract) CacheHandler->setBlendEquation(GL_FUNC_ADD_OES); @@ -1656,58 +1510,48 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } } - // Blend Factor - if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? - && material.MaterialType != EMT_ONETEXTURE_BLEND - ) - { - E_BLEND_FACTOR srcRGBFact = EBF_ZERO; - E_BLEND_FACTOR dstRGBFact = EBF_ZERO; - E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; - E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; - E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; - u32 alphaSource = 0; + // Blend Factor + if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? + && material.MaterialType != EMT_ONETEXTURE_BLEND) { + E_BLEND_FACTOR srcRGBFact = EBF_ZERO; + E_BLEND_FACTOR dstRGBFact = EBF_ZERO; + E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; + E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; + E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; + u32 alphaSource = 0; - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); - if (queryFeature(EVDF_BLEND_SEPARATE)) - { + if (queryFeature(EVDF_BLEND_SEPARATE)) { CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), - getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); - } - else - { + getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); + } else { CacheHandler->setBlendFunc(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact)); - } + } } // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver. // thickness - if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) - { - if (AntiAlias) - { -// glPointSize(core::clamp(static_cast(material.Thickness), DimSmoothedPoint[0], DimSmoothedPoint[1])); + if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) { + if (AntiAlias) { + // glPointSize(core::clamp(static_cast(material.Thickness), DimSmoothedPoint[0], DimSmoothedPoint[1])); // we don't use point smoothing glPointSize(core::clamp(static_cast(material.Thickness), DimAliasedPoint[0], DimAliasedPoint[1])); - } - else - { + } else { glPointSize(core::clamp(static_cast(material.Thickness), DimAliasedPoint[0], DimAliasedPoint[1])); glLineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); } } // Anti aliasing - if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) - { + if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) { if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - if ((AntiAlias >= 2) && (material.AntiAliasing & (EAAM_SIMPLE|EAAM_QUALITY))) + if ((AntiAlias >= 2) && (material.AntiAliasing & (EAAM_SIMPLE | EAAM_QUALITY))) glEnable(GL_MULTISAMPLE); else glDisable(GL_MULTISAMPLE); @@ -1718,15 +1562,14 @@ void COGLES1Driver::setBasicRenderStates(const SMaterial& material, const SMater } //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. -void COGLES1Driver::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates) +void COGLES1Driver::setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates) { // Set textures to TU/TIU and apply filters to them - for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) - { + for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) { CacheHandler->getTextureCache().set(i, material.TextureLayers[i].Texture); - const COGLES1Texture* tmpTexture = CacheHandler->getTextureCache().get(i); + const COGLES1Texture *tmpTexture = CacheHandler->getTextureCache().get(i); if (!tmpTexture) continue; @@ -1742,8 +1585,7 @@ void COGLES1Driver::setTextureRenderStates(const SMaterial& material, bool reset if (!isRTT && Matrices[ETS_TEXTURE_0 + i].isIdentity()) glLoadIdentity(); - else - { + else { GLfloat glmat[16]; if (isRTT) getGLTextureMatrix(glmat, Matrices[ETS_TEXTURE_0 + i] * TextureFlipMatrix); @@ -1753,60 +1595,47 @@ void COGLES1Driver::setTextureRenderStates(const SMaterial& material, bool reset } } - COGLES1Texture::SStatesCache& statesCache = tmpTexture->getStatesCache(); + COGLES1Texture::SStatesCache &statesCache = tmpTexture->getStatesCache(); if (resetAllRenderstates) statesCache.IsCached = false; #if defined(GL_EXT_texture_lod_bias) - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_lod_bias]) - { - if (material.TextureLayers[i].LODBias) - { + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_lod_bias]) { + if (material.TextureLayers[i].LODBias) { const float tmp = core::clamp(material.TextureLayers[i].LODBias * 0.125f, -MaxTextureLODBias, MaxTextureLODBias); glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, tmp); - } - else + } else glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.f); } #endif - if (!statesCache.IsCached || material.TextureLayers[i].MagFilter != statesCache.MagFilter) - { + if (!statesCache.IsCached || material.TextureLayers[i].MagFilter != statesCache.MagFilter) { E_TEXTURE_MAG_FILTER magFilter = material.TextureLayers[i].MagFilter; glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER, - magFilter == ETMAGF_NEAREST ? GL_NEAREST : - (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); + magFilter == ETMAGF_NEAREST ? GL_NEAREST : (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); statesCache.MagFilter = magFilter; } - if (material.UseMipMaps && tmpTexture->hasMipMaps()) - { + if (material.UseMipMaps && tmpTexture->hasMipMaps()) { if (!statesCache.IsCached || material.TextureLayers[i].MinFilter != statesCache.MinFilter || - !statesCache.MipMapStatus) - { + !statesCache.MipMapStatus) { E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : - minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST : - minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); + minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST + : minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR + : (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); statesCache.MinFilter = minFilter; statesCache.MipMapStatus = true; } - } - else - { + } else { if (!statesCache.IsCached || material.TextureLayers[i].MinFilter != statesCache.MinFilter || - statesCache.MipMapStatus) - { + statesCache.MipMapStatus) { E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); - + (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); statesCache.MinFilter = minFilter; statesCache.MipMapStatus = false; @@ -1815,23 +1644,20 @@ void COGLES1Driver::setTextureRenderStates(const SMaterial& material, bool reset #ifdef GL_EXT_texture_filter_anisotropic if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] && - (!statesCache.IsCached || material.TextureLayers[i].AnisotropicFilter != statesCache.AnisotropicFilter)) - { + (!statesCache.IsCached || material.TextureLayers[i].AnisotropicFilter != statesCache.AnisotropicFilter)) { glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT, - material.TextureLayers[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); + material.TextureLayers[i].AnisotropicFilter > 1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); statesCache.AnisotropicFilter = material.TextureLayers[i].AnisotropicFilter; } #endif - if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapU != statesCache.WrapU) - { + if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapU != statesCache.WrapU) { glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayers[i].TextureWrapU)); statesCache.WrapU = material.TextureLayers[i].TextureWrapU; } - if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapV != statesCache.WrapV) - { + if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapV != statesCache.WrapV) { glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayers[i].TextureWrapV)); statesCache.WrapV = material.TextureLayers[i].TextureWrapV; } @@ -1843,23 +1669,19 @@ void COGLES1Driver::setTextureRenderStates(const SMaterial& material, bool reset CacheHandler->setActiveTexture(GL_TEXTURE0); } - //! sets the needed renderstates void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) { - if (CurrentRenderMode != ERM_2D || Transformation3DChanged) - { + if (CurrentRenderMode != ERM_2D || Transformation3DChanged) { // unset last 3d material - if (CurrentRenderMode == ERM_3D) - { + if (CurrentRenderMode == ERM_3D) { if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); } - if (Transformation3DChanged) - { + if (Transformation3DChanged) { glMatrixMode(GL_PROJECTION); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); core::matrix4 m(core::matrix4::EM4CONST_NOTHING); m.buildProjectionMatrixOrthoLH(f32(renderTargetSize.Width), f32(-(s32)(renderTargetSize.Height)), -1.0f, 1.0f); m.setTranslation(core::vector3df(-1, 1, 0)); @@ -1874,7 +1696,7 @@ void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh Material = (OverrideMaterial2DEnabled) ? OverrideMaterial2D : InitMaterial2D; Material.Lighting = false; - Material.TextureLayers[0].Texture = (texture) ? const_cast(CacheHandler->getTextureCache().get(0)) : 0; + Material.TextureLayers[0].Texture = (texture) ? const_cast(CacheHandler->getTextureCache().get(0)) : 0; setTransform(ETS_TEXTURE_0, core::IdentityMatrix); setBasicRenderStates(Material, LastMaterial, false); @@ -1885,35 +1707,27 @@ void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh // no alphaChannel without texture alphaChannel &= texture; - if (alphaChannel || alpha) - { + if (alphaChannel || alpha) { CacheHandler->setBlend(true); CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CacheHandler->setBlendEquation(GL_FUNC_ADD); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.f); - } - else - { + } else { CacheHandler->setBlend(false); glDisable(GL_ALPHA_TEST); } - if (texture) - { + if (texture) { // Due to the transformation change, the previous line would call a reset each frame // but we can safely reset the variable as it was false before Transformation3DChanged = false; - if (alphaChannel) - { + if (alphaChannel) { // if alpha and alpha texture just modulate, otherwise use only the alpha channel - if (alpha) - { + if (alpha) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } - else - { + } else { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE); @@ -1922,11 +1736,8 @@ void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR); } - } - else - { - if (alpha) - { + } else { + if (alpha) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PRIMARY_COLOR); @@ -1934,9 +1745,7 @@ void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR); - } - else - { + } else { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } } @@ -1945,25 +1754,22 @@ void COGLES1Driver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh CurrentRenderMode = ERM_2D; } - //! \return Returns the name of the video driver. -const char* COGLES1Driver::getName() const +const char *COGLES1Driver::getName() const { return Name.c_str(); } - //! Sets the dynamic ambient light color. -void COGLES1Driver::setAmbientLight(const SColorf& color) +void COGLES1Driver::setAmbientLight(const SColorf &color) { CNullDriver::setAmbientLight(color); GLfloat data[4] = {color.r, color.g, color.b, color.a}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, data); } - // this code was sent in by Oliver Klems, thank you -void COGLES1Driver::setViewPort(const core::rect& area) +void COGLES1Driver::setViewPort(const core::rect &area) { core::rect vp = area; core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); @@ -1975,33 +1781,30 @@ void COGLES1Driver::setViewPort(const core::rect& area) ViewPort = vp; } - void COGLES1Driver::setViewPortRaw(u32 width, u32 height) { CacheHandler->setViewport(0, 0, width, height); ViewPort = core::recti(0, 0, width, height); } - //! Sets the fog mode. void COGLES1Driver::setFog(SColor c, E_FOG_TYPE fogType, f32 start, - f32 end, f32 density, bool pixelFog, bool rangeFog) + f32 end, f32 density, bool pixelFog, bool rangeFog) { CNullDriver::setFog(c, fogType, start, end, density, pixelFog, rangeFog); - glFogf(GL_FOG_MODE, GLfloat((fogType==EFT_FOG_LINEAR)? GL_LINEAR : (fogType==EFT_FOG_EXP)?GL_EXP:GL_EXP2)); + glFogf(GL_FOG_MODE, GLfloat((fogType == EFT_FOG_LINEAR) ? GL_LINEAR : (fogType == EFT_FOG_EXP) ? GL_EXP + : GL_EXP2)); #ifdef GL_EXT_fog_coord if (FeatureAvailable[IRR_EXT_fog_coord]) glFogi(GL_FOG_COORDINATE_SOURCE, GL_FRAGMENT_DEPTH); #endif - if (fogType==EFT_FOG_LINEAR) - { + if (fogType == EFT_FOG_LINEAR) { glFogf(GL_FOG_START, start); glFogf(GL_FOG_END, end); - } - else + } else glFogf(GL_FOG_DENSITY, density); if (pixelFog) @@ -2014,114 +1817,108 @@ void COGLES1Driver::setFog(SColor c, E_FOG_TYPE fogType, f32 start, glFogfv(GL_FOG_COLOR, data); } - //! Draws a 3d line. -void COGLES1Driver::draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color) +void COGLES1Driver::draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color) { setRenderStates3DMode(); - u16 indices[] = {0,1}; + u16 indices[] = {0, 1}; S3DVertex vertices[2]; - vertices[0] = S3DVertex(start.X,start.Y,start.Z, 0,0,1, color, 0,0); - vertices[1] = S3DVertex(end.X,end.Y,end.Z, 0,0,1, color, 0,0); + vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0); drawVertexPrimitiveList2d3d(vertices, 2, indices, 1, video::EVT_STANDARD, scene::EPT_LINES); } - //! Only used by the internal engine. Used to notify the driver that //! the window was resized. -void COGLES1Driver::OnResize(const core::dimension2d& size) +void COGLES1Driver::OnResize(const core::dimension2d &size) { CNullDriver::OnResize(size); CacheHandler->setViewport(0, 0, size.Width, size.Height); Transformation3DChanged = true; } - //! Returns type of video driver E_DRIVER_TYPE COGLES1Driver::getDriverType() const { return EDT_OGLES1; } - //! returns color format ECOLOR_FORMAT COGLES1Driver::getColorFormat() const { return ColorFormat; } - //! Get a vertex shader constant index. -s32 COGLES1Driver::getVertexShaderConstantID(const c8* name) +s32 COGLES1Driver::getVertexShaderConstantID(const c8 *name) { return getPixelShaderConstantID(name); } //! Get a pixel shader constant index. -s32 COGLES1Driver::getPixelShaderConstantID(const c8* name) +s32 COGLES1Driver::getPixelShaderConstantID(const c8 *name) { os::Printer::log("Error: Please use IMaterialRendererServices from IShaderConstantSetCallBack::OnSetConstants not VideoDriver->getPixelShaderConstantID()."); return -1; } //! Sets a constant for the vertex shader based on an index. -bool COGLES1Driver::setVertexShaderConstant(s32 index, const f32* floats, int count) +bool COGLES1Driver::setVertexShaderConstant(s32 index, const f32 *floats, int count) { - //pass this along, as in GLSL the same routine is used for both vertex and fragment shaders + // pass this along, as in GLSL the same routine is used for both vertex and fragment shaders return setPixelShaderConstant(index, floats, count); } //! Int interface for the above. -bool COGLES1Driver::setVertexShaderConstant(s32 index, const s32* ints, int count) +bool COGLES1Driver::setVertexShaderConstant(s32 index, const s32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } -bool COGLES1Driver::setVertexShaderConstant(s32 index, const u32* ints, int count) +bool COGLES1Driver::setVertexShaderConstant(s32 index, const u32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } //! Sets a constant for the pixel shader based on an index. -bool COGLES1Driver::setPixelShaderConstant(s32 index, const f32* floats, int count) +bool COGLES1Driver::setPixelShaderConstant(s32 index, const f32 *floats, int count) { os::Printer::log("Error: Please use IMaterialRendererServices from IShaderConstantSetCallBack::OnSetConstants not VideoDriver->setPixelShaderConstant()."); return false; } //! Int interface for the above. -bool COGLES1Driver::setPixelShaderConstant(s32 index, const s32* ints, int count) +bool COGLES1Driver::setPixelShaderConstant(s32 index, const s32 *ints, int count) { os::Printer::log("Error: Please use IMaterialRendererServices from IShaderConstantSetCallBack::OnSetConstants not VideoDriver->setPixelShaderConstant()."); return false; } -bool COGLES1Driver::setPixelShaderConstant(s32 index, const u32* ints, int count) +bool COGLES1Driver::setPixelShaderConstant(s32 index, const u32 *ints, int count) { os::Printer::log("Error: Please use IMaterialRendererServices from IShaderConstantSetCallBack::OnSetConstants not VideoDriver->setPixelShaderConstant()."); return false; } - //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. s32 COGLES1Driver::addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, - E_GEOMETRY_SHADER_TYPE gsCompileTarget, - scene::E_PRIMITIVE_TYPE inType, - scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, + E_GEOMETRY_SHADER_TYPE gsCompileTarget, + scene::E_PRIMITIVE_TYPE inType, + scene::E_PRIMITIVE_TYPE outType, + u32 verticesOut, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) { os::Printer::log("No shader support."); return -1; @@ -2129,23 +1926,21 @@ s32 COGLES1Driver::addHighLevelShaderMaterial( //! Returns a pointer to the IVideoDriver interface. (Implementation for //! IMaterialRendererServices) -IVideoDriver* COGLES1Driver::getVideoDriver() +IVideoDriver *COGLES1Driver::getVideoDriver() { return this; } - //! Returns pointer to the IGPUProgrammingServices interface. -IGPUProgrammingServices* COGLES1Driver::getGPUProgrammingServices() +IGPUProgrammingServices *COGLES1Driver::getGPUProgrammingServices() { return this; } - -ITexture* COGLES1Driver::addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format) +ITexture *COGLES1Driver::addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format) { - //disable mip-mapping + // disable mip-mapping bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); @@ -2153,25 +1948,24 @@ ITexture* COGLES1Driver::addRenderTargetTexture(const core::dimension2d& si core::dimension2du destSize(size); - if (!supportForFBO) - { + if (!supportForFBO) { destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); } - COGLES1Texture* renderTargetTexture = new COGLES1Texture(name, destSize, ETT_2D, format, this); + COGLES1Texture *renderTargetTexture = new COGLES1Texture(name, destSize, ETT_2D, format, this); addTexture(renderTargetTexture); renderTargetTexture->drop(); - //restore mip-mapping + // restore mip-mapping setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); return renderTargetTexture; } -ITexture* COGLES1Driver::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format) +ITexture *COGLES1Driver::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path &name, const ECOLOR_FORMAT format) { - //disable mip-mapping + // disable mip-mapping bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); @@ -2180,17 +1974,16 @@ ITexture* COGLES1Driver::addRenderTargetTextureCubemap(const irr::u32 sideLen, c const core::dimension2d size(sideLen, sideLen); core::dimension2du destSize(size); - if (!supportForFBO) - { + if (!supportForFBO) { destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); } - COGLES1Texture* renderTargetTexture = new COGLES1Texture(name, destSize, ETT_CUBEMAP, format, this); + COGLES1Texture *renderTargetTexture = new COGLES1Texture(name, destSize, ETT_CUBEMAP, format, this); addTexture(renderTargetTexture); renderTargetTexture->drop(); - //restore mip-mapping + // restore mip-mapping setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); return renderTargetTexture; @@ -2202,10 +1995,9 @@ u32 COGLES1Driver::getMaximalPrimitiveCount() const return 65535; } -bool COGLES1Driver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) +bool COGLES1Driver::setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) { - if (target && target->getDriverType() != EDT_OGLES1) - { + if (target && target->getDriverType() != EDT_OGLES1) { os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL driver.", ELL_ERROR); return false; } @@ -2214,12 +2006,10 @@ bool COGLES1Driver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol core::dimension2d destRenderTargetSize(0, 0); - if (target) - { - COGLES1RenderTarget* renderTarget = static_cast(target); + if (target) { + COGLES1RenderTarget *renderTarget = static_cast(target); - if (supportForFBO) - { + if (supportForFBO) { CacheHandler->setFBO(renderTarget->getBufferID()); renderTarget->update(); } @@ -2227,19 +2017,15 @@ bool COGLES1Driver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol destRenderTargetSize = renderTarget->getSize(); setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); - } - else - { + } else { if (supportForFBO) CacheHandler->setFBO(0); - else - { - COGLES1RenderTarget* prevRenderTarget = static_cast(CurrentRenderTarget); - COGLES1Texture* renderTargetTexture = static_cast(prevRenderTarget->getTexture()); + else { + COGLES1RenderTarget *prevRenderTarget = static_cast(CurrentRenderTarget); + COGLES1Texture *renderTargetTexture = static_cast(prevRenderTarget->getTexture()); - if (renderTargetTexture) - { - const COGLES1Texture* prevTexture = CacheHandler->getTextureCache().get(0); + if (renderTargetTexture) { + const COGLES1Texture *prevTexture = CacheHandler->getTextureCache().get(0); CacheHandler->getTextureCache().set(0, renderTargetTexture); @@ -2255,8 +2041,7 @@ bool COGLES1Driver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol setViewPortRaw(ScreenSize.Width, ScreenSize.Height); } - if (CurrentRenderTargetSize != destRenderTargetSize) - { + if (CurrentRenderTargetSize != destRenderTargetSize) { CurrentRenderTargetSize = destRenderTargetSize; Transformation3DChanged = true; @@ -2264,8 +2049,7 @@ bool COGLES1Driver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol CurrentRenderTarget = target; - if (!supportForFBO) - { + if (!supportForFBO) { clearFlag |= ECBF_COLOR; clearFlag |= ECBF_DEPTH; } @@ -2279,26 +2063,23 @@ void COGLES1Driver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) { GLbitfield mask = 0; - if (flag & ECBF_COLOR) - { + if (flag & ECBF_COLOR) { glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); const f32 inv = 1.0f / 255.0f; glClearColor(color.getRed() * inv, color.getGreen() * inv, - color.getBlue() * inv, color.getAlpha() * inv); + color.getBlue() * inv, color.getAlpha() * inv); mask |= GL_COLOR_BUFFER_BIT; } - if (flag & ECBF_DEPTH) - { + if (flag & ECBF_DEPTH) { glDepthMask(GL_TRUE); glClearDepthf(depth); mask |= GL_DEPTH_BUFFER_BIT; } - if (flag & ECBF_STENCIL) - { + if (flag & ECBF_STENCIL) { glClearStencil(stencil); mask |= GL_STENCIL_BUFFER_BIT; } @@ -2307,58 +2088,49 @@ void COGLES1Driver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) glClear(mask); } - //! Returns an image created from the last rendered frame. // We want to read the front buffer to get the latest render finished. // This is not possible under ogl-es, though, so one has to call this method // outside of the render loop only. -IImage* COGLES1Driver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) +IImage *COGLES1Driver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) { - if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS) + if (target == video::ERT_MULTI_RENDER_TEXTURES || target == video::ERT_RENDER_TEXTURE || target == video::ERT_STEREO_BOTH_BUFFERS) return 0; - GLint internalformat=GL_RGBA; - GLint type=GL_UNSIGNED_BYTE; - if (false - && (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_IMG_read_format] - || FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_read_format] - || FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_read_format_bgra])) - { + GLint internalformat = GL_RGBA; + GLint type = GL_UNSIGNED_BYTE; + if (false && (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_IMG_read_format] || FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_read_format] || FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_read_format_bgra])) { #ifdef GL_IMPLEMENTATION_COLOR_READ_TYPE_OES glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES, &internalformat); glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE_OES, &type); #endif // there are formats we don't support ATM - if (GL_UNSIGNED_SHORT_4_4_4_4==type) - type=GL_UNSIGNED_SHORT_5_5_5_1; + if (GL_UNSIGNED_SHORT_4_4_4_4 == type) + type = GL_UNSIGNED_SHORT_5_5_5_1; #ifdef GL_EXT_read_format_bgra - else if (GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT==type) - type=GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT; + else if (GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT == type) + type = GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT; #endif } - IImage* newImage = 0; - if ((GL_RGBA==internalformat) + IImage *newImage = 0; + if ((GL_RGBA == internalformat) #ifdef GL_EXT_read_format_bgra - || (GL_BGRA_EXT==internalformat) + || (GL_BGRA_EXT == internalformat) #endif - ) - { - if (GL_UNSIGNED_BYTE==type) + ) { + if (GL_UNSIGNED_BYTE == type) newImage = new CImage(ECF_A8R8G8B8, ScreenSize); else newImage = new CImage(ECF_A1R5G5B5, ScreenSize); - } - else - { - if (GL_UNSIGNED_BYTE==type) + } else { + if (GL_UNSIGNED_BYTE == type) newImage = new CImage(ECF_R8G8B8, ScreenSize); else newImage = new CImage(ECF_R5G6B5, ScreenSize); } - u8* pixels = static_cast(newImage->getData()); - if (!pixels) - { + u8 *pixels = static_cast(newImage->getData()); + if (!pixels) { newImage->drop(); return 0; } @@ -2366,21 +2138,19 @@ IImage* COGLES1Driver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels); // opengl images are horizontally flipped, so we have to fix that here. - const s32 pitch=newImage->getPitch(); - u8* p2 = pixels + (ScreenSize.Height - 1) * pitch; - u8* tmpBuffer = new u8[pitch]; - for (u32 i=0; i < ScreenSize.Height; i += 2) - { + const s32 pitch = newImage->getPitch(); + u8 *p2 = pixels + (ScreenSize.Height - 1) * pitch; + u8 *tmpBuffer = new u8[pitch]; + for (u32 i = 0; i < ScreenSize.Height; i += 2) { memcpy(tmpBuffer, pixels, pitch); memcpy(pixels, p2, pitch); memcpy(p2, tmpBuffer, pitch); pixels += pitch; p2 -= pitch; } - delete [] tmpBuffer; + delete[] tmpBuffer; - if (testGLError(__LINE__)) - { + if (testGLError(__LINE__)) { newImage->drop(); return 0; } @@ -2388,25 +2158,23 @@ IImage* COGLES1Driver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE return newImage; } -void COGLES1Driver::removeTexture(ITexture* texture) +void COGLES1Driver::removeTexture(ITexture *texture) { CacheHandler->getTextureCache().remove(texture); CNullDriver::removeTexture(texture); } - //! Set/unset a clipping plane. -bool COGLES1Driver::setClipPlane(u32 index, const core::plane3df& plane, bool enable) +bool COGLES1Driver::setClipPlane(u32 index, const core::plane3df &plane, bool enable) { if (index >= MaxUserClipPlanes) return false; - UserClipPlane[index]=plane; + UserClipPlane[index] = plane; enableClipPlane(index, enable); return true; } - void COGLES1Driver::uploadClipPlane(u32 index) { // opengl needs an array of doubles for the plane equation @@ -2418,49 +2186,42 @@ void COGLES1Driver::uploadClipPlane(u32 index) glClipPlanef(GL_CLIP_PLANE0 + index, clip_plane); } - //! Enable/disable a clipping plane. void COGLES1Driver::enableClipPlane(u32 index, bool enable) { if (index >= MaxUserClipPlanes) return; - if (enable) - { - if (!UserClipPlaneEnabled[index]) - { + if (enable) { + if (!UserClipPlaneEnabled[index]) { uploadClipPlane(index); glEnable(GL_CLIP_PLANE0 + index); } - } - else + } else glDisable(GL_CLIP_PLANE0 + index); - UserClipPlaneEnabled[index]=enable; + UserClipPlaneEnabled[index] = enable; } - core::dimension2du COGLES1Driver::getMaxTextureSize() const { return core::dimension2du(MaxTextureSize, MaxTextureSize); } - GLenum COGLES1Driver::getGLBlend(E_BLEND_FACTOR factor) const { static GLenum const blendTable[] = - { - GL_ZERO, - GL_ONE, - GL_DST_COLOR, - GL_ONE_MINUS_DST_COLOR, - GL_SRC_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_SRC_ALPHA, - GL_ONE_MINUS_SRC_ALPHA, - GL_DST_ALPHA, - GL_ONE_MINUS_DST_ALPHA, - GL_SRC_ALPHA_SATURATE - }; + { + GL_ZERO, + GL_ONE, + GL_DST_COLOR, + GL_ONE_MINUS_DST_COLOR, + GL_SRC_COLOR, + GL_ONE_MINUS_SRC_COLOR, + GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA, + GL_DST_ALPHA, + GL_ONE_MINUS_DST_ALPHA, + GL_SRC_ALPHA_SATURATE}; return blendTable[factor]; } @@ -2469,8 +2230,7 @@ GLenum COGLES1Driver::getZBufferBits() const { GLenum bits = 0; - switch (Params.ZBufferBits) - { + switch (Params.ZBufferBits) { case 24: #if defined(GL_OES_depth24) if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth24)) @@ -2495,8 +2255,8 @@ GLenum COGLES1Driver::getZBufferBits() const return bits; } -bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const +bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const { bool supported = false; internalFormat = GL_RGBA; @@ -2504,8 +2264,7 @@ bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern pixelType = GL_UNSIGNED_BYTE; *converter = 0; - switch (format) - { + switch (format) { case ECF_A1R5G5B5: supported = true; internalFormat = GL_RGBA; @@ -2528,14 +2287,11 @@ bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern case ECF_A8R8G8B8: supported = true; if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) || - queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) || - queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888)) - { + queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) || + queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888)) { internalFormat = GL_BGRA; pixelFormat = GL_BGRA; - } - else - { + } else { internalFormat = GL_RGBA; pixelFormat = GL_RGBA; *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8; @@ -2550,8 +2306,7 @@ bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern break; case ECF_D32: #if defined(GL_OES_depth32) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32)) - { + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32)) { supported = true; internalFormat = GL_DEPTH_COMPONENT32_OES; pixelFormat = GL_DEPTH_COMPONENT; @@ -2561,8 +2316,7 @@ bool COGLES1Driver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern break; case ECF_D24S8: #ifdef GL_OES_packed_depth_stencil - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil)) - { + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil)) { supported = true; internalFormat = GL_DEPTH24_STENCIL8_OES; pixelFormat = GL_DEPTH_STENCIL_OES; @@ -2607,16 +2361,16 @@ bool COGLES1Driver::queryTextureFormat(ECOLOR_FORMAT format) const GLint dummyInternalFormat; GLenum dummyPixelFormat; GLenum dummyPixelType; - void (*dummyConverter)(const void*, s32, void*); + void (*dummyConverter)(const void *, s32, void *); return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter); } -bool COGLES1Driver::needsTransparentRenderPass(const irr::video::SMaterial& material) const +bool COGLES1Driver::needsTransparentRenderPass(const irr::video::SMaterial &material) const { return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); } -COGLES1CacheHandler* COGLES1Driver::getCacheHandler() const +COGLES1CacheHandler *COGLES1Driver::getCacheHandler() const { return CacheHandler; } @@ -2636,7 +2390,7 @@ class IVideoDriver; class IContextManager; #endif -IVideoDriver* createOGLES1Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) +IVideoDriver *createOGLES1Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) { #ifdef _IRR_COMPILE_WITH_OGLES1_ return new COGLES1Driver(params, io, contextManager); diff --git a/source/Irrlicht/COGLESDriver.h b/source/Irrlicht/COGLESDriver.h index 25dce6b0..8733ab36 100644 --- a/source/Irrlicht/COGLESDriver.h +++ b/source/Irrlicht/COGLESDriver.h @@ -20,306 +20,305 @@ namespace irr namespace video { - class COGLES1Driver : public CNullDriver, public IMaterialRendererServices, public COGLES1ExtensionHandler +class COGLES1Driver : public CNullDriver, public IMaterialRendererServices, public COGLES1ExtensionHandler +{ + friend class COpenGLCoreTexture; + +public: + //! constructor + COGLES1Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); + + //! destructor + virtual ~COGLES1Driver(); + + virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) override; + + bool endScene() override; + + //! sets transformation + void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) override; + + struct SHWBufferLink_opengl : public SHWBufferLink { - friend class COpenGLCoreTexture; + SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer) : + SHWBufferLink(_MeshBuffer), vbo_verticesID(0), vbo_indicesID(0) {} - public: - //! constructor - COGLES1Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); + GLuint vbo_verticesID; // tmp + GLuint vbo_indicesID; // tmp - //! destructor - virtual ~COGLES1Driver(); + GLuint vbo_verticesSize; // tmp + GLuint vbo_indicesSize; // tmp + }; - virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; + bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool endScene() override; + //! updates hardware buffer if needed + bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; - //! sets transformation - void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; + //! Create hardware buffer from mesh + SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer *mb) override; + //! Delete hardware buffer (only some drivers can) + void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - struct SHWBufferLink_opengl : public SHWBufferLink - { - SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer): SHWBufferLink(_MeshBuffer), vbo_verticesID(0),vbo_indicesID(0){} + //! Draw hardware buffer + void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - GLuint vbo_verticesID; //tmp - GLuint vbo_indicesID; //tmp + IRenderTarget *addRenderTarget() override; - GLuint vbo_verticesSize; //tmp - GLuint vbo_indicesSize; //tmp + //! draws a vertex primitive list + virtual void drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - }; + void drawVertexPrimitiveList2d3d(const void *vertices, u32 vertexCount, const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType = EIT_16BIT, bool threed = true); - bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + //! queries the features of the driver, returns true if feature is available + bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override + { + // return FeatureEnabled[feature] && COGLES1ExtensionHandler::queryFeature(feature); + return COGLES1ExtensionHandler::queryFeature(feature); + } - //! updates hardware buffer if needed - bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; + //! Sets a material. + void setMaterial(const SMaterial &material) override; - //! Create hardware buffer from mesh - SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) override; - - //! Delete hardware buffer (only some drivers can) - void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - - //! Draw hardware buffer - void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - - IRenderTarget* addRenderTarget() override; - - //! draws a vertex primitive list - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - - void drawVertexPrimitiveList2d3d(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType=EIT_16BIT, bool threed=true); - - //! queries the features of the driver, returns true if feature is available - bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override - { -// return FeatureEnabled[feature] && COGLES1ExtensionHandler::queryFeature(feature); - return COGLES1ExtensionHandler::queryFeature(feature); - } - - //! Sets a material. - void setMaterial(const SMaterial& material) override; - - virtual void draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect = 0, + virtual void draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect = 0, SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect = 0, - const video::SColor* const colors = 0, bool useAlphaChannelOfTexture = false) override; + virtual void draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect = 0, + const video::SColor *const colors = 0, bool useAlphaChannelOfTexture = false) override; - virtual void draw2DImage(const video::ITexture* texture, u32 layer, bool flip); + virtual void draw2DImage(const video::ITexture *texture, u32 layer, bool flip); - //! draws a set of 2d images, using a color and the alpha channel of the texture if desired. - virtual void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect=0, - SColor color=SColor(255,255,255,255), - bool useAlphaChannelOfTexture=false) override; + //! draws a set of 2d images, using a color and the alpha channel of the texture if desired. + virtual void draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), + bool useAlphaChannelOfTexture = false) override; - //! draw an 2d rectangle - virtual void draw2DRectangle(SColor color, const core::rect& pos, - const core::rect* clip = 0) override; + //! draw an 2d rectangle + virtual void draw2DRectangle(SColor color, const core::rect &pos, + const core::rect *clip = 0) override; - //!Draws an 2d rectangle with a gradient. - virtual void draw2DRectangle(const core::rect& pos, + //! Draws an 2d rectangle with a gradient. + virtual void draw2DRectangle(const core::rect &pos, SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip = 0) override; + const core::rect *clip = 0) override; - //! Draws a 2d line. - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color=SColor(255,255,255,255)) override; + //! Draws a 2d line. + virtual void draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! Draws a 3d line. - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, - SColor color = SColor(255,255,255,255)) override; + //! Draws a 3d line. + virtual void draw3DLine(const core::vector3df &start, + const core::vector3df &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! Returns the name of the video driver. - const char* getName() const override; + //! Returns the name of the video driver. + const char *getName() const override; - //! Sets the dynamic ambient light color. - void setAmbientLight(const SColorf& color) override; + //! Sets the dynamic ambient light color. + void setAmbientLight(const SColorf &color) override; - //! sets a viewport - void setViewPort(const core::rect& area) override; + //! sets a viewport + void setViewPort(const core::rect &area) override; - //! Sets the fog mode. - virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start, + //! Sets the fog mode. + virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, f32 density, bool pixelFog, bool rangeFog) override; - //! Only used internally by the engine - void OnResize(const core::dimension2d& size) override; + //! Only used internally by the engine + void OnResize(const core::dimension2d &size) override; - //! Returns type of video driver - E_DRIVER_TYPE getDriverType() const override; + //! Returns type of video driver + E_DRIVER_TYPE getDriverType() const override; - //! get color format of the current color buffer - ECOLOR_FORMAT getColorFormat() const override; + //! get color format of the current color buffer + ECOLOR_FORMAT getColorFormat() const override; - //! Returns the transformation set by setTransform - const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; + //! Returns the transformation set by setTransform + const core::matrix4 &getTransform(E_TRANSFORMATION_STATE state) const override; - //! Can be called by an IMaterialRenderer to make its work easier. - virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, + //! Can be called by an IMaterialRenderer to make its work easier. + virtual void setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, bool resetAllRenderstates) override; - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - virtual void setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates); + //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. + virtual void setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates); - //! Get a vertex shader constant index. - s32 getVertexShaderConstantID(const c8* name) override; + //! Get a vertex shader constant index. + s32 getVertexShaderConstantID(const c8 *name) override; - //! Get a pixel shader constant index. - s32 getPixelShaderConstantID(const c8* name) override; + //! Get a pixel shader constant index. + s32 getPixelShaderConstantID(const c8 *name) override; - //! Sets a constant for the vertex shader based on an index. - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; + //! Sets a constant for the vertex shader based on an index. + bool setVertexShaderConstant(s32 index, const f32 *floats, int count) override; - //! Int interface for the above. - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; + //! Int interface for the above. + bool setVertexShaderConstant(s32 index, const s32 *ints, int count) override; - //! Uint interface for the above. - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; + //! Uint interface for the above. + bool setVertexShaderConstant(s32 index, const u32 *ints, int count) override; - //! Sets a constant for the pixel shader based on an index. - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; + //! Sets a constant for the pixel shader based on an index. + bool setPixelShaderConstant(s32 index, const f32 *floats, int count) override; - //! Int interface for the above. - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; + //! Int interface for the above. + bool setPixelShaderConstant(s32 index, const s32 *ints, int count) override; - //! Uint interface for the above. - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + //! Uint interface for the above. + bool setPixelShaderConstant(s32 index, const u32 *ints, int count) override; - //! Adds a new material renderer to the VideoDriver - virtual s32 addHighLevelShaderMaterial(const c8* vertexShaderProgram, const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, const c8* pixelShaderProgram, const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, const c8* geometryShaderProgram, const c8* geometryShaderEntryPointName, + //! Adds a new material renderer to the VideoDriver + virtual s32 addHighLevelShaderMaterial(const c8 *vertexShaderProgram, const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, const c8 *pixelShaderProgram, const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, const c8 *geometryShaderProgram, const c8 *geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, + u32 verticesOut, IShaderConstantSetCallBack *callback, E_MATERIAL_TYPE baseMaterial, s32 userData) override; - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* getGPUProgrammingServices() override; + //! Returns pointer to the IGPUProgrammingServices interface. + IGPUProgrammingServices *getGPUProgrammingServices() override; - //! Returns a pointer to the IVideoDriver interface. - IVideoDriver* getVideoDriver() override; + //! Returns a pointer to the IVideoDriver interface. + IVideoDriver *getVideoDriver() override; - //! Returns the maximum amount of primitives - u32 getMaximalPrimitiveCount() const override; + //! Returns the maximum amount of primitives + u32 getMaximalPrimitiveCount() const override; - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + virtual ITexture *addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; - //! Creates a render target texture for a cubemap - ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) override; + //! Creates a render target texture for a cubemap + ITexture *addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name, const ECOLOR_FORMAT format) override; - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), + virtual bool setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0) override; - void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; + void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; - //! Returns an image created from the last rendered frame. - IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; + //! Returns an image created from the last rendered frame. + IImage *createScreenShot(video::ECOLOR_FORMAT format = video::ECF_UNKNOWN, video::E_RENDER_TARGET target = video::ERT_FRAME_BUFFER) override; - //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) - bool testGLError(int code=0); + //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) + bool testGLError(int code = 0); - //! Set/unset a clipping plane. - bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false) override; + //! Set/unset a clipping plane. + bool setClipPlane(u32 index, const core::plane3df &plane, bool enable = false) override; - //! Enable/disable a clipping plane. - void enableClipPlane(u32 index, bool enable) override; + //! Enable/disable a clipping plane. + void enableClipPlane(u32 index, bool enable) override; - //! Returns the graphics card vendor name. - core::stringc getVendorInfo() override - { - return VendorName; - } + //! Returns the graphics card vendor name. + core::stringc getVendorInfo() override + { + return VendorName; + } - //! Get the maximal texture size for this driver - core::dimension2du getMaxTextureSize() const override; + //! Get the maximal texture size for this driver + core::dimension2du getMaxTextureSize() const override; - void removeTexture(ITexture* texture) override; + void removeTexture(ITexture *texture) override; - //! Check if the driver supports creating textures with the given color format - bool queryTextureFormat(ECOLOR_FORMAT format) const override; + //! Check if the driver supports creating textures with the given color format + bool queryTextureFormat(ECOLOR_FORMAT format) const override; - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + bool needsTransparentRenderPass(const irr::video::SMaterial &material) const override; - //! Convert E_BLEND_FACTOR to OpenGL equivalent - GLenum getGLBlend(E_BLEND_FACTOR factor) const; + //! Convert E_BLEND_FACTOR to OpenGL equivalent + GLenum getGLBlend(E_BLEND_FACTOR factor) const; - //! Get ZBuffer bits. - GLenum getZBufferBits() const; + //! Get ZBuffer bits. + GLenum getZBufferBits() const; - bool getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const; + bool getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const; - COGLES1CacheHandler* getCacheHandler() const; + COGLES1CacheHandler *getCacheHandler() const; - private: - void uploadClipPlane(u32 index); +private: + void uploadClipPlane(u32 index); - //! inits the opengl-es driver - bool genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer); + //! inits the opengl-es driver + bool genericDriverInit(const core::dimension2d &screenSize, bool stencilBuffer); - ITexture* createDeviceDependentTexture(const io::path& name, IImage* image) override; + ITexture *createDeviceDependentTexture(const io::path &name, IImage *image) override; - ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) override; + ITexture *createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) override; - //! creates a transposed matrix in supplied GLfloat array to pass to OGLES1 - inline void getGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m); - inline void getGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4& m); + //! creates a transposed matrix in supplied GLfloat array to pass to OGLES1 + inline void getGLMatrix(GLfloat gl_matrix[16], const core::matrix4 &m); + inline void getGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4 &m); - //! Set GL pipeline to desired texture wrap modes of the material - void setWrapMode(const SMaterial& material); + //! Set GL pipeline to desired texture wrap modes of the material + void setWrapMode(const SMaterial &material); - //! Get OpenGL wrap enum from Irrlicht enum - GLint getTextureWrapMode(u8 clamp) const; + //! Get OpenGL wrap enum from Irrlicht enum + GLint getTextureWrapMode(u8 clamp) const; - //! sets the needed renderstates - void setRenderStates3DMode(); + //! sets the needed renderstates + void setRenderStates3DMode(); - //! sets the needed renderstates - void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); + //! sets the needed renderstates + void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); - void createMaterialRenderers(); + void createMaterialRenderers(); - //! Assign a hardware light to the specified requested light, if any - //! free hardware lights exist. - //! \param[in] lightIndex: the index of the requesting light - void assignHardwareLight(u32 lightIndex); + //! Assign a hardware light to the specified requested light, if any + //! free hardware lights exist. + //! \param[in] lightIndex: the index of the requesting light + void assignHardwareLight(u32 lightIndex); - //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` - virtual void setViewPortRaw(u32 width, u32 height); + //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` + virtual void setViewPortRaw(u32 width, u32 height); - COGLES1CacheHandler* CacheHandler; + COGLES1CacheHandler *CacheHandler; - core::stringc Name; - core::matrix4 Matrices[ETS_COUNT]; - core::array ColorBuffer; + core::stringc Name; + core::matrix4 Matrices[ETS_COUNT]; + core::array ColorBuffer; - //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. - enum E_RENDER_MODE - { - ERM_NONE = 0, // no render state has been set yet. - ERM_2D, // 2d drawing rendermode - ERM_3D // 3d rendering mode - }; - - E_RENDER_MODE CurrentRenderMode; - //! bool to make all renderstates reset if set to true. - bool ResetRenderStates; - bool Transformation3DChanged; - u8 AntiAlias; - - SMaterial Material, LastMaterial; - core::array UserClipPlane; - std::vector UserClipPlaneEnabled; - - core::stringc VendorName; - - core::matrix4 TextureFlipMatrix; - - //! Color buffer format - ECOLOR_FORMAT ColorFormat; - - SIrrlichtCreationParameters Params; - - IContextManager* ContextManager; + //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. + enum E_RENDER_MODE + { + ERM_NONE = 0, // no render state has been set yet. + ERM_2D, // 2d drawing rendermode + ERM_3D // 3d rendering mode }; + E_RENDER_MODE CurrentRenderMode; + //! bool to make all renderstates reset if set to true. + bool ResetRenderStates; + bool Transformation3DChanged; + u8 AntiAlias; + + SMaterial Material, LastMaterial; + core::array UserClipPlane; + std::vector UserClipPlaneEnabled; + + core::stringc VendorName; + + core::matrix4 TextureFlipMatrix; + + //! Color buffer format + ECOLOR_FORMAT ColorFormat; + + SIrrlichtCreationParameters Params; + + IContextManager *ContextManager; +}; + } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/COGLESExtensionHandler.cpp b/source/Irrlicht/COGLESExtensionHandler.cpp index 1fb7ebaf..ba2c0c9b 100644 --- a/source/Irrlicht/COGLESExtensionHandler.cpp +++ b/source/Irrlicht/COGLESExtensionHandler.cpp @@ -23,75 +23,72 @@ namespace irr namespace video { - COGLES1ExtensionHandler::COGLES1ExtensionHandler() : COGLESCoreExtensionHandler(), - MaxUserClipPlanes(0), MaxLights(0) - , pGlBlendEquationOES(0), pGlBlendFuncSeparateOES(0), +COGLES1ExtensionHandler::COGLES1ExtensionHandler() : + COGLESCoreExtensionHandler(), + MaxUserClipPlanes(0), MaxLights(0), pGlBlendEquationOES(0), pGlBlendFuncSeparateOES(0), pGlBindFramebufferOES(0), pGlDeleteFramebuffersOES(0), pGlGenFramebuffersOES(0), pGlCheckFramebufferStatusOES(0), pGlFramebufferTexture2DOES(0), pGlGenerateMipmapOES(0) - { +{ +} + +void COGLES1ExtensionHandler::initExtensions() +{ + getGLVersion(); + + if (Version >= 100) + os::Printer::log("OpenGL ES driver version is 1.1.", ELL_INFORMATION); + else + os::Printer::log("OpenGL ES driver version is 1.0.", ELL_WARNING); + + getGLExtensions(); + + GLint val = 0; + + if (Version > 100 || FeatureAvailable[IRR_GL_IMG_user_clip_plane]) { + glGetIntegerv(GL_MAX_CLIP_PLANES, &val); + MaxUserClipPlanes = static_cast(val); } - void COGLES1ExtensionHandler::initExtensions() - { - getGLVersion(); + glGetIntegerv(GL_MAX_LIGHTS, &val); + MaxLights = static_cast(val); - if (Version >= 100) - os::Printer::log("OpenGL ES driver version is 1.1.", ELL_INFORMATION); - else - os::Printer::log("OpenGL ES driver version is 1.0.", ELL_WARNING); - - getGLExtensions(); - - GLint val = 0; - - if (Version > 100 || FeatureAvailable[IRR_GL_IMG_user_clip_plane]) - { - glGetIntegerv(GL_MAX_CLIP_PLANES, &val); - MaxUserClipPlanes = static_cast(val); - } - - glGetIntegerv(GL_MAX_LIGHTS, &val); - MaxLights = static_cast(val); - - glGetIntegerv(GL_MAX_TEXTURE_UNITS, &val); - Feature.MaxTextureUnits = static_cast(val); + glGetIntegerv(GL_MAX_TEXTURE_UNITS, &val); + Feature.MaxTextureUnits = static_cast(val); #ifdef GL_EXT_texture_filter_anisotropic - if (FeatureAvailable[IRR_GL_EXT_texture_filter_anisotropic]) - { - glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); - MaxAnisotropy = static_cast(val); - } + if (FeatureAvailable[IRR_GL_EXT_texture_filter_anisotropic]) { + glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); + MaxAnisotropy = static_cast(val); + } #endif #ifdef GL_MAX_ELEMENTS_INDICES - glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &val); - MaxIndices = val; + glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &val); + MaxIndices = val; #endif - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); - MaxTextureSize = static_cast(val); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); + MaxTextureSize = static_cast(val); #ifdef GL_EXT_texture_lod_bias - if (FeatureAvailable[IRR_GL_EXT_texture_lod_bias]) - glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias); + if (FeatureAvailable[IRR_GL_EXT_texture_lod_bias]) + glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias); #endif - glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); - glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); + glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); + glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); - Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); - Feature.ColorAttachment = 1; + Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); + Feature.ColorAttachment = 1; - pGlBlendEquationOES = (PFNGLBLENDEQUATIONOESPROC)eglGetProcAddress("glBlendEquationOES"); - pGlBlendFuncSeparateOES = (PFNGLBLENDFUNCSEPARATEOESPROC)eglGetProcAddress("glBlendFuncSeparateOES"); - pGlBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROESPROC)eglGetProcAddress("glBindFramebufferOES"); - pGlDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOESPROC)eglGetProcAddress("glDeleteFramebuffersOES"); - pGlGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOESPROC)eglGetProcAddress("glGenFramebuffersOES"); - pGlCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOESPROC)eglGetProcAddress("glCheckFramebufferStatusOES"); - pGlFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOESPROC)eglGetProcAddress("glFramebufferTexture2DOES"); - pGlGenerateMipmapOES = (PFNGLGENERATEMIPMAPOESPROC)eglGetProcAddress("glGenerateMipmapOES"); - } + pGlBlendEquationOES = (PFNGLBLENDEQUATIONOESPROC)eglGetProcAddress("glBlendEquationOES"); + pGlBlendFuncSeparateOES = (PFNGLBLENDFUNCSEPARATEOESPROC)eglGetProcAddress("glBlendFuncSeparateOES"); + pGlBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROESPROC)eglGetProcAddress("glBindFramebufferOES"); + pGlDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOESPROC)eglGetProcAddress("glDeleteFramebuffersOES"); + pGlGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOESPROC)eglGetProcAddress("glGenFramebuffersOES"); + pGlCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOESPROC)eglGetProcAddress("glCheckFramebufferStatusOES"); + pGlFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOESPROC)eglGetProcAddress("glFramebufferTexture2DOES"); + pGlGenerateMipmapOES = (PFNGLGENERATEMIPMAPOESPROC)eglGetProcAddress("glGenerateMipmapOES"); +} } // end namespace video } // end namespace irr - #endif // _IRR_COMPILE_WITH_OGLES2_ diff --git a/source/Irrlicht/COGLESExtensionHandler.h b/source/Irrlicht/COGLESExtensionHandler.h index 559d6c89..d9e1ac4b 100644 --- a/source/Irrlicht/COGLESExtensionHandler.h +++ b/source/Irrlicht/COGLESExtensionHandler.h @@ -20,171 +20,169 @@ namespace irr namespace video { - class COGLES1ExtensionHandler : public COGLESCoreExtensionHandler +class COGLES1ExtensionHandler : public COGLESCoreExtensionHandler +{ +public: + COGLES1ExtensionHandler(); + + void initExtensions(); + + bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const { - public: - COGLES1ExtensionHandler(); + switch (feature) { + case EVDF_RENDER_TO_TARGET: + case EVDF_HARDWARE_TL: + case EVDF_MULTITEXTURE: + case EVDF_BILINEAR_FILTER: + case EVDF_MIP_MAP: + case EVDF_TEXTURE_NSQUARE: + case EVDF_STENCIL_BUFFER: + case EVDF_ALPHA_TO_COVERAGE: + case EVDF_COLOR_MASK: + case EVDF_POLYGON_OFFSET: + case EVDF_TEXTURE_MATRIX: + return true; + case EVDF_TEXTURE_NPOT: + return FeatureAvailable[IRR_GL_APPLE_texture_2D_limited_npot] || FeatureAvailable[IRR_GL_OES_texture_npot]; + case EVDF_MIP_MAP_AUTO_UPDATE: + return Version > 100; + case EVDF_BLEND_OPERATIONS: + return FeatureAvailable[IRR_GL_OES_blend_subtract]; + case EVDF_BLEND_SEPARATE: + return FeatureAvailable[IRR_GL_OES_blend_func_separate]; + case EVDF_FRAMEBUFFER_OBJECT: + return FeatureAvailable[IRR_GL_OES_framebuffer_object]; + case EVDF_VERTEX_BUFFER_OBJECT: + return Version > 100; + default: + return true; + }; + } - void initExtensions(); + inline void irrGlActiveTexture(GLenum texture) + { + glActiveTexture(texture); + } - bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const - { - switch (feature) - { - case EVDF_RENDER_TO_TARGET: - case EVDF_HARDWARE_TL: - case EVDF_MULTITEXTURE: - case EVDF_BILINEAR_FILTER: - case EVDF_MIP_MAP: - case EVDF_TEXTURE_NSQUARE: - case EVDF_STENCIL_BUFFER: - case EVDF_ALPHA_TO_COVERAGE: - case EVDF_COLOR_MASK: - case EVDF_POLYGON_OFFSET: - case EVDF_TEXTURE_MATRIX: - return true; - case EVDF_TEXTURE_NPOT: - return FeatureAvailable[IRR_GL_APPLE_texture_2D_limited_npot] || FeatureAvailable[IRR_GL_OES_texture_npot]; - case EVDF_MIP_MAP_AUTO_UPDATE: - return Version>100; - case EVDF_BLEND_OPERATIONS: - return FeatureAvailable[IRR_GL_OES_blend_subtract]; - case EVDF_BLEND_SEPARATE: - return FeatureAvailable[IRR_GL_OES_blend_func_separate]; - case EVDF_FRAMEBUFFER_OBJECT: - return FeatureAvailable[IRR_GL_OES_framebuffer_object]; - case EVDF_VERTEX_BUFFER_OBJECT: - return Version>100; - default: - return true; - }; - } + inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, + GLsizei imageSize, const void *data) + { + glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + } - inline void irrGlActiveTexture(GLenum texture) - { - glActiveTexture(texture); - } + inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, + GLenum format, GLsizei imageSize, const void *data) + { + glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + } - inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, - GLsizei imageSize, const void* data) - { - glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); - } + inline void irrGlUseProgram(GLuint prog) + { + } - inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLsizei imageSize, const void* data) - { - glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); - } + inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) + { + if (pGlBindFramebufferOES) + pGlBindFramebufferOES(target, framebuffer); + } - inline void irrGlUseProgram(GLuint prog) - { - } + inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) + { + if (pGlDeleteFramebuffersOES) + pGlDeleteFramebuffersOES(n, framebuffers); + } - inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) - { - if (pGlBindFramebufferOES) - pGlBindFramebufferOES(target, framebuffer); - } + inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) + { + if (pGlGenFramebuffersOES) + pGlGenFramebuffersOES(n, framebuffers); + } - inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) - { - if (pGlDeleteFramebuffersOES) - pGlDeleteFramebuffersOES(n, framebuffers); - } + inline GLenum irrGlCheckFramebufferStatus(GLenum target) + { + if (pGlCheckFramebufferStatusOES) + return pGlCheckFramebufferStatusOES(target); + else + return 0; + } - inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) - { - if (pGlGenFramebuffersOES) - pGlGenFramebuffersOES(n, framebuffers); - } + inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) + { + if (pGlFramebufferTexture2DOES) + pGlFramebufferTexture2DOES(target, attachment, textarget, texture, level); + } - inline GLenum irrGlCheckFramebufferStatus(GLenum target) - { - if (pGlCheckFramebufferStatusOES) - return pGlCheckFramebufferStatusOES(target); - else - return 0; - } + inline void irrGlGenerateMipmap(GLenum target) + { + if (pGlGenerateMipmapOES) + pGlGenerateMipmapOES(target); + } - inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) - { - if (pGlFramebufferTexture2DOES) - pGlFramebufferTexture2DOES(target, attachment, textarget, texture, level); - } + inline void irrGlActiveStencilFace(GLenum face) + { + } - inline void irrGlGenerateMipmap(GLenum target) - { - if (pGlGenerateMipmapOES) - pGlGenerateMipmapOES(target); - } + inline void irrGlDrawBuffer(GLenum mode) + { + } - inline void irrGlActiveStencilFace(GLenum face) - { - } + inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) + { + } - inline void irrGlDrawBuffer(GLenum mode) - { - } + inline void irrGlBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) + { + if (pGlBlendFuncSeparateOES) + pGlBlendFuncSeparateOES(srcRGB, dstRGB, srcAlpha, dstAlpha); + } - inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) - { - } + inline void irrGlBlendEquation(GLenum mode) + { + if (pGlBlendEquationOES) + pGlBlendEquationOES(mode); + } - inline void irrGlBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) - { - if (pGlBlendFuncSeparateOES) - pGlBlendFuncSeparateOES(srcRGB, dstRGB, srcAlpha, dstAlpha); - } + inline void irrGlEnableIndexed(GLenum target, GLuint index) + { + } - inline void irrGlBlendEquation(GLenum mode) - { - if (pGlBlendEquationOES) - pGlBlendEquationOES(mode); - } + inline void irrGlDisableIndexed(GLenum target, GLuint index) + { + } - inline void irrGlEnableIndexed(GLenum target, GLuint index) - { - } + inline void irrGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a) + { + } - inline void irrGlDisableIndexed(GLenum target, GLuint index) - { - } + inline void irrGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst) + { + } - inline void irrGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a) - { - } + inline void irrGlBlendFuncSeparateIndexed(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) + { + } - inline void irrGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst) - { - } + inline void irrGlBlendEquationIndexed(GLuint buf, GLenum mode) + { + } - inline void irrGlBlendFuncSeparateIndexed(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) - { - } + inline void irrGlBlendEquationSeparateIndexed(GLuint buf, GLenum modeRGB, GLenum modeAlpha) + { + } - inline void irrGlBlendEquationIndexed(GLuint buf, GLenum mode) - { - } +protected: + u8 MaxUserClipPlanes; + u8 MaxLights; - inline void irrGlBlendEquationSeparateIndexed(GLuint buf, GLenum modeRGB, GLenum modeAlpha) - { - } - - protected: - - u8 MaxUserClipPlanes; - u8 MaxLights; - - PFNGLBLENDEQUATIONOESPROC pGlBlendEquationOES; - PFNGLBLENDFUNCSEPARATEOESPROC pGlBlendFuncSeparateOES; - PFNGLBINDFRAMEBUFFEROESPROC pGlBindFramebufferOES; - PFNGLDELETEFRAMEBUFFERSOESPROC pGlDeleteFramebuffersOES; - PFNGLGENFRAMEBUFFERSOESPROC pGlGenFramebuffersOES; - PFNGLCHECKFRAMEBUFFERSTATUSOESPROC pGlCheckFramebufferStatusOES; - PFNGLFRAMEBUFFERTEXTURE2DOESPROC pGlFramebufferTexture2DOES; - PFNGLGENERATEMIPMAPOESPROC pGlGenerateMipmapOES; - }; + PFNGLBLENDEQUATIONOESPROC pGlBlendEquationOES; + PFNGLBLENDFUNCSEPARATEOESPROC pGlBlendFuncSeparateOES; + PFNGLBINDFRAMEBUFFEROESPROC pGlBindFramebufferOES; + PFNGLDELETEFRAMEBUFFERSOESPROC pGlDeleteFramebuffersOES; + PFNGLGENFRAMEBUFFERSOESPROC pGlGenFramebuffersOES; + PFNGLCHECKFRAMEBUFFERSTATUSOESPROC pGlCheckFramebufferStatusOES; + PFNGLFRAMEBUFFERTEXTURE2DOESPROC pGlFramebufferTexture2DOES; + PFNGLGENERATEMIPMAPOESPROC pGlGenerateMipmapOES; +}; } } diff --git a/source/Irrlicht/COGLESMaterialRenderer.h b/source/Irrlicht/COGLESMaterialRenderer.h index 9c7c7396..69d1b81f 100644 --- a/source/Irrlicht/COGLESMaterialRenderer.h +++ b/source/Irrlicht/COGLESMaterialRenderer.h @@ -18,33 +18,29 @@ namespace video class COGLES1MaterialRenderer : public IMaterialRenderer { public: - //! Constructor - COGLES1MaterialRenderer(video::COGLES1Driver* driver) : Driver(driver) + COGLES1MaterialRenderer(video::COGLES1Driver *driver) : + Driver(driver) { } protected: - - video::COGLES1Driver* Driver; + video::COGLES1Driver *Driver; }; - //! Solid material renderer class COGLES1MaterialRenderer_SOLID : public COGLES1MaterialRenderer { public: + COGLES1MaterialRenderer_SOLID(video::COGLES1Driver *d) : + COGLES1MaterialRenderer(d) {} - COGLES1MaterialRenderer_SOLID(video::COGLES1Driver* d) - : COGLES1MaterialRenderer(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - if (resetAllRenderstates || (material.MaterialType != lastMaterial.MaterialType)) - { + if (resetAllRenderstates || (material.MaterialType != lastMaterial.MaterialType)) { // thanks to Murphy, the following line removed some // bugs with several OGLES1 implementations. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); @@ -52,54 +48,48 @@ public: } }; - //! Generic Texture Blend class COGLES1MaterialRenderer_ONETEXTURE_BLEND : public COGLES1MaterialRenderer { public: + COGLES1MaterialRenderer_ONETEXTURE_BLEND(video::COGLES1Driver *d) : + COGLES1MaterialRenderer(d) {} - COGLES1MaterialRenderer_ONETEXTURE_BLEND(video::COGLES1Driver* d) - : COGLES1MaterialRenderer(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); -// if (material.MaterialType != lastMaterial.MaterialType || -// material.MaterialTypeParam != lastMaterial.MaterialTypeParam || -// resetAllRenderstates) + // if (material.MaterialType != lastMaterial.MaterialType || + // material.MaterialTypeParam != lastMaterial.MaterialTypeParam || + // resetAllRenderstates) { - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + E_BLEND_FACTOR srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact; E_MODULATE_FUNC modulate; u32 alphaSource; unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - Driver->getCacheHandler()->setBlend(true); + Driver->getCacheHandler()->setBlend(true); - if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) - { - Driver->getCacheHandler()->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), - Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); - } - else - { - Driver->getCacheHandler()->setBlendFunc(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact)); - } + if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) { + Driver->getCacheHandler()->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), + Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); + } else { + Driver->getCacheHandler()->setBlendFunc(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact)); + } glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE, (f32) modulate ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE, (f32)modulate); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.f); if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || - textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) - { + textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) { glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE); @@ -111,7 +101,7 @@ public: virtual void OnUnsetMaterial() { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE, 1.f ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE, 1.f); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS); Driver->getCacheHandler()->setBlend(false); @@ -125,55 +115,72 @@ public: return true; } - private: - - u32 getGLBlend ( E_BLEND_FACTOR factor ) const - { - u32 r = 0; - switch ( factor ) - { - case EBF_ZERO: r = GL_ZERO; break; - case EBF_ONE: r = GL_ONE; break; - case EBF_DST_COLOR: r = GL_DST_COLOR; break; - case EBF_ONE_MINUS_DST_COLOR: r = GL_ONE_MINUS_DST_COLOR; break; - case EBF_SRC_COLOR: r = GL_SRC_COLOR; break; - case EBF_ONE_MINUS_SRC_COLOR: r = GL_ONE_MINUS_SRC_COLOR; break; - case EBF_SRC_ALPHA: r = GL_SRC_ALPHA; break; - case EBF_ONE_MINUS_SRC_ALPHA: r = GL_ONE_MINUS_SRC_ALPHA; break; - case EBF_DST_ALPHA: r = GL_DST_ALPHA; break; - case EBF_ONE_MINUS_DST_ALPHA: r = GL_ONE_MINUS_DST_ALPHA; break; - case EBF_SRC_ALPHA_SATURATE: r = GL_SRC_ALPHA_SATURATE; break; - } - return r; +private: + u32 getGLBlend(E_BLEND_FACTOR factor) const + { + u32 r = 0; + switch (factor) { + case EBF_ZERO: + r = GL_ZERO; + break; + case EBF_ONE: + r = GL_ONE; + break; + case EBF_DST_COLOR: + r = GL_DST_COLOR; + break; + case EBF_ONE_MINUS_DST_COLOR: + r = GL_ONE_MINUS_DST_COLOR; + break; + case EBF_SRC_COLOR: + r = GL_SRC_COLOR; + break; + case EBF_ONE_MINUS_SRC_COLOR: + r = GL_ONE_MINUS_SRC_COLOR; + break; + case EBF_SRC_ALPHA: + r = GL_SRC_ALPHA; + break; + case EBF_ONE_MINUS_SRC_ALPHA: + r = GL_ONE_MINUS_SRC_ALPHA; + break; + case EBF_DST_ALPHA: + r = GL_DST_ALPHA; + break; + case EBF_ONE_MINUS_DST_ALPHA: + r = GL_ONE_MINUS_DST_ALPHA; + break; + case EBF_SRC_ALPHA_SATURATE: + r = GL_SRC_ALPHA_SATURATE; + break; } + return r; + } }; - //! Transparent vertex alpha material renderer class COGLES1MaterialRenderer_TRANSPARENT_VERTEX_ALPHA : public COGLES1MaterialRenderer { public: + COGLES1MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(video::COGLES1Driver *d) : + COGLES1MaterialRenderer(d) {} - COGLES1MaterialRenderer_TRANSPARENT_VERTEX_ALPHA(video::COGLES1Driver* d) - : COGLES1MaterialRenderer(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); Driver->getCacheHandler()->setBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); Driver->getCacheHandler()->setBlend(true); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PRIMARY_COLOR ); + glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PRIMARY_COLOR); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PRIMARY_COLOR ); + glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PRIMARY_COLOR); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE); } } @@ -182,11 +189,11 @@ public: { // default values glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE ); - glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE ); - glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_PREVIOUS ); + glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE); + glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE); + glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_PREVIOUS); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE ); + glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PREVIOUS); Driver->getCacheHandler()->setBlend(false); @@ -199,26 +206,22 @@ public: } }; - //! Transparent alpha channel material renderer class COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL : public COGLES1MaterialRenderer { public: + COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(video::COGLES1Driver *d) : + COGLES1MaterialRenderer(d) {} - COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(video::COGLES1Driver* d) - : COGLES1MaterialRenderer(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); Driver->getCacheHandler()->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Driver->getCacheHandler()->setBlend(true); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates - || material.MaterialTypeParam != lastMaterial.MaterialTypeParam ) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates || material.MaterialTypeParam != lastMaterial.MaterialTypeParam) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); @@ -246,23 +249,19 @@ public: } }; - - //! Transparent alpha channel material renderer class COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF : public COGLES1MaterialRenderer { public: + COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(video::COGLES1Driver *d) : + COGLES1MaterialRenderer(d) {} - COGLES1MaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(video::COGLES1Driver* d) - : COGLES1MaterialRenderer(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) { glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5f); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); @@ -277,7 +276,7 @@ public: //! Returns if the material is transparent. virtual bool isTransparent() const { - return false; // this material is not really transparent because it does no blending. + return false; // this material is not really transparent because it does no blending. } }; diff --git a/source/Irrlicht/COSOperator.cpp b/source/Irrlicht/COSOperator.cpp index bc428c2d..b2646379 100644 --- a/source/Irrlicht/COSOperator.cpp +++ b/source/Irrlicht/COSOperator.cpp @@ -34,8 +34,7 @@ static const bool sdl_supports_primary_selection = [] { #if SDL_VERSION_ATLEAST(2, 25, 0) SDL_version linked_version; SDL_GetVersion(&linked_version); - return (linked_version.major == 2 && linked_version.minor >= 25) - || linked_version.major > 2; + return (linked_version.major == 2 && linked_version.minor >= 25) || linked_version.major > 2; #else return false; #endif @@ -47,21 +46,21 @@ namespace irr #if defined(_IRR_COMPILE_WITH_X11_DEVICE_) // constructor linux - COSOperator::COSOperator(const core::stringc& osVersion, CIrrDeviceLinux* device) -: OperatingSystem(osVersion), IrrDeviceLinux(device) +COSOperator::COSOperator(const core::stringc &osVersion, CIrrDeviceLinux *device) : + OperatingSystem(osVersion), IrrDeviceLinux(device) { } #endif // constructor -COSOperator::COSOperator(const core::stringc& osVersion) : OperatingSystem(osVersion) +COSOperator::COSOperator(const core::stringc &osVersion) : + OperatingSystem(osVersion) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("COSOperator"); - #endif +#endif } - COSOperator::~COSOperator() { #ifdef _IRR_COMPILE_WITH_SDL_DEVICE_ @@ -70,18 +69,16 @@ COSOperator::~COSOperator() #endif } - //! returns the current operating system version as string. -const core::stringc& COSOperator::getOperatingSystemVersion() const +const core::stringc &COSOperator::getOperatingSystemVersion() const { return OperatingSystem; } - //! copies text to the clipboard void COSOperator::copyToClipboard(const c8 *text) const { - if (strlen(text)==0) + if (strlen(text) == 0) return; #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) @@ -98,7 +95,7 @@ void COSOperator::copyToClipboard(const c8 *text) const const u32 size = (tempbuffer.size() + 1) * sizeof(wchar_t); HGLOBAL clipbuffer; - void * buffer; + void *buffer; clipbuffer = GlobalAlloc(GMEM_MOVEABLE, size); buffer = GlobalLock(clipbuffer); @@ -110,28 +107,26 @@ void COSOperator::copyToClipboard(const c8 *text) const CloseClipboard(); #elif defined(_IRR_COMPILE_WITH_OSX_DEVICE_) - NSString *str = nil; - NSPasteboard *board = nil; + NSString *str = nil; + NSPasteboard *board = nil; - if ((text != NULL) && (strlen(text) > 0)) - { - str = [NSString stringWithCString:text encoding:NSUTF8StringEncoding]; - board = [NSPasteboard generalPasteboard]; - [board declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:NSApp]; - [board setString:str forType:NSStringPboardType]; - } + if ((text != NULL) && (strlen(text) > 0)) { + str = [NSString stringWithCString:text encoding:NSUTF8StringEncoding]; + board = [NSPasteboard generalPasteboard]; + [board declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:NSApp]; + [board setString:str forType:NSStringPboardType]; + } #elif defined(_IRR_COMPILE_WITH_X11_DEVICE_) - if ( IrrDeviceLinux ) - IrrDeviceLinux->copyToClipboard(text); + if (IrrDeviceLinux) + IrrDeviceLinux->copyToClipboard(text); #endif } - //! copies text to the primary selection void COSOperator::copyToPrimarySelection(const c8 *text) const { - if (strlen(text)==0) + if (strlen(text) == 0) return; #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) @@ -141,14 +136,13 @@ void COSOperator::copyToPrimarySelection(const c8 *text) const #endif #elif defined(_IRR_COMPILE_WITH_X11_DEVICE_) - if ( IrrDeviceLinux ) - IrrDeviceLinux->copyToPrimarySelection(text); + if (IrrDeviceLinux) + IrrDeviceLinux->copyToPrimarySelection(text); #endif } - //! gets text from the clipboard -const c8* COSOperator::getTextFromClipboard() const +const c8 *COSOperator::getTextFromClipboard() const { #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) SDL_free(ClipboardSelectionText); @@ -159,36 +153,36 @@ const c8* COSOperator::getTextFromClipboard() const if (!OpenClipboard(NULL)) return 0; - HANDLE hData = GetClipboardData( CF_UNICODETEXT ); + HANDLE hData = GetClipboardData(CF_UNICODETEXT); if (hData == NULL) // Probably not in Unicode text format return 0; - wchar_t * buffer = (wchar_t*) GlobalLock( hData ); + wchar_t *buffer = (wchar_t *)GlobalLock(hData); core::wStringToUTF8(ClipboardBuf, buffer); - GlobalUnlock( hData ); + GlobalUnlock(hData); CloseClipboard(); return ClipboardBuf.c_str(); #elif defined(_IRR_COMPILE_WITH_OSX_DEVICE_) - NSString* str = nil; - NSPasteboard* board = nil; - char* result = 0; + NSString *str = nil; + NSPasteboard *board = nil; + char *result = 0; - board = [NSPasteboard generalPasteboard]; - str = [board stringForType:NSStringPboardType]; + board = [NSPasteboard generalPasteboard]; + str = [board stringForType:NSStringPboardType]; - if (str != nil) - result = (char*)[str cStringUsingEncoding:NSUTF8StringEncoding]; + if (str != nil) + result = (char *)[str cStringUsingEncoding:NSUTF8StringEncoding]; - return (result); + return (result); #elif defined(_IRR_COMPILE_WITH_X11_DEVICE_) - if ( IrrDeviceLinux ) - return IrrDeviceLinux->getTextFromClipboard(); - return 0; + if (IrrDeviceLinux) + return IrrDeviceLinux->getTextFromClipboard(); + return 0; #else @@ -196,9 +190,8 @@ const c8* COSOperator::getTextFromClipboard() const #endif } - //! gets text from the primary selection -const c8* COSOperator::getTextFromPrimarySelection() const +const c8 *COSOperator::getTextFromPrimarySelection() const { #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) #if SDL_VERSION_ATLEAST(2, 25, 0) @@ -211,7 +204,7 @@ const c8* COSOperator::getTextFromPrimarySelection() const return 0; #elif defined(_IRR_COMPILE_WITH_X11_DEVICE_) - if ( IrrDeviceLinux ) + if (IrrDeviceLinux) return IrrDeviceLinux->getTextFromPrimarySelection(); return 0; @@ -221,35 +214,34 @@ const c8* COSOperator::getTextFromPrimarySelection() const #endif } - -bool COSOperator::getSystemMemory(u32* Total, u32* Avail) const +bool COSOperator::getSystemMemory(u32 *Total, u32 *Avail) const { #if defined(_IRR_WINDOWS_API_) MEMORYSTATUSEX MemoryStatusEx; - MemoryStatusEx.dwLength = sizeof(MEMORYSTATUSEX); + MemoryStatusEx.dwLength = sizeof(MEMORYSTATUSEX); // cannot fail GlobalMemoryStatusEx(&MemoryStatusEx); if (Total) - *Total = (u32)(MemoryStatusEx.ullTotalPhys>>10); + *Total = (u32)(MemoryStatusEx.ullTotalPhys >> 10); if (Avail) - *Avail = (u32)(MemoryStatusEx.ullAvailPhys>>10); + *Avail = (u32)(MemoryStatusEx.ullAvailPhys >> 10); return true; #elif defined(_IRR_POSIX_API_) && defined(_SC_PHYS_PAGES) && defined(_SC_AVPHYS_PAGES) - long ps = sysconf(_SC_PAGESIZE); - long pp = sysconf(_SC_PHYS_PAGES); - long ap = sysconf(_SC_AVPHYS_PAGES); + long ps = sysconf(_SC_PAGESIZE); + long pp = sysconf(_SC_PHYS_PAGES); + long ap = sysconf(_SC_AVPHYS_PAGES); if (ps == -1 || (Total && pp == -1) || (Avail && ap == -1)) return false; if (Total) - *Total = (u32)((pp>>10)*ps); + *Total = (u32)((pp >> 10) * ps); if (Avail) - *Avail = (u32)((ap>>10)*ps); + *Avail = (u32)((ap >> 10) * ps); return true; #elif defined(_IRR_OSX_PLATFORM_) int mib[2]; @@ -263,9 +255,9 @@ bool COSOperator::getSystemMemory(u32* Total, u32* Avail) const sysctl(mib, 2, &physical_memory, &length, NULL, 0); if (Total) - *Total = (u32)(physical_memory>>10); + *Total = (u32)(physical_memory >> 10); if (Avail) - *Avail = (u32)(physical_memory>>10); // we don't know better + *Avail = (u32)(physical_memory >> 10); // we don't know better return true; #else // TODO: implement for others @@ -273,6 +265,4 @@ bool COSOperator::getSystemMemory(u32* Total, u32* Avail) const #endif } - } // end namespace - diff --git a/source/Irrlicht/COSOperator.h b/source/Irrlicht/COSOperator.h index 6a682d8e..c1059bff 100644 --- a/source/Irrlicht/COSOperator.h +++ b/source/Irrlicht/COSOperator.h @@ -15,12 +15,11 @@ class CIrrDeviceLinux; class COSOperator : public IOSOperator { public: - // constructor #if defined(_IRR_COMPILE_WITH_X11_DEVICE_) - COSOperator(const core::stringc& osversion, CIrrDeviceLinux* device); + COSOperator(const core::stringc &osversion, CIrrDeviceLinux *device); #endif - COSOperator(const core::stringc& osversion); + COSOperator(const core::stringc &osversion); ~COSOperator(); @@ -28,7 +27,7 @@ public: COSOperator &operator=(const COSOperator &) = delete; //! Get the current OS version as string. - const core::stringc& getOperatingSystemVersion() const override; + const core::stringc &getOperatingSystemVersion() const override; //! Copies text to the clipboard //! \param text: text in utf-8 @@ -41,28 +40,27 @@ public: //! Get text from the clipboard //! \return Returns 0 if no string is in there, otherwise an utf-8 string. - const c8* getTextFromClipboard() const override; + const c8 *getTextFromClipboard() const override; //! Get text from the primary selection //! This is a no-op on some platforms. //! \return Returns 0 if no string is in there, otherwise an utf-8 string. - const c8* getTextFromPrimarySelection() const override; + const c8 *getTextFromPrimarySelection() const override; //! Get the total and available system RAM /** \param totalBytes: will contain the total system memory in Kilobytes (1024 B) \param availableBytes: will contain the available memory in Kilobytes (1024 B) \return True if successful, false if not */ - bool getSystemMemory(u32* Total, u32* Avail) const override; + bool getSystemMemory(u32 *Total, u32 *Avail) const override; private: - core::stringc OperatingSystem; #if defined(_IRR_COMPILE_WITH_X11_DEVICE_) - CIrrDeviceLinux * IrrDeviceLinux; + CIrrDeviceLinux *IrrDeviceLinux; #endif -#ifdef _IRR_WINDOWS_API_ +#ifdef _IRR_WINDOWS_API_ mutable core::stringc ClipboardBuf; #endif @@ -71,7 +69,6 @@ private: mutable char *ClipboardSelectionText = nullptr; mutable char *PrimarySelectionText = nullptr; #endif - }; } // end namespace diff --git a/source/Irrlicht/COpenGLCacheHandler.cpp b/source/Irrlicht/COpenGLCacheHandler.cpp index d08ad3f0..577967c5 100644 --- a/source/Irrlicht/COpenGLCacheHandler.cpp +++ b/source/Irrlicht/COpenGLCacheHandler.cpp @@ -15,10 +15,10 @@ namespace video /* COpenGLCacheHandler */ -COpenGLCacheHandler::COpenGLCacheHandler(COpenGLDriver* driver) : - COpenGLCoreCacheHandler(driver), AlphaMode(GL_ALWAYS), AlphaRef(0.f), AlphaTest(false), - MatrixMode(GL_MODELVIEW), ClientActiveTexture(GL_TEXTURE0), ClientStateVertex(false), - ClientStateNormal(false), ClientStateColor(false), ClientStateTexCoord0(false) +COpenGLCacheHandler::COpenGLCacheHandler(COpenGLDriver *driver) : + COpenGLCoreCacheHandler(driver), AlphaMode(GL_ALWAYS), AlphaRef(0.f), AlphaTest(false), + MatrixMode(GL_MODELVIEW), ClientActiveTexture(GL_TEXTURE0), ClientStateVertex(false), + ClientStateNormal(false), ClientStateColor(false), ClientStateTexCoord0(false) { // Initial OpenGL values from specification. @@ -41,8 +41,7 @@ COpenGLCacheHandler::~COpenGLCacheHandler() void COpenGLCacheHandler::setAlphaFunc(GLenum mode, GLclampf ref) { - if (AlphaMode != mode || AlphaRef != ref) - { + if (AlphaMode != mode || AlphaRef != ref) { glAlphaFunc(mode, ref); AlphaMode = mode; @@ -52,8 +51,7 @@ void COpenGLCacheHandler::setAlphaFunc(GLenum mode, GLclampf ref) void COpenGLCacheHandler::setAlphaTest(bool enable) { - if (AlphaTest != enable) - { + if (AlphaTest != enable) { if (enable) glEnable(GL_ALPHA_TEST); else @@ -64,8 +62,7 @@ void COpenGLCacheHandler::setAlphaTest(bool enable) void COpenGLCacheHandler::setClientState(bool vertex, bool normal, bool color, bool texCoord0) { - if (ClientStateVertex != vertex) - { + if (ClientStateVertex != vertex) { if (vertex) glEnableClientState(GL_VERTEX_ARRAY); else @@ -74,8 +71,7 @@ void COpenGLCacheHandler::setClientState(bool vertex, bool normal, bool color, b ClientStateVertex = vertex; } - if (ClientStateNormal != normal) - { + if (ClientStateNormal != normal) { if (normal) glEnableClientState(GL_NORMAL_ARRAY); else @@ -84,8 +80,7 @@ void COpenGLCacheHandler::setClientState(bool vertex, bool normal, bool color, b ClientStateNormal = normal; } - if (ClientStateColor != color) - { + if (ClientStateColor != color) { if (color) glEnableClientState(GL_COLOR_ARRAY); else @@ -94,8 +89,7 @@ void COpenGLCacheHandler::setClientState(bool vertex, bool normal, bool color, b ClientStateColor = color; } - if (ClientStateTexCoord0 != texCoord0) - { + if (ClientStateTexCoord0 != texCoord0) { setClientActiveTexture(GL_TEXTURE0_ARB); if (texCoord0) @@ -109,8 +103,7 @@ void COpenGLCacheHandler::setClientState(bool vertex, bool normal, bool color, b void COpenGLCacheHandler::setMatrixMode(GLenum mode) { - if (MatrixMode != mode) - { + if (MatrixMode != mode) { glMatrixMode(mode); MatrixMode = mode; } @@ -118,8 +111,7 @@ void COpenGLCacheHandler::setMatrixMode(GLenum mode) void COpenGLCacheHandler::setClientActiveTexture(GLenum texture) { - if (ClientActiveTexture != texture) - { + if (ClientActiveTexture != texture) { Driver->irrGlClientActiveTexture(texture); ClientActiveTexture = texture; } diff --git a/source/Irrlicht/COpenGLCacheHandler.h b/source/Irrlicht/COpenGLCacheHandler.h index ef80ce37..968e452d 100644 --- a/source/Irrlicht/COpenGLCacheHandler.h +++ b/source/Irrlicht/COpenGLCacheHandler.h @@ -17,44 +17,44 @@ namespace irr namespace video { - class COpenGLCacheHandler : public COpenGLCoreCacheHandler - { - public: - COpenGLCacheHandler(COpenGLDriver* driver); - virtual ~COpenGLCacheHandler(); +class COpenGLCacheHandler : public COpenGLCoreCacheHandler +{ +public: + COpenGLCacheHandler(COpenGLDriver *driver); + virtual ~COpenGLCacheHandler(); - // Alpha calls. + // Alpha calls. - void setAlphaFunc(GLenum mode, GLclampf ref); + void setAlphaFunc(GLenum mode, GLclampf ref); - void setAlphaTest(bool enable); + void setAlphaTest(bool enable); - // Client state calls. + // Client state calls. - void setClientState(bool vertex, bool normal, bool color, bool texCoord0); + void setClientState(bool vertex, bool normal, bool color, bool texCoord0); - // Matrix calls. + // Matrix calls. - void setMatrixMode(GLenum mode); + void setMatrixMode(GLenum mode); - // Texture calls. + // Texture calls. - void setClientActiveTexture(GLenum texture); + void setClientActiveTexture(GLenum texture); - protected: - GLenum AlphaMode; - GLclampf AlphaRef; - bool AlphaTest; +protected: + GLenum AlphaMode; + GLclampf AlphaRef; + bool AlphaTest; - GLenum MatrixMode; + GLenum MatrixMode; - GLenum ClientActiveTexture; + GLenum ClientActiveTexture; - bool ClientStateVertex; - bool ClientStateNormal; - bool ClientStateColor; - bool ClientStateTexCoord0; - }; + bool ClientStateVertex; + bool ClientStateNormal; + bool ClientStateColor; + bool ClientStateTexCoord0; +}; } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/COpenGLCommon.h b/source/Irrlicht/COpenGLCommon.h index 17f12f50..3b43b35a 100644 --- a/source/Irrlicht/COpenGLCommon.h +++ b/source/Irrlicht/COpenGLCommon.h @@ -7,10 +7,10 @@ #ifdef _IRR_COMPILE_WITH_OPENGL_ #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) && defined(IRR_PREFER_SDL_GL_HEADER) - #include - #include +#include +#include #else - #include "vendor/gl.h" +#include "vendor/gl.h" #endif #define GL_FRAMEBUFFER_INCOMPLETE_FORMATS GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT @@ -24,23 +24,23 @@ namespace irr namespace video { - // Forward declarations. +// Forward declarations. - class COpenGLCoreFeature; +class COpenGLCoreFeature; - template - class COpenGLCoreTexture; +template +class COpenGLCoreTexture; - template - class COpenGLCoreRenderTarget; +template +class COpenGLCoreRenderTarget; - template - class COpenGLCoreCacheHandler; +template +class COpenGLCoreCacheHandler; - class COpenGLDriver; - typedef COpenGLCoreTexture COpenGLTexture; - typedef COpenGLCoreRenderTarget COpenGLRenderTarget; - class COpenGLCacheHandler; +class COpenGLDriver; +typedef COpenGLCoreTexture COpenGLTexture; +typedef COpenGLCoreRenderTarget COpenGLRenderTarget; +class COpenGLCacheHandler; } } diff --git a/source/Irrlicht/COpenGLCoreCacheHandler.h b/source/Irrlicht/COpenGLCoreCacheHandler.h index 0447d76a..6422f26b 100644 --- a/source/Irrlicht/COpenGLCoreCacheHandler.h +++ b/source/Irrlicht/COpenGLCoreCacheHandler.h @@ -16,22 +16,20 @@ namespace video enum ESetTextureActive { - EST_ACTIVE_ALWAYS, // texture unit always active after set call - EST_ACTIVE_ON_CHANGE // texture unit only active after call when texture changed in cache + EST_ACTIVE_ALWAYS, // texture unit always active after set call + EST_ACTIVE_ON_CHANGE // texture unit only active after call when texture changed in cache }; - template class COpenGLCoreCacheHandler { class STextureCache { public: - STextureCache(COpenGLCoreCacheHandler& cacheHandler, E_DRIVER_TYPE driverType, u32 textureCount) : - CacheHandler(cacheHandler), DriverType(driverType), TextureCount(textureCount) + STextureCache(COpenGLCoreCacheHandler &cacheHandler, E_DRIVER_TYPE driverType, u32 textureCount) : + CacheHandler(cacheHandler), DriverType(driverType), TextureCount(textureCount) { - for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) - { + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { Texture[i] = 0; } } @@ -41,7 +39,7 @@ class COpenGLCoreCacheHandler clear(); } - const TOpenGLTexture* operator[](int index) const + const TOpenGLTexture *operator[](int index) const { if (static_cast(index) < MATERIAL_MAX_TEXTURES) return Texture[static_cast(index)]; @@ -49,7 +47,7 @@ class COpenGLCoreCacheHandler return 0; } - const TOpenGLTexture* get(u32 index) const + const TOpenGLTexture *get(u32 index) const { if (index < MATERIAL_MAX_TEXTURES) return Texture[index]; @@ -57,54 +55,47 @@ class COpenGLCoreCacheHandler return 0; } - bool set(u32 index, const ITexture* texture, ESetTextureActive esa=EST_ACTIVE_ALWAYS) + bool set(u32 index, const ITexture *texture, ESetTextureActive esa = EST_ACTIVE_ALWAYS) { bool status = false; E_DRIVER_TYPE type = DriverType; - if (index < MATERIAL_MAX_TEXTURES && index < TextureCount) - { - if ( esa == EST_ACTIVE_ALWAYS ) + if (index < MATERIAL_MAX_TEXTURES && index < TextureCount) { + if (esa == EST_ACTIVE_ALWAYS) CacheHandler.setActiveTexture(GL_TEXTURE0 + index); - const TOpenGLTexture* prevTexture = Texture[index]; + const TOpenGLTexture *prevTexture = Texture[index]; - if (texture != prevTexture) - { - if ( esa == EST_ACTIVE_ON_CHANGE ) + if (texture != prevTexture) { + if (esa == EST_ACTIVE_ON_CHANGE) CacheHandler.setActiveTexture(GL_TEXTURE0 + index); - if (texture) - { + if (texture) { type = texture->getDriverType(); - if (type == DriverType) - { + if (type == DriverType) { texture->grab(); - const TOpenGLTexture* curTexture = static_cast(texture); + const TOpenGLTexture *curTexture = static_cast(texture); const GLenum curTextureType = curTexture->getOpenGLTextureType(); const GLenum prevTextureType = (prevTexture) ? prevTexture->getOpenGLTextureType() : curTextureType; - if (curTextureType != prevTextureType) - { + if (curTextureType != prevTextureType) { GL.BindTexture(prevTextureType, 0); -#if ( defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON) ) +#if (defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) GL.Disable(prevTextureType); GL.Enable(curTextureType); #endif } -#if ( defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON) ) +#if (defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) else if (!prevTexture) GL.Enable(curTextureType); #endif - GL.BindTexture(curTextureType, static_cast(texture)->getOpenGLTextureName()); - } - else - { + GL.BindTexture(curTextureType, static_cast(texture)->getOpenGLTextureName()); + } else { texture = 0; os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR); @@ -113,18 +104,17 @@ class COpenGLCoreCacheHandler } } - if (!texture && prevTexture) - { + if (!texture && prevTexture) { const GLenum prevTextureType = prevTexture->getOpenGLTextureType(); GL.BindTexture(prevTextureType, 0); -#if ( defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON) ) +#if (defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) GL.Disable(prevTextureType); #endif } - Texture[index] = static_cast(texture); + Texture[index] = static_cast(texture); if (prevTexture) prevTexture->drop(); @@ -136,15 +126,13 @@ class COpenGLCoreCacheHandler return (status && type == DriverType); } - void remove(ITexture* texture) + void remove(ITexture *texture) { if (!texture) return; - for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) - { - if (Texture[i] == texture) - { + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (Texture[i] == texture) { Texture[i] = 0; texture->drop(); @@ -154,11 +142,9 @@ class COpenGLCoreCacheHandler void clear() { - for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) - { - if (Texture[i]) - { - const TOpenGLTexture* prevTexture = Texture[i]; + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (Texture[i]) { + const TOpenGLTexture *prevTexture = Texture[i]; Texture[i] = 0; @@ -168,31 +154,31 @@ class COpenGLCoreCacheHandler } private: - COpenGLCoreCacheHandler& CacheHandler; + COpenGLCoreCacheHandler &CacheHandler; E_DRIVER_TYPE DriverType; - const TOpenGLTexture* Texture[MATERIAL_MAX_TEXTURES]; + const TOpenGLTexture *Texture[MATERIAL_MAX_TEXTURES]; u32 TextureCount; }; public: - COpenGLCoreCacheHandler(TOpenGLDriver* driver) : - Driver(driver), + COpenGLCoreCacheHandler(TOpenGLDriver *driver) : + Driver(driver), #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable: 4355) // Warning: "'this' : used in base member initializer list. ". It's OK, we don't use the reference in STextureCache constructor. +#pragma warning(disable : 4355) // Warning: "'this' : used in base member initializer list. ". It's OK, we don't use the reference in STextureCache constructor. #endif - TextureCache(STextureCache(*this, driver->getDriverType(), driver->getFeature().MaxTextureUnits)), + TextureCache(STextureCache(*this, driver->getDriverType(), driver->getFeature().MaxTextureUnits)), #if defined(_MSC_VER) #pragma warning(pop) #endif - FrameBufferCount(0), BlendEquation(0), BlendSourceRGB(0), - BlendDestinationRGB(0), BlendSourceAlpha(0), BlendDestinationAlpha(0), Blend(0), BlendEquationInvalid(false), BlendFuncInvalid(false), BlendInvalid(false), - ColorMask(0), ColorMaskInvalid(false), CullFaceMode(GL_BACK), CullFace(false), DepthFunc(GL_LESS), DepthMask(true), DepthTest(false), FrameBufferID(0), - ProgramID(0), ActiveTexture(GL_TEXTURE0), ViewportX(0), ViewportY(0) + FrameBufferCount(0), BlendEquation(0), BlendSourceRGB(0), + BlendDestinationRGB(0), BlendSourceAlpha(0), BlendDestinationAlpha(0), Blend(0), BlendEquationInvalid(false), BlendFuncInvalid(false), BlendInvalid(false), + ColorMask(0), ColorMaskInvalid(false), CullFaceMode(GL_BACK), CullFace(false), DepthFunc(GL_LESS), DepthMask(true), DepthTest(false), FrameBufferID(0), + ProgramID(0), ActiveTexture(GL_TEXTURE0), ViewportX(0), ViewportY(0) { - const COpenGLCoreFeature& feature = Driver->getFeature(); + const COpenGLCoreFeature &feature = Driver->getFeature(); FrameBufferCount = core::max_(static_cast(1), static_cast(feature.MultipleRenderTarget)); @@ -206,13 +192,11 @@ public: // Initial OpenGL values from specification. - if (feature.BlendOperation) - { + if (feature.BlendOperation) { Driver->irrGlBlendEquation(GL_FUNC_ADD); } - for (u32 i = 0; i < FrameBufferCount; ++i) - { + for (u32 i = 0; i < FrameBufferCount; ++i) { BlendEquation[i] = GL_FUNC_ADD; BlendSourceRGB[i] = GL_ONE; @@ -238,7 +222,7 @@ public: Driver->irrGlActiveTexture(ActiveTexture); -#if ( defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON) ) +#if (defined(IRR_COMPILE_GL_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) GL.Disable(GL_TEXTURE_2D); #endif @@ -265,7 +249,7 @@ public: return Driver->getDriverType(); } - STextureCache& getTextureCache() + STextureCache &getTextureCache() { return TextureCache; } @@ -274,8 +258,7 @@ public: void setBlendEquation(GLenum mode) { - if (BlendEquation[0] != mode || BlendEquationInvalid) - { + if (BlendEquation[0] != mode || BlendEquationInvalid) { Driver->irrGlBlendEquation(mode); for (GLuint i = 0; i < FrameBufferCount; ++i) @@ -287,8 +270,7 @@ public: void setBlendEquationIndexed(GLuint index, GLenum mode) { - if (index < FrameBufferCount && BlendEquation[index] != mode) - { + if (index < FrameBufferCount && BlendEquation[index] != mode) { Driver->irrGlBlendEquationIndexed(index, mode); BlendEquation[index] = mode; @@ -299,13 +281,11 @@ public: void setBlendFunc(GLenum source, GLenum destination) { if (BlendSourceRGB[0] != source || BlendDestinationRGB[0] != destination || - BlendSourceAlpha[0] != source || BlendDestinationAlpha[0] != destination || - BlendFuncInvalid) - { + BlendSourceAlpha[0] != source || BlendDestinationAlpha[0] != destination || + BlendFuncInvalid) { GL.BlendFunc(source, destination); - for (GLuint i = 0; i < FrameBufferCount; ++i) - { + for (GLuint i = 0; i < FrameBufferCount; ++i) { BlendSourceRGB[i] = source; BlendDestinationRGB[i] = destination; BlendSourceAlpha[i] = source; @@ -318,16 +298,13 @@ public: void setBlendFuncSeparate(GLenum sourceRGB, GLenum destinationRGB, GLenum sourceAlpha, GLenum destinationAlpha) { - if (sourceRGB != sourceAlpha || destinationRGB != destinationAlpha) - { + if (sourceRGB != sourceAlpha || destinationRGB != destinationAlpha) { if (BlendSourceRGB[0] != sourceRGB || BlendDestinationRGB[0] != destinationRGB || - BlendSourceAlpha[0] != sourceAlpha || BlendDestinationAlpha[0] != destinationAlpha || - BlendFuncInvalid) - { + BlendSourceAlpha[0] != sourceAlpha || BlendDestinationAlpha[0] != destinationAlpha || + BlendFuncInvalid) { Driver->irrGlBlendFuncSeparate(sourceRGB, destinationRGB, sourceAlpha, destinationAlpha); - for (GLuint i = 0; i < FrameBufferCount; ++i) - { + for (GLuint i = 0; i < FrameBufferCount; ++i) { BlendSourceRGB[i] = sourceRGB; BlendDestinationRGB[i] = destinationRGB; BlendSourceAlpha[i] = sourceAlpha; @@ -336,9 +313,7 @@ public: BlendFuncInvalid = false; } - } - else - { + } else { setBlendFunc(sourceRGB, destinationRGB); } } @@ -346,8 +321,7 @@ public: void setBlendFuncIndexed(GLuint index, GLenum source, GLenum destination) { if (index < FrameBufferCount && (BlendSourceRGB[index] != source || BlendDestinationRGB[index] != destination || - BlendSourceAlpha[index] != source || BlendDestinationAlpha[index] != destination)) - { + BlendSourceAlpha[index] != source || BlendDestinationAlpha[index] != destination)) { Driver->irrGlBlendFuncIndexed(index, source, destination); BlendSourceRGB[index] = source; @@ -360,11 +334,9 @@ public: void setBlendFuncSeparateIndexed(GLuint index, GLenum sourceRGB, GLenum destinationRGB, GLenum sourceAlpha, GLenum destinationAlpha) { - if (sourceRGB != sourceAlpha || destinationRGB != destinationAlpha) - { + if (sourceRGB != sourceAlpha || destinationRGB != destinationAlpha) { if (index < FrameBufferCount && (BlendSourceRGB[index] != sourceRGB || BlendDestinationRGB[index] != destinationRGB || - BlendSourceAlpha[index] != sourceAlpha || BlendDestinationAlpha[index] != destinationAlpha)) - { + BlendSourceAlpha[index] != sourceAlpha || BlendDestinationAlpha[index] != destinationAlpha)) { Driver->irrGlBlendFuncSeparateIndexed(index, sourceRGB, destinationRGB, sourceAlpha, destinationAlpha); BlendSourceRGB[index] = sourceRGB; @@ -373,17 +345,14 @@ public: BlendDestinationAlpha[index] = destinationAlpha; BlendFuncInvalid = true; } - } - else - { + } else { setBlendFuncIndexed(index, sourceRGB, destinationRGB); } } void setBlend(bool enable) { - if (Blend[0] != enable || BlendInvalid) - { + if (Blend[0] != enable || BlendInvalid) { if (enable) GL.Enable(GL_BLEND); else @@ -398,8 +367,7 @@ public: void setBlendIndexed(GLuint index, bool enable) { - if (index < FrameBufferCount && Blend[index] != enable) - { + if (index < FrameBufferCount && Blend[index] != enable) { if (enable) Driver->irrGlEnableIndexed(GL_BLEND, index); else @@ -412,15 +380,14 @@ public: // Color Mask. - void getColorMask(u8& mask) + void getColorMask(u8 &mask) { mask = ColorMask[0]; } void setColorMask(u8 mask) { - if (ColorMask[0] != mask || ColorMaskInvalid) - { + if (ColorMask[0] != mask || ColorMaskInvalid) { GL.ColorMask((mask & ECP_RED) ? GL_TRUE : GL_FALSE, (mask & ECP_GREEN) ? GL_TRUE : GL_FALSE, (mask & ECP_BLUE) ? GL_TRUE : GL_FALSE, (mask & ECP_ALPHA) ? GL_TRUE : GL_FALSE); for (GLuint i = 0; i < FrameBufferCount; ++i) @@ -432,8 +399,7 @@ public: void setColorMaskIndexed(GLuint index, u8 mask) { - if (index < FrameBufferCount && ColorMask[index] != mask) - { + if (index < FrameBufferCount && ColorMask[index] != mask) { Driver->irrGlColorMaskIndexed(index, (mask & ECP_RED) ? GL_TRUE : GL_FALSE, (mask & ECP_GREEN) ? GL_TRUE : GL_FALSE, (mask & ECP_BLUE) ? GL_TRUE : GL_FALSE, (mask & ECP_ALPHA) ? GL_TRUE : GL_FALSE); ColorMask[index] = mask; @@ -445,8 +411,7 @@ public: void setCullFaceFunc(GLenum mode) { - if (CullFaceMode != mode) - { + if (CullFaceMode != mode) { GL.CullFace(mode); CullFaceMode = mode; } @@ -454,8 +419,7 @@ public: void setCullFace(bool enable) { - if (CullFace != enable) - { + if (CullFace != enable) { if (enable) GL.Enable(GL_CULL_FACE); else @@ -469,22 +433,20 @@ public: void setDepthFunc(GLenum mode) { - if (DepthFunc != mode) - { + if (DepthFunc != mode) { GL.DepthFunc(mode); DepthFunc = mode; } } - void getDepthMask(bool& depth) + void getDepthMask(bool &depth) { depth = DepthMask; } void setDepthMask(bool enable) { - if (DepthMask != enable) - { + if (DepthMask != enable) { if (enable) GL.DepthMask(GL_TRUE); else @@ -494,15 +456,14 @@ public: } } - void getDepthTest(bool& enable) - { - enable = DepthTest; - } + void getDepthTest(bool &enable) + { + enable = DepthTest; + } void setDepthTest(bool enable) { - if (DepthTest != enable) - { + if (DepthTest != enable) { if (enable) GL.Enable(GL_DEPTH_TEST); else @@ -514,15 +475,14 @@ public: // FBO calls. - void getFBO(GLuint& frameBufferID) const + void getFBO(GLuint &frameBufferID) const { frameBufferID = FrameBufferID; } void setFBO(GLuint frameBufferID) { - if (FrameBufferID != frameBufferID) - { + if (FrameBufferID != frameBufferID) { Driver->irrGlBindFramebuffer(GL_FRAMEBUFFER, frameBufferID); FrameBufferID = frameBufferID; } @@ -530,15 +490,14 @@ public: // Shaders calls. - void getProgram(GLuint& programID) const + void getProgram(GLuint &programID) const { programID = ProgramID; } void setProgram(GLuint programID) { - if (ProgramID != programID) - { + if (ProgramID != programID) { Driver->irrGlUseProgram(programID); ProgramID = programID; } @@ -546,15 +505,14 @@ public: // Texture calls. - void getActiveTexture(GLenum& texture) const + void getActiveTexture(GLenum &texture) const { texture = ActiveTexture; } void setActiveTexture(GLenum texture) { - if (ActiveTexture != texture) - { + if (ActiveTexture != texture) { Driver->irrGlActiveTexture(texture); ActiveTexture = texture; } @@ -562,7 +520,7 @@ public: // Viewport calls. - void getViewport(GLint& viewportX, GLint& viewportY, GLsizei& viewportWidth, GLsizei& viewportHeight) const + void getViewport(GLint &viewportX, GLint &viewportY, GLsizei &viewportWidth, GLsizei &viewportHeight) const { viewportX = ViewportX; viewportY = ViewportY; @@ -572,8 +530,7 @@ public: void setViewport(GLint viewportX, GLint viewportY, GLsizei viewportWidth, GLsizei viewportHeight) { - if (ViewportX != viewportX || ViewportY != viewportY || ViewportWidth != viewportWidth || ViewportHeight != viewportHeight) - { + if (ViewportX != viewportX || ViewportY != viewportY || ViewportWidth != viewportWidth || ViewportHeight != viewportHeight) { GL.Viewport(viewportX, viewportY, viewportWidth, viewportHeight); ViewportX = viewportX; ViewportY = viewportY; @@ -585,37 +542,34 @@ public: //! Compare material to current cache and update it when there are differences // Some material renderers do change the cache beyond the original material settings // This corrects the material to represent the current cache state again. - void correctCacheMaterial(irr::video::SMaterial& material) + void correctCacheMaterial(irr::video::SMaterial &material) { // Fix textures which got removed - for ( u32 i=0; i < MATERIAL_MAX_TEXTURES; ++i ) - { - if ( material.TextureLayers[i].Texture && !TextureCache[i] ) - { + for (u32 i = 0; i < MATERIAL_MAX_TEXTURES; ++i) { + if (material.TextureLayers[i].Texture && !TextureCache[i]) { material.TextureLayers[i].Texture = 0; } } } protected: - TOpenGLDriver* Driver; + TOpenGLDriver *Driver; STextureCache TextureCache; GLuint FrameBufferCount; - GLenum* BlendEquation; - GLenum* BlendSourceRGB; - GLenum* BlendDestinationRGB; - GLenum* BlendSourceAlpha; - GLenum* BlendDestinationAlpha; - bool* Blend; + GLenum *BlendEquation; + GLenum *BlendSourceRGB; + GLenum *BlendDestinationRGB; + GLenum *BlendSourceAlpha; + GLenum *BlendDestinationAlpha; + bool *Blend; bool BlendEquationInvalid; bool BlendFuncInvalid; bool BlendInvalid; - - u8* ColorMask; + u8 *ColorMask; bool ColorMaskInvalid; GLenum CullFaceMode; diff --git a/source/Irrlicht/COpenGLCoreFeature.h b/source/Irrlicht/COpenGLCoreFeature.h index a7cf78bb..dc3d40e0 100644 --- a/source/Irrlicht/COpenGLCoreFeature.h +++ b/source/Irrlicht/COpenGLCoreFeature.h @@ -14,7 +14,8 @@ namespace video class COpenGLCoreFeature { public: - COpenGLCoreFeature() : BlendOperation(false), ColorAttachment(0), MultipleRenderTarget(0), MaxTextureUnits(1) + COpenGLCoreFeature() : + BlendOperation(false), ColorAttachment(0), MultipleRenderTarget(0), MaxTextureUnits(1) { } diff --git a/source/Irrlicht/COpenGLCoreRenderTarget.h b/source/Irrlicht/COpenGLCoreRenderTarget.h index 9f7e0924..105cdd70 100644 --- a/source/Irrlicht/COpenGLCoreRenderTarget.h +++ b/source/Irrlicht/COpenGLCoreRenderTarget.h @@ -23,8 +23,9 @@ template class COpenGLCoreRenderTarget : public IRenderTarget { public: - COpenGLCoreRenderTarget(TOpenGLDriver* driver) : AssignedDepth(false), AssignedStencil(false), RequestTextureUpdate(false), RequestDepthStencilUpdate(false), - BufferID(0), ColorAttachment(0), MultipleRenderTarget(0), Driver(driver) + COpenGLCoreRenderTarget(TOpenGLDriver *driver) : + AssignedDepth(false), AssignedStencil(false), RequestTextureUpdate(false), RequestDepthStencilUpdate(false), + BufferID(0), ColorAttachment(0), MultipleRenderTarget(0), Driver(driver) { #ifdef _DEBUG setDebugName("COpenGLCoreRenderTarget"); @@ -51,8 +52,7 @@ public: if (ColorAttachment > 0 && BufferID != 0) Driver->irrGlDeleteFramebuffers(1, &BufferID); - for (u32 i = 0; i < Textures.size(); ++i) - { + for (u32 i = 0; i < Textures.size(); ++i) { if (Textures[i]) Textures[i]->drop(); } @@ -61,19 +61,17 @@ public: DepthStencil->drop(); } - void setTextures(ITexture* const * textures, u32 numTextures, ITexture* depthStencil, const E_CUBE_SURFACE* cubeSurfaces, u32 numCubeSurfaces) override + void setTextures(ITexture *const *textures, u32 numTextures, ITexture *depthStencil, const E_CUBE_SURFACE *cubeSurfaces, u32 numCubeSurfaces) override { bool needSizeUpdate = false; // Set color attachments. - if (!Textures.equals(textures, numTextures) || !CubeSurfaces.equals(cubeSurfaces, numCubeSurfaces)) - { + if (!Textures.equals(textures, numTextures) || !CubeSurfaces.equals(cubeSurfaces, numCubeSurfaces)) { needSizeUpdate = true; - core::array prevTextures(Textures); + core::array prevTextures(Textures); - if (numTextures > static_cast(ColorAttachment)) - { + if (numTextures > static_cast(ColorAttachment)) { core::stringc message = "This GPU supports up to "; message += static_cast(ColorAttachment); message += " textures per render target."; @@ -83,30 +81,24 @@ public: Textures.set_used(core::min_(numTextures, static_cast(ColorAttachment))); - for (u32 i = 0; i < Textures.size(); ++i) - { - TOpenGLTexture* currentTexture = (textures[i] && textures[i]->getDriverType() == DriverType) ? static_cast(textures[i]) : 0; + for (u32 i = 0; i < Textures.size(); ++i) { + TOpenGLTexture *currentTexture = (textures[i] && textures[i]->getDriverType() == DriverType) ? static_cast(textures[i]) : 0; GLuint textureID = 0; - if (currentTexture) - { + if (currentTexture) { textureID = currentTexture->getOpenGLTextureName(); } - if (textureID != 0) - { + if (textureID != 0) { Textures[i] = textures[i]; Textures[i]->grab(); - } - else - { + } else { Textures[i] = 0; } } - for (u32 i = 0; i < prevTextures.size(); ++i) - { + for (u32 i = 0; i < prevTextures.size(); ++i) { if (prevTextures[i]) prevTextures[i]->drop(); } @@ -114,43 +106,33 @@ public: RequestTextureUpdate = true; } - if (!CubeSurfaces.equals(cubeSurfaces, numCubeSurfaces)) - { + if (!CubeSurfaces.equals(cubeSurfaces, numCubeSurfaces)) { CubeSurfaces.set_data(cubeSurfaces, numCubeSurfaces); RequestTextureUpdate = true; } // Set depth and stencil attachments. - if (DepthStencil != depthStencil) - { - if (DepthStencil) - { + if (DepthStencil != depthStencil) { + if (DepthStencil) { DepthStencil->drop(); DepthStencil = 0; } needSizeUpdate = true; - TOpenGLTexture* currentTexture = (depthStencil && depthStencil->getDriverType() == DriverType) ? static_cast(depthStencil) : 0; + TOpenGLTexture *currentTexture = (depthStencil && depthStencil->getDriverType() == DriverType) ? static_cast(depthStencil) : 0; - if (currentTexture) - { - if (currentTexture->getType() == ETT_2D) - { + if (currentTexture) { + if (currentTexture->getType() == ETT_2D) { GLuint textureID = currentTexture->getOpenGLTextureName(); const ECOLOR_FORMAT textureFormat = (textureID != 0) ? depthStencil->getColorFormat() : ECF_UNKNOWN; - if (IImage::isDepthFormat(textureFormat)) - { + if (IImage::isDepthFormat(textureFormat)) { DepthStencil = depthStencil; DepthStencil->grab(); - } - else - { + } else { os::Printer::log("Ignoring depth/stencil texture without depth color format.", ELL_WARNING); } - } - else - { + } else { os::Printer::log("This driver doesn't support depth/stencil to cubemaps.", ELL_WARNING); } } @@ -158,16 +140,14 @@ public: RequestDepthStencilUpdate = true; } - if (needSizeUpdate) - { + if (needSizeUpdate) { // Set size required for a viewport. - ITexture* firstTexture = getTexture(); + ITexture *firstTexture = getTexture(); if (firstTexture) Size = firstTexture->getSize(); - else - { + else { if (DepthStencil) Size = DepthStencil->getSize(); else @@ -178,32 +158,26 @@ public: void update() { - if (RequestTextureUpdate || RequestDepthStencilUpdate) - { + if (RequestTextureUpdate || RequestDepthStencilUpdate) { // Set color attachments. - if (RequestTextureUpdate) - { + if (RequestTextureUpdate) { // Set new color textures. const u32 textureSize = core::min_(Textures.size(), AssignedTextures.size()); - for (u32 i = 0; i < textureSize; ++i) - { - TOpenGLTexture* currentTexture = static_cast(Textures[i]); + for (u32 i = 0; i < textureSize; ++i) { + TOpenGLTexture *currentTexture = static_cast(Textures[i]); GLuint textureID = currentTexture ? currentTexture->getOpenGLTextureName() : 0; - if (textureID != 0) - { + if (textureID != 0) { AssignedTextures[i] = GL_COLOR_ATTACHMENT0 + i; GLenum textarget = currentTexture->getType() == ETT_2D ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_POSITIVE_X + (int)CubeSurfaces[i]; Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, AssignedTextures[i], textarget, textureID, 0); #ifdef _DEBUG Driver->testGLError(__LINE__); #endif - } - else if (AssignedTextures[i] != GL_NONE) - { + } else if (AssignedTextures[i] != GL_NONE) { AssignedTextures[i] = GL_NONE; Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, AssignedTextures[i], GL_TEXTURE_2D, 0, 0); @@ -213,10 +187,8 @@ public: // Reset other render target channels. - for (u32 i = textureSize; i < AssignedTextures.size(); ++i) - { - if (AssignedTextures[i] != GL_NONE) - { + for (u32 i = textureSize; i < AssignedTextures.size(); ++i) { + if (AssignedTextures[i] != GL_NONE) { Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, AssignedTextures[i], GL_TEXTURE_2D, 0, 0); AssignedTextures[i] = GL_NONE; } @@ -227,37 +199,29 @@ public: // Set depth and stencil attachments. - if (RequestDepthStencilUpdate) - { + if (RequestDepthStencilUpdate) { const ECOLOR_FORMAT textureFormat = (DepthStencil) ? DepthStencil->getColorFormat() : ECF_UNKNOWN; - if (IImage::isDepthFormat(textureFormat)) - { - GLuint textureID = static_cast(DepthStencil)->getOpenGLTextureName(); + if (IImage::isDepthFormat(textureFormat)) { + GLuint textureID = static_cast(DepthStencil)->getOpenGLTextureName(); -#ifdef _IRR_EMSCRIPTEN_PLATFORM_ // The WEBGL_depth_texture extension does not allow attaching stencil+depth separate. - if (textureFormat == ECF_D24S8) - { +#ifdef _IRR_EMSCRIPTEN_PLATFORM_ // The WEBGL_depth_texture extension does not allow attaching stencil+depth separate. + if (textureFormat == ECF_D24S8) { GLenum attachment = 0x821A; // GL_DEPTH_STENCIL_ATTACHMENT Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, textureID, 0); AssignedStencil = true; - } - else - { + } else { Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureID, 0); AssignedStencil = false; } #else Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureID, 0); - if (textureFormat == ECF_D24S8) - { + if (textureFormat == ECF_D24S8) { Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, textureID, 0); AssignedStencil = true; - } - else - { + } else { if (AssignedStencil) Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); @@ -265,9 +229,7 @@ public: } #endif AssignedDepth = true; - } - else - { + } else { if (AssignedDepth) Driver->irrGlFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0); @@ -286,16 +248,14 @@ public: // Configure drawing operation. - if (ColorAttachment > 0 && BufferID != 0) - { + if (ColorAttachment > 0 && BufferID != 0) { const u32 textureSize = Textures.size(); if (textureSize == 0) Driver->irrGlDrawBuffer(GL_NONE); else if (textureSize == 1 || MultipleRenderTarget == 0) Driver->irrGlDrawBuffer(GL_COLOR_ATTACHMENT0); - else - { + else { const u32 bufferCount = core::min_(MultipleRenderTarget, core::min_(textureSize, AssignedTextures.size())); Driver->irrGlDrawBuffers(bufferCount, AssignedTextures.pointer()); @@ -304,7 +264,6 @@ public: #ifdef _DEBUG Driver->testGLError(__LINE__); #endif - } #ifdef _DEBUG @@ -318,15 +277,14 @@ public: return BufferID; } - const core::dimension2d& getSize() const + const core::dimension2d &getSize() const { return Size; } - ITexture* getTexture() const + ITexture *getTexture() const { - for (u32 i = 0; i < Textures.size(); ++i) - { + for (u32 i = 0; i < Textures.size(); ++i) { if (Textures[i]) return Textures[i]; } @@ -335,41 +293,40 @@ public: } protected: - bool checkFBO(TOpenGLDriver* driver) + bool checkFBO(TOpenGLDriver *driver) { if (ColorAttachment == 0) return true; GLenum status = driver->irrGlCheckFramebufferStatus(GL_FRAMEBUFFER); - switch (status) - { - case GL_FRAMEBUFFER_COMPLETE: - return true; - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - os::Printer::log("FBO has invalid read buffer", ELL_ERROR); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - os::Printer::log("FBO has invalid draw buffer", ELL_ERROR); - break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - os::Printer::log("FBO has one or several incomplete image attachments", ELL_ERROR); - break; - case GL_FRAMEBUFFER_INCOMPLETE_FORMATS: - os::Printer::log("FBO has one or several image attachments with different internal formats", ELL_ERROR); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - os::Printer::log("FBO has one or several image attachments with different dimensions", ELL_ERROR); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - os::Printer::log("FBO missing an image attachment", ELL_ERROR); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - os::Printer::log("FBO format unsupported", ELL_ERROR); - break; - default: - os::Printer::log("FBO error", ELL_ERROR); - break; + switch (status) { + case GL_FRAMEBUFFER_COMPLETE: + return true; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + os::Printer::log("FBO has invalid read buffer", ELL_ERROR); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + os::Printer::log("FBO has invalid draw buffer", ELL_ERROR); + break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + os::Printer::log("FBO has one or several incomplete image attachments", ELL_ERROR); + break; + case GL_FRAMEBUFFER_INCOMPLETE_FORMATS: + os::Printer::log("FBO has one or several image attachments with different internal formats", ELL_ERROR); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + os::Printer::log("FBO has one or several image attachments with different dimensions", ELL_ERROR); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + os::Printer::log("FBO missing an image attachment", ELL_ERROR); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + os::Printer::log("FBO format unsupported", ELL_ERROR); + break; + default: + os::Printer::log("FBO error", ELL_ERROR); + break; } return false; @@ -389,7 +346,7 @@ protected: u32 ColorAttachment; u32 MultipleRenderTarget; - TOpenGLDriver* Driver; + TOpenGLDriver *Driver; }; } diff --git a/source/Irrlicht/COpenGLCoreTexture.h b/source/Irrlicht/COpenGLCoreTexture.h index 0fcd06ca..45bf2f0b 100644 --- a/source/Irrlicht/COpenGLCoreTexture.h +++ b/source/Irrlicht/COpenGLCoreTexture.h @@ -25,9 +25,10 @@ class COpenGLCoreTexture : public ITexture public: struct SStatesCache { - SStatesCache() : WrapU(ETC_REPEAT), WrapV(ETC_REPEAT), WrapW(ETC_REPEAT), - LODBias(0), AnisotropicFilter(0), MinFilter(video::ETMINF_NEAREST_MIPMAP_NEAREST), - MagFilter(video::ETMAGF_NEAREST), MipMapStatus(false), IsCached(false) + SStatesCache() : + WrapU(ETC_REPEAT), WrapV(ETC_REPEAT), WrapW(ETC_REPEAT), + LODBias(0), AnisotropicFilter(0), MinFilter(video::ETMINF_NEAREST_MIPMAP_NEAREST), + MagFilter(video::ETMAGF_NEAREST), MipMapStatus(false), IsCached(false) { } @@ -42,9 +43,10 @@ public: bool IsCached; }; - COpenGLCoreTexture(const io::path& name, const core::array& images, E_TEXTURE_TYPE type, TOpenGLDriver* driver) : ITexture(name, type), Driver(driver), TextureType(GL_TEXTURE_2D), - TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_RGBA), PixelType(GL_UNSIGNED_BYTE), Converter(0), LockReadOnly(false), LockImage(0), LockLayer(0), - KeepImage(false), MipLevelStored(0), LegacyAutoGenerateMipMaps(false) + COpenGLCoreTexture(const io::path &name, const core::array &images, E_TEXTURE_TYPE type, TOpenGLDriver *driver) : + ITexture(name, type), Driver(driver), TextureType(GL_TEXTURE_2D), + TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_RGBA), PixelType(GL_UNSIGNED_BYTE), Converter(0), LockReadOnly(false), LockImage(0), LockLayer(0), + KeepImage(false), MipLevelStored(0), LegacyAutoGenerateMipMaps(false) { _IRR_DEBUG_BREAK_IF(images.size() == 0) @@ -57,14 +59,12 @@ public: if (!InternalFormat) return; - const core::array* tmpImages = &images; + const core::array *tmpImages = &images; - if (KeepImage || OriginalSize != Size || OriginalColorFormat != ColorFormat) - { + if (KeepImage || OriginalSize != Size || OriginalColorFormat != ColorFormat) { Images.set_used(images.size()); - for (u32 i = 0; i < images.size(); ++i) - { + for (u32 i = 0; i < images.size(); ++i) { Images[i] = Driver->createImage(ColorFormat, Size); if (images[i]->getDimension() == Size) @@ -72,14 +72,10 @@ public: else images[i]->copyToScaling(Images[i]); - if ( images[i]->getMipMapsData() ) - { - if ( OriginalSize == Size && OriginalColorFormat == ColorFormat ) - { - Images[i]->setMipMapsData( images[i]->getMipMapsData(), false); - } - else - { + if (images[i]->getMipMapsData()) { + if (OriginalSize == Size && OriginalColorFormat == ColorFormat) { + Images[i]->setMipMapsData(images[i]->getMipMapsData(), false); + } else { // TODO: handle at least mipmap with changing color format os::Printer::log("COpenGLCoreTexture: Can't handle format changes for mipmap data. Mipmap data dropped", ELL_WARNING); } @@ -91,15 +87,14 @@ public: GL.GenTextures(1, &TextureName); - const COpenGLCoreTexture* prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); + const COpenGLCoreTexture *prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); Driver->getCacheHandler()->getTextureCache().set(0, this); GL.TexParameteri(TextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL.TexParameteri(TextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); #ifdef GL_GENERATE_MIPMAP_HINT - if (HasMipMaps) - { + if (HasMipMaps) { if (Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED)) GL.Hint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST); else if (Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_QUALITY)) @@ -112,35 +107,31 @@ public: for (u32 i = 0; i < (*tmpImages).size(); ++i) uploadTexture(true, i, 0, (*tmpImages)[i]->getData()); - if (HasMipMaps && !LegacyAutoGenerateMipMaps) - { + if (HasMipMaps && !LegacyAutoGenerateMipMaps) { // Create mipmaps (either from image mipmaps or generate them) - for (u32 i = 0; i < (*tmpImages).size(); ++i) - { - void* mipmapsData = (*tmpImages)[i]->getMipMapsData(); + for (u32 i = 0; i < (*tmpImages).size(); ++i) { + void *mipmapsData = (*tmpImages)[i]->getMipMapsData(); regenerateMipMapLevels(mipmapsData, i); } } - if (!KeepImage) - { + if (!KeepImage) { for (u32 i = 0; i < Images.size(); ++i) Images[i]->drop(); Images.clear(); } - Driver->getCacheHandler()->getTextureCache().set(0, prevTexture); Driver->testGLError(__LINE__); } - COpenGLCoreTexture(const io::path& name, const core::dimension2d& size, E_TEXTURE_TYPE type, ECOLOR_FORMAT format, TOpenGLDriver* driver) - : ITexture(name, type), - Driver(driver), TextureType(GL_TEXTURE_2D), - TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_RGBA), PixelType(GL_UNSIGNED_BYTE), Converter(0), LockReadOnly(false), LockImage(0), LockLayer(0), KeepImage(false), - MipLevelStored(0), LegacyAutoGenerateMipMaps(false) + COpenGLCoreTexture(const io::path &name, const core::dimension2d &size, E_TEXTURE_TYPE type, ECOLOR_FORMAT format, TOpenGLDriver *driver) : + ITexture(name, type), + Driver(driver), TextureType(GL_TEXTURE_2D), + TextureName(0), InternalFormat(GL_RGBA), PixelFormat(GL_RGBA), PixelType(GL_UNSIGNED_BYTE), Converter(0), LockReadOnly(false), LockImage(0), LockLayer(0), KeepImage(false), + MipLevelStored(0), LegacyAutoGenerateMipMaps(false) { DriverType = Driver->getDriverType(); TextureType = TextureTypeIrrToGL(Type); @@ -159,18 +150,16 @@ public: Pitch = Size.Width * IImage::getBitsPerPixelFromFormat(ColorFormat) / 8; - if ( !Driver->getColorFormatParameters(ColorFormat, InternalFormat, PixelFormat, PixelType, &Converter) ) - { - os::Printer::log("COpenGLCoreTexture: Color format is not supported", ColorFormatNames[ColorFormat < ECF_UNKNOWN?ColorFormat:ECF_UNKNOWN], ELL_ERROR); + if (!Driver->getColorFormatParameters(ColorFormat, InternalFormat, PixelFormat, PixelType, &Converter)) { + os::Printer::log("COpenGLCoreTexture: Color format is not supported", ColorFormatNames[ColorFormat < ECF_UNKNOWN ? ColorFormat : ECF_UNKNOWN], ELL_ERROR); return; } GL.GenTextures(1, &TextureName); - const COpenGLCoreTexture* prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); + const COpenGLCoreTexture *prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); Driver->getCacheHandler()->getTextureCache().set(0, this); - GL.TexParameteri(TextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL.TexParameteri(TextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL.TexParameteri(TextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -184,8 +173,7 @@ public: StatesCache.WrapV = ETC_CLAMP_TO_EDGE; StatesCache.WrapW = ETC_CLAMP_TO_EDGE; - switch (Type) - { + switch (Type) { case ETT_2D: GL.TexImage2D(GL_TEXTURE_2D, 0, InternalFormat, Size.Width, Size.Height, 0, PixelFormat, PixelType, 0); break; @@ -200,8 +188,7 @@ public: } Driver->getCacheHandler()->getTextureCache().set(0, prevTexture); - if ( Driver->testGLError(__LINE__) ) - { + if (Driver->testGLError(__LINE__)) { char msg[256]; snprintf_irr(msg, 256, "COpenGLCoreTexture: InternalFormat:0x%04x PixelFormat:0x%04x", (int)InternalFormat, (int)PixelFormat); os::Printer::log(msg, ELL_ERROR); @@ -220,7 +207,7 @@ public: Images[i]->drop(); } - void* lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel=0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) override + void *lock(E_TEXTURE_LOCK_MODE mode = ETLM_READ_WRITE, u32 mipmapLevel = 0, u32 layer = 0, E_TEXTURE_LOCK_FLAGS lockFlags = ETLF_FLIP_Y_UP_RTT) override { if (LockImage) return getLockImageData(MipLevelStored); @@ -232,38 +219,33 @@ public: LockLayer = layer; MipLevelStored = mipmapLevel; - if (KeepImage) - { + if (KeepImage) { _IRR_DEBUG_BREAK_IF(LockLayer > Images.size()) - if ( mipmapLevel == 0 || (Images[LockLayer] && Images[LockLayer]->getMipMapsData(mipmapLevel)) ) - { + if (mipmapLevel == 0 || (Images[LockLayer] && Images[LockLayer]->getMipMapsData(mipmapLevel))) { LockImage = Images[LockLayer]; LockImage->grab(); } } - if ( !LockImage ) - { - core::dimension2d lockImageSize( IImage::getMipMapsSize(Size, MipLevelStored)); + if (!LockImage) { + core::dimension2d lockImageSize(IImage::getMipMapsSize(Size, MipLevelStored)); // note: we save mipmap data also in the image because IImage doesn't allow saving single mipmap levels to the mipmap data LockImage = Driver->createImage(ColorFormat, lockImageSize); - if (LockImage && mode != ETLM_WRITE_ONLY) - { + if (LockImage && mode != ETLM_WRITE_ONLY) { bool passed = true; #ifdef IRR_COMPILE_GL_COMMON - IImage* tmpImage = LockImage; // not sure yet if the size required by glGetTexImage is always correct, if not we might have to allocate a different tmpImage and convert colors later on. + IImage *tmpImage = LockImage; // not sure yet if the size required by glGetTexImage is always correct, if not we might have to allocate a different tmpImage and convert colors later on. Driver->getCacheHandler()->getTextureCache().set(0, this); Driver->testGLError(__LINE__); GLenum tmpTextureType = TextureType; - if (tmpTextureType == GL_TEXTURE_CUBE_MAP) - { + if (tmpTextureType == GL_TEXTURE_CUBE_MAP) { _IRR_DEBUG_BREAK_IF(layer > 5) tmpTextureType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + layer; @@ -272,17 +254,15 @@ public: GL.GetTexImage(tmpTextureType, MipLevelStored, PixelFormat, PixelType, tmpImage->getData()); Driver->testGLError(__LINE__); - if (IsRenderTarget && lockFlags == ETLF_FLIP_Y_UP_RTT) - { + if (IsRenderTarget && lockFlags == ETLF_FLIP_Y_UP_RTT) { const s32 pitch = tmpImage->getPitch(); - u8* srcA = static_cast(tmpImage->getData()); - u8* srcB = srcA + (tmpImage->getDimension().Height - 1) * pitch; + u8 *srcA = static_cast(tmpImage->getData()); + u8 *srcB = srcA + (tmpImage->getDimension().Height - 1) * pitch; - u8* tmpBuffer = new u8[pitch]; + u8 *tmpBuffer = new u8[pitch]; - for (u32 i = 0; i < tmpImage->getDimension().Height; i += 2) - { + for (u32 i = 0; i < tmpImage->getDimension().Height; i += 2) { memcpy(tmpBuffer, srcA, pitch); memcpy(srcA, srcB, pitch); memcpy(srcB, tmpBuffer, pitch); @@ -292,9 +272,9 @@ public: delete[] tmpBuffer; } -#elif (defined(IRR_COMPILE_GLES2_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) -// TODO: on ES2 we can likely also work with glCopyTexImage2D instead of rendering which should be faster. - COpenGLCoreTexture* tmpTexture = new COpenGLCoreTexture("OGL_CORE_LOCK_TEXTURE", Size, ETT_2D, ColorFormat, Driver); +#elif (defined(IRR_COMPILE_GLES2_COMMON) || defined(IRR_COMPILE_GLES_COMMON)) + // TODO: on ES2 we can likely also work with glCopyTexImage2D instead of rendering which should be faster. + COpenGLCoreTexture *tmpTexture = new COpenGLCoreTexture("OGL_CORE_LOCK_TEXTURE", Size, ETT_2D, ColorFormat, Driver); GLuint tmpFBO = 0; Driver->irrGlGenFramebuffers(1, &tmpFBO); @@ -316,7 +296,7 @@ public: Driver->draw2DImage(this, layer, true); - IImage* tmpImage = Driver->createImage(ECF_A8R8G8B8, Size); + IImage *tmpImage = Driver->createImage(ECF_A8R8G8B8, Size); GL.ReadPixels(0, 0, Size.Width, Size.Height, GL_RGBA, GL_UNSIGNED_BYTE, tmpImage->getData()); Driver->getCacheHandler()->setFBO(prevFBO); @@ -325,11 +305,10 @@ public: Driver->irrGlDeleteFramebuffers(1, &tmpFBO); delete tmpTexture; - void* src = tmpImage->getData(); - void* dest = LockImage->getData(); + void *src = tmpImage->getData(); + void *dest = LockImage->getData(); - switch (ColorFormat) - { + switch (ColorFormat) { case ECF_A1R5G5B5: CColorConverter::convert_A8R8G8B8toA1B5G5R5(src, tmpImage->getDimension().getArea(), dest); break; @@ -349,8 +328,7 @@ public: tmpImage->drop(); #endif - if (!passed) - { + if (!passed) { LockImage->drop(); LockImage = 0; } @@ -367,9 +345,8 @@ public: if (!LockImage) return; - if (!LockReadOnly) - { - const COpenGLCoreTexture* prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); + if (!LockReadOnly) { + const COpenGLCoreTexture *prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); Driver->getCacheHandler()->getTextureCache().set(0, this); uploadTexture(false, LockLayer, MipLevelStored, getLockImageData(MipLevelStored)); @@ -384,24 +361,22 @@ public: LockLayer = 0; } - void regenerateMipMapLevels(void* data = 0, u32 layer = 0) override + void regenerateMipMapLevels(void *data = 0, u32 layer = 0) override { if (!HasMipMaps || LegacyAutoGenerateMipMaps || (Size.Width <= 1 && Size.Height <= 1)) return; - const COpenGLCoreTexture* prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); + const COpenGLCoreTexture *prevTexture = Driver->getCacheHandler()->getTextureCache().get(0); Driver->getCacheHandler()->getTextureCache().set(0, this); - if (data) - { + if (data) { u32 width = Size.Width; u32 height = Size.Height; - u8* tmpData = static_cast(data); + u8 *tmpData = static_cast(data); u32 dataSize = 0; u32 level = 0; - do - { + do { if (width > 1) width >>= 1; @@ -414,11 +389,8 @@ public: uploadTexture(true, layer, level, tmpData); tmpData += dataSize; - } - while (width != 1 || height != 1); - } - else - { + } while (width != 1 || height != 1); + } else { Driver->irrGlGenerateMipmap(TextureType); } @@ -435,18 +407,15 @@ public: return TextureName; } - SStatesCache& getStatesCache() const + SStatesCache &getStatesCache() const { return StatesCache; } protected: - - void * getLockImageData(irr::u32 miplevel) const + void *getLockImageData(irr::u32 miplevel) const { - if ( KeepImage && MipLevelStored > 0 - && LockImage->getMipMapsData(MipLevelStored) ) - { + if (KeepImage && MipLevelStored > 0 && LockImage->getMipMapsData(MipLevelStored)) { return LockImage->getMipMapsData(MipLevelStored); } return LockImage->getData(); @@ -457,8 +426,7 @@ protected: // We only try for to adapt "simple" formats ECOLOR_FORMAT destFormat = (format <= ECF_A8R8G8B8) ? ECF_A8R8G8B8 : format; - switch (format) - { + switch (format) { case ECF_A1R5G5B5: if (!Driver->getTextureCreationFlag(ETCF_ALWAYS_32_BIT)) destFormat = ECF_A1R5G5B5; @@ -469,7 +437,7 @@ protected: break; case ECF_A8R8G8B8: if (Driver->getTextureCreationFlag(ETCF_ALWAYS_16_BIT) || - Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED)) + Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED)) destFormat = ECF_A1R5G5B5; break; case ECF_R8G8B8: @@ -480,10 +448,8 @@ protected: break; } - if (Driver->getTextureCreationFlag(ETCF_NO_ALPHA_CHANNEL)) - { - switch (destFormat) - { + if (Driver->getTextureCreationFlag(ETCF_NO_ALPHA_CHANNEL)) { + switch (destFormat) { case ECF_A1R5G5B5: destFormat = ECF_R5G6B5; break; @@ -498,41 +464,35 @@ protected: return destFormat; } - void getImageValues(const IImage* image) + void getImageValues(const IImage *image) { OriginalColorFormat = image->getColorFormat(); ColorFormat = getBestColorFormat(OriginalColorFormat); - if ( !Driver->getColorFormatParameters(ColorFormat, InternalFormat, PixelFormat, PixelType, &Converter) ) - { - os::Printer::log("getImageValues: Color format is not supported", ColorFormatNames[ColorFormat < ECF_UNKNOWN?ColorFormat:ECF_UNKNOWN], ELL_ERROR); + if (!Driver->getColorFormatParameters(ColorFormat, InternalFormat, PixelFormat, PixelType, &Converter)) { + os::Printer::log("getImageValues: Color format is not supported", ColorFormatNames[ColorFormat < ECF_UNKNOWN ? ColorFormat : ECF_UNKNOWN], ELL_ERROR); InternalFormat = 0; return; } - if (IImage::isCompressedFormat(image->getColorFormat())) - { + if (IImage::isCompressedFormat(image->getColorFormat())) { KeepImage = false; } OriginalSize = image->getDimension(); Size = OriginalSize; - if (Size.Width == 0 || Size.Height == 0) - { + if (Size.Width == 0 || Size.Height == 0) { os::Printer::log("Invalid size of image for texture.", ELL_ERROR); return; } const f32 ratio = (f32)Size.Width / (f32)Size.Height; - if ((Size.Width > Driver->MaxTextureSize) && (ratio >= 1.f)) - { + if ((Size.Width > Driver->MaxTextureSize) && (ratio >= 1.f)) { Size.Width = Driver->MaxTextureSize; Size.Height = (u32)(Driver->MaxTextureSize / ratio); - } - else if (Size.Height > Driver->MaxTextureSize) - { + } else if (Size.Height > Driver->MaxTextureSize) { Size.Height = Driver->MaxTextureSize; Size.Width = (u32)(Driver->MaxTextureSize * ratio); } @@ -544,7 +504,7 @@ protected: Pitch = Size.Width * IImage::getBitsPerPixelFromFormat(ColorFormat) / 8; } - void uploadTexture(bool initTexture, u32 layer, u32 level, void* data) + void uploadTexture(bool initTexture, u32 layer, u32 level, void *data) { if (!data) return; @@ -558,20 +518,17 @@ protected: GLenum tmpTextureType = TextureType; - if (tmpTextureType == GL_TEXTURE_CUBE_MAP) - { + if (tmpTextureType == GL_TEXTURE_CUBE_MAP) { _IRR_DEBUG_BREAK_IF(layer > 5) tmpTextureType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + layer; } - if (!IImage::isCompressedFormat(ColorFormat)) - { - CImage* tmpImage = 0; - void* tmpData = data; + if (!IImage::isCompressedFormat(ColorFormat)) { + CImage *tmpImage = 0; + void *tmpData = data; - if (Converter) - { + if (Converter) { const core::dimension2d tmpImageSize(width, height); tmpImage = new CImage(ColorFormat, tmpImageSize); @@ -580,8 +537,7 @@ protected: Converter(data, tmpImageSize.getArea(), tmpData); } - switch (TextureType) - { + switch (TextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: if (initTexture) @@ -595,13 +551,10 @@ protected: } delete tmpImage; - } - else - { + } else { u32 dataSize = IImage::getDataSizeFromFormat(ColorFormat, width, height); - switch (TextureType) - { + switch (TextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: if (initTexture) @@ -618,8 +571,7 @@ protected: GLenum TextureTypeIrrToGL(E_TEXTURE_TYPE type) const { - switch ( type) - { + switch (type) { case ETT_2D: return GL_TEXTURE_2D; case ETT_CUBEMAP: @@ -630,21 +582,21 @@ protected: return GL_TEXTURE_2D; } - TOpenGLDriver* Driver; + TOpenGLDriver *Driver; GLenum TextureType; GLuint TextureName; GLint InternalFormat; GLenum PixelFormat; GLenum PixelType; - void (*Converter)(const void*, s32, void*); + void (*Converter)(const void *, s32, void *); bool LockReadOnly; - IImage* LockImage; + IImage *LockImage; u32 LockLayer; bool KeepImage; - core::array Images; + core::array Images; u8 MipLevelStored; bool LegacyAutoGenerateMipMaps; diff --git a/source/Irrlicht/COpenGLDriver.cpp b/source/Irrlicht/COpenGLDriver.cpp index 64e50f60..a82c0457 100644 --- a/source/Irrlicht/COpenGLDriver.cpp +++ b/source/Irrlicht/COpenGLDriver.cpp @@ -26,12 +26,12 @@ namespace video { // Statics variables -const u16 COpenGLDriver::Quad2DIndices[4] = { 0, 1, 2, 3 }; +const u16 COpenGLDriver::Quad2DIndices[4] = {0, 1, 2, 3}; -COpenGLDriver::COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - : CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(), CacheHandler(0), CurrentRenderMode(ERM_NONE), ResetRenderStates(true), - Transformation3DChanged(true), AntiAlias(params.AntiAlias), ColorFormat(ECF_R8G8B8), FixedPipelineState(EOFPS_ENABLE), Params(params), - ContextManager(contextManager) +COpenGLDriver::COpenGLDriver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) : + CNullDriver(io, params.WindowSize), COpenGLExtensionHandler(), CacheHandler(0), CurrentRenderMode(ERM_NONE), ResetRenderStates(true), + Transformation3DChanged(true), AntiAlias(params.AntiAlias), ColorFormat(ECF_R8G8B8), FixedPipelineState(EOFPS_ENABLE), Params(params), + ContextManager(contextManager) { #ifdef _DEBUG setDebugName("COpenGLDriver"); @@ -70,8 +70,7 @@ COpenGLDriver::~COpenGLDriver() delete CacheHandler; - if (ContextManager) - { + if (ContextManager) { ContextManager->destroyContext(); ContextManager->destroySurface(); ContextManager->terminate(); @@ -88,20 +87,19 @@ bool COpenGLDriver::genericDriverInit() if (ContextManager) ContextManager->grab(); - Name="OpenGL "; + Name = "OpenGL "; Name.append(glGetString(GL_VERSION)); - s32 pos=Name.findNext(' ', 7); + s32 pos = Name.findNext(' ', 7); if (pos != -1) - Name=Name.subString(0, pos); + Name = Name.subString(0, pos); printVersion(); // print renderer information - const GLubyte* renderer = glGetString(GL_RENDERER); - const GLubyte* vendor = glGetString(GL_VENDOR); - if (renderer && vendor) - { - os::Printer::log(reinterpret_cast(renderer), reinterpret_cast(vendor), ELL_INFORMATION); - VendorName = reinterpret_cast(vendor); + const GLubyte *renderer = glGetString(GL_RENDERER); + const GLubyte *vendor = glGetString(GL_VENDOR); + if (renderer && vendor) { + os::Printer::log(reinterpret_cast(renderer), reinterpret_cast(vendor), ELL_INFORMATION); + VendorName = reinterpret_cast(vendor); } u32 i; @@ -113,14 +111,12 @@ bool COpenGLDriver::genericDriverInit() delete CacheHandler; CacheHandler = new COpenGLCacheHandler(this); - if (queryFeature(EVDF_ARB_GLSL)) - { + if (queryFeature(EVDF_ARB_GLSL)) { char buf[32]; - const u32 maj = ShaderLanguageVersion/100; - snprintf_irr(buf, 32, "%u.%u", maj, ShaderLanguageVersion-maj*100); + const u32 maj = ShaderLanguageVersion / 100; + snprintf_irr(buf, 32, "%u.%u", maj, ShaderLanguageVersion - maj * 100); os::Printer::log("GLSL version", buf, ELL_INFORMATION); - } - else + } else os::Printer::log("GLSL not available.", ELL_INFORMATION); DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits); DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits); @@ -140,22 +136,22 @@ bool COpenGLDriver::genericDriverInit() glPixelStorei(GL_PACK_ALIGNMENT, 1); UserClipPlanes.reallocate(MaxUserClipPlanes); - for (i=0; i(i), core::IdentityMatrix); - setAmbientLight(SColorf(0.0f,0.0f,0.0f,0.0f)); + setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f)); #ifdef GL_EXT_separate_specular_color if (FeatureAvailable[IRR_EXT_separate_specular_color]) glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); #endif glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1); -// This is a fast replacement for NORMALIZE_NORMALS -// if ((Version>101) || FeatureAvailable[IRR_EXT_rescale_normal]) -// glEnable(GL_RESCALE_NORMAL_EXT); + // This is a fast replacement for NORMALIZE_NORMALS + // if ((Version>101) || FeatureAvailable[IRR_EXT_rescale_normal]) + // glEnable(GL_RESCALE_NORMAL_EXT); glClearDepth(1.0); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); @@ -166,10 +162,10 @@ bool COpenGLDriver::genericDriverInit() #endif // Create built-in 2D quad for 2D rendering (both quads and lines). - Quad2DVertices[0] = S3DVertex(core::vector3df(-1.0f, 1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255,255,255,255), core::vector2df(0.0f, 1.0f)); - Quad2DVertices[1] = S3DVertex(core::vector3df(1.0f, 1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255,255,255,255), core::vector2df(1.0f, 1.0f)); - Quad2DVertices[2] = S3DVertex(core::vector3df(1.0f, -1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255,255,255,255), core::vector2df(1.0f, 0.0f)); - Quad2DVertices[3] = S3DVertex(core::vector3df(-1.0f, -1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255,255,255,255), core::vector2df(0.0f, 0.0f)); + Quad2DVertices[0] = S3DVertex(core::vector3df(-1.0f, 1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255, 255, 255, 255), core::vector2df(0.0f, 1.0f)); + Quad2DVertices[1] = S3DVertex(core::vector3df(1.0f, 1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255, 255, 255, 255), core::vector2df(1.0f, 1.0f)); + Quad2DVertices[2] = S3DVertex(core::vector3df(1.0f, -1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255, 255, 255, 255), core::vector2df(1.0f, 0.0f)); + Quad2DVertices[3] = S3DVertex(core::vector3df(-1.0f, -1.0f, 0.0f), core::vector3df(0.0f, 0.0f, 0.0f), SColor(255, 255, 255, 255), core::vector2df(0.0f, 0.0f)); // create material renderers createMaterialRenderers(); @@ -181,7 +177,7 @@ bool COpenGLDriver::genericDriverInit() setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog); // create matrix for flipping textures - TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0,0), core::vector2df(0,1.0f), core::vector2df(1.0f,-1.0f)); + TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f)); // We need to reset once more at the beginning of the first rendering. // This fixes problems with intermediate changes to the material during texture load. @@ -190,7 +186,6 @@ bool COpenGLDriver::genericDriverInit() return true; } - void COpenGLDriver::createMaterialRenderers() { addAndDropMaterialRenderer(new COpenGLMaterialRenderer_SOLID(this)); @@ -200,7 +195,7 @@ void COpenGLDriver::createMaterialRenderers() addAndDropMaterialRenderer(new COpenGLMaterialRenderer_ONETEXTURE_BLEND(this)); } -bool COpenGLDriver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) +bool COpenGLDriver::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData &videoData, core::rect *sourceRect) { CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); @@ -228,52 +223,44 @@ bool COpenGLDriver::endScene() return status; } - //! Returns the transformation set by setTransform -const core::matrix4& COpenGLDriver::getTransform(E_TRANSFORMATION_STATE state) const +const core::matrix4 &COpenGLDriver::getTransform(E_TRANSFORMATION_STATE state) const { return Matrices[state]; } - //! sets transformation -void COpenGLDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) +void COpenGLDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) { Matrices[state] = mat; Transformation3DChanged = true; - switch (state) - { + switch (state) { case ETS_VIEW: - case ETS_WORLD: - { - // OpenGL only has a model matrix, view and world is not existent. so lets fake these two. - CacheHandler->setMatrixMode(GL_MODELVIEW); + case ETS_WORLD: { + // OpenGL only has a model matrix, view and world is not existent. so lets fake these two. + CacheHandler->setMatrixMode(GL_MODELVIEW); - // first load the viewing transformation for user clip planes - glLoadMatrixf((Matrices[ETS_VIEW]).pointer()); + // first load the viewing transformation for user clip planes + glLoadMatrixf((Matrices[ETS_VIEW]).pointer()); - // we have to update the clip planes to the latest view matrix - for (u32 i=0; isetMatrixMode(GL_PROJECTION); - glLoadMatrixf(mat.pointer()); - } - break; + // now the real model-view matrix + glMultMatrixf(Matrices[ETS_WORLD].pointer()); + } break; + case ETS_PROJECTION: { + CacheHandler->setMatrixMode(GL_PROJECTION); + glLoadMatrixf(mat.pointer()); + } break; default: break; } } - bool COpenGLDriver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) { if (!HWBuffer) @@ -283,73 +270,58 @@ bool COpenGLDriver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) return false; #if defined(GL_ARB_vertex_buffer_object) - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void* vertices=mb->getVertices(); - const u32 vertexCount=mb->getVertexCount(); - const E_VERTEX_TYPE vType=mb->getVertexType(); + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const u32 vertexCount = mb->getVertexCount(); + const E_VERTEX_TYPE vType = mb->getVertexType(); const u32 vertexSize = getVertexPitchFromType(vType); - const c8* vbuf = static_cast(vertices); + const c8 *vbuf = static_cast(vertices); core::array buffer; - if (!FeatureAvailable[IRR_ARB_vertex_array_bgra] && !FeatureAvailable[IRR_EXT_vertex_array_bgra]) - { - //buffer vertex data, and convert colors... + if (!FeatureAvailable[IRR_ARB_vertex_array_bgra] && !FeatureAvailable[IRR_EXT_vertex_array_bgra]) { + // buffer vertex data, and convert colors... buffer.set_used(vertexSize * vertexCount); memcpy(buffer.pointer(), vertices, vertexSize * vertexCount); vbuf = buffer.const_pointer(); // in order to convert the colors into opengl format (RGBA) - switch (vType) - { - case EVT_STANDARD: - { - S3DVertex* pb = reinterpret_cast(buffer.pointer()); - const S3DVertex* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertex *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color)); } - break; - case EVT_2TCOORDS: - { - S3DVertex2TCoords* pb = reinterpret_cast(buffer.pointer()); - const S3DVertex2TCoords* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertex2TCoords *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color)); } - break; - case EVT_TANGENTS: - { - S3DVertexTangents* pb = reinterpret_cast(buffer.pointer()); - const S3DVertexTangents* po = static_cast(vertices); - for (u32 i=0; i(buffer.pointer()); + const S3DVertexTangents *po = static_cast(vertices); + for (u32 i = 0; i < vertexCount; i++) { + po[i].Color.toOpenGLColor((u8 *)&(pb[i].Color)); } + } break; + default: { + return false; + } } } - //get or create buffer - bool newBuffer=false; - if (!HWBuffer->vbo_verticesID) - { + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_verticesID) { extGlGenBuffers(1, &HWBuffer->vbo_verticesID); if (!HWBuffer->vbo_verticesID) return false; - newBuffer=true; - } - else if (HWBuffer->vbo_verticesSize < vertexCount*vertexSize) - { - newBuffer=true; + newBuffer = true; + } else if (HWBuffer->vbo_verticesSize < vertexCount * vertexSize) { + newBuffer = true; } extGlBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); @@ -357,15 +329,14 @@ bool COpenGLDriver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) // copy data to graphics card if (!newBuffer) extGlBufferSubData(GL_ARRAY_BUFFER, 0, vertexCount * vertexSize, vbuf); - else - { - HWBuffer->vbo_verticesSize = vertexCount*vertexSize; + else { + HWBuffer->vbo_verticesSize = vertexCount * vertexSize; - if (HWBuffer->Mapped_Vertex==scene::EHM_STATIC) + if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC) extGlBufferData(GL_ARRAY_BUFFER, vertexCount * vertexSize, vbuf, GL_STATIC_DRAW); - else if (HWBuffer->Mapped_Vertex==scene::EHM_DYNAMIC) + else if (HWBuffer->Mapped_Vertex == scene::EHM_DYNAMIC) extGlBufferData(GL_ARRAY_BUFFER, vertexCount * vertexSize, vbuf, GL_DYNAMIC_DRAW); - else //scene::EHM_STREAM + else // scene::EHM_STREAM extGlBufferData(GL_ARRAY_BUFFER, vertexCount * vertexSize, vbuf, GL_STREAM_DRAW); } @@ -377,7 +348,6 @@ bool COpenGLDriver::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) #endif } - bool COpenGLDriver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) { if (!HWBuffer) @@ -387,43 +357,35 @@ bool COpenGLDriver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) return false; #if defined(GL_ARB_vertex_buffer_object) - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; - const void* indices=mb->getIndices(); - u32 indexCount= mb->getIndexCount(); + const void *indices = mb->getIndices(); + u32 indexCount = mb->getIndexCount(); GLenum indexSize; - switch (mb->getIndexType()) - { - case EIT_16BIT: - { - indexSize=sizeof(u16); - break; - } - case EIT_32BIT: - { - indexSize=sizeof(u32); - break; - } - default: - { - return false; - } + switch (mb->getIndexType()) { + case EIT_16BIT: { + indexSize = sizeof(u16); + break; + } + case EIT_32BIT: { + indexSize = sizeof(u32); + break; + } + default: { + return false; + } } - - //get or create buffer - bool newBuffer=false; - if (!HWBuffer->vbo_indicesID) - { + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_indicesID) { extGlGenBuffers(1, &HWBuffer->vbo_indicesID); if (!HWBuffer->vbo_indicesID) return false; - newBuffer=true; - } - else if (HWBuffer->vbo_indicesSize < indexCount*indexSize) - { - newBuffer=true; + newBuffer = true; + } else if (HWBuffer->vbo_indicesSize < indexCount * indexSize) { + newBuffer = true; } extGlBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); @@ -431,15 +393,14 @@ bool COpenGLDriver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) // copy data to graphics card if (!newBuffer) extGlBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); - else - { - HWBuffer->vbo_indicesSize = indexCount*indexSize; + else { + HWBuffer->vbo_indicesSize = indexCount * indexSize; - if (HWBuffer->Mapped_Index==scene::EHM_STATIC) + if (HWBuffer->Mapped_Index == scene::EHM_STATIC) extGlBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW); - else if (HWBuffer->Mapped_Index==scene::EHM_DYNAMIC) + else if (HWBuffer->Mapped_Index == scene::EHM_DYNAMIC) extGlBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW); - else //scene::EHM_STREAM + else // scene::EHM_STREAM extGlBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STREAM_DRAW); } @@ -451,35 +412,28 @@ bool COpenGLDriver::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) #endif } - //! updates hardware buffer if needed bool COpenGLDriver::updateHardwareBuffer(SHWBufferLink *HWBuffer) { if (!HWBuffer) return false; - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() - || !((SHWBufferLink_opengl*)HWBuffer)->vbo_verticesID) - { + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() || !((SHWBufferLink_opengl *)HWBuffer)->vbo_verticesID) { HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - if (!updateVertexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer)) + if (!updateVertexHardwareBuffer((SHWBufferLink_opengl *)HWBuffer)) return false; } } - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() - || !((SHWBufferLink_opengl*)HWBuffer)->vbo_indicesID) - { + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() || !((SHWBufferLink_opengl *)HWBuffer)->vbo_indicesID) { HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer)) + if (!updateIndexHardwareBuffer((SHWBufferLink_opengl *)HWBuffer)) return false; } } @@ -487,30 +441,28 @@ bool COpenGLDriver::updateHardwareBuffer(SHWBufferLink *HWBuffer) return true; } - //! Create hardware buffer from meshbuffer -COpenGLDriver::SHWBufferLink *COpenGLDriver::createHardwareBuffer(const scene::IMeshBuffer* mb) +COpenGLDriver::SHWBufferLink *COpenGLDriver::createHardwareBuffer(const scene::IMeshBuffer *mb) { #if defined(GL_ARB_vertex_buffer_object) - if (!mb || (mb->getHardwareMappingHint_Index()==scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex()==scene::EHM_NEVER)) + if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) return 0; - SHWBufferLink_opengl *HWBuffer=new SHWBufferLink_opengl(mb); + SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); - //add to map + // add to map HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); - HWBuffer->ChangedID_Vertex=HWBuffer->MeshBuffer->getChangedID_Vertex(); - HWBuffer->ChangedID_Index=HWBuffer->MeshBuffer->getChangedID_Index(); - HWBuffer->Mapped_Vertex=mb->getHardwareMappingHint_Vertex(); - HWBuffer->Mapped_Index=mb->getHardwareMappingHint_Index(); - HWBuffer->vbo_verticesID=0; - HWBuffer->vbo_indicesID=0; - HWBuffer->vbo_verticesSize=0; - HWBuffer->vbo_indicesSize=0; + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); + HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); + HWBuffer->vbo_verticesID = 0; + HWBuffer->vbo_indicesID = 0; + HWBuffer->vbo_verticesSize = 0; + HWBuffer->vbo_indicesSize = 0; - if (!updateHardwareBuffer(HWBuffer)) - { + if (!updateHardwareBuffer(HWBuffer)) { deleteHardwareBuffer(HWBuffer); return 0; } @@ -521,71 +473,64 @@ COpenGLDriver::SHWBufferLink *COpenGLDriver::createHardwareBuffer(const scene::I #endif } - void COpenGLDriver::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) { if (!_HWBuffer) return; #if defined(GL_ARB_vertex_buffer_object) - SHWBufferLink_opengl *HWBuffer=(SHWBufferLink_opengl*)_HWBuffer; - if (HWBuffer->vbo_verticesID) - { + SHWBufferLink_opengl *HWBuffer = (SHWBufferLink_opengl *)_HWBuffer; + if (HWBuffer->vbo_verticesID) { extGlDeleteBuffers(1, &HWBuffer->vbo_verticesID); - HWBuffer->vbo_verticesID=0; + HWBuffer->vbo_verticesID = 0; } - if (HWBuffer->vbo_indicesID) - { + if (HWBuffer->vbo_indicesID) { extGlDeleteBuffers(1, &HWBuffer->vbo_indicesID); - HWBuffer->vbo_indicesID=0; + HWBuffer->vbo_indicesID = 0; } #endif CNullDriver::deleteHardwareBuffer(_HWBuffer); } - //! Draw hardware buffer void COpenGLDriver::drawHardwareBuffer(SHWBufferLink *_HWBuffer) { if (!_HWBuffer) return; - updateHardwareBuffer(_HWBuffer); //check if update is needed + updateHardwareBuffer(_HWBuffer); // check if update is needed #if defined(GL_ARB_vertex_buffer_object) - SHWBufferLink_opengl *HWBuffer=(SHWBufferLink_opengl*)_HWBuffer; + SHWBufferLink_opengl *HWBuffer = (SHWBufferLink_opengl *)_HWBuffer; - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void *vertices=mb->getVertices(); - const void *indexList=mb->getIndices(); + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const void *indexList = mb->getIndices(); - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) - { + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { extGlBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); - vertices=0; + vertices = 0; } - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) - { + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { extGlBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - indexList=0; + indexList = 0; } drawVertexPrimitiveList(vertices, mb->getVertexCount(), indexList, mb->getPrimitiveCount(), mb->getVertexType(), mb->getPrimitiveType(), mb->getIndexType()); - if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER) + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) extGlBindBuffer(GL_ARRAY_BUFFER, 0); - if (HWBuffer->Mapped_Index!=scene::EHM_NEVER) + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) extGlBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #endif } - //! Create occlusion query. /** Use node for identification and mesh for occlusion test. */ -void COpenGLDriver::addOcclusionQuery(scene::ISceneNode* node, - const scene::IMesh* mesh) +void COpenGLDriver::addOcclusionQuery(scene::ISceneNode *node, + const scene::IMesh *mesh) { if (!queryFeature(EVDF_OCCLUSION_QUERY)) return; @@ -593,91 +538,83 @@ void COpenGLDriver::addOcclusionQuery(scene::ISceneNode* node, CNullDriver::addOcclusionQuery(node, mesh); const s32 index = OcclusionQueries.linear_search(SOccQuery(node)); if ((index != -1) && (OcclusionQueries[index].UID == 0)) - extGlGenQueries(1, reinterpret_cast(&OcclusionQueries[index].UID)); + extGlGenQueries(1, reinterpret_cast(&OcclusionQueries[index].UID)); } - //! Remove occlusion query. -void COpenGLDriver::removeOcclusionQuery(scene::ISceneNode* node) +void COpenGLDriver::removeOcclusionQuery(scene::ISceneNode *node) { const s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index != -1) - { + if (index != -1) { if (OcclusionQueries[index].UID != 0) - extGlDeleteQueries(1, reinterpret_cast(&OcclusionQueries[index].UID)); + extGlDeleteQueries(1, reinterpret_cast(&OcclusionQueries[index].UID)); CNullDriver::removeOcclusionQuery(node); } } - //! Run occlusion query. Draws mesh stored in query. /** If the mesh shall not be rendered visible, use overrideMaterial to disable the color and depth buffer. */ -void COpenGLDriver::runOcclusionQuery(scene::ISceneNode* node, bool visible) +void COpenGLDriver::runOcclusionQuery(scene::ISceneNode *node, bool visible) { if (!node) return; const s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index != -1) - { + if (index != -1) { if (OcclusionQueries[index].UID) extGlBeginQuery( #ifdef GL_ARB_occlusion_query - GL_SAMPLES_PASSED_ARB, + GL_SAMPLES_PASSED_ARB, #else - 0, + 0, #endif - OcclusionQueries[index].UID); - CNullDriver::runOcclusionQuery(node,visible); + OcclusionQueries[index].UID); + CNullDriver::runOcclusionQuery(node, visible); if (OcclusionQueries[index].UID) extGlEndQuery( #ifdef GL_ARB_occlusion_query - GL_SAMPLES_PASSED_ARB); + GL_SAMPLES_PASSED_ARB); #else - 0); + 0); #endif testGLError(__LINE__); } } - //! Update occlusion query. Retrieves results from GPU. /** If the query shall not block, set the flag to false. Update might not occur in this case, though */ -void COpenGLDriver::updateOcclusionQuery(scene::ISceneNode* node, bool block) +void COpenGLDriver::updateOcclusionQuery(scene::ISceneNode *node, bool block) { const s32 index = OcclusionQueries.linear_search(SOccQuery(node)); - if (index != -1) - { + if (index != -1) { // not yet started - if (OcclusionQueries[index].Run==u32(~0)) + if (OcclusionQueries[index].Run == u32(~0)) return; - GLint available = block?GL_TRUE:GL_FALSE; - if (!block) - { + GLint available = block ? GL_TRUE : GL_FALSE; + if (!block) { extGlGetQueryObjectiv(OcclusionQueries[index].UID, #ifdef GL_ARB_occlusion_query - GL_QUERY_RESULT_AVAILABLE_ARB, + GL_QUERY_RESULT_AVAILABLE_ARB, #elif defined(GL_NV_occlusion_query) - GL_PIXEL_COUNT_AVAILABLE_NV, + GL_PIXEL_COUNT_AVAILABLE_NV, #else - 0, + 0, #endif - &available); + &available); testGLError(__LINE__); } - if (available==GL_TRUE) - { + if (available == GL_TRUE) { extGlGetQueryObjectiv(OcclusionQueries[index].UID, #ifdef GL_ARB_occlusion_query - GL_QUERY_RESULT_ARB, + GL_QUERY_RESULT_ARB, #elif defined(GL_NV_occlusion_query) - GL_PIXEL_COUNT_NV, + GL_PIXEL_COUNT_NV, #else - 0, + 0, #endif - &available); + &available); if (queryFeature(EVDF_OCCLUSION_QUERY)) OcclusionQueries[index].Result = available; } @@ -685,12 +622,11 @@ void COpenGLDriver::updateOcclusionQuery(scene::ISceneNode* node, bool block) } } - //! Return query result. /** Return value is the number of visible pixels/fragments. The value is a safe approximation, i.e. can be larger than the actual value of pixels. */ -u32 COpenGLDriver::getOcclusionQueryResult(scene::ISceneNode* node) const +u32 COpenGLDriver::getOcclusionQueryResult(scene::ISceneNode *node) const { const s32 index = OcclusionQueries.linear_search(SOccQuery(node)); if (index != -1) @@ -699,27 +635,24 @@ u32 COpenGLDriver::getOcclusionQueryResult(scene::ISceneNode* node) const return ~0; } - //! Create render target. -IRenderTarget* COpenGLDriver::addRenderTarget() +IRenderTarget *COpenGLDriver::addRenderTarget() { - COpenGLRenderTarget* renderTarget = new COpenGLRenderTarget(this); + COpenGLRenderTarget *renderTarget = new COpenGLRenderTarget(this); RenderTargets.push_back(renderTarget); return renderTarget; } - // small helper function to create vertex buffer object address offsets -static inline const GLvoid * buffer_offset(const size_t offset) +static inline const GLvoid *buffer_offset(const size_t offset) { return (const GLvoid *)offset; } - //! draws a vertex primitive list -void COpenGLDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, +void COpenGLDriver::drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { if (!primitiveCount || !vertexCount) @@ -736,141 +669,119 @@ void COpenGLDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCoun // draw everything setRenderStates3DMode(); - if ((pType!=scene::EPT_POINTS) && (pType!=scene::EPT_POINT_SPRITES)) + if ((pType != scene::EPT_POINTS) && (pType != scene::EPT_POINT_SPRITES)) CacheHandler->setClientState(true, true, true, true); else CacheHandler->setClientState(true, false, true, false); -//due to missing defines in OSX headers, we have to be more specific with this check -//#if defined(GL_ARB_vertex_array_bgra) || defined(GL_EXT_vertex_array_bgra) +// due to missing defines in OSX headers, we have to be more specific with this check +// #if defined(GL_ARB_vertex_array_bgra) || defined(GL_EXT_vertex_array_bgra) #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif - if (vertices) - { - if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - { - switch (vType) - { - case EVT_STANDARD: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(vertices))[0].Color); - break; - case EVT_2TCOORDS: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Color); - break; - case EVT_TANGENTS: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Color); - break; + if (vertices) { + if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) { + switch (vType) { + case EVT_STANDARD: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(vertices))[0].Color); + break; + case EVT_2TCOORDS: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Color); + break; + case EVT_TANGENTS: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Color); + break; } - } - else - { + } else { // avoid passing broken pointer to OpenGL - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } } - switch (vType) - { - case EVT_STANDARD: + switch (vType) { + case EVT_STANDARD: + if (vertices) { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex), buffer_offset(12)); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), 0); + } + + if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache()[1]) { + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex), buffer_offset(12)); - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), 0); - } + } + break; + case EVT_2TCOORDS: + if (vertices) { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(12)); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); + } - if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache()[1]) - { - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - } - break; - case EVT_2TCOORDS: + if (Feature.MaxTextureUnits > 0) { + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(12)); - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); + } + break; + case EVT_TANGENTS: + if (vertices) { + glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); + } else { + glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(12)); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); + } - - if (Feature.MaxTextureUnits > 0) - { - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); - } - break; - case EVT_TANGENTS: + if (Feature.MaxTextureUnits > 0) { + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Tangent); else - { - glNormalPointer(GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(12)); - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); - } + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(36)); - if (Feature.MaxTextureUnits > 0) - { - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Tangent); - else - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(36)); - - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 2); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Binormal); - else - glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(48)); - } - break; + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 2); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + if (vertices) + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Binormal); + else + glTexCoordPointer(3, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(48)); + } + break; } renderArray(indexList, primitiveCount, pType, iType); - if (Feature.MaxTextureUnits > 0) - { - if (vType==EVT_TANGENTS) - { + if (Feature.MaxTextureUnits > 0) { + if (vType == EVT_TANGENTS) { CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 2); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } - if ((vType!=EVT_STANDARD) || CacheHandler->getTextureCache()[1]) - { + if ((vType != EVT_STANDARD) || CacheHandler->getTextureCache()[1]) { CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } @@ -878,155 +789,134 @@ void COpenGLDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCoun } } - -void COpenGLDriver::getColorBuffer(const void* vertices, u32 vertexCount, E_VERTEX_TYPE vType) +void COpenGLDriver::getColorBuffer(const void *vertices, u32 vertexCount, E_VERTEX_TYPE vType) { // convert colors to gl color format. - vertexCount *= 4; //reused as color component count + vertexCount *= 4; // reused as color component count ColorBuffer.set_used(vertexCount); u32 i; - switch (vType) - { - case EVT_STANDARD: - { - const S3DVertex* p = static_cast(vertices); - for (i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + switch (vType) { + case EVT_STANDARD: { + const S3DVertex *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; - case EVT_2TCOORDS: - { - const S3DVertex2TCoords* p = static_cast(vertices); - for (i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + } break; + case EVT_2TCOORDS: { + const S3DVertex2TCoords *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; - case EVT_TANGENTS: - { - const S3DVertexTangents* p = static_cast(vertices); - for (i=0; iColor.toOpenGLColor(&ColorBuffer[i]); - ++p; - } + } break; + case EVT_TANGENTS: { + const S3DVertexTangents *p = static_cast(vertices); + for (i = 0; i < vertexCount; i += 4) { + p->Color.toOpenGLColor(&ColorBuffer[i]); + ++p; } - break; + } break; } } - -void COpenGLDriver::renderArray(const void* indexList, u32 primitiveCount, +void COpenGLDriver::renderArray(const void *indexList, u32 primitiveCount, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { - GLenum indexSize=0; + GLenum indexSize = 0; - switch (iType) - { - case EIT_16BIT: - { - indexSize=GL_UNSIGNED_SHORT; - break; - } - case EIT_32BIT: - { - indexSize=GL_UNSIGNED_INT; - break; - } + switch (iType) { + case EIT_16BIT: { + indexSize = GL_UNSIGNED_SHORT; + break; + } + case EIT_32BIT: { + indexSize = GL_UNSIGNED_INT; + break; + } } - switch (pType) - { - case scene::EPT_POINTS: - case scene::EPT_POINT_SPRITES: - { + switch (pType) { + case scene::EPT_POINTS: + case scene::EPT_POINT_SPRITES: { #ifdef GL_ARB_point_sprite - if (pType==scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) - glEnable(GL_POINT_SPRITE_ARB); + if (pType == scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) + glEnable(GL_POINT_SPRITE_ARB); #endif - // prepare size and attenuation (where supported) - GLfloat particleSize=Material.Thickness; -// if (AntiAlias) -// particleSize=core::clamp(particleSize, DimSmoothedPoint[0], DimSmoothedPoint[1]); -// else - particleSize=core::clamp(particleSize, DimAliasedPoint[0], DimAliasedPoint[1]); + // prepare size and attenuation (where supported) + GLfloat particleSize = Material.Thickness; + // if (AntiAlias) + // particleSize=core::clamp(particleSize, DimSmoothedPoint[0], DimSmoothedPoint[1]); + // else + particleSize = core::clamp(particleSize, DimAliasedPoint[0], DimAliasedPoint[1]); #if defined(GL_VERSION_1_4) || defined(GL_ARB_point_parameters) || defined(GL_EXT_point_parameters) || defined(GL_SGIS_point_parameters) - const float att[] = {1.0f, 1.0f, 0.0f}; + const float att[] = {1.0f, 1.0f, 0.0f}; #if defined(GL_VERSION_1_4) - extGlPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, att); -// extGlPointParameterf(GL_POINT_SIZE_MIN,1.f); - extGlPointParameterf(GL_POINT_SIZE_MAX, particleSize); - extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE, 1.0f); + extGlPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, att); + // extGlPointParameterf(GL_POINT_SIZE_MIN,1.f); + extGlPointParameterf(GL_POINT_SIZE_MAX, particleSize); + extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE, 1.0f); #elif defined(GL_ARB_point_parameters) - extGlPointParameterfv(GL_POINT_DISTANCE_ATTENUATION_ARB, att); -// extGlPointParameterf(GL_POINT_SIZE_MIN_ARB,1.f); - extGlPointParameterf(GL_POINT_SIZE_MAX_ARB, particleSize); - extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_ARB, 1.0f); + extGlPointParameterfv(GL_POINT_DISTANCE_ATTENUATION_ARB, att); + // extGlPointParameterf(GL_POINT_SIZE_MIN_ARB,1.f); + extGlPointParameterf(GL_POINT_SIZE_MAX_ARB, particleSize); + extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_ARB, 1.0f); #elif defined(GL_EXT_point_parameters) - extGlPointParameterfv(GL_DISTANCE_ATTENUATION_EXT, att); -// extGlPointParameterf(GL_POINT_SIZE_MIN_EXT,1.f); - extGlPointParameterf(GL_POINT_SIZE_MAX_EXT, particleSize); - extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_EXT, 1.0f); + extGlPointParameterfv(GL_DISTANCE_ATTENUATION_EXT, att); + // extGlPointParameterf(GL_POINT_SIZE_MIN_EXT,1.f); + extGlPointParameterf(GL_POINT_SIZE_MAX_EXT, particleSize); + extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_EXT, 1.0f); #elif defined(GL_SGIS_point_parameters) - extGlPointParameterfv(GL_DISTANCE_ATTENUATION_SGIS, att); -// extGlPointParameterf(GL_POINT_SIZE_MIN_SGIS,1.f); - extGlPointParameterf(GL_POINT_SIZE_MAX_SGIS, particleSize); - extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_SGIS, 1.0f); + extGlPointParameterfv(GL_DISTANCE_ATTENUATION_SGIS, att); + // extGlPointParameterf(GL_POINT_SIZE_MIN_SGIS,1.f); + extGlPointParameterf(GL_POINT_SIZE_MAX_SGIS, particleSize); + extGlPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_SGIS, 1.0f); #endif #endif - glPointSize(particleSize); + glPointSize(particleSize); #ifdef GL_ARB_point_sprite - if (pType == scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) - { - CacheHandler->setActiveTexture(GL_TEXTURE0_ARB); - glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE, GL_TRUE); - } -#endif - glDrawArrays(GL_POINTS, 0, primitiveCount); -#ifdef GL_ARB_point_sprite - if (pType==scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) - { - glDisable(GL_POINT_SPRITE_ARB); - - CacheHandler->setActiveTexture(GL_TEXTURE0_ARB); - glTexEnvf(GL_POINT_SPRITE_ARB,GL_COORD_REPLACE, GL_FALSE); - } -#endif + if (pType == scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) { + CacheHandler->setActiveTexture(GL_TEXTURE0_ARB); + glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE, GL_TRUE); } - break; - case scene::EPT_LINE_STRIP: - glDrawElements(GL_LINE_STRIP, primitiveCount+1, indexSize, indexList); - break; - case scene::EPT_LINE_LOOP: - glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); - break; - case scene::EPT_LINES: - glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_STRIP: - glDrawElements(GL_TRIANGLE_STRIP, primitiveCount+2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_FAN: - glDrawElements(GL_TRIANGLE_FAN, primitiveCount+2, indexSize, indexList); - break; - case scene::EPT_TRIANGLES: - glDrawElements(GL_TRIANGLES, primitiveCount*3, indexSize, indexList); - break; +#endif + glDrawArrays(GL_POINTS, 0, primitiveCount); +#ifdef GL_ARB_point_sprite + if (pType == scene::EPT_POINT_SPRITES && FeatureAvailable[IRR_ARB_point_sprite]) { + glDisable(GL_POINT_SPRITE_ARB); + + CacheHandler->setActiveTexture(GL_TEXTURE0_ARB); + glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE, GL_FALSE); + } +#endif + } break; + case scene::EPT_LINE_STRIP: + glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList); + break; + case scene::EPT_LINE_LOOP: + glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); + break; + case scene::EPT_LINES: + glDrawElements(GL_LINES, primitiveCount * 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_STRIP: + glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_FAN: + glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLES: + glDrawElements(GL_TRIANGLES, primitiveCount * 3, indexSize, indexList); + break; } } - //! draws a vertex primitive list in 2d -void COpenGLDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, +void COpenGLDriver::draw2DVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { if (!primitiveCount || !vertexCount) @@ -1042,125 +932,104 @@ void COpenGLDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCo // draw everything CacheHandler->getTextureCache().set(0, Material.getTexture(0)); - if (Material.MaterialType==EMT_ONETEXTURE_BLEND) - { + if (Material.MaterialType == EMT_ONETEXTURE_BLEND) { E_BLEND_FACTOR srcFact; E_BLEND_FACTOR dstFact; E_MODULATE_FUNC modulo; u32 alphaSource; - unpack_textureBlendFunc ( srcFact, dstFact, modulo, alphaSource, Material.MaterialTypeParam); - setRenderStates2DMode(alphaSource&video::EAS_VERTEX_COLOR, (Material.getTexture(0) != 0), (alphaSource&video::EAS_TEXTURE) != 0); - } - else - setRenderStates2DMode(Material.MaterialType==EMT_TRANSPARENT_VERTEX_ALPHA, (Material.getTexture(0) != 0), Material.MaterialType==EMT_TRANSPARENT_ALPHA_CHANNEL); + unpack_textureBlendFunc(srcFact, dstFact, modulo, alphaSource, Material.MaterialTypeParam); + setRenderStates2DMode(alphaSource & video::EAS_VERTEX_COLOR, (Material.getTexture(0) != 0), (alphaSource & video::EAS_TEXTURE) != 0); + } else + setRenderStates2DMode(Material.MaterialType == EMT_TRANSPARENT_VERTEX_ALPHA, (Material.getTexture(0) != 0), Material.MaterialType == EMT_TRANSPARENT_ALPHA_CHANNEL); - if ((pType!=scene::EPT_POINTS) && (pType!=scene::EPT_POINT_SPRITES)) + if ((pType != scene::EPT_POINTS) && (pType != scene::EPT_POINT_SPRITES)) CacheHandler->setClientState(true, false, true, true); else CacheHandler->setClientState(true, false, true, false); -//due to missing defines in OSX headers, we have to be more specific with this check -//#if defined(GL_ARB_vertex_array_bgra) || defined(GL_EXT_vertex_array_bgra) +// due to missing defines in OSX headers, we have to be more specific with this check +// #if defined(GL_ARB_vertex_array_bgra) || defined(GL_EXT_vertex_array_bgra) #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif - if (vertices) - { - if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - { - switch (vType) - { - case EVT_STANDARD: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(vertices))[0].Color); - break; - case EVT_2TCOORDS: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Color); - break; - case EVT_TANGENTS: - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Color); - break; + if (vertices) { + if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) { + switch (vType) { + case EVT_STANDARD: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(vertices))[0].Color); + break; + case EVT_2TCOORDS: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Color); + break; + case EVT_TANGENTS: + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Color); + break; } - } - else - { + } else { // avoid passing broken pointer to OpenGL - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } } - switch (vType) - { - case EVT_STANDARD: + switch (vType) { + case EVT_STANDARD: + if (vertices) { + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); + } else { + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), 0); + } + + if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache()[1]) { + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); else - { - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), buffer_offset(24)); glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), 0); - } + } + break; + case EVT_2TCOORDS: + if (vertices) { + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); + } else { + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); + } - if (Feature.MaxTextureUnits > 0 && CacheHandler->getTextureCache()[1]) - { - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(vertices))[0].TCoords); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), buffer_offset(28)); - } - break; - case EVT_2TCOORDS: + if (Feature.MaxTextureUnits > 0) { + CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vertices) - { - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].Pos); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); else - { - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex2TCoords), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(28)); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(0)); - } + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); + } + break; + case EVT_TANGENTS: + if (vertices) { + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); + } else { + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); + } - if (Feature.MaxTextureUnits > 0) - { - CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - if (vertices) - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), &(static_cast(vertices))[0].TCoords2); - else - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex2TCoords), buffer_offset(36)); - } - break; - case EVT_TANGENTS: - if (vertices) - { - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), &(static_cast(vertices))[0].Pos); - } - else - { - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertexTangents), buffer_offset(24)); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(28)); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertexTangents), buffer_offset(0)); - } - - break; + break; } renderArray(indexList, primitiveCount, pType, iType); - if (Feature.MaxTextureUnits > 0) - { - if ((vType!=EVT_STANDARD) || CacheHandler->getTextureCache()[1]) - { + if (Feature.MaxTextureUnits > 0) { + if ((vType != EVT_STANDARD) || CacheHandler->getTextureCache()[1]) { CacheHandler->setClientActiveTexture(GL_TEXTURE0 + 1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } @@ -1168,10 +1037,9 @@ void COpenGLDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCo } } - -void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect, SColor color, - bool useAlphaChannelOfTexture) +void COpenGLDriver::draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect, SColor color, + bool useAlphaChannelOfTexture) { if (!texture) return; @@ -1181,36 +1049,35 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::posi // clip these coordinates core::rect targetRect(destPos, sourceRect.getSize()); - if (clipRect) - { + if (clipRect) { targetRect.clipAgainst(*clipRect); - if ( targetRect.getWidth() < 0 || targetRect.getHeight() < 0 ) + if (targetRect.getWidth() < 0 || targetRect.getHeight() < 0) return; } - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - targetRect.clipAgainst( core::rect(0,0, (s32)renderTargetSize.Width, (s32)renderTargetSize.Height) ); - if ( targetRect.getWidth() < 0 || targetRect.getHeight() < 0 ) - return; + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); + targetRect.clipAgainst(core::rect(0, 0, (s32)renderTargetSize.Width, (s32)renderTargetSize.Height)); + if (targetRect.getWidth() < 0 || targetRect.getHeight() < 0) + return; // ok, we've clipped everything. // now draw it. const core::dimension2d sourceSize(targetRect.getSize()); - const core::position2d sourcePos(sourceRect.UpperLeftCorner + (targetRect.UpperLeftCorner-destPos)); + const core::position2d sourcePos(sourceRect.UpperLeftCorner + (targetRect.UpperLeftCorner - destPos)); - const core::dimension2d& ss = texture->getOriginalSize(); + const core::dimension2d &ss = texture->getOriginalSize(); const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); const core::rect tcoords( - sourcePos.X * invW, - sourcePos.Y * invH, - (sourcePos.X + sourceSize.Width) * invW, - (sourcePos.Y + sourceSize.Height) * invH); + sourcePos.X * invW, + sourcePos.Y * invH, + (sourcePos.X + sourceSize.Width) * invW, + (sourcePos.Y + sourceSize.Height) * invH); disableTextures(1); if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(color.getAlpha()<255, true, useAlphaChannelOfTexture); + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); Quad2DVertices[0].Color = color; Quad2DVertices[1].Color = color; @@ -1232,8 +1099,8 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::posi CacheHandler->setClientState(true, false, true, true); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; @@ -1241,9 +1108,8 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::posi const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } @@ -1251,49 +1117,46 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::posi glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_SHORT, Quad2DIndices); } - -void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect, - const video::SColor* const colors, bool useAlphaChannelOfTexture) +void COpenGLDriver::draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect, + const video::SColor *const colors, bool useAlphaChannelOfTexture) { if (!texture) return; - const core::dimension2d& ss = texture->getOriginalSize(); + const core::dimension2d &ss = texture->getOriginalSize(); const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); const core::rect tcoords( - sourceRect.UpperLeftCorner.X * invW, - sourceRect.UpperLeftCorner.Y * invH, - sourceRect.LowerRightCorner.X * invW, - sourceRect.LowerRightCorner.Y *invH); + sourceRect.UpperLeftCorner.X * invW, + sourceRect.UpperLeftCorner.Y * invH, + sourceRect.LowerRightCorner.X * invW, + sourceRect.LowerRightCorner.Y * invH); const video::SColor temp[4] = - { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF - }; + { + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF}; - const video::SColor* const useColor = colors ? colors : temp; + const video::SColor *const useColor = colors ? colors : temp; disableTextures(1); if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(useColor[0].getAlpha()<255 || useColor[1].getAlpha()<255 || - useColor[2].getAlpha()<255 || useColor[3].getAlpha()<255, - true, useAlphaChannelOfTexture); + setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || + useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, + true, useAlphaChannelOfTexture); - if (clipRect) - { + if (clipRect) { if (!clipRect->isValid()) return; glEnable(GL_SCISSOR_TEST); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, - clipRect->getWidth(), clipRect->getHeight()); + clipRect->getWidth(), clipRect->getHeight()); } Quad2DVertices[0].Color = useColor[0]; @@ -1316,8 +1179,8 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::rect CacheHandler->setClientState(true, false, true, true); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; @@ -1325,9 +1188,8 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::rect const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } @@ -1338,8 +1200,7 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, const core::rect glDisable(GL_SCISSOR_TEST); } - -void COpenGLDriver::draw2DImage(const video::ITexture* texture, u32 layer, bool flip) +void COpenGLDriver::draw2DImage(const video::ITexture *texture, u32 layer, bool flip) { if (!texture || !CacheHandler->getTextureCache().set(0, texture)) return; @@ -1358,86 +1219,73 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, u32 layer, bool CacheHandler->setClientState(true, false, false, true); const core::vector3df positionData[4] = { - core::vector3df(-1.f, 1.f, 0.f), - core::vector3df(1.f, 1.f, 0.f), - core::vector3df(1.f, -1.f, 0.f), - core::vector3df(-1.f, -1.f, 0.f) - }; + core::vector3df(-1.f, 1.f, 0.f), + core::vector3df(1.f, 1.f, 0.f), + core::vector3df(1.f, -1.f, 0.f), + core::vector3df(-1.f, -1.f, 0.f)}; glVertexPointer(2, GL_FLOAT, sizeof(core::vector3df), positionData); - if (texture && texture->getType() == ETT_CUBEMAP) - { + if (texture && texture->getType() == ETT_CUBEMAP) { const core::vector3df texcoordCubeData[6][4] = { - // GL_TEXTURE_CUBE_MAP_POSITIVE_X - { - core::vector3df(1.f, 1.f, 1.f), - core::vector3df(1.f, 1.f, -1.f), - core::vector3df(1.f, -1.f, -1.f), - core::vector3df(1.f, -1.f, 1.f) - }, + // GL_TEXTURE_CUBE_MAP_POSITIVE_X + { + core::vector3df(1.f, 1.f, 1.f), + core::vector3df(1.f, 1.f, -1.f), + core::vector3df(1.f, -1.f, -1.f), + core::vector3df(1.f, -1.f, 1.f)}, - // GL_TEXTURE_CUBE_MAP_NEGATIVE_X - { - core::vector3df(-1.f, 1.f, -1.f), - core::vector3df(-1.f, 1.f, 1.f), - core::vector3df(-1.f, -1.f, 1.f), - core::vector3df(-1.f, -1.f, -1.f) - }, + // GL_TEXTURE_CUBE_MAP_NEGATIVE_X + { + core::vector3df(-1.f, 1.f, -1.f), + core::vector3df(-1.f, 1.f, 1.f), + core::vector3df(-1.f, -1.f, 1.f), + core::vector3df(-1.f, -1.f, -1.f)}, - // GL_TEXTURE_CUBE_MAP_POSITIVE_Y - { - core::vector3df(-1.f, 1.f, -1.f), - core::vector3df(1.f, 1.f, -1.f), - core::vector3df(1.f, 1.f, 1.f), - core::vector3df(-1.f, 1.f, 1.f) - }, + // GL_TEXTURE_CUBE_MAP_POSITIVE_Y + { + core::vector3df(-1.f, 1.f, -1.f), + core::vector3df(1.f, 1.f, -1.f), + core::vector3df(1.f, 1.f, 1.f), + core::vector3df(-1.f, 1.f, 1.f)}, - // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y - { - core::vector3df(-1.f, -1.f, 1.f), - core::vector3df(-1.f, -1.f, -1.f), - core::vector3df(1.f, -1.f, -1.f), - core::vector3df(1.f, -1.f, 1.f) - }, + // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y + { + core::vector3df(-1.f, -1.f, 1.f), + core::vector3df(-1.f, -1.f, -1.f), + core::vector3df(1.f, -1.f, -1.f), + core::vector3df(1.f, -1.f, 1.f)}, - // GL_TEXTURE_CUBE_MAP_POSITIVE_Z - { - core::vector3df(-1.f, 1.f, 1.f), - core::vector3df(-1.f, -1.f, 1.f), - core::vector3df(1.f, -1.f, 1.f), - core::vector3df(1.f, 1.f, 1.f) - }, + // GL_TEXTURE_CUBE_MAP_POSITIVE_Z + { + core::vector3df(-1.f, 1.f, 1.f), + core::vector3df(-1.f, -1.f, 1.f), + core::vector3df(1.f, -1.f, 1.f), + core::vector3df(1.f, 1.f, 1.f)}, - // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z - { - core::vector3df(1.f, 1.f, -1.f), - core::vector3df(-1.f, 1.f, -1.f), - core::vector3df(-1.f, -1.f, -1.f), - core::vector3df(1.f, -1.f, -1.f) - } - }; + // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z + { + core::vector3df(1.f, 1.f, -1.f), + core::vector3df(-1.f, 1.f, -1.f), + core::vector3df(-1.f, -1.f, -1.f), + core::vector3df(1.f, -1.f, -1.f)}}; const core::vector3df texcoordData[4] = { - texcoordCubeData[layer][(flip) ? 3 : 0], - texcoordCubeData[layer][(flip) ? 2 : 1], - texcoordCubeData[layer][(flip) ? 1 : 2], - texcoordCubeData[layer][(flip) ? 0 : 3] - }; + texcoordCubeData[layer][(flip) ? 3 : 0], + texcoordCubeData[layer][(flip) ? 2 : 1], + texcoordCubeData[layer][(flip) ? 1 : 2], + texcoordCubeData[layer][(flip) ? 0 : 3]}; glTexCoordPointer(3, GL_FLOAT, sizeof(core::vector3df), texcoordData); - } - else - { + } else { f32 modificator = (flip) ? 1.f : 0.f; core::vector2df texcoordData[4] = { - core::vector2df(0.f, 0.f + modificator), - core::vector2df(1.f, 0.f + modificator), - core::vector2df(1.f, 1.f - modificator), - core::vector2df(0.f, 1.f - modificator) - }; + core::vector2df(0.f, 0.f + modificator), + core::vector2df(1.f, 0.f + modificator), + core::vector2df(1.f, 1.f - modificator), + core::vector2df(0.f, 1.f - modificator)}; glTexCoordPointer(2, GL_FLOAT, sizeof(core::vector2df), texcoordData); } @@ -1445,30 +1293,29 @@ void COpenGLDriver::draw2DImage(const video::ITexture* texture, u32 layer, bool glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_SHORT, Quad2DIndices); } - //! draws a set of 2d images, using a color and the alpha channel of the //! texture if desired. -void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) +void COpenGLDriver::draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, + bool useAlphaChannelOfTexture) { if (!texture) return; const u32 drawCount = core::min_(positions.size(), sourceRects.size()); - const core::dimension2d& ss = texture->getOriginalSize(); + const core::dimension2d &ss = texture->getOriginalSize(); const f32 invW = 1.f / static_cast(ss.Width); const f32 invH = 1.f / static_cast(ss.Height); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); disableTextures(1); if (!CacheHandler->getTextureCache().set(0, texture)) return; - setRenderStates2DMode(color.getAlpha()<255, true, useAlphaChannelOfTexture); + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); Quad2DVertices[0].Color = color; Quad2DVertices[1].Color = color; @@ -1480,24 +1327,22 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, CacheHandler->setClientState(true, false, true, true); - glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glTexCoordPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].TCoords); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } - for (u32 i=0; i sourcePos(sourceRects[i].UpperLeftCorner); // This needs to be signed as it may go negative. core::dimension2d sourceSize(sourceRects[i].getSize()); - if (clipRect) - { - if (targetPos.X < clipRect->UpperLeftCorner.X) - { + if (clipRect) { + if (targetPos.X < clipRect->UpperLeftCorner.X) { sourceSize.Width += targetPos.X - clipRect->UpperLeftCorner.X; if (sourceSize.Width <= 0) continue; @@ -1517,15 +1360,13 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, targetPos.X = clipRect->UpperLeftCorner.X; } - if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) - { + if (targetPos.X + sourceSize.Width > clipRect->LowerRightCorner.X) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - clipRect->LowerRightCorner.X; if (sourceSize.Width <= 0) continue; } - if (targetPos.Y < clipRect->UpperLeftCorner.Y) - { + if (targetPos.Y < clipRect->UpperLeftCorner.Y) { sourceSize.Height += targetPos.Y - clipRect->UpperLeftCorner.Y; if (sourceSize.Height <= 0) continue; @@ -1534,8 +1375,7 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, targetPos.Y = clipRect->UpperLeftCorner.Y; } - if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) - { + if (targetPos.Y + sourceSize.Height > clipRect->LowerRightCorner.Y) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - clipRect->LowerRightCorner.Y; if (sourceSize.Height <= 0) continue; @@ -1544,8 +1384,7 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, // clip these coordinates - if (targetPos.X<0) - { + if (targetPos.X < 0) { sourceSize.Width += targetPos.X; if (sourceSize.Width <= 0) continue; @@ -1554,15 +1393,13 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, targetPos.X = 0; } - if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) - { + if (targetPos.X + sourceSize.Width > (s32)renderTargetSize.Width) { sourceSize.Width -= (targetPos.X + sourceSize.Width) - renderTargetSize.Width; if (sourceSize.Width <= 0) continue; } - if (targetPos.Y<0) - { + if (targetPos.Y < 0) { sourceSize.Height += targetPos.Y; if (sourceSize.Height <= 0) continue; @@ -1571,8 +1408,7 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, targetPos.Y = 0; } - if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) - { + if (targetPos.Y + sourceSize.Height > (s32)renderTargetSize.Height) { sourceSize.Height -= (targetPos.Y + sourceSize.Height) - renderTargetSize.Height; if (sourceSize.Height <= 0) continue; @@ -1603,10 +1439,9 @@ void COpenGLDriver::draw2DImageBatch(const video::ITexture* texture, } } - //! draw a 2d rectangle -void COpenGLDriver::draw2DRectangle(SColor color, const core::rect& position, - const core::rect* clip) +void COpenGLDriver::draw2DRectangle(SColor color, const core::rect &position, + const core::rect *clip) { disableTextures(); setRenderStates2DMode(color.getAlpha() < 255, false, false); @@ -1621,14 +1456,13 @@ void COpenGLDriver::draw2DRectangle(SColor color, const core::rect& positio glColor4ub(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); glRectf(GLfloat(pos.UpperLeftCorner.X), GLfloat(pos.UpperLeftCorner.Y), - GLfloat(pos.LowerRightCorner.X), GLfloat(pos.LowerRightCorner.Y)); + GLfloat(pos.LowerRightCorner.X), GLfloat(pos.LowerRightCorner.Y)); } - //! draw an 2d rectangle -void COpenGLDriver::draw2DRectangle(const core::rect& position, - SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip) +void COpenGLDriver::draw2DRectangle(const core::rect &position, + SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip) { core::rect pos = position; @@ -1641,9 +1475,10 @@ void COpenGLDriver::draw2DRectangle(const core::rect& position, disableTextures(); setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || - colorRightUp.getAlpha() < 255 || - colorLeftDown.getAlpha() < 255 || - colorRightDown.getAlpha() < 255, false, false); + colorRightUp.getAlpha() < 255 || + colorLeftDown.getAlpha() < 255 || + colorRightDown.getAlpha() < 255, + false, false); Quad2DVertices[0].Color = colorLeftUp; Quad2DVertices[1].Color = colorRightUp; @@ -1660,28 +1495,26 @@ void COpenGLDriver::draw2DRectangle(const core::rect& position, CacheHandler->setClientState(true, false, true, false); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_SHORT, Quad2DIndices); } - //! Draws a 2d line. -void COpenGLDriver::draw2DLine(const core::position2d& start, - const core::position2d& end, SColor color) +void COpenGLDriver::draw2DLine(const core::position2d &start, + const core::position2d &end, SColor color) { { disableTextures(); @@ -1698,18 +1531,17 @@ void COpenGLDriver::draw2DLine(const core::position2d& start, CacheHandler->setClientState(true, false, true, false); - glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glVertexPointer(2, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } @@ -1722,29 +1554,25 @@ void COpenGLDriver::draw2DLine(const core::position2d& start, } } - //! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled. //! Returns whether disabling was successful or not. bool COpenGLDriver::disableTextures(u32 fromStage) { - bool result=true; - for (u32 i=fromStage; igetTextureCache().set(i, 0, EST_ACTIVE_ON_CHANGE); } return result; } - //! creates a matrix in supplied GLfloat array to pass to OpenGL -inline void COpenGLDriver::getGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m) +inline void COpenGLDriver::getGLMatrix(GLfloat gl_matrix[16], const core::matrix4 &m) { memcpy(gl_matrix, m.pointer(), 16 * sizeof(f32)); } - //! creates a opengltexturematrix from a D3D style texture matrix -inline void COpenGLDriver::getGLTextureMatrix(GLfloat *o, const core::matrix4& m) +inline void COpenGLDriver::getGLTextureMatrix(GLfloat *o, const core::matrix4 &m) { o[0] = m[0]; o[1] = m[1]; @@ -1767,19 +1595,19 @@ inline void COpenGLDriver::getGLTextureMatrix(GLfloat *o, const core::matrix4& m o[15] = 1.f; } -ITexture* COpenGLDriver::createDeviceDependentTexture(const io::path& name, IImage* image) +ITexture *COpenGLDriver::createDeviceDependentTexture(const io::path &name, IImage *image) { - core::array imageArray(1); + core::array imageArray(1); imageArray.push_back(image); - COpenGLTexture* texture = new COpenGLTexture(name, imageArray, ETT_2D, this); + COpenGLTexture *texture = new COpenGLTexture(name, imageArray, ETT_2D, this); return texture; } -ITexture* COpenGLDriver::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) +ITexture *COpenGLDriver::createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) { - COpenGLTexture* texture = new COpenGLTexture(name, image, ETT_CUBEMAP, this); + COpenGLTexture *texture = new COpenGLTexture(name, image, ETT_CUBEMAP, this); return texture; } @@ -1788,9 +1616,8 @@ void COpenGLDriver::disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag) { CNullDriver::disableFeature(feature, flag); - if ( feature == EVDF_TEXTURE_CUBEMAP_SEAMLESS ) - { - if ( queryFeature(feature) ) + if (feature == EVDF_TEXTURE_CUBEMAP_SEAMLESS) { + if (queryFeature(feature)) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); else if (COpenGLExtensionHandler::queryFeature(feature)) glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); @@ -1798,64 +1625,66 @@ void COpenGLDriver::disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag) } //! Sets a material. All 3d drawing functions draw geometry now using this material. -void COpenGLDriver::setMaterial(const SMaterial& material) +void COpenGLDriver::setMaterial(const SMaterial &material) { Material = material; OverrideMaterial.apply(Material); - for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) - { - const ITexture* texture = Material.getTexture(i); + for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) { + const ITexture *texture = Material.getTexture(i); CacheHandler->getTextureCache().set(i, texture, EST_ACTIVE_ON_CHANGE); - if ( texture ) - { + if (texture) { setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); } } } - //! prints error if an error happened. bool COpenGLDriver::testGLError(int code) { #ifdef _DEBUG GLenum g = glGetError(); - switch (g) - { + switch (g) { case GL_NO_ERROR: return false; case GL_INVALID_ENUM: - os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_INVALID_VALUE: - os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_INVALID_OPERATION: - os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_STACK_OVERFLOW: - os::Printer::log("GL_STACK_OVERFLOW", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_STACK_OVERFLOW", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_STACK_UNDERFLOW: - os::Printer::log("GL_STACK_UNDERFLOW", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_STACK_UNDERFLOW", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_OUT_OF_MEMORY: - os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); + break; case GL_TABLE_TOO_LARGE: - os::Printer::log("GL_TABLE_TOO_LARGE", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_TABLE_TOO_LARGE", core::stringc(code).c_str(), ELL_ERROR); + break; #if defined(GL_EXT_framebuffer_object) case GL_INVALID_FRAMEBUFFER_OPERATION_EXT: - os::Printer::log("GL_INVALID_FRAMEBUFFER_OPERATION", core::stringc(code).c_str(), ELL_ERROR); break; + os::Printer::log("GL_INVALID_FRAMEBUFFER_OPERATION", core::stringc(code).c_str(), ELL_ERROR); + break; #endif }; -// _IRR_DEBUG_BREAK_IF(true); + // _IRR_DEBUG_BREAK_IF(true); return true; #else return false; #endif } - //! sets the needed renderstates void COpenGLDriver::setRenderStates3DMode() { - if (CurrentRenderMode != ERM_3D) - { + if (CurrentRenderMode != ERM_3D) { // Reset Texture Stages CacheHandler->setBlend(false); CacheHandler->setAlphaTest(false); @@ -1877,8 +1706,7 @@ void COpenGLDriver::setRenderStates3DMode() #endif } - if (ResetRenderStates || LastMaterial != Material) - { + if (ResetRenderStates || LastMaterial != Material) { // unset old material if (LastMaterial.MaterialType != Material.MaterialType && @@ -1888,7 +1716,7 @@ void COpenGLDriver::setRenderStates3DMode() // set new material. if (static_cast(Material.MaterialType) < MaterialRenderers.size()) MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( - Material, LastMaterial, ResetRenderStates, this); + Material, LastMaterial, ResetRenderStates, this); LastMaterial = Material; CacheHandler->correctCacheMaterial(LastMaterial); @@ -1901,125 +1729,119 @@ void COpenGLDriver::setRenderStates3DMode() CurrentRenderMode = ERM_3D; } - //! Get native wrap mode value GLint COpenGLDriver::getTextureWrapMode(const u8 clamp) { - GLint mode=GL_REPEAT; - switch (clamp) - { - case ETC_REPEAT: - mode=GL_REPEAT; - break; - case ETC_CLAMP: - mode=GL_CLAMP; - break; - case ETC_CLAMP_TO_EDGE: + GLint mode = GL_REPEAT; + switch (clamp) { + case ETC_REPEAT: + mode = GL_REPEAT; + break; + case ETC_CLAMP: + mode = GL_CLAMP; + break; + case ETC_CLAMP_TO_EDGE: #ifdef GL_VERSION_1_2 - if (Version>101) - mode=GL_CLAMP_TO_EDGE; - else + if (Version > 101) + mode = GL_CLAMP_TO_EDGE; + else #endif #ifdef GL_SGIS_texture_edge_clamp - if (FeatureAvailable[IRR_SGIS_texture_edge_clamp]) - mode=GL_CLAMP_TO_EDGE_SGIS; - else + if (FeatureAvailable[IRR_SGIS_texture_edge_clamp]) + mode = GL_CLAMP_TO_EDGE_SGIS; + else #endif - // fallback - mode=GL_CLAMP; - break; - case ETC_CLAMP_TO_BORDER: + // fallback + mode = GL_CLAMP; + break; + case ETC_CLAMP_TO_BORDER: #ifdef GL_VERSION_1_3 - if (Version>102) - mode=GL_CLAMP_TO_BORDER; - else + if (Version > 102) + mode = GL_CLAMP_TO_BORDER; + else #endif #ifdef GL_ARB_texture_border_clamp - if (FeatureAvailable[IRR_ARB_texture_border_clamp]) - mode=GL_CLAMP_TO_BORDER_ARB; - else + if (FeatureAvailable[IRR_ARB_texture_border_clamp]) + mode = GL_CLAMP_TO_BORDER_ARB; + else #endif #ifdef GL_SGIS_texture_border_clamp - if (FeatureAvailable[IRR_SGIS_texture_border_clamp]) - mode=GL_CLAMP_TO_BORDER_SGIS; - else + if (FeatureAvailable[IRR_SGIS_texture_border_clamp]) + mode = GL_CLAMP_TO_BORDER_SGIS; + else #endif - // fallback - mode=GL_CLAMP; - break; - case ETC_MIRROR: + // fallback + mode = GL_CLAMP; + break; + case ETC_MIRROR: #ifdef GL_VERSION_1_4 - if (Version>103) - mode=GL_MIRRORED_REPEAT; - else + if (Version > 103) + mode = GL_MIRRORED_REPEAT; + else #endif #ifdef GL_ARB_texture_border_clamp - if (FeatureAvailable[IRR_ARB_texture_mirrored_repeat]) - mode=GL_MIRRORED_REPEAT_ARB; - else + if (FeatureAvailable[IRR_ARB_texture_mirrored_repeat]) + mode = GL_MIRRORED_REPEAT_ARB; + else #endif #ifdef GL_IBM_texture_mirrored_repeat - if (FeatureAvailable[IRR_IBM_texture_mirrored_repeat]) - mode=GL_MIRRORED_REPEAT_IBM; - else + if (FeatureAvailable[IRR_IBM_texture_mirrored_repeat]) + mode = GL_MIRRORED_REPEAT_IBM; + else #endif - mode=GL_REPEAT; - break; - case ETC_MIRROR_CLAMP: + mode = GL_REPEAT; + break; + case ETC_MIRROR_CLAMP: #ifdef GL_EXT_texture_mirror_clamp - if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) - mode=GL_MIRROR_CLAMP_EXT; - else + if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) + mode = GL_MIRROR_CLAMP_EXT; + else #endif #if defined(GL_ATI_texture_mirror_once) - if (FeatureAvailable[IRR_ATI_texture_mirror_once]) - mode=GL_MIRROR_CLAMP_ATI; - else + if (FeatureAvailable[IRR_ATI_texture_mirror_once]) + mode = GL_MIRROR_CLAMP_ATI; + else #endif - mode=GL_CLAMP; - break; - case ETC_MIRROR_CLAMP_TO_EDGE: + mode = GL_CLAMP; + break; + case ETC_MIRROR_CLAMP_TO_EDGE: #ifdef GL_EXT_texture_mirror_clamp - if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) - mode=GL_MIRROR_CLAMP_TO_EDGE_EXT; - else + if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) + mode = GL_MIRROR_CLAMP_TO_EDGE_EXT; + else #endif #if defined(GL_ATI_texture_mirror_once) - if (FeatureAvailable[IRR_ATI_texture_mirror_once]) - mode=GL_MIRROR_CLAMP_TO_EDGE_ATI; - else + if (FeatureAvailable[IRR_ATI_texture_mirror_once]) + mode = GL_MIRROR_CLAMP_TO_EDGE_ATI; + else #endif - mode=GL_CLAMP; - break; - case ETC_MIRROR_CLAMP_TO_BORDER: + mode = GL_CLAMP; + break; + case ETC_MIRROR_CLAMP_TO_BORDER: #ifdef GL_EXT_texture_mirror_clamp - if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) - mode=GL_MIRROR_CLAMP_TO_BORDER_EXT; - else + if (FeatureAvailable[IRR_EXT_texture_mirror_clamp]) + mode = GL_MIRROR_CLAMP_TO_BORDER_EXT; + else #endif - mode=GL_CLAMP; - break; + mode = GL_CLAMP; + break; } return mode; } - //! Can be called by an IMaterialRenderer to make its work easier. -void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, - bool resetAllRenderStates) +void COpenGLDriver::setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, + bool resetAllRenderStates) { // Fixed pipeline isn't important for shader based materials E_OPENGL_FIXED_PIPELINE_STATE tempState = FixedPipelineState; - if (resetAllRenderStates || tempState == EOFPS_ENABLE || tempState == EOFPS_DISABLE_TO_ENABLE) - { + if (resetAllRenderStates || tempState == EOFPS_ENABLE || tempState == EOFPS_DISABLE_TO_ENABLE) { // material colors if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.ColorMaterial != material.ColorMaterial) - { - switch (material.ColorMaterial) - { + lastmaterial.ColorMaterial != material.ColorMaterial) { + switch (material.ColorMaterial) { case ECM_NONE: glDisable(GL_COLOR_MATERIAL); break; @@ -2044,18 +1866,16 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater } if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.AmbientColor != material.AmbientColor || - lastmaterial.DiffuseColor != material.DiffuseColor || - lastmaterial.EmissiveColor != material.EmissiveColor || - lastmaterial.ColorMaterial != material.ColorMaterial) - { + lastmaterial.AmbientColor != material.AmbientColor || + lastmaterial.DiffuseColor != material.DiffuseColor || + lastmaterial.EmissiveColor != material.EmissiveColor || + lastmaterial.ColorMaterial != material.ColorMaterial) { GLfloat color[4]; const f32 inv = 1.0f / 255.0f; if ((material.ColorMaterial != video::ECM_AMBIENT) && - (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) - { + (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) { color[0] = material.AmbientColor.getRed() * inv; color[1] = material.AmbientColor.getGreen() * inv; color[2] = material.AmbientColor.getBlue() * inv; @@ -2064,8 +1884,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater } if ((material.ColorMaterial != video::ECM_DIFFUSE) && - (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) - { + (material.ColorMaterial != video::ECM_DIFFUSE_AND_AMBIENT)) { color[0] = material.DiffuseColor.getRed() * inv; color[1] = material.DiffuseColor.getGreen() * inv; color[2] = material.DiffuseColor.getBlue() * inv; @@ -2073,8 +1892,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color); } - if (material.ColorMaterial != video::ECM_EMISSIVE) - { + if (material.ColorMaterial != video::ECM_EMISSIVE) { color[0] = material.EmissiveColor.getRed() * inv; color[1] = material.EmissiveColor.getGreen() * inv; color[2] = material.EmissiveColor.getBlue() * inv; @@ -2084,18 +1902,16 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater } if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.SpecularColor != material.SpecularColor || - lastmaterial.Shininess != material.Shininess || - lastmaterial.ColorMaterial != material.ColorMaterial) - { - GLfloat color[4]={0.f,0.f,0.f,1.f}; + lastmaterial.SpecularColor != material.SpecularColor || + lastmaterial.Shininess != material.Shininess || + lastmaterial.ColorMaterial != material.ColorMaterial) { + GLfloat color[4] = {0.f, 0.f, 0.f, 1.f}; const f32 inv = 1.0f / 255.0f; glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material.Shininess); // disable Specular colors if no shininess is set if ((material.Shininess != 0.0f) && - (material.ColorMaterial != video::ECM_SPECULAR)) - { + (material.ColorMaterial != video::ECM_SPECULAR)) { #ifdef GL_EXT_separate_specular_color if (FeatureAvailable[IRR_EXT_separate_specular_color]) glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); @@ -2114,8 +1930,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // shademode if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.GouraudShading != material.GouraudShading) - { + lastmaterial.GouraudShading != material.GouraudShading) { if (material.GouraudShading) glShadeModel(GL_SMOOTH); else @@ -2124,8 +1939,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // lighting if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.Lighting != material.Lighting) - { + lastmaterial.Lighting != material.Lighting) { if (material.Lighting) glEnable(GL_LIGHTING); else @@ -2134,8 +1948,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // fog if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.FogEnable != material.FogEnable) - { + lastmaterial.FogEnable != material.FogEnable) { if (material.FogEnable) glEnable(GL_FOG); else @@ -2144,8 +1957,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // normalization if (resetAllRenderStates || tempState == EOFPS_DISABLE_TO_ENABLE || - lastmaterial.NormalizeNormals != material.NormalizeNormals) - { + lastmaterial.NormalizeNormals != material.NormalizeNormals) { if (material.NormalizeNormals) glEnable(GL_NORMALIZE); else @@ -2154,9 +1966,7 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // Set fixed pipeline as active. tempState = EOFPS_ENABLE; - } - else if (tempState == EOFPS_ENABLE_TO_DISABLE) - { + } else if (tempState == EOFPS_ENABLE_TO_DISABLE) { glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); glDisable(GL_FOG); @@ -2170,11 +1980,11 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater // fillmode - fixed pipeline call, but it emulate GL_LINES behaviour in rendering, so it stay here. if (resetAllRenderStates || (lastmaterial.Wireframe != material.Wireframe) || (lastmaterial.PointCloud != material.PointCloud)) - glPolygonMode(GL_FRONT_AND_BACK, material.Wireframe ? GL_LINE : material.PointCloud? GL_POINT : GL_FILL); + glPolygonMode(GL_FRONT_AND_BACK, material.Wireframe ? GL_LINE : material.PointCloud ? GL_POINT + : GL_FILL); // ZBuffer - switch (material.ZBuffer) - { + switch (material.ZBuffer) { case ECFN_DISABLED: CacheHandler->setDepthTest(false); break; @@ -2215,33 +2025,23 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater } // ZWrite - if (getWriteZBuffer(material)) - { + if (getWriteZBuffer(material)) { CacheHandler->setDepthMask(true); - } - else - { + } else { CacheHandler->setDepthMask(false); } // Back face culling - if ((material.FrontfaceCulling) && (material.BackfaceCulling)) - { + if ((material.FrontfaceCulling) && (material.BackfaceCulling)) { CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK); CacheHandler->setCullFace(true); - } - else if (material.BackfaceCulling) - { + } else if (material.BackfaceCulling) { CacheHandler->setCullFaceFunc(GL_BACK); CacheHandler->setCullFace(true); - } - else if (material.FrontfaceCulling) - { + } else if (material.FrontfaceCulling) { CacheHandler->setCullFaceFunc(GL_FRONT); CacheHandler->setCullFace(true); - } - else - { + } else { CacheHandler->setCullFace(false); } @@ -2249,186 +2049,165 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater CacheHandler->setColorMask(material.ColorMask); // Blend Equation - if (material.BlendOperation == EBO_NONE) - CacheHandler->setBlend(false); - else - { - CacheHandler->setBlend(true); + if (material.BlendOperation == EBO_NONE) + CacheHandler->setBlend(false); + else { + CacheHandler->setBlend(true); #if defined(GL_EXT_blend_subtract) || defined(GL_EXT_blend_minmax) || defined(GL_EXT_blend_logic_op) || defined(GL_VERSION_1_4) - if (queryFeature(EVDF_BLEND_OPERATIONS)) - { - switch (material.BlendOperation) - { - case EBO_SUBTRACT: + if (queryFeature(EVDF_BLEND_OPERATIONS)) { + switch (material.BlendOperation) { + case EBO_SUBTRACT: #if defined(GL_VERSION_1_4) - CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); + CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); #elif defined(GL_EXT_blend_subtract) - CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT_EXT); + CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT_EXT); #endif - break; - case EBO_REVSUBTRACT: + break; + case EBO_REVSUBTRACT: #if defined(GL_VERSION_1_4) - CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); #elif defined(GL_EXT_blend_subtract) - CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT_EXT); + CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT_EXT); #endif - break; - case EBO_MIN: + break; + case EBO_MIN: #if defined(GL_VERSION_1_4) - CacheHandler->setBlendEquation(GL_MIN); + CacheHandler->setBlendEquation(GL_MIN); #elif defined(GL_EXT_blend_minmax) - CacheHandler->setBlendEquation(GL_MIN_EXT); + CacheHandler->setBlendEquation(GL_MIN_EXT); #endif - break; - case EBO_MAX: + break; + case EBO_MAX: #if defined(GL_VERSION_1_4) - CacheHandler->setBlendEquation(GL_MAX); + CacheHandler->setBlendEquation(GL_MAX); #elif defined(GL_EXT_blend_minmax) - CacheHandler->setBlendEquation(GL_MAX_EXT); + CacheHandler->setBlendEquation(GL_MAX_EXT); #endif - break; - case EBO_MIN_FACTOR: + break; + case EBO_MIN_FACTOR: #if defined(GL_AMD_blend_minmax_factor) - if (FeatureAvailable[IRR_AMD_blend_minmax_factor]) - CacheHandler->setBlendEquation(GL_FACTOR_MIN_AMD); + if (FeatureAvailable[IRR_AMD_blend_minmax_factor]) + CacheHandler->setBlendEquation(GL_FACTOR_MIN_AMD); #endif - // fallback in case of missing extension + // fallback in case of missing extension #if defined(GL_VERSION_1_4) #if defined(GL_AMD_blend_minmax_factor) - else + else #endif - CacheHandler->setBlendEquation(GL_MIN); + CacheHandler->setBlendEquation(GL_MIN); #endif - break; - case EBO_MAX_FACTOR: + break; + case EBO_MAX_FACTOR: #if defined(GL_AMD_blend_minmax_factor) - if (FeatureAvailable[IRR_AMD_blend_minmax_factor]) - CacheHandler->setBlendEquation(GL_FACTOR_MAX_AMD); + if (FeatureAvailable[IRR_AMD_blend_minmax_factor]) + CacheHandler->setBlendEquation(GL_FACTOR_MAX_AMD); #endif - // fallback in case of missing extension + // fallback in case of missing extension #if defined(GL_VERSION_1_4) #if defined(GL_AMD_blend_minmax_factor) - else + else #endif - CacheHandler->setBlendEquation(GL_MAX); + CacheHandler->setBlendEquation(GL_MAX); #endif - break; - case EBO_MIN_ALPHA: + break; + case EBO_MIN_ALPHA: #if defined(GL_SGIX_blend_alpha_minmax) - if (FeatureAvailable[IRR_SGIX_blend_alpha_minmax]) - CacheHandler->setBlendEquation(GL_ALPHA_MIN_SGIX); - // fallback in case of missing extension - else - if (FeatureAvailable[IRR_EXT_blend_minmax]) - CacheHandler->setBlendEquation(GL_MIN_EXT); + if (FeatureAvailable[IRR_SGIX_blend_alpha_minmax]) + CacheHandler->setBlendEquation(GL_ALPHA_MIN_SGIX); + // fallback in case of missing extension + else if (FeatureAvailable[IRR_EXT_blend_minmax]) + CacheHandler->setBlendEquation(GL_MIN_EXT); #endif - break; - case EBO_MAX_ALPHA: + break; + case EBO_MAX_ALPHA: #if defined(GL_SGIX_blend_alpha_minmax) - if (FeatureAvailable[IRR_SGIX_blend_alpha_minmax]) - CacheHandler->setBlendEquation(GL_ALPHA_MAX_SGIX); - // fallback in case of missing extension - else - if (FeatureAvailable[IRR_EXT_blend_minmax]) - CacheHandler->setBlendEquation(GL_MAX_EXT); + if (FeatureAvailable[IRR_SGIX_blend_alpha_minmax]) + CacheHandler->setBlendEquation(GL_ALPHA_MAX_SGIX); + // fallback in case of missing extension + else if (FeatureAvailable[IRR_EXT_blend_minmax]) + CacheHandler->setBlendEquation(GL_MAX_EXT); #endif - break; - default: + break; + default: #if defined(GL_VERSION_1_4) - CacheHandler->setBlendEquation(GL_FUNC_ADD); + CacheHandler->setBlendEquation(GL_FUNC_ADD); #elif defined(GL_EXT_blend_subtract) || defined(GL_EXT_blend_minmax) || defined(GL_EXT_blend_logic_op) - CacheHandler->setBlendEquation(GL_FUNC_ADD_EXT); + CacheHandler->setBlendEquation(GL_FUNC_ADD_EXT); #endif - break; - } + break; + } } #endif } - // Blend Factor - if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? - && material.MaterialType != EMT_ONETEXTURE_BLEND - ) - { - E_BLEND_FACTOR srcRGBFact = EBF_ZERO; - E_BLEND_FACTOR dstRGBFact = EBF_ZERO; - E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; - E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; - E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; - u32 alphaSource = 0; + // Blend Factor + if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? + && material.MaterialType != EMT_ONETEXTURE_BLEND) { + E_BLEND_FACTOR srcRGBFact = EBF_ZERO; + E_BLEND_FACTOR dstRGBFact = EBF_ZERO; + E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; + E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; + E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; + u32 alphaSource = 0; - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); - if (queryFeature(EVDF_BLEND_SEPARATE)) - { - CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), - getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); - } - else - { - CacheHandler->setBlendFunc(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact)); - } + if (queryFeature(EVDF_BLEND_SEPARATE)) { + CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), + getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); + } else { + CacheHandler->setBlendFunc(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact)); + } } // Polygon Offset if (queryFeature(EVDF_POLYGON_OFFSET) && (resetAllRenderStates || - lastmaterial.PolygonOffsetSlopeScale != material.PolygonOffsetSlopeScale || - lastmaterial.PolygonOffsetDepthBias != material.PolygonOffsetDepthBias )) - { - glDisable(lastmaterial.Wireframe?GL_POLYGON_OFFSET_LINE:lastmaterial.PointCloud?GL_POLYGON_OFFSET_POINT:GL_POLYGON_OFFSET_FILL); - if ( material.PolygonOffsetSlopeScale || material.PolygonOffsetDepthBias ) - { - glEnable(material.Wireframe?GL_POLYGON_OFFSET_LINE:material.PointCloud?GL_POLYGON_OFFSET_POINT:GL_POLYGON_OFFSET_FILL); + lastmaterial.PolygonOffsetSlopeScale != material.PolygonOffsetSlopeScale || + lastmaterial.PolygonOffsetDepthBias != material.PolygonOffsetDepthBias)) { + glDisable(lastmaterial.Wireframe ? GL_POLYGON_OFFSET_LINE : lastmaterial.PointCloud ? GL_POLYGON_OFFSET_POINT + : GL_POLYGON_OFFSET_FILL); + if (material.PolygonOffsetSlopeScale || material.PolygonOffsetDepthBias) { + glEnable(material.Wireframe ? GL_POLYGON_OFFSET_LINE : material.PointCloud ? GL_POLYGON_OFFSET_POINT + : GL_POLYGON_OFFSET_FILL); glPolygonOffset(material.PolygonOffsetSlopeScale, material.PolygonOffsetDepthBias); - } - else - { + } else { glPolygonOffset(0.0f, 0.f); } } // thickness - if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) - { - if (AntiAlias) - { -// glPointSize(core::clamp(static_cast(material.Thickness), DimSmoothedPoint[0], DimSmoothedPoint[1])); + if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) { + if (AntiAlias) { + // glPointSize(core::clamp(static_cast(material.Thickness), DimSmoothedPoint[0], DimSmoothedPoint[1])); // we don't use point smoothing glPointSize(core::clamp(static_cast(material.Thickness), DimAliasedPoint[0], DimAliasedPoint[1])); glLineWidth(core::clamp(static_cast(material.Thickness), DimSmoothedLine[0], DimSmoothedLine[1])); - } - else - { + } else { glPointSize(core::clamp(static_cast(material.Thickness), DimAliasedPoint[0], DimAliasedPoint[1])); glLineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); } } // Anti aliasing - if ((resetAllRenderStates - || lastmaterial.AntiAliasing != material.AntiAliasing) - && FeatureAvailable[IRR_ARB_multisample]) { + if ((resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) && FeatureAvailable[IRR_ARB_multisample]) { if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); - if ((AntiAlias >= 2) && (material.AntiAliasing & (EAAM_SIMPLE|EAAM_QUALITY))) - { + if ((AntiAlias >= 2) && (material.AntiAliasing & (EAAM_SIMPLE | EAAM_QUALITY))) { glEnable(GL_MULTISAMPLE_ARB); #ifdef GL_NV_multisample_filter_hint - if (FeatureAvailable[IRR_NV_multisample_filter_hint]) - { + if (FeatureAvailable[IRR_NV_multisample_filter_hint]) { if ((material.AntiAliasing & EAAM_QUALITY) == EAAM_QUALITY) glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST); else glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_FASTEST); } #endif - } - else + } else glDisable(GL_MULTISAMPLE_ARB); } @@ -2440,34 +2219,30 @@ void COpenGLDriver::setBasicRenderStates(const SMaterial& material, const SMater } //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. -void COpenGLDriver::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates) +void COpenGLDriver::setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates) { // Set textures to TU/TIU and apply filters to them - for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) - { + for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) { bool fixedPipeline = false; if (FixedPipelineState == EOFPS_ENABLE || FixedPipelineState == EOFPS_DISABLE_TO_ENABLE) fixedPipeline = true; - const COpenGLTexture* tmpTexture = CacheHandler->getTextureCache().get(i); + const COpenGLTexture *tmpTexture = CacheHandler->getTextureCache().get(i); - if (tmpTexture) - { + if (tmpTexture) { CacheHandler->setActiveTexture(GL_TEXTURE0 + i); // Minetest uses the first texture matrix even with the programmable pipeline - if (fixedPipeline || i == 0) - { + if (fixedPipeline || i == 0) { const bool isRTT = tmpTexture->isRenderTarget(); CacheHandler->setMatrixMode(GL_TEXTURE); if (!isRTT && Matrices[ETS_TEXTURE_0 + i].isIdentity()) glLoadIdentity(); - else - { + else { GLfloat glmat[16]; if (isRTT) getGLTextureMatrix(glmat, Matrices[ETS_TEXTURE_0 + i] * TextureFlipMatrix); @@ -2479,85 +2254,65 @@ void COpenGLDriver::setTextureRenderStates(const SMaterial& material, bool reset const GLenum tmpType = tmpTexture->getOpenGLTextureType(); - COpenGLTexture::SStatesCache& statesCache = tmpTexture->getStatesCache(); + COpenGLTexture::SStatesCache &statesCache = tmpTexture->getStatesCache(); if (resetAllRenderstates) statesCache.IsCached = false; #ifdef GL_VERSION_2_1 - if (Version >= 201) - { - if (!statesCache.IsCached || material.TextureLayers[i].LODBias != statesCache.LODBias) - { - if (material.TextureLayers[i].LODBias) - { + if (Version >= 201) { + if (!statesCache.IsCached || material.TextureLayers[i].LODBias != statesCache.LODBias) { + if (material.TextureLayers[i].LODBias) { const float tmp = core::clamp(material.TextureLayers[i].LODBias * 0.125f, -MaxTextureLODBias, MaxTextureLODBias); glTexParameterf(tmpType, GL_TEXTURE_LOD_BIAS, tmp); - } - else + } else glTexParameterf(tmpType, GL_TEXTURE_LOD_BIAS, 0.f); statesCache.LODBias = material.TextureLayers[i].LODBias; } - } - else if (FeatureAvailable[IRR_EXT_texture_lod_bias]) - { - if (material.TextureLayers[i].LODBias) - { + } else if (FeatureAvailable[IRR_EXT_texture_lod_bias]) { + if (material.TextureLayers[i].LODBias) { const float tmp = core::clamp(material.TextureLayers[i].LODBias * 0.125f, -MaxTextureLODBias, MaxTextureLODBias); glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, tmp); - } - else + } else glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.f); } #elif defined(GL_EXT_texture_lod_bias) - if (FeatureAvailable[IRR_EXT_texture_lod_bias]) - { - if (material.TextureLayers[i].LODBias) - { + if (FeatureAvailable[IRR_EXT_texture_lod_bias]) { + if (material.TextureLayers[i].LODBias) { const float tmp = core::clamp(material.TextureLayers[i].LODBias * 0.125f, -MaxTextureLODBias, MaxTextureLODBias); glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, tmp); - } - else + } else glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.f); } #endif - if (!statesCache.IsCached || material.TextureLayers[i].MagFilter != statesCache.MagFilter) - { + if (!statesCache.IsCached || material.TextureLayers[i].MagFilter != statesCache.MagFilter) { E_TEXTURE_MAG_FILTER magFilter = material.TextureLayers[i].MagFilter; glTexParameteri(tmpType, GL_TEXTURE_MAG_FILTER, - magFilter == ETMAGF_NEAREST ? GL_NEAREST : - (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); + magFilter == ETMAGF_NEAREST ? GL_NEAREST : (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); statesCache.MagFilter = magFilter; } - if (material.UseMipMaps && tmpTexture->hasMipMaps()) - { + if (material.UseMipMaps && tmpTexture->hasMipMaps()) { if (!statesCache.IsCached || material.TextureLayers[i].MinFilter != statesCache.MinFilter || - !statesCache.MipMapStatus) - { + !statesCache.MipMapStatus) { E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; glTexParameteri(tmpType, GL_TEXTURE_MIN_FILTER, - minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : - minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST : - minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); + minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST + : minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR + : (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); statesCache.MinFilter = minFilter; statesCache.MipMapStatus = true; } - } - else - { + } else { if (!statesCache.IsCached || material.TextureLayers[i].MinFilter != statesCache.MinFilter || - statesCache.MipMapStatus) - { + statesCache.MipMapStatus) { E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; glTexParameteri(tmpType, GL_TEXTURE_MIN_FILTER, - (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); + (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); statesCache.MinFilter = minFilter; statesCache.MipMapStatus = false; @@ -2566,29 +2321,25 @@ void COpenGLDriver::setTextureRenderStates(const SMaterial& material, bool reset #ifdef GL_EXT_texture_filter_anisotropic if (FeatureAvailable[IRR_EXT_texture_filter_anisotropic] && - (!statesCache.IsCached || material.TextureLayers[i].AnisotropicFilter != statesCache.AnisotropicFilter)) - { + (!statesCache.IsCached || material.TextureLayers[i].AnisotropicFilter != statesCache.AnisotropicFilter)) { glTexParameteri(tmpType, GL_TEXTURE_MAX_ANISOTROPY_EXT, - material.TextureLayers[i].AnisotropicFilter > 1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); + material.TextureLayers[i].AnisotropicFilter > 1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); statesCache.AnisotropicFilter = material.TextureLayers[i].AnisotropicFilter; } #endif - if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapU != statesCache.WrapU) - { + if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapU != statesCache.WrapU) { glTexParameteri(tmpType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayers[i].TextureWrapU)); statesCache.WrapU = material.TextureLayers[i].TextureWrapU; } - if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapV != statesCache.WrapV) - { + if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapV != statesCache.WrapV) { glTexParameteri(tmpType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayers[i].TextureWrapV)); statesCache.WrapV = material.TextureLayers[i].TextureWrapV; } - if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapW != statesCache.WrapW) - { + if (!statesCache.IsCached || material.TextureLayers[i].TextureWrapW != statesCache.WrapW) { glTexParameteri(tmpType, GL_TEXTURE_WRAP_R, getTextureWrapMode(material.TextureLayers[i].TextureWrapW)); statesCache.WrapW = material.TextureLayers[i].TextureWrapW; } @@ -2598,7 +2349,6 @@ void COpenGLDriver::setTextureRenderStates(const SMaterial& material, bool reset } } - //! Enable the 2d override material void COpenGLDriver::enableMaterial2D(bool enable) { @@ -2607,7 +2357,6 @@ void COpenGLDriver::enableMaterial2D(bool enable) CNullDriver::enableMaterial2D(enable); } - //! sets the needed renderstates void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) { @@ -2619,23 +2368,20 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh bool resetAllRenderStates = false; - if (CurrentRenderMode != ERM_2D || Transformation3DChanged) - { + if (CurrentRenderMode != ERM_2D || Transformation3DChanged) { // unset last 3d material - if (CurrentRenderMode == ERM_3D) - { + if (CurrentRenderMode == ERM_3D) { if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); } - if (Transformation3DChanged) - { + if (Transformation3DChanged) { CacheHandler->setMatrixMode(GL_PROJECTION); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); core::matrix4 m(core::matrix4::EM4CONST_NOTHING); m.buildProjectionMatrixOrthoLH(f32(renderTargetSize.Width), f32(-(s32)(renderTargetSize.Height)), -1.0f, 1.0f); - m.setTranslation(core::vector3df(-1,1,0)); + m.setTranslation(core::vector3df(-1, 1, 0)); glLoadMatrixf(m.pointer()); CacheHandler->setMatrixMode(GL_MODELVIEW); @@ -2659,16 +2405,13 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh SMaterial currentMaterial = (!OverrideMaterial2DEnabled) ? InitMaterial2D : OverrideMaterial2D; currentMaterial.Lighting = false; - if (texture) - { + if (texture) { setTransform(ETS_TEXTURE_0, core::IdentityMatrix); // Due to the transformation change, the previous line would call a reset each frame // but we can safely reset the variable as it was false before Transformation3DChanged = false; - } - else - { + } else { CacheHandler->getTextureCache().set(0, 0); } @@ -2680,34 +2423,25 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh // no alphaChannel without texture alphaChannel &= texture; - if (alphaChannel || alpha) - { + if (alphaChannel || alpha) { CacheHandler->setBlend(true); CacheHandler->setAlphaTest(true); CacheHandler->setAlphaFunc(GL_GREATER, 0.f); - } - else - { + } else { CacheHandler->setBlend(false); CacheHandler->setAlphaTest(false); } - if (texture) - { + if (texture) { CacheHandler->setActiveTexture(GL_TEXTURE0_ARB); - if (alphaChannel) - { + if (alphaChannel) { // if alpha and alpha texture just modulate, otherwise use only the alpha channel - if (alpha) - { + if (alpha) { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } - else - { + } else { #if defined(GL_ARB_texture_env_combine) || defined(GL_EXT_texture_env_combine) - if (FeatureAvailable[IRR_ARB_texture_env_combine]||FeatureAvailable[IRR_EXT_texture_env_combine]) - { + if (FeatureAvailable[IRR_ARB_texture_env_combine] || FeatureAvailable[IRR_EXT_texture_env_combine]) { #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE); @@ -2725,19 +2459,14 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PRIMARY_COLOR_EXT); #endif - } - else + } else #endif glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } - } - else - { - if (alpha) - { + } else { + if (alpha) { #if defined(GL_ARB_texture_env_combine) || defined(GL_EXT_texture_env_combine) - if (FeatureAvailable[IRR_ARB_texture_env_combine]||FeatureAvailable[IRR_EXT_texture_env_combine]) - { + if (FeatureAvailable[IRR_ARB_texture_env_combine] || FeatureAvailable[IRR_EXT_texture_env_combine]) { #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE); @@ -2755,13 +2484,10 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PRIMARY_COLOR_EXT); #endif - } - else + } else #endif glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } - else - { + } else { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } } @@ -2770,28 +2496,25 @@ void COpenGLDriver::setRenderStates2DMode(bool alpha, bool texture, bool alphaCh CurrentRenderMode = ERM_2D; } - //! \return Returns the name of the video driver. -const char* COpenGLDriver::getName() const +const char *COpenGLDriver::getName() const { return Name.c_str(); } - //! Sets the dynamic ambient light color. The default color is //! (0,0,0,0) which means it is dark. //! \param color: New color of the ambient light. -void COpenGLDriver::setAmbientLight(const SColorf& color) +void COpenGLDriver::setAmbientLight(const SColorf &color) { CNullDriver::setAmbientLight(color); GLfloat data[4] = {color.r, color.g, color.b, color.a}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, data); } - // this code was sent in by Oliver Klems, thank you! (I modified the glViewport // method just a bit. -void COpenGLDriver::setViewPort(const core::rect& area) +void COpenGLDriver::setViewPort(const core::rect &area) { core::rect vp = area; core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); @@ -2803,29 +2526,27 @@ void COpenGLDriver::setViewPort(const core::rect& area) ViewPort = vp; } - void COpenGLDriver::setViewPortRaw(u32 width, u32 height) { CacheHandler->setViewport(0, 0, width, height); ViewPort = core::recti(0, 0, width, height); } - //! Sets the fog mode. void COpenGLDriver::setFog(SColor c, E_FOG_TYPE fogType, f32 start, - f32 end, f32 density, bool pixelFog, bool rangeFog) + f32 end, f32 density, bool pixelFog, bool rangeFog) { CNullDriver::setFog(c, fogType, start, end, density, pixelFog, rangeFog); - glFogf(GL_FOG_MODE, GLfloat((fogType==EFT_FOG_LINEAR)? GL_LINEAR : (fogType==EFT_FOG_EXP)?GL_EXP:GL_EXP2)); + glFogf(GL_FOG_MODE, GLfloat((fogType == EFT_FOG_LINEAR) ? GL_LINEAR : (fogType == EFT_FOG_EXP) ? GL_EXP + : GL_EXP2)); #ifdef GL_EXT_fog_coord if (FeatureAvailable[IRR_EXT_fog_coord]) glFogi(GL_FOG_COORDINATE_SOURCE, GL_FRAGMENT_DEPTH); #endif #ifdef GL_NV_fog_distance - if (FeatureAvailable[IRR_NV_fog_distance]) - { + if (FeatureAvailable[IRR_NV_fog_distance]) { if (rangeFog) glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_RADIAL_NV); else @@ -2833,12 +2554,10 @@ void COpenGLDriver::setFog(SColor c, E_FOG_TYPE fogType, f32 start, } #endif - if (fogType==EFT_FOG_LINEAR) - { + if (fogType == EFT_FOG_LINEAR) { glFogf(GL_FOG_START, start); glFogf(GL_FOG_END, end); - } - else + } else glFogf(GL_FOG_DENSITY, density); if (pixelFog) @@ -2852,7 +2571,7 @@ void COpenGLDriver::setFog(SColor c, E_FOG_TYPE fogType, f32 start, } //! Draws a 3d box. -void COpenGLDriver::draw3DBox( const core::aabbox3d& box, SColor color ) +void COpenGLDriver::draw3DBox(const core::aabbox3d &box, SColor color) { core::vector3df edges[8]; box.getEdges(edges); @@ -2861,7 +2580,7 @@ void COpenGLDriver::draw3DBox( const core::aabbox3d& box, SColor color ) video::S3DVertex v[24]; - for(u32 i = 0; i < 24; i++) + for (u32 i = 0; i < 24; i++) v[i].Color = color; v[0].Pos = edges[5]; @@ -2894,28 +2613,26 @@ void COpenGLDriver::draw3DBox( const core::aabbox3d& box, SColor color ) CacheHandler->setClientState(true, false, true, false); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(v))[0].Pos); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(v))[0].Pos); #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(v))[0].Color); - else - { - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(v))[0].Color); + else { + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } glDrawArrays(GL_LINES, 0, 24); } - //! Draws a 3d line. -void COpenGLDriver::draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color) +void COpenGLDriver::draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color) { setRenderStates3DMode(); @@ -2930,27 +2647,25 @@ void COpenGLDriver::draw3DLine(const core::vector3df& start, CacheHandler->setClientState(true, false, true, false); - glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); + glVertexPointer(3, GL_FLOAT, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Pos); #ifdef GL_BGRA - const GLint colorSize=(FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra])?GL_BGRA:4; + const GLint colorSize = (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) ? GL_BGRA : 4; #else - const GLint colorSize=4; + const GLint colorSize = 4; #endif if (FeatureAvailable[IRR_ARB_vertex_array_bgra] || FeatureAvailable[IRR_EXT_vertex_array_bgra]) - glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); - else - { - _IRR_DEBUG_BREAK_IF(ColorBuffer.size()==0); + glColorPointer(colorSize, GL_UNSIGNED_BYTE, sizeof(S3DVertex), &(static_cast(Quad2DVertices))[0].Color); + else { + _IRR_DEBUG_BREAK_IF(ColorBuffer.size() == 0); glColorPointer(colorSize, GL_UNSIGNED_BYTE, 0, &ColorBuffer[0]); } glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, Quad2DIndices); } - //! Removes a texture from the texture cache and deletes it, freeing lot of memory. -void COpenGLDriver::removeTexture(ITexture* texture) +void COpenGLDriver::removeTexture(ITexture *texture) { CacheHandler->getTextureCache().remove(texture); CNullDriver::removeTexture(texture); @@ -2962,141 +2677,135 @@ bool COpenGLDriver::queryTextureFormat(ECOLOR_FORMAT format) const GLint dummyInternalFormat; GLenum dummyPixelFormat; GLenum dummyPixelType; - void (*dummyConverter)(const void*, s32, void*); + void (*dummyConverter)(const void *, s32, void *); return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter); } -bool COpenGLDriver::needsTransparentRenderPass(const irr::video::SMaterial& material) const +bool COpenGLDriver::needsTransparentRenderPass(const irr::video::SMaterial &material) const { return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); } //! Only used by the internal engine. Used to notify the driver that //! the window was resized. -void COpenGLDriver::OnResize(const core::dimension2d& size) +void COpenGLDriver::OnResize(const core::dimension2d &size) { CNullDriver::OnResize(size); CacheHandler->setViewport(0, 0, size.Width, size.Height); Transformation3DChanged = true; } - //! Returns type of video driver E_DRIVER_TYPE COpenGLDriver::getDriverType() const { return EDT_OPENGL; } - //! returns color format ECOLOR_FORMAT COpenGLDriver::getColorFormat() const { return ColorFormat; } - //! Get a vertex shader constant index. -s32 COpenGLDriver::getVertexShaderConstantID(const c8* name) +s32 COpenGLDriver::getVertexShaderConstantID(const c8 *name) { return getPixelShaderConstantID(name); } //! Get a pixel shader constant index. -s32 COpenGLDriver::getPixelShaderConstantID(const c8* name) +s32 COpenGLDriver::getPixelShaderConstantID(const c8 *name) { os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID()."); return -1; } //! Sets a constant for the vertex shader based on an index. -bool COpenGLDriver::setVertexShaderConstant(s32 index, const f32* floats, int count) +bool COpenGLDriver::setVertexShaderConstant(s32 index, const f32 *floats, int count) { - //pass this along, as in GLSL the same routine is used for both vertex and fragment shaders + // pass this along, as in GLSL the same routine is used for both vertex and fragment shaders return setPixelShaderConstant(index, floats, count); } //! Int interface for the above. -bool COpenGLDriver::setVertexShaderConstant(s32 index, const s32* ints, int count) +bool COpenGLDriver::setVertexShaderConstant(s32 index, const s32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } //! Uint interface for the above. -bool COpenGLDriver::setVertexShaderConstant(s32 index, const u32* ints, int count) +bool COpenGLDriver::setVertexShaderConstant(s32 index, const u32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } //! Sets a constant for the pixel shader based on an index. -bool COpenGLDriver::setPixelShaderConstant(s32 index, const f32* floats, int count) +bool COpenGLDriver::setPixelShaderConstant(s32 index, const f32 *floats, int count) { os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); return false; } //! Int interface for the above. -bool COpenGLDriver::setPixelShaderConstant(s32 index, const s32* ints, int count) +bool COpenGLDriver::setPixelShaderConstant(s32 index, const s32 *ints, int count) { os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); return false; } -bool COpenGLDriver::setPixelShaderConstant(s32 index, const u32* ints, int count) +bool COpenGLDriver::setPixelShaderConstant(s32 index, const u32 *ints, int count) { os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); return false; } - //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. s32 COpenGLDriver::addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, - E_GEOMETRY_SHADER_TYPE gsCompileTarget, - scene::E_PRIMITIVE_TYPE inType, - scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, + E_GEOMETRY_SHADER_TYPE gsCompileTarget, + scene::E_PRIMITIVE_TYPE inType, + scene::E_PRIMITIVE_TYPE outType, + u32 verticesOut, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) { s32 nr = -1; - COpenGLSLMaterialRenderer* r = new COpenGLSLMaterialRenderer( + COpenGLSLMaterialRenderer *r = new COpenGLSLMaterialRenderer( this, nr, vertexShaderProgram, vertexShaderEntryPointName, vsCompileTarget, pixelShaderProgram, pixelShaderEntryPointName, psCompileTarget, geometryShaderProgram, geometryShaderEntryPointName, gsCompileTarget, inType, outType, verticesOut, - callback,baseMaterial, userData); + callback, baseMaterial, userData); r->drop(); return nr; } - //! Returns a pointer to the IVideoDriver interface. (Implementation for //! IMaterialRendererServices) -IVideoDriver* COpenGLDriver::getVideoDriver() +IVideoDriver *COpenGLDriver::getVideoDriver() { return this; } - -ITexture* COpenGLDriver::addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format) +ITexture *COpenGLDriver::addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format) { - if ( IImage::isCompressedFormat(format) ) + if (IImage::isCompressedFormat(format)) return 0; - //disable mip-mapping + // disable mip-mapping bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); @@ -3104,29 +2813,28 @@ ITexture* COpenGLDriver::addRenderTargetTexture(const core::dimension2d& si core::dimension2du destSize(size); - if (!supportForFBO) - { + if (!supportForFBO) { destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); } - COpenGLTexture* renderTargetTexture = new COpenGLTexture(name, destSize, ETT_2D, format, this); + COpenGLTexture *renderTargetTexture = new COpenGLTexture(name, destSize, ETT_2D, format, this); addTexture(renderTargetTexture); renderTargetTexture->drop(); - //restore mip-mapping + // restore mip-mapping setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); return renderTargetTexture; } //! Creates a render target texture for a cubemap -ITexture* COpenGLDriver::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format) +ITexture *COpenGLDriver::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path &name, const ECOLOR_FORMAT format) { - if ( IImage::isCompressedFormat(format) ) + if (IImage::isCompressedFormat(format)) return 0; - //disable mip-mapping + // disable mip-mapping bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); @@ -3135,23 +2843,21 @@ ITexture* COpenGLDriver::addRenderTargetTextureCubemap(const irr::u32 sideLen, c const core::dimension2d size(sideLen, sideLen); core::dimension2du destSize(size); - if (!supportForFBO) - { + if (!supportForFBO) { destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); } - COpenGLTexture* renderTargetTexture = new COpenGLTexture(name, destSize, ETT_CUBEMAP, format, this); + COpenGLTexture *renderTargetTexture = new COpenGLTexture(name, destSize, ETT_CUBEMAP, format, this); addTexture(renderTargetTexture); renderTargetTexture->drop(); - //restore mip-mapping + // restore mip-mapping setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); return renderTargetTexture; } - //! Returns the maximum amount of primitives (mostly vertices) which //! the device is able to render with one drawIndexedTriangleList //! call. @@ -3160,10 +2866,9 @@ u32 COpenGLDriver::getMaximalPrimitiveCount() const return 0x7fffffff; } -bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) +bool COpenGLDriver::setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) { - if (target && target->getDriverType() != EDT_OPENGL) - { + if (target && target->getDriverType() != EDT_OPENGL) { os::Printer::log("Fatal Error: Tried to set a render target not owned by this driver.", ELL_ERROR); return false; } @@ -3172,12 +2877,10 @@ bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol core::dimension2d destRenderTargetSize(0, 0); - if (target) - { - COpenGLRenderTarget* renderTarget = static_cast(target); + if (target) { + COpenGLRenderTarget *renderTarget = static_cast(target); - if (supportForFBO) - { + if (supportForFBO) { CacheHandler->setFBO(renderTarget->getBufferID()); renderTarget->update(); } @@ -3185,19 +2888,15 @@ bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol destRenderTargetSize = renderTarget->getSize(); setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); - } - else - { + } else { if (supportForFBO) CacheHandler->setFBO(0); - else - { - COpenGLRenderTarget* prevRenderTarget = static_cast(CurrentRenderTarget); - COpenGLTexture* renderTargetTexture = static_cast(prevRenderTarget->getTexture()); + else { + COpenGLRenderTarget *prevRenderTarget = static_cast(CurrentRenderTarget); + COpenGLTexture *renderTargetTexture = static_cast(prevRenderTarget->getTexture()); - if (renderTargetTexture) - { - const COpenGLTexture* prevTexture = CacheHandler->getTextureCache()[0]; + if (renderTargetTexture) { + const COpenGLTexture *prevTexture = CacheHandler->getTextureCache()[0]; CacheHandler->getTextureCache().set(0, renderTargetTexture); @@ -3213,8 +2912,7 @@ bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol setViewPortRaw(ScreenSize.Width, ScreenSize.Height); } - if (CurrentRenderTargetSize != destRenderTargetSize) - { + if (CurrentRenderTargetSize != destRenderTargetSize) { CurrentRenderTargetSize = destRenderTargetSize; Transformation3DChanged = true; @@ -3222,8 +2920,7 @@ bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol CurrentRenderTarget = target; - if (!supportForFBO) - { + if (!supportForFBO) { clearFlag |= ECBF_COLOR; clearFlag |= ECBF_DEPTH; } @@ -3233,7 +2930,6 @@ bool COpenGLDriver::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SCol return true; } - void COpenGLDriver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) { GLbitfield mask = 0; @@ -3243,26 +2939,23 @@ void COpenGLDriver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) CacheHandler->getColorMask(colorMask); CacheHandler->getDepthMask(depthMask); - if (flag & ECBF_COLOR) - { + if (flag & ECBF_COLOR) { CacheHandler->setColorMask(ECP_ALL); const f32 inv = 1.0f / 255.0f; glClearColor(color.getRed() * inv, color.getGreen() * inv, - color.getBlue() * inv, color.getAlpha() * inv); + color.getBlue() * inv, color.getAlpha() * inv); mask |= GL_COLOR_BUFFER_BIT; } - if (flag & ECBF_DEPTH) - { + if (flag & ECBF_DEPTH) { CacheHandler->setDepthMask(true); glClearDepth(depth); mask |= GL_DEPTH_BUFFER_BIT; } - if (flag & ECBF_STENCIL) - { + if (flag & ECBF_STENCIL) { glClearStencil(stencil); mask |= GL_STENCIL_BUFFER_BIT; } @@ -3274,21 +2967,20 @@ void COpenGLDriver::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) CacheHandler->setDepthMask(depthMask); } - //! Returns an image created from the last rendered frame. -IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) +IImage *COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) { if (target != video::ERT_FRAME_BUFFER) return 0; - if (format==video::ECF_UNKNOWN) - format=getColorFormat(); + if (format == video::ECF_UNKNOWN) + format = getColorFormat(); // TODO: Maybe we could support more formats (floating point and some of those beyond ECF_R8), didn't really try yet if (IImage::isCompressedFormat(format) || IImage::isDepthFormat(format) || IImage::isFloatingPointFormat(format) || format >= ECF_R8) return 0; - // allows to read pixels in top-to-bottom order + // allows to read pixels in top-to-bottom order #ifdef GL_MESA_pack_invert if (FeatureAvailable[IRR_MESA_pack_invert]) glPixelStorei(GL_PACK_INVERT_MESA, GL_TRUE); @@ -3297,8 +2989,7 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE GLenum fmt; GLenum type; - switch (format) - { + switch (format) { case ECF_A1R5G5B5: fmt = GL_BGRA; type = GL_UNSIGNED_SHORT_1_5_5_5_REV; @@ -3323,13 +3014,12 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE type = GL_UNSIGNED_BYTE; break; } - IImage* newImage = createImage(format, ScreenSize); + IImage *newImage = createImage(format, ScreenSize); - u8* pixels = 0; + u8 *pixels = 0; if (newImage) - pixels = static_cast(newImage->getData()); - if (pixels) - { + pixels = static_cast(newImage->getData()); + if (pixels) { glReadBuffer(GL_FRONT); glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, fmt, type, pixels); testGLError(__LINE__); @@ -3341,35 +3031,31 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE glPixelStorei(GL_PACK_INVERT_MESA, GL_FALSE); else #endif - if (pixels && newImage) - { + if (pixels && newImage) { // opengl images are horizontally flipped, so we have to fix that here. const s32 pitch = newImage->getPitch(); - u8* p2 = pixels + (ScreenSize.Height - 1) * pitch; - u8* tmpBuffer = new u8[pitch]; - for (u32 i=0; i < ScreenSize.Height; i += 2) - { + u8 *p2 = pixels + (ScreenSize.Height - 1) * pitch; + u8 *tmpBuffer = new u8[pitch]; + for (u32 i = 0; i < ScreenSize.Height; i += 2) { memcpy(tmpBuffer, pixels, pitch); -// for (u32 j=0; jdrop(); return 0; @@ -3379,17 +3065,16 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE } //! Set/unset a clipping plane. -bool COpenGLDriver::setClipPlane(u32 index, const core::plane3df& plane, bool enable) +bool COpenGLDriver::setClipPlane(u32 index, const core::plane3df &plane, bool enable) { if (index >= MaxUserClipPlanes) return false; - UserClipPlanes[index].Plane=plane; + UserClipPlanes[index].Plane = plane; enableClipPlane(index, enable); return true; } - void COpenGLDriver::uploadClipPlane(u32 index) { // opengl needs an array of doubles for the plane equation @@ -3401,79 +3086,92 @@ void COpenGLDriver::uploadClipPlane(u32 index) glClipPlane(GL_CLIP_PLANE0 + index, clip_plane); } - //! Enable/disable a clipping plane. void COpenGLDriver::enableClipPlane(u32 index, bool enable) { if (index >= MaxUserClipPlanes) return; - if (enable) - { - if (!UserClipPlanes[index].Enabled) - { + if (enable) { + if (!UserClipPlanes[index].Enabled) { uploadClipPlane(index); glEnable(GL_CLIP_PLANE0 + index); } - } - else + } else glDisable(GL_CLIP_PLANE0 + index); - UserClipPlanes[index].Enabled=enable; + UserClipPlanes[index].Enabled = enable; } - core::dimension2du COpenGLDriver::getMaxTextureSize() const { return core::dimension2du(MaxTextureSize, MaxTextureSize); } - //! Convert E_PRIMITIVE_TYPE to OpenGL equivalent GLenum COpenGLDriver::primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const { - switch (type) - { - case scene::EPT_POINTS: - return GL_POINTS; - case scene::EPT_LINE_STRIP: - return GL_LINE_STRIP; - case scene::EPT_LINE_LOOP: - return GL_LINE_LOOP; - case scene::EPT_LINES: - return GL_LINES; - case scene::EPT_TRIANGLE_STRIP: - return GL_TRIANGLE_STRIP; - case scene::EPT_TRIANGLE_FAN: - return GL_TRIANGLE_FAN; - case scene::EPT_TRIANGLES: - return GL_TRIANGLES; - case scene::EPT_POINT_SPRITES: + switch (type) { + case scene::EPT_POINTS: + return GL_POINTS; + case scene::EPT_LINE_STRIP: + return GL_LINE_STRIP; + case scene::EPT_LINE_LOOP: + return GL_LINE_LOOP; + case scene::EPT_LINES: + return GL_LINES; + case scene::EPT_TRIANGLE_STRIP: + return GL_TRIANGLE_STRIP; + case scene::EPT_TRIANGLE_FAN: + return GL_TRIANGLE_FAN; + case scene::EPT_TRIANGLES: + return GL_TRIANGLES; + case scene::EPT_POINT_SPRITES: #ifdef GL_ARB_point_sprite - return GL_POINT_SPRITE_ARB; + return GL_POINT_SPRITE_ARB; #else - return GL_POINTS; + return GL_POINTS; #endif } return GL_TRIANGLES; } - GLenum COpenGLDriver::getGLBlend(E_BLEND_FACTOR factor) const { GLenum r = 0; - switch (factor) - { - case EBF_ZERO: r = GL_ZERO; break; - case EBF_ONE: r = GL_ONE; break; - case EBF_DST_COLOR: r = GL_DST_COLOR; break; - case EBF_ONE_MINUS_DST_COLOR: r = GL_ONE_MINUS_DST_COLOR; break; - case EBF_SRC_COLOR: r = GL_SRC_COLOR; break; - case EBF_ONE_MINUS_SRC_COLOR: r = GL_ONE_MINUS_SRC_COLOR; break; - case EBF_SRC_ALPHA: r = GL_SRC_ALPHA; break; - case EBF_ONE_MINUS_SRC_ALPHA: r = GL_ONE_MINUS_SRC_ALPHA; break; - case EBF_DST_ALPHA: r = GL_DST_ALPHA; break; - case EBF_ONE_MINUS_DST_ALPHA: r = GL_ONE_MINUS_DST_ALPHA; break; - case EBF_SRC_ALPHA_SATURATE: r = GL_SRC_ALPHA_SATURATE; break; + switch (factor) { + case EBF_ZERO: + r = GL_ZERO; + break; + case EBF_ONE: + r = GL_ONE; + break; + case EBF_DST_COLOR: + r = GL_DST_COLOR; + break; + case EBF_ONE_MINUS_DST_COLOR: + r = GL_ONE_MINUS_DST_COLOR; + break; + case EBF_SRC_COLOR: + r = GL_SRC_COLOR; + break; + case EBF_ONE_MINUS_SRC_COLOR: + r = GL_ONE_MINUS_SRC_COLOR; + break; + case EBF_SRC_ALPHA: + r = GL_SRC_ALPHA; + break; + case EBF_ONE_MINUS_SRC_ALPHA: + r = GL_ONE_MINUS_SRC_ALPHA; + break; + case EBF_DST_ALPHA: + r = GL_DST_ALPHA; + break; + case EBF_ONE_MINUS_DST_ALPHA: + r = GL_ONE_MINUS_DST_ALPHA; + break; + case EBF_SRC_ALPHA_SATURATE: + r = GL_SRC_ALPHA_SATURATE; + break; } return r; } @@ -3481,8 +3179,7 @@ GLenum COpenGLDriver::getGLBlend(E_BLEND_FACTOR factor) const GLenum COpenGLDriver::getZBufferBits() const { GLenum bits = 0; - switch (Params.ZBufferBits) - { + switch (Params.ZBufferBits) { case 16: bits = GL_DEPTH_COMPONENT16; break; @@ -3499,8 +3196,8 @@ GLenum COpenGLDriver::getZBufferBits() const return bits; } -bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const +bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const { // NOTE: Converter variable not used here, but don't remove, it's used in the OGL-ES drivers. @@ -3509,8 +3206,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern pixelFormat = GL_RGBA; pixelType = GL_UNSIGNED_BYTE; - switch (format) - { + switch (format) { case ECF_A1R5G5B5: supported = true; internalFormat = GL_RGBA; @@ -3550,18 +3246,15 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern break; case ECF_D24S8: #ifdef GL_VERSION_3_0 - if (Version >= 300) - { + if (Version >= 300) { supported = true; internalFormat = GL_DEPTH_STENCIL; pixelFormat = GL_DEPTH_STENCIL; pixelType = GL_UNSIGNED_INT_24_8; - } - else + } else #endif #ifdef GL_EXT_packed_depth_stencil - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_EXT_packed_depth_stencil)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_EXT_packed_depth_stencil)) { supported = true; internalFormat = GL_DEPTH_STENCIL_EXT; pixelFormat = GL_DEPTH_STENCIL_EXT; @@ -3570,8 +3263,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern #endif break; case ECF_R8: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_R8; pixelFormat = GL_RED; @@ -3579,8 +3271,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_R8G8: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_RG8; pixelFormat = GL_RG; @@ -3588,8 +3279,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_R16: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_R16; pixelFormat = GL_RED; @@ -3597,8 +3287,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_R16G16: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_RG16; pixelFormat = GL_RG; @@ -3606,8 +3295,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_R16F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_R16F; pixelFormat = GL_RED; @@ -3620,8 +3308,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_G16R16F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_RG16F; pixelFormat = GL_RG; @@ -3634,8 +3321,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_A16B16G16R16F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_float)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_float)) { supported = true; internalFormat = GL_RGBA16F_ARB; pixelFormat = GL_RGBA; @@ -3648,8 +3334,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_R32F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_R32F; pixelFormat = GL_RED; @@ -3657,8 +3342,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_G32R32F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_rg)) { supported = true; internalFormat = GL_RG32F; pixelFormat = GL_RG; @@ -3666,8 +3350,7 @@ bool COpenGLDriver::getColorFormatParameters(ECOLOR_FORMAT format, GLint& intern } break; case ECF_A32B32G32R32F: - if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_float)) - { + if (queryOpenGLFeature(COpenGLExtensionHandler::IRR_ARB_texture_float)) { supported = true; internalFormat = GL_RGBA32F_ARB; pixelFormat = GL_RGBA; @@ -3691,17 +3374,16 @@ void COpenGLDriver::setFixedPipelineState(COpenGLDriver::E_OPENGL_FIXED_PIPELINE FixedPipelineState = state; } -const SMaterial& COpenGLDriver::getCurrentMaterial() const +const SMaterial &COpenGLDriver::getCurrentMaterial() const { return Material; } -COpenGLCacheHandler* COpenGLDriver::getCacheHandler() const +COpenGLCacheHandler *COpenGLDriver::getCacheHandler() const { return CacheHandler; } - } // end namespace } // end namespace @@ -3712,24 +3394,21 @@ namespace irr namespace video { - IVideoDriver* createOpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { +IVideoDriver *createOpenGLDriver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ #ifdef _IRR_COMPILE_WITH_OPENGL_ - COpenGLDriver* ogl = new COpenGLDriver(params, io, contextManager); + COpenGLDriver *ogl = new COpenGLDriver(params, io, contextManager); - if (!ogl->initDriver()) - { - ogl->drop(); - ogl = 0; - } - - return ogl; -#else - return 0; -#endif + if (!ogl->initDriver()) { + ogl->drop(); + ogl = 0; } + return ogl; +#else + return 0; +#endif +} + } // end namespace } // end namespace - - diff --git a/source/Irrlicht/COpenGLDriver.h b/source/Irrlicht/COpenGLDriver.h index 4cb7d40f..9618e5c1 100644 --- a/source/Irrlicht/COpenGLDriver.h +++ b/source/Irrlicht/COpenGLDriver.h @@ -8,10 +8,10 @@ namespace irr { - class CIrrDeviceWin32; - class CIrrDeviceLinux; - class CIrrDeviceSDL; - class CIrrDeviceMacOSX; +class CIrrDeviceWin32; +class CIrrDeviceLinux; +class CIrrDeviceSDL; +class CIrrDeviceMacOSX; } #ifdef _IRR_COMPILE_WITH_OPENGL_ @@ -27,412 +27,411 @@ namespace irr namespace video { - class IContextManager; +class IContextManager; - class COpenGLDriver : public CNullDriver, public IMaterialRendererServices, public COpenGLExtensionHandler +class COpenGLDriver : public CNullDriver, public IMaterialRendererServices, public COpenGLExtensionHandler +{ +public: + // Information about state of fixed pipeline activity. + enum E_OPENGL_FIXED_PIPELINE_STATE { - public: - // Information about state of fixed pipeline activity. - enum E_OPENGL_FIXED_PIPELINE_STATE - { - EOFPS_ENABLE = 0, // fixed pipeline. - EOFPS_DISABLE, // programmable pipeline. - EOFPS_ENABLE_TO_DISABLE, // switch from fixed to programmable pipeline. - EOFPS_DISABLE_TO_ENABLE // switch from programmable to fixed pipeline. - }; + EOFPS_ENABLE = 0, // fixed pipeline. + EOFPS_DISABLE, // programmable pipeline. + EOFPS_ENABLE_TO_DISABLE, // switch from fixed to programmable pipeline. + EOFPS_DISABLE_TO_ENABLE // switch from programmable to fixed pipeline. + }; - COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); + COpenGLDriver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); - bool initDriver(); + bool initDriver(); - //! destructor - virtual ~COpenGLDriver(); + //! destructor + virtual ~COpenGLDriver(); - virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255,0,0,0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; + virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) override; - bool endScene() override; + bool endScene() override; - //! sets transformation - void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; + //! sets transformation + void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) override; + struct SHWBufferLink_opengl : public SHWBufferLink + { + SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer) : + SHWBufferLink(_MeshBuffer), vbo_verticesID(0), vbo_indicesID(0) {} - struct SHWBufferLink_opengl : public SHWBufferLink - { - SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer): SHWBufferLink(_MeshBuffer), vbo_verticesID(0),vbo_indicesID(0){} + GLuint vbo_verticesID; // tmp + GLuint vbo_indicesID; // tmp - GLuint vbo_verticesID; //tmp - GLuint vbo_indicesID; //tmp + GLuint vbo_verticesSize; // tmp + GLuint vbo_indicesSize; // tmp + }; - GLuint vbo_verticesSize; //tmp - GLuint vbo_indicesSize; //tmp - }; + //! updates hardware buffer if needed + bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; - //! updates hardware buffer if needed - bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; + //! Create hardware buffer from mesh + SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer *mb) override; - //! Create hardware buffer from mesh - SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) override; + //! Delete hardware buffer (only some drivers can) + void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - //! Delete hardware buffer (only some drivers can) - void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; + //! Draw hardware buffer + void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - //! Draw hardware buffer - void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; + //! Create occlusion query. + /** Use node for identification and mesh for occlusion test. */ + virtual void addOcclusionQuery(scene::ISceneNode *node, + const scene::IMesh *mesh = 0) override; - //! Create occlusion query. - /** Use node for identification and mesh for occlusion test. */ - virtual void addOcclusionQuery(scene::ISceneNode* node, - const scene::IMesh* mesh=0) override; + //! Remove occlusion query. + void removeOcclusionQuery(scene::ISceneNode *node) override; - //! Remove occlusion query. - void removeOcclusionQuery(scene::ISceneNode* node) override; + //! Run occlusion query. Draws mesh stored in query. + /** If the mesh shall not be rendered visible, use + overrideMaterial to disable the color and depth buffer. */ + void runOcclusionQuery(scene::ISceneNode *node, bool visible = false) override; - //! Run occlusion query. Draws mesh stored in query. - /** If the mesh shall not be rendered visible, use - overrideMaterial to disable the color and depth buffer. */ - void runOcclusionQuery(scene::ISceneNode* node, bool visible=false) override; + //! Update occlusion query. Retrieves results from GPU. + /** If the query shall not block, set the flag to false. + Update might not occur in this case, though */ + void updateOcclusionQuery(scene::ISceneNode *node, bool block = true) override; - //! Update occlusion query. Retrieves results from GPU. - /** If the query shall not block, set the flag to false. - Update might not occur in this case, though */ - void updateOcclusionQuery(scene::ISceneNode* node, bool block=true) override; + //! Return query result. + /** Return value is the number of visible pixels/fragments. + The value is a safe approximation, i.e. can be larger then the + actual value of pixels. */ + u32 getOcclusionQueryResult(scene::ISceneNode *node) const override; - //! Return query result. - /** Return value is the number of visible pixels/fragments. - The value is a safe approximation, i.e. can be larger then the - actual value of pixels. */ - u32 getOcclusionQueryResult(scene::ISceneNode* node) const override; + //! Create render target. + IRenderTarget *addRenderTarget() override; - //! Create render target. - IRenderTarget* addRenderTarget() override; + //! draws a vertex primitive list + virtual void drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - //! draws a vertex primitive list - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; + //! draws a vertex primitive list in 2d + virtual void draw2DVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - //! draws a vertex primitive list in 2d - virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; + //! queries the features of the driver, returns true if feature is available + bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override + { + return FeatureEnabled[feature] && COpenGLExtensionHandler::queryFeature(feature); + } - //! queries the features of the driver, returns true if feature is available - bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override - { - return FeatureEnabled[feature] && COpenGLExtensionHandler::queryFeature(feature); - } + //! Disable a feature of the driver. + void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag = true) override; - //! Disable a feature of the driver. - void disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag=true) override; + //! Sets a material. All 3d drawing functions draw geometry now + //! using this material. + //! \param material: Material to be used from now on. + void setMaterial(const SMaterial &material) override; - //! Sets a material. All 3d drawing functions draw geometry now - //! using this material. - //! \param material: Material to be used from now on. - void setMaterial(const SMaterial& material) override; - - virtual void draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect = 0, + virtual void draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect = 0, SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect = 0, - const video::SColor* const colors = 0, bool useAlphaChannelOfTexture = false) override; + virtual void draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect = 0, + const video::SColor *const colors = 0, bool useAlphaChannelOfTexture = false) override; - // Explicitly bring in base class methods, otherwise - // this overload would hide them. - using CNullDriver::draw2DImage; - virtual void draw2DImage(const video::ITexture* texture, u32 layer, bool flip); + // Explicitly bring in base class methods, otherwise + // this overload would hide them. + using CNullDriver::draw2DImage; + virtual void draw2DImage(const video::ITexture *texture, u32 layer, bool flip); - //! draws a set of 2d images, using a color and the alpha channel of the - //! texture if desired. - void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) override; + //! draws a set of 2d images, using a color and the alpha channel of the + //! texture if desired. + void draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, + bool useAlphaChannelOfTexture) override; - //! draw an 2d rectangle - virtual void draw2DRectangle(SColor color, const core::rect& pos, - const core::rect* clip = 0) override; + //! draw an 2d rectangle + virtual void draw2DRectangle(SColor color, const core::rect &pos, + const core::rect *clip = 0) override; - //!Draws an 2d rectangle with a gradient. - virtual void draw2DRectangle(const core::rect& pos, + //! Draws an 2d rectangle with a gradient. + virtual void draw2DRectangle(const core::rect &pos, SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip = 0) override; + const core::rect *clip = 0) override; - //! Draws a 2d line. - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color=SColor(255,255,255,255)) override; + //! Draws a 2d line. + virtual void draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! Draws a 3d box - void draw3DBox( const core::aabbox3d& box, SColor color = SColor(255,255,255,255 ) ) override; + //! Draws a 3d box + void draw3DBox(const core::aabbox3d &box, SColor color = SColor(255, 255, 255, 255)) override; - //! Draws a 3d line. - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, - SColor color = SColor(255,255,255,255)) override; + //! Draws a 3d line. + virtual void draw3DLine(const core::vector3df &start, + const core::vector3df &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! \return Returns the name of the video driver. Example: In case of the Direct3D8 - //! driver, it would return "Direct3D8.1". - const char* getName() const override; + //! \return Returns the name of the video driver. Example: In case of the Direct3D8 + //! driver, it would return "Direct3D8.1". + const char *getName() const override; - //! Sets the dynamic ambient light color. The default color is - //! (0,0,0,0) which means it is dark. - //! \param color: New color of the ambient light. - void setAmbientLight(const SColorf& color) override; + //! Sets the dynamic ambient light color. The default color is + //! (0,0,0,0) which means it is dark. + //! \param color: New color of the ambient light. + void setAmbientLight(const SColorf &color) override; - //! sets a viewport - void setViewPort(const core::rect& area) override; + //! sets a viewport + void setViewPort(const core::rect &area) override; - //! Sets the fog mode. - virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start, + //! Sets the fog mode. + virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, f32 density, bool pixelFog, bool rangeFog) override; - //! Only used by the internal engine. Used to notify the driver that - //! the window was resized. - void OnResize(const core::dimension2d& size) override; + //! Only used by the internal engine. Used to notify the driver that + //! the window was resized. + void OnResize(const core::dimension2d &size) override; - //! Returns type of video driver - E_DRIVER_TYPE getDriverType() const override; + //! Returns type of video driver + E_DRIVER_TYPE getDriverType() const override; - //! get color format of the current color buffer - ECOLOR_FORMAT getColorFormat() const override; + //! get color format of the current color buffer + ECOLOR_FORMAT getColorFormat() const override; - //! Returns the transformation set by setTransform - const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; + //! Returns the transformation set by setTransform + const core::matrix4 &getTransform(E_TRANSFORMATION_STATE state) const override; - //! Can be called by an IMaterialRenderer to make its work easier. - virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, + //! Can be called by an IMaterialRenderer to make its work easier. + virtual void setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, bool resetAllRenderstates) override; - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - virtual void setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates); + //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. + virtual void setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates); - //! Get a vertex shader constant index. - s32 getVertexShaderConstantID(const c8* name) override; + //! Get a vertex shader constant index. + s32 getVertexShaderConstantID(const c8 *name) override; - //! Get a pixel shader constant index. - s32 getPixelShaderConstantID(const c8* name) override; + //! Get a pixel shader constant index. + s32 getPixelShaderConstantID(const c8 *name) override; - //! Sets a constant for the vertex shader based on an index. - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; + //! Sets a constant for the vertex shader based on an index. + bool setVertexShaderConstant(s32 index, const f32 *floats, int count) override; - //! Int interface for the above. - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; + //! Int interface for the above. + bool setVertexShaderConstant(s32 index, const s32 *ints, int count) override; - //! Uint interface for the above. - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; + //! Uint interface for the above. + bool setVertexShaderConstant(s32 index, const u32 *ints, int count) override; - //! Sets a constant for the pixel shader based on an index. - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; + //! Sets a constant for the pixel shader based on an index. + bool setPixelShaderConstant(s32 index, const f32 *floats, int count) override; - //! Int interface for the above. - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; + //! Int interface for the above. + bool setPixelShaderConstant(s32 index, const s32 *ints, int count) override; - //! Uint interface for the above. - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + //! Uint interface for the above. + bool setPixelShaderConstant(s32 index, const u32 *ints, int count) override; - //! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled. - //! Returns whether disabling was successful or not. - bool disableTextures(u32 fromStage=0); + //! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled. + //! Returns whether disabling was successful or not. + bool disableTextures(u32 fromStage = 0); - //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. - virtual s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData = 0) override; + //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. + virtual s32 addHighLevelShaderMaterial( + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) override; - //! Returns a pointer to the IVideoDriver interface. (Implementation for - //! IMaterialRendererServices) - IVideoDriver* getVideoDriver() override; + //! Returns a pointer to the IVideoDriver interface. (Implementation for + //! IMaterialRendererServices) + IVideoDriver *getVideoDriver() override; - //! Returns the maximum amount of primitives (mostly vertices) which - //! the device is able to render with one drawIndexedTriangleList - //! call. - u32 getMaximalPrimitiveCount() const override; + //! Returns the maximum amount of primitives (mostly vertices) which + //! the device is able to render with one drawIndexedTriangleList + //! call. + u32 getMaximalPrimitiveCount() const override; - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + virtual ITexture *addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; - //! Creates a render target texture for a cubemap - ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) override; + //! Creates a render target texture for a cubemap + ITexture *addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name, const ECOLOR_FORMAT format) override; - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255,0,0,0), + virtual bool setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0) override; - void clearBuffers(u16 flag, SColor color = SColor(255,0,0,0), f32 depth = 1.f, u8 stencil = 0) override; + void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; - //! Returns an image created from the last rendered frame. - IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; + //! Returns an image created from the last rendered frame. + IImage *createScreenShot(video::ECOLOR_FORMAT format = video::ECF_UNKNOWN, video::E_RENDER_TARGET target = video::ERT_FRAME_BUFFER) override; - //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) - //! for performance reasons only available in debug mode - bool testGLError(int code=0); + //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) + //! for performance reasons only available in debug mode + bool testGLError(int code = 0); - //! Set/unset a clipping plane. - //! There are at least 6 clipping planes available for the user to set at will. - //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. - //! \param plane: The plane itself. - //! \param enable: If true, enable the clipping plane else disable it. - bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false) override; + //! Set/unset a clipping plane. + //! There are at least 6 clipping planes available for the user to set at will. + //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. + //! \param plane: The plane itself. + //! \param enable: If true, enable the clipping plane else disable it. + bool setClipPlane(u32 index, const core::plane3df &plane, bool enable = false) override; - //! Enable/disable a clipping plane. - //! There are at least 6 clipping planes available for the user to set at will. - //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. - //! \param enable: If true, enable the clipping plane else disable it. - void enableClipPlane(u32 index, bool enable) override; + //! Enable/disable a clipping plane. + //! There are at least 6 clipping planes available for the user to set at will. + //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. + //! \param enable: If true, enable the clipping plane else disable it. + void enableClipPlane(u32 index, bool enable) override; - //! Enable the 2d override material - void enableMaterial2D(bool enable=true) override; + //! Enable the 2d override material + void enableMaterial2D(bool enable = true) override; - //! Returns the graphics card vendor name. - core::stringc getVendorInfo() override {return VendorName;} + //! Returns the graphics card vendor name. + core::stringc getVendorInfo() override { return VendorName; } - //! Returns the maximum texture size supported. - core::dimension2du getMaxTextureSize() const override; + //! Returns the maximum texture size supported. + core::dimension2du getMaxTextureSize() const override; - //! Removes a texture from the texture cache and deletes it, freeing lot of memory. - void removeTexture(ITexture* texture) override; + //! Removes a texture from the texture cache and deletes it, freeing lot of memory. + void removeTexture(ITexture *texture) override; - //! Check if the driver supports creating textures with the given color format - bool queryTextureFormat(ECOLOR_FORMAT format) const override; + //! Check if the driver supports creating textures with the given color format + bool queryTextureFormat(ECOLOR_FORMAT format) const override; - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + bool needsTransparentRenderPass(const irr::video::SMaterial &material) const override; - //! Convert E_PRIMITIVE_TYPE to OpenGL equivalent - GLenum primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const; + //! Convert E_PRIMITIVE_TYPE to OpenGL equivalent + GLenum primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const; - //! Convert E_BLEND_FACTOR to OpenGL equivalent - GLenum getGLBlend(E_BLEND_FACTOR factor) const; + //! Convert E_BLEND_FACTOR to OpenGL equivalent + GLenum getGLBlend(E_BLEND_FACTOR factor) const; - //! Get ZBuffer bits. - GLenum getZBufferBits() const; + //! Get ZBuffer bits. + GLenum getZBufferBits() const; - bool getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const; + bool getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const; - //! Return info about fixed pipeline state. - E_OPENGL_FIXED_PIPELINE_STATE getFixedPipelineState() const; + //! Return info about fixed pipeline state. + E_OPENGL_FIXED_PIPELINE_STATE getFixedPipelineState() const; - //! Set info about fixed pipeline state. - void setFixedPipelineState(E_OPENGL_FIXED_PIPELINE_STATE state); + //! Set info about fixed pipeline state. + void setFixedPipelineState(E_OPENGL_FIXED_PIPELINE_STATE state); - //! Get current material. - const SMaterial& getCurrentMaterial() const; + //! Get current material. + const SMaterial &getCurrentMaterial() const; - COpenGLCacheHandler* getCacheHandler() const; + COpenGLCacheHandler *getCacheHandler() const; - private: +private: + bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + void uploadClipPlane(u32 index); - void uploadClipPlane(u32 index); + //! inits the parts of the open gl driver used on all platforms + bool genericDriverInit(); - //! inits the parts of the open gl driver used on all platforms - bool genericDriverInit(); + ITexture *createDeviceDependentTexture(const io::path &name, IImage *image) override; - ITexture* createDeviceDependentTexture(const io::path& name, IImage* image) override; + ITexture *createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) override; - ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) override; + //! creates a transposed matrix in supplied GLfloat array to pass to OpenGL + inline void getGLMatrix(GLfloat gl_matrix[16], const core::matrix4 &m); + inline void getGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4 &m); - //! creates a transposed matrix in supplied GLfloat array to pass to OpenGL - inline void getGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m); - inline void getGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4& m); + //! get native wrap mode value + GLint getTextureWrapMode(const u8 clamp); - //! get native wrap mode value - GLint getTextureWrapMode(const u8 clamp); + //! sets the needed renderstates + void setRenderStates3DMode(); - //! sets the needed renderstates - void setRenderStates3DMode(); + //! sets the needed renderstates + void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); - //! sets the needed renderstates - void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); + void createMaterialRenderers(); - void createMaterialRenderers(); + //! Assign a hardware light to the specified requested light, if any + //! free hardware lights exist. + //! \param[in] lightIndex: the index of the requesting light + void assignHardwareLight(u32 lightIndex); - //! Assign a hardware light to the specified requested light, if any - //! free hardware lights exist. - //! \param[in] lightIndex: the index of the requesting light - void assignHardwareLight(u32 lightIndex); + //! helper function for render setup. + void getColorBuffer(const void *vertices, u32 vertexCount, E_VERTEX_TYPE vType); - //! helper function for render setup. - void getColorBuffer(const void* vertices, u32 vertexCount, E_VERTEX_TYPE vType); + //! helper function doing the actual rendering. + void renderArray(const void *indexList, u32 primitiveCount, + scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType); - //! helper function doing the actual rendering. - void renderArray(const void* indexList, u32 primitiveCount, - scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType); + //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` + virtual void setViewPortRaw(u32 width, u32 height); - //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` - virtual void setViewPortRaw(u32 width, u32 height); + COpenGLCacheHandler *CacheHandler; - COpenGLCacheHandler* CacheHandler; + core::stringc Name; + core::matrix4 Matrices[ETS_COUNT]; + core::array ColorBuffer; - core::stringc Name; - core::matrix4 Matrices[ETS_COUNT]; - core::array ColorBuffer; - - //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. - enum E_RENDER_MODE - { - ERM_NONE = 0, // no render state has been set yet. - ERM_2D, // 2d drawing rendermode - ERM_3D // 3d rendering mode - }; - - E_RENDER_MODE CurrentRenderMode; - //! bool to make all renderstates reset if set to true. - bool ResetRenderStates; - bool Transformation3DChanged; - u8 AntiAlias; - - SMaterial Material, LastMaterial; - - struct SUserClipPlane - { - SUserClipPlane() : Enabled(false) {} - core::plane3df Plane; - bool Enabled; - }; - core::array UserClipPlanes; - - core::stringc VendorName; - - core::matrix4 TextureFlipMatrix; - - //! Color buffer format - ECOLOR_FORMAT ColorFormat; - - E_OPENGL_FIXED_PIPELINE_STATE FixedPipelineState; - - SIrrlichtCreationParameters Params; - - //! Built-in 2D quad for 2D rendering. - S3DVertex Quad2DVertices[4]; - static const u16 Quad2DIndices[4]; - - IContextManager* ContextManager; + //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. + enum E_RENDER_MODE + { + ERM_NONE = 0, // no render state has been set yet. + ERM_2D, // 2d drawing rendermode + ERM_3D // 3d rendering mode }; + E_RENDER_MODE CurrentRenderMode; + //! bool to make all renderstates reset if set to true. + bool ResetRenderStates; + bool Transformation3DChanged; + u8 AntiAlias; + + SMaterial Material, LastMaterial; + + struct SUserClipPlane + { + SUserClipPlane() : + Enabled(false) {} + core::plane3df Plane; + bool Enabled; + }; + core::array UserClipPlanes; + + core::stringc VendorName; + + core::matrix4 TextureFlipMatrix; + + //! Color buffer format + ECOLOR_FORMAT ColorFormat; + + E_OPENGL_FIXED_PIPELINE_STATE FixedPipelineState; + + SIrrlichtCreationParameters Params; + + //! Built-in 2D quad for 2D rendering. + S3DVertex Quad2DVertices[4]; + static const u16 Quad2DIndices[4]; + + IContextManager *ContextManager; +}; + } // end namespace video } // end namespace irr - #endif // _IRR_COMPILE_WITH_OPENGL_ diff --git a/source/Irrlicht/COpenGLExtensionHandler.cpp b/source/Irrlicht/COpenGLExtensionHandler.cpp index 08d1b802..d5aade12 100644 --- a/source/Irrlicht/COpenGLExtensionHandler.cpp +++ b/source/Irrlicht/COpenGLExtensionHandler.cpp @@ -23,140 +23,135 @@ COpenGLExtensionHandler::COpenGLExtensionHandler() : MaxAnisotropy(1), MaxUserClipPlanes(0), MaxAuxBuffers(0), MaxIndices(65535), MaxTextureSize(1), MaxGeometryVerticesOut(0), MaxTextureLODBias(0.f), Version(0), ShaderLanguageVersion(0), - OcclusionQuerySupport(false), IsAtiRadeonX(false) - ,pGlActiveTexture(0) - ,pGlActiveTextureARB(0), pGlClientActiveTextureARB(0), - pGlGenProgramsARB(0), pGlGenProgramsNV(0), - pGlBindProgramARB(0), pGlBindProgramNV(0), - pGlDeleteProgramsARB(0), pGlDeleteProgramsNV(0), - pGlProgramStringARB(0), pGlLoadProgramNV(0), - pGlProgramLocalParameter4fvARB(0), - pGlCreateShaderObjectARB(0), pGlShaderSourceARB(0), - pGlCompileShaderARB(0), pGlCreateProgramObjectARB(0), pGlAttachObjectARB(0), - pGlLinkProgramARB(0), pGlUseProgramObjectARB(0), pGlDeleteObjectARB(0), - pGlCreateProgram(0), pGlUseProgram(0), - pGlDeleteProgram(0), pGlDeleteShader(0), - pGlGetAttachedObjectsARB(0), pGlGetAttachedShaders(0), - pGlCreateShader(0), pGlShaderSource(0), pGlCompileShader(0), - pGlAttachShader(0), pGlLinkProgram(0), - pGlGetInfoLogARB(0), pGlGetShaderInfoLog(0), pGlGetProgramInfoLog(0), - pGlGetObjectParameterivARB(0), pGlGetShaderiv(0), pGlGetProgramiv(0), - pGlGetUniformLocationARB(0), pGlGetUniformLocation(0), - pGlUniform1fvARB(0), pGlUniform2fvARB(0), pGlUniform3fvARB(0), pGlUniform4fvARB(0), - pGlUniform1ivARB(0), pGlUniform2ivARB(0), pGlUniform3ivARB(0), pGlUniform4ivARB(0), - pGlUniform1uiv(0), pGlUniform2uiv(0), pGlUniform3uiv(0), pGlUniform4uiv(0), - pGlUniformMatrix2fvARB(0), pGlUniformMatrix2x3fv(0), pGlUniformMatrix2x4fv(0), - pGlUniformMatrix3x2fv(0), pGlUniformMatrix3fvARB(0), pGlUniformMatrix3x4fv(0), - pGlUniformMatrix4x2fv(0), pGlUniformMatrix4x3fv(0), pGlUniformMatrix4fvARB(0), - pGlGetActiveUniformARB(0), pGlGetActiveUniform(0), - pGlPointParameterfARB(0), pGlPointParameterfvARB(0), - pGlStencilFuncSeparate(0), pGlStencilOpSeparate(0), - pGlStencilFuncSeparateATI(0), pGlStencilOpSeparateATI(0), - pGlCompressedTexImage2D(0), pGlCompressedTexSubImage2D(0), - // ARB framebuffer object - pGlBindFramebuffer(0), pGlDeleteFramebuffers(0), pGlGenFramebuffers(0), - pGlCheckFramebufferStatus(0), pGlFramebufferTexture2D(0), - pGlBindRenderbuffer(0), pGlDeleteRenderbuffers(0), pGlGenRenderbuffers(0), - pGlRenderbufferStorage(0), pGlFramebufferRenderbuffer(0), pGlGenerateMipmap(0), - // EXT framebuffer object - pGlBindFramebufferEXT(0), pGlDeleteFramebuffersEXT(0), pGlGenFramebuffersEXT(0), - pGlCheckFramebufferStatusEXT(0), pGlFramebufferTexture2DEXT(0), - pGlBindRenderbufferEXT(0), pGlDeleteRenderbuffersEXT(0), pGlGenRenderbuffersEXT(0), - pGlRenderbufferStorageEXT(0), pGlFramebufferRenderbufferEXT(0), pGlGenerateMipmapEXT(0), - pGlActiveStencilFaceEXT(0), - // MRTs - pGlDrawBuffersARB(0), pGlDrawBuffersATI(0), - pGlGenBuffersARB(0), pGlBindBufferARB(0), pGlBufferDataARB(0), pGlDeleteBuffersARB(0), - pGlBufferSubDataARB(0), pGlGetBufferSubDataARB(0), pGlMapBufferARB(0), pGlUnmapBufferARB(0), - pGlIsBufferARB(0), pGlGetBufferParameterivARB(0), pGlGetBufferPointervARB(0), - pGlProvokingVertexARB(0), pGlProvokingVertexEXT(0), - pGlProgramParameteriARB(0), pGlProgramParameteriEXT(0), - pGlGenQueriesARB(0), pGlDeleteQueriesARB(0), pGlIsQueryARB(0), - pGlBeginQueryARB(0), pGlEndQueryARB(0), pGlGetQueryivARB(0), - pGlGetQueryObjectivARB(0), pGlGetQueryObjectuivARB(0), - pGlGenOcclusionQueriesNV(0), pGlDeleteOcclusionQueriesNV(0), - pGlIsOcclusionQueryNV(0), pGlBeginOcclusionQueryNV(0), - pGlEndOcclusionQueryNV(0), pGlGetOcclusionQueryivNV(0), - pGlGetOcclusionQueryuivNV(0), - // Blend - pGlBlendFuncSeparateEXT(0), pGlBlendFuncSeparate(0), - pGlBlendEquationEXT(0), pGlBlendEquation(0), pGlBlendEquationSeparateEXT(0), pGlBlendEquationSeparate(0), - // Indexed - pGlEnableIndexedEXT(0), pGlDisableIndexedEXT(0), - pGlColorMaskIndexedEXT(0), - pGlBlendFuncIndexedAMD(0), pGlBlendFunciARB(0), pGlBlendFuncSeparateIndexedAMD(0), pGlBlendFuncSeparateiARB(0), - pGlBlendEquationIndexedAMD(0), pGlBlendEquationiARB(0), pGlBlendEquationSeparateIndexedAMD(0), pGlBlendEquationSeparateiARB(0), - // DSA - pGlTextureStorage2D(0), pGlTextureStorage3D(0), pGlTextureSubImage2D(0), pGlGetTextureImage(0), pGlNamedFramebufferTexture(0), - pGlTextureParameteri(0), pGlTextureParameterf(0), pGlTextureParameteriv(0), pGlTextureParameterfv(0), - pGlCreateTextures(0), pGlCreateFramebuffers(0), pGlBindTextures(0), pGlGenerateTextureMipmap(0), - // DSA with EXT or functions to simulate it - pGlTextureStorage2DEXT(0), pGlTexStorage2D(0), pGlTextureStorage3DEXT(0), pGlTexStorage3D(0), pGlTextureSubImage2DEXT(0), pGlGetTextureImageEXT(0), - pGlNamedFramebufferTextureEXT(0), pGlFramebufferTexture(0), pGlGenerateTextureMipmapEXT(0) + OcclusionQuerySupport(false), IsAtiRadeonX(false), pGlActiveTexture(0), pGlActiveTextureARB(0), pGlClientActiveTextureARB(0), + pGlGenProgramsARB(0), pGlGenProgramsNV(0), + pGlBindProgramARB(0), pGlBindProgramNV(0), + pGlDeleteProgramsARB(0), pGlDeleteProgramsNV(0), + pGlProgramStringARB(0), pGlLoadProgramNV(0), + pGlProgramLocalParameter4fvARB(0), + pGlCreateShaderObjectARB(0), pGlShaderSourceARB(0), + pGlCompileShaderARB(0), pGlCreateProgramObjectARB(0), pGlAttachObjectARB(0), + pGlLinkProgramARB(0), pGlUseProgramObjectARB(0), pGlDeleteObjectARB(0), + pGlCreateProgram(0), pGlUseProgram(0), + pGlDeleteProgram(0), pGlDeleteShader(0), + pGlGetAttachedObjectsARB(0), pGlGetAttachedShaders(0), + pGlCreateShader(0), pGlShaderSource(0), pGlCompileShader(0), + pGlAttachShader(0), pGlLinkProgram(0), + pGlGetInfoLogARB(0), pGlGetShaderInfoLog(0), pGlGetProgramInfoLog(0), + pGlGetObjectParameterivARB(0), pGlGetShaderiv(0), pGlGetProgramiv(0), + pGlGetUniformLocationARB(0), pGlGetUniformLocation(0), + pGlUniform1fvARB(0), pGlUniform2fvARB(0), pGlUniform3fvARB(0), pGlUniform4fvARB(0), + pGlUniform1ivARB(0), pGlUniform2ivARB(0), pGlUniform3ivARB(0), pGlUniform4ivARB(0), + pGlUniform1uiv(0), pGlUniform2uiv(0), pGlUniform3uiv(0), pGlUniform4uiv(0), + pGlUniformMatrix2fvARB(0), pGlUniformMatrix2x3fv(0), pGlUniformMatrix2x4fv(0), + pGlUniformMatrix3x2fv(0), pGlUniformMatrix3fvARB(0), pGlUniformMatrix3x4fv(0), + pGlUniformMatrix4x2fv(0), pGlUniformMatrix4x3fv(0), pGlUniformMatrix4fvARB(0), + pGlGetActiveUniformARB(0), pGlGetActiveUniform(0), + pGlPointParameterfARB(0), pGlPointParameterfvARB(0), + pGlStencilFuncSeparate(0), pGlStencilOpSeparate(0), + pGlStencilFuncSeparateATI(0), pGlStencilOpSeparateATI(0), + pGlCompressedTexImage2D(0), pGlCompressedTexSubImage2D(0), + // ARB framebuffer object + pGlBindFramebuffer(0), pGlDeleteFramebuffers(0), pGlGenFramebuffers(0), + pGlCheckFramebufferStatus(0), pGlFramebufferTexture2D(0), + pGlBindRenderbuffer(0), pGlDeleteRenderbuffers(0), pGlGenRenderbuffers(0), + pGlRenderbufferStorage(0), pGlFramebufferRenderbuffer(0), pGlGenerateMipmap(0), + // EXT framebuffer object + pGlBindFramebufferEXT(0), pGlDeleteFramebuffersEXT(0), pGlGenFramebuffersEXT(0), + pGlCheckFramebufferStatusEXT(0), pGlFramebufferTexture2DEXT(0), + pGlBindRenderbufferEXT(0), pGlDeleteRenderbuffersEXT(0), pGlGenRenderbuffersEXT(0), + pGlRenderbufferStorageEXT(0), pGlFramebufferRenderbufferEXT(0), pGlGenerateMipmapEXT(0), + pGlActiveStencilFaceEXT(0), + // MRTs + pGlDrawBuffersARB(0), pGlDrawBuffersATI(0), + pGlGenBuffersARB(0), pGlBindBufferARB(0), pGlBufferDataARB(0), pGlDeleteBuffersARB(0), + pGlBufferSubDataARB(0), pGlGetBufferSubDataARB(0), pGlMapBufferARB(0), pGlUnmapBufferARB(0), + pGlIsBufferARB(0), pGlGetBufferParameterivARB(0), pGlGetBufferPointervARB(0), + pGlProvokingVertexARB(0), pGlProvokingVertexEXT(0), + pGlProgramParameteriARB(0), pGlProgramParameteriEXT(0), + pGlGenQueriesARB(0), pGlDeleteQueriesARB(0), pGlIsQueryARB(0), + pGlBeginQueryARB(0), pGlEndQueryARB(0), pGlGetQueryivARB(0), + pGlGetQueryObjectivARB(0), pGlGetQueryObjectuivARB(0), + pGlGenOcclusionQueriesNV(0), pGlDeleteOcclusionQueriesNV(0), + pGlIsOcclusionQueryNV(0), pGlBeginOcclusionQueryNV(0), + pGlEndOcclusionQueryNV(0), pGlGetOcclusionQueryivNV(0), + pGlGetOcclusionQueryuivNV(0), + // Blend + pGlBlendFuncSeparateEXT(0), pGlBlendFuncSeparate(0), + pGlBlendEquationEXT(0), pGlBlendEquation(0), pGlBlendEquationSeparateEXT(0), pGlBlendEquationSeparate(0), + // Indexed + pGlEnableIndexedEXT(0), pGlDisableIndexedEXT(0), + pGlColorMaskIndexedEXT(0), + pGlBlendFuncIndexedAMD(0), pGlBlendFunciARB(0), pGlBlendFuncSeparateIndexedAMD(0), pGlBlendFuncSeparateiARB(0), + pGlBlendEquationIndexedAMD(0), pGlBlendEquationiARB(0), pGlBlendEquationSeparateIndexedAMD(0), pGlBlendEquationSeparateiARB(0), + // DSA + pGlTextureStorage2D(0), pGlTextureStorage3D(0), pGlTextureSubImage2D(0), pGlGetTextureImage(0), pGlNamedFramebufferTexture(0), + pGlTextureParameteri(0), pGlTextureParameterf(0), pGlTextureParameteriv(0), pGlTextureParameterfv(0), + pGlCreateTextures(0), pGlCreateFramebuffers(0), pGlBindTextures(0), pGlGenerateTextureMipmap(0), + // DSA with EXT or functions to simulate it + pGlTextureStorage2DEXT(0), pGlTexStorage2D(0), pGlTextureStorage3DEXT(0), pGlTexStorage3D(0), pGlTextureSubImage2DEXT(0), pGlGetTextureImageEXT(0), + pGlNamedFramebufferTextureEXT(0), pGlFramebufferTexture(0), pGlGenerateTextureMipmapEXT(0) #if defined(GLX_SGI_swap_control) - ,pGlxSwapIntervalSGI(0) + , + pGlxSwapIntervalSGI(0) #endif #if defined(GLX_EXT_swap_control) - ,pGlxSwapIntervalEXT(0) + , + pGlxSwapIntervalEXT(0) #endif #if defined(WGL_EXT_swap_control) - ,pWglSwapIntervalEXT(0) + , + pWglSwapIntervalEXT(0) #endif #if defined(GLX_MESA_swap_control) - ,pGlxSwapIntervalMESA(0) + , + pGlxSwapIntervalMESA(0) #endif { - for (u32 i=0; i(glGetString(GL_VERSION))); - Version = static_cast(core::floor32(ogl_ver)*100+core::round32(core::fract(ogl_ver)*10.0f)); - if ( Version >= 102) + const f32 ogl_ver = core::fast_atof(reinterpret_cast(glGetString(GL_VERSION))); + Version = static_cast(core::floor32(ogl_ver) * 100 + core::round32(core::fract(ogl_ver) * 10.0f)); + if (Version >= 102) os::Printer::log("OpenGL driver version is 1.2 or better.", ELL_INFORMATION); else os::Printer::log("OpenGL driver version is not 1.2 or better.", ELL_WARNING); { - const char* t = reinterpret_cast(glGetString(GL_EXTENSIONS)); + const char *t = reinterpret_cast(glGetString(GL_EXTENSIONS)); size_t len = 0; c8 *str = 0; - if (t) - { + if (t) { len = strlen(t); - str = new c8[len+1]; + str = new c8[len + 1]; } - c8* p = str; + c8 *p = str; - for (size_t i=0; i(t[i]); - if (str[i] == ' ') - { + if (str[i] == ' ') { str[i] = 0; - for (u32 j=0; jgetProcAddress(x) +#define IRR_OGL_LOAD_EXTENSION(x) cmgr->getProcAddress(x) // get multitexturing function pointers - pGlActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) IRR_OGL_LOAD_EXTENSION("glActiveTextureARB"); - pGlClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC) IRR_OGL_LOAD_EXTENSION("glClientActiveTextureARB"); + pGlActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)IRR_OGL_LOAD_EXTENSION("glActiveTextureARB"); + pGlClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)IRR_OGL_LOAD_EXTENSION("glClientActiveTextureARB"); // get fragment and vertex program function pointers - pGlGenProgramsARB = (PFNGLGENPROGRAMSARBPROC) IRR_OGL_LOAD_EXTENSION("glGenProgramsARB"); - pGlGenProgramsNV = (PFNGLGENPROGRAMSNVPROC) IRR_OGL_LOAD_EXTENSION("glGenProgramsNV"); - pGlBindProgramARB = (PFNGLBINDPROGRAMARBPROC) IRR_OGL_LOAD_EXTENSION("glBindProgramARB"); - pGlBindProgramNV = (PFNGLBINDPROGRAMNVPROC) IRR_OGL_LOAD_EXTENSION("glBindProgramNV"); - pGlProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC) IRR_OGL_LOAD_EXTENSION("glProgramStringARB"); - pGlLoadProgramNV = (PFNGLLOADPROGRAMNVPROC) IRR_OGL_LOAD_EXTENSION("glLoadProgramNV"); - pGlDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC) IRR_OGL_LOAD_EXTENSION("glDeleteProgramsARB"); - pGlDeleteProgramsNV = (PFNGLDELETEPROGRAMSNVPROC) IRR_OGL_LOAD_EXTENSION("glDeleteProgramsNV"); - pGlProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) IRR_OGL_LOAD_EXTENSION("glProgramLocalParameter4fvARB"); - pGlCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC) IRR_OGL_LOAD_EXTENSION("glCreateShaderObjectARB"); - pGlCreateShader = (PFNGLCREATESHADERPROC) IRR_OGL_LOAD_EXTENSION("glCreateShader"); - pGlShaderSourceARB = (PFNGLSHADERSOURCEARBPROC) IRR_OGL_LOAD_EXTENSION("glShaderSourceARB"); - pGlShaderSource = (PFNGLSHADERSOURCEPROC) IRR_OGL_LOAD_EXTENSION("glShaderSource"); - pGlCompileShaderARB = (PFNGLCOMPILESHADERARBPROC) IRR_OGL_LOAD_EXTENSION("glCompileShaderARB"); - pGlCompileShader = (PFNGLCOMPILESHADERPROC) IRR_OGL_LOAD_EXTENSION("glCompileShader"); - pGlCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC) IRR_OGL_LOAD_EXTENSION("glCreateProgramObjectARB"); - pGlCreateProgram = (PFNGLCREATEPROGRAMPROC) IRR_OGL_LOAD_EXTENSION("glCreateProgram"); - pGlAttachObjectARB = (PFNGLATTACHOBJECTARBPROC) IRR_OGL_LOAD_EXTENSION("glAttachObjectARB"); - pGlAttachShader = (PFNGLATTACHSHADERPROC) IRR_OGL_LOAD_EXTENSION("glAttachShader"); - pGlLinkProgramARB = (PFNGLLINKPROGRAMARBPROC) IRR_OGL_LOAD_EXTENSION("glLinkProgramARB"); - pGlLinkProgram = (PFNGLLINKPROGRAMPROC) IRR_OGL_LOAD_EXTENSION("glLinkProgram"); - pGlUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC) IRR_OGL_LOAD_EXTENSION("glUseProgramObjectARB"); - pGlUseProgram = (PFNGLUSEPROGRAMPROC) IRR_OGL_LOAD_EXTENSION("glUseProgram"); - pGlDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC) IRR_OGL_LOAD_EXTENSION("glDeleteObjectARB"); - pGlDeleteProgram = (PFNGLDELETEPROGRAMPROC) IRR_OGL_LOAD_EXTENSION("glDeleteProgram"); - pGlDeleteShader = (PFNGLDELETESHADERPROC) IRR_OGL_LOAD_EXTENSION("glDeleteShader"); - pGlGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC) IRR_OGL_LOAD_EXTENSION("glGetAttachedShaders"); - pGlGetAttachedObjectsARB = (PFNGLGETATTACHEDOBJECTSARBPROC) IRR_OGL_LOAD_EXTENSION("glGetAttachedObjectsARB"); - pGlGetInfoLogARB = (PFNGLGETINFOLOGARBPROC) IRR_OGL_LOAD_EXTENSION("glGetInfoLogARB"); - pGlGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) IRR_OGL_LOAD_EXTENSION("glGetShaderInfoLog"); - pGlGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) IRR_OGL_LOAD_EXTENSION("glGetProgramInfoLog"); - pGlGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetObjectParameterivARB"); - pGlGetShaderiv = (PFNGLGETSHADERIVPROC) IRR_OGL_LOAD_EXTENSION("glGetShaderiv"); - pGlGetProgramiv = (PFNGLGETPROGRAMIVPROC) IRR_OGL_LOAD_EXTENSION("glGetProgramiv"); - pGlGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC) IRR_OGL_LOAD_EXTENSION("glGetUniformLocationARB"); - pGlGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) IRR_OGL_LOAD_EXTENSION("glGetUniformLocation"); - pGlUniform1fvARB = (PFNGLUNIFORM1FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform1fvARB"); - pGlUniform2fvARB = (PFNGLUNIFORM2FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform2fvARB"); - pGlUniform3fvARB = (PFNGLUNIFORM3FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform3fvARB"); - pGlUniform4fvARB = (PFNGLUNIFORM4FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform4fvARB"); - pGlUniform1ivARB = (PFNGLUNIFORM1IVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform1ivARB"); - pGlUniform2ivARB = (PFNGLUNIFORM2IVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform2ivARB"); - pGlUniform3ivARB = (PFNGLUNIFORM3IVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform3ivARB"); - pGlUniform4ivARB = (PFNGLUNIFORM4IVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniform4ivARB"); - pGlUniform1uiv = (PFNGLUNIFORM1UIVPROC) IRR_OGL_LOAD_EXTENSION("glUniform1uiv"); - pGlUniform2uiv = (PFNGLUNIFORM2UIVPROC) IRR_OGL_LOAD_EXTENSION("glUniform2uiv"); - pGlUniform3uiv = (PFNGLUNIFORM3UIVPROC) IRR_OGL_LOAD_EXTENSION("glUniform3uiv"); - pGlUniform4uiv = (PFNGLUNIFORM4UIVPROC) IRR_OGL_LOAD_EXTENSION("glUniform4uiv"); - pGlUniformMatrix2fvARB = (PFNGLUNIFORMMATRIX2FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniformMatrix2fvARB"); - pGlUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC) IRR_OGL_LOAD_EXTENSION("glUniformMatrix2x3fv"); + pGlGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)IRR_OGL_LOAD_EXTENSION("glGenProgramsARB"); + pGlGenProgramsNV = (PFNGLGENPROGRAMSNVPROC)IRR_OGL_LOAD_EXTENSION("glGenProgramsNV"); + pGlBindProgramARB = (PFNGLBINDPROGRAMARBPROC)IRR_OGL_LOAD_EXTENSION("glBindProgramARB"); + pGlBindProgramNV = (PFNGLBINDPROGRAMNVPROC)IRR_OGL_LOAD_EXTENSION("glBindProgramNV"); + pGlProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)IRR_OGL_LOAD_EXTENSION("glProgramStringARB"); + pGlLoadProgramNV = (PFNGLLOADPROGRAMNVPROC)IRR_OGL_LOAD_EXTENSION("glLoadProgramNV"); + pGlDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)IRR_OGL_LOAD_EXTENSION("glDeleteProgramsARB"); + pGlDeleteProgramsNV = (PFNGLDELETEPROGRAMSNVPROC)IRR_OGL_LOAD_EXTENSION("glDeleteProgramsNV"); + pGlProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)IRR_OGL_LOAD_EXTENSION("glProgramLocalParameter4fvARB"); + pGlCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)IRR_OGL_LOAD_EXTENSION("glCreateShaderObjectARB"); + pGlCreateShader = (PFNGLCREATESHADERPROC)IRR_OGL_LOAD_EXTENSION("glCreateShader"); + pGlShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)IRR_OGL_LOAD_EXTENSION("glShaderSourceARB"); + pGlShaderSource = (PFNGLSHADERSOURCEPROC)IRR_OGL_LOAD_EXTENSION("glShaderSource"); + pGlCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)IRR_OGL_LOAD_EXTENSION("glCompileShaderARB"); + pGlCompileShader = (PFNGLCOMPILESHADERPROC)IRR_OGL_LOAD_EXTENSION("glCompileShader"); + pGlCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)IRR_OGL_LOAD_EXTENSION("glCreateProgramObjectARB"); + pGlCreateProgram = (PFNGLCREATEPROGRAMPROC)IRR_OGL_LOAD_EXTENSION("glCreateProgram"); + pGlAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)IRR_OGL_LOAD_EXTENSION("glAttachObjectARB"); + pGlAttachShader = (PFNGLATTACHSHADERPROC)IRR_OGL_LOAD_EXTENSION("glAttachShader"); + pGlLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)IRR_OGL_LOAD_EXTENSION("glLinkProgramARB"); + pGlLinkProgram = (PFNGLLINKPROGRAMPROC)IRR_OGL_LOAD_EXTENSION("glLinkProgram"); + pGlUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)IRR_OGL_LOAD_EXTENSION("glUseProgramObjectARB"); + pGlUseProgram = (PFNGLUSEPROGRAMPROC)IRR_OGL_LOAD_EXTENSION("glUseProgram"); + pGlDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)IRR_OGL_LOAD_EXTENSION("glDeleteObjectARB"); + pGlDeleteProgram = (PFNGLDELETEPROGRAMPROC)IRR_OGL_LOAD_EXTENSION("glDeleteProgram"); + pGlDeleteShader = (PFNGLDELETESHADERPROC)IRR_OGL_LOAD_EXTENSION("glDeleteShader"); + pGlGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)IRR_OGL_LOAD_EXTENSION("glGetAttachedShaders"); + pGlGetAttachedObjectsARB = (PFNGLGETATTACHEDOBJECTSARBPROC)IRR_OGL_LOAD_EXTENSION("glGetAttachedObjectsARB"); + pGlGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)IRR_OGL_LOAD_EXTENSION("glGetInfoLogARB"); + pGlGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)IRR_OGL_LOAD_EXTENSION("glGetShaderInfoLog"); + pGlGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)IRR_OGL_LOAD_EXTENSION("glGetProgramInfoLog"); + pGlGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetObjectParameterivARB"); + pGlGetShaderiv = (PFNGLGETSHADERIVPROC)IRR_OGL_LOAD_EXTENSION("glGetShaderiv"); + pGlGetProgramiv = (PFNGLGETPROGRAMIVPROC)IRR_OGL_LOAD_EXTENSION("glGetProgramiv"); + pGlGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)IRR_OGL_LOAD_EXTENSION("glGetUniformLocationARB"); + pGlGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)IRR_OGL_LOAD_EXTENSION("glGetUniformLocation"); + pGlUniform1fvARB = (PFNGLUNIFORM1FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform1fvARB"); + pGlUniform2fvARB = (PFNGLUNIFORM2FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform2fvARB"); + pGlUniform3fvARB = (PFNGLUNIFORM3FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform3fvARB"); + pGlUniform4fvARB = (PFNGLUNIFORM4FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform4fvARB"); + pGlUniform1ivARB = (PFNGLUNIFORM1IVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform1ivARB"); + pGlUniform2ivARB = (PFNGLUNIFORM2IVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform2ivARB"); + pGlUniform3ivARB = (PFNGLUNIFORM3IVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform3ivARB"); + pGlUniform4ivARB = (PFNGLUNIFORM4IVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniform4ivARB"); + pGlUniform1uiv = (PFNGLUNIFORM1UIVPROC)IRR_OGL_LOAD_EXTENSION("glUniform1uiv"); + pGlUniform2uiv = (PFNGLUNIFORM2UIVPROC)IRR_OGL_LOAD_EXTENSION("glUniform2uiv"); + pGlUniform3uiv = (PFNGLUNIFORM3UIVPROC)IRR_OGL_LOAD_EXTENSION("glUniform3uiv"); + pGlUniform4uiv = (PFNGLUNIFORM4UIVPROC)IRR_OGL_LOAD_EXTENSION("glUniform4uiv"); + pGlUniformMatrix2fvARB = (PFNGLUNIFORMMATRIX2FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix2fvARB"); + pGlUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix2x3fv"); pGlUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix2x4fv"); pGlUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix3x2fv"); - pGlUniformMatrix3fvARB = (PFNGLUNIFORMMATRIX3FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniformMatrix3fvARB"); + pGlUniformMatrix3fvARB = (PFNGLUNIFORMMATRIX3FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix3fvARB"); pGlUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix3x4fv"); pGlUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix4x2fv"); pGlUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix4x3fv"); - pGlUniformMatrix4fvARB = (PFNGLUNIFORMMATRIX4FVARBPROC) IRR_OGL_LOAD_EXTENSION("glUniformMatrix4fvARB"); - pGlGetActiveUniformARB = (PFNGLGETACTIVEUNIFORMARBPROC) IRR_OGL_LOAD_EXTENSION("glGetActiveUniformARB"); - pGlGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC) IRR_OGL_LOAD_EXTENSION("glGetActiveUniform"); + pGlUniformMatrix4fvARB = (PFNGLUNIFORMMATRIX4FVARBPROC)IRR_OGL_LOAD_EXTENSION("glUniformMatrix4fvARB"); + pGlGetActiveUniformARB = (PFNGLGETACTIVEUNIFORMARBPROC)IRR_OGL_LOAD_EXTENSION("glGetActiveUniformARB"); + pGlGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)IRR_OGL_LOAD_EXTENSION("glGetActiveUniform"); // get point parameter extension - pGlPointParameterfARB = (PFNGLPOINTPARAMETERFARBPROC) IRR_OGL_LOAD_EXTENSION("glPointParameterfARB"); - pGlPointParameterfvARB = (PFNGLPOINTPARAMETERFVARBPROC) IRR_OGL_LOAD_EXTENSION("glPointParameterfvARB"); + pGlPointParameterfARB = (PFNGLPOINTPARAMETERFARBPROC)IRR_OGL_LOAD_EXTENSION("glPointParameterfARB"); + pGlPointParameterfvARB = (PFNGLPOINTPARAMETERFVARBPROC)IRR_OGL_LOAD_EXTENSION("glPointParameterfvARB"); // get stencil extension - pGlStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC) IRR_OGL_LOAD_EXTENSION("glStencilFuncSeparate"); - pGlStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC) IRR_OGL_LOAD_EXTENSION("glStencilOpSeparate"); - pGlStencilFuncSeparateATI = (PFNGLSTENCILFUNCSEPARATEATIPROC) IRR_OGL_LOAD_EXTENSION("glStencilFuncSeparateATI"); - pGlStencilOpSeparateATI = (PFNGLSTENCILOPSEPARATEATIPROC) IRR_OGL_LOAD_EXTENSION("glStencilOpSeparateATI"); + pGlStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)IRR_OGL_LOAD_EXTENSION("glStencilFuncSeparate"); + pGlStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)IRR_OGL_LOAD_EXTENSION("glStencilOpSeparate"); + pGlStencilFuncSeparateATI = (PFNGLSTENCILFUNCSEPARATEATIPROC)IRR_OGL_LOAD_EXTENSION("glStencilFuncSeparateATI"); + pGlStencilOpSeparateATI = (PFNGLSTENCILOPSEPARATEATIPROC)IRR_OGL_LOAD_EXTENSION("glStencilOpSeparateATI"); // compressed textures - pGlCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC) IRR_OGL_LOAD_EXTENSION("glCompressedTexImage2D"); - pGlCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) IRR_OGL_LOAD_EXTENSION("glCompressedTexSubImage2D"); + pGlCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glCompressedTexImage2D"); + pGlCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glCompressedTexSubImage2D"); // ARB FrameBufferObjects - pGlBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) IRR_OGL_LOAD_EXTENSION("glBindFramebuffer"); - pGlDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) IRR_OGL_LOAD_EXTENSION("glDeleteFramebuffers"); - pGlGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) IRR_OGL_LOAD_EXTENSION("glGenFramebuffers"); - pGlCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) IRR_OGL_LOAD_EXTENSION("glCheckFramebufferStatus"); - pGlFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) IRR_OGL_LOAD_EXTENSION("glFramebufferTexture2D"); - pGlBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) IRR_OGL_LOAD_EXTENSION("glBindRenderbuffer"); - pGlDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) IRR_OGL_LOAD_EXTENSION("glDeleteRenderbuffers"); - pGlGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) IRR_OGL_LOAD_EXTENSION("glGenRenderbuffers"); - pGlRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) IRR_OGL_LOAD_EXTENSION("glRenderbufferStorage"); - pGlFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) IRR_OGL_LOAD_EXTENSION("glFramebufferRenderbuffer"); - pGlGenerateMipmap = (PFNGLGENERATEMIPMAPPROC) IRR_OGL_LOAD_EXTENSION("glGenerateMipmap"); + pGlBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)IRR_OGL_LOAD_EXTENSION("glBindFramebuffer"); + pGlDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)IRR_OGL_LOAD_EXTENSION("glDeleteFramebuffers"); + pGlGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)IRR_OGL_LOAD_EXTENSION("glGenFramebuffers"); + pGlCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)IRR_OGL_LOAD_EXTENSION("glCheckFramebufferStatus"); + pGlFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferTexture2D"); + pGlBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)IRR_OGL_LOAD_EXTENSION("glBindRenderbuffer"); + pGlDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)IRR_OGL_LOAD_EXTENSION("glDeleteRenderbuffers"); + pGlGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)IRR_OGL_LOAD_EXTENSION("glGenRenderbuffers"); + pGlRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)IRR_OGL_LOAD_EXTENSION("glRenderbufferStorage"); + pGlFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferRenderbuffer"); + pGlGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)IRR_OGL_LOAD_EXTENSION("glGenerateMipmap"); // EXT FrameBufferObjects - pGlBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) IRR_OGL_LOAD_EXTENSION("glBindFramebufferEXT"); - pGlDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) IRR_OGL_LOAD_EXTENSION("glDeleteFramebuffersEXT"); - pGlGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) IRR_OGL_LOAD_EXTENSION("glGenFramebuffersEXT"); - pGlCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) IRR_OGL_LOAD_EXTENSION("glCheckFramebufferStatusEXT"); - pGlFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) IRR_OGL_LOAD_EXTENSION("glFramebufferTexture2DEXT"); - pGlBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC) IRR_OGL_LOAD_EXTENSION("glBindRenderbufferEXT"); - pGlDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC) IRR_OGL_LOAD_EXTENSION("glDeleteRenderbuffersEXT"); - pGlGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC) IRR_OGL_LOAD_EXTENSION("glGenRenderbuffersEXT"); - pGlRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC) IRR_OGL_LOAD_EXTENSION("glRenderbufferStorageEXT"); - pGlFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) IRR_OGL_LOAD_EXTENSION("glFramebufferRenderbufferEXT"); - pGlGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC) IRR_OGL_LOAD_EXTENSION("glGenerateMipmapEXT"); - pGlDrawBuffersARB = (PFNGLDRAWBUFFERSARBPROC) IRR_OGL_LOAD_EXTENSION("glDrawBuffersARB"); - pGlDrawBuffersATI = (PFNGLDRAWBUFFERSATIPROC) IRR_OGL_LOAD_EXTENSION("glDrawBuffersATI"); + pGlBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)IRR_OGL_LOAD_EXTENSION("glBindFramebufferEXT"); + pGlDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)IRR_OGL_LOAD_EXTENSION("glDeleteFramebuffersEXT"); + pGlGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)IRR_OGL_LOAD_EXTENSION("glGenFramebuffersEXT"); + pGlCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)IRR_OGL_LOAD_EXTENSION("glCheckFramebufferStatusEXT"); + pGlFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferTexture2DEXT"); + pGlBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)IRR_OGL_LOAD_EXTENSION("glBindRenderbufferEXT"); + pGlDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)IRR_OGL_LOAD_EXTENSION("glDeleteRenderbuffersEXT"); + pGlGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)IRR_OGL_LOAD_EXTENSION("glGenRenderbuffersEXT"); + pGlRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)IRR_OGL_LOAD_EXTENSION("glRenderbufferStorageEXT"); + pGlFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferRenderbufferEXT"); + pGlGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)IRR_OGL_LOAD_EXTENSION("glGenerateMipmapEXT"); + pGlDrawBuffersARB = (PFNGLDRAWBUFFERSARBPROC)IRR_OGL_LOAD_EXTENSION("glDrawBuffersARB"); + pGlDrawBuffersATI = (PFNGLDRAWBUFFERSATIPROC)IRR_OGL_LOAD_EXTENSION("glDrawBuffersATI"); // get vertex buffer extension - pGlGenBuffersARB = (PFNGLGENBUFFERSARBPROC) IRR_OGL_LOAD_EXTENSION("glGenBuffersARB"); - pGlBindBufferARB = (PFNGLBINDBUFFERARBPROC) IRR_OGL_LOAD_EXTENSION("glBindBufferARB"); - pGlBufferDataARB = (PFNGLBUFFERDATAARBPROC) IRR_OGL_LOAD_EXTENSION("glBufferDataARB"); - pGlDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC) IRR_OGL_LOAD_EXTENSION("glDeleteBuffersARB"); - pGlBufferSubDataARB= (PFNGLBUFFERSUBDATAARBPROC) IRR_OGL_LOAD_EXTENSION("glBufferSubDataARB"); - pGlGetBufferSubDataARB= (PFNGLGETBUFFERSUBDATAARBPROC)IRR_OGL_LOAD_EXTENSION("glGetBufferSubDataARB"); - pGlMapBufferARB= (PFNGLMAPBUFFERARBPROC) IRR_OGL_LOAD_EXTENSION("glMapBufferARB"); - pGlUnmapBufferARB= (PFNGLUNMAPBUFFERARBPROC) IRR_OGL_LOAD_EXTENSION("glUnmapBufferARB"); - pGlIsBufferARB= (PFNGLISBUFFERARBPROC) IRR_OGL_LOAD_EXTENSION("glIsBufferARB"); - pGlGetBufferParameterivARB= (PFNGLGETBUFFERPARAMETERIVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetBufferParameterivARB"); - pGlGetBufferPointervARB= (PFNGLGETBUFFERPOINTERVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetBufferPointervARB"); - pGlProvokingVertexARB= (PFNGLPROVOKINGVERTEXPROC) IRR_OGL_LOAD_EXTENSION("glProvokingVertex"); - pGlProvokingVertexEXT= (PFNGLPROVOKINGVERTEXEXTPROC) IRR_OGL_LOAD_EXTENSION("glProvokingVertexEXT"); - pGlProgramParameteriARB= (PFNGLPROGRAMPARAMETERIARBPROC) IRR_OGL_LOAD_EXTENSION("glProgramParameteriARB"); - pGlProgramParameteriEXT= (PFNGLPROGRAMPARAMETERIEXTPROC) IRR_OGL_LOAD_EXTENSION("glProgramParameteriEXT"); + pGlGenBuffersARB = (PFNGLGENBUFFERSARBPROC)IRR_OGL_LOAD_EXTENSION("glGenBuffersARB"); + pGlBindBufferARB = (PFNGLBINDBUFFERARBPROC)IRR_OGL_LOAD_EXTENSION("glBindBufferARB"); + pGlBufferDataARB = (PFNGLBUFFERDATAARBPROC)IRR_OGL_LOAD_EXTENSION("glBufferDataARB"); + pGlDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)IRR_OGL_LOAD_EXTENSION("glDeleteBuffersARB"); + pGlBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)IRR_OGL_LOAD_EXTENSION("glBufferSubDataARB"); + pGlGetBufferSubDataARB = (PFNGLGETBUFFERSUBDATAARBPROC)IRR_OGL_LOAD_EXTENSION("glGetBufferSubDataARB"); + pGlMapBufferARB = (PFNGLMAPBUFFERARBPROC)IRR_OGL_LOAD_EXTENSION("glMapBufferARB"); + pGlUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)IRR_OGL_LOAD_EXTENSION("glUnmapBufferARB"); + pGlIsBufferARB = (PFNGLISBUFFERARBPROC)IRR_OGL_LOAD_EXTENSION("glIsBufferARB"); + pGlGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetBufferParameterivARB"); + pGlGetBufferPointervARB = (PFNGLGETBUFFERPOINTERVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetBufferPointervARB"); + pGlProvokingVertexARB = (PFNGLPROVOKINGVERTEXPROC)IRR_OGL_LOAD_EXTENSION("glProvokingVertex"); + pGlProvokingVertexEXT = (PFNGLPROVOKINGVERTEXEXTPROC)IRR_OGL_LOAD_EXTENSION("glProvokingVertexEXT"); + pGlProgramParameteriARB = (PFNGLPROGRAMPARAMETERIARBPROC)IRR_OGL_LOAD_EXTENSION("glProgramParameteriARB"); + pGlProgramParameteriEXT = (PFNGLPROGRAMPARAMETERIEXTPROC)IRR_OGL_LOAD_EXTENSION("glProgramParameteriEXT"); // occlusion query - pGlGenQueriesARB = (PFNGLGENQUERIESARBPROC) IRR_OGL_LOAD_EXTENSION("glGenQueriesARB"); - pGlDeleteQueriesARB = (PFNGLDELETEQUERIESARBPROC) IRR_OGL_LOAD_EXTENSION("glDeleteQueriesARB"); - pGlIsQueryARB = (PFNGLISQUERYARBPROC) IRR_OGL_LOAD_EXTENSION("glIsQueryARB"); - pGlBeginQueryARB = (PFNGLBEGINQUERYARBPROC) IRR_OGL_LOAD_EXTENSION("glBeginQueryARB"); - pGlEndQueryARB = (PFNGLENDQUERYARBPROC) IRR_OGL_LOAD_EXTENSION("glEndQueryARB"); - pGlGetQueryivARB = (PFNGLGETQUERYIVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetQueryivARB"); - pGlGetQueryObjectivARB = (PFNGLGETQUERYOBJECTIVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetQueryObjectivARB"); - pGlGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC) IRR_OGL_LOAD_EXTENSION("glGetQueryObjectuivARB"); - pGlGenOcclusionQueriesNV = (PFNGLGENOCCLUSIONQUERIESNVPROC) IRR_OGL_LOAD_EXTENSION("glGenOcclusionQueriesNV"); - pGlDeleteOcclusionQueriesNV = (PFNGLDELETEOCCLUSIONQUERIESNVPROC) IRR_OGL_LOAD_EXTENSION("glDeleteOcclusionQueriesNV"); - pGlIsOcclusionQueryNV = (PFNGLISOCCLUSIONQUERYNVPROC) IRR_OGL_LOAD_EXTENSION("glIsOcclusionQueryNV"); - pGlBeginOcclusionQueryNV = (PFNGLBEGINOCCLUSIONQUERYNVPROC) IRR_OGL_LOAD_EXTENSION("glBeginOcclusionQueryNV"); - pGlEndOcclusionQueryNV = (PFNGLENDOCCLUSIONQUERYNVPROC) IRR_OGL_LOAD_EXTENSION("glEndOcclusionQueryNV"); - pGlGetOcclusionQueryivNV = (PFNGLGETOCCLUSIONQUERYIVNVPROC) IRR_OGL_LOAD_EXTENSION("glGetOcclusionQueryivNV"); - pGlGetOcclusionQueryuivNV = (PFNGLGETOCCLUSIONQUERYUIVNVPROC) IRR_OGL_LOAD_EXTENSION("glGetOcclusionQueryuivNV"); + pGlGenQueriesARB = (PFNGLGENQUERIESARBPROC)IRR_OGL_LOAD_EXTENSION("glGenQueriesARB"); + pGlDeleteQueriesARB = (PFNGLDELETEQUERIESARBPROC)IRR_OGL_LOAD_EXTENSION("glDeleteQueriesARB"); + pGlIsQueryARB = (PFNGLISQUERYARBPROC)IRR_OGL_LOAD_EXTENSION("glIsQueryARB"); + pGlBeginQueryARB = (PFNGLBEGINQUERYARBPROC)IRR_OGL_LOAD_EXTENSION("glBeginQueryARB"); + pGlEndQueryARB = (PFNGLENDQUERYARBPROC)IRR_OGL_LOAD_EXTENSION("glEndQueryARB"); + pGlGetQueryivARB = (PFNGLGETQUERYIVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetQueryivARB"); + pGlGetQueryObjectivARB = (PFNGLGETQUERYOBJECTIVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetQueryObjectivARB"); + pGlGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)IRR_OGL_LOAD_EXTENSION("glGetQueryObjectuivARB"); + pGlGenOcclusionQueriesNV = (PFNGLGENOCCLUSIONQUERIESNVPROC)IRR_OGL_LOAD_EXTENSION("glGenOcclusionQueriesNV"); + pGlDeleteOcclusionQueriesNV = (PFNGLDELETEOCCLUSIONQUERIESNVPROC)IRR_OGL_LOAD_EXTENSION("glDeleteOcclusionQueriesNV"); + pGlIsOcclusionQueryNV = (PFNGLISOCCLUSIONQUERYNVPROC)IRR_OGL_LOAD_EXTENSION("glIsOcclusionQueryNV"); + pGlBeginOcclusionQueryNV = (PFNGLBEGINOCCLUSIONQUERYNVPROC)IRR_OGL_LOAD_EXTENSION("glBeginOcclusionQueryNV"); + pGlEndOcclusionQueryNV = (PFNGLENDOCCLUSIONQUERYNVPROC)IRR_OGL_LOAD_EXTENSION("glEndOcclusionQueryNV"); + pGlGetOcclusionQueryivNV = (PFNGLGETOCCLUSIONQUERYIVNVPROC)IRR_OGL_LOAD_EXTENSION("glGetOcclusionQueryivNV"); + pGlGetOcclusionQueryuivNV = (PFNGLGETOCCLUSIONQUERYUIVNVPROC)IRR_OGL_LOAD_EXTENSION("glGetOcclusionQueryuivNV"); // blend - pGlBlendFuncSeparateEXT = (PFNGLBLENDFUNCSEPARATEEXTPROC) IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateEXT"); - pGlBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC) IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparate"); - pGlBlendEquationEXT = (PFNGLBLENDEQUATIONEXTPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationEXT"); - pGlBlendEquation = (PFNGLBLENDEQUATIONPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquation"); - pGlBlendEquationSeparateEXT = (PFNGLBLENDEQUATIONSEPARATEEXTPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateEXT"); - pGlBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparate"); + pGlBlendFuncSeparateEXT = (PFNGLBLENDFUNCSEPARATEEXTPROC)IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateEXT"); + pGlBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparate"); + pGlBlendEquationEXT = (PFNGLBLENDEQUATIONEXTPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationEXT"); + pGlBlendEquation = (PFNGLBLENDEQUATIONPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquation"); + pGlBlendEquationSeparateEXT = (PFNGLBLENDEQUATIONSEPARATEEXTPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateEXT"); + pGlBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparate"); // indexed - pGlEnableIndexedEXT = (PFNGLENABLEINDEXEDEXTPROC) IRR_OGL_LOAD_EXTENSION("glEnableIndexedEXT"); - pGlDisableIndexedEXT = (PFNGLDISABLEINDEXEDEXTPROC) IRR_OGL_LOAD_EXTENSION("glDisableIndexedEXT"); - pGlColorMaskIndexedEXT = (PFNGLCOLORMASKINDEXEDEXTPROC) IRR_OGL_LOAD_EXTENSION("glColorMaskIndexedEXT"); - pGlBlendFuncIndexedAMD = (PFNGLBLENDFUNCINDEXEDAMDPROC) IRR_OGL_LOAD_EXTENSION("glBlendFuncIndexedAMD"); - pGlBlendFunciARB = (PFNGLBLENDFUNCIPROC) IRR_OGL_LOAD_EXTENSION("glBlendFunciARB"); - pGlBlendFuncSeparateIndexedAMD = (PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateIndexedAMD"); - pGlBlendFuncSeparateiARB = (PFNGLBLENDFUNCSEPARATEIPROC) IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateiARB"); - pGlBlendEquationIndexedAMD = (PFNGLBLENDEQUATIONINDEXEDAMDPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationIndexedAMD"); - pGlBlendEquationiARB = (PFNGLBLENDEQUATIONIPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationiARB"); - pGlBlendEquationSeparateIndexedAMD = (PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateIndexedAMD"); - pGlBlendEquationSeparateiARB = (PFNGLBLENDEQUATIONSEPARATEIPROC) IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateiARB"); + pGlEnableIndexedEXT = (PFNGLENABLEINDEXEDEXTPROC)IRR_OGL_LOAD_EXTENSION("glEnableIndexedEXT"); + pGlDisableIndexedEXT = (PFNGLDISABLEINDEXEDEXTPROC)IRR_OGL_LOAD_EXTENSION("glDisableIndexedEXT"); + pGlColorMaskIndexedEXT = (PFNGLCOLORMASKINDEXEDEXTPROC)IRR_OGL_LOAD_EXTENSION("glColorMaskIndexedEXT"); + pGlBlendFuncIndexedAMD = (PFNGLBLENDFUNCINDEXEDAMDPROC)IRR_OGL_LOAD_EXTENSION("glBlendFuncIndexedAMD"); + pGlBlendFunciARB = (PFNGLBLENDFUNCIPROC)IRR_OGL_LOAD_EXTENSION("glBlendFunciARB"); + pGlBlendFuncSeparateIndexedAMD = (PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC)IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateIndexedAMD"); + pGlBlendFuncSeparateiARB = (PFNGLBLENDFUNCSEPARATEIPROC)IRR_OGL_LOAD_EXTENSION("glBlendFuncSeparateiARB"); + pGlBlendEquationIndexedAMD = (PFNGLBLENDEQUATIONINDEXEDAMDPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationIndexedAMD"); + pGlBlendEquationiARB = (PFNGLBLENDEQUATIONIPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationiARB"); + pGlBlendEquationSeparateIndexedAMD = (PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateIndexedAMD"); + pGlBlendEquationSeparateiARB = (PFNGLBLENDEQUATIONSEPARATEIPROC)IRR_OGL_LOAD_EXTENSION("glBlendEquationSeparateiARB"); - pGlTextureStorage2D = (PFNGLTEXTURESTORAGE2DPROC) IRR_OGL_LOAD_EXTENSION("glTextureStorage2D"); - pGlTextureStorage3D = (PFNGLTEXTURESTORAGE3DPROC) IRR_OGL_LOAD_EXTENSION("glTextureStorage3D"); + pGlTextureStorage2D = (PFNGLTEXTURESTORAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage2D"); + pGlTextureStorage3D = (PFNGLTEXTURESTORAGE3DPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage3D"); pGlTextureSubImage2D = (PFNGLTEXTURESUBIMAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glTextureSubImage2D"); pGlGetTextureImage = (PFNGLGETTEXTUREIMAGEPROC)IRR_OGL_LOAD_EXTENSION("glGetTextureImage"); - pGlNamedFramebufferTexture = (PFNGLNAMEDFRAMEBUFFERTEXTUREPROC) IRR_OGL_LOAD_EXTENSION("glNamedFramebufferTexture"); - pGlTextureParameteri = (PFNGLTEXTUREPARAMETERIPROC) IRR_OGL_LOAD_EXTENSION("glTextureParameteri"); + pGlNamedFramebufferTexture = (PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)IRR_OGL_LOAD_EXTENSION("glNamedFramebufferTexture"); + pGlTextureParameteri = (PFNGLTEXTUREPARAMETERIPROC)IRR_OGL_LOAD_EXTENSION("glTextureParameteri"); pGlTextureParameterf = (PFNGLTEXTUREPARAMETERFPROC)IRR_OGL_LOAD_EXTENSION("glTextureParameterf"); pGlTextureParameteriv = (PFNGLTEXTUREPARAMETERIVPROC)IRR_OGL_LOAD_EXTENSION("glTextureParameteriv"); pGlTextureParameterfv = (PFNGLTEXTUREPARAMETERFVPROC)IRR_OGL_LOAD_EXTENSION("glTextureParameterfv"); - pGlCreateTextures = (PFNGLCREATETEXTURESPROC) IRR_OGL_LOAD_EXTENSION("glCreateTextures"); - pGlCreateFramebuffers = (PFNGLCREATEFRAMEBUFFERSPROC) IRR_OGL_LOAD_EXTENSION("glCreateFramebuffers"); - pGlBindTextures = (PFNGLBINDTEXTURESPROC) IRR_OGL_LOAD_EXTENSION("glBindTextures"); - pGlGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC) IRR_OGL_LOAD_EXTENSION("glGenerateTextureMipmap"); - //============================== - pGlTextureStorage2DEXT = (PFNGLTEXTURESTORAGE2DEXTPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage2DEXT"); - pGlTexStorage2D = (PFNGLTEXSTORAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glTexStorage2D"); - pGlTextureStorage3DEXT = (PFNGLTEXTURESTORAGE3DEXTPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage3DEXT"); - pGlTexStorage3D = (PFNGLTEXSTORAGE3DPROC)IRR_OGL_LOAD_EXTENSION("glTexStorage3D"); + pGlCreateTextures = (PFNGLCREATETEXTURESPROC)IRR_OGL_LOAD_EXTENSION("glCreateTextures"); + pGlCreateFramebuffers = (PFNGLCREATEFRAMEBUFFERSPROC)IRR_OGL_LOAD_EXTENSION("glCreateFramebuffers"); + pGlBindTextures = (PFNGLBINDTEXTURESPROC)IRR_OGL_LOAD_EXTENSION("glBindTextures"); + pGlGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC)IRR_OGL_LOAD_EXTENSION("glGenerateTextureMipmap"); + //============================== + pGlTextureStorage2DEXT = (PFNGLTEXTURESTORAGE2DEXTPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage2DEXT"); + pGlTexStorage2D = (PFNGLTEXSTORAGE2DPROC)IRR_OGL_LOAD_EXTENSION("glTexStorage2D"); + pGlTextureStorage3DEXT = (PFNGLTEXTURESTORAGE3DEXTPROC)IRR_OGL_LOAD_EXTENSION("glTextureStorage3DEXT"); + pGlTexStorage3D = (PFNGLTEXSTORAGE3DPROC)IRR_OGL_LOAD_EXTENSION("glTexStorage3D"); pGlTextureSubImage2DEXT = (PFNGLTEXTURESUBIMAGE2DEXTPROC)IRR_OGL_LOAD_EXTENSION("glTextureSubImage2DEXT"); pGlGetTextureImageEXT = (PFNGLGETTEXTUREIMAGEEXTPROC)IRR_OGL_LOAD_EXTENSION("glGetTextureImageEXT"); - pGlNamedFramebufferTextureEXT = (PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC)IRR_OGL_LOAD_EXTENSION("glNamedFramebufferTextureEXT"); - pGlFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferTexture"); - pGlActiveTexture = (PFNGLACTIVETEXTUREPROC)IRR_OGL_LOAD_EXTENSION("glActiveTexture"); - pGlGenerateTextureMipmapEXT = (PFNGLGENERATETEXTUREMIPMAPEXTPROC) IRR_OGL_LOAD_EXTENSION("glGenerateTextureMipmapEXT"); + pGlNamedFramebufferTextureEXT = (PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC)IRR_OGL_LOAD_EXTENSION("glNamedFramebufferTextureEXT"); + pGlFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)IRR_OGL_LOAD_EXTENSION("glFramebufferTexture"); + pGlActiveTexture = (PFNGLACTIVETEXTUREPROC)IRR_OGL_LOAD_EXTENSION("glActiveTexture"); + pGlGenerateTextureMipmapEXT = (PFNGLGENERATETEXTUREMIPMAPEXTPROC)IRR_OGL_LOAD_EXTENSION("glGenerateTextureMipmapEXT"); - // get vsync extension - #if defined(WGL_EXT_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - pWglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) IRR_OGL_LOAD_EXTENSION("wglSwapIntervalEXT"); - #endif - #if defined(GLX_SGI_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - pGlxSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalSGI"); - #endif - #if defined(GLX_EXT_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - pGlxSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalEXT"); - #endif - #if defined(GLX_MESA_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - pGlxSwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalMESA"); - #endif +// get vsync extension +#if defined(WGL_EXT_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) + pWglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)IRR_OGL_LOAD_EXTENSION("wglSwapIntervalEXT"); +#endif +#if defined(GLX_SGI_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) + pGlxSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalSGI"); +#endif +#if defined(GLX_EXT_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) + pGlxSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalEXT"); +#endif +#if defined(GLX_MESA_swap_control) && !defined(_IRR_COMPILE_WITH_SDL_DEVICE_) + pGlxSwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)IRR_OGL_LOAD_EXTENSION("glXSwapIntervalMESA"); +#endif - GLint num=0; + GLint num = 0; // set some properties #if defined(GL_ARB_multitexture) || defined(GL_VERSION_1_3) - if (Version>102 || FeatureAvailable[IRR_ARB_multitexture]) - { + if (Version > 102 || FeatureAvailable[IRR_ARB_multitexture]) { #if defined(GL_MAX_TEXTURE_UNITS) glGetIntegerv(GL_MAX_TEXTURE_UNITS, &num); #elif defined(GL_MAX_TEXTURE_UNITS_ARB) glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &num); #endif - Feature.MaxTextureUnits=static_cast(num); // MULTITEXTURING (fixed function pipeline texture units) + Feature.MaxTextureUnits = static_cast(num); // MULTITEXTURING (fixed function pipeline texture units) } #endif #if defined(GL_ARB_vertex_shader) || defined(GL_VERSION_2_0) - if (Version>=200 || FeatureAvailable[IRR_ARB_vertex_shader]) - { - num=0; + if (Version >= 200 || FeatureAvailable[IRR_ARB_vertex_shader]) { + num = 0; #if defined(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS) glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &num); #elif defined(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB) glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &num); #endif - Feature.MaxTextureUnits =core::max_(Feature.MaxTextureUnits,static_cast(num)); + Feature.MaxTextureUnits = core::max_(Feature.MaxTextureUnits, static_cast(num)); } #endif glGetIntegerv(GL_MAX_LIGHTS, &num); - MaxLights=static_cast(num); + MaxLights = static_cast(num); #ifdef GL_EXT_texture_filter_anisotropic - if (FeatureAvailable[IRR_EXT_texture_filter_anisotropic]) - { + if (FeatureAvailable[IRR_EXT_texture_filter_anisotropic]) { glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &num); - MaxAnisotropy=static_cast(num); + MaxAnisotropy = static_cast(num); } #endif #ifdef GL_VERSION_1_2 - if (Version>101) - { + if (Version > 101) { glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &num); - MaxIndices=num; + MaxIndices = num; } #endif glGetIntegerv(GL_MAX_TEXTURE_SIZE, &num); - MaxTextureSize=static_cast(num); - if (queryFeature(EVDF_GEOMETRY_SHADER)) - { + MaxTextureSize = static_cast(num); + if (queryFeature(EVDF_GEOMETRY_SHADER)) { #if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_shader4) glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &num); - MaxGeometryVerticesOut=static_cast(num); + MaxGeometryVerticesOut = static_cast(num); #elif defined(GL_NV_geometry_program4) extGlGetProgramiv(GEOMETRY_PROGRAM_NV, GL_MAX_PROGRAM_OUTPUT_VERTICES_NV, &num); - MaxGeometryVerticesOut=static_cast(num); + MaxGeometryVerticesOut = static_cast(num); #endif } #ifdef GL_EXT_texture_lod_bias @@ -440,12 +429,11 @@ void COpenGLExtensionHandler::initExtensions(video::IContextManager *cmgr, bool glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias); #endif glGetIntegerv(GL_MAX_CLIP_PLANES, &num); - MaxUserClipPlanes=static_cast(num); + MaxUserClipPlanes = static_cast(num); glGetIntegerv(GL_AUX_BUFFERS, &num); - MaxAuxBuffers=static_cast(num); + MaxAuxBuffers = static_cast(num); #ifdef GL_ARB_draw_buffers - if (FeatureAvailable[IRR_ARB_draw_buffers]) - { + if (FeatureAvailable[IRR_ARB_draw_buffers]) { glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &num); Feature.MultipleRenderTarget = static_cast(num); } @@ -454,15 +442,13 @@ void COpenGLExtensionHandler::initExtensions(video::IContextManager *cmgr, bool #ifdef GL_ARB_draw_buffers else #endif - if (FeatureAvailable[IRR_ATI_draw_buffers]) - { + if (FeatureAvailable[IRR_ATI_draw_buffers]) { glGetIntegerv(GL_MAX_DRAW_BUFFERS_ATI, &num); Feature.MultipleRenderTarget = static_cast(num); } #endif #ifdef GL_ARB_framebuffer_object - if (FeatureAvailable[IRR_ARB_framebuffer_object]) - { + if (FeatureAvailable[IRR_ARB_framebuffer_object]) { glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &num); Feature.ColorAttachment = static_cast(num); } @@ -471,71 +457,61 @@ void COpenGLExtensionHandler::initExtensions(video::IContextManager *cmgr, bool #ifdef GL_ARB_framebuffer_object else #endif - if (FeatureAvailable[IRR_EXT_framebuffer_object]) - { - glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &num); - Feature.ColorAttachment = static_cast(num); - } + if (FeatureAvailable[IRR_EXT_framebuffer_object]) { + glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &num); + Feature.ColorAttachment = static_cast(num); + } #endif glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, DimSmoothedLine); glGetFloatv(GL_SMOOTH_POINT_SIZE_RANGE, DimSmoothedPoint); -#if defined(GL_ARB_shading_language_100) || defined (GL_VERSION_2_0) - if (FeatureAvailable[IRR_ARB_shading_language_100] || Version>=200) - { +#if defined(GL_ARB_shading_language_100) || defined(GL_VERSION_2_0) + if (FeatureAvailable[IRR_ARB_shading_language_100] || Version >= 200) { glGetError(); // clean error buffer #ifdef GL_SHADING_LANGUAGE_VERSION - const GLubyte* shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); + const GLubyte *shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); #else - const GLubyte* shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION_ARB); + const GLubyte *shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION_ARB); #endif if (glGetError() == GL_INVALID_ENUM) ShaderLanguageVersion = 100; - else - { - const f32 sl_ver = core::fast_atof(reinterpret_cast(shaderVersion)); - ShaderLanguageVersion = static_cast(core::floor32(sl_ver)*100+core::round32(core::fract(sl_ver)*10.0f)); + else { + const f32 sl_ver = core::fast_atof(reinterpret_cast(shaderVersion)); + ShaderLanguageVersion = static_cast(core::floor32(sl_ver) * 100 + core::round32(core::fract(sl_ver) * 10.0f)); } } #endif - if (!pGlActiveTextureARB || !pGlClientActiveTextureARB) - { + if (!pGlActiveTextureARB || !pGlClientActiveTextureARB) { Feature.MaxTextureUnits = 1; os::Printer::log("Failed to load OpenGL's multitexture extension, proceeding without.", ELL_WARNING); - } - else - Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); + } else + Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); #ifdef GL_ARB_occlusion_query - if (FeatureAvailable[IRR_ARB_occlusion_query]) - { - extGlGetQueryiv(GL_SAMPLES_PASSED_ARB,GL_QUERY_COUNTER_BITS_ARB, - &num); - OcclusionQuerySupport=(num>0); - } - else + if (FeatureAvailable[IRR_ARB_occlusion_query]) { + extGlGetQueryiv(GL_SAMPLES_PASSED_ARB, GL_QUERY_COUNTER_BITS_ARB, + &num); + OcclusionQuerySupport = (num > 0); + } else #endif #ifdef GL_NV_occlusion_query - if (FeatureAvailable[IRR_NV_occlusion_query]) - { + if (FeatureAvailable[IRR_NV_occlusion_query]) { glGetIntegerv(GL_PIXEL_COUNTER_BITS_NV, &num); - OcclusionQuerySupport=(num>0); - } - else + OcclusionQuerySupport = (num > 0); + } else #endif - OcclusionQuerySupport=false; + OcclusionQuerySupport = false; - Feature.BlendOperation = (Version >= 104) || - FeatureAvailable[IRR_EXT_blend_minmax] || - FeatureAvailable[IRR_EXT_blend_subtract] || - FeatureAvailable[IRR_EXT_blend_logic_op]; + Feature.BlendOperation = (Version >= 104) || + FeatureAvailable[IRR_EXT_blend_minmax] || + FeatureAvailable[IRR_EXT_blend_subtract] || + FeatureAvailable[IRR_EXT_blend_logic_op]; #ifdef _DEBUG - if (FeatureAvailable[IRR_NVX_gpu_memory_info]) - { + if (FeatureAvailable[IRR_NVX_gpu_memory_info]) { // undocumented flags, so use the RAW values GLint val; glGetIntegerv(0x9047, &val); @@ -546,8 +522,7 @@ void COpenGLExtensionHandler::initExtensions(video::IContextManager *cmgr, bool os::Printer::log("Available video memory (kB)", core::stringc(val)); } #ifdef GL_ATI_meminfo - if (FeatureAvailable[IRR_ATI_meminfo]) - { + if (FeatureAvailable[IRR_ATI_meminfo]) { GLint val[4]; glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, val); os::Printer::log("Free texture memory (kB)", core::stringc(val[0])); @@ -564,15 +539,14 @@ void COpenGLExtensionHandler::initExtensions(video::IContextManager *cmgr, bool #endif } -const COpenGLCoreFeature& COpenGLExtensionHandler::getFeature() const +const COpenGLCoreFeature &COpenGLExtensionHandler::getFeature() const { return Feature; } bool COpenGLExtensionHandler::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const { - switch (feature) - { + switch (feature) { case EVDF_RENDER_TO_TARGET: return true; case EVDF_HARDWARE_TL: @@ -597,7 +571,7 @@ bool COpenGLExtensionHandler::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const case EVDF_PIXEL_SHADER_2_0: case EVDF_VERTEX_SHADER_2_0: case EVDF_ARB_GLSL: - return (FeatureAvailable[IRR_ARB_shading_language_100]||Version>=200); + return (FeatureAvailable[IRR_ARB_shading_language_100] || Version >= 200); case EVDF_TEXTURE_NSQUARE: return true; // non-square is always supported case EVDF_TEXTURE_NPOT: @@ -627,11 +601,11 @@ bool COpenGLExtensionHandler::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const return FeatureAvailable[IRR_ARB_occlusion_query] && OcclusionQuerySupport; case EVDF_POLYGON_OFFSET: // both features supported with OpenGL 1.1 - return Version>=101; + return Version >= 101; case EVDF_BLEND_OPERATIONS: return Feature.BlendOperation; case EVDF_BLEND_SEPARATE: - return (Version>=104) || FeatureAvailable[IRR_EXT_blend_func_separate]; + return (Version >= 104) || FeatureAvailable[IRR_EXT_blend_func_separate]; case EVDF_TEXTURE_MATRIX: return true; case EVDF_TEXTURE_CUBEMAP: @@ -646,7 +620,6 @@ bool COpenGLExtensionHandler::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const }; } - } } diff --git a/source/Irrlicht/COpenGLExtensionHandler.h b/source/Irrlicht/COpenGLExtensionHandler.h index 2c1a1e19..ada1c9a3 100644 --- a/source/Irrlicht/COpenGLExtensionHandler.h +++ b/source/Irrlicht/COpenGLExtensionHandler.h @@ -21,494 +21,493 @@ namespace video class IContextManager; -static const char* const OpenGLFeatureStrings[] = { - "GL_3DFX_multisample", - "GL_3DFX_tbuffer", - "GL_3DFX_texture_compression_FXT1", - "GL_AMD_blend_minmax_factor", - "GL_AMD_conservative_depth", - "GL_AMD_debug_output", - "GL_AMD_depth_clamp_separate", - "GL_AMD_draw_buffers_blend", - "GL_AMD_interleaved_elements", - "GL_AMD_multi_draw_indirect", - "GL_AMD_name_gen_delete", - "GL_AMD_performance_monitor", - "GL_AMD_pinned_memory", - "GL_AMD_query_buffer_object", - "GL_AMD_sample_positions", - "GL_AMD_seamless_cubemap_per_texture", - "GL_AMD_shader_atomic_counter_ops", - "GL_AMD_shader_stencil_export", - "GL_AMD_shader_trinary_minmax", - "GL_AMD_sparse_texture", - "GL_AMD_stencil_operation_extended", - "GL_AMD_texture_texture4", - "GL_AMD_transform_feedback3_lines_triangles", - "GL_AMD_vertex_shader_layer", - "GL_AMD_vertex_shader_tessellator", - "GL_AMD_vertex_shader_viewport_index", - "GL_APPLE_aux_depth_stencil", - "GL_APPLE_client_storage", - "GL_APPLE_element_array", - "GL_APPLE_fence", - "GL_APPLE_float_pixels", - "GL_APPLE_flush_buffer_range", - "GL_APPLE_object_purgeable", - "GL_APPLE_rgb_422", - "GL_APPLE_row_bytes", - "GL_APPLE_specular_vector", - "GL_APPLE_texture_range", - "GL_APPLE_transform_hint", - "GL_APPLE_vertex_array_object", - "GL_APPLE_vertex_array_range", - "GL_APPLE_vertex_program_evaluators", - "GL_APPLE_ycbcr_422", - "GL_ARB_arrays_of_arrays", - "GL_ARB_base_instance", - "GL_ARB_bindless_texture", - "GL_ARB_blend_func_extended", - "GL_ARB_buffer_storage", - "GL_ARB_cl_event", - "GL_ARB_clear_buffer_object", - "GL_ARB_clear_texture", - "GL_ARB_color_buffer_float", - "GL_ARB_compatibility", - "GL_ARB_compressed_texture_pixel_storage", - "GL_ARB_compute_shader", - "GL_ARB_compute_variable_group_size", - "GL_ARB_conservative_depth", - "GL_ARB_copy_buffer", - "GL_ARB_copy_image", - "GL_ARB_debug_output", - "GL_ARB_depth_buffer_float", - "GL_ARB_depth_clamp", - "GL_ARB_depth_texture", - "GL_ARB_direct_state_access", - "GL_ARB_draw_buffers", - "GL_ARB_draw_buffers_blend", - "GL_ARB_draw_elements_base_vertex", - "GL_ARB_draw_indirect", - "GL_ARB_draw_instanced", - "GL_ARB_ES2_compatibility", - "GL_ARB_ES3_compatibility", - "GL_ARB_enhanced_layouts", - "GL_ARB_explicit_attrib_location", - "GL_ARB_explicit_uniform_location", - "GL_ARB_fragment_coord_conventions", - "GL_ARB_fragment_layer_viewport", - "GL_ARB_fragment_program", - "GL_ARB_fragment_program_shadow", - "GL_ARB_fragment_shader", - "GL_ARB_framebuffer_no_attachments", - "GL_ARB_framebuffer_object", - "GL_ARB_framebuffer_sRGB", - "GL_ARB_geometry_shader4", - "GL_ARB_get_program_binary", - "GL_ARB_gpu_shader5", - "GL_ARB_gpu_shader_fp64", - "GL_ARB_half_float_pixel", - "GL_ARB_half_float_vertex", - "GL_ARB_imaging", - "GL_ARB_indirect_parameters", - "GL_ARB_instanced_arrays", - "GL_ARB_internalformat_query", - "GL_ARB_internalformat_query2", - "GL_ARB_invalidate_subdata", - "GL_ARB_map_buffer_alignment", - "GL_ARB_map_buffer_range", - "GL_ARB_matrix_palette", - "GL_ARB_multi_bind", - "GL_ARB_multi_draw_indirect", - "GL_ARB_multisample", - "GL_ARB_multitexture", - "GL_ARB_occlusion_query", - "GL_ARB_occlusion_query2", - "GL_ARB_pixel_buffer_object", - "GL_ARB_point_parameters", - "GL_ARB_point_sprite", - "GL_ARB_program_interface_query", - "GL_ARB_provoking_vertex", - "GL_ARB_query_buffer_object", - "GL_ARB_robust_buffer_access_behavior", - "GL_ARB_robustness", - "GL_ARB_robustness_isolation", - "GL_ARB_sample_shading", - "GL_ARB_sampler_objects", - "GL_ARB_seamless_cube_map", - "GL_ARB_seamless_cubemap_per_texture", - "GL_ARB_separate_shader_objects", - "GL_ARB_shader_atomic_counters", - "GL_ARB_shader_bit_encoding", - "GL_ARB_shader_draw_parameters", - "GL_ARB_shader_group_vote", - "GL_ARB_shader_image_load_store", - "GL_ARB_shader_image_size", - "GL_ARB_shader_objects", - "GL_ARB_shader_precision", - "GL_ARB_shader_stencil_export", - "GL_ARB_shader_storage_buffer_object", - "GL_ARB_shader_subroutine", - "GL_ARB_shader_texture_lod", - "GL_ARB_shading_language_100", - "GL_ARB_shading_language_420pack", - "GL_ARB_shading_language_include", - "GL_ARB_shading_language_packing", - "GL_ARB_shadow", - "GL_ARB_shadow_ambient", - "GL_ARB_sparse_texture", - "GL_ARB_stencil_texturing", - "GL_ARB_sync", - "GL_ARB_tessellation_shader", - "GL_ARB_texture_border_clamp", - "GL_ARB_texture_buffer_object", - "GL_ARB_texture_buffer_object_rgb32", - "GL_ARB_texture_buffer_range", - "GL_ARB_texture_compression", - "GL_ARB_texture_compression_bptc", - "GL_ARB_texture_compression_rgtc", - "GL_ARB_texture_cube_map", - "GL_ARB_texture_cube_map_array", - "GL_ARB_texture_env_add", - "GL_ARB_texture_env_combine", - "GL_ARB_texture_env_crossbar", - "GL_ARB_texture_env_dot3", - "GL_ARB_texture_float", - "GL_ARB_texture_gather", - "GL_ARB_texture_mirror_clamp_to_edge", - "GL_ARB_texture_mirrored_repeat", - "GL_ARB_texture_multisample", - "GL_ARB_texture_non_power_of_two", - "GL_ARB_texture_query_levels", - "GL_ARB_texture_query_lod", - "GL_ARB_texture_rectangle", - "GL_ARB_texture_rg", - "GL_ARB_texture_rgb10_a2ui", - "GL_ARB_texture_stencil8", - "GL_ARB_texture_storage", - "GL_ARB_texture_storage_multisample", - "GL_ARB_texture_swizzle", - "GL_ARB_texture_view", - "GL_ARB_timer_query", - "GL_ARB_transform_feedback2", - "GL_ARB_transform_feedback3", - "GL_ARB_transform_feedback_instanced", - "GL_ARB_transpose_matrix", - "GL_ARB_uniform_buffer_object", - "GL_ARB_vertex_array_bgra", - "GL_ARB_vertex_array_object", - "GL_ARB_vertex_attrib_64bit", - "GL_ARB_vertex_attrib_binding", - "GL_ARB_vertex_blend", - "GL_ARB_vertex_buffer_object", - "GL_ARB_vertex_program", - "GL_ARB_vertex_shader", - "GL_ARB_vertex_type_10f_11f_11f_rev", - "GL_ARB_vertex_type_2_10_10_10_rev", - "GL_ARB_viewport_array", - "GL_ARB_window_pos", - "GL_ATI_draw_buffers", - "GL_ATI_element_array", - "GL_ATI_envmap_bumpmap", - "GL_ATI_fragment_shader", - "GL_ATI_map_object_buffer", - "GL_ATI_meminfo", - "GL_ATI_pixel_format_float", - "GL_ATI_pn_triangles", - "GL_ATI_separate_stencil", - "GL_ATI_text_fragment_shader", - "GL_ATI_texture_env_combine3", - "GL_ATI_texture_float", - "GL_ATI_texture_mirror_once", - "GL_ATI_vertex_array_object", - "GL_ATI_vertex_attrib_array_object", - "GL_ATI_vertex_streams", - "GL_EXT_422_pixels", - "GL_EXT_abgr", - "GL_EXT_bgra", - "GL_EXT_bindable_uniform", - "GL_EXT_blend_color", - "GL_EXT_blend_equation_separate", - "GL_EXT_blend_func_separate", - "GL_EXT_blend_logic_op", - "GL_EXT_blend_minmax", - "GL_EXT_blend_subtract", - "GL_EXT_clip_volume_hint", - "GL_EXT_cmyka", - "GL_EXT_color_subtable", - "GL_EXT_compiled_vertex_array", - "GL_EXT_convolution", - "GL_EXT_coordinate_frame", - "GL_EXT_copy_texture", - "GL_EXT_cull_vertex", - "GL_EXT_debug_label", - "GL_EXT_debug_marker", - "GL_EXT_depth_bounds_test", - "GL_EXT_direct_state_access", - "GL_EXT_draw_buffers2", - "GL_EXT_draw_instanced", - "GL_EXT_draw_range_elements", - "GL_EXT_fog_coord", - "GL_EXT_framebuffer_blit", - "GL_EXT_framebuffer_multisample", - "GL_EXT_framebuffer_multisample_blit_scaled", - "GL_EXT_framebuffer_object", - "GL_EXT_framebuffer_sRGB", - "GL_EXT_geometry_shader4", - "GL_EXT_gpu_program_parameters", - "GL_EXT_gpu_shader4", - "GL_EXT_histogram", - "GL_EXT_index_array_formats", - "GL_EXT_index_func", - "GL_EXT_index_material", - "GL_EXT_index_texture", - "GL_EXT_light_texture", - "GL_EXT_misc_attribute", - "GL_EXT_multi_draw_arrays", - "GL_EXT_multisample", - "GL_EXT_packed_depth_stencil", - "GL_EXT_packed_float", - "GL_EXT_packed_pixels", - "GL_EXT_paletted_texture", - "GL_EXT_pixel_buffer_object", - "GL_EXT_pixel_transform", - "GL_EXT_pixel_transform_color_table", - "GL_EXT_point_parameters", - "GL_EXT_polygon_offset", - "GL_EXT_provoking_vertex", - "GL_EXT_rescale_normal", - "GL_EXT_secondary_color", - "GL_EXT_separate_shader_objects", - "GL_EXT_separate_specular_color", - "GL_EXT_shader_image_load_store", - "GL_EXT_shader_integer_mix", - "GL_EXT_shadow_funcs", - "GL_EXT_shared_texture_palette", - "GL_EXT_stencil_clear_tag", - "GL_EXT_stencil_two_side", - "GL_EXT_stencil_wrap", - "GL_EXT_subtexture", - "GL_EXT_texture", - "GL_EXT_texture3D", - "GL_EXT_texture_array", - "GL_EXT_texture_buffer_object", - "GL_EXT_texture_compression_latc", - "GL_EXT_texture_compression_rgtc", - "GL_EXT_texture_compression_s3tc", - "GL_EXT_texture_cube_map", - "GL_EXT_texture_env_add", - "GL_EXT_texture_env_combine", - "GL_EXT_texture_env_dot3", - "GL_EXT_texture_filter_anisotropic", - "GL_EXT_texture_integer", - "GL_EXT_texture_lod_bias", - "GL_EXT_texture_mirror_clamp", - "GL_EXT_texture_object", - "GL_EXT_texture_perturb_normal", - "GL_EXT_texture_shared_exponent", - "GL_EXT_texture_snorm", - "GL_EXT_texture_sRGB", - "GL_EXT_texture_sRGB_decode", - "GL_EXT_texture_swizzle", - "GL_EXT_timer_query", - "GL_EXT_transform_feedback", - "GL_EXT_vertex_array", - "GL_EXT_vertex_array_bgra", - "GL_EXT_vertex_attrib_64bit", - "GL_EXT_vertex_shader", - "GL_EXT_vertex_weighting", - "GL_EXT_x11_sync_object", - "GL_GREMEDY_frame_terminator", - "GL_GREMEDY_string_marker", - "GL_HP_convolution_border_modes", - "GL_HP_image_transform", - "GL_HP_occlusion_test", - "GL_HP_texture_lighting", - "GL_IBM_cull_vertex", - "GL_IBM_multimode_draw_arrays", - "GL_IBM_rasterpos_clip", - "GL_IBM_static_data", - "GL_IBM_texture_mirrored_repeat", - "GL_IBM_vertex_array_lists", - "GL_INGR_blend_func_separate", - "GL_INGR_color_clamp", - "GL_INGR_interlace_read", - "GL_INGR_palette_buffer", - "GL_INTEL_map_texture", - "GL_INTEL_parallel_arrays", - "GL_INTEL_texture_scissor", - "GL_KHR_debug", - "GL_KHR_texture_compression_astc_hdr", - "GL_KHR_texture_compression_astc_ldr", - "GL_MESA_pack_invert", - "GL_MESA_resize_buffers", - "GL_MESA_window_pos", - "GL_MESAX_texture_stack", - "GL_MESA_ycbcr_texture", - "GL_NVX_conditional_render", - "GL_NV_bindless_multi_draw_indirect", - "GL_NV_bindless_texture", - "GL_NV_blend_equation_advanced", - "GL_NV_blend_equation_advanced_coherent", - "GL_NV_blend_square", - "GL_NV_compute_program5", - "GL_NV_conditional_render", - "GL_NV_copy_depth_to_color", - "GL_NV_copy_image", - "GL_NV_deep_texture3D", - "GL_NV_depth_buffer_float", - "GL_NV_depth_clamp", - "GL_NV_draw_texture", - "GL_NV_evaluators", - "GL_NV_explicit_multisample", - "GL_NV_fence", - "GL_NV_float_buffer", - "GL_NV_fog_distance", - "GL_NV_fragment_program", - "GL_NV_fragment_program2", - "GL_NV_fragment_program4", - "GL_NV_fragment_program_option", - "GL_NV_framebuffer_multisample_coverage", - "GL_NV_geometry_program4", - "GL_NV_geometry_shader4", - "GL_NV_gpu_program4", - "GL_NV_gpu_program5", - "GL_NV_gpu_program5_mem_extended", - "GL_NV_gpu_shader5", - "GL_NV_half_float", - "GL_NV_light_max_exponent", - "GL_NV_multisample_coverage", - "GL_NV_multisample_filter_hint", - "GL_NV_occlusion_query", - "GL_NV_packed_depth_stencil", - "GL_NV_parameter_buffer_object", - "GL_NV_parameter_buffer_object2", - "GL_NV_path_rendering", - "GL_NV_pixel_data_range", - "GL_NV_point_sprite", - "GL_NV_present_video", - "GL_NV_primitive_restart", - "GL_NV_register_combiners", - "GL_NV_register_combiners2", - "GL_NV_shader_atomic_counters", - "GL_NV_shader_atomic_float", - "GL_NV_shader_buffer_load", - "GL_NV_shader_buffer_store", - "GL_NV_shader_storage_buffer_object", - "GL_NV_tessellation_program5", - "GL_NV_texgen_emboss", - "GL_NV_texgen_reflection", - "GL_NV_texture_barrier", - "GL_NV_texture_compression_vtc", - "GL_NV_texture_env_combine4", - "GL_NV_texture_expand_normal", - "GL_NV_texture_multisample", - "GL_NV_texture_rectangle", - "GL_NV_texture_shader", - "GL_NV_texture_shader2", - "GL_NV_texture_shader3", - "GL_NV_transform_feedback", - "GL_NV_transform_feedback2", - "GL_NV_vdpau_interop", - "GL_NV_vertex_array_range", - "GL_NV_vertex_array_range2", - "GL_NV_vertex_attrib_integer_64bit", - "GL_NV_vertex_buffer_unified_memory", - "GL_NV_vertex_program", - "GL_NV_vertex_program1_1", - "GL_NV_vertex_program2", - "GL_NV_vertex_program2_option", - "GL_NV_vertex_program3", - "GL_NV_vertex_program4", - "GL_NV_video_capture", - "GL_OES_byte_coordinates", - "GL_OES_compressed_paletted_texture", - "GL_OES_fixed_point", - "GL_OES_query_matrix", - "GL_OES_read_format", - "GL_OES_single_precision", - "GL_OML_interlace", - "GL_OML_resample", - "GL_OML_subsample", - "GL_PGI_misc_hints", - "GL_PGI_vertex_hints", - "GL_REND_screen_coordinates", - "GL_S3_s3tc", - "GL_SGI_color_matrix", - "GL_SGI_color_table", - "GL_SGI_texture_color_table", - "GL_SGIS_detail_texture", - "GL_SGIS_fog_function", - "GL_SGIS_generate_mipmap", - "GL_SGIS_multisample", - "GL_SGIS_pixel_texture", - "GL_SGIS_point_line_texgen", - "GL_SGIS_point_parameters", - "GL_SGIS_sharpen_texture", - "GL_SGIS_texture4D", - "GL_SGIS_texture_border_clamp", - "GL_SGIS_texture_color_mask", - "GL_SGIS_texture_edge_clamp", - "GL_SGIS_texture_filter4", - "GL_SGIS_texture_lod", - "GL_SGIS_texture_select", - "GL_SGIX_async", - "GL_SGIX_async_histogram", - "GL_SGIX_async_pixel", - "GL_SGIX_blend_alpha_minmax", - "GL_SGIX_calligraphic_fragment", - "GL_SGIX_clipmap", - "GL_SGIX_convolution_accuracy", - "GL_SGIX_depth_pass_instrument", - "GL_SGIX_depth_texture", - "GL_SGIX_flush_raster", - "GL_SGIX_fog_offset", - "GL_SGIX_fog_scale", - "GL_SGIX_fragment_lighting", - "GL_SGIX_framezoom", - "GL_SGIX_igloo_interface", - "GL_SGIX_instruments", - "GL_SGIX_interlace", - "GL_SGIX_ir_instrument1", - "GL_SGIX_list_priority", - "GL_SGIX_pixel_texture", - "GL_SGIX_pixel_tiles", - "GL_SGIX_polynomial_ffd", - "GL_SGIX_reference_plane", - "GL_SGIX_resample", - "GL_SGIX_scalebias_hint", - "GL_SGIX_shadow", - "GL_SGIX_shadow_ambient", - "GL_SGIX_sprite", - "GL_SGIX_subsample", - "GL_SGIX_tag_sample_buffer", - "GL_SGIX_texture_add_env", - "GL_SGIX_texture_coordinate_clamp", - "GL_SGIX_texture_lod_bias", - "GL_SGIX_texture_multi_buffer", - "GL_SGIX_texture_scale_bias", - "GL_SGIX_vertex_preclip", - "GL_SGIX_ycrcb", - "GL_SGIX_ycrcba", - "GL_SGIX_ycrcb_subsample", - "GL_SUN_convolution_border_modes", - "GL_SUN_global_alpha", - "GL_SUN_mesh_array", - "GL_SUN_slice_accum", - "GL_SUN_triangle_list", - "GL_SUN_vertex", - "GL_SUNX_constant_data", - "GL_WIN_phong_shading", - "GL_WIN_specular_fog", - // unofficial stuff - "GL_NVX_gpu_memory_info" -}; - +static const char *const OpenGLFeatureStrings[] = { + "GL_3DFX_multisample", + "GL_3DFX_tbuffer", + "GL_3DFX_texture_compression_FXT1", + "GL_AMD_blend_minmax_factor", + "GL_AMD_conservative_depth", + "GL_AMD_debug_output", + "GL_AMD_depth_clamp_separate", + "GL_AMD_draw_buffers_blend", + "GL_AMD_interleaved_elements", + "GL_AMD_multi_draw_indirect", + "GL_AMD_name_gen_delete", + "GL_AMD_performance_monitor", + "GL_AMD_pinned_memory", + "GL_AMD_query_buffer_object", + "GL_AMD_sample_positions", + "GL_AMD_seamless_cubemap_per_texture", + "GL_AMD_shader_atomic_counter_ops", + "GL_AMD_shader_stencil_export", + "GL_AMD_shader_trinary_minmax", + "GL_AMD_sparse_texture", + "GL_AMD_stencil_operation_extended", + "GL_AMD_texture_texture4", + "GL_AMD_transform_feedback3_lines_triangles", + "GL_AMD_vertex_shader_layer", + "GL_AMD_vertex_shader_tessellator", + "GL_AMD_vertex_shader_viewport_index", + "GL_APPLE_aux_depth_stencil", + "GL_APPLE_client_storage", + "GL_APPLE_element_array", + "GL_APPLE_fence", + "GL_APPLE_float_pixels", + "GL_APPLE_flush_buffer_range", + "GL_APPLE_object_purgeable", + "GL_APPLE_rgb_422", + "GL_APPLE_row_bytes", + "GL_APPLE_specular_vector", + "GL_APPLE_texture_range", + "GL_APPLE_transform_hint", + "GL_APPLE_vertex_array_object", + "GL_APPLE_vertex_array_range", + "GL_APPLE_vertex_program_evaluators", + "GL_APPLE_ycbcr_422", + "GL_ARB_arrays_of_arrays", + "GL_ARB_base_instance", + "GL_ARB_bindless_texture", + "GL_ARB_blend_func_extended", + "GL_ARB_buffer_storage", + "GL_ARB_cl_event", + "GL_ARB_clear_buffer_object", + "GL_ARB_clear_texture", + "GL_ARB_color_buffer_float", + "GL_ARB_compatibility", + "GL_ARB_compressed_texture_pixel_storage", + "GL_ARB_compute_shader", + "GL_ARB_compute_variable_group_size", + "GL_ARB_conservative_depth", + "GL_ARB_copy_buffer", + "GL_ARB_copy_image", + "GL_ARB_debug_output", + "GL_ARB_depth_buffer_float", + "GL_ARB_depth_clamp", + "GL_ARB_depth_texture", + "GL_ARB_direct_state_access", + "GL_ARB_draw_buffers", + "GL_ARB_draw_buffers_blend", + "GL_ARB_draw_elements_base_vertex", + "GL_ARB_draw_indirect", + "GL_ARB_draw_instanced", + "GL_ARB_ES2_compatibility", + "GL_ARB_ES3_compatibility", + "GL_ARB_enhanced_layouts", + "GL_ARB_explicit_attrib_location", + "GL_ARB_explicit_uniform_location", + "GL_ARB_fragment_coord_conventions", + "GL_ARB_fragment_layer_viewport", + "GL_ARB_fragment_program", + "GL_ARB_fragment_program_shadow", + "GL_ARB_fragment_shader", + "GL_ARB_framebuffer_no_attachments", + "GL_ARB_framebuffer_object", + "GL_ARB_framebuffer_sRGB", + "GL_ARB_geometry_shader4", + "GL_ARB_get_program_binary", + "GL_ARB_gpu_shader5", + "GL_ARB_gpu_shader_fp64", + "GL_ARB_half_float_pixel", + "GL_ARB_half_float_vertex", + "GL_ARB_imaging", + "GL_ARB_indirect_parameters", + "GL_ARB_instanced_arrays", + "GL_ARB_internalformat_query", + "GL_ARB_internalformat_query2", + "GL_ARB_invalidate_subdata", + "GL_ARB_map_buffer_alignment", + "GL_ARB_map_buffer_range", + "GL_ARB_matrix_palette", + "GL_ARB_multi_bind", + "GL_ARB_multi_draw_indirect", + "GL_ARB_multisample", + "GL_ARB_multitexture", + "GL_ARB_occlusion_query", + "GL_ARB_occlusion_query2", + "GL_ARB_pixel_buffer_object", + "GL_ARB_point_parameters", + "GL_ARB_point_sprite", + "GL_ARB_program_interface_query", + "GL_ARB_provoking_vertex", + "GL_ARB_query_buffer_object", + "GL_ARB_robust_buffer_access_behavior", + "GL_ARB_robustness", + "GL_ARB_robustness_isolation", + "GL_ARB_sample_shading", + "GL_ARB_sampler_objects", + "GL_ARB_seamless_cube_map", + "GL_ARB_seamless_cubemap_per_texture", + "GL_ARB_separate_shader_objects", + "GL_ARB_shader_atomic_counters", + "GL_ARB_shader_bit_encoding", + "GL_ARB_shader_draw_parameters", + "GL_ARB_shader_group_vote", + "GL_ARB_shader_image_load_store", + "GL_ARB_shader_image_size", + "GL_ARB_shader_objects", + "GL_ARB_shader_precision", + "GL_ARB_shader_stencil_export", + "GL_ARB_shader_storage_buffer_object", + "GL_ARB_shader_subroutine", + "GL_ARB_shader_texture_lod", + "GL_ARB_shading_language_100", + "GL_ARB_shading_language_420pack", + "GL_ARB_shading_language_include", + "GL_ARB_shading_language_packing", + "GL_ARB_shadow", + "GL_ARB_shadow_ambient", + "GL_ARB_sparse_texture", + "GL_ARB_stencil_texturing", + "GL_ARB_sync", + "GL_ARB_tessellation_shader", + "GL_ARB_texture_border_clamp", + "GL_ARB_texture_buffer_object", + "GL_ARB_texture_buffer_object_rgb32", + "GL_ARB_texture_buffer_range", + "GL_ARB_texture_compression", + "GL_ARB_texture_compression_bptc", + "GL_ARB_texture_compression_rgtc", + "GL_ARB_texture_cube_map", + "GL_ARB_texture_cube_map_array", + "GL_ARB_texture_env_add", + "GL_ARB_texture_env_combine", + "GL_ARB_texture_env_crossbar", + "GL_ARB_texture_env_dot3", + "GL_ARB_texture_float", + "GL_ARB_texture_gather", + "GL_ARB_texture_mirror_clamp_to_edge", + "GL_ARB_texture_mirrored_repeat", + "GL_ARB_texture_multisample", + "GL_ARB_texture_non_power_of_two", + "GL_ARB_texture_query_levels", + "GL_ARB_texture_query_lod", + "GL_ARB_texture_rectangle", + "GL_ARB_texture_rg", + "GL_ARB_texture_rgb10_a2ui", + "GL_ARB_texture_stencil8", + "GL_ARB_texture_storage", + "GL_ARB_texture_storage_multisample", + "GL_ARB_texture_swizzle", + "GL_ARB_texture_view", + "GL_ARB_timer_query", + "GL_ARB_transform_feedback2", + "GL_ARB_transform_feedback3", + "GL_ARB_transform_feedback_instanced", + "GL_ARB_transpose_matrix", + "GL_ARB_uniform_buffer_object", + "GL_ARB_vertex_array_bgra", + "GL_ARB_vertex_array_object", + "GL_ARB_vertex_attrib_64bit", + "GL_ARB_vertex_attrib_binding", + "GL_ARB_vertex_blend", + "GL_ARB_vertex_buffer_object", + "GL_ARB_vertex_program", + "GL_ARB_vertex_shader", + "GL_ARB_vertex_type_10f_11f_11f_rev", + "GL_ARB_vertex_type_2_10_10_10_rev", + "GL_ARB_viewport_array", + "GL_ARB_window_pos", + "GL_ATI_draw_buffers", + "GL_ATI_element_array", + "GL_ATI_envmap_bumpmap", + "GL_ATI_fragment_shader", + "GL_ATI_map_object_buffer", + "GL_ATI_meminfo", + "GL_ATI_pixel_format_float", + "GL_ATI_pn_triangles", + "GL_ATI_separate_stencil", + "GL_ATI_text_fragment_shader", + "GL_ATI_texture_env_combine3", + "GL_ATI_texture_float", + "GL_ATI_texture_mirror_once", + "GL_ATI_vertex_array_object", + "GL_ATI_vertex_attrib_array_object", + "GL_ATI_vertex_streams", + "GL_EXT_422_pixels", + "GL_EXT_abgr", + "GL_EXT_bgra", + "GL_EXT_bindable_uniform", + "GL_EXT_blend_color", + "GL_EXT_blend_equation_separate", + "GL_EXT_blend_func_separate", + "GL_EXT_blend_logic_op", + "GL_EXT_blend_minmax", + "GL_EXT_blend_subtract", + "GL_EXT_clip_volume_hint", + "GL_EXT_cmyka", + "GL_EXT_color_subtable", + "GL_EXT_compiled_vertex_array", + "GL_EXT_convolution", + "GL_EXT_coordinate_frame", + "GL_EXT_copy_texture", + "GL_EXT_cull_vertex", + "GL_EXT_debug_label", + "GL_EXT_debug_marker", + "GL_EXT_depth_bounds_test", + "GL_EXT_direct_state_access", + "GL_EXT_draw_buffers2", + "GL_EXT_draw_instanced", + "GL_EXT_draw_range_elements", + "GL_EXT_fog_coord", + "GL_EXT_framebuffer_blit", + "GL_EXT_framebuffer_multisample", + "GL_EXT_framebuffer_multisample_blit_scaled", + "GL_EXT_framebuffer_object", + "GL_EXT_framebuffer_sRGB", + "GL_EXT_geometry_shader4", + "GL_EXT_gpu_program_parameters", + "GL_EXT_gpu_shader4", + "GL_EXT_histogram", + "GL_EXT_index_array_formats", + "GL_EXT_index_func", + "GL_EXT_index_material", + "GL_EXT_index_texture", + "GL_EXT_light_texture", + "GL_EXT_misc_attribute", + "GL_EXT_multi_draw_arrays", + "GL_EXT_multisample", + "GL_EXT_packed_depth_stencil", + "GL_EXT_packed_float", + "GL_EXT_packed_pixels", + "GL_EXT_paletted_texture", + "GL_EXT_pixel_buffer_object", + "GL_EXT_pixel_transform", + "GL_EXT_pixel_transform_color_table", + "GL_EXT_point_parameters", + "GL_EXT_polygon_offset", + "GL_EXT_provoking_vertex", + "GL_EXT_rescale_normal", + "GL_EXT_secondary_color", + "GL_EXT_separate_shader_objects", + "GL_EXT_separate_specular_color", + "GL_EXT_shader_image_load_store", + "GL_EXT_shader_integer_mix", + "GL_EXT_shadow_funcs", + "GL_EXT_shared_texture_palette", + "GL_EXT_stencil_clear_tag", + "GL_EXT_stencil_two_side", + "GL_EXT_stencil_wrap", + "GL_EXT_subtexture", + "GL_EXT_texture", + "GL_EXT_texture3D", + "GL_EXT_texture_array", + "GL_EXT_texture_buffer_object", + "GL_EXT_texture_compression_latc", + "GL_EXT_texture_compression_rgtc", + "GL_EXT_texture_compression_s3tc", + "GL_EXT_texture_cube_map", + "GL_EXT_texture_env_add", + "GL_EXT_texture_env_combine", + "GL_EXT_texture_env_dot3", + "GL_EXT_texture_filter_anisotropic", + "GL_EXT_texture_integer", + "GL_EXT_texture_lod_bias", + "GL_EXT_texture_mirror_clamp", + "GL_EXT_texture_object", + "GL_EXT_texture_perturb_normal", + "GL_EXT_texture_shared_exponent", + "GL_EXT_texture_snorm", + "GL_EXT_texture_sRGB", + "GL_EXT_texture_sRGB_decode", + "GL_EXT_texture_swizzle", + "GL_EXT_timer_query", + "GL_EXT_transform_feedback", + "GL_EXT_vertex_array", + "GL_EXT_vertex_array_bgra", + "GL_EXT_vertex_attrib_64bit", + "GL_EXT_vertex_shader", + "GL_EXT_vertex_weighting", + "GL_EXT_x11_sync_object", + "GL_GREMEDY_frame_terminator", + "GL_GREMEDY_string_marker", + "GL_HP_convolution_border_modes", + "GL_HP_image_transform", + "GL_HP_occlusion_test", + "GL_HP_texture_lighting", + "GL_IBM_cull_vertex", + "GL_IBM_multimode_draw_arrays", + "GL_IBM_rasterpos_clip", + "GL_IBM_static_data", + "GL_IBM_texture_mirrored_repeat", + "GL_IBM_vertex_array_lists", + "GL_INGR_blend_func_separate", + "GL_INGR_color_clamp", + "GL_INGR_interlace_read", + "GL_INGR_palette_buffer", + "GL_INTEL_map_texture", + "GL_INTEL_parallel_arrays", + "GL_INTEL_texture_scissor", + "GL_KHR_debug", + "GL_KHR_texture_compression_astc_hdr", + "GL_KHR_texture_compression_astc_ldr", + "GL_MESA_pack_invert", + "GL_MESA_resize_buffers", + "GL_MESA_window_pos", + "GL_MESAX_texture_stack", + "GL_MESA_ycbcr_texture", + "GL_NVX_conditional_render", + "GL_NV_bindless_multi_draw_indirect", + "GL_NV_bindless_texture", + "GL_NV_blend_equation_advanced", + "GL_NV_blend_equation_advanced_coherent", + "GL_NV_blend_square", + "GL_NV_compute_program5", + "GL_NV_conditional_render", + "GL_NV_copy_depth_to_color", + "GL_NV_copy_image", + "GL_NV_deep_texture3D", + "GL_NV_depth_buffer_float", + "GL_NV_depth_clamp", + "GL_NV_draw_texture", + "GL_NV_evaluators", + "GL_NV_explicit_multisample", + "GL_NV_fence", + "GL_NV_float_buffer", + "GL_NV_fog_distance", + "GL_NV_fragment_program", + "GL_NV_fragment_program2", + "GL_NV_fragment_program4", + "GL_NV_fragment_program_option", + "GL_NV_framebuffer_multisample_coverage", + "GL_NV_geometry_program4", + "GL_NV_geometry_shader4", + "GL_NV_gpu_program4", + "GL_NV_gpu_program5", + "GL_NV_gpu_program5_mem_extended", + "GL_NV_gpu_shader5", + "GL_NV_half_float", + "GL_NV_light_max_exponent", + "GL_NV_multisample_coverage", + "GL_NV_multisample_filter_hint", + "GL_NV_occlusion_query", + "GL_NV_packed_depth_stencil", + "GL_NV_parameter_buffer_object", + "GL_NV_parameter_buffer_object2", + "GL_NV_path_rendering", + "GL_NV_pixel_data_range", + "GL_NV_point_sprite", + "GL_NV_present_video", + "GL_NV_primitive_restart", + "GL_NV_register_combiners", + "GL_NV_register_combiners2", + "GL_NV_shader_atomic_counters", + "GL_NV_shader_atomic_float", + "GL_NV_shader_buffer_load", + "GL_NV_shader_buffer_store", + "GL_NV_shader_storage_buffer_object", + "GL_NV_tessellation_program5", + "GL_NV_texgen_emboss", + "GL_NV_texgen_reflection", + "GL_NV_texture_barrier", + "GL_NV_texture_compression_vtc", + "GL_NV_texture_env_combine4", + "GL_NV_texture_expand_normal", + "GL_NV_texture_multisample", + "GL_NV_texture_rectangle", + "GL_NV_texture_shader", + "GL_NV_texture_shader2", + "GL_NV_texture_shader3", + "GL_NV_transform_feedback", + "GL_NV_transform_feedback2", + "GL_NV_vdpau_interop", + "GL_NV_vertex_array_range", + "GL_NV_vertex_array_range2", + "GL_NV_vertex_attrib_integer_64bit", + "GL_NV_vertex_buffer_unified_memory", + "GL_NV_vertex_program", + "GL_NV_vertex_program1_1", + "GL_NV_vertex_program2", + "GL_NV_vertex_program2_option", + "GL_NV_vertex_program3", + "GL_NV_vertex_program4", + "GL_NV_video_capture", + "GL_OES_byte_coordinates", + "GL_OES_compressed_paletted_texture", + "GL_OES_fixed_point", + "GL_OES_query_matrix", + "GL_OES_read_format", + "GL_OES_single_precision", + "GL_OML_interlace", + "GL_OML_resample", + "GL_OML_subsample", + "GL_PGI_misc_hints", + "GL_PGI_vertex_hints", + "GL_REND_screen_coordinates", + "GL_S3_s3tc", + "GL_SGI_color_matrix", + "GL_SGI_color_table", + "GL_SGI_texture_color_table", + "GL_SGIS_detail_texture", + "GL_SGIS_fog_function", + "GL_SGIS_generate_mipmap", + "GL_SGIS_multisample", + "GL_SGIS_pixel_texture", + "GL_SGIS_point_line_texgen", + "GL_SGIS_point_parameters", + "GL_SGIS_sharpen_texture", + "GL_SGIS_texture4D", + "GL_SGIS_texture_border_clamp", + "GL_SGIS_texture_color_mask", + "GL_SGIS_texture_edge_clamp", + "GL_SGIS_texture_filter4", + "GL_SGIS_texture_lod", + "GL_SGIS_texture_select", + "GL_SGIX_async", + "GL_SGIX_async_histogram", + "GL_SGIX_async_pixel", + "GL_SGIX_blend_alpha_minmax", + "GL_SGIX_calligraphic_fragment", + "GL_SGIX_clipmap", + "GL_SGIX_convolution_accuracy", + "GL_SGIX_depth_pass_instrument", + "GL_SGIX_depth_texture", + "GL_SGIX_flush_raster", + "GL_SGIX_fog_offset", + "GL_SGIX_fog_scale", + "GL_SGIX_fragment_lighting", + "GL_SGIX_framezoom", + "GL_SGIX_igloo_interface", + "GL_SGIX_instruments", + "GL_SGIX_interlace", + "GL_SGIX_ir_instrument1", + "GL_SGIX_list_priority", + "GL_SGIX_pixel_texture", + "GL_SGIX_pixel_tiles", + "GL_SGIX_polynomial_ffd", + "GL_SGIX_reference_plane", + "GL_SGIX_resample", + "GL_SGIX_scalebias_hint", + "GL_SGIX_shadow", + "GL_SGIX_shadow_ambient", + "GL_SGIX_sprite", + "GL_SGIX_subsample", + "GL_SGIX_tag_sample_buffer", + "GL_SGIX_texture_add_env", + "GL_SGIX_texture_coordinate_clamp", + "GL_SGIX_texture_lod_bias", + "GL_SGIX_texture_multi_buffer", + "GL_SGIX_texture_scale_bias", + "GL_SGIX_vertex_preclip", + "GL_SGIX_ycrcb", + "GL_SGIX_ycrcba", + "GL_SGIX_ycrcb_subsample", + "GL_SUN_convolution_border_modes", + "GL_SUN_global_alpha", + "GL_SUN_mesh_array", + "GL_SUN_slice_accum", + "GL_SUN_triangle_list", + "GL_SUN_vertex", + "GL_SUNX_constant_data", + "GL_WIN_phong_shading", + "GL_WIN_specular_fog", + // unofficial stuff + "GL_NVX_gpu_memory_info"}; class COpenGLExtensionHandler { - public: - enum EOpenGLFeatures { +public: + enum EOpenGLFeatures + { IRR_3DFX_multisample = 0, IRR_3DFX_tbuffer, IRR_3DFX_texture_compression_FXT1, @@ -991,14 +990,13 @@ class COpenGLExtensionHandler IRR_OpenGL_Feature_Count }; - // constructor COpenGLExtensionHandler(); // deferred initialization void initExtensions(video::IContextManager *cmgr, bool stencilBuffer); - const COpenGLCoreFeature& getFeature() const; + const COpenGLCoreFeature &getFeature() const; //! queries the features of the driver, returns true if feature is available bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const; @@ -1055,7 +1053,7 @@ class COpenGLExtensionHandler //! Workaround until direct state access with framebuffers is stable enough in drivers // https://devtalk.nvidia.com/default/topic/1030494/opengl/bug-amp-amp-spec-violation-checknamedframebufferstatus-returns-gl_framebuffer_incomplete_dimensions_ext-under-gl-4-5-core/ // https://stackoverflow.com/questions/51304706/problems-with-attaching-textures-of-different-sizes-to-fbo - static bool needsDSAFramebufferHack; + static bool needsDSAFramebufferHack; // public access to the (loaded) extensions. // general functions @@ -1063,14 +1061,14 @@ class COpenGLExtensionHandler void irrGlClientActiveTexture(GLenum texture); void extGlPointParameterf(GLint loc, GLfloat f); void extGlPointParameterfv(GLint loc, const GLfloat *v); - void extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); - void extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass); + void extGlStencilFuncSeparate(GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); + void extGlStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass); void irrGlCompressedTexImage2D(GLenum target, GLint level, - GLenum internalformat, GLsizei width, GLsizei height, - GLint border, GLsizei imageSize, const void* data); + GLenum internalformat, GLsizei width, GLsizei height, + GLint border, GLsizei imageSize, const void *data); void irrGlCompressedTexSubImage2D(GLenum target, GLint level, - GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLsizei imageSize, const void* data); + GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, + GLenum format, GLsizei imageSize, const void *data); // shader programming void extGlGenPrograms(GLsizei n, GLuint *programs); @@ -1105,8 +1103,8 @@ class COpenGLExtensionHandler void extGlDeleteObject(GLhandleARB object); void extGlDeleteProgram(GLuint object); void extGlDeleteShader(GLuint shader); - void extGlGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders); - void extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei* count, GLhandleARB* shaders); + void extGlGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei *count, GLuint *shaders); + void extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei *count, GLhandleARB *shaders); void extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); void extGlGetShaderInfoLog(GLuint shader, GLsizei maxLength, GLsizei *length, GLchar *infoLog); void extGlGetProgramInfoLog(GLuint program, GLsizei maxLength, GLsizei *length, GLchar *infoLog); @@ -1164,13 +1162,13 @@ class COpenGLExtensionHandler void extGlBindBuffer(GLenum target, GLuint buffer); void extGlBufferData(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); void extGlDeleteBuffers(GLsizei n, const GLuint *buffers); - void extGlBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); - void extGlGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); - void *extGlMapBuffer (GLenum target, GLenum access); - GLboolean extGlUnmapBuffer (GLenum target); - GLboolean extGlIsBuffer (GLuint buffer); - void extGlGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); - void extGlGetBufferPointerv (GLenum target, GLenum pname, GLvoid **params); + void extGlBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); + void extGlGetBufferSubData(GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); + void *extGlMapBuffer(GLenum target, GLenum access); + GLboolean extGlUnmapBuffer(GLenum target); + GLboolean extGlIsBuffer(GLuint buffer); + void extGlGetBufferParameteriv(GLenum target, GLenum pname, GLint *params); + void extGlGetBufferPointerv(GLenum target, GLenum pname, GLvoid **params); void extGlProvokingVertex(GLenum mode); void extGlProgramParameteri(GLuint program, GLenum pname, GLint value); @@ -1197,20 +1195,19 @@ class COpenGLExtensionHandler void irrGlBlendEquationIndexed(GLuint buf, GLenum mode); void irrGlBlendEquationSeparateIndexed(GLuint buf, GLenum modeRGB, GLenum modeAlpha); - void extGlTextureSubImage2D(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels); - void extGlTextureStorage2D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); - void extGlTextureStorage3D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); - void extGlGetTextureImage(GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void* pixels); - void extGlNamedFramebufferTexture(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); - void extGlTextureParameteri(GLuint texture, GLenum pname, GLint param); - void extGlTextureParameterf(GLuint texture, GLenum pname, GLfloat param); - void extGlTextureParameteriv(GLuint texture, GLenum pname, const GLint* params); - void extGlTextureParameterfv(GLuint texture, GLenum pname, const GLfloat* params); - void extGlCreateTextures(GLenum target, GLsizei n, GLuint* textures); - void extGlCreateFramebuffers(GLsizei n, GLuint* framebuffers); - void extGlBindTextures(GLuint first, GLsizei count, const GLuint *textures, const GLenum* targets); - void extGlGenerateTextureMipmap(GLuint texture, GLenum target); - + void extGlTextureSubImage2D(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); + void extGlTextureStorage2D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); + void extGlTextureStorage3D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); + void extGlGetTextureImage(GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); + void extGlNamedFramebufferTexture(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); + void extGlTextureParameteri(GLuint texture, GLenum pname, GLint param); + void extGlTextureParameterf(GLuint texture, GLenum pname, GLfloat param); + void extGlTextureParameteriv(GLuint texture, GLenum pname, const GLint *params); + void extGlTextureParameterfv(GLuint texture, GLenum pname, const GLfloat *params); + void extGlCreateTextures(GLenum target, GLsizei n, GLuint *textures); + void extGlCreateFramebuffers(GLsizei n, GLuint *framebuffers); + void extGlBindTextures(GLuint first, GLsizei count, const GLuint *textures, const GLenum *targets); + void extGlGenerateTextureMipmap(GLuint texture, GLenum target); // generic vsync setting method for several extensions void extGlSwapInterval(int interval); @@ -1218,194 +1215,194 @@ class COpenGLExtensionHandler // the global feature array bool FeatureAvailable[IRR_OpenGL_Feature_Count]; - protected: - COpenGLCoreFeature Feature; +protected: + COpenGLCoreFeature Feature; - PFNGLACTIVETEXTUREPROC pGlActiveTexture; - PFNGLACTIVETEXTUREARBPROC pGlActiveTextureARB; - PFNGLCLIENTACTIVETEXTUREARBPROC pGlClientActiveTextureARB; - PFNGLGENPROGRAMSARBPROC pGlGenProgramsARB; - PFNGLGENPROGRAMSNVPROC pGlGenProgramsNV; - PFNGLBINDPROGRAMARBPROC pGlBindProgramARB; - PFNGLBINDPROGRAMNVPROC pGlBindProgramNV; - PFNGLDELETEPROGRAMSARBPROC pGlDeleteProgramsARB; - PFNGLDELETEPROGRAMSNVPROC pGlDeleteProgramsNV; - PFNGLPROGRAMSTRINGARBPROC pGlProgramStringARB; - PFNGLLOADPROGRAMNVPROC pGlLoadProgramNV; - PFNGLPROGRAMLOCALPARAMETER4FVARBPROC pGlProgramLocalParameter4fvARB; - PFNGLCREATESHADEROBJECTARBPROC pGlCreateShaderObjectARB; - PFNGLSHADERSOURCEARBPROC pGlShaderSourceARB; - PFNGLCOMPILESHADERARBPROC pGlCompileShaderARB; - PFNGLCREATEPROGRAMOBJECTARBPROC pGlCreateProgramObjectARB; - PFNGLATTACHOBJECTARBPROC pGlAttachObjectARB; - PFNGLLINKPROGRAMARBPROC pGlLinkProgramARB; - PFNGLUSEPROGRAMOBJECTARBPROC pGlUseProgramObjectARB; - PFNGLDELETEOBJECTARBPROC pGlDeleteObjectARB; - PFNGLCREATEPROGRAMPROC pGlCreateProgram; - PFNGLUSEPROGRAMPROC pGlUseProgram; - PFNGLDELETEPROGRAMPROC pGlDeleteProgram; - PFNGLDELETESHADERPROC pGlDeleteShader; - PFNGLGETATTACHEDOBJECTSARBPROC pGlGetAttachedObjectsARB; - PFNGLGETATTACHEDSHADERSPROC pGlGetAttachedShaders; - PFNGLCREATESHADERPROC pGlCreateShader; - PFNGLSHADERSOURCEPROC pGlShaderSource; - PFNGLCOMPILESHADERPROC pGlCompileShader; - PFNGLATTACHSHADERPROC pGlAttachShader; - PFNGLLINKPROGRAMPROC pGlLinkProgram; - PFNGLGETINFOLOGARBPROC pGlGetInfoLogARB; - PFNGLGETSHADERINFOLOGPROC pGlGetShaderInfoLog; - PFNGLGETPROGRAMINFOLOGPROC pGlGetProgramInfoLog; - PFNGLGETOBJECTPARAMETERIVARBPROC pGlGetObjectParameterivARB; - PFNGLGETSHADERIVPROC pGlGetShaderiv; - PFNGLGETSHADERIVPROC pGlGetProgramiv; - PFNGLGETUNIFORMLOCATIONARBPROC pGlGetUniformLocationARB; - PFNGLGETUNIFORMLOCATIONPROC pGlGetUniformLocation; - PFNGLUNIFORM1FVARBPROC pGlUniform1fvARB; - PFNGLUNIFORM2FVARBPROC pGlUniform2fvARB; - PFNGLUNIFORM3FVARBPROC pGlUniform3fvARB; - PFNGLUNIFORM4FVARBPROC pGlUniform4fvARB; - PFNGLUNIFORM1IVARBPROC pGlUniform1ivARB; - PFNGLUNIFORM2IVARBPROC pGlUniform2ivARB; - PFNGLUNIFORM3IVARBPROC pGlUniform3ivARB; - PFNGLUNIFORM4IVARBPROC pGlUniform4ivARB; - PFNGLUNIFORM1UIVPROC pGlUniform1uiv; - PFNGLUNIFORM2UIVPROC pGlUniform2uiv; - PFNGLUNIFORM3UIVPROC pGlUniform3uiv; - PFNGLUNIFORM4UIVPROC pGlUniform4uiv; - PFNGLUNIFORMMATRIX2FVARBPROC pGlUniformMatrix2fvARB; - PFNGLUNIFORMMATRIX2X3FVPROC pGlUniformMatrix2x3fv; - PFNGLUNIFORMMATRIX2X4FVPROC pGlUniformMatrix2x4fv; - PFNGLUNIFORMMATRIX3X2FVPROC pGlUniformMatrix3x2fv; - PFNGLUNIFORMMATRIX3FVARBPROC pGlUniformMatrix3fvARB; - PFNGLUNIFORMMATRIX3X4FVPROC pGlUniformMatrix3x4fv; - PFNGLUNIFORMMATRIX4X2FVPROC pGlUniformMatrix4x2fv; - PFNGLUNIFORMMATRIX4X3FVPROC pGlUniformMatrix4x3fv; - PFNGLUNIFORMMATRIX4FVARBPROC pGlUniformMatrix4fvARB; - PFNGLGETACTIVEUNIFORMARBPROC pGlGetActiveUniformARB; - PFNGLGETACTIVEUNIFORMPROC pGlGetActiveUniform; - PFNGLPOINTPARAMETERFARBPROC pGlPointParameterfARB; - PFNGLPOINTPARAMETERFVARBPROC pGlPointParameterfvARB; - PFNGLSTENCILFUNCSEPARATEPROC pGlStencilFuncSeparate; - PFNGLSTENCILOPSEPARATEPROC pGlStencilOpSeparate; - PFNGLSTENCILFUNCSEPARATEATIPROC pGlStencilFuncSeparateATI; - PFNGLSTENCILOPSEPARATEATIPROC pGlStencilOpSeparateATI; - PFNGLCOMPRESSEDTEXIMAGE2DPROC pGlCompressedTexImage2D; - PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC pGlCompressedTexSubImage2D; - // ARB framebuffer object - PFNGLBINDFRAMEBUFFERPROC pGlBindFramebuffer; - PFNGLDELETEFRAMEBUFFERSPROC pGlDeleteFramebuffers; - PFNGLGENFRAMEBUFFERSPROC pGlGenFramebuffers; - PFNGLCHECKFRAMEBUFFERSTATUSPROC pGlCheckFramebufferStatus; - PFNGLFRAMEBUFFERTEXTURE2DPROC pGlFramebufferTexture2D; - PFNGLBINDRENDERBUFFERPROC pGlBindRenderbuffer; - PFNGLDELETERENDERBUFFERSPROC pGlDeleteRenderbuffers; - PFNGLGENRENDERBUFFERSPROC pGlGenRenderbuffers; - PFNGLRENDERBUFFERSTORAGEPROC pGlRenderbufferStorage; - PFNGLFRAMEBUFFERRENDERBUFFERPROC pGlFramebufferRenderbuffer; - PFNGLGENERATEMIPMAPPROC pGlGenerateMipmap; - // EXT framebuffer object - PFNGLBINDFRAMEBUFFEREXTPROC pGlBindFramebufferEXT; - PFNGLDELETEFRAMEBUFFERSEXTPROC pGlDeleteFramebuffersEXT; - PFNGLGENFRAMEBUFFERSEXTPROC pGlGenFramebuffersEXT; - PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC pGlCheckFramebufferStatusEXT; - PFNGLFRAMEBUFFERTEXTURE2DEXTPROC pGlFramebufferTexture2DEXT; - PFNGLBINDRENDERBUFFEREXTPROC pGlBindRenderbufferEXT; - PFNGLDELETERENDERBUFFERSEXTPROC pGlDeleteRenderbuffersEXT; - PFNGLGENRENDERBUFFERSEXTPROC pGlGenRenderbuffersEXT; - PFNGLRENDERBUFFERSTORAGEEXTPROC pGlRenderbufferStorageEXT; - PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC pGlFramebufferRenderbufferEXT; - PFNGLGENERATEMIPMAPEXTPROC pGlGenerateMipmapEXT; - PFNGLACTIVESTENCILFACEEXTPROC pGlActiveStencilFaceEXT; - PFNGLDRAWBUFFERSARBPROC pGlDrawBuffersARB; - PFNGLDRAWBUFFERSATIPROC pGlDrawBuffersATI; - PFNGLGENBUFFERSARBPROC pGlGenBuffersARB; - PFNGLBINDBUFFERARBPROC pGlBindBufferARB; - PFNGLBUFFERDATAARBPROC pGlBufferDataARB; - PFNGLDELETEBUFFERSARBPROC pGlDeleteBuffersARB; - PFNGLBUFFERSUBDATAARBPROC pGlBufferSubDataARB; - PFNGLGETBUFFERSUBDATAARBPROC pGlGetBufferSubDataARB; - PFNGLMAPBUFFERARBPROC pGlMapBufferARB; - PFNGLUNMAPBUFFERARBPROC pGlUnmapBufferARB; - PFNGLISBUFFERARBPROC pGlIsBufferARB; - PFNGLGETBUFFERPARAMETERIVARBPROC pGlGetBufferParameterivARB; - PFNGLGETBUFFERPOINTERVARBPROC pGlGetBufferPointervARB; - PFNGLPROVOKINGVERTEXPROC pGlProvokingVertexARB; - PFNGLPROVOKINGVERTEXEXTPROC pGlProvokingVertexEXT; - PFNGLPROGRAMPARAMETERIARBPROC pGlProgramParameteriARB; - PFNGLPROGRAMPARAMETERIEXTPROC pGlProgramParameteriEXT; - PFNGLGENQUERIESARBPROC pGlGenQueriesARB; - PFNGLDELETEQUERIESARBPROC pGlDeleteQueriesARB; - PFNGLISQUERYARBPROC pGlIsQueryARB; - PFNGLBEGINQUERYARBPROC pGlBeginQueryARB; - PFNGLENDQUERYARBPROC pGlEndQueryARB; - PFNGLGETQUERYIVARBPROC pGlGetQueryivARB; - PFNGLGETQUERYOBJECTIVARBPROC pGlGetQueryObjectivARB; - PFNGLGETQUERYOBJECTUIVARBPROC pGlGetQueryObjectuivARB; - PFNGLGENOCCLUSIONQUERIESNVPROC pGlGenOcclusionQueriesNV; - PFNGLDELETEOCCLUSIONQUERIESNVPROC pGlDeleteOcclusionQueriesNV; - PFNGLISOCCLUSIONQUERYNVPROC pGlIsOcclusionQueryNV; - PFNGLBEGINOCCLUSIONQUERYNVPROC pGlBeginOcclusionQueryNV; - PFNGLENDOCCLUSIONQUERYNVPROC pGlEndOcclusionQueryNV; - PFNGLGETOCCLUSIONQUERYIVNVPROC pGlGetOcclusionQueryivNV; - PFNGLGETOCCLUSIONQUERYUIVNVPROC pGlGetOcclusionQueryuivNV; - // Blend - PFNGLBLENDFUNCSEPARATEEXTPROC pGlBlendFuncSeparateEXT; - PFNGLBLENDFUNCSEPARATEPROC pGlBlendFuncSeparate; - PFNGLBLENDEQUATIONEXTPROC pGlBlendEquationEXT; - PFNGLBLENDEQUATIONPROC pGlBlendEquation; - PFNGLBLENDEQUATIONSEPARATEEXTPROC pGlBlendEquationSeparateEXT; - PFNGLBLENDEQUATIONSEPARATEPROC pGlBlendEquationSeparate; - // Indexed - PFNGLENABLEINDEXEDEXTPROC pGlEnableIndexedEXT; - PFNGLDISABLEINDEXEDEXTPROC pGlDisableIndexedEXT; - PFNGLCOLORMASKINDEXEDEXTPROC pGlColorMaskIndexedEXT; - PFNGLBLENDFUNCINDEXEDAMDPROC pGlBlendFuncIndexedAMD; - PFNGLBLENDFUNCIPROC pGlBlendFunciARB; - PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC pGlBlendFuncSeparateIndexedAMD; - PFNGLBLENDFUNCSEPARATEIPROC pGlBlendFuncSeparateiARB; - PFNGLBLENDEQUATIONINDEXEDAMDPROC pGlBlendEquationIndexedAMD; - PFNGLBLENDEQUATIONIPROC pGlBlendEquationiARB; - PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC pGlBlendEquationSeparateIndexedAMD; - PFNGLBLENDEQUATIONSEPARATEIPROC pGlBlendEquationSeparateiARB; + PFNGLACTIVETEXTUREPROC pGlActiveTexture; + PFNGLACTIVETEXTUREARBPROC pGlActiveTextureARB; + PFNGLCLIENTACTIVETEXTUREARBPROC pGlClientActiveTextureARB; + PFNGLGENPROGRAMSARBPROC pGlGenProgramsARB; + PFNGLGENPROGRAMSNVPROC pGlGenProgramsNV; + PFNGLBINDPROGRAMARBPROC pGlBindProgramARB; + PFNGLBINDPROGRAMNVPROC pGlBindProgramNV; + PFNGLDELETEPROGRAMSARBPROC pGlDeleteProgramsARB; + PFNGLDELETEPROGRAMSNVPROC pGlDeleteProgramsNV; + PFNGLPROGRAMSTRINGARBPROC pGlProgramStringARB; + PFNGLLOADPROGRAMNVPROC pGlLoadProgramNV; + PFNGLPROGRAMLOCALPARAMETER4FVARBPROC pGlProgramLocalParameter4fvARB; + PFNGLCREATESHADEROBJECTARBPROC pGlCreateShaderObjectARB; + PFNGLSHADERSOURCEARBPROC pGlShaderSourceARB; + PFNGLCOMPILESHADERARBPROC pGlCompileShaderARB; + PFNGLCREATEPROGRAMOBJECTARBPROC pGlCreateProgramObjectARB; + PFNGLATTACHOBJECTARBPROC pGlAttachObjectARB; + PFNGLLINKPROGRAMARBPROC pGlLinkProgramARB; + PFNGLUSEPROGRAMOBJECTARBPROC pGlUseProgramObjectARB; + PFNGLDELETEOBJECTARBPROC pGlDeleteObjectARB; + PFNGLCREATEPROGRAMPROC pGlCreateProgram; + PFNGLUSEPROGRAMPROC pGlUseProgram; + PFNGLDELETEPROGRAMPROC pGlDeleteProgram; + PFNGLDELETESHADERPROC pGlDeleteShader; + PFNGLGETATTACHEDOBJECTSARBPROC pGlGetAttachedObjectsARB; + PFNGLGETATTACHEDSHADERSPROC pGlGetAttachedShaders; + PFNGLCREATESHADERPROC pGlCreateShader; + PFNGLSHADERSOURCEPROC pGlShaderSource; + PFNGLCOMPILESHADERPROC pGlCompileShader; + PFNGLATTACHSHADERPROC pGlAttachShader; + PFNGLLINKPROGRAMPROC pGlLinkProgram; + PFNGLGETINFOLOGARBPROC pGlGetInfoLogARB; + PFNGLGETSHADERINFOLOGPROC pGlGetShaderInfoLog; + PFNGLGETPROGRAMINFOLOGPROC pGlGetProgramInfoLog; + PFNGLGETOBJECTPARAMETERIVARBPROC pGlGetObjectParameterivARB; + PFNGLGETSHADERIVPROC pGlGetShaderiv; + PFNGLGETSHADERIVPROC pGlGetProgramiv; + PFNGLGETUNIFORMLOCATIONARBPROC pGlGetUniformLocationARB; + PFNGLGETUNIFORMLOCATIONPROC pGlGetUniformLocation; + PFNGLUNIFORM1FVARBPROC pGlUniform1fvARB; + PFNGLUNIFORM2FVARBPROC pGlUniform2fvARB; + PFNGLUNIFORM3FVARBPROC pGlUniform3fvARB; + PFNGLUNIFORM4FVARBPROC pGlUniform4fvARB; + PFNGLUNIFORM1IVARBPROC pGlUniform1ivARB; + PFNGLUNIFORM2IVARBPROC pGlUniform2ivARB; + PFNGLUNIFORM3IVARBPROC pGlUniform3ivARB; + PFNGLUNIFORM4IVARBPROC pGlUniform4ivARB; + PFNGLUNIFORM1UIVPROC pGlUniform1uiv; + PFNGLUNIFORM2UIVPROC pGlUniform2uiv; + PFNGLUNIFORM3UIVPROC pGlUniform3uiv; + PFNGLUNIFORM4UIVPROC pGlUniform4uiv; + PFNGLUNIFORMMATRIX2FVARBPROC pGlUniformMatrix2fvARB; + PFNGLUNIFORMMATRIX2X3FVPROC pGlUniformMatrix2x3fv; + PFNGLUNIFORMMATRIX2X4FVPROC pGlUniformMatrix2x4fv; + PFNGLUNIFORMMATRIX3X2FVPROC pGlUniformMatrix3x2fv; + PFNGLUNIFORMMATRIX3FVARBPROC pGlUniformMatrix3fvARB; + PFNGLUNIFORMMATRIX3X4FVPROC pGlUniformMatrix3x4fv; + PFNGLUNIFORMMATRIX4X2FVPROC pGlUniformMatrix4x2fv; + PFNGLUNIFORMMATRIX4X3FVPROC pGlUniformMatrix4x3fv; + PFNGLUNIFORMMATRIX4FVARBPROC pGlUniformMatrix4fvARB; + PFNGLGETACTIVEUNIFORMARBPROC pGlGetActiveUniformARB; + PFNGLGETACTIVEUNIFORMPROC pGlGetActiveUniform; + PFNGLPOINTPARAMETERFARBPROC pGlPointParameterfARB; + PFNGLPOINTPARAMETERFVARBPROC pGlPointParameterfvARB; + PFNGLSTENCILFUNCSEPARATEPROC pGlStencilFuncSeparate; + PFNGLSTENCILOPSEPARATEPROC pGlStencilOpSeparate; + PFNGLSTENCILFUNCSEPARATEATIPROC pGlStencilFuncSeparateATI; + PFNGLSTENCILOPSEPARATEATIPROC pGlStencilOpSeparateATI; + PFNGLCOMPRESSEDTEXIMAGE2DPROC pGlCompressedTexImage2D; + PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC pGlCompressedTexSubImage2D; + // ARB framebuffer object + PFNGLBINDFRAMEBUFFERPROC pGlBindFramebuffer; + PFNGLDELETEFRAMEBUFFERSPROC pGlDeleteFramebuffers; + PFNGLGENFRAMEBUFFERSPROC pGlGenFramebuffers; + PFNGLCHECKFRAMEBUFFERSTATUSPROC pGlCheckFramebufferStatus; + PFNGLFRAMEBUFFERTEXTURE2DPROC pGlFramebufferTexture2D; + PFNGLBINDRENDERBUFFERPROC pGlBindRenderbuffer; + PFNGLDELETERENDERBUFFERSPROC pGlDeleteRenderbuffers; + PFNGLGENRENDERBUFFERSPROC pGlGenRenderbuffers; + PFNGLRENDERBUFFERSTORAGEPROC pGlRenderbufferStorage; + PFNGLFRAMEBUFFERRENDERBUFFERPROC pGlFramebufferRenderbuffer; + PFNGLGENERATEMIPMAPPROC pGlGenerateMipmap; + // EXT framebuffer object + PFNGLBINDFRAMEBUFFEREXTPROC pGlBindFramebufferEXT; + PFNGLDELETEFRAMEBUFFERSEXTPROC pGlDeleteFramebuffersEXT; + PFNGLGENFRAMEBUFFERSEXTPROC pGlGenFramebuffersEXT; + PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC pGlCheckFramebufferStatusEXT; + PFNGLFRAMEBUFFERTEXTURE2DEXTPROC pGlFramebufferTexture2DEXT; + PFNGLBINDRENDERBUFFEREXTPROC pGlBindRenderbufferEXT; + PFNGLDELETERENDERBUFFERSEXTPROC pGlDeleteRenderbuffersEXT; + PFNGLGENRENDERBUFFERSEXTPROC pGlGenRenderbuffersEXT; + PFNGLRENDERBUFFERSTORAGEEXTPROC pGlRenderbufferStorageEXT; + PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC pGlFramebufferRenderbufferEXT; + PFNGLGENERATEMIPMAPEXTPROC pGlGenerateMipmapEXT; + PFNGLACTIVESTENCILFACEEXTPROC pGlActiveStencilFaceEXT; + PFNGLDRAWBUFFERSARBPROC pGlDrawBuffersARB; + PFNGLDRAWBUFFERSATIPROC pGlDrawBuffersATI; + PFNGLGENBUFFERSARBPROC pGlGenBuffersARB; + PFNGLBINDBUFFERARBPROC pGlBindBufferARB; + PFNGLBUFFERDATAARBPROC pGlBufferDataARB; + PFNGLDELETEBUFFERSARBPROC pGlDeleteBuffersARB; + PFNGLBUFFERSUBDATAARBPROC pGlBufferSubDataARB; + PFNGLGETBUFFERSUBDATAARBPROC pGlGetBufferSubDataARB; + PFNGLMAPBUFFERARBPROC pGlMapBufferARB; + PFNGLUNMAPBUFFERARBPROC pGlUnmapBufferARB; + PFNGLISBUFFERARBPROC pGlIsBufferARB; + PFNGLGETBUFFERPARAMETERIVARBPROC pGlGetBufferParameterivARB; + PFNGLGETBUFFERPOINTERVARBPROC pGlGetBufferPointervARB; + PFNGLPROVOKINGVERTEXPROC pGlProvokingVertexARB; + PFNGLPROVOKINGVERTEXEXTPROC pGlProvokingVertexEXT; + PFNGLPROGRAMPARAMETERIARBPROC pGlProgramParameteriARB; + PFNGLPROGRAMPARAMETERIEXTPROC pGlProgramParameteriEXT; + PFNGLGENQUERIESARBPROC pGlGenQueriesARB; + PFNGLDELETEQUERIESARBPROC pGlDeleteQueriesARB; + PFNGLISQUERYARBPROC pGlIsQueryARB; + PFNGLBEGINQUERYARBPROC pGlBeginQueryARB; + PFNGLENDQUERYARBPROC pGlEndQueryARB; + PFNGLGETQUERYIVARBPROC pGlGetQueryivARB; + PFNGLGETQUERYOBJECTIVARBPROC pGlGetQueryObjectivARB; + PFNGLGETQUERYOBJECTUIVARBPROC pGlGetQueryObjectuivARB; + PFNGLGENOCCLUSIONQUERIESNVPROC pGlGenOcclusionQueriesNV; + PFNGLDELETEOCCLUSIONQUERIESNVPROC pGlDeleteOcclusionQueriesNV; + PFNGLISOCCLUSIONQUERYNVPROC pGlIsOcclusionQueryNV; + PFNGLBEGINOCCLUSIONQUERYNVPROC pGlBeginOcclusionQueryNV; + PFNGLENDOCCLUSIONQUERYNVPROC pGlEndOcclusionQueryNV; + PFNGLGETOCCLUSIONQUERYIVNVPROC pGlGetOcclusionQueryivNV; + PFNGLGETOCCLUSIONQUERYUIVNVPROC pGlGetOcclusionQueryuivNV; + // Blend + PFNGLBLENDFUNCSEPARATEEXTPROC pGlBlendFuncSeparateEXT; + PFNGLBLENDFUNCSEPARATEPROC pGlBlendFuncSeparate; + PFNGLBLENDEQUATIONEXTPROC pGlBlendEquationEXT; + PFNGLBLENDEQUATIONPROC pGlBlendEquation; + PFNGLBLENDEQUATIONSEPARATEEXTPROC pGlBlendEquationSeparateEXT; + PFNGLBLENDEQUATIONSEPARATEPROC pGlBlendEquationSeparate; + // Indexed + PFNGLENABLEINDEXEDEXTPROC pGlEnableIndexedEXT; + PFNGLDISABLEINDEXEDEXTPROC pGlDisableIndexedEXT; + PFNGLCOLORMASKINDEXEDEXTPROC pGlColorMaskIndexedEXT; + PFNGLBLENDFUNCINDEXEDAMDPROC pGlBlendFuncIndexedAMD; + PFNGLBLENDFUNCIPROC pGlBlendFunciARB; + PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC pGlBlendFuncSeparateIndexedAMD; + PFNGLBLENDFUNCSEPARATEIPROC pGlBlendFuncSeparateiARB; + PFNGLBLENDEQUATIONINDEXEDAMDPROC pGlBlendEquationIndexedAMD; + PFNGLBLENDEQUATIONIPROC pGlBlendEquationiARB; + PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC pGlBlendEquationSeparateIndexedAMD; + PFNGLBLENDEQUATIONSEPARATEIPROC pGlBlendEquationSeparateiARB; - // DSA - PFNGLTEXTURESTORAGE2DPROC pGlTextureStorage2D; - PFNGLTEXTURESTORAGE3DPROC pGlTextureStorage3D; - PFNGLTEXTURESUBIMAGE2DPROC pGlTextureSubImage2D; - PFNGLGETTEXTUREIMAGEPROC pGlGetTextureImage; - PFNGLNAMEDFRAMEBUFFERTEXTUREPROC pGlNamedFramebufferTexture; - PFNGLTEXTUREPARAMETERIPROC pGlTextureParameteri; - PFNGLTEXTUREPARAMETERFPROC pGlTextureParameterf; - PFNGLTEXTUREPARAMETERIVPROC pGlTextureParameteriv; - PFNGLTEXTUREPARAMETERFVPROC pGlTextureParameterfv; + // DSA + PFNGLTEXTURESTORAGE2DPROC pGlTextureStorage2D; + PFNGLTEXTURESTORAGE3DPROC pGlTextureStorage3D; + PFNGLTEXTURESUBIMAGE2DPROC pGlTextureSubImage2D; + PFNGLGETTEXTUREIMAGEPROC pGlGetTextureImage; + PFNGLNAMEDFRAMEBUFFERTEXTUREPROC pGlNamedFramebufferTexture; + PFNGLTEXTUREPARAMETERIPROC pGlTextureParameteri; + PFNGLTEXTUREPARAMETERFPROC pGlTextureParameterf; + PFNGLTEXTUREPARAMETERIVPROC pGlTextureParameteriv; + PFNGLTEXTUREPARAMETERFVPROC pGlTextureParameterfv; - PFNGLCREATETEXTURESPROC pGlCreateTextures; - PFNGLCREATEFRAMEBUFFERSPROC pGlCreateFramebuffers; - PFNGLBINDTEXTURESPROC pGlBindTextures; - PFNGLGENERATETEXTUREMIPMAPPROC pGlGenerateTextureMipmap; - // DSA with EXT or functions to simulate it - PFNGLTEXTURESTORAGE2DEXTPROC pGlTextureStorage2DEXT; - PFNGLTEXSTORAGE2DPROC pGlTexStorage2D; - PFNGLTEXTURESTORAGE3DEXTPROC pGlTextureStorage3DEXT; - PFNGLTEXSTORAGE3DPROC pGlTexStorage3D; - PFNGLTEXTURESUBIMAGE2DEXTPROC pGlTextureSubImage2DEXT; - PFNGLGETTEXTUREIMAGEEXTPROC pGlGetTextureImageEXT; - PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC pGlNamedFramebufferTextureEXT; - PFNGLFRAMEBUFFERTEXTUREPROC pGlFramebufferTexture; - PFNGLGENERATETEXTUREMIPMAPEXTPROC pGlGenerateTextureMipmapEXT; + PFNGLCREATETEXTURESPROC pGlCreateTextures; + PFNGLCREATEFRAMEBUFFERSPROC pGlCreateFramebuffers; + PFNGLBINDTEXTURESPROC pGlBindTextures; + PFNGLGENERATETEXTUREMIPMAPPROC pGlGenerateTextureMipmap; + // DSA with EXT or functions to simulate it + PFNGLTEXTURESTORAGE2DEXTPROC pGlTextureStorage2DEXT; + PFNGLTEXSTORAGE2DPROC pGlTexStorage2D; + PFNGLTEXTURESTORAGE3DEXTPROC pGlTextureStorage3DEXT; + PFNGLTEXSTORAGE3DPROC pGlTexStorage3D; + PFNGLTEXTURESUBIMAGE2DEXTPROC pGlTextureSubImage2DEXT; + PFNGLGETTEXTUREIMAGEEXTPROC pGlGetTextureImageEXT; + PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC pGlNamedFramebufferTextureEXT; + PFNGLFRAMEBUFFERTEXTUREPROC pGlFramebufferTexture; + PFNGLGENERATETEXTUREMIPMAPEXTPROC pGlGenerateTextureMipmapEXT; - #if defined(WGL_EXT_swap_control) - PFNWGLSWAPINTERVALEXTPROC pWglSwapIntervalEXT; - #endif - #if defined(GLX_SGI_swap_control) - PFNGLXSWAPINTERVALSGIPROC pGlxSwapIntervalSGI; - #endif - #if defined(GLX_EXT_swap_control) - PFNGLXSWAPINTERVALEXTPROC pGlxSwapIntervalEXT; - #endif - #if defined(GLX_MESA_swap_control) - PFNGLXSWAPINTERVALMESAPROC pGlxSwapIntervalMESA; - #endif +#if defined(WGL_EXT_swap_control) + PFNWGLSWAPINTERVALEXTPROC pWglSwapIntervalEXT; +#endif +#if defined(GLX_SGI_swap_control) + PFNGLXSWAPINTERVALSGIPROC pGlxSwapIntervalSGI; +#endif +#if defined(GLX_EXT_swap_control) + PFNGLXSWAPINTERVALEXTPROC pGlxSwapIntervalEXT; +#endif +#if defined(GLX_MESA_swap_control) + PFNGLXSWAPINTERVALMESAPROC pGlxSwapIntervalMESA; +#endif }; inline void COpenGLExtensionHandler::irrGlActiveTexture(GLenum texture) @@ -1425,7 +1422,7 @@ inline void COpenGLExtensionHandler::irrGlClientActiveTexture(GLenum texture) inline void COpenGLExtensionHandler::extGlGenPrograms(GLsizei n, GLuint *programs) { if (programs) - memset(programs,0,n*sizeof(GLuint)); + memset(programs, 0, n * sizeof(GLuint)); if (pGlGenProgramsARB) pGlGenProgramsARB(n, programs); else if (pGlGenProgramsNV) @@ -1463,7 +1460,7 @@ inline void COpenGLExtensionHandler::extGlDeletePrograms(GLsizei n, const GLuint inline void COpenGLExtensionHandler::extGlProgramLocalParameter4fv(GLenum n, GLuint i, const GLfloat *f) { if (pGlProgramLocalParameter4fvARB) - pGlProgramLocalParameter4fvARB(n,i,f); + pGlProgramLocalParameter4fvARB(n, i, f); } inline GLhandleARB COpenGLExtensionHandler::extGlCreateShaderObject(GLenum shaderType) @@ -1572,18 +1569,18 @@ inline void COpenGLExtensionHandler::extGlDeleteShader(GLuint shader) pGlDeleteShader(shader); } -inline void COpenGLExtensionHandler::extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei* count, GLhandleARB* shaders) +inline void COpenGLExtensionHandler::extGlGetAttachedObjects(GLhandleARB program, GLsizei maxcount, GLsizei *count, GLhandleARB *shaders) { if (count) - *count=0; + *count = 0; if (pGlGetAttachedObjectsARB) pGlGetAttachedObjectsARB(program, maxcount, count, shaders); } -inline void COpenGLExtensionHandler::extGlGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) +inline void COpenGLExtensionHandler::extGlGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei *count, GLuint *shaders) { if (count) - *count=0; + *count = 0; if (pGlGetAttachedShaders) pGlGetAttachedShaders(program, maxcount, count, shaders); } @@ -1591,7 +1588,7 @@ inline void COpenGLExtensionHandler::extGlGetAttachedShaders(GLuint program, GLs inline void COpenGLExtensionHandler::extGlGetInfoLog(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog) { if (length) - *length=0; + *length = 0; if (pGlGetInfoLogARB) pGlGetInfoLogARB(object, maxLength, length, infoLog); } @@ -1599,7 +1596,7 @@ inline void COpenGLExtensionHandler::extGlGetInfoLog(GLhandleARB object, GLsizei inline void COpenGLExtensionHandler::extGlGetShaderInfoLog(GLuint shader, GLsizei maxLength, GLsizei *length, GLchar *infoLog) { if (length) - *length=0; + *length = 0; if (pGlGetShaderInfoLog) pGlGetShaderInfoLog(shader, maxLength, length, infoLog); } @@ -1607,7 +1604,7 @@ inline void COpenGLExtensionHandler::extGlGetShaderInfoLog(GLuint shader, GLsize inline void COpenGLExtensionHandler::extGlGetProgramInfoLog(GLuint program, GLsizei maxLength, GLsizei *length, GLchar *infoLog) { if (length) - *length=0; + *length = 0; if (pGlGetProgramInfoLog) pGlGetProgramInfoLog(program, maxLength, length, infoLog); } @@ -1722,7 +1719,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix2fv(GLint loc, GLsizei co pGlUniformMatrix2fvARB(loc, count, transpose, v); } -inline void COpenGLExtensionHandler::extGlUniformMatrix2x3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix2x3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix2x3fv) pGlUniformMatrix2x3fv(loc, count, transpose, v); @@ -1730,7 +1727,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix2x3fv(GLint loc, GLsizei os::Printer::log("glUniformMatrix2x3fv not supported", ELL_ERROR); } -inline void COpenGLExtensionHandler::extGlUniformMatrix2x4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix2x4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix2x4fv) pGlUniformMatrix2x4fv(loc, count, transpose, v); @@ -1738,7 +1735,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix2x4fv(GLint loc, GLsizei os::Printer::log("glUniformMatrix2x4fv not supported", ELL_ERROR); } -inline void COpenGLExtensionHandler::extGlUniformMatrix3x2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix3x2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix3x2fv) pGlUniformMatrix3x2fv(loc, count, transpose, v); @@ -1752,7 +1749,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix3fv(GLint loc, GLsizei co pGlUniformMatrix3fvARB(loc, count, transpose, v); } -inline void COpenGLExtensionHandler::extGlUniformMatrix3x4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix3x4fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix3x4fv) pGlUniformMatrix3x4fv(loc, count, transpose, v); @@ -1760,7 +1757,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix3x4fv(GLint loc, GLsizei os::Printer::log("glUniformMatrix3x4fv not supported", ELL_ERROR); } -inline void COpenGLExtensionHandler::extGlUniformMatrix4x2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix4x2fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix4x2fv) pGlUniformMatrix4x2fv(loc, count, transpose, v); @@ -1768,7 +1765,7 @@ inline void COpenGLExtensionHandler::extGlUniformMatrix4x2fv(GLint loc, GLsizei os::Printer::log("glUniformMatrix4x2fv not supported", ELL_ERROR); } -inline void COpenGLExtensionHandler::extGlUniformMatrix4x3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat* v) +inline void COpenGLExtensionHandler::extGlUniformMatrix4x3fv(GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v) { if (pGlUniformMatrix4x3fv) pGlUniformMatrix4x3fv(loc, count, transpose, v); @@ -1787,7 +1784,7 @@ inline void COpenGLExtensionHandler::extGlGetActiveUniformARB(GLhandleARB progra GLint *size, GLenum *type, GLcharARB *name) { if (length) - *length=0; + *length = 0; if (pGlGetActiveUniformARB) pGlGetActiveUniformARB(program, index, maxlength, length, size, type, name); } @@ -1797,7 +1794,7 @@ inline void COpenGLExtensionHandler::extGlGetActiveUniform(GLuint program, GLint *size, GLenum *type, GLchar *name) { if (length) - *length=0; + *length = 0; if (pGlGetActiveUniform) pGlGetActiveUniform(program, index, maxlength, length, size, type, name); } @@ -1814,7 +1811,7 @@ inline void COpenGLExtensionHandler::extGlPointParameterfv(GLint loc, const GLfl pGlPointParameterfvARB(loc, v); } -inline void COpenGLExtensionHandler::extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask) +inline void COpenGLExtensionHandler::extGlStencilFuncSeparate(GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask) { if (pGlStencilFuncSeparate) pGlStencilFuncSeparate(frontfunc, backfunc, ref, mask); @@ -1822,7 +1819,7 @@ inline void COpenGLExtensionHandler::extGlStencilFuncSeparate (GLenum frontfunc, pGlStencilFuncSeparateATI(frontfunc, backfunc, ref, mask); } -inline void COpenGLExtensionHandler::extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass) +inline void COpenGLExtensionHandler::extGlStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) { if (pGlStencilOpSeparate) pGlStencilOpSeparate(face, fail, zfail, zpass); @@ -1830,15 +1827,15 @@ inline void COpenGLExtensionHandler::extGlStencilOpSeparate (GLenum face, GLenum pGlStencilOpSeparateATI(face, fail, zfail, zpass); } -inline void COpenGLExtensionHandler::irrGlCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, - GLsizei height, GLint border, GLsizei imageSize, const void* data) +inline void COpenGLExtensionHandler::irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, + GLsizei height, GLint border, GLsizei imageSize, const void *data) { if (pGlCompressedTexImage2D) pGlCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } inline void COpenGLExtensionHandler::irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, - GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data) + GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data) { if (pGlCompressedTexSubImage2D) pGlCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); @@ -1863,7 +1860,7 @@ inline void COpenGLExtensionHandler::irrGlDeleteFramebuffers(GLsizei n, const GL inline void COpenGLExtensionHandler::irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) { if (framebuffers) - memset(framebuffers,0,n*sizeof(GLuint)); + memset(framebuffers, 0, n * sizeof(GLuint)); if (pGlGenFramebuffers) pGlGenFramebuffers(n, framebuffers); else if (pGlGenFramebuffersEXT) @@ -1907,7 +1904,7 @@ inline void COpenGLExtensionHandler::irrGlDeleteRenderbuffers(GLsizei n, const G inline void COpenGLExtensionHandler::irrGlGenRenderbuffers(GLsizei n, GLuint *renderbuffers) { if (renderbuffers) - memset(renderbuffers,0,n*sizeof(GLuint)); + memset(renderbuffers, 0, n * sizeof(GLuint)); if (pGlGenRenderbuffers) pGlGenRenderbuffers(n, renderbuffers); else if (pGlGenRenderbuffersEXT) @@ -1957,11 +1954,10 @@ inline void COpenGLExtensionHandler::irrGlDrawBuffers(GLsizei n, const GLenum *b pGlDrawBuffersATI(n, bufs); } - inline void COpenGLExtensionHandler::extGlGenBuffers(GLsizei n, GLuint *buffers) { if (buffers) - memset(buffers,0,n*sizeof(GLuint)); + memset(buffers, 0, n * sizeof(GLuint)); if (pGlGenBuffersARB) pGlGenBuffersARB(n, buffers); } @@ -2029,7 +2025,6 @@ inline void COpenGLExtensionHandler::extGlGetBufferPointerv(GLenum target, GLenu pGlGetBufferPointervARB(target, pname, params); } - inline void COpenGLExtensionHandler::extGlProvokingVertex(GLenum mode) { if (FeatureAvailable[IRR_ARB_provoking_vertex] && pGlProvokingVertexARB) @@ -2040,8 +2035,7 @@ inline void COpenGLExtensionHandler::extGlProvokingVertex(GLenum mode) inline void COpenGLExtensionHandler::extGlProgramParameteri(GLuint program, GLenum pname, GLint value) { - if (queryFeature(EVDF_GEOMETRY_SHADER)) - { + if (queryFeature(EVDF_GEOMETRY_SHADER)) { if (pGlProgramParameteriARB) pGlProgramParameteriARB(program, pname, value); else if (pGlProgramParameteriEXT) @@ -2178,243 +2172,214 @@ inline void COpenGLExtensionHandler::irrGlBlendEquationSeparateIndexed(GLuint bu pGlBlendEquationSeparateIndexedAMD(buf, modeRGB, modeAlpha); } -inline void COpenGLExtensionHandler::extGlTextureSubImage2D(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) +inline void COpenGLExtensionHandler::extGlTextureSubImage2D(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels) { - if (Version>=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - if (pGlTextureSubImage2D) - pGlTextureSubImage2D(texture, level, xoffset, yoffset,width, height,format, type, pixels); - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - if (pGlTextureSubImage2DEXT) - pGlTextureSubImage2DEXT(texture, target, level, xoffset, yoffset,width, height,format, type, pixels); - } - else - { - GLint bound; - switch (target) - { + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + if (pGlTextureSubImage2D) + pGlTextureSubImage2D(texture, level, xoffset, yoffset, width, height, format, type, pixels); + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + if (pGlTextureSubImage2DEXT) + pGlTextureSubImage2DEXT(texture, target, level, xoffset, yoffset, width, height, format, type, pixels); + } else { + GLint bound; + switch (target) { #ifdef GL_VERSION_3_0 - case GL_TEXTURE_1D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); - break; + case GL_TEXTURE_1D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); + break; #elif GL_EXT_texture_array - case GL_TEXTURE_1D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); - break; + case GL_TEXTURE_1D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); + break; #endif - case GL_TEXTURE_2D: - glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); - break; + case GL_TEXTURE_2D: + glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); + break; #ifdef GL_VERSION_3_2 - case GL_TEXTURE_2D_MULTISAMPLE: - glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE, &bound); - break; + case GL_TEXTURE_2D_MULTISAMPLE: + glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE, &bound); + break; #endif - case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: - case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: - case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: - case GL_TEXTURE_CUBE_MAP_POSITIVE_X: - case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: - case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); - break; + case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: + case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: + case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: + case GL_TEXTURE_CUBE_MAP_POSITIVE_X: + case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: + case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); + break; #ifdef GL_VERSION_3_1 - case GL_TEXTURE_RECTANGLE: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); - break; + case GL_TEXTURE_RECTANGLE: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); + break; #elif defined(GL_ARB_texture_rectangle) - case GL_TEXTURE_RECTANGLE_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); - break; + case GL_TEXTURE_RECTANGLE_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); + break; #endif - default: - return; - } - glBindTexture(target, texture); - glTexSubImage2D(target, level, xoffset, yoffset,width, height,format, type, pixels); - glBindTexture(target, bound); - } + default: + return; + } + glBindTexture(target, texture); + glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + glBindTexture(target, bound); + } } inline void COpenGLExtensionHandler::extGlTextureStorage2D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) { - if (Version>=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - if (pGlTextureStorage2D) - pGlTextureStorage2D(texture,levels,internalformat,width,height); - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - if (pGlTextureStorage2DEXT) - pGlTextureStorage2DEXT(texture,target,levels,internalformat,width,height); - } + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + if (pGlTextureStorage2D) + pGlTextureStorage2D(texture, levels, internalformat, width, height); + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + if (pGlTextureStorage2DEXT) + pGlTextureStorage2DEXT(texture, target, levels, internalformat, width, height); + } - else - if (pGlTexStorage2D) - { - GLint bound; - switch (target) - { + else if (pGlTexStorage2D) { + GLint bound; + switch (target) { #ifdef GL_VERSION_3_0 - case GL_TEXTURE_1D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); - break; + case GL_TEXTURE_1D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); + break; #elif GL_EXT_texture_array - case GL_TEXTURE_1D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); - break; + case GL_TEXTURE_1D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); + break; #endif - case GL_TEXTURE_2D: - glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); - break; - case GL_TEXTURE_CUBE_MAP: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); - break; + case GL_TEXTURE_2D: + glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); + break; + case GL_TEXTURE_CUBE_MAP: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); + break; #ifdef GL_VERSION_3_1 - case GL_TEXTURE_RECTANGLE: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); - break; + case GL_TEXTURE_RECTANGLE: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); + break; #elif defined(GL_ARB_texture_rectangle) - case GL_TEXTURE_RECTANGLE_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); - break; + case GL_TEXTURE_RECTANGLE_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); + break; #endif - default: - return; - } - glBindTexture(target, texture); - pGlTexStorage2D(target,levels,internalformat,width,height); - glBindTexture(target, bound); - } + default: + return; + } + glBindTexture(target, texture); + pGlTexStorage2D(target, levels, internalformat, width, height); + glBindTexture(target, bound); + } } inline void COpenGLExtensionHandler::extGlTextureStorage3D(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) { - if (Version>=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - if (pGlTextureStorage3D) - pGlTextureStorage3D(texture,levels,internalformat,width,height,depth); - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - if (pGlTextureStorage3DEXT) - pGlTextureStorage3DEXT(texture,target,levels,internalformat,width,height,depth); - } - else - if (pGlTexStorage3D) - { - GLint bound; - switch (target) - { -#ifdef GL_VERSION_3_0 - case GL_TEXTURE_2D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); - break; -#elif GL_EXT_texture_array - case GL_TEXTURE_2D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); - break; -#endif - case GL_TEXTURE_3D: - glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); - break; -#ifdef GL_VERSION_4_0 - case GL_TEXTURE_CUBE_MAP_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); - break; -#elif defined(GL_ARB_texture_cube_map_array) - case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); - break; -#endif - default: - return; - } - glBindTexture(target, texture); - pGlTexStorage3D(target,levels,internalformat,width,height,depth); - glBindTexture(target, bound); - } -} - -inline void COpenGLExtensionHandler::extGlGetTextureImage(GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void* pixels) -{ - if (Version>=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - if (pGlGetTextureImage) - pGlGetTextureImage(texture,level,format,type,bufSize,pixels); - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - if (pGlGetTextureImageEXT) - pGlGetTextureImageEXT(texture,target,level,format,type,pixels); - } - else - { + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + if (pGlTextureStorage3D) + pGlTextureStorage3D(texture, levels, internalformat, width, height, depth); + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + if (pGlTextureStorage3DEXT) + pGlTextureStorage3DEXT(texture, target, levels, internalformat, width, height, depth); + } else if (pGlTexStorage3D) { GLint bound; - switch (target) - { + switch (target) { #ifdef GL_VERSION_3_0 - case GL_TEXTURE_2D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); - break; + case GL_TEXTURE_2D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); + break; #elif GL_EXT_texture_array - case GL_TEXTURE_2D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); - break; + case GL_TEXTURE_2D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); + break; #endif - case GL_TEXTURE_3D: - glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); - break; + case GL_TEXTURE_3D: + glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); + break; #ifdef GL_VERSION_4_0 - case GL_TEXTURE_CUBE_MAP_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); - break; + case GL_TEXTURE_CUBE_MAP_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); + break; #elif defined(GL_ARB_texture_cube_map_array) - case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); - break; + case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); + break; #endif - default: - return; + default: + return; } glBindTexture(target, texture); - glGetTexImage(target,level,format,type,pixels); + pGlTexStorage3D(target, levels, internalformat, width, height, depth); + glBindTexture(target, bound); + } +} + +inline void COpenGLExtensionHandler::extGlGetTextureImage(GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels) +{ + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + if (pGlGetTextureImage) + pGlGetTextureImage(texture, level, format, type, bufSize, pixels); + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + if (pGlGetTextureImageEXT) + pGlGetTextureImageEXT(texture, target, level, format, type, pixels); + } else { + GLint bound; + switch (target) { +#ifdef GL_VERSION_3_0 + case GL_TEXTURE_2D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); + break; +#elif GL_EXT_texture_array + case GL_TEXTURE_2D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); + break; +#endif + case GL_TEXTURE_3D: + glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); + break; +#ifdef GL_VERSION_4_0 + case GL_TEXTURE_CUBE_MAP_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); + break; +#elif defined(GL_ARB_texture_cube_map_array) + case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); + break; +#endif + default: + return; + } + glBindTexture(target, texture); + glGetTexImage(target, level, format, type, pixels); glBindTexture(target, bound); } } inline void COpenGLExtensionHandler::extGlNamedFramebufferTexture(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level) { - if (!needsDSAFramebufferHack) - { - if (Version>=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - pGlNamedFramebufferTexture(framebuffer, attachment, texture, level); - return; - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - pGlNamedFramebufferTextureEXT(framebuffer, attachment, texture, level); - return; - } - } + if (!needsDSAFramebufferHack) { + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + pGlNamedFramebufferTexture(framebuffer, attachment, texture, level); + return; + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + pGlNamedFramebufferTextureEXT(framebuffer, attachment, texture, level); + return; + } + } - GLuint bound; - glGetIntegerv(GL_FRAMEBUFFER_BINDING,reinterpret_cast(&bound)); + GLuint bound; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast(&bound)); - if (bound!=framebuffer) - pGlBindFramebuffer(GL_FRAMEBUFFER,framebuffer); - pGlFramebufferTexture(GL_FRAMEBUFFER,attachment,texture,level); - if (bound!=framebuffer) - pGlBindFramebuffer(GL_FRAMEBUFFER,bound); + if (bound != framebuffer) + pGlBindFramebuffer(GL_FRAMEBUFFER, framebuffer); + pGlFramebufferTexture(GL_FRAMEBUFFER, attachment, texture, level); + if (bound != framebuffer) + pGlBindFramebuffer(GL_FRAMEBUFFER, bound); } inline void COpenGLExtensionHandler::extGlTextureParameteri(GLuint texture, GLenum pname, GLint param) { - if (pGlTextureParameteri) - pGlTextureParameteri(texture, pname, param); + if (pGlTextureParameteri) + pGlTextureParameteri(texture, pname, param); } inline void COpenGLExtensionHandler::extGlTextureParameterf(GLuint texture, GLenum pname, GLfloat param) @@ -2423,203 +2388,199 @@ inline void COpenGLExtensionHandler::extGlTextureParameterf(GLuint texture, GLen pGlTextureParameterf(texture, pname, param); } -inline void COpenGLExtensionHandler::extGlTextureParameteriv(GLuint texture, GLenum pname, const GLint* params) +inline void COpenGLExtensionHandler::extGlTextureParameteriv(GLuint texture, GLenum pname, const GLint *params) { if (pGlTextureParameteriv) pGlTextureParameteriv(texture, pname, params); } -inline void COpenGLExtensionHandler::extGlTextureParameterfv(GLuint texture, GLenum pname, const GLfloat* params) +inline void COpenGLExtensionHandler::extGlTextureParameterfv(GLuint texture, GLenum pname, const GLfloat *params) { if (pGlTextureParameterfv) pGlTextureParameterfv(texture, pname, params); } -inline void COpenGLExtensionHandler::extGlCreateTextures(GLenum target, GLsizei n, GLuint* textures) +inline void COpenGLExtensionHandler::extGlCreateTextures(GLenum target, GLsizei n, GLuint *textures) { - if (Version>=405) - { - if (pGlCreateTextures) - pGlCreateTextures(target,n,textures); - else if (textures) - memset(textures,0,n*sizeof(GLuint)); - } - else - { - glGenTextures(n,textures); - } + if (Version >= 405) { + if (pGlCreateTextures) + pGlCreateTextures(target, n, textures); + else if (textures) + memset(textures, 0, n * sizeof(GLuint)); + } else { + glGenTextures(n, textures); + } } -inline void COpenGLExtensionHandler::extGlCreateFramebuffers(GLsizei n, GLuint* framebuffers) +inline void COpenGLExtensionHandler::extGlCreateFramebuffers(GLsizei n, GLuint *framebuffers) { - if (!needsDSAFramebufferHack) - { - if (Version>=405) - { - pGlCreateFramebuffers(n, framebuffers); - return; - } - } + if (!needsDSAFramebufferHack) { + if (Version >= 405) { + pGlCreateFramebuffers(n, framebuffers); + return; + } + } - pGlGenFramebuffers(n, framebuffers); + pGlGenFramebuffers(n, framebuffers); } -inline void COpenGLExtensionHandler::extGlBindTextures(GLuint first, GLsizei count, const GLuint *textures, const GLenum* targets) +inline void COpenGLExtensionHandler::extGlBindTextures(GLuint first, GLsizei count, const GLuint *textures, const GLenum *targets) { - const GLenum supportedTargets[] = { GL_TEXTURE_1D, GL_TEXTURE_2D // GL 1.x - ,GL_TEXTURE_3D // GL 2.x + const GLenum supportedTargets[] = {GL_TEXTURE_1D, GL_TEXTURE_2D // GL 1.x + , + GL_TEXTURE_3D // GL 2.x #ifdef GL_VERSION_3_1 - ,GL_TEXTURE_RECTANGLE + , + GL_TEXTURE_RECTANGLE #elif defined(GL_ARB_texture_rectangle) - ,GL_TEXTURE_RECTANGLE_ARB + , + GL_TEXTURE_RECTANGLE_ARB #endif - ,GL_TEXTURE_CUBE_MAP + , + GL_TEXTURE_CUBE_MAP #ifdef GL_VERSION_3_0 - ,GL_TEXTURE_1D_ARRAY,GL_TEXTURE_2D_ARRAY // GL 3.x + , + GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D_ARRAY // GL 3.x #elif GL_EXT_texture_array - ,GL_TEXTURE_1D_ARRAY_EXT,GL_TEXTURE_2D_ARRAY_EXT + , + GL_TEXTURE_1D_ARRAY_EXT, GL_TEXTURE_2D_ARRAY_EXT #endif #ifdef GL_VERSION_3_1 - ,GL_TEXTURE_BUFFER + , + GL_TEXTURE_BUFFER #elif defined(GL_ARB_texture_buffer_object) - ,GL_TEXTURE_BUFFER_ARB + , + GL_TEXTURE_BUFFER_ARB #elif defined(GL_EXT_texture_buffer_object) - ,GL_TEXTURE_BUFFER_EXT + , + GL_TEXTURE_BUFFER_EXT #endif #ifdef GL_VERSION_4_0 - ,GL_TEXTURE_CUBE_MAP_ARRAY // GL 4.x + , + GL_TEXTURE_CUBE_MAP_ARRAY // GL 4.x #elif defined(GL_ARB_texture_cube_map_array) - ,GL_TEXTURE_CUBE_MAP_ARRAY_ARB + , + GL_TEXTURE_CUBE_MAP_ARRAY_ARB #endif #ifdef GL_VERSION_3_2 - ,GL_TEXTURE_2D_MULTISAMPLE,GL_TEXTURE_2D_MULTISAMPLE_ARRAY + , + GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY #endif }; - if (Version>=404||FeatureAvailable[IRR_ARB_multi_bind]) - { - if (pGlBindTextures) - pGlBindTextures(first,count,textures); - } - else - { - GLint activeTex = 0; - glGetIntegerv(GL_ACTIVE_TEXTURE,&activeTex); + if (Version >= 404 || FeatureAvailable[IRR_ARB_multi_bind]) { + if (pGlBindTextures) + pGlBindTextures(first, count, textures); + } else { + GLint activeTex = 0; + glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); - for (GLsizei i=0; i=405 || FeatureAvailable[IRR_ARB_direct_state_access]) - { - if (pGlGenerateTextureMipmap) - pGlGenerateTextureMipmap(texture); - } - else if (FeatureAvailable[IRR_EXT_direct_state_access]) - { - if (pGlGenerateTextureMipmapEXT) - pGlGenerateTextureMipmapEXT(texture,target); - } - else if (pGlGenerateMipmap) - { - GLint bound; - switch (target) - { - case GL_TEXTURE_1D: - glGetIntegerv(GL_TEXTURE_BINDING_1D, &bound); - break; + if (Version >= 405 || FeatureAvailable[IRR_ARB_direct_state_access]) { + if (pGlGenerateTextureMipmap) + pGlGenerateTextureMipmap(texture); + } else if (FeatureAvailable[IRR_EXT_direct_state_access]) { + if (pGlGenerateTextureMipmapEXT) + pGlGenerateTextureMipmapEXT(texture, target); + } else if (pGlGenerateMipmap) { + GLint bound; + switch (target) { + case GL_TEXTURE_1D: + glGetIntegerv(GL_TEXTURE_BINDING_1D, &bound); + break; #ifdef GL_VERSION_3_0 - case GL_TEXTURE_1D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); - break; + case GL_TEXTURE_1D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY, &bound); + break; #elif GL_EXT_texture_array - case GL_TEXTURE_1D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); - break; + case GL_TEXTURE_1D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_1D_ARRAY_EXT, &bound); + break; #endif - case GL_TEXTURE_2D: - glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); - break; + case GL_TEXTURE_2D: + glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); + break; #ifdef GL_VERSION_3_0 - case GL_TEXTURE_2D_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); - break; + case GL_TEXTURE_2D_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY, &bound); + break; #elif GL_EXT_texture_array - case GL_TEXTURE_2D_ARRAY_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); - break; + case GL_TEXTURE_2D_ARRAY_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_2D_ARRAY_EXT, &bound); + break; #endif #ifdef GL_VERSION_3_2 - case GL_TEXTURE_2D_MULTISAMPLE: - glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE, &bound); - break; - case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, &bound); - break; + case GL_TEXTURE_2D_MULTISAMPLE: + glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE, &bound); + break; + case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, &bound); + break; #endif - case GL_TEXTURE_3D: - glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); - break; + case GL_TEXTURE_3D: + glGetIntegerv(GL_TEXTURE_BINDING_3D, &bound); + break; #ifdef GL_VERSION_3_1 - case GL_TEXTURE_BUFFER: - glGetIntegerv(GL_TEXTURE_BINDING_BUFFER, &bound); - break; + case GL_TEXTURE_BUFFER: + glGetIntegerv(GL_TEXTURE_BINDING_BUFFER, &bound); + break; #elif defined(GL_ARB_texture_buffer_object) - case GL_TEXTURE_BUFFER_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_BUFFER_ARB, &bound); - break; + case GL_TEXTURE_BUFFER_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_BUFFER_ARB, &bound); + break; #elif defined(GL_EXT_texture_buffer_object) - case GL_TEXTURE_BUFFER_EXT: - glGetIntegerv(GL_TEXTURE_BINDING_BUFFER_EXT, &bound); - break; + case GL_TEXTURE_BUFFER_EXT: + glGetIntegerv(GL_TEXTURE_BINDING_BUFFER_EXT, &bound); + break; #endif - case GL_TEXTURE_CUBE_MAP: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); - break; + case GL_TEXTURE_CUBE_MAP: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound); + break; #ifdef GL_VERSION_4_0 - case GL_TEXTURE_CUBE_MAP_ARRAY: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); - break; + case GL_TEXTURE_CUBE_MAP_ARRAY: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, &bound); + break; #elif defined(GL_ARB_texture_cube_map_array) - case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); - break; + case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, &bound); + break; #endif #ifdef GL_VERSION_3_1 - case GL_TEXTURE_RECTANGLE: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); - break; + case GL_TEXTURE_RECTANGLE: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, &bound); + break; #elif defined(GL_ARB_texture_rectangle) - case GL_TEXTURE_RECTANGLE_ARB: - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); - break; + case GL_TEXTURE_RECTANGLE_ARB: + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &bound); + break; #endif - default: - os::Printer::log("DevSH would like to ask you what are you doing!!??\n",ELL_ERROR); - return; - } - glBindTexture(target, texture); - pGlGenerateMipmap(target); - glBindTexture(target, bound); - } + default: + os::Printer::log("DevSH would like to ask you what are you doing!!??\n", ELL_ERROR); + return; + } + glBindTexture(target, texture); + pGlGenerateMipmap(target); + glBindTexture(target, bound); + } } inline void COpenGLExtensionHandler::extGlSwapInterval(int interval) @@ -2644,12 +2605,11 @@ inline void COpenGLExtensionHandler::extGlSwapInterval(int interval) // does not work with interval==0 if (interval && pGlxSwapIntervalSGI) pGlxSwapIntervalSGI(interval); - } +} #endif #endif } - } } diff --git a/source/Irrlicht/COpenGLMaterialRenderer.h b/source/Irrlicht/COpenGLMaterialRenderer.h index 25c85d0d..b4706f53 100644 --- a/source/Irrlicht/COpenGLMaterialRenderer.h +++ b/source/Irrlicht/COpenGLMaterialRenderer.h @@ -20,11 +20,11 @@ namespace video class COpenGLMaterialRenderer_SOLID : public IMaterialRenderer { public: + COpenGLMaterialRenderer_SOLID(video::COpenGLDriver *d) : + Driver(d) {} - COpenGLMaterialRenderer_SOLID(video::COpenGLDriver* d) : Driver(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_DISABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE_TO_ENABLE); @@ -36,20 +36,18 @@ public: } protected: - - video::COpenGLDriver* Driver; + video::COpenGLDriver *Driver; }; - //! Generic Texture Blend class COpenGLMaterialRenderer_ONETEXTURE_BLEND : public IMaterialRenderer { public: + COpenGLMaterialRenderer_ONETEXTURE_BLEND(video::COpenGLDriver *d) : + Driver(d) {} - COpenGLMaterialRenderer_ONETEXTURE_BLEND(video::COpenGLDriver* d) : Driver(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_DISABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE_TO_ENABLE); @@ -59,26 +57,23 @@ public: Driver->disableTextures(1); Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); -// if (material.MaterialType != lastMaterial.MaterialType || -// material.MaterialTypeParam != lastMaterial.MaterialTypeParam || -// resetAllRenderstates) + // if (material.MaterialType != lastMaterial.MaterialType || + // material.MaterialTypeParam != lastMaterial.MaterialTypeParam || + // resetAllRenderstates) { - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + E_BLEND_FACTOR srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact; E_MODULATE_FUNC modulate; u32 alphaSource; unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - Driver->getCacheHandler()->setBlend(true); + Driver->getCacheHandler()->setBlend(true); - if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) - { - Driver->getCacheHandler()->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), - Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); - } - else - { - Driver->getCacheHandler()->setBlendFunc(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact)); - } + if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) { + Driver->getCacheHandler()->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), + Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); + } else { + Driver->getCacheHandler()->setBlendFunc(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact)); + } Driver->getCacheHandler()->setActiveTexture(GL_TEXTURE0_ARB); @@ -87,20 +82,18 @@ public: glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (f32) modulate ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (f32)modulate); #else glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PREVIOUS_EXT); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, (f32) modulate ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, (f32)modulate); #endif if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || - textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) - { - if (alphaSource==EAS_VERTEX_COLOR) - { + textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) { + if (alphaSource == EAS_VERTEX_COLOR) { #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PRIMARY_COLOR_ARB); @@ -108,9 +101,7 @@ public: glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_PRIMARY_COLOR_EXT); #endif - } - else if (alphaSource==EAS_TEXTURE) - { + } else if (alphaSource == EAS_TEXTURE) { #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE); @@ -118,9 +109,7 @@ public: glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_TEXTURE); #endif - } - else - { + } else { #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PRIMARY_COLOR_ARB); @@ -143,11 +132,11 @@ public: #ifdef GL_ARB_texture_env_combine glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.f ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.f); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB); #else glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_MODULATE); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 1.f ); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 1.f); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PREVIOUS_EXT); #endif @@ -162,20 +151,18 @@ public: } protected: - - video::COpenGLDriver* Driver; + video::COpenGLDriver *Driver; }; - //! Transparent vertex alpha material renderer class COpenGLMaterialRenderer_TRANSPARENT_VERTEX_ALPHA : public IMaterialRenderer { public: + COpenGLMaterialRenderer_TRANSPARENT_VERTEX_ALPHA(video::COpenGLDriver *d) : + Driver(d) {} - COpenGLMaterialRenderer_TRANSPARENT_VERTEX_ALPHA(video::COpenGLDriver* d) : Driver(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_DISABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE_TO_ENABLE); @@ -186,10 +173,9 @@ public: Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); Driver->getCacheHandler()->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Driver->getCacheHandler()->setBlend(true); + Driver->getCacheHandler()->setBlend(true); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) { Driver->getCacheHandler()->setActiveTexture(GL_TEXTURE0_ARB); #ifdef GL_ARB_texture_env_combine @@ -202,7 +188,7 @@ public: #else glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_PRIMARY_COLOR_EXT ); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_PRIMARY_COLOR_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PREVIOUS_EXT); @@ -216,11 +202,11 @@ public: glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #ifdef GL_ARB_texture_env_combine - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE ); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE ); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE); #else - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_MODULATE ); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_TEXTURE ); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_EXT, GL_TEXTURE); #endif Driver->getCacheHandler()->setBlend(false); @@ -233,20 +219,18 @@ public: } protected: - - video::COpenGLDriver* Driver; + video::COpenGLDriver *Driver; }; - //! Transparent alpha channel material renderer class COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL : public IMaterialRenderer { public: + COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(video::COpenGLDriver *d) : + Driver(d) {} - COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL(video::COpenGLDriver* d) : Driver(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_DISABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE_TO_ENABLE); @@ -256,13 +240,12 @@ public: Driver->disableTextures(1); Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - Driver->getCacheHandler()->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Driver->getCacheHandler()->setBlend(true); - Driver->getCacheHandler()->setAlphaTest(true); - Driver->getCacheHandler()->setAlphaFunc(GL_GREATER, material.MaterialTypeParam); + Driver->getCacheHandler()->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Driver->getCacheHandler()->setBlend(true); + Driver->getCacheHandler()->setAlphaTest(true); + Driver->getCacheHandler()->setAlphaFunc(GL_GREATER, material.MaterialTypeParam); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates || material.MaterialTypeParam != lastMaterial.MaterialTypeParam ) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates || material.MaterialTypeParam != lastMaterial.MaterialTypeParam) { Driver->getCacheHandler()->setActiveTexture(GL_TEXTURE0_ARB); #ifdef GL_ARB_texture_env_combine @@ -289,9 +272,9 @@ public: glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #ifdef GL_ARB_texture_env_combine - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE ); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE); #else - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_MODULATE ); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_EXT, GL_MODULATE); #endif Driver->getCacheHandler()->setAlphaTest(false); Driver->getCacheHandler()->setBlend(false); @@ -304,20 +287,18 @@ public: } protected: - - video::COpenGLDriver* Driver; + video::COpenGLDriver *Driver; }; - //! Transparent alpha channel material renderer class COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF : public IMaterialRenderer { public: + COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(video::COpenGLDriver *d) : + Driver(d) {} - COpenGLMaterialRenderer_TRANSPARENT_ALPHA_CHANNEL_REF(video::COpenGLDriver* d) : Driver(d) {} - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_DISABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE_TO_ENABLE); @@ -327,8 +308,7 @@ public: Driver->disableTextures(1); Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) { Driver->getCacheHandler()->setAlphaTest(true); Driver->getCacheHandler()->setAlphaFunc(GL_GREATER, 0.5f); } @@ -342,12 +322,11 @@ public: //! Returns if the material is transparent. bool isTransparent() const override { - return false; // this material is not really transparent because it does no blending. + return false; // this material is not really transparent because it does no blending. } protected: - - video::COpenGLDriver* Driver; + video::COpenGLDriver *Driver; }; } // end namespace video diff --git a/source/Irrlicht/COpenGLSLMaterialRenderer.cpp b/source/Irrlicht/COpenGLSLMaterialRenderer.cpp index 9958d2fd..535e72fc 100644 --- a/source/Irrlicht/COpenGLSLMaterialRenderer.cpp +++ b/source/Irrlicht/COpenGLSLMaterialRenderer.cpp @@ -31,31 +31,30 @@ namespace irr namespace video { - //! Constructor -COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(video::COpenGLDriver* driver, - s32& outMaterialTypeNr, const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, +COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(video::COpenGLDriver *driver, + s32 &outMaterialTypeNr, const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, - IShaderConstantSetCallBack* callback, + IShaderConstantSetCallBack *callback, E_MATERIAL_TYPE baseMaterial, - s32 userData) - : Driver(driver), CallBack(callback), Alpha(false), Blending(false), AlphaTest(false), Program(0), Program2(0), UserData(userData) + s32 userData) : + Driver(driver), + CallBack(callback), Alpha(false), Blending(false), AlphaTest(false), Program(0), Program2(0), UserData(userData) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("COpenGLSLMaterialRenderer"); - #endif +#endif - switch (baseMaterial) - { + switch (baseMaterial) { case EMT_TRANSPARENT_VERTEX_ALPHA: case EMT_TRANSPARENT_ALPHA_CHANNEL: Alpha = true; @@ -79,16 +78,15 @@ COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(video::COpenGLDriver* drive init(outMaterialTypeNr, vertexShaderProgram, pixelShaderProgram, geometryShaderProgram); } - //! constructor only for use by derived classes who want to //! create a fall back material for example. -COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(COpenGLDriver* driver, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, s32 userData) -: Driver(driver), CallBack(callback), Alpha(false), Blending(false), AlphaTest(false), Program(0), Program2(0), UserData(userData) +COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(COpenGLDriver *driver, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, s32 userData) : + Driver(driver), + CallBack(callback), Alpha(false), Blending(false), AlphaTest(false), Program(0), Program2(0), UserData(userData) { - switch (baseMaterial) - { + switch (baseMaterial) { case EMT_TRANSPARENT_VERTEX_ALPHA: case EMT_TRANSPARENT_ALPHA_CHANNEL: Alpha = true; @@ -107,36 +105,33 @@ COpenGLSLMaterialRenderer::COpenGLSLMaterialRenderer(COpenGLDriver* driver, CallBack->grab(); } - //! Destructor COpenGLSLMaterialRenderer::~COpenGLSLMaterialRenderer() { if (CallBack) CallBack->drop(); - if (Program) - { + if (Program) { GLhandleARB shaders[8]; GLint count; Driver->extGlGetAttachedObjects(Program, 8, &count, shaders); // avoid bugs in some drivers, which return larger numbers // use int variable to avoid compiler problems with template - int mincount=core::min_((int)count,8); - for (int i=0; iextGlDeleteObject(shaders[i]); Driver->extGlDeleteObject(Program); Program = 0; } - if (Program2) - { + if (Program2) { GLuint shaders[8]; GLint count; Driver->extGlGetAttachedShaders(Program2, 8, &count, shaders); // avoid bugs in some drivers, which return larger numbers // use int variable to avoid compiler problems with template - int mincount=core::min_((int)count,8); - for (int i=0; iextGlDeleteShader(shaders[i]); Driver->extGlDeleteProgram(Program2); Program2 = 0; @@ -145,11 +140,10 @@ COpenGLSLMaterialRenderer::~COpenGLSLMaterialRenderer() UniformInfo.clear(); } - -void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, - const c8* vertexShaderProgram, - const c8* pixelShaderProgram, - const c8* geometryShaderProgram, +void COpenGLSLMaterialRenderer::init(s32 &outMaterialTypeNr, + const c8 *vertexShaderProgram, + const c8 *pixelShaderProgram, + const c8 *geometryShaderProgram, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut) { @@ -158,7 +152,7 @@ void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, if (!createProgram()) return; -#if defined(GL_ARB_vertex_shader) && defined (GL_ARB_fragment_shader) +#if defined(GL_ARB_vertex_shader) && defined(GL_ARB_fragment_shader) if (vertexShaderProgram) if (!createShader(GL_VERTEX_SHADER_ARB, vertexShaderProgram)) return; @@ -169,8 +163,7 @@ void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, #endif #if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_program4) || defined(GL_NV_geometry_shader4) - if (geometryShaderProgram && Driver->queryFeature(EVDF_GEOMETRY_SHADER)) - { + if (geometryShaderProgram && Driver->queryFeature(EVDF_GEOMETRY_SHADER)) { if (!createShader(GL_GEOMETRY_SHADER_EXT, geometryShaderProgram)) return; #if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_shader4) @@ -178,13 +171,13 @@ void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, { Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_INPUT_TYPE_EXT, Driver->primitiveTypeToGL(inType)); Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_OUTPUT_TYPE_EXT, Driver->primitiveTypeToGL(outType)); - if (verticesOut==0) + if (verticesOut == 0) Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_VERTICES_OUT_EXT, Driver->MaxGeometryVerticesOut); else Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_VERTICES_OUT_EXT, core::min_(verticesOut, Driver->MaxGeometryVerticesOut)); } #elif defined(GL_NV_geometry_program4) - if (verticesOut==0) + if (verticesOut == 0) Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, Driver->MaxGeometryVerticesOut); else Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, core::min_(verticesOut, Driver->MaxGeometryVerticesOut)); @@ -199,32 +192,29 @@ void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, outMaterialTypeNr = Driver->addMaterialRenderer(this); } - -bool COpenGLSLMaterialRenderer::OnRender(IMaterialRendererServices* service, - E_VERTEX_TYPE vtxtype) +bool COpenGLSLMaterialRenderer::OnRender(IMaterialRendererServices *service, + E_VERTEX_TYPE vtxtype) { // call callback to set shader constants - if (CallBack && (Program||Program2)) + if (CallBack && (Program || Program2)) CallBack->OnSetConstants(this, UserData); return true; } - -void COpenGLSLMaterialRenderer::OnSetMaterial(const video::SMaterial& material, - const video::SMaterial& lastMaterial, - bool resetAllRenderstates, - video::IMaterialRendererServices* services) +void COpenGLSLMaterialRenderer::OnSetMaterial(const video::SMaterial &material, + const video::SMaterial &lastMaterial, + bool resetAllRenderstates, + video::IMaterialRendererServices *services) { if (Driver->getFixedPipelineState() == COpenGLDriver::EOFPS_ENABLE) Driver->setFixedPipelineState(COpenGLDriver::EOFPS_ENABLE_TO_DISABLE); else Driver->setFixedPipelineState(COpenGLDriver::EOFPS_DISABLE); - COpenGLCacheHandler* cacheHandler = Driver->getCacheHandler(); + COpenGLCacheHandler *cacheHandler = Driver->getCacheHandler(); - if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) - { + if (material.MaterialType != lastMaterial.MaterialType || resetAllRenderstates) { if (Program2) Driver->irrGlUseProgram(Program2); else if (Program) @@ -233,34 +223,26 @@ void COpenGLSLMaterialRenderer::OnSetMaterial(const video::SMaterial& material, Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - if (Alpha) - { + if (Alpha) { cacheHandler->setBlend(true); cacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); cacheHandler->setAlphaTest(true); cacheHandler->setAlphaFunc(GL_GREATER, 0.f); - } - else if (Blending) - { - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + } else if (Blending) { + E_BLEND_FACTOR srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact; E_MODULATE_FUNC modulate; u32 alphaSource; unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) - { + if (Driver->queryFeature(EVDF_BLEND_SEPARATE)) { cacheHandler->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), - Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); - } - else - { + Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); + } else { cacheHandler->setBlendFunc(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact)); - } + } cacheHandler->setBlend(true); - } - else if (AlphaTest) - { + } else if (AlphaTest) { cacheHandler->setAlphaTest(true); cacheHandler->setAlphaFunc(GL_GREATER, 0.5f); } @@ -269,7 +251,6 @@ void COpenGLSLMaterialRenderer::OnSetMaterial(const video::SMaterial& material, CallBack->OnSetMaterial(material); } - void COpenGLSLMaterialRenderer::OnUnsetMaterial() { if (Program) @@ -277,39 +258,33 @@ void COpenGLSLMaterialRenderer::OnUnsetMaterial() if (Program2) Driver->irrGlUseProgram(0); - COpenGLCacheHandler* cacheHandler = Driver->getCacheHandler(); - if (Alpha || Blending) - { + COpenGLCacheHandler *cacheHandler = Driver->getCacheHandler(); + if (Alpha || Blending) { cacheHandler->setBlend(false); } - if (Alpha || AlphaTest) - { + if (Alpha || AlphaTest) { cacheHandler->setAlphaTest(false); } } - //! Returns if the material is transparent. bool COpenGLSLMaterialRenderer::isTransparent() const { return (Alpha || Blending); } - bool COpenGLSLMaterialRenderer::createProgram() { - if (Driver->Version>=200) + if (Driver->Version >= 200) Program2 = Driver->extGlCreateProgram(); else Program = Driver->extGlCreateProgramObject(); return true; } - -bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char* shader) +bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char *shader) { - if (Program2) - { + if (Program2) { GLuint shaderHandle = Driver->extGlCreateShader(shaderType); Driver->extGlShaderSource(shaderHandle, 1, &shader, NULL); Driver->extGlCompileShader(shaderHandle); @@ -320,33 +295,29 @@ bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char* shad Driver->extGlGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &status); #endif - if (status != GL_TRUE) - { + if (status != GL_TRUE) { core::stringc typeInfo("shaderType: "); typeInfo += core::stringc((unsigned long)shaderType); os::Printer::log("GLSL (> 2.x) shader failed to compile", typeInfo.c_str(), ELL_ERROR); // check error message and log it - GLint maxLength=0; + GLint maxLength = 0; GLint length; #ifdef GL_VERSION_2_0 Driver->extGlGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &maxLength); #endif - if (maxLength) - { + if (maxLength) { GLchar *infoLog = new GLchar[maxLength]; Driver->extGlGetShaderInfoLog(shaderHandle, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; } Driver->extGlAttachShader(Program2, shaderHandle); - } - else - { + } else { GLhandleARB shaderHandle = Driver->extGlCreateShaderObject(shaderType); Driver->extGlShaderSourceARB(shaderHandle, 1, &shader, NULL); @@ -358,24 +329,22 @@ bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char* shad Driver->extGlGetObjectParameteriv(shaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &status); #endif - if (!status) - { + if (!status) { core::stringc typeInfo("shaderType: "); typeInfo += core::stringc((unsigned long)shaderType); os::Printer::log("GLSL shader failed to compile", typeInfo.c_str(), ELL_ERROR); // check error message and log it - GLint maxLength=0; + GLint maxLength = 0; GLsizei length; #ifdef GL_ARB_shader_objects Driver->extGlGetObjectParameteriv(shaderHandle, GL_OBJECT_INFO_LOG_LENGTH_ARB, &maxLength); #endif - if (maxLength) - { + if (maxLength) { GLcharARB *infoLog = new GLcharARB[maxLength]; Driver->extGlGetInfoLog(shaderHandle, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; @@ -386,11 +355,9 @@ bool COpenGLSLMaterialRenderer::createShader(GLenum shaderType, const char* shad return true; } - bool COpenGLSLMaterialRenderer::linkProgram() { - if (Program2) - { + if (Program2) { Driver->extGlLinkProgram(Program2); GLint status = 0; @@ -399,21 +366,19 @@ bool COpenGLSLMaterialRenderer::linkProgram() Driver->extGlGetProgramiv(Program2, GL_LINK_STATUS, &status); #endif - if (!status) - { + if (!status) { os::Printer::log("GLSL (> 2.x) shader program failed to link", ELL_ERROR); // check error message and log it - GLint maxLength=0; + GLint maxLength = 0; GLsizei length; #ifdef GL_VERSION_2_0 Driver->extGlGetProgramiv(Program2, GL_INFO_LOG_LENGTH, &maxLength); #endif - if (maxLength) - { + if (maxLength) { GLchar *infoLog = new GLchar[maxLength]; Driver->extGlGetProgramInfoLog(Program2, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; @@ -426,8 +391,7 @@ bool COpenGLSLMaterialRenderer::linkProgram() Driver->extGlGetProgramiv(Program2, GL_ACTIVE_UNIFORMS, &num); #endif - if (num == 0) - { + if (num == 0) { // no uniforms return true; } @@ -437,8 +401,7 @@ bool COpenGLSLMaterialRenderer::linkProgram() Driver->extGlGetProgramiv(Program2, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxlen); #endif - if (maxlen == 0) - { + if (maxlen == 0) { os::Printer::log("GLSL (> 2.x): failed to retrieve uniform information", ELL_ERROR); return false; } @@ -450,23 +413,20 @@ bool COpenGLSLMaterialRenderer::linkProgram() UniformInfo.clear(); UniformInfo.reallocate(num); - for (GLint i=0; i < num; ++i) - { + for (GLint i = 0; i < num; ++i) { SUniformInfo ui; memset(buf, 0, maxlen); GLint size; - Driver->extGlGetActiveUniform(Program2, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); + Driver->extGlGetActiveUniform(Program2, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); ui.name = buf; ui.location = Driver->extGlGetUniformLocation(Program2, buf); UniformInfo.push_back(ui); } - delete [] buf; - } - else - { + delete[] buf; + } else { Driver->extGlLinkProgramARB(Program); GLint status = 0; @@ -475,22 +435,20 @@ bool COpenGLSLMaterialRenderer::linkProgram() Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_LINK_STATUS_ARB, &status); #endif - if (!status) - { + if (!status) { os::Printer::log("GLSL shader program failed to link", ELL_ERROR); // check error message and log it - GLint maxLength=0; + GLint maxLength = 0; GLsizei length; #ifdef GL_ARB_shader_objects Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_INFO_LOG_LENGTH_ARB, &maxLength); #endif - if (maxLength) - { + if (maxLength) { GLcharARB *infoLog = new GLcharARB[maxLength]; Driver->extGlGetInfoLog(Program, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; @@ -499,23 +457,21 @@ bool COpenGLSLMaterialRenderer::linkProgram() // get uniforms information GLint num = 0; - #ifdef GL_ARB_shader_objects +#ifdef GL_ARB_shader_objects Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &num); - #endif +#endif - if (num == 0) - { + if (num == 0) { // no uniforms return true; } GLint maxlen = 0; - #ifdef GL_ARB_shader_objects +#ifdef GL_ARB_shader_objects Driver->extGlGetObjectParameteriv(Program, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, &maxlen); - #endif +#endif - if (maxlen == 0) - { + if (maxlen == 0) { os::Printer::log("GLSL: failed to retrieve uniform information", ELL_ERROR); return false; } @@ -527,43 +483,40 @@ bool COpenGLSLMaterialRenderer::linkProgram() UniformInfo.clear(); UniformInfo.reallocate(num); - for (int i=0; i < num; ++i) - { + for (int i = 0; i < num; ++i) { SUniformInfo ui; memset(buf, 0, maxlen); GLint size; - Driver->extGlGetActiveUniformARB(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); + Driver->extGlGetActiveUniformARB(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); ui.name = buf; ui.location = Driver->extGlGetUniformLocationARB(Program, buf); UniformInfo.push_back(ui); } - delete [] buf; + delete[] buf; } return true; } - -void COpenGLSLMaterialRenderer::setBasicRenderStates(const SMaterial& material, - const SMaterial& lastMaterial, - bool resetAllRenderstates) +void COpenGLSLMaterialRenderer::setBasicRenderStates(const SMaterial &material, + const SMaterial &lastMaterial, + bool resetAllRenderstates) { // forward Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); } -s32 COpenGLSLMaterialRenderer::getVertexShaderConstantID(const c8* name) +s32 COpenGLSLMaterialRenderer::getVertexShaderConstantID(const c8 *name) { return getPixelShaderConstantID(name); } -s32 COpenGLSLMaterialRenderer::getPixelShaderConstantID(const c8* name) +s32 COpenGLSLMaterialRenderer::getPixelShaderConstantID(const c8 *name) { - for (u32 i = 0; i < UniformInfo.size(); ++i) - { + for (u32 i = 0; i < UniformInfo.size(); ++i) { if (UniformInfo[i].name == name) return i; } @@ -571,163 +524,156 @@ s32 COpenGLSLMaterialRenderer::getPixelShaderConstantID(const c8* name) return -1; } -bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const f32* floats, int count) +bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const f32 *floats, int count) { return setPixelShaderConstant(index, floats, count); } -bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const s32* ints, int count) +bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const s32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } -bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const u32* ints, int count) +bool COpenGLSLMaterialRenderer::setVertexShaderConstant(s32 index, const u32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } -bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const f32* floats, int count) +bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const f32 *floats, int count) { - if(index < 0 || UniformInfo[index].location < 0) + if (index < 0 || UniformInfo[index].location < 0) return false; bool status = true; - switch (UniformInfo[index].type) - { - case GL_FLOAT: - Driver->extGlUniform1fv(UniformInfo[index].location, count, floats); - break; - case GL_FLOAT_VEC2: - Driver->extGlUniform2fv(UniformInfo[index].location, count/2, floats); - break; - case GL_FLOAT_VEC3: - Driver->extGlUniform3fv(UniformInfo[index].location, count/3, floats); - break; - case GL_FLOAT_VEC4: - Driver->extGlUniform4fv(UniformInfo[index].location, count/4, floats); - break; - case GL_FLOAT_MAT2: - Driver->extGlUniformMatrix2fv(UniformInfo[index].location, count/4, false, floats); - break; - case GL_FLOAT_MAT2x3: - Driver->extGlUniformMatrix2x3fv(UniformInfo[index].location, count/6, false, floats); - break; - case GL_FLOAT_MAT2x4: - Driver->extGlUniformMatrix2x4fv(UniformInfo[index].location, count/8, false, floats); - break; - case GL_FLOAT_MAT3x2: - Driver->extGlUniformMatrix3x2fv(UniformInfo[index].location, count/6, false, floats); - break; - case GL_FLOAT_MAT3: - Driver->extGlUniformMatrix3fv(UniformInfo[index].location, count/9, false, floats); - break; - case GL_FLOAT_MAT3x4: - Driver->extGlUniformMatrix3x4fv(UniformInfo[index].location, count/12, false, floats); - break; - case GL_FLOAT_MAT4x2: - Driver->extGlUniformMatrix4x2fv(UniformInfo[index].location, count/8, false, floats); - break; - case GL_FLOAT_MAT4x3: - Driver->extGlUniformMatrix4x3fv(UniformInfo[index].location, count/12, false, floats); - break; - case GL_FLOAT_MAT4: - Driver->extGlUniformMatrix4fv(UniformInfo[index].location, count/16, false, floats); - break; - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - { - if(floats) - { - const GLint id = static_cast(*floats); - Driver->extGlUniform1iv(UniformInfo[index].location, 1, &id); - } - else - status = false; - } - break; - default: + switch (UniformInfo[index].type) { + case GL_FLOAT: + Driver->extGlUniform1fv(UniformInfo[index].location, count, floats); + break; + case GL_FLOAT_VEC2: + Driver->extGlUniform2fv(UniformInfo[index].location, count / 2, floats); + break; + case GL_FLOAT_VEC3: + Driver->extGlUniform3fv(UniformInfo[index].location, count / 3, floats); + break; + case GL_FLOAT_VEC4: + Driver->extGlUniform4fv(UniformInfo[index].location, count / 4, floats); + break; + case GL_FLOAT_MAT2: + Driver->extGlUniformMatrix2fv(UniformInfo[index].location, count / 4, false, floats); + break; + case GL_FLOAT_MAT2x3: + Driver->extGlUniformMatrix2x3fv(UniformInfo[index].location, count / 6, false, floats); + break; + case GL_FLOAT_MAT2x4: + Driver->extGlUniformMatrix2x4fv(UniformInfo[index].location, count / 8, false, floats); + break; + case GL_FLOAT_MAT3x2: + Driver->extGlUniformMatrix3x2fv(UniformInfo[index].location, count / 6, false, floats); + break; + case GL_FLOAT_MAT3: + Driver->extGlUniformMatrix3fv(UniformInfo[index].location, count / 9, false, floats); + break; + case GL_FLOAT_MAT3x4: + Driver->extGlUniformMatrix3x4fv(UniformInfo[index].location, count / 12, false, floats); + break; + case GL_FLOAT_MAT4x2: + Driver->extGlUniformMatrix4x2fv(UniformInfo[index].location, count / 8, false, floats); + break; + case GL_FLOAT_MAT4x3: + Driver->extGlUniformMatrix4x3fv(UniformInfo[index].location, count / 12, false, floats); + break; + case GL_FLOAT_MAT4: + Driver->extGlUniformMatrix4fv(UniformInfo[index].location, count / 16, false, floats); + break; + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: { + if (floats) { + const GLint id = static_cast(*floats); + Driver->extGlUniform1iv(UniformInfo[index].location, 1, &id); + } else status = false; - break; + } break; + default: + status = false; + break; } return status; } -bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const s32* ints, int count) +bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const s32 *ints, int count) { - if(index < 0 || UniformInfo[index].location < 0) + if (index < 0 || UniformInfo[index].location < 0) return false; bool status = true; - switch (UniformInfo[index].type) - { - case GL_INT: - case GL_BOOL: - Driver->extGlUniform1iv(UniformInfo[index].location, count, reinterpret_cast(ints)); - break; - case GL_INT_VEC2: - case GL_BOOL_VEC2: - Driver->extGlUniform2iv(UniformInfo[index].location, count/2, reinterpret_cast(ints)); - break; - case GL_INT_VEC3: - case GL_BOOL_VEC3: - Driver->extGlUniform3iv(UniformInfo[index].location, count/3, reinterpret_cast(ints)); - break; - case GL_INT_VEC4: - case GL_BOOL_VEC4: - Driver->extGlUniform4iv(UniformInfo[index].location, count/4, reinterpret_cast(ints)); - break; - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - Driver->extGlUniform1iv(UniformInfo[index].location, 1, reinterpret_cast(ints)); - break; - default: - status = false; - break; + switch (UniformInfo[index].type) { + case GL_INT: + case GL_BOOL: + Driver->extGlUniform1iv(UniformInfo[index].location, count, reinterpret_cast(ints)); + break; + case GL_INT_VEC2: + case GL_BOOL_VEC2: + Driver->extGlUniform2iv(UniformInfo[index].location, count / 2, reinterpret_cast(ints)); + break; + case GL_INT_VEC3: + case GL_BOOL_VEC3: + Driver->extGlUniform3iv(UniformInfo[index].location, count / 3, reinterpret_cast(ints)); + break; + case GL_INT_VEC4: + case GL_BOOL_VEC4: + Driver->extGlUniform4iv(UniformInfo[index].location, count / 4, reinterpret_cast(ints)); + break; + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + Driver->extGlUniform1iv(UniformInfo[index].location, 1, reinterpret_cast(ints)); + break; + default: + status = false; + break; } return status; } -bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const u32* ints, int count) +bool COpenGLSLMaterialRenderer::setPixelShaderConstant(s32 index, const u32 *ints, int count) { - if(index < 0 || UniformInfo[index].location < 0) + if (index < 0 || UniformInfo[index].location < 0) return false; bool status = true; - switch (UniformInfo[index].type) - { - case GL_UNSIGNED_INT: - Driver->extGlUniform1uiv(UniformInfo[index].location, count, reinterpret_cast(ints)); - break; + switch (UniformInfo[index].type) { + case GL_UNSIGNED_INT: + Driver->extGlUniform1uiv(UniformInfo[index].location, count, reinterpret_cast(ints)); + break; #if defined(GL_VERSION_3_0) - case GL_UNSIGNED_INT_VEC2: - Driver->extGlUniform2uiv(UniformInfo[index].location, count/2, reinterpret_cast(ints)); - break; - case GL_UNSIGNED_INT_VEC3: - Driver->extGlUniform3uiv(UniformInfo[index].location, count/3, reinterpret_cast(ints)); - break; - case GL_UNSIGNED_INT_VEC4: - Driver->extGlUniform4uiv(UniformInfo[index].location, count/4, reinterpret_cast(ints)); - break; + case GL_UNSIGNED_INT_VEC2: + Driver->extGlUniform2uiv(UniformInfo[index].location, count / 2, reinterpret_cast(ints)); + break; + case GL_UNSIGNED_INT_VEC3: + Driver->extGlUniform3uiv(UniformInfo[index].location, count / 3, reinterpret_cast(ints)); + break; + case GL_UNSIGNED_INT_VEC4: + Driver->extGlUniform4uiv(UniformInfo[index].location, count / 4, reinterpret_cast(ints)); + break; #endif - default: - status = false; - break; + default: + status = false; + break; } return status; } -IVideoDriver* COpenGLSLMaterialRenderer::getVideoDriver() +IVideoDriver *COpenGLSLMaterialRenderer::getVideoDriver() { return Driver; } @@ -735,6 +681,4 @@ IVideoDriver* COpenGLSLMaterialRenderer::getVideoDriver() } // end namespace video } // end namespace irr - #endif - diff --git a/source/Irrlicht/COpenGLSLMaterialRenderer.h b/source/Irrlicht/COpenGLSLMaterialRenderer.h index 574bb338..2f4a485d 100644 --- a/source/Irrlicht/COpenGLSLMaterialRenderer.h +++ b/source/Irrlicht/COpenGLSLMaterialRenderer.h @@ -28,34 +28,33 @@ class IShaderConstantSetCallBack; class COpenGLSLMaterialRenderer : public IMaterialRenderer, public IMaterialRendererServices { public: - //! Constructor COpenGLSLMaterialRenderer( - COpenGLDriver* driver, - s32& outMaterialTypeNr, - const c8* vertexShaderProgram = 0, - const c8* vertexShaderEntryPointName = 0, - E_VERTEX_SHADER_TYPE vsCompileTarget = video::EVST_VS_1_1, - const c8* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = 0, - E_PIXEL_SHADER_TYPE psCompileTarget = video::EPST_PS_1_1, - const c8* geometryShaderProgram = 0, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = EMT_SOLID, - s32 userData = 0); + COpenGLDriver *driver, + s32 &outMaterialTypeNr, + const c8 *vertexShaderProgram = 0, + const c8 *vertexShaderEntryPointName = 0, + E_VERTEX_SHADER_TYPE vsCompileTarget = video::EVST_VS_1_1, + const c8 *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = 0, + E_PIXEL_SHADER_TYPE psCompileTarget = video::EPST_PS_1_1, + const c8 *geometryShaderProgram = 0, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = EMT_SOLID, + s32 userData = 0); //! Destructor virtual ~COpenGLSLMaterialRenderer(); - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services) override; + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services) override; - bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) override; + bool OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype) override; void OnUnsetMaterial() override; @@ -63,46 +62,45 @@ public: bool isTransparent() const override; //! Access the callback provided by the users when creating shader materials - IShaderConstantSetCallBack* getShaderConstantSetCallBack() const override + IShaderConstantSetCallBack *getShaderConstantSetCallBack() const override { return CallBack; } // implementations for the render services - void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates) override; - s32 getVertexShaderConstantID(const c8* name) override; - s32 getPixelShaderConstantID(const c8* name) override; - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; - IVideoDriver* getVideoDriver() override; + void setBasicRenderStates(const SMaterial &material, const SMaterial &lastMaterial, bool resetAllRenderstates) override; + s32 getVertexShaderConstantID(const c8 *name) override; + s32 getPixelShaderConstantID(const c8 *name) override; + bool setVertexShaderConstant(s32 index, const f32 *floats, int count) override; + bool setVertexShaderConstant(s32 index, const s32 *ints, int count) override; + bool setVertexShaderConstant(s32 index, const u32 *ints, int count) override; + bool setPixelShaderConstant(s32 index, const f32 *floats, int count) override; + bool setPixelShaderConstant(s32 index, const s32 *ints, int count) override; + bool setPixelShaderConstant(s32 index, const u32 *ints, int count) override; + IVideoDriver *getVideoDriver() override; protected: - //! constructor only for use by derived classes who want to //! create a fall back material for example. - COpenGLSLMaterialRenderer(COpenGLDriver* driver, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData=0); + COpenGLSLMaterialRenderer(COpenGLDriver *driver, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData = 0); - void init(s32& outMaterialTypeNr, - const c8* vertexShaderProgram, - const c8* pixelShaderProgram, - const c8* geometryShaderProgram, - scene::E_PRIMITIVE_TYPE inType=scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType=scene::EPT_TRIANGLE_STRIP, - u32 verticesOut=0); + void init(s32 &outMaterialTypeNr, + const c8 *vertexShaderProgram, + const c8 *pixelShaderProgram, + const c8 *geometryShaderProgram, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0); bool createProgram(); - bool createShader(GLenum shaderType, const char* shader); + bool createShader(GLenum shaderType, const char *shader); bool linkProgram(); - COpenGLDriver* Driver; - IShaderConstantSetCallBack* CallBack; + COpenGLDriver *Driver; + IShaderConstantSetCallBack *CallBack; bool Alpha; bool Blending; @@ -121,7 +119,6 @@ protected: s32 UserData; }; - } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/CReadFile.cpp b/source/Irrlicht/CReadFile.cpp index 4db0d3bf..c482d593 100644 --- a/source/Irrlicht/CReadFile.cpp +++ b/source/Irrlicht/CReadFile.cpp @@ -9,27 +9,24 @@ namespace irr namespace io { - -CReadFile::CReadFile(const io::path& fileName) -: File(0), FileSize(0), Filename(fileName) +CReadFile::CReadFile(const io::path &fileName) : + File(0), FileSize(0), Filename(fileName) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CReadFile"); - #endif +#endif openFile(); } - CReadFile::~CReadFile() { if (File) fclose(File); } - //! returns how much was read -size_t CReadFile::read(void* buffer, size_t sizeToRead) +size_t CReadFile::read(void *buffer, size_t sizeToRead) { if (!isOpen()) return 0; @@ -37,7 +34,6 @@ size_t CReadFile::read(void* buffer, size_t sizeToRead) return fread(buffer, 1, sizeToRead, File); } - //! changes position in file, returns true if successful //! if relativeMovement==true, the pos is changed relative to current pos, //! otherwise from begin of file @@ -49,21 +45,18 @@ bool CReadFile::seek(long finalPos, bool relativeMovement) return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0; } - //! returns size of file long CReadFile::getSize() const { return FileSize; } - //! returns where in the file we are. long CReadFile::getPos() const { return ftell(File); } - //! opens the file void CReadFile::openFile() { @@ -75,8 +68,7 @@ void CReadFile::openFile() File = fopen(Filename.c_str(), "rb"); - if (File) - { + if (File) { // get FileSize fseek(File, 0, SEEK_END); @@ -85,17 +77,15 @@ void CReadFile::openFile() } } - //! returns name of file -const io::path& CReadFile::getFileName() const +const io::path &CReadFile::getFileName() const { return Filename; } - -IReadFile* CReadFile::createReadFile(const io::path& fileName) +IReadFile *CReadFile::createReadFile(const io::path &fileName) { - CReadFile* file = new CReadFile(fileName); + CReadFile *file = new CReadFile(fileName); if (file->isOpen()) return file; @@ -103,7 +93,5 @@ IReadFile* CReadFile::createReadFile(const io::path& fileName) return 0; } - } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CReadFile.h b/source/Irrlicht/CReadFile.h index 1a4c15c2..14f67477 100644 --- a/source/Irrlicht/CReadFile.h +++ b/source/Irrlicht/CReadFile.h @@ -14,57 +14,54 @@ namespace irr namespace io { - /*! - Class for reading a real file from disk. - */ - class CReadFile : public IReadFile +/*! + Class for reading a real file from disk. +*/ +class CReadFile : public IReadFile +{ +public: + CReadFile(const io::path &fileName); + + virtual ~CReadFile(); + + //! returns how much was read + size_t read(void *buffer, size_t sizeToRead) override; + + //! changes position in file, returns true if successful + bool seek(long finalPos, bool relativeMovement = false) override; + + //! returns size of file + long getSize() const override; + + //! returns if file is open + bool isOpen() const { - public: + return File != 0; + } - CReadFile(const io::path& fileName); + //! returns where in the file we are. + long getPos() const override; - virtual ~CReadFile(); + //! returns name of file + const io::path &getFileName() const override; - //! returns how much was read - size_t read(void* buffer, size_t sizeToRead) override; + //! Get the type of the class implementing this interface + EREAD_FILE_TYPE getType() const override + { + return ERFT_READ_FILE; + } - //! changes position in file, returns true if successful - bool seek(long finalPos, bool relativeMovement = false) override; + //! create read file on disk. + static IReadFile *createReadFile(const io::path &fileName); - //! returns size of file - long getSize() const override; +private: + //! opens the file + void openFile(); - //! returns if file is open - bool isOpen() const - { - return File != 0; - } - - //! returns where in the file we are. - long getPos() const override; - - //! returns name of file - const io::path& getFileName() const override; - - //! Get the type of the class implementing this interface - EREAD_FILE_TYPE getType() const override - { - return ERFT_READ_FILE; - } - - //! create read file on disk. - static IReadFile* createReadFile(const io::path& fileName); - - private: - - //! opens the file - void openFile(); - - FILE* File; - long FileSize; - io::path Filename; - }; + FILE *File; + long FileSize; + io::path Filename; +}; } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CSDLManager.cpp b/source/Irrlicht/CSDLManager.cpp index b8c61a4d..c2b38e47 100644 --- a/source/Irrlicht/CSDLManager.cpp +++ b/source/Irrlicht/CSDLManager.cpp @@ -14,30 +14,31 @@ namespace irr namespace video { -CSDLManager::CSDLManager(CIrrDeviceSDL* device) : IContextManager(), SDLDevice(device) +CSDLManager::CSDLManager(CIrrDeviceSDL *device) : + IContextManager(), SDLDevice(device) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CSDLManager"); - #endif +#endif } -bool CSDLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) +bool CSDLManager::initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) { Data = data; return true; } -const SExposedVideoData& CSDLManager::getContext() const +const SExposedVideoData &CSDLManager::getContext() const { return Data; } -bool CSDLManager::activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) +bool CSDLManager::activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) { return true; } -void* CSDLManager::getProcAddress(const std::string &procName) +void *CSDLManager::getProcAddress(const std::string &procName) { return SDL_GL_GetProcAddress(procName.c_str()); } diff --git a/source/Irrlicht/CSDLManager.h b/source/Irrlicht/CSDLManager.h index b8aa1cfb..22efeb1e 100644 --- a/source/Irrlicht/CSDLManager.h +++ b/source/Irrlicht/CSDLManager.h @@ -10,39 +10,39 @@ namespace irr { - class CIrrDeviceSDL; +class CIrrDeviceSDL; namespace video { - // Manager for SDL with OpenGL - class CSDLManager : public IContextManager - { - public: - CSDLManager(CIrrDeviceSDL* device); +// Manager for SDL with OpenGL +class CSDLManager : public IContextManager +{ +public: + CSDLManager(CIrrDeviceSDL *device); - virtual ~CSDLManager() {} + virtual ~CSDLManager() {} - bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) override; + bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) override; - void terminate() override {}; - bool generateSurface() override { return true; }; - void destroySurface() override {}; - bool generateContext() override { return true; }; - void destroyContext() override {}; + void terminate() override{}; + bool generateSurface() override { return true; }; + void destroySurface() override{}; + bool generateContext() override { return true; }; + void destroyContext() override{}; - const SExposedVideoData& getContext() const override; + const SExposedVideoData &getContext() const override; - bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero=false) override; + bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero = false) override; - void* getProcAddress(const std::string &procName) override; + void *getProcAddress(const std::string &procName) override; - bool swapBuffers() override; + bool swapBuffers() override; - private: - SExposedVideoData Data; - CIrrDeviceSDL *SDLDevice; - }; +private: + SExposedVideoData Data; + CIrrDeviceSDL *SDLDevice; +}; } } diff --git a/source/Irrlicht/CSceneCollisionManager.cpp b/source/Irrlicht/CSceneCollisionManager.cpp index cfd08ff0..692f3c44 100644 --- a/source/Irrlicht/CSceneCollisionManager.cpp +++ b/source/Irrlicht/CSceneCollisionManager.cpp @@ -15,18 +15,17 @@ namespace scene { //! constructor -CSceneCollisionManager::CSceneCollisionManager(ISceneManager* smanager, video::IVideoDriver* driver) -: SceneManager(smanager), Driver(driver) +CSceneCollisionManager::CSceneCollisionManager(ISceneManager *smanager, video::IVideoDriver *driver) : + SceneManager(smanager), Driver(driver) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CSceneCollisionManager"); - #endif +#endif if (Driver) Driver->grab(); } - //! destructor CSceneCollisionManager::~CSceneCollisionManager() { @@ -34,12 +33,11 @@ CSceneCollisionManager::~CSceneCollisionManager() Driver->drop(); } - //! Returns a 3d ray which would go through the 2d screen coordinates. core::line3d CSceneCollisionManager::getRayFromScreenCoordinates( - const core::position2d & pos, const ICameraSceneNode* camera) + const core::position2d &pos, const ICameraSceneNode *camera) { - core::line3d ln(0,0,0,0,0,0); + core::line3d ln(0, 0, 0, 0, 0, 0); if (!SceneManager) return ln; @@ -50,20 +48,20 @@ core::line3d CSceneCollisionManager::getRayFromScreenCoordinates( if (!camera) return ln; - const scene::SViewFrustum* f = camera->getViewFrustum(); + const scene::SViewFrustum *f = camera->getViewFrustum(); core::vector3df farLeftUp = f->getFarLeftUp(); core::vector3df lefttoright = f->getFarRightUp() - farLeftUp; core::vector3df uptodown = f->getFarLeftDown() - farLeftUp; - const core::rect& viewPort = Driver->getViewPort(); + const core::rect &viewPort = Driver->getViewPort(); core::dimension2d screenSize(viewPort.getWidth(), viewPort.getHeight()); f32 dx = pos.X / (f32)screenSize.Width; f32 dy = pos.Y / (f32)screenSize.Height; if (camera->isOrthogonal()) - ln.start = f->cameraPosition + (lefttoright * (dx-0.5f)) + (uptodown * (dy-0.5f)); + ln.start = f->cameraPosition + (lefttoright * (dx - 0.5f)) + (uptodown * (dy - 0.5f)); else ln.start = f->cameraPosition; diff --git a/source/Irrlicht/CSceneCollisionManager.h b/source/Irrlicht/CSceneCollisionManager.h index d2db8091..d3dc2ef7 100644 --- a/source/Irrlicht/CSceneCollisionManager.h +++ b/source/Irrlicht/CSceneCollisionManager.h @@ -13,26 +13,23 @@ namespace irr namespace scene { - class CSceneCollisionManager : public ISceneCollisionManager - { - public: +class CSceneCollisionManager : public ISceneCollisionManager +{ +public: + //! constructor + CSceneCollisionManager(ISceneManager *smanager, video::IVideoDriver *driver); - //! constructor - CSceneCollisionManager(ISceneManager* smanager, video::IVideoDriver* driver); + //! destructor + virtual ~CSceneCollisionManager(); - //! destructor - virtual ~CSceneCollisionManager(); - - //! Returns a 3d ray which would go through the 2d screen coordinates. - virtual core::line3d getRayFromScreenCoordinates( - const core::position2d & pos, const ICameraSceneNode* camera = 0) override; - - private: - - ISceneManager* SceneManager; - video::IVideoDriver* Driver; - }; + //! Returns a 3d ray which would go through the 2d screen coordinates. + virtual core::line3d getRayFromScreenCoordinates( + const core::position2d &pos, const ICameraSceneNode *camera = 0) override; +private: + ISceneManager *SceneManager; + video::IVideoDriver *Driver; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CSceneManager.cpp b/source/Irrlicht/CSceneManager.cpp index 2dbd3fe4..b20f6010 100644 --- a/source/Irrlicht/CSceneManager.cpp +++ b/source/Irrlicht/CSceneManager.cpp @@ -33,17 +33,18 @@ namespace scene { //! constructor -CSceneManager::CSceneManager(video::IVideoDriver* driver, - gui::ICursorControl* cursorControl, IMeshCache* cache) -: ISceneNode(0, 0), Driver(driver), - CursorControl(cursorControl), - ActiveCamera(0), ShadowColor(150,0,0,0), AmbientLight(0,0,0,0), Parameters(0), - MeshCache(cache), CurrentRenderPass(ESNRP_NONE) +CSceneManager::CSceneManager(video::IVideoDriver *driver, + gui::ICursorControl *cursorControl, IMeshCache *cache) : + ISceneNode(0, 0), + Driver(driver), + CursorControl(cursorControl), + ActiveCamera(0), ShadowColor(150, 0, 0, 0), AmbientLight(0, 0, 0, 0), Parameters(0), + MeshCache(cache), CurrentRenderPass(ESNRP_NONE) { - #ifdef _DEBUG +#ifdef _DEBUG ISceneManager::setDebugName("CSceneManager ISceneManager"); ISceneNode::setDebugName("CSceneManager ISceneNode"); - #endif +#endif // root node's scene manager SceneManager = this; @@ -77,7 +78,6 @@ CSceneManager::CSceneManager(video::IVideoDriver* driver, MeshLoaderList.push_back(new CB3DMeshFileLoader(this)); } - //! destructor CSceneManager::~CSceneManager() { @@ -96,7 +96,7 @@ CSceneManager::~CSceneManager() CollisionManager->drop(); u32 i; - for (i=0; idrop(); if (ActiveCamera) @@ -118,15 +118,14 @@ CSceneManager::~CSceneManager() Driver->drop(); } - //! gets an animatable mesh. loads it if needed. returned pointer must not be dropped. -IAnimatedMesh* CSceneManager::getMesh(io::IReadFile* file) +IAnimatedMesh *CSceneManager::getMesh(io::IReadFile *file) { if (!file) return 0; io::path name = file->getFileName(); - IAnimatedMesh* msh = MeshCache->getMeshByName(name); + IAnimatedMesh *msh = MeshCache->getMeshByName(name); if (msh) return msh; @@ -136,21 +135,18 @@ IAnimatedMesh* CSceneManager::getMesh(io::IReadFile* file) } // load and create a mesh which we know already isn't in the cache and put it in there -IAnimatedMesh* CSceneManager::getUncachedMesh(io::IReadFile* file, const io::path& filename, const io::path& cachename) +IAnimatedMesh *CSceneManager::getUncachedMesh(io::IReadFile *file, const io::path &filename, const io::path &cachename) { - IAnimatedMesh* msh = 0; + IAnimatedMesh *msh = 0; // iterate the list in reverse order so user-added loaders can override the built-in ones s32 count = MeshLoaderList.size(); - for (s32 i=count-1; i>=0; --i) - { - if (MeshLoaderList[i]->isALoadableFileExtension(filename)) - { + for (s32 i = count - 1; i >= 0; --i) { + if (MeshLoaderList[i]->isALoadableFileExtension(filename)) { // reset file to avoid side effects of previous calls to createMesh file->seek(0); msh = MeshLoaderList[i]->createMesh(file); - if (msh) - { + if (msh) { MeshCache->addMesh(cachename, msh); msh->drop(); break; @@ -167,17 +163,16 @@ IAnimatedMesh* CSceneManager::getUncachedMesh(io::IReadFile* file, const io::pat } //! returns the video driver -video::IVideoDriver* CSceneManager::getVideoDriver() +video::IVideoDriver *CSceneManager::getVideoDriver() { return Driver; } - //! adds a scene node for rendering a static mesh //! the returned pointer must not be dropped. -IMeshSceneNode* CSceneManager::addMeshSceneNode(IMesh* mesh, ISceneNode* parent, s32 id, - const core::vector3df& position, const core::vector3df& rotation, - const core::vector3df& scale, bool alsoAddIfMeshPointerZero) +IMeshSceneNode *CSceneManager::addMeshSceneNode(IMesh *mesh, ISceneNode *parent, s32 id, + const core::vector3df &position, const core::vector3df &rotation, + const core::vector3df &scale, bool alsoAddIfMeshPointerZero) { if (!alsoAddIfMeshPointerZero && !mesh) return 0; @@ -185,17 +180,16 @@ IMeshSceneNode* CSceneManager::addMeshSceneNode(IMesh* mesh, ISceneNode* parent, if (!parent) parent = this; - IMeshSceneNode* node = new CMeshSceneNode(mesh, parent, this, id, position, rotation, scale); + IMeshSceneNode *node = new CMeshSceneNode(mesh, parent, this, id, position, rotation, scale); node->drop(); return node; } - //! adds a scene node for rendering an animated mesh model -IAnimatedMeshSceneNode* CSceneManager::addAnimatedMeshSceneNode(IAnimatedMesh* mesh, ISceneNode* parent, s32 id, - const core::vector3df& position, const core::vector3df& rotation, - const core::vector3df& scale, bool alsoAddIfMeshPointerZero) +IAnimatedMeshSceneNode *CSceneManager::addAnimatedMeshSceneNode(IAnimatedMesh *mesh, ISceneNode *parent, s32 id, + const core::vector3df &position, const core::vector3df &rotation, + const core::vector3df &scale, bool alsoAddIfMeshPointerZero) { if (!alsoAddIfMeshPointerZero && !mesh) return 0; @@ -203,28 +197,27 @@ IAnimatedMeshSceneNode* CSceneManager::addAnimatedMeshSceneNode(IAnimatedMesh* m if (!parent) parent = this; - IAnimatedMeshSceneNode* node = - new CAnimatedMeshSceneNode(mesh, parent, this, id, position, rotation, scale); + IAnimatedMeshSceneNode *node = + new CAnimatedMeshSceneNode(mesh, parent, this, id, position, rotation, scale); node->drop(); return node; } - //! Adds a camera scene node to the tree and sets it as active camera. //! \param position: Position of the space relative to its parent where the camera will be placed. //! \param lookat: Position where the camera will look at. Also known as target. //! \param parent: Parent scene node of the camera. Can be null. If the parent moves, //! the camera will move too. //! \return Returns pointer to interface to camera -ICameraSceneNode* CSceneManager::addCameraSceneNode(ISceneNode* parent, - const core::vector3df& position, const core::vector3df& lookat, s32 id, - bool makeActive) +ICameraSceneNode *CSceneManager::addCameraSceneNode(ISceneNode *parent, + const core::vector3df &position, const core::vector3df &lookat, s32 id, + bool makeActive) { if (!parent) parent = this; - ICameraSceneNode* node = new CCameraSceneNode(parent, this, id, position, lookat); + ICameraSceneNode *node = new CCameraSceneNode(parent, this, id, position, lookat); if (makeActive) setActiveCamera(node); @@ -233,77 +226,70 @@ ICameraSceneNode* CSceneManager::addCameraSceneNode(ISceneNode* parent, return node; } - //! Adds a billboard scene node to the scene. A billboard is like a 3d sprite: A 2d element, //! which always looks to the camera. It is usually used for things like explosions, fire, //! lensflares and things like that. -IBillboardSceneNode* CSceneManager::addBillboardSceneNode(ISceneNode* parent, - const core::dimension2d& size, const core::vector3df& position, s32 id, - video::SColor colorTop, video::SColor colorBottom - ) +IBillboardSceneNode *CSceneManager::addBillboardSceneNode(ISceneNode *parent, + const core::dimension2d &size, const core::vector3df &position, s32 id, + video::SColor colorTop, video::SColor colorBottom) { if (!parent) parent = this; - IBillboardSceneNode* node = new CBillboardSceneNode(parent, this, id, position, size, - colorTop, colorBottom); + IBillboardSceneNode *node = new CBillboardSceneNode(parent, this, id, position, size, + colorTop, colorBottom); node->drop(); return node; } - //! Adds an empty scene node. -ISceneNode* CSceneManager::addEmptySceneNode(ISceneNode* parent, s32 id) +ISceneNode *CSceneManager::addEmptySceneNode(ISceneNode *parent, s32 id) { if (!parent) parent = this; - ISceneNode* node = new CEmptySceneNode(parent, this, id); + ISceneNode *node = new CEmptySceneNode(parent, this, id); node->drop(); return node; } - //! Adds a dummy transformation scene node to the scene graph. -IDummyTransformationSceneNode* CSceneManager::addDummyTransformationSceneNode( - ISceneNode* parent, s32 id) +IDummyTransformationSceneNode *CSceneManager::addDummyTransformationSceneNode( + ISceneNode *parent, s32 id) { if (!parent) parent = this; - IDummyTransformationSceneNode* node = new CDummyTransformationSceneNode( - parent, this, id); + IDummyTransformationSceneNode *node = new CDummyTransformationSceneNode( + parent, this, id); node->drop(); return node; } - //! Returns the root scene node. This is the scene node which is parent //! of all scene nodes. The root scene node is a special scene node which //! only exists to manage all scene nodes. It is not rendered and cannot //! be removed from the scene. //! \return Returns a pointer to the root scene node. -ISceneNode* CSceneManager::getRootSceneNode() +ISceneNode *CSceneManager::getRootSceneNode() { return this; } - //! Returns the current active camera. //! \return The active camera is returned. Note that this can be NULL, if there //! was no camera created yet. -ICameraSceneNode* CSceneManager::getActiveCamera() const +ICameraSceneNode *CSceneManager::getActiveCamera() const { return ActiveCamera; } - //! Sets the active camera. The previous active camera will be deactivated. //! \param camera: The new camera which should be active. -void CSceneManager::setActiveCamera(ICameraSceneNode* camera) +void CSceneManager::setActiveCamera(ICameraSceneNode *camera) { if (camera) camera->grab(); @@ -313,15 +299,13 @@ void CSceneManager::setActiveCamera(ICameraSceneNode* camera) ActiveCamera = camera; } - //! renders the node. void CSceneManager::render() { } - //! returns the axis aligned bounding box of this node -const core::aabbox3d& CSceneManager::getBoundingBox() const +const core::aabbox3d &CSceneManager::getBoundingBox() const { _IRR_DEBUG_BREAK_IF(true) // Bounding Box of Scene Manager should never be used. @@ -329,34 +313,29 @@ const core::aabbox3d& CSceneManager::getBoundingBox() const return dummy; } - //! returns if node is culled -bool CSceneManager::isCulled(const ISceneNode* node) const +bool CSceneManager::isCulled(const ISceneNode *node) const { - const ICameraSceneNode* cam = getActiveCamera(); - if (!cam) - { + const ICameraSceneNode *cam = getActiveCamera(); + if (!cam) { return false; } bool result = false; // has occlusion query information - if (node->getAutomaticCulling() & scene::EAC_OCC_QUERY) - { - result = (Driver->getOcclusionQueryResult(const_cast(node))==0); + if (node->getAutomaticCulling() & scene::EAC_OCC_QUERY) { + result = (Driver->getOcclusionQueryResult(const_cast(node)) == 0); } // can be seen by a bounding box ? - if (!result && (node->getAutomaticCulling() & scene::EAC_BOX)) - { + if (!result && (node->getAutomaticCulling() & scene::EAC_BOX)) { core::aabbox3d tbox = node->getBoundingBox(); node->getAbsoluteTransformation().transformBoxEx(tbox); - result = !(tbox.intersectsWithBox(cam->getViewFrustum()->getBoundingBox() )); + result = !(tbox.intersectsWithBox(cam->getViewFrustum()->getBoundingBox())); } // can be seen by a bounding sphere - if (!result && (node->getAutomaticCulling() & scene::EAC_FRUSTUM_SPHERE)) - { + if (!result && (node->getAutomaticCulling() & scene::EAC_FRUSTUM_SPHERE)) { const core::aabbox3df nbox = node->getTransformedBoundingBox(); const float rad = nbox.getRadius(); const core::vector3df center = nbox.getCenter(); @@ -371,32 +350,27 @@ bool CSceneManager::isCulled(const ISceneNode* node) const } // can be seen by cam pyramid planes ? - if (!result && (node->getAutomaticCulling() & scene::EAC_FRUSTUM_BOX)) - { + if (!result && (node->getAutomaticCulling() & scene::EAC_FRUSTUM_BOX)) { SViewFrustum frust = *cam->getViewFrustum(); - //transform the frustum to the node's current absolute transformation + // transform the frustum to the node's current absolute transformation core::matrix4 invTrans(node->getAbsoluteTransformation(), core::matrix4::EM4CONST_INVERSE); - //invTrans.makeInverse(); + // invTrans.makeInverse(); frust.transform(invTrans); core::vector3df edges[8]; node->getBoundingBox().getEdges(edges); - for (s32 i=0; igetMaterialCount(); taken = 0; - for (u32 i=0; ineedsTransparentRenderPass(node->getMaterial(i))) - { + for (u32 i = 0; i < count; ++i) { + if (Driver->needsTransparentRenderPass(node->getMaterial(i))) { // register as transparent node TransparentNodeEntry e(node, camWorldPos); TransparentNodeList.push_back(e); @@ -476,16 +437,14 @@ u32 CSceneManager::registerNodeForRendering(ISceneNode* node, E_SCENE_NODE_RENDE } // not transparent, register as solid - if (!taken) - { + if (!taken) { SolidNodeList.push_back(node); taken = 1; } } break; case ESNRP_GUI: - if (!isCulled(node)) - { + if (!isCulled(node)) { GuiNodeList.push_back(node); taken = 1; } @@ -521,11 +480,11 @@ void CSceneManager::drawAll() // reset all transforms Driver->setMaterial(video::SMaterial()); - Driver->setTransform ( video::ETS_PROJECTION, core::IdentityMatrix ); - Driver->setTransform ( video::ETS_VIEW, core::IdentityMatrix ); - Driver->setTransform ( video::ETS_WORLD, core::IdentityMatrix ); - for (i=video::ETS_COUNT-1; i>=video::ETS_TEXTURE_0; --i) - Driver->setTransform ( (video::E_TRANSFORMATION_STATE)i, core::IdentityMatrix ); + Driver->setTransform(video::ETS_PROJECTION, core::IdentityMatrix); + Driver->setTransform(video::ETS_VIEW, core::IdentityMatrix); + Driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); + for (i = video::ETS_COUNT - 1; i >= video::ETS_TEXTURE_0; --i) + Driver->setTransform((video::E_TRANSFORMATION_STATE)i, core::IdentityMatrix); // TODO: This should not use an attribute here but a real parameter when necessary (too slow!) Driver->setAllowZWriteOnTransparent(Parameters->getAttributeAsBool(ALLOW_ZWRITE_ON_TRANSPARENT)); @@ -536,9 +495,8 @@ void CSceneManager::drawAll() First Scene Node for prerendering should be the active camera consistent Camera is needed for culling */ - camWorldPos.set(0,0,0); - if (ActiveCamera) - { + camWorldPos.set(0, 0, 0); + if (ActiveCamera) { ActiveCamera->render(); camWorldPos = ActiveCamera->getAbsolutePosition(); } @@ -546,12 +504,12 @@ void CSceneManager::drawAll() // let all nodes register themselves OnRegisterSceneNode(); - //render camera scenes + // render camera scenes { CurrentRenderPass = ESNRP_CAMERA; Driver->getOverrideMaterial().Enabled = ((Driver->getOverrideMaterial().EnablePasses & CurrentRenderPass) != 0); - for (i=0; irender(); CameraList.set_used(0); @@ -562,7 +520,7 @@ void CSceneManager::drawAll() CurrentRenderPass = ESNRP_SKY_BOX; Driver->getOverrideMaterial().Enabled = ((Driver->getOverrideMaterial().EnablePasses & CurrentRenderPass) != 0); - for (i=0; irender(); SkyBoxList.set_used(0); @@ -575,7 +533,7 @@ void CSceneManager::drawAll() SolidNodeList.sort(); // sort by textures - for (i=0; irender(); SolidNodeList.set_used(0); @@ -587,7 +545,7 @@ void CSceneManager::drawAll() Driver->getOverrideMaterial().Enabled = ((Driver->getOverrideMaterial().EnablePasses & CurrentRenderPass) != 0); TransparentNodeList.sort(); // sort by distance from camera - for (i=0; irender(); TransparentNodeList.set_used(0); @@ -600,7 +558,7 @@ void CSceneManager::drawAll() TransparentEffectNodeList.sort(); // sort by distance from camera - for (i=0; irender(); TransparentEffectNodeList.set_used(0); @@ -611,7 +569,7 @@ void CSceneManager::drawAll() CurrentRenderPass = ESNRP_GUI; Driver->getOverrideMaterial().Enabled = ((Driver->getOverrideMaterial().EnablePasses & CurrentRenderPass) != 0); - for (i=0; irender(); GuiNodeList.set_used(0); @@ -621,9 +579,8 @@ void CSceneManager::drawAll() CurrentRenderPass = ESNRP_NONE; } - //! Adds an external mesh loader. -void CSceneManager::addExternalMeshLoader(IMeshLoader* externalLoader) +void CSceneManager::addExternalMeshLoader(IMeshLoader *externalLoader) { if (!externalLoader) return; @@ -632,16 +589,14 @@ void CSceneManager::addExternalMeshLoader(IMeshLoader* externalLoader) MeshLoaderList.push_back(externalLoader); } - //! Returns the number of mesh loaders supported by Irrlicht at this time u32 CSceneManager::getMeshLoaderCount() const { return MeshLoaderList.size(); } - //! Retrieve the given mesh loader -IMeshLoader* CSceneManager::getMeshLoader(u32 index) const +IMeshLoader *CSceneManager::getMeshLoader(u32 index) const { if (index < MeshLoaderList.size()) return MeshLoaderList[index]; @@ -649,23 +604,20 @@ IMeshLoader* CSceneManager::getMeshLoader(u32 index) const return 0; } - //! Returns a pointer to the scene collision manager. -ISceneCollisionManager* CSceneManager::getSceneCollisionManager() +ISceneCollisionManager *CSceneManager::getSceneCollisionManager() { return CollisionManager; } - //! Returns a pointer to the mesh manipulator. -IMeshManipulator* CSceneManager::getMeshManipulator() +IMeshManipulator *CSceneManager::getMeshManipulator() { return Driver->getMeshManipulator(); } - //! Adds a scene node to the deletion queue. -void CSceneManager::addToDeletionQueue(ISceneNode* node) +void CSceneManager::addToDeletionQueue(ISceneNode *node) { if (!node) return; @@ -674,15 +626,13 @@ void CSceneManager::addToDeletionQueue(ISceneNode* node) DeletionList.push_back(node); } - //! clears the deletion list void CSceneManager::clearDeletionList() { if (DeletionList.empty()) return; - for (u32 i=0; iremove(); DeletionList[i]->drop(); } @@ -690,9 +640,8 @@ void CSceneManager::clearDeletionList() DeletionList.clear(); } - //! Returns the first scene node with the specified name. -ISceneNode* CSceneManager::getSceneNodeFromName(const char* name, ISceneNode* start) +ISceneNode *CSceneManager::getSceneNodeFromName(const char *name, ISceneNode *start) { if (start == 0) start = getRootSceneNode(); @@ -701,12 +650,11 @@ ISceneNode* CSceneManager::getSceneNodeFromName(const char* name, ISceneNode* st if (startName.has_value() && startName == name) return start; - ISceneNode* node = 0; + ISceneNode *node = 0; - const ISceneNodeList& list = start->getChildren(); + const ISceneNodeList &list = start->getChildren(); ISceneNodeList::const_iterator it = list.begin(); - for (; it!=list.end(); ++it) - { + for (; it != list.end(); ++it) { node = getSceneNodeFromName(name, *it); if (node) return node; @@ -715,9 +663,8 @@ ISceneNode* CSceneManager::getSceneNodeFromName(const char* name, ISceneNode* st return 0; } - //! Returns the first scene node with the specified id. -ISceneNode* CSceneManager::getSceneNodeFromId(s32 id, ISceneNode* start) +ISceneNode *CSceneManager::getSceneNodeFromId(s32 id, ISceneNode *start) { if (start == 0) start = getRootSceneNode(); @@ -725,12 +672,11 @@ ISceneNode* CSceneManager::getSceneNodeFromId(s32 id, ISceneNode* start) if (start->getID() == id) return start; - ISceneNode* node = 0; + ISceneNode *node = 0; - const ISceneNodeList& list = start->getChildren(); + const ISceneNodeList &list = start->getChildren(); ISceneNodeList::const_iterator it = list.begin(); - for (; it!=list.end(); ++it) - { + for (; it != list.end(); ++it) { node = getSceneNodeFromId(id, *it); if (node) return node; @@ -739,9 +685,8 @@ ISceneNode* CSceneManager::getSceneNodeFromId(s32 id, ISceneNode* start) return 0; } - //! Returns the first scene node with the specified type. -ISceneNode* CSceneManager::getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode* start) +ISceneNode *CSceneManager::getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode *start) { if (start == 0) start = getRootSceneNode(); @@ -749,12 +694,11 @@ ISceneNode* CSceneManager::getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, IS if (start->getType() == type || ESNT_ANY == type) return start; - ISceneNode* node = 0; + ISceneNode *node = 0; - const ISceneNodeList& list = start->getChildren(); + const ISceneNodeList &list = start->getChildren(); ISceneNodeList::const_iterator it = list.begin(); - for (; it!=list.end(); ++it) - { + for (; it != list.end(); ++it) { node = getSceneNodeFromType(type, *it); if (node) return node; @@ -763,9 +707,8 @@ ISceneNode* CSceneManager::getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, IS return 0; } - //! returns scene nodes by type. -void CSceneManager::getSceneNodesFromType(ESCENE_NODE_TYPE type, core::array& outNodes, ISceneNode* start) +void CSceneManager::getSceneNodesFromType(ESCENE_NODE_TYPE type, core::array &outNodes, ISceneNode *start) { if (start == 0) start = getRootSceneNode(); @@ -773,29 +716,26 @@ void CSceneManager::getSceneNodesFromType(ESCENE_NODE_TYPE type, core::arraygetType() == type || ESNT_ANY == type) outNodes.push_back(start); - const ISceneNodeList& list = start->getChildren(); + const ISceneNodeList &list = start->getChildren(); ISceneNodeList::const_iterator it = list.begin(); - for (; it!=list.end(); ++it) - { + for (; it != list.end(); ++it) { getSceneNodesFromType(type, outNodes, *it); } } - //! Posts an input event to the environment. Usually you do not have to //! use this method, it is used by the internal engine. -bool CSceneManager::postEventFromUser(const SEvent& event) +bool CSceneManager::postEventFromUser(const SEvent &event) { bool ret = false; - ICameraSceneNode* cam = getActiveCamera(); + ICameraSceneNode *cam = getActiveCamera(); if (cam) ret = cam->OnEvent(event); return ret; } - //! Removes all children of this scene node void CSceneManager::removeAll() { @@ -806,39 +746,34 @@ void CSceneManager::removeAll() Driver->setMaterial(video::SMaterial()); } - //! Clears the whole scene. All scene nodes are removed. void CSceneManager::clear() { removeAll(); } - //! Returns interface to the parameters set in this scene. -io::IAttributes* CSceneManager::getParameters() +io::IAttributes *CSceneManager::getParameters() { return Parameters; } - //! Returns current render pass. E_SCENE_NODE_RENDER_PASS CSceneManager::getSceneNodeRenderPass() const { return CurrentRenderPass; } - //! Returns an interface to the mesh cache which is shared between all existing scene managers. -IMeshCache* CSceneManager::getMeshCache() +IMeshCache *CSceneManager::getMeshCache() { return MeshCache; } - //! Creates a new scene manager. -ISceneManager* CSceneManager::createNewSceneManager(bool cloneContent) +ISceneManager *CSceneManager::createNewSceneManager(bool cloneContent) { - CSceneManager* manager = new CSceneManager(Driver, CursorControl, MeshCache); + CSceneManager *manager = new CSceneManager(Driver, CursorControl, MeshCache); if (cloneContent) manager->cloneMembers(this, manager); @@ -846,35 +781,29 @@ ISceneManager* CSceneManager::createNewSceneManager(bool cloneContent) return manager; } - //! Sets ambient color of the scene void CSceneManager::setAmbientLight(const video::SColorf &ambientColor) { AmbientLight = ambientColor; } - //! Returns ambient color of the scene -const video::SColorf& CSceneManager::getAmbientLight() const +const video::SColorf &CSceneManager::getAmbientLight() const { return AmbientLight; } - //! Get a skinned mesh, which is not available as header-only code -ISkinnedMesh* CSceneManager::createSkinnedMesh() +ISkinnedMesh *CSceneManager::createSkinnedMesh() { return new CSkinnedMesh(); } - // creates a scenemanager -ISceneManager* createSceneManager(video::IVideoDriver* driver, gui::ICursorControl* cursorcontrol) +ISceneManager *createSceneManager(video::IVideoDriver *driver, gui::ICursorControl *cursorcontrol) { return new CSceneManager(driver, cursorcontrol, nullptr); } - } // end namespace scene } // end namespace irr - diff --git a/source/Irrlicht/CSceneManager.h b/source/Irrlicht/CSceneManager.h index db13bed9..0e27290a 100644 --- a/source/Irrlicht/CSceneManager.h +++ b/source/Irrlicht/CSceneManager.h @@ -16,290 +16,293 @@ namespace irr { namespace io { - class IFileSystem; +class IFileSystem; } namespace scene { - class IMeshCache; +class IMeshCache; - /*! - The Scene Manager manages scene nodes, mesh resources, cameras and all the other stuff. - */ - class CSceneManager : public ISceneManager, public ISceneNode - { - public: +/*! + The Scene Manager manages scene nodes, mesh resources, cameras and all the other stuff. +*/ +class CSceneManager : public ISceneManager, public ISceneNode +{ +public: + //! constructor + CSceneManager(video::IVideoDriver *driver, gui::ICursorControl *cursorControl, IMeshCache *cache = 0); - //! constructor - CSceneManager(video::IVideoDriver* driver, gui::ICursorControl* cursorControl, IMeshCache* cache = 0); + //! destructor + virtual ~CSceneManager(); - //! destructor - virtual ~CSceneManager(); + //! gets an animateable mesh. loads it if needed. returned pointer must not be dropped. + IAnimatedMesh *getMesh(io::IReadFile *file) override; - //! gets an animateable mesh. loads it if needed. returned pointer must not be dropped. - IAnimatedMesh* getMesh(io::IReadFile* file) override; + //! Returns an interface to the mesh cache which is shared between all existing scene managers. + IMeshCache *getMeshCache() override; - //! Returns an interface to the mesh cache which is shared between all existing scene managers. - IMeshCache* getMeshCache() override; + //! returns the video driver + video::IVideoDriver *getVideoDriver() override; - //! returns the video driver - video::IVideoDriver* getVideoDriver() override; + //! adds a scene node for rendering an animated mesh model + virtual IAnimatedMeshSceneNode *addAnimatedMeshSceneNode(IAnimatedMesh *mesh, ISceneNode *parent = 0, s32 id = -1, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f), + bool alsoAddIfMeshPointerZero = false) override; - //! adds a scene node for rendering an animated mesh model - virtual IAnimatedMeshSceneNode* addAnimatedMeshSceneNode(IAnimatedMesh* mesh, ISceneNode* parent=0, s32 id=-1, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f), - bool alsoAddIfMeshPointerZero=false) override; + //! adds a scene node for rendering a static mesh + //! the returned pointer must not be dropped. + virtual IMeshSceneNode *addMeshSceneNode(IMesh *mesh, ISceneNode *parent = 0, s32 id = -1, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &rotation = core::vector3df(0, 0, 0), + const core::vector3df &scale = core::vector3df(1.0f, 1.0f, 1.0f), + bool alsoAddIfMeshPointerZero = false) override; - //! adds a scene node for rendering a static mesh - //! the returned pointer must not be dropped. - virtual IMeshSceneNode* addMeshSceneNode(IMesh* mesh, ISceneNode* parent=0, s32 id=-1, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& rotation = core::vector3df(0,0,0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f), - bool alsoAddIfMeshPointerZero=false) override; + //! renders the node. + void render() override; - //! renders the node. - void render() override; + //! returns the axis aligned bounding box of this node + const core::aabbox3d &getBoundingBox() const override; - //! returns the axis aligned bounding box of this node - const core::aabbox3d& getBoundingBox() const override; + //! registers a node for rendering it at a specific time. + u32 registerNodeForRendering(ISceneNode *node, E_SCENE_NODE_RENDER_PASS pass = ESNRP_AUTOMATIC) override; - //! registers a node for rendering it at a specific time. - u32 registerNodeForRendering(ISceneNode* node, E_SCENE_NODE_RENDER_PASS pass = ESNRP_AUTOMATIC) override; + //! Clear all nodes which are currently registered for rendering + void clearAllRegisteredNodesForRendering() override; - //! Clear all nodes which are currently registered for rendering - void clearAllRegisteredNodesForRendering() override; + //! draws all scene nodes + void drawAll() override; - //! draws all scene nodes - void drawAll() override; + //! Adds a camera scene node to the tree and sets it as active camera. + //! \param position: Position of the space relative to its parent where the camera will be placed. + //! \param lookat: Position where the camera will look at. Also known as target. + //! \param parent: Parent scene node of the camera. Can be null. If the parent moves, + //! the camera will move too. + //! \return Pointer to interface to camera + virtual ICameraSceneNode *addCameraSceneNode(ISceneNode *parent = 0, + const core::vector3df &position = core::vector3df(0, 0, 0), + const core::vector3df &lookat = core::vector3df(0, 0, 100), + s32 id = -1, bool makeActive = true) override; - //! Adds a camera scene node to the tree and sets it as active camera. - //! \param position: Position of the space relative to its parent where the camera will be placed. - //! \param lookat: Position where the camera will look at. Also known as target. - //! \param parent: Parent scene node of the camera. Can be null. If the parent moves, - //! the camera will move too. - //! \return Pointer to interface to camera - virtual ICameraSceneNode* addCameraSceneNode(ISceneNode* parent = 0, - const core::vector3df& position = core::vector3df(0,0,0), - const core::vector3df& lookat = core::vector3df(0,0,100), - s32 id=-1, bool makeActive=true) override; - - //! Adds a billboard scene node to the scene. A billboard is like a 3d sprite: A 2d element, - //! which always looks to the camera. It is usually used for things like explosions, fire, - //! lensflares and things like that. - virtual IBillboardSceneNode* addBillboardSceneNode(ISceneNode* parent = 0, - const core::dimension2d& size = core::dimension2d(10.0f, 10.0f), - const core::vector3df& position = core::vector3df(0,0,0), s32 id=-1, + //! Adds a billboard scene node to the scene. A billboard is like a 3d sprite: A 2d element, + //! which always looks to the camera. It is usually used for things like explosions, fire, + //! lensflares and things like that. + virtual IBillboardSceneNode *addBillboardSceneNode(ISceneNode *parent = 0, + const core::dimension2d &size = core::dimension2d(10.0f, 10.0f), + const core::vector3df &position = core::vector3df(0, 0, 0), s32 id = -1, video::SColor shadeTop = 0xFFFFFFFF, video::SColor shadeBottom = 0xFFFFFFFF) override; - //! Adds a dummy transformation scene node to the scene graph. - virtual IDummyTransformationSceneNode* addDummyTransformationSceneNode( - ISceneNode* parent=0, s32 id=-1) override; + //! Adds a dummy transformation scene node to the scene graph. + virtual IDummyTransformationSceneNode *addDummyTransformationSceneNode( + ISceneNode *parent = 0, s32 id = -1) override; - //! Adds an empty scene node. - ISceneNode* addEmptySceneNode(ISceneNode* parent, s32 id=-1) override; + //! Adds an empty scene node. + ISceneNode *addEmptySceneNode(ISceneNode *parent, s32 id = -1) override; - //! Returns the root scene node. This is the scene node which is parent - //! of all scene nodes. The root scene node is a special scene node which - //! only exists to manage all scene nodes. It is not rendered and cannot - //! be removed from the scene. - //! \return Pointer to the root scene node. - ISceneNode* getRootSceneNode() override; + //! Returns the root scene node. This is the scene node which is parent + //! of all scene nodes. The root scene node is a special scene node which + //! only exists to manage all scene nodes. It is not rendered and cannot + //! be removed from the scene. + //! \return Pointer to the root scene node. + ISceneNode *getRootSceneNode() override; - //! Returns the current active camera. - //! \return The active camera is returned. Note that this can be NULL, if there - //! was no camera created yet. - ICameraSceneNode* getActiveCamera() const override; + //! Returns the current active camera. + //! \return The active camera is returned. Note that this can be NULL, if there + //! was no camera created yet. + ICameraSceneNode *getActiveCamera() const override; - //! Sets the active camera. The previous active camera will be deactivated. - //! \param camera: The new camera which should be active. - void setActiveCamera(ICameraSceneNode* camera) override; + //! Sets the active camera. The previous active camera will be deactivated. + //! \param camera: The new camera which should be active. + void setActiveCamera(ICameraSceneNode *camera) override; - //! Adds an external mesh loader. - void addExternalMeshLoader(IMeshLoader* externalLoader) override; + //! Adds an external mesh loader. + void addExternalMeshLoader(IMeshLoader *externalLoader) override; - //! Returns the number of mesh loaders supported by Irrlicht at this time - u32 getMeshLoaderCount() const override; + //! Returns the number of mesh loaders supported by Irrlicht at this time + u32 getMeshLoaderCount() const override; - //! Retrieve the given mesh loader - IMeshLoader* getMeshLoader(u32 index) const override; + //! Retrieve the given mesh loader + IMeshLoader *getMeshLoader(u32 index) const override; - //! Returns a pointer to the scene collision manager. - ISceneCollisionManager* getSceneCollisionManager() override; + //! Returns a pointer to the scene collision manager. + ISceneCollisionManager *getSceneCollisionManager() override; - //! Returns a pointer to the mesh manipulator. - IMeshManipulator* getMeshManipulator() override; + //! Returns a pointer to the mesh manipulator. + IMeshManipulator *getMeshManipulator() override; - //! Adds a scene node to the deletion queue. - void addToDeletionQueue(ISceneNode* node) override; + //! Adds a scene node to the deletion queue. + void addToDeletionQueue(ISceneNode *node) override; - //! Returns the first scene node with the specified id. - ISceneNode* getSceneNodeFromId(s32 id, ISceneNode* start=0) override; + //! Returns the first scene node with the specified id. + ISceneNode *getSceneNodeFromId(s32 id, ISceneNode *start = 0) override; - //! Returns the first scene node with the specified name. - ISceneNode* getSceneNodeFromName(const c8* name, ISceneNode* start=0) override; + //! Returns the first scene node with the specified name. + ISceneNode *getSceneNodeFromName(const c8 *name, ISceneNode *start = 0) override; - //! Returns the first scene node with the specified type. - ISceneNode* getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode* start=0) override; + //! Returns the first scene node with the specified type. + ISceneNode *getSceneNodeFromType(scene::ESCENE_NODE_TYPE type, ISceneNode *start = 0) override; - //! returns scene nodes by type. - void getSceneNodesFromType(ESCENE_NODE_TYPE type, core::array& outNodes, ISceneNode* start=0) override; + //! returns scene nodes by type. + void getSceneNodesFromType(ESCENE_NODE_TYPE type, core::array &outNodes, ISceneNode *start = 0) override; - //! Posts an input event to the environment. Usually you do not have to - //! use this method, it is used by the internal engine. - bool postEventFromUser(const SEvent& event) override; + //! Posts an input event to the environment. Usually you do not have to + //! use this method, it is used by the internal engine. + bool postEventFromUser(const SEvent &event) override; - //! Clears the whole scene. All scene nodes are removed. - void clear() override; + //! Clears the whole scene. All scene nodes are removed. + void clear() override; - //! Removes all children of this scene node - void removeAll() override; + //! Removes all children of this scene node + void removeAll() override; - //! Returns interface to the parameters set in this scene. - io::IAttributes* getParameters() override; + //! Returns interface to the parameters set in this scene. + io::IAttributes *getParameters() override; - //! Returns current render pass. - E_SCENE_NODE_RENDER_PASS getSceneNodeRenderPass() const override; + //! Returns current render pass. + E_SCENE_NODE_RENDER_PASS getSceneNodeRenderPass() const override; - //! Creates a new scene manager. - ISceneManager* createNewSceneManager(bool cloneContent) override; + //! Creates a new scene manager. + ISceneManager *createNewSceneManager(bool cloneContent) override; - //! Returns type of the scene node - ESCENE_NODE_TYPE getType() const override { return ESNT_SCENE_MANAGER; } + //! Returns type of the scene node + ESCENE_NODE_TYPE getType() const override { return ESNT_SCENE_MANAGER; } - //! Get a skinned mesh, which is not available as header-only code - ISkinnedMesh* createSkinnedMesh() override; + //! Get a skinned mesh, which is not available as header-only code + ISkinnedMesh *createSkinnedMesh() override; - //! Sets ambient color of the scene - void setAmbientLight(const video::SColorf &ambientColor) override; + //! Sets ambient color of the scene + void setAmbientLight(const video::SColorf &ambientColor) override; - //! Returns ambient color of the scene - const video::SColorf& getAmbientLight() const override; + //! Returns ambient color of the scene + const video::SColorf &getAmbientLight() const override; - //! Get current render time. - E_SCENE_NODE_RENDER_PASS getCurrentRenderPass() const override { return CurrentRenderPass; } + //! Get current render time. + E_SCENE_NODE_RENDER_PASS getCurrentRenderPass() const override { return CurrentRenderPass; } - //! Set current render time. - void setCurrentRenderPass(E_SCENE_NODE_RENDER_PASS nextPass) override { CurrentRenderPass = nextPass; } + //! Set current render time. + void setCurrentRenderPass(E_SCENE_NODE_RENDER_PASS nextPass) override { CurrentRenderPass = nextPass; } - //! returns if node is culled - bool isCulled(const ISceneNode* node) const override; + //! returns if node is culled + bool isCulled(const ISceneNode *node) const override; + +private: + // load and create a mesh which we know already isn't in the cache and put it in there + IAnimatedMesh *getUncachedMesh(io::IReadFile *file, const io::path &filename, const io::path &cachename); + + //! clears the deletion list + void clearDeletionList(); + + struct DefaultNodeEntry + { + DefaultNodeEntry() + { + } + + DefaultNodeEntry(ISceneNode *n) : + Node(n), TextureValue(0) + { + if (n->getMaterialCount()) + TextureValue = (n->getMaterial(0).getTexture(0)); + } + + bool operator<(const DefaultNodeEntry &other) const + { + return (TextureValue < other.TextureValue); + } + + ISceneNode *Node; private: - - // load and create a mesh which we know already isn't in the cache and put it in there - IAnimatedMesh* getUncachedMesh(io::IReadFile* file, const io::path& filename, const io::path& cachename); - - //! clears the deletion list - void clearDeletionList(); - - struct DefaultNodeEntry - { - DefaultNodeEntry() - { } - - DefaultNodeEntry(ISceneNode* n) : - Node(n), TextureValue(0) - { - if (n->getMaterialCount()) - TextureValue = (n->getMaterial(0).getTexture(0)); - } - - bool operator < (const DefaultNodeEntry& other) const - { - return (TextureValue < other.TextureValue); - } - - ISceneNode* Node; - private: - void* TextureValue; - }; - - //! sort on distance (center) to camera - struct TransparentNodeEntry - { - TransparentNodeEntry() - { } - - TransparentNodeEntry(ISceneNode* n, const core::vector3df& camera) - : Node(n) - { - Distance = Node->getAbsoluteTransformation().getTranslation().getDistanceFromSQ(camera); - } - - bool operator < (const TransparentNodeEntry& other) const - { - return Distance > other.Distance; - } - - ISceneNode* Node; - private: - f64 Distance; - }; - - //! sort on distance (sphere) to camera - struct DistanceNodeEntry - { - DistanceNodeEntry(ISceneNode* n, const core::vector3df& cameraPos) - : Node(n) - { - setNodeAndDistanceFromPosition(n, cameraPos); - } - - bool operator < (const DistanceNodeEntry& other) const - { - return Distance < other.Distance; - } - - void setNodeAndDistanceFromPosition(ISceneNode* n, const core::vector3df & fromPosition) - { - Node = n; - Distance = Node->getAbsoluteTransformation().getTranslation().getDistanceFromSQ(fromPosition); - Distance -= Node->getBoundingBox().getExtent().getLengthSQ() * 0.5; - } - - ISceneNode* Node; - private: - f64 Distance; - }; - - //! video driver - video::IVideoDriver* Driver; - - //! cursor control - gui::ICursorControl* CursorControl; - - //! collision manager - ISceneCollisionManager* CollisionManager; - - //! render pass lists - core::array CameraList; - core::array SkyBoxList; - core::array SolidNodeList; - core::array TransparentNodeList; - core::array TransparentEffectNodeList; - core::array GuiNodeList; - - core::array MeshLoaderList; - core::array DeletionList; - - //! current active camera - ICameraSceneNode* ActiveCamera; - core::vector3df camWorldPos; // Position of camera for transparent nodes. - - video::SColor ShadowColor; - video::SColorf AmbientLight; - - //! String parameters - // NOTE: Attributes are slow and should only be used for debug-info and not in release - io::CAttributes* Parameters; - - //! Mesh cache - IMeshCache* MeshCache; - - E_SCENE_NODE_RENDER_PASS CurrentRenderPass; + void *TextureValue; }; + //! sort on distance (center) to camera + struct TransparentNodeEntry + { + TransparentNodeEntry() + { + } + + TransparentNodeEntry(ISceneNode *n, const core::vector3df &camera) : + Node(n) + { + Distance = Node->getAbsoluteTransformation().getTranslation().getDistanceFromSQ(camera); + } + + bool operator<(const TransparentNodeEntry &other) const + { + return Distance > other.Distance; + } + + ISceneNode *Node; + + private: + f64 Distance; + }; + + //! sort on distance (sphere) to camera + struct DistanceNodeEntry + { + DistanceNodeEntry(ISceneNode *n, const core::vector3df &cameraPos) : + Node(n) + { + setNodeAndDistanceFromPosition(n, cameraPos); + } + + bool operator<(const DistanceNodeEntry &other) const + { + return Distance < other.Distance; + } + + void setNodeAndDistanceFromPosition(ISceneNode *n, const core::vector3df &fromPosition) + { + Node = n; + Distance = Node->getAbsoluteTransformation().getTranslation().getDistanceFromSQ(fromPosition); + Distance -= Node->getBoundingBox().getExtent().getLengthSQ() * 0.5; + } + + ISceneNode *Node; + + private: + f64 Distance; + }; + + //! video driver + video::IVideoDriver *Driver; + + //! cursor control + gui::ICursorControl *CursorControl; + + //! collision manager + ISceneCollisionManager *CollisionManager; + + //! render pass lists + core::array CameraList; + core::array SkyBoxList; + core::array SolidNodeList; + core::array TransparentNodeList; + core::array TransparentEffectNodeList; + core::array GuiNodeList; + + core::array MeshLoaderList; + core::array DeletionList; + + //! current active camera + ICameraSceneNode *ActiveCamera; + core::vector3df camWorldPos; // Position of camera for transparent nodes. + + video::SColor ShadowColor; + video::SColorf AmbientLight; + + //! String parameters + // NOTE: Attributes are slow and should only be used for debug-info and not in release + io::CAttributes *Parameters; + + //! Mesh cache + IMeshCache *MeshCache; + + E_SCENE_NODE_RENDER_PASS CurrentRenderPass; +}; + } // end namespace video } // end namespace scene diff --git a/source/Irrlicht/CSkinnedMesh.cpp b/source/Irrlicht/CSkinnedMesh.cpp index c36a285d..93ebde57 100644 --- a/source/Irrlicht/CSkinnedMesh.cpp +++ b/source/Irrlicht/CSkinnedMesh.cpp @@ -10,76 +10,72 @@ namespace { - // Frames must always be increasing, so we remove objects where this isn't the case - // return number of kicked keys - template // T = objects containing a "frame" variable - irr::u32 dropBadKeys(irr::core::array& array) - { - if (array.size()<2) - return 0; +// Frames must always be increasing, so we remove objects where this isn't the case +// return number of kicked keys +template // T = objects containing a "frame" variable +irr::u32 dropBadKeys(irr::core::array &array) +{ + if (array.size() < 2) + return 0; - irr::u32 n=1; // new index - for(irr::u32 j=1;j 0 ) - { - array.erase(n, d); - } - return d; + irr::u32 n = 1; // new index + for (irr::u32 j = 1; j < array.size(); ++j) { + if (array[j].frame < array[n - 1].frame) + continue; // bad frame, unneeded and may cause problems + if (n != j) + array[n] = array[j]; + ++n; } - - // drop identical middle keys - we only need the first and last - // return number of kicked keys - template // Cmp = comparison for keys of type T - irr::u32 dropMiddleKeys(irr::core::array& array, Cmp & cmp) - { - if ( array.size() < 3 ) - return 0; - - irr::u32 s = 0; // old index for current key - irr::u32 n = 1; // new index for next key - for(irr::u32 j=1;j s+1 ) // had there been identical keys? - array[n++] = array[j-1]; // keep the last - array[n++] = array[j]; // keep the new one - s = j; - } - if ( array.size() > s+1 ) // identical keys at the array end? - array[n++] = array[array.size()-1]; // keep the last - - irr::u32 d = array.size()-n; // remove already copied keys - if ( d > 0 ) - { - array.erase(n, d); - } - return d; + irr::u32 d = array.size() - n; // remove already copied keys + if (d > 0) { + array.erase(n, d); } + return d; +} - bool identicalPos(const irr::scene::ISkinnedMesh::SPositionKey& a, const irr::scene::ISkinnedMesh::SPositionKey& b) - { - return a.position == b.position; - } +// drop identical middle keys - we only need the first and last +// return number of kicked keys +template // Cmp = comparison for keys of type T +irr::u32 dropMiddleKeys(irr::core::array &array, Cmp &cmp) +{ + if (array.size() < 3) + return 0; - bool identicalScale(const irr::scene::ISkinnedMesh::SScaleKey& a, const irr::scene::ISkinnedMesh::SScaleKey& b) - { - return a.scale == b.scale; - } + irr::u32 s = 0; // old index for current key + irr::u32 n = 1; // new index for next key + for (irr::u32 j = 1; j < array.size(); ++j) { + if (cmp(array[j], array[s])) + continue; // same key, handle later - bool identicalRotation(const irr::scene::ISkinnedMesh::SRotationKey& a, const irr::scene::ISkinnedMesh::SRotationKey& b) - { - return a.rotation == b.rotation; + if (j > s + 1) // had there been identical keys? + array[n++] = array[j - 1]; // keep the last + array[n++] = array[j]; // keep the new one + s = j; } + if (array.size() > s + 1) // identical keys at the array end? + array[n++] = array[array.size() - 1]; // keep the last + + irr::u32 d = array.size() - n; // remove already copied keys + if (d > 0) { + array.erase(n, d); + } + return d; +} + +bool identicalPos(const irr::scene::ISkinnedMesh::SPositionKey &a, const irr::scene::ISkinnedMesh::SPositionKey &b) +{ + return a.position == b.position; +} + +bool identicalScale(const irr::scene::ISkinnedMesh::SScaleKey &a, const irr::scene::ISkinnedMesh::SScaleKey &b) +{ + return a.scale == b.scale; +} + +bool identicalRotation(const irr::scene::ISkinnedMesh::SRotationKey &a, const irr::scene::ISkinnedMesh::SRotationKey &b) +{ + return a.rotation == b.rotation; +} } namespace irr @@ -87,45 +83,40 @@ namespace irr namespace scene { - //! constructor -CSkinnedMesh::CSkinnedMesh() -: SkinningBuffers(0), EndFrame(0.f), FramesPerSecond(25.f), - LastAnimatedFrame(-1), SkinnedLastFrame(false), - InterpolationMode(EIM_LINEAR), - HasAnimation(false), PreparedForSkinning(false), - AnimateNormals(true), HardwareSkinning(false) +CSkinnedMesh::CSkinnedMesh() : + SkinningBuffers(0), EndFrame(0.f), FramesPerSecond(25.f), + LastAnimatedFrame(-1), SkinnedLastFrame(false), + InterpolationMode(EIM_LINEAR), + HasAnimation(false), PreparedForSkinning(false), + AnimateNormals(true), HardwareSkinning(false) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CSkinnedMesh"); - #endif +#endif - SkinningBuffers=&LocalBuffers; + SkinningBuffers = &LocalBuffers; } - //! destructor CSkinnedMesh::~CSkinnedMesh() { - for (u32 i=0; idrop(); } } - //! returns the amount of frames in milliseconds. //! If the amount is 1, it is a static (=non animated) mesh. u32 CSkinnedMesh::getFrameCount() const { - return core::floor32(EndFrame+1.f); + return core::floor32(EndFrame + 1.f); } - //! Gets the default animation speed of the animated mesh. /** \return Amount of frames per second. If the amount is 0, it is a static, non animated mesh. */ f32 CSkinnedMesh::getAnimationSpeed() const @@ -133,21 +124,19 @@ f32 CSkinnedMesh::getAnimationSpeed() const return FramesPerSecond; } - //! Gets the frame count of the animated mesh. /** \param fps Frames per second to play the animation with. If the amount is 0, it is not animated. The actual speed is set in the scene node the mesh is instantiated in.*/ void CSkinnedMesh::setAnimationSpeed(f32 fps) { - FramesPerSecond=fps; + FramesPerSecond = fps; } - //! returns the animated mesh based on a detail level. 0 is the lowest, 255 the highest detail. Note, that some Meshes will ignore the detail level. -IMesh* CSkinnedMesh::getMesh(s32 frame, s32 detailLevel, s32 startFrameLoop, s32 endFrameLoop) +IMesh *CSkinnedMesh::getMesh(s32 frame, s32 detailLevel, s32 startFrameLoop, s32 endFrameLoop) { - //animate(frame,startFrameLoop, endFrameLoop); - if (frame==-1) + // animate(frame,startFrameLoop, endFrameLoop); + if (frame == -1) return this; animateMesh((f32)frame, 1.0f); @@ -155,30 +144,27 @@ IMesh* CSkinnedMesh::getMesh(s32 frame, s32 detailLevel, s32 startFrameLoop, s32 return this; } - //-------------------------------------------------------------------------- // Keyframe Animation //-------------------------------------------------------------------------- - //! Animates this mesh's joints based on frame input //! blend: {0-old position, 1-New position} void CSkinnedMesh::animateMesh(f32 frame, f32 blend) { - if (!HasAnimation || LastAnimatedFrame==frame) + if (!HasAnimation || LastAnimatedFrame == frame) return; - LastAnimatedFrame=frame; - SkinnedLastFrame=false; + LastAnimatedFrame = frame; + SkinnedLastFrame = false; - if (blend<=0.f) - return; //No need to animate + if (blend <= 0.f) + return; // No need to animate - for (u32 i=0; iAnimatedposition; @@ -194,26 +180,23 @@ void CSkinnedMesh::animateMesh(f32 frame, f32 blend) scale, joint->scaleHint, rotation, joint->rotationHint); - if (blend==1.0f) - { - //No blending needed + if (blend == 1.0f) { + // No blending needed joint->Animatedposition = position; joint->Animatedscale = scale; joint->Animatedrotation = rotation; - } - else - { - //Blend animation + } else { + // Blend animation joint->Animatedposition = core::lerp(oldPosition, position, blend); joint->Animatedscale = core::lerp(oldScale, scale, blend); joint->Animatedrotation.slerp(oldRotation, rotation, blend); } } - //Note: - //LocalAnimatedMatrix needs to be built at some point, but this function may be called lots of times for - //one render (to play two animations at the same time) LocalAnimatedMatrix only needs to be built once. - //a call to buildAllLocalAnimatedMatrices is needed before skinning the mesh, and before the user gets the joints to move + // Note: + // LocalAnimatedMatrix needs to be built at some point, but this function may be called lots of times for + // one render (to play two animations at the same time) LocalAnimatedMatrix only needs to be built once. + // a call to buildAllLocalAnimatedMatrices is needed before skinning the mesh, and before the user gets the joints to move //---------------- // Temp! @@ -223,21 +206,18 @@ void CSkinnedMesh::animateMesh(f32 frame, f32 blend) updateBoundingBox(); } - void CSkinnedMesh::buildAllLocalAnimatedMatrices() { - for (u32 i=0; iUseAnimationFrom && - (joint->UseAnimationFrom->PositionKeys.size() || - joint->UseAnimationFrom->ScaleKeys.size() || - joint->UseAnimationFrom->RotationKeys.size() )) - { - joint->GlobalSkinningSpace=false; + (joint->UseAnimationFrom->PositionKeys.size() || + joint->UseAnimationFrom->ScaleKeys.size() || + joint->UseAnimationFrom->RotationKeys.size())) { + joint->GlobalSkinningSpace = false; // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched to getMatrix_transposed instead of getMatrix for downward compatibility. // Not tested so far if this was correct or wrong before quaternion fix! @@ -246,22 +226,21 @@ void CSkinnedMesh::buildAllLocalAnimatedMatrices() // --- joint->LocalAnimatedMatrix *= joint->Animatedrotation.getMatrix() --- f32 *m1 = joint->LocalAnimatedMatrix.pointer(); core::vector3df &Pos = joint->Animatedposition; - m1[0] += Pos.X*m1[3]; - m1[1] += Pos.Y*m1[3]; - m1[2] += Pos.Z*m1[3]; - m1[4] += Pos.X*m1[7]; - m1[5] += Pos.Y*m1[7]; - m1[6] += Pos.Z*m1[7]; - m1[8] += Pos.X*m1[11]; - m1[9] += Pos.Y*m1[11]; - m1[10] += Pos.Z*m1[11]; - m1[12] += Pos.X*m1[15]; - m1[13] += Pos.Y*m1[15]; - m1[14] += Pos.Z*m1[15]; + m1[0] += Pos.X * m1[3]; + m1[1] += Pos.Y * m1[3]; + m1[2] += Pos.Z * m1[3]; + m1[4] += Pos.X * m1[7]; + m1[5] += Pos.Y * m1[7]; + m1[6] += Pos.Z * m1[7]; + m1[8] += Pos.X * m1[11]; + m1[9] += Pos.Y * m1[11]; + m1[10] += Pos.Z * m1[11]; + m1[12] += Pos.X * m1[15]; + m1[13] += Pos.Y * m1[15]; + m1[14] += Pos.Z * m1[15]; // ----------------------------------- - if (joint->ScaleKeys.size()) - { + if (joint->ScaleKeys.size()) { /* core::matrix4 scaleMatrix; scaleMatrix.setScale(joint->Animatedscale); @@ -269,7 +248,7 @@ void CSkinnedMesh::buildAllLocalAnimatedMatrices() */ // -------- joint->LocalAnimatedMatrix *= scaleMatrix ----------------- - core::matrix4& mat = joint->LocalAnimatedMatrix; + core::matrix4 &mat = joint->LocalAnimatedMatrix; mat[0] *= joint->Animatedscale.X; mat[1] *= joint->Animatedscale.X; mat[2] *= joint->Animatedscale.X; @@ -284,26 +263,20 @@ void CSkinnedMesh::buildAllLocalAnimatedMatrices() mat[11] *= joint->Animatedscale.Z; // ----------------------------------- } - } - else - { - joint->LocalAnimatedMatrix=joint->LocalMatrix; + } else { + joint->LocalAnimatedMatrix = joint->LocalMatrix; } } - SkinnedLastFrame=false; + SkinnedLastFrame = false; } - void CSkinnedMesh::buildAllGlobalAnimatedMatrices(SJoint *joint, SJoint *parentJoint) { - if (!joint) - { - for (u32 i=0; iGlobalSkinningSpace) joint->GlobalAnimatedMatrix = joint->LocalAnimatedMatrix; @@ -311,193 +284,159 @@ void CSkinnedMesh::buildAllGlobalAnimatedMatrices(SJoint *joint, SJoint *parentJ joint->GlobalAnimatedMatrix = parentJoint->GlobalAnimatedMatrix * joint->LocalAnimatedMatrix; } - for (u32 j=0; jChildren.size(); ++j) + for (u32 j = 0; j < joint->Children.size(); ++j) buildAllGlobalAnimatedMatrices(joint->Children[j], joint); } - void CSkinnedMesh::getFrameData(f32 frame, SJoint *joint, - core::vector3df &position, s32 &positionHint, - core::vector3df &scale, s32 &scaleHint, - core::quaternion &rotation, s32 &rotationHint) + core::vector3df &position, s32 &positionHint, + core::vector3df &scale, s32 &scaleHint, + core::quaternion &rotation, s32 &rotationHint) { s32 foundPositionIndex = -1; s32 foundScaleIndex = -1; s32 foundRotationIndex = -1; - if (joint->UseAnimationFrom) - { - const core::array &PositionKeys=joint->UseAnimationFrom->PositionKeys; - const core::array &ScaleKeys=joint->UseAnimationFrom->ScaleKeys; - const core::array &RotationKeys=joint->UseAnimationFrom->RotationKeys; + if (joint->UseAnimationFrom) { + const core::array &PositionKeys = joint->UseAnimationFrom->PositionKeys; + const core::array &ScaleKeys = joint->UseAnimationFrom->ScaleKeys; + const core::array &RotationKeys = joint->UseAnimationFrom->RotationKeys; - if (PositionKeys.size()) - { + if (PositionKeys.size()) { foundPositionIndex = -1; - //Test the Hints... - if (positionHint>=0 && (u32)positionHint < PositionKeys.size()) - { - //check this hint - if (positionHint>0 && PositionKeys[positionHint].frame>=frame && PositionKeys[positionHint-1].frame=frame && - PositionKeys[positionHint+0].frame= 0 && (u32)positionHint < PositionKeys.size()) { + // check this hint + if (positionHint > 0 && PositionKeys[positionHint].frame >= frame && PositionKeys[positionHint - 1].frame < frame) + foundPositionIndex = positionHint; + else if (positionHint + 1 < (s32)PositionKeys.size()) { + // check the next index + if (PositionKeys[positionHint + 1].frame >= frame && + PositionKeys[positionHint + 0].frame < frame) { positionHint++; - foundPositionIndex=positionHint; + foundPositionIndex = positionHint; } } } - //The hint test failed, do a full scan... - if (foundPositionIndex==-1) - { - for (u32 i=0; i= frame) //Keys should to be sorted by frame + // The hint test failed, do a full scan... + if (foundPositionIndex == -1) { + for (u32 i = 0; i < PositionKeys.size(); ++i) { + if (PositionKeys[i].frame >= frame) // Keys should to be sorted by frame { - foundPositionIndex=i; - positionHint=i; + foundPositionIndex = i; + positionHint = i; break; } } } - //Do interpolation... - if (foundPositionIndex!=-1) - { - if (InterpolationMode==EIM_CONSTANT || foundPositionIndex==0) - { + // Do interpolation... + if (foundPositionIndex != -1) { + if (InterpolationMode == EIM_CONSTANT || foundPositionIndex == 0) { position = PositionKeys[foundPositionIndex].position; - } - else if (InterpolationMode==EIM_LINEAR) - { - const SPositionKey& KeyA = PositionKeys[foundPositionIndex]; - const SPositionKey& KeyB = PositionKeys[foundPositionIndex-1]; + } else if (InterpolationMode == EIM_LINEAR) { + const SPositionKey &KeyA = PositionKeys[foundPositionIndex]; + const SPositionKey &KeyB = PositionKeys[foundPositionIndex - 1]; const f32 fd1 = frame - KeyA.frame; const f32 fd2 = KeyB.frame - frame; - position = ((KeyB.position-KeyA.position)/(fd1+fd2))*fd1 + KeyA.position; + position = ((KeyB.position - KeyA.position) / (fd1 + fd2)) * fd1 + KeyA.position; } } } //------------------------------------------------------------ - if (ScaleKeys.size()) - { + if (ScaleKeys.size()) { foundScaleIndex = -1; - //Test the Hints... - if (scaleHint>=0 && (u32)scaleHint < ScaleKeys.size()) - { - //check this hint - if (scaleHint>0 && ScaleKeys[scaleHint].frame>=frame && ScaleKeys[scaleHint-1].frame=frame && - ScaleKeys[scaleHint+0].frame= 0 && (u32)scaleHint < ScaleKeys.size()) { + // check this hint + if (scaleHint > 0 && ScaleKeys[scaleHint].frame >= frame && ScaleKeys[scaleHint - 1].frame < frame) + foundScaleIndex = scaleHint; + else if (scaleHint + 1 < (s32)ScaleKeys.size()) { + // check the next index + if (ScaleKeys[scaleHint + 1].frame >= frame && + ScaleKeys[scaleHint + 0].frame < frame) { scaleHint++; - foundScaleIndex=scaleHint; + foundScaleIndex = scaleHint; } } } - - //The hint test failed, do a full scan... - if (foundScaleIndex==-1) - { - for (u32 i=0; i= frame) //Keys should to be sorted by frame + // The hint test failed, do a full scan... + if (foundScaleIndex == -1) { + for (u32 i = 0; i < ScaleKeys.size(); ++i) { + if (ScaleKeys[i].frame >= frame) // Keys should to be sorted by frame { - foundScaleIndex=i; - scaleHint=i; + foundScaleIndex = i; + scaleHint = i; break; } } } - //Do interpolation... - if (foundScaleIndex!=-1) - { - if (InterpolationMode==EIM_CONSTANT || foundScaleIndex==0) - { + // Do interpolation... + if (foundScaleIndex != -1) { + if (InterpolationMode == EIM_CONSTANT || foundScaleIndex == 0) { scale = ScaleKeys[foundScaleIndex].scale; - } - else if (InterpolationMode==EIM_LINEAR) - { - const SScaleKey& KeyA = ScaleKeys[foundScaleIndex]; - const SScaleKey& KeyB = ScaleKeys[foundScaleIndex-1]; + } else if (InterpolationMode == EIM_LINEAR) { + const SScaleKey &KeyA = ScaleKeys[foundScaleIndex]; + const SScaleKey &KeyB = ScaleKeys[foundScaleIndex - 1]; const f32 fd1 = frame - KeyA.frame; const f32 fd2 = KeyB.frame - frame; - scale = ((KeyB.scale-KeyA.scale)/(fd1+fd2))*fd1 + KeyA.scale; + scale = ((KeyB.scale - KeyA.scale) / (fd1 + fd2)) * fd1 + KeyA.scale; } } } //------------------------------------------------------------- - if (RotationKeys.size()) - { + if (RotationKeys.size()) { foundRotationIndex = -1; - //Test the Hints... - if (rotationHint>=0 && (u32)rotationHint < RotationKeys.size()) - { - //check this hint - if (rotationHint>0 && RotationKeys[rotationHint].frame>=frame && RotationKeys[rotationHint-1].frame=frame && - RotationKeys[rotationHint+0].frame= 0 && (u32)rotationHint < RotationKeys.size()) { + // check this hint + if (rotationHint > 0 && RotationKeys[rotationHint].frame >= frame && RotationKeys[rotationHint - 1].frame < frame) + foundRotationIndex = rotationHint; + else if (rotationHint + 1 < (s32)RotationKeys.size()) { + // check the next index + if (RotationKeys[rotationHint + 1].frame >= frame && + RotationKeys[rotationHint + 0].frame < frame) { rotationHint++; - foundRotationIndex=rotationHint; + foundRotationIndex = rotationHint; } } } - - //The hint test failed, do a full scan... - if (foundRotationIndex==-1) - { - for (u32 i=0; i= frame) //Keys should be sorted by frame + // The hint test failed, do a full scan... + if (foundRotationIndex == -1) { + for (u32 i = 0; i < RotationKeys.size(); ++i) { + if (RotationKeys[i].frame >= frame) // Keys should be sorted by frame { - foundRotationIndex=i; - rotationHint=i; + foundRotationIndex = i; + rotationHint = i; break; } } } - //Do interpolation... - if (foundRotationIndex!=-1) - { - if (InterpolationMode==EIM_CONSTANT || foundRotationIndex==0) - { + // Do interpolation... + if (foundRotationIndex != -1) { + if (InterpolationMode == EIM_CONSTANT || foundRotationIndex == 0) { rotation = RotationKeys[foundRotationIndex].rotation; - } - else if (InterpolationMode==EIM_LINEAR) - { - const SRotationKey& KeyA = RotationKeys[foundRotationIndex]; - const SRotationKey& KeyB = RotationKeys[foundRotationIndex-1]; + } else if (InterpolationMode == EIM_LINEAR) { + const SRotationKey &KeyA = RotationKeys[foundRotationIndex]; + const SRotationKey &KeyB = RotationKeys[foundRotationIndex - 1]; const f32 fd1 = frame - KeyA.frame; const f32 fd2 = KeyB.frame - frame; - const f32 t = fd1/(fd1+fd2); + const f32 t = fd1 / (fd1 + fd2); /* f32 t = 0; @@ -527,54 +466,48 @@ void CSkinnedMesh::skinMesh() buildAllGlobalAnimatedMatrices(); //----------------- - SkinnedLastFrame=true; - if (!HardwareSkinning) - { - //Software skin.... + SkinnedLastFrame = true; + if (!HardwareSkinning) { + // Software skin.... u32 i; - //rigid animation - for (i=0; iAttachedMeshes.size(); ++j) - { - SSkinMeshBuffer* Buffer=(*SkinningBuffers)[ AllJoints[i]->AttachedMeshes[j] ]; - Buffer->Transformation=AllJoints[i]->GlobalAnimatedMatrix; + // rigid animation + for (i = 0; i < AllJoints.size(); ++i) { + for (u32 j = 0; j < AllJoints[i]->AttachedMeshes.size(); ++j) { + SSkinMeshBuffer *Buffer = (*SkinningBuffers)[AllJoints[i]->AttachedMeshes[j]]; + Buffer->Transformation = AllJoints[i]->GlobalAnimatedMatrix; } } - //clear skinning helper array - for (i=0; isize(); ++i) + for (i = 0; i < SkinningBuffers->size(); ++i) (*SkinningBuffers)[i]->setDirty(EBT_VERTEX); } updateBoundingBox(); } - void CSkinnedMesh::skinJoint(SJoint *joint, SJoint *parentJoint) { - if (joint->Weights.size()) - { - //Find this joints pull on vertices... + if (joint->Weights.size()) { + // Find this joints pull on vertices... core::matrix4 jointVertexPull(core::matrix4::EM4CONST_NOTHING); jointVertexPull.setbyproduct(joint->GlobalAnimatedMatrix, joint->GlobalInversedMatrix); core::vector3df thisVertexMove, thisNormalMove; - core::array &buffersUsed=*SkinningBuffers; + core::array &buffersUsed = *SkinningBuffers; - //Skin Vertices Positions and Normals... - for (u32 i=0; iWeights.size(); ++i) - { - SWeight& weight = joint->Weights[i]; + // Skin Vertices Positions and Normals... + for (u32 i = 0; i < joint->Weights.size(); ++i) { + SWeight &weight = joint->Weights[i]; // Pull this vertex... jointVertexPull.transformVect(thisVertexMove, weight.StaticPos); @@ -582,8 +515,7 @@ void CSkinnedMesh::skinJoint(SJoint *joint, SJoint *parentJoint) if (AnimateNormals) jointVertexPull.rotateVect(thisNormalMove, weight.StaticNormal); - if (! (*(weight.Moved)) ) - { + if (!(*(weight.Moved))) { *(weight.Moved) = true; buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Pos = thisVertexMove * weight.strength; @@ -592,9 +524,7 @@ void CSkinnedMesh::skinJoint(SJoint *joint, SJoint *parentJoint) buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Normal = thisNormalMove * weight.strength; //*(weight._Pos) = thisVertexMove * weight.strength; - } - else - { + } else { buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Pos += thisVertexMove * weight.strength; if (AnimateNormals) @@ -607,18 +537,16 @@ void CSkinnedMesh::skinJoint(SJoint *joint, SJoint *parentJoint) } } - //Skin all children - for (u32 j=0; jChildren.size(); ++j) + // Skin all children + for (u32 j = 0; j < joint->Children.size(); ++j) skinJoint(joint->Children[j], joint); } - E_ANIMATED_MESH_TYPE CSkinnedMesh::getMeshType() const { return EAMT_SKINNED; } - //! Gets joint count. u32 CSkinnedMesh::getJointCount() const { @@ -626,7 +554,8 @@ u32 CSkinnedMesh::getJointCount() const } //! Gets the name of a joint. -const std::optional &CSkinnedMesh::getJointName(u32 number) const { +const std::optional &CSkinnedMesh::getJointName(u32 number) const +{ if (number >= getJointCount()) { static const std::optional nullopt; return nullopt; @@ -634,12 +563,10 @@ const std::optional &CSkinnedMesh::getJointName(u32 number) const { return AllJoints[number]->Name; } - //! Gets a joint number from its name std::optional CSkinnedMesh::getJointNumber(const std::string &name) const { - for (u32 i=0; iName == name) return i; } @@ -647,16 +574,14 @@ std::optional CSkinnedMesh::getJointNumber(const std::string &name) const return std::nullopt; } - //! returns amount of mesh buffers. u32 CSkinnedMesh::getMeshBufferCount() const { return LocalBuffers.size(); } - //! returns pointer to a mesh buffer -IMeshBuffer* CSkinnedMesh::getMeshBuffer(u32 nr) const +IMeshBuffer *CSkinnedMesh::getMeshBuffer(u32 nr) const { if (nr < LocalBuffers.size()) return LocalBuffers[nr]; @@ -664,74 +589,63 @@ IMeshBuffer* CSkinnedMesh::getMeshBuffer(u32 nr) const return 0; } - //! Returns pointer to a mesh buffer which fits a material -IMeshBuffer* CSkinnedMesh::getMeshBuffer(const video::SMaterial &material) const +IMeshBuffer *CSkinnedMesh::getMeshBuffer(const video::SMaterial &material) const { - for (u32 i=0; igetMaterial() == material) return LocalBuffers[i]; } return 0; } - //! returns an axis aligned bounding box -const core::aabbox3d& CSkinnedMesh::getBoundingBox() const +const core::aabbox3d &CSkinnedMesh::getBoundingBox() const { return BoundingBox; } - //! set user axis aligned bounding box -void CSkinnedMesh::setBoundingBox( const core::aabbox3df& box) +void CSkinnedMesh::setBoundingBox(const core::aabbox3df &box) { BoundingBox = box; } - //! set the hardware mapping hint, for driver void CSkinnedMesh::setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer) { - for (u32 i=0; isetHardwareMappingHint(newMappingHint, buffer); } - //! flags the meshbuffer as changed, reloads hardware buffers void CSkinnedMesh::setDirty(E_BUFFER_TYPE buffer) { - for (u32 i=0; isetDirty(buffer); } - //! uses animation from another mesh bool CSkinnedMesh::useAnimationFrom(const ISkinnedMesh *mesh) { - bool unmatched=false; + bool unmatched = false; - for(u32 i=0;iUseAnimationFrom=0; + for (u32 i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + joint->UseAnimationFrom = 0; - if (joint->Name=="") - unmatched=true; - else - { - for(u32 j=0;jgetAllJoints().size();++j) - { - SJoint *otherJoint=mesh->getAllJoints()[j]; - if (joint->Name==otherJoint->Name) - { - joint->UseAnimationFrom=otherJoint; + if (joint->Name == "") + unmatched = true; + else { + for (u32 j = 0; j < mesh->getAllJoints().size(); ++j) { + SJoint *otherJoint = mesh->getAllJoints()[j]; + if (joint->Name == otherJoint->Name) { + joint->UseAnimationFrom = otherJoint; } } if (!joint->UseAnimationFrom) - unmatched=true; + unmatched = true; } } @@ -740,57 +654,47 @@ bool CSkinnedMesh::useAnimationFrom(const ISkinnedMesh *mesh) return !unmatched; } - -//!Update Normals when Animating -//!False= Don't animate them, faster -//!True= Update normals (default) +//! Update Normals when Animating +//! False= Don't animate them, faster +//! True= Update normals (default) void CSkinnedMesh::updateNormalsWhenAnimating(bool on) { AnimateNormals = on; } - -//!Sets Interpolation Mode +//! Sets Interpolation Mode void CSkinnedMesh::setInterpolationMode(E_INTERPOLATION_MODE mode) { InterpolationMode = mode; } - -core::array &CSkinnedMesh::getMeshBuffers() +core::array &CSkinnedMesh::getMeshBuffers() { return LocalBuffers; } - -core::array &CSkinnedMesh::getAllJoints() +core::array &CSkinnedMesh::getAllJoints() { return AllJoints; } - -const core::array &CSkinnedMesh::getAllJoints() const +const core::array &CSkinnedMesh::getAllJoints() const { return AllJoints; } - //! (This feature is not implemented in irrlicht yet) bool CSkinnedMesh::setHardwareSkinning(bool on) { - if (HardwareSkinning!=on) - { - if (on) - { + if (HardwareSkinning != on) { + if (on) { - //set mesh to static pose... - for (u32 i=0; iWeights.size(); ++j) - { - const u16 buffer_id=joint->Weights[j].buffer_id; - const u32 vertex_id=joint->Weights[j].vertex_id; + // set mesh to static pose... + for (u32 i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + for (u32 j = 0; j < joint->Weights.size(); ++j) { + const u16 buffer_id = joint->Weights[j].buffer_id; + const u32 vertex_id = joint->Weights[j].vertex_id; LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos = joint->Weights[j].StaticPos; LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal = joint->Weights[j].StaticNormal; LocalBuffers[buffer_id]->boundingBoxNeedsRecalculated(); @@ -798,21 +702,19 @@ bool CSkinnedMesh::setHardwareSkinning(bool on) } } - HardwareSkinning=on; + HardwareSkinning = on; } return HardwareSkinning; } void CSkinnedMesh::refreshJointCache() { - //copy cache from the mesh... - for (u32 i=0; iWeights.size(); ++j) - { - const u16 buffer_id=joint->Weights[j].buffer_id; - const u32 vertex_id=joint->Weights[j].vertex_id; + // copy cache from the mesh... + for (u32 i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + for (u32 j = 0; j < joint->Weights.size(); ++j) { + const u16 buffer_id = joint->Weights[j].buffer_id; + const u32 vertex_id = joint->Weights[j].vertex_id; joint->Weights[j].StaticPos = LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos; joint->Weights[j].StaticNormal = LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal; } @@ -821,14 +723,12 @@ void CSkinnedMesh::refreshJointCache() void CSkinnedMesh::resetAnimation() { - //copy from the cache to the mesh... - for (u32 i=0; iWeights.size(); ++j) - { - const u16 buffer_id=joint->Weights[j].buffer_id; - const u32 vertex_id=joint->Weights[j].vertex_id; + // copy from the cache to the mesh... + for (u32 i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + for (u32 j = 0; j < joint->Weights.size(); ++j) { + const u16 buffer_id = joint->Weights[j].buffer_id; + const u32 vertex_id = joint->Weights[j].vertex_id; LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos = joint->Weights[j].StaticPos; LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal = joint->Weights[j].StaticNormal; } @@ -837,16 +737,15 @@ void CSkinnedMesh::resetAnimation() LastAnimatedFrame = -1; } -void CSkinnedMesh::calculateGlobalMatrices(SJoint *joint,SJoint *parentJoint) +void CSkinnedMesh::calculateGlobalMatrices(SJoint *joint, SJoint *parentJoint) { if (!joint && parentJoint) // bit of protection from endless loops return; - //Go through the root bones - if (!joint) - { - for (u32 i=0; iGlobalMatrix = parentJoint->GlobalMatrix * joint->LocalMatrix; - joint->LocalAnimatedMatrix=joint->LocalMatrix; - joint->GlobalAnimatedMatrix=joint->GlobalMatrix; + joint->LocalAnimatedMatrix = joint->LocalMatrix; + joint->GlobalAnimatedMatrix = joint->GlobalMatrix; - if (joint->GlobalInversedMatrix.isIdentity())//might be pre calculated + if (joint->GlobalInversedMatrix.isIdentity()) // might be pre calculated { joint->GlobalInversedMatrix = joint->GlobalMatrix; joint->GlobalInversedMatrix.makeInverse(); // slow } - for (u32 j=0; jChildren.size(); ++j) - calculateGlobalMatrices(joint->Children[j],joint); - SkinnedLastFrame=false; + for (u32 j = 0; j < joint->Children.size(); ++j) + calculateGlobalMatrices(joint->Children[j], joint); + SkinnedLastFrame = false; } - void CSkinnedMesh::checkForAnimation() { - u32 i,j; - //Check for animation... + u32 i, j; + // Check for animation... HasAnimation = false; - for(i=0;iUseAnimationFrom) - { + for (i = 0; i < AllJoints.size(); ++i) { + if (AllJoints[i]->UseAnimationFrom) { if (AllJoints[i]->UseAnimationFrom->PositionKeys.size() || - AllJoints[i]->UseAnimationFrom->ScaleKeys.size() || - AllJoints[i]->UseAnimationFrom->RotationKeys.size() ) - { + AllJoints[i]->UseAnimationFrom->ScaleKeys.size() || + AllJoints[i]->UseAnimationFrom->RotationKeys.size()) { HasAnimation = true; } } } - //meshes with weights, are still counted as animated for ragdolls, etc - if (!HasAnimation) - { - for(i=0;iWeights.size()) HasAnimation = true; } } - if (HasAnimation) - { + if (HasAnimation) { //--- Find the length of the animation --- - EndFrame=0; - for(i=0;iUseAnimationFrom) - { + EndFrame = 0; + for (i = 0; i < AllJoints.size(); ++i) { + if (AllJoints[i]->UseAnimationFrom) { if (AllJoints[i]->UseAnimationFrom->PositionKeys.size()) if (AllJoints[i]->UseAnimationFrom->PositionKeys.getLast().frame > EndFrame) - EndFrame=AllJoints[i]->UseAnimationFrom->PositionKeys.getLast().frame; + EndFrame = AllJoints[i]->UseAnimationFrom->PositionKeys.getLast().frame; if (AllJoints[i]->UseAnimationFrom->ScaleKeys.size()) if (AllJoints[i]->UseAnimationFrom->ScaleKeys.getLast().frame > EndFrame) - EndFrame=AllJoints[i]->UseAnimationFrom->ScaleKeys.getLast().frame; + EndFrame = AllJoints[i]->UseAnimationFrom->ScaleKeys.getLast().frame; if (AllJoints[i]->UseAnimationFrom->RotationKeys.size()) if (AllJoints[i]->UseAnimationFrom->RotationKeys.getLast().frame > EndFrame) - EndFrame=AllJoints[i]->UseAnimationFrom->RotationKeys.getLast().frame; + EndFrame = AllJoints[i]->UseAnimationFrom->RotationKeys.getLast().frame; } } } - if (HasAnimation && !PreparedForSkinning) - { - PreparedForSkinning=true; + if (HasAnimation && !PreparedForSkinning) { + PreparedForSkinning = true; - //check for bugs: - for(i=0; i < AllJoints.size(); ++i) - { + // check for bugs: + for (i = 0; i < AllJoints.size(); ++i) { SJoint *joint = AllJoints[i]; - for (j=0; jWeights.size(); ++j) - { - const u16 buffer_id=joint->Weights[j].buffer_id; - const u32 vertex_id=joint->Weights[j].vertex_id; + for (j = 0; j < joint->Weights.size(); ++j) { + const u16 buffer_id = joint->Weights[j].buffer_id; + const u32 vertex_id = joint->Weights[j].vertex_id; - //check for invalid ids - if (buffer_id>=LocalBuffers.size()) - { + // check for invalid ids + if (buffer_id >= LocalBuffers.size()) { os::Printer::log("Skinned Mesh: Weight buffer id too large", ELL_WARNING); - joint->Weights[j].buffer_id = joint->Weights[j].vertex_id =0; - } - else if (vertex_id>=LocalBuffers[buffer_id]->getVertexCount()) - { + joint->Weights[j].buffer_id = joint->Weights[j].vertex_id = 0; + } else if (vertex_id >= LocalBuffers[buffer_id]->getVertexCount()) { os::Printer::log("Skinned Mesh: Weight vertex id too large", ELL_WARNING); - joint->Weights[j].buffer_id = joint->Weights[j].vertex_id =0; + joint->Weights[j].buffer_id = joint->Weights[j].vertex_id = 0; } } } - //An array used in skinning + // An array used in skinning - for (i=0; iWeights.size(); ++j) - { - const u16 buffer_id=joint->Weights[j].buffer_id; - const u32 vertex_id=joint->Weights[j].vertex_id; + for (j = 0; j < joint->Weights.size(); ++j) { + const u16 buffer_id = joint->Weights[j].buffer_id; + const u32 vertex_id = joint->Weights[j].vertex_id; - joint->Weights[j].Moved = &Vertices_Moved[buffer_id] [vertex_id]; + joint->Weights[j].Moved = &Vertices_Moved[buffer_id][vertex_id]; joint->Weights[j].StaticPos = LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos; joint->Weights[j].StaticNormal = LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal; - //joint->Weights[j]._Pos=&Buffers[buffer_id]->getVertex(vertex_id)->Pos; + // joint->Weights[j]._Pos=&Buffers[buffer_id]->getVertex(vertex_id)->Pos; } } // normalize weights normalizeWeights(); } - SkinnedLastFrame=false; + SkinnedLastFrame = false; } //! called by loader after populating with mesh and bone data @@ -985,61 +867,50 @@ void CSkinnedMesh::finalize() u32 i; // Make sure we recalc the next frame - LastAnimatedFrame=-1; - SkinnedLastFrame=false; + LastAnimatedFrame = -1; + SkinnedLastFrame = false; - //calculate bounding box - for (i=0; irecalculateBoundingBox(); } - if (AllJoints.size() || RootJoints.size()) - { + if (AllJoints.size() || RootJoints.size()) { // populate AllJoints or RootJoints, depending on which is empty - if (!RootJoints.size()) - { + if (!RootJoints.size()) { - for(u32 CheckingIdx=0; CheckingIdx < AllJoints.size(); ++CheckingIdx) - { + for (u32 CheckingIdx = 0; CheckingIdx < AllJoints.size(); ++CheckingIdx) { - bool foundParent=false; - for(i=0; i < AllJoints.size(); ++i) - { - for(u32 n=0; n < AllJoints[i]->Children.size(); ++n) - { + bool foundParent = false; + for (i = 0; i < AllJoints.size(); ++i) { + for (u32 n = 0; n < AllJoints[i]->Children.size(); ++n) { if (AllJoints[i]->Children[n] == AllJoints[CheckingIdx]) - foundParent=true; + foundParent = true; } } if (!foundParent) RootJoints.push_back(AllJoints[CheckingIdx]); } - } - else - { - AllJoints=RootJoints; + } else { + AllJoints = RootJoints; } } - for(i=0; i < AllJoints.size(); ++i) - { - AllJoints[i]->UseAnimationFrom=AllJoints[i]; + for (i = 0; i < AllJoints.size(); ++i) { + AllJoints[i]->UseAnimationFrom = AllJoints[i]; } - //Set array sizes... + // Set array sizes... - for (i=0; i() ); + for (i = 0; i < LocalBuffers.size(); ++i) { + Vertices_Moved.push_back(core::array()); Vertices_Moved[i].set_used(LocalBuffers[i]->getVertexCount()); } checkForAnimation(); - if (HasAnimation) - { + if (HasAnimation) { irr::u32 redundantPosKeys = 0; irr::u32 unorderedPosKeys = 0; irr::u32 redundantScaleKeys = 0; @@ -1048,9 +919,8 @@ void CSkinnedMesh::finalize() irr::u32 unorderedRotationKeys = 0; //--- optimize and check keyframes --- - for(i=0;i &PositionKeys =AllJoints[i]->PositionKeys; + for (i = 0; i < AllJoints.size(); ++i) { + core::array &PositionKeys = AllJoints[i]->PositionKeys; core::array &ScaleKeys = AllJoints[i]->ScaleKeys; core::array &RotationKeys = AllJoints[i]->RotationKeys; @@ -1063,123 +933,104 @@ void CSkinnedMesh::finalize() redundantRotationKeys += dropMiddleKeys(RotationKeys, identicalRotation); unorderedRotationKeys += dropBadKeys(RotationKeys); - //Fill empty keyframe areas - if (PositionKeys.size()) - { + // Fill empty keyframe areas + if (PositionKeys.size()) { SPositionKey *Key; - Key=&PositionKeys[0];//getFirst - if (Key->frame!=0) - { + Key = &PositionKeys[0]; // getFirst + if (Key->frame != 0) { PositionKeys.push_front(*Key); - Key=&PositionKeys[0];//getFirst - Key->frame=0; + Key = &PositionKeys[0]; // getFirst + Key->frame = 0; } - Key=&PositionKeys.getLast(); - if (Key->frame!=EndFrame) - { + Key = &PositionKeys.getLast(); + if (Key->frame != EndFrame) { PositionKeys.push_back(*Key); - Key=&PositionKeys.getLast(); - Key->frame=EndFrame; + Key = &PositionKeys.getLast(); + Key->frame = EndFrame; } } - if (ScaleKeys.size()) - { + if (ScaleKeys.size()) { SScaleKey *Key; - Key=&ScaleKeys[0];//getFirst - if (Key->frame!=0) - { + Key = &ScaleKeys[0]; // getFirst + if (Key->frame != 0) { ScaleKeys.push_front(*Key); - Key=&ScaleKeys[0];//getFirst - Key->frame=0; + Key = &ScaleKeys[0]; // getFirst + Key->frame = 0; } - Key=&ScaleKeys.getLast(); - if (Key->frame!=EndFrame) - { + Key = &ScaleKeys.getLast(); + if (Key->frame != EndFrame) { ScaleKeys.push_back(*Key); - Key=&ScaleKeys.getLast(); - Key->frame=EndFrame; + Key = &ScaleKeys.getLast(); + Key->frame = EndFrame; } } - if (RotationKeys.size()) - { + if (RotationKeys.size()) { SRotationKey *Key; - Key=&RotationKeys[0];//getFirst - if (Key->frame!=0) - { + Key = &RotationKeys[0]; // getFirst + if (Key->frame != 0) { RotationKeys.push_front(*Key); - Key=&RotationKeys[0];//getFirst - Key->frame=0; + Key = &RotationKeys[0]; // getFirst + Key->frame = 0; } - Key=&RotationKeys.getLast(); - if (Key->frame!=EndFrame) - { + Key = &RotationKeys.getLast(); + if (Key->frame != EndFrame) { RotationKeys.push_back(*Key); - Key=&RotationKeys.getLast(); - Key->frame=EndFrame; + Key = &RotationKeys.getLast(); + Key->frame = EndFrame; } } } - if ( redundantPosKeys > 0 ) - { + if (redundantPosKeys > 0) { os::Printer::log("Skinned Mesh - redundant position frames kicked", core::stringc(redundantPosKeys).c_str(), ELL_DEBUG); } - if ( unorderedPosKeys > 0 ) - { + if (unorderedPosKeys > 0) { irr::os::Printer::log("Skinned Mesh - unsorted position frames kicked", irr::core::stringc(unorderedPosKeys).c_str(), irr::ELL_DEBUG); } - if ( redundantScaleKeys > 0 ) - { + if (redundantScaleKeys > 0) { os::Printer::log("Skinned Mesh - redundant scale frames kicked", core::stringc(redundantScaleKeys).c_str(), ELL_DEBUG); } - if ( unorderedScaleKeys > 0 ) - { + if (unorderedScaleKeys > 0) { irr::os::Printer::log("Skinned Mesh - unsorted scale frames kicked", irr::core::stringc(unorderedScaleKeys).c_str(), irr::ELL_DEBUG); } - if ( redundantRotationKeys > 0 ) - { + if (redundantRotationKeys > 0) { os::Printer::log("Skinned Mesh - redundant rotation frames kicked", core::stringc(redundantRotationKeys).c_str(), ELL_DEBUG); } - if ( unorderedRotationKeys > 0 ) - { + if (unorderedRotationKeys > 0) { irr::os::Printer::log("Skinned Mesh - unsorted rotation frames kicked", irr::core::stringc(unorderedRotationKeys).c_str(), irr::ELL_DEBUG); } } - //Needed for animation and skinning... + // Needed for animation and skinning... - calculateGlobalMatrices(0,0); + calculateGlobalMatrices(0, 0); - //animateMesh(0, 1); - //buildAllLocalAnimatedMatrices(); - //buildAllGlobalAnimatedMatrices(); + // animateMesh(0, 1); + // buildAllLocalAnimatedMatrices(); + // buildAllGlobalAnimatedMatrices(); - //rigid animation for non animated meshes - for (i=0; iAttachedMeshes.size(); ++j) - { - SSkinMeshBuffer* Buffer=(*SkinningBuffers)[ AllJoints[i]->AttachedMeshes[j] ]; - Buffer->Transformation=AllJoints[i]->GlobalAnimatedMatrix; + // rigid animation for non animated meshes + for (i = 0; i < AllJoints.size(); ++i) { + for (u32 j = 0; j < AllJoints[i]->AttachedMeshes.size(); ++j) { + SSkinMeshBuffer *Buffer = (*SkinningBuffers)[AllJoints[i]->AttachedMeshes[j]]; + Buffer->Transformation = AllJoints[i]->GlobalAnimatedMatrix; } } - //calculate bounding box + // calculate bounding box if (LocalBuffers.empty()) - BoundingBox.reset(0,0,0); - else - { + BoundingBox.reset(0, 0, 0); + else { irr::core::aabbox3df bb(LocalBuffers[0]->BoundingBox); LocalBuffers[0]->Transformation.transformBoxEx(bb); BoundingBox.reset(bb); - for (u32 j=1; jBoundingBox; LocalBuffers[j]->Transformation.transformBoxEx(bb); @@ -1188,19 +1039,16 @@ void CSkinnedMesh::finalize() } } - void CSkinnedMesh::updateBoundingBox(void) { - if(!SkinningBuffers) + if (!SkinningBuffers) return; - core::array & buffer = *SkinningBuffers; - BoundingBox.reset(0,0,0); + core::array &buffer = *SkinningBuffers; + BoundingBox.reset(0, 0, 0); - if (!buffer.empty()) - { - for (u32 j=0; jrecalculateBoundingBox(); core::aabbox3df bb = buffer[j]->BoundingBox; buffer[j]->Transformation.transformBoxEx(bb); @@ -1210,34 +1058,28 @@ void CSkinnedMesh::updateBoundingBox(void) } } - scene::SSkinMeshBuffer *CSkinnedMesh::addMeshBuffer() { - scene::SSkinMeshBuffer *buffer=new scene::SSkinMeshBuffer(); + scene::SSkinMeshBuffer *buffer = new scene::SSkinMeshBuffer(); LocalBuffers.push_back(buffer); return buffer; } - CSkinnedMesh::SJoint *CSkinnedMesh::addJoint(SJoint *parent) { - SJoint *joint=new SJoint; + SJoint *joint = new SJoint; AllJoints.push_back(joint); - if (!parent) - { - //Add root joints to array in finalize() - } - else - { - //Set parent (Be careful of the mesh loader also setting the parent) + if (!parent) { + // Add root joints to array in finalize() + } else { + // Set parent (Be careful of the mesh loader also setting the parent) parent->Children.push_back(joint); } return joint; } - CSkinnedMesh::SPositionKey *CSkinnedMesh::addPositionKey(SJoint *joint) { if (!joint) @@ -1247,7 +1089,6 @@ CSkinnedMesh::SPositionKey *CSkinnedMesh::addPositionKey(SJoint *joint) return &joint->PositionKeys.getLast(); } - CSkinnedMesh::SScaleKey *CSkinnedMesh::addScaleKey(SJoint *joint) { if (!joint) @@ -1257,7 +1098,6 @@ CSkinnedMesh::SScaleKey *CSkinnedMesh::addScaleKey(SJoint *joint) return &joint->ScaleKeys.getLast(); } - CSkinnedMesh::SRotationKey *CSkinnedMesh::addRotationKey(SJoint *joint) { if (!joint) @@ -1267,7 +1107,6 @@ CSkinnedMesh::SRotationKey *CSkinnedMesh::addRotationKey(SJoint *joint) return &joint->RotationKeys.getLast(); } - CSkinnedMesh::SWeight *CSkinnedMesh::addWeight(SJoint *joint) { if (!joint) @@ -1277,225 +1116,198 @@ CSkinnedMesh::SWeight *CSkinnedMesh::addWeight(SJoint *joint) return &joint->Weights.getLast(); } - bool CSkinnedMesh::isStatic() { return !HasAnimation; } - void CSkinnedMesh::normalizeWeights() { // note: unsure if weights ids are going to be used. // Normalise the weights on bones.... - u32 i,j; - core::array< core::array > verticesTotalWeight; + u32 i, j; + core::array> verticesTotalWeight; verticesTotalWeight.reallocate(LocalBuffers.size()); - for (i=0; i()); verticesTotalWeight[i].set_used(LocalBuffers[i]->getVertexCount()); } - for (i=0; iWeights.size(); ++j) - { - if (joint->Weights[j].strength<=0)//Check for invalid weights + for (i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + for (j = 0; j < joint->Weights.size(); ++j) { + if (joint->Weights[j].strength <= 0) // Check for invalid weights { joint->Weights.erase(j); --j; - } - else - { - verticesTotalWeight[joint->Weights[j].buffer_id] [joint->Weights[j].vertex_id] += joint->Weights[j].strength; + } else { + verticesTotalWeight[joint->Weights[j].buffer_id][joint->Weights[j].vertex_id] += joint->Weights[j].strength; } } } - for (i=0; iWeights.size(); ++j) - { - const f32 total = verticesTotalWeight[joint->Weights[j].buffer_id] [joint->Weights[j].vertex_id]; + for (i = 0; i < AllJoints.size(); ++i) { + SJoint *joint = AllJoints[i]; + for (j = 0; j < joint->Weights.size(); ++j) { + const f32 total = verticesTotalWeight[joint->Weights[j].buffer_id][joint->Weights[j].vertex_id]; if (total != 0 && total != 1) joint->Weights[j].strength /= total; } } } - -void CSkinnedMesh::recoverJointsFromMesh(core::array &jointChildSceneNodes) +void CSkinnedMesh::recoverJointsFromMesh(core::array &jointChildSceneNodes) { - for (u32 i=0; isetPosition(joint->LocalAnimatedMatrix.getTranslation()); node->setRotation(joint->LocalAnimatedMatrix.getRotationDegrees()); node->setScale(joint->LocalAnimatedMatrix.getScale()); - node->positionHint=joint->positionHint; - node->scaleHint=joint->scaleHint; - node->rotationHint=joint->rotationHint; + node->positionHint = joint->positionHint; + node->scaleHint = joint->scaleHint; + node->rotationHint = joint->rotationHint; node->updateAbsolutePosition(); } } - -void CSkinnedMesh::transferJointsToMesh(const core::array &jointChildSceneNodes) +void CSkinnedMesh::transferJointsToMesh(const core::array &jointChildSceneNodes) { - for (u32 i=0; iLocalAnimatedMatrix.setRotationDegrees(node->getRotation()); joint->LocalAnimatedMatrix.setTranslation(node->getPosition()); joint->LocalAnimatedMatrix *= core::matrix4().setScale(node->getScale()); - joint->positionHint=node->positionHint; - joint->scaleHint=node->scaleHint; - joint->rotationHint=node->rotationHint; + joint->positionHint = node->positionHint; + joint->scaleHint = node->scaleHint; + joint->rotationHint = node->rotationHint; - joint->GlobalSkinningSpace=(node->getSkinningSpace()==EBSS_GLOBAL); + joint->GlobalSkinningSpace = (node->getSkinningSpace() == EBSS_GLOBAL); } // Make sure we recalc the next frame - LastAnimatedFrame=-1; - SkinnedLastFrame=false; + LastAnimatedFrame = -1; + SkinnedLastFrame = false; } - -void CSkinnedMesh::transferOnlyJointsHintsToMesh(const core::array &jointChildSceneNodes) +void CSkinnedMesh::transferOnlyJointsHintsToMesh(const core::array &jointChildSceneNodes) { - for (u32 i=0; ipositionHint=node->positionHint; - joint->scaleHint=node->scaleHint; - joint->rotationHint=node->rotationHint; + joint->positionHint = node->positionHint; + joint->scaleHint = node->scaleHint; + joint->rotationHint = node->rotationHint; } - SkinnedLastFrame=false; + SkinnedLastFrame = false; } - -void CSkinnedMesh::addJoints(core::array &jointChildSceneNodes, - IAnimatedMeshSceneNode* node, ISceneManager* smgr) +void CSkinnedMesh::addJoints(core::array &jointChildSceneNodes, + IAnimatedMeshSceneNode *node, ISceneManager *smgr) { - //Create new joints - for (u32 i=0; iName)); } - //Match up parents - for (u32 i=0; iChildren.size(); ++n) - { - if (parentTest->Children[n]==joint) - { - parentID=j; + for (u32 j = 0; (parentID == -1) && (j < AllJoints.size()); ++j) { + if (i != j) { + const SJoint *const parentTest = AllJoints[j]; + for (u32 n = 0; n < parentTest->Children.size(); ++n) { + if (parentTest->Children[n] == joint) { + parentID = j; break; } } } } - IBoneSceneNode* bone=jointChildSceneNodes[i]; - if (parentID!=-1) + IBoneSceneNode *bone = jointChildSceneNodes[i]; + if (parentID != -1) bone->setParent(jointChildSceneNodes[parentID]); else bone->setParent(node); bone->drop(); } - SkinnedLastFrame=false; + SkinnedLastFrame = false; } - void CSkinnedMesh::convertMeshToTangents() { // now calculate tangents - for (u32 b=0; b < LocalBuffers.size(); ++b) - { - if (LocalBuffers[b]) - { + for (u32 b = 0; b < LocalBuffers.size(); ++b) { + if (LocalBuffers[b]) { LocalBuffers[b]->convertToTangents(); const s32 idxCnt = LocalBuffers[b]->getIndexCount(); - u16* idx = LocalBuffers[b]->getIndices(); - video::S3DVertexTangents* v = - (video::S3DVertexTangents*)LocalBuffers[b]->getVertices(); + u16 *idx = LocalBuffers[b]->getIndices(); + video::S3DVertexTangents *v = + (video::S3DVertexTangents *)LocalBuffers[b]->getVertices(); - for (s32 i=0; i &getBoundingBox() const override; - //! returns an axis aligned bounding box - const core::aabbox3d& getBoundingBox() const override; + //! set user axis aligned bounding box + void setBoundingBox(const core::aabbox3df &box) override; - //! set user axis aligned bounding box - void setBoundingBox( const core::aabbox3df& box) override; + //! set the hardware mapping hint, for driver + void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override; - //! set the hardware mapping hint, for driver - void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint, E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) override; + //! flags the meshbuffer as changed, reloads hardware buffers + void setDirty(E_BUFFER_TYPE buffer = EBT_VERTEX_AND_INDEX) override; - //! flags the meshbuffer as changed, reloads hardware buffers - void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) override; + //! Returns the type of the animated mesh. + E_ANIMATED_MESH_TYPE getMeshType() const override; - //! Returns the type of the animated mesh. - E_ANIMATED_MESH_TYPE getMeshType() const override; + //! Gets joint count. + u32 getJointCount() const override; - //! Gets joint count. - u32 getJointCount() const override; + //! Gets the name of a joint. + const std::optional &getJointName(u32 number) const override; - //! Gets the name of a joint. - const std::optional &getJointName(u32 number) const override; + //! Gets a joint number from its name + std::optional getJointNumber(const std::string &name) const override; - //! Gets a joint number from its name - std::optional getJointNumber(const std::string &name) const override; + //! uses animation from another mesh + bool useAnimationFrom(const ISkinnedMesh *mesh) override; - //! uses animation from another mesh - bool useAnimationFrom(const ISkinnedMesh *mesh) override; + //! Update Normals when Animating + //! False= Don't (default) + //! True = Update normals, slower + void updateNormalsWhenAnimating(bool on) override; - //! Update Normals when Animating - //! False= Don't (default) - //! True = Update normals, slower - void updateNormalsWhenAnimating(bool on) override; + //! Sets Interpolation Mode + void setInterpolationMode(E_INTERPOLATION_MODE mode) override; - //! Sets Interpolation Mode - void setInterpolationMode(E_INTERPOLATION_MODE mode) override; + //! Convertes the mesh to contain tangent information + void convertMeshToTangents() override; - //! Convertes the mesh to contain tangent information - void convertMeshToTangents() override; + //! Does the mesh have no animation + bool isStatic() override; - //! Does the mesh have no animation - bool isStatic() override; + //! (This feature is not implemented in irrlicht yet) + bool setHardwareSkinning(bool on) override; - //! (This feature is not implemented in irrlicht yet) - bool setHardwareSkinning(bool on) override; + //! Refreshes vertex data cached in joints such as positions and normals + void refreshJointCache() override; - //! Refreshes vertex data cached in joints such as positions and normals - void refreshJointCache() override; + //! Moves the mesh into static position. + void resetAnimation() override; - //! Moves the mesh into static position. - void resetAnimation() override; + // Interface for the mesh loaders (finalize should lock these functions, and they should have some prefix like loader_ + // these functions will use the needed arrays, set values, etc to help the loaders - //Interface for the mesh loaders (finalize should lock these functions, and they should have some prefix like loader_ - //these functions will use the needed arrays, set values, etc to help the loaders + //! exposed for loaders to add mesh buffers + core::array &getMeshBuffers() override; - //! exposed for loaders to add mesh buffers - core::array &getMeshBuffers() override; + //! alternative method for adding joints + core::array &getAllJoints() override; - //! alternative method for adding joints - core::array &getAllJoints() override; + //! alternative method for adding joints + const core::array &getAllJoints() const override; - //! alternative method for adding joints - const core::array &getAllJoints() const override; + //! loaders should call this after populating the mesh + void finalize() override; - //! loaders should call this after populating the mesh - void finalize() override; + //! Adds a new meshbuffer to the mesh, access it as last one + SSkinMeshBuffer *addMeshBuffer() override; - //! Adds a new meshbuffer to the mesh, access it as last one - SSkinMeshBuffer *addMeshBuffer() override; + //! Adds a new joint to the mesh, access it as last one + SJoint *addJoint(SJoint *parent = 0) override; - //! Adds a new joint to the mesh, access it as last one - SJoint *addJoint(SJoint *parent=0) override; + //! Adds a new position key to the mesh, access it as last one + SPositionKey *addPositionKey(SJoint *joint) override; + //! Adds a new rotation key to the mesh, access it as last one + SRotationKey *addRotationKey(SJoint *joint) override; + //! Adds a new scale key to the mesh, access it as last one + SScaleKey *addScaleKey(SJoint *joint) override; - //! Adds a new position key to the mesh, access it as last one - SPositionKey *addPositionKey(SJoint *joint) override; - //! Adds a new rotation key to the mesh, access it as last one - SRotationKey *addRotationKey(SJoint *joint) override; - //! Adds a new scale key to the mesh, access it as last one - SScaleKey *addScaleKey(SJoint *joint) override; + //! Adds a new weight to the mesh, access it as last one + SWeight *addWeight(SJoint *joint) override; - //! Adds a new weight to the mesh, access it as last one - SWeight *addWeight(SJoint *joint) override; + virtual void updateBoundingBox(void); - virtual void updateBoundingBox(void); + //! Recovers the joints from the mesh + void recoverJointsFromMesh(core::array &jointChildSceneNodes); - //! Recovers the joints from the mesh - void recoverJointsFromMesh(core::array &jointChildSceneNodes); + //! Tranfers the joint data to the mesh + void transferJointsToMesh(const core::array &jointChildSceneNodes); - //! Tranfers the joint data to the mesh - void transferJointsToMesh(const core::array &jointChildSceneNodes); + //! Tranfers the joint hints to the mesh + void transferOnlyJointsHintsToMesh(const core::array &jointChildSceneNodes); - //! Tranfers the joint hints to the mesh - void transferOnlyJointsHintsToMesh(const core::array &jointChildSceneNodes); - - //! Creates an array of joints from this mesh as children of node - void addJoints(core::array &jointChildSceneNodes, - IAnimatedMeshSceneNode* node, - ISceneManager* smgr); + //! Creates an array of joints from this mesh as children of node + void addJoints(core::array &jointChildSceneNodes, + IAnimatedMeshSceneNode *node, + ISceneManager *smgr); private: - void checkForAnimation(); + void checkForAnimation(); - void normalizeWeights(); + void normalizeWeights(); - void buildAllLocalAnimatedMatrices(); + void buildAllLocalAnimatedMatrices(); - void buildAllGlobalAnimatedMatrices(SJoint *Joint=0, SJoint *ParentJoint=0); + void buildAllGlobalAnimatedMatrices(SJoint *Joint = 0, SJoint *ParentJoint = 0); - void getFrameData(f32 frame, SJoint *Node, - core::vector3df &position, s32 &positionHint, - core::vector3df &scale, s32 &scaleHint, - core::quaternion &rotation, s32 &rotationHint); + void getFrameData(f32 frame, SJoint *Node, + core::vector3df &position, s32 &positionHint, + core::vector3df &scale, s32 &scaleHint, + core::quaternion &rotation, s32 &rotationHint); - void calculateGlobalMatrices(SJoint *Joint,SJoint *ParentJoint); + void calculateGlobalMatrices(SJoint *Joint, SJoint *ParentJoint); - void skinJoint(SJoint *Joint, SJoint *ParentJoint); + void skinJoint(SJoint *Joint, SJoint *ParentJoint); - void calculateTangents(core::vector3df& normal, - core::vector3df& tangent, core::vector3df& binormal, - const core::vector3df& vt1, const core::vector3df& vt2, const core::vector3df& vt3, - const core::vector2df& tc1, const core::vector2df& tc2, const core::vector2df& tc3); + void calculateTangents(core::vector3df &normal, + core::vector3df &tangent, core::vector3df &binormal, + const core::vector3df &vt1, const core::vector3df &vt2, const core::vector3df &vt3, + const core::vector2df &tc1, const core::vector2df &tc2, const core::vector2df &tc3); - core::array *SkinningBuffers; //Meshbuffer to skin, default is to skin localBuffers + core::array *SkinningBuffers; // Meshbuffer to skin, default is to skin localBuffers - core::array LocalBuffers; + core::array LocalBuffers; - core::array AllJoints; - core::array RootJoints; + core::array AllJoints; + core::array RootJoints; - // bool can't be used here because std::vector - // doesn't allow taking a reference to individual elements. - core::array< core::array > Vertices_Moved; + // bool can't be used here because std::vector + // doesn't allow taking a reference to individual elements. + core::array> Vertices_Moved; - core::aabbox3d BoundingBox; + core::aabbox3d BoundingBox; - f32 EndFrame; - f32 FramesPerSecond; + f32 EndFrame; + f32 FramesPerSecond; - f32 LastAnimatedFrame; - bool SkinnedLastFrame; + f32 LastAnimatedFrame; + bool SkinnedLastFrame; - E_INTERPOLATION_MODE InterpolationMode:8; + E_INTERPOLATION_MODE InterpolationMode : 8; - bool HasAnimation; - bool PreparedForSkinning; - bool AnimateNormals; - bool HardwareSkinning; - }; + bool HasAnimation; + bool PreparedForSkinning; + bool AnimateNormals; + bool HardwareSkinning; +}; } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CTimer.h b/source/Irrlicht/CTimer.h index 4a57baa2..950365cd 100644 --- a/source/Irrlicht/CTimer.h +++ b/source/Irrlicht/CTimer.h @@ -9,90 +9,88 @@ namespace irr { - //! Device independent implementation of the timer - class CTimer : public ITimer +//! Device independent implementation of the timer +class CTimer : public ITimer +{ +public: + CTimer() { - public: + os::Timer::initTimer(); + } - CTimer() - { - os::Timer::initTimer(); - } + //! Returns current real time in milliseconds of the system. + /** This value does not start with 0 when the application starts. + For example in one implementation the value returned could be the + amount of milliseconds which have elapsed since the system was started. */ + u32 getRealTime() const override + { + return os::Timer::getRealTime(); + } - //! Returns current real time in milliseconds of the system. - /** This value does not start with 0 when the application starts. - For example in one implementation the value returned could be the - amount of milliseconds which have elapsed since the system was started. */ - u32 getRealTime() const override - { - return os::Timer::getRealTime(); - } + //! Returns current virtual time in milliseconds. + /** This value starts with 0 and can be manipulated using setTime(), stopTimer(), + startTimer(), etc. This value depends on the set speed of the timer if the timer + is stopped, etc. If you need the system time, use getRealTime() */ + u32 getTime() const override + { + return os::Timer::getTime(); + } - //! Returns current virtual time in milliseconds. - /** This value starts with 0 and can be manipulated using setTime(), stopTimer(), - startTimer(), etc. This value depends on the set speed of the timer if the timer - is stopped, etc. If you need the system time, use getRealTime() */ - u32 getTime() const override - { - return os::Timer::getTime(); - } + //! sets current virtual time + void setTime(u32 time) override + { + os::Timer::setTime(time); + } - //! sets current virtual time - void setTime(u32 time) override - { - os::Timer::setTime(time); - } + //! Stops the game timer. + /** The timer is reference counted, which means everything which calls + stopTimer() will also have to call startTimer(), otherwise the timer may not start/stop + corretly again. */ + void stop() override + { + os::Timer::stopTimer(); + } - //! Stops the game timer. - /** The timer is reference counted, which means everything which calls - stopTimer() will also have to call startTimer(), otherwise the timer may not start/stop - corretly again. */ - void stop() override - { - os::Timer::stopTimer(); - } + //! Starts the game timer. + /** The timer is reference counted, which means everything which calls + stopTimer() will also have to call startTimer(), otherwise the timer may not start/stop + corretly again. */ + void start() override + { + os::Timer::startTimer(); + } - //! Starts the game timer. - /** The timer is reference counted, which means everything which calls - stopTimer() will also have to call startTimer(), otherwise the timer may not start/stop - corretly again. */ - void start() override - { - os::Timer::startTimer(); - } + //! Sets the speed of the timer + /** The speed is the factor with which the time is running faster or slower then the + real system time. */ + void setSpeed(f32 speed = 1.0f) override + { + os::Timer::setSpeed(speed); + } - //! Sets the speed of the timer - /** The speed is the factor with which the time is running faster or slower then the - real system time. */ - void setSpeed(f32 speed = 1.0f) override - { - os::Timer::setSpeed(speed); - } + //! Returns current speed of the timer + /** The speed is the factor with which the time is running faster or slower then the + real system time. */ + f32 getSpeed() const override + { + return os::Timer::getSpeed(); + } - //! Returns current speed of the timer - /** The speed is the factor with which the time is running faster or slower then the - real system time. */ - f32 getSpeed() const override - { - return os::Timer::getSpeed(); - } + //! Returns if game timer is currently stopped + bool isStopped() const override + { + bool ret = os::Timer::isStopped(); + return ret; + } - //! Returns if game timer is currently stopped - bool isStopped() const override - { - bool ret = os::Timer::isStopped(); - return ret; - } - - //! Advances the virtual time - /** Makes the virtual timer update the time value based on the real time. This is - called automatically when calling IrrlichtDevice::run(), but you can call it manually - if you don't use this method. */ - void tick() override - { - os::Timer::tick(); - } - }; + //! Advances the virtual time + /** Makes the virtual timer update the time value based on the real time. This is + called automatically when calling IrrlichtDevice::run(), but you can call it manually + if you don't use this method. */ + void tick() override + { + os::Timer::tick(); + } +}; } // end namespace - diff --git a/source/Irrlicht/CWGLManager.cpp b/source/Irrlicht/CWGLManager.cpp index 5fb75ba3..fbd262cb 100644 --- a/source/Irrlicht/CWGLManager.cpp +++ b/source/Irrlicht/CWGLManager.cpp @@ -16,12 +16,12 @@ namespace irr namespace video { -CWGLManager::CWGLManager() - : PrimaryContext(SExposedVideoData(0)), PixelFormat(0), libHandle(NULL) +CWGLManager::CWGLManager() : + PrimaryContext(SExposedVideoData(0)), PixelFormat(0), libHandle(NULL) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CWGLManager"); - #endif +#endif memset(FunctionPointers, 0, sizeof(FunctionPointers)); } @@ -29,29 +29,29 @@ CWGLManager::~CWGLManager() { } -bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata) +bool CWGLManager::initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &videodata) { // store params, videoData is set later as it would be overwritten else - Params=params; + Params = params; // Create a window to test antialiasing support - const fschar_t* ClassName = __TEXT("CWGLManager"); + const fschar_t *ClassName = __TEXT("CWGLManager"); HINSTANCE lhInstance = GetModuleHandle(0); // Register Class WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = (WNDPROC)DefWindowProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = lhInstance; - wcex.hIcon = 0; - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = 0; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = (WNDPROC)DefWindowProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = lhInstance; + wcex.hIcon = 0; + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wcex.lpszMenuName = 0; wcex.lpszClassName = ClassName; - wcex.hIconSm = 0; + wcex.hIconSm = 0; RegisterClassEx(&wcex); RECT clientSize; @@ -72,11 +72,10 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2; const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2; - HWND temporary_wnd=CreateWindow(ClassName, __TEXT(""), style, windowLeft, + HWND temporary_wnd = CreateWindow(ClassName, __TEXT(""), style, windowLeft, windowTop, realWidth, realHeight, NULL, NULL, lhInstance, NULL); - if (!temporary_wnd) - { + if (!temporary_wnd) { os::Printer::log("Cannot create a temporary window.", ELL_ERROR); UnregisterClass(ClassName, lhInstance); return false; @@ -86,66 +85,50 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE // Set up pixel format descriptor with desired parameters PIXELFORMATDESCRIPTOR tmp_pfd = { - sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor - 1, // Version Number - (DWORD)(PFD_DRAW_TO_WINDOW | // Format Must Support Window - PFD_SUPPORT_OPENGL | // Format Must Support OpenGL - (Params.Doublebuffer?PFD_DOUBLEBUFFER:0) | // Must Support Double Buffering - (Params.Stereobuffer?PFD_STEREO:0)), // Must Support Stereo Buffer - PFD_TYPE_RGBA, // Request An RGBA Format - Params.Bits, // Select Our Color Depth - 0, 0, 0, 0, 0, 0, // Color Bits Ignored - 0, // No Alpha Buffer - 0, // Shift Bit Ignored - 0, // No Accumulation Buffer - 0, 0, 0, 0, // Accumulation Bits Ignored - Params.ZBufferBits, // Z-Buffer (Depth Buffer) - BYTE(Params.Stencilbuffer ? 1 : 0), // Stencil Buffer Depth - 0, // No Auxiliary Buffer - PFD_MAIN_PLANE, // Main Drawing Layer - 0, // Reserved - 0, 0, 0 // Layer Masks Ignored + sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor + 1, // Version Number + (DWORD)(PFD_DRAW_TO_WINDOW | // Format Must Support Window + PFD_SUPPORT_OPENGL | // Format Must Support OpenGL + (Params.Doublebuffer ? PFD_DOUBLEBUFFER : 0) | // Must Support Double Buffering + (Params.Stereobuffer ? PFD_STEREO : 0)), // Must Support Stereo Buffer + PFD_TYPE_RGBA, // Request An RGBA Format + Params.Bits, // Select Our Color Depth + 0, 0, 0, 0, 0, 0, // Color Bits Ignored + 0, // No Alpha Buffer + 0, // Shift Bit Ignored + 0, // No Accumulation Buffer + 0, 0, 0, 0, // Accumulation Bits Ignored + Params.ZBufferBits, // Z-Buffer (Depth Buffer) + BYTE(Params.Stencilbuffer ? 1 : 0), // Stencil Buffer Depth + 0, // No Auxiliary Buffer + PFD_MAIN_PLANE, // Main Drawing Layer + 0, // Reserved + 0, 0, 0 // Layer Masks Ignored }; - pfd=tmp_pfd; + pfd = tmp_pfd; - for (u32 i=0; i<6; ++i) - { - if (i == 1) - { - if (Params.Stencilbuffer) - { + for (u32 i = 0; i < 6; ++i) { + if (i == 1) { + if (Params.Stencilbuffer) { os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = false; pfd.cStencilBits = 0; - } - else + } else continue; - } - else - if (i == 2) - { + } else if (i == 2) { pfd.cDepthBits = 24; - } - else - if (i == 3) - { - if (Params.Bits!=16) + } else if (i == 3) { + if (Params.Bits != 16) pfd.cDepthBits = 16; else continue; - } - else - if (i == 4) - { + } else if (i == 4) { // try single buffer if (Params.Doublebuffer) pfd.dwFlags &= ~PFD_DOUBLEBUFFER; else continue; - } - else - if (i == 5) - { + } else if (i == 5) { os::Printer::log("Cannot create a GL device context", "No suitable format for temporary window.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); @@ -161,9 +144,8 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE SetPixelFormat(HDc, PixelFormat, &pfd); os::Printer::log("Create temporary GL rendering context", ELL_DEBUG); - HGLRC hrc=wglCreateContext(HDc); - if (!hrc) - { + HGLRC hrc = wglCreateContext(HDc); + if (!hrc) { os::Printer::log("Cannot create a temporary GL rendering context.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); @@ -175,8 +157,7 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE CurrentContext.OpenGLWin32.HRc = hrc; CurrentContext.OpenGLWin32.HWnd = temporary_wnd; - if (!activateContext(CurrentContext, false)) - { + if (!activateContext(CurrentContext, false)) { os::Printer::log("Cannot activate a temporary GL rendering context.", ELL_ERROR); wglDeleteContext(hrc); ReleaseDC(temporary_wnd, HDc); @@ -197,18 +178,17 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE #endif const bool pixel_format_supported = (wglExtensions.find("WGL_ARB_pixel_format") != -1); const bool multi_sample_supported = ((wglExtensions.find("WGL_ARB_multisample") != -1) || - (wglExtensions.find("WGL_EXT_multisample") != -1) || (wglExtensions.find("WGL_3DFX_multisample") != -1) ); + (wglExtensions.find("WGL_EXT_multisample") != -1) || (wglExtensions.find("WGL_3DFX_multisample") != -1)); #ifdef _DEBUG os::Printer::log("WGL_extensions", wglExtensions); #endif // Without a GL context we can't call wglGetProcAddress so store this for later - FunctionPointers[0] = (void*)wglGetProcAddress("wglCreateContextAttribsARB"); + FunctionPointers[0] = (void *)wglGetProcAddress("wglCreateContextAttribsARB"); #ifdef WGL_ARB_pixel_format PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormat_ARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); - if (pixel_format_supported && wglChoosePixelFormat_ARB) - { + if (pixel_format_supported && wglChoosePixelFormat_ARB) { // This value determines the number of samples used for antialiasing // My experience is that 8 does not show a big // improvement over 4, but 4 shows a big improvement @@ -219,60 +199,54 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE f32 fAttributes[] = {0.0, 0.0}; s32 iAttributes[] = - { - WGL_DRAW_TO_WINDOW_ARB,1, - WGL_SUPPORT_OPENGL_ARB,1, - WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, - WGL_COLOR_BITS_ARB,(Params.Bits==32) ? 24 : 15, - WGL_ALPHA_BITS_ARB,(Params.Bits==32) ? 8 : 1, - WGL_DEPTH_BITS_ARB,Params.ZBufferBits, // 10,11 - WGL_STENCIL_BITS_ARB,Params.Stencilbuffer ? 1 : 0, - WGL_DOUBLE_BUFFER_ARB,Params.Doublebuffer ? 1 : 0, - WGL_STEREO_ARB,Params.Stereobuffer ? 1 : 0, - WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, + { + WGL_DRAW_TO_WINDOW_ARB, 1, + WGL_SUPPORT_OPENGL_ARB, 1, + WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, + WGL_COLOR_BITS_ARB, (Params.Bits == 32) ? 24 : 15, + WGL_ALPHA_BITS_ARB, (Params.Bits == 32) ? 8 : 1, + WGL_DEPTH_BITS_ARB, Params.ZBufferBits, // 10,11 + WGL_STENCIL_BITS_ARB, Params.Stencilbuffer ? 1 : 0, + WGL_DOUBLE_BUFFER_ARB, Params.Doublebuffer ? 1 : 0, + WGL_STEREO_ARB, Params.Stereobuffer ? 1 : 0, + WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, #ifdef WGL_ARB_multisample - WGL_SAMPLES_ARB,Params.AntiAlias, // 20,21 - WGL_SAMPLE_BUFFERS_ARB, (Params.AntiAlias>0) ? 1 : 0, + WGL_SAMPLES_ARB, Params.AntiAlias, // 20,21 + WGL_SAMPLE_BUFFERS_ARB, (Params.AntiAlias > 0) ? 1 : 0, #elif defined(WGL_EXT_multisample) - WGL_SAMPLES_EXT,AntiAlias, // 20,21 - WGL_SAMPLE_BUFFERS_EXT, (Params.AntiAlias>0) ? 1 : 0, + WGL_SAMPLES_EXT, AntiAlias, // 20,21 + WGL_SAMPLE_BUFFERS_EXT, (Params.AntiAlias > 0) ? 1 : 0, #elif defined(WGL_3DFX_multisample) - WGL_SAMPLES_3DFX,AntiAlias, // 20,21 - WGL_SAMPLE_BUFFERS_3DFX, (Params.AntiAlias>0) ? 1 : 0, + WGL_SAMPLES_3DFX, AntiAlias, // 20,21 + WGL_SAMPLE_BUFFERS_3DFX, (Params.AntiAlias > 0) ? 1 : 0, #endif -// WGL_DEPTH_FLOAT_EXT, 1, - 0,0,0,0 - }; - int iAttrSize = sizeof(iAttributes)/sizeof(int); - if (!multi_sample_supported) - { - memmove(&iAttributes[20],&iAttributes[24],sizeof(int)*(iAttrSize-24)); + // WGL_DEPTH_FLOAT_EXT, 1, + 0, 0, 0, 0}; + int iAttrSize = sizeof(iAttributes) / sizeof(int); + if (!multi_sample_supported) { + memmove(&iAttributes[20], &iAttributes[24], sizeof(int) * (iAttrSize - 24)); iAttrSize -= 4; } - s32 rv=0; + s32 rv = 0; // Try to get an acceptable pixel format - do - { - int pixelFormat=0; - UINT numFormats=0; - const BOOL valid = wglChoosePixelFormat_ARB(HDc,iAttributes,fAttributes,1,&pixelFormat,&numFormats); + do { + int pixelFormat = 0; + UINT numFormats = 0; + const BOOL valid = wglChoosePixelFormat_ARB(HDc, iAttributes, fAttributes, 1, &pixelFormat, &numFormats); if (valid && numFormats) rv = pixelFormat; else iAttributes[21] -= 1; + } while (rv == 0 && iAttributes[21] > 1); + if (rv) { + PixelFormat = rv; + Params.AntiAlias = iAttributes[21]; } - while(rv==0 && iAttributes[21]>1); - if (rv) - { - PixelFormat=rv; - Params.AntiAlias=iAttributes[21]; - } - } - else + } else #endif - Params.AntiAlias=0; + Params.AntiAlias = 0; // this only terminates the temporary HRc destroyContext(); @@ -282,17 +256,15 @@ bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SE UnregisterClass(ClassName, lhInstance); // now get new window - CurrentContext.OpenGLWin32.HWnd=videodata.OpenGLWin32.HWnd; + CurrentContext.OpenGLWin32.HWnd = videodata.OpenGLWin32.HWnd; // get hdc - if (!(CurrentContext.OpenGLWin32.HDc=GetDC((HWND)videodata.OpenGLWin32.HWnd))) - { + if (!(CurrentContext.OpenGLWin32.HDc = GetDC((HWND)videodata.OpenGLWin32.HWnd))) { os::Printer::log("Cannot create a GL device context.", ELL_ERROR); return false; } - if (!PrimaryContext.OpenGLWin32.HWnd) - { - PrimaryContext.OpenGLWin32.HWnd=CurrentContext.OpenGLWin32.HWnd; - PrimaryContext.OpenGLWin32.HDc=CurrentContext.OpenGLWin32.HDc; + if (!PrimaryContext.OpenGLWin32.HWnd) { + PrimaryContext.OpenGLWin32.HWnd = CurrentContext.OpenGLWin32.HWnd; + PrimaryContext.OpenGLWin32.HDc = CurrentContext.OpenGLWin32.HDc; } return true; @@ -313,36 +285,24 @@ bool CWGLManager::generateSurface() { HDC HDc = (HDC)CurrentContext.OpenGLWin32.HDc; // search for pixel format the simple way - if (PixelFormat==0 || (!SetPixelFormat(HDc, PixelFormat, &pfd))) - { - for (u32 i=0; i<5; ++i) - { - if (i == 1) - { - if (Params.Stencilbuffer) - { + if (PixelFormat == 0 || (!SetPixelFormat(HDc, PixelFormat, &pfd))) { + for (u32 i = 0; i < 5; ++i) { + if (i == 1) { + if (Params.Stencilbuffer) { os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = false; pfd.cStencilBits = 0; - } - else + } else continue; - } - else - if (i == 2) - { + } else if (i == 2) { pfd.cDepthBits = 24; } - if (i == 3) - { - if (Params.Bits!=16) + if (i == 3) { + if (Params.Bits != 16) pfd.cDepthBits = 16; else continue; - } - else - if (i == 4) - { + } else if (i == 4) { os::Printer::log("Cannot create a GL device context", "No suitable format.", ELL_ERROR); return false; } @@ -354,22 +314,18 @@ bool CWGLManager::generateSurface() } // set pixel format - if (!SetPixelFormat(HDc, PixelFormat, &pfd)) - { + if (!SetPixelFormat(HDc, PixelFormat, &pfd)) { os::Printer::log("Cannot set the pixel format.", ELL_ERROR); return false; } } - if (pfd.cAlphaBits != 0) - { + if (pfd.cAlphaBits != 0) { if (pfd.cRedBits == 8) ColorFormat = ECF_A8R8G8B8; else ColorFormat = ECF_A1R5G5B5; - } - else - { + } else { if (pfd.cRedBits == 8) ColorFormat = ECF_R8G8B8; else @@ -385,31 +341,27 @@ void CWGLManager::destroySurface() bool CWGLManager::generateContext() { - HDC HDc=(HDC)CurrentContext.OpenGLWin32.HDc; + HDC HDc = (HDC)CurrentContext.OpenGLWin32.HDc; HGLRC hrc; // create rendering context #ifdef WGL_ARB_create_context PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribs_ARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)FunctionPointers[0]; - if (wglCreateContextAttribs_ARB) - { + if (wglCreateContextAttribs_ARB) { // with 3.0 all available profiles should be usable, higher versions impose restrictions // we need at least 1.1 const int iAttribs[] = - { - WGL_CONTEXT_MAJOR_VERSION_ARB, 1, - WGL_CONTEXT_MINOR_VERSION_ARB, 1, -// WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, // enable to get a debug context (depends on driver if that does anything) - 0 - }; - hrc=wglCreateContextAttribs_ARB(HDc, 0, iAttribs); - } - else + { + WGL_CONTEXT_MAJOR_VERSION_ARB, 1, + WGL_CONTEXT_MINOR_VERSION_ARB, 1, + // WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, // enable to get a debug context (depends on driver if that does anything) + 0}; + hrc = wglCreateContextAttribs_ARB(HDc, 0, iAttribs); + } else #endif - hrc=wglCreateContext(HDc); + hrc = wglCreateContext(HDc); os::Printer::log("Irrlicht context"); - if (!hrc) - { + if (!hrc) { os::Printer::log("Cannot create a GL rendering context.", ELL_ERROR); return false; } @@ -417,73 +369,65 @@ bool CWGLManager::generateContext() // set exposed data CurrentContext.OpenGLWin32.HRc = hrc; if (!PrimaryContext.OpenGLWin32.HRc) - PrimaryContext.OpenGLWin32.HRc=CurrentContext.OpenGLWin32.HRc; + PrimaryContext.OpenGLWin32.HRc = CurrentContext.OpenGLWin32.HRc; return true; } -const SExposedVideoData& CWGLManager::getContext() const +const SExposedVideoData &CWGLManager::getContext() const { return CurrentContext; } -bool CWGLManager::activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) +bool CWGLManager::activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) { - if (videoData.OpenGLWin32.HWnd && videoData.OpenGLWin32.HDc && videoData.OpenGLWin32.HRc) - { - if (!wglMakeCurrent((HDC)videoData.OpenGLWin32.HDc, (HGLRC)videoData.OpenGLWin32.HRc)) - { + if (videoData.OpenGLWin32.HWnd && videoData.OpenGLWin32.HDc && videoData.OpenGLWin32.HRc) { + if (!wglMakeCurrent((HDC)videoData.OpenGLWin32.HDc, (HGLRC)videoData.OpenGLWin32.HRc)) { os::Printer::log("Render Context switch failed."); return false; } - CurrentContext=videoData; - } - else if (!restorePrimaryOnZero && !videoData.OpenGLWin32.HDc && !videoData.OpenGLWin32.HRc) - { - if (!wglMakeCurrent((HDC)0, (HGLRC)0)) - { + CurrentContext = videoData; + } else if (!restorePrimaryOnZero && !videoData.OpenGLWin32.HDc && !videoData.OpenGLWin32.HRc) { + if (!wglMakeCurrent((HDC)0, (HGLRC)0)) { os::Printer::log("Render Context reset failed."); return false; } CurrentContext = videoData; } // set back to main context - else if (!videoData.OpenGLWin32.HWnd && CurrentContext.OpenGLWin32.HDc != PrimaryContext.OpenGLWin32.HDc) - { - if (!wglMakeCurrent((HDC)PrimaryContext.OpenGLWin32.HDc, (HGLRC)PrimaryContext.OpenGLWin32.HRc)) - { + else if (!videoData.OpenGLWin32.HWnd && CurrentContext.OpenGLWin32.HDc != PrimaryContext.OpenGLWin32.HDc) { + if (!wglMakeCurrent((HDC)PrimaryContext.OpenGLWin32.HDc, (HGLRC)PrimaryContext.OpenGLWin32.HRc)) { os::Printer::log("Render Context switch (back to main) failed."); return false; } - CurrentContext=PrimaryContext; + CurrentContext = PrimaryContext; } return true; } void CWGLManager::destroyContext() { - if (CurrentContext.OpenGLWin32.HRc) - { + if (CurrentContext.OpenGLWin32.HRc) { if (!wglMakeCurrent((HDC)CurrentContext.OpenGLWin32.HDc, 0)) os::Printer::log("Release of render context failed.", ELL_WARNING); if (!wglDeleteContext((HGLRC)CurrentContext.OpenGLWin32.HRc)) os::Printer::log("Deletion of render context failed.", ELL_WARNING); - if (PrimaryContext.OpenGLWin32.HRc==CurrentContext.OpenGLWin32.HRc) - PrimaryContext.OpenGLWin32.HRc=0; - CurrentContext.OpenGLWin32.HRc=0; + if (PrimaryContext.OpenGLWin32.HRc == CurrentContext.OpenGLWin32.HRc) + PrimaryContext.OpenGLWin32.HRc = 0; + CurrentContext.OpenGLWin32.HRc = 0; } } -void* CWGLManager::getProcAddress(const std::string &procName) +void *CWGLManager::getProcAddress(const std::string &procName) { - void* proc = NULL; - proc = (void*)wglGetProcAddress(procName.c_str()); + void *proc = NULL; + proc = (void *)wglGetProcAddress(procName.c_str()); if (!proc) { // Fallback if (!libHandle) libHandle = LoadLibraryA("opengl32.dll"); if (libHandle) - proc = (void*)GetProcAddress(libHandle, procName.c_str()); + proc = (void *)GetProcAddress(libHandle, procName.c_str()); } return proc; } diff --git a/source/Irrlicht/CWGLManager.h b/source/Irrlicht/CWGLManager.h index c31c6f6c..b8276d5f 100644 --- a/source/Irrlicht/CWGLManager.h +++ b/source/Irrlicht/CWGLManager.h @@ -4,8 +4,8 @@ #pragma once -#ifdef _IRR_COMPILE_WITH_WGL_MANAGER_ - +#ifdef _IRR_COMPILE_WITH_WGL_MANAGER_ + #include "SIrrCreationParameters.h" #include "SExposedVideoData.h" #include "IContextManager.h" @@ -19,58 +19,58 @@ namespace irr { namespace video { - // WGL manager. - class CWGLManager : public IContextManager - { - public: - //! Constructor. - CWGLManager(); +// WGL manager. +class CWGLManager : public IContextManager +{ +public: + //! Constructor. + CWGLManager(); - //! Destructor - ~CWGLManager(); + //! Destructor + ~CWGLManager(); - // Initialize - bool initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& data) override; + // Initialize + bool initialize(const SIrrlichtCreationParameters ¶ms, const SExposedVideoData &data) override; - // Terminate - void terminate() override; + // Terminate + void terminate() override; - // Create surface. - bool generateSurface() override; + // Create surface. + bool generateSurface() override; - // Destroy surface. - void destroySurface() override; + // Destroy surface. + void destroySurface() override; - // Create context. - bool generateContext() override; + // Create context. + bool generateContext() override; - // Destroy EGL context. - void destroyContext() override; + // Destroy EGL context. + void destroyContext() override; - //! Get current context - const SExposedVideoData& getContext() const override; + //! Get current context + const SExposedVideoData &getContext() const override; - //! Change render context, disable old and activate new defined by videoData - bool activateContext(const SExposedVideoData& videoData, bool restorePrimaryOnZero) override; + //! Change render context, disable old and activate new defined by videoData + bool activateContext(const SExposedVideoData &videoData, bool restorePrimaryOnZero) override; - // Get procedure address. - void* getProcAddress(const std::string &procName) override; + // Get procedure address. + void *getProcAddress(const std::string &procName) override; - // Swap buffers. - bool swapBuffers() override; + // Swap buffers. + bool swapBuffers() override; - private: - SIrrlichtCreationParameters Params; - SExposedVideoData PrimaryContext; - SExposedVideoData CurrentContext; - s32 PixelFormat; - PIXELFORMATDESCRIPTOR pfd; - ECOLOR_FORMAT ColorFormat; - void* FunctionPointers[1]; +private: + SIrrlichtCreationParameters Params; + SExposedVideoData PrimaryContext; + SExposedVideoData CurrentContext; + s32 PixelFormat; + PIXELFORMATDESCRIPTOR pfd; + ECOLOR_FORMAT ColorFormat; + void *FunctionPointers[1]; - HMODULE libHandle; - }; + HMODULE libHandle; +}; } } - -#endif + +#endif diff --git a/source/Irrlicht/CWriteFile.cpp b/source/Irrlicht/CWriteFile.cpp index 322a6b2b..362b284e 100644 --- a/source/Irrlicht/CWriteFile.cpp +++ b/source/Irrlicht/CWriteFile.cpp @@ -10,37 +10,30 @@ namespace irr namespace io { - -CWriteFile::CWriteFile(const io::path& fileName, bool append) -: Filename(fileName), FileSize(0) +CWriteFile::CWriteFile(const io::path &fileName, bool append) : + Filename(fileName), FileSize(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CWriteFile"); - #endif +#endif openFile(append); } - - CWriteFile::~CWriteFile() { if (File) fclose(File); } - - //! returns if file is open inline bool CWriteFile::isOpen() const { return File != 0; } - - //! returns how much was read -size_t CWriteFile::write(const void* buffer, size_t sizeToWrite) +size_t CWriteFile::write(const void *buffer, size_t sizeToWrite) { if (!isOpen()) return 0; @@ -48,8 +41,6 @@ size_t CWriteFile::write(const void* buffer, size_t sizeToWrite) return fwrite(buffer, 1, sizeToWrite, File); } - - //! changes position in file, returns true if successful //! if relativeMovement==true, the pos is changed relative to current pos, //! otherwise from begin of file @@ -61,29 +52,23 @@ bool CWriteFile::seek(long finalPos, bool relativeMovement) return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0; } - - //! returns where in the file we are. long CWriteFile::getPos() const { return ftell(File); } - - //! opens the file void CWriteFile::openFile(bool append) { - if (Filename.size() == 0) - { + if (Filename.size() == 0) { File = 0; return; } File = fopen(Filename.c_str(), append ? "ab" : "wb"); - if (File) - { + if (File) { // get FileSize fseek(File, 0, SEEK_END); @@ -92,10 +77,8 @@ void CWriteFile::openFile(bool append) } } - - //! returns name of file -const io::path& CWriteFile::getFileName() const +const io::path &CWriteFile::getFileName() const { return Filename; } @@ -109,9 +92,9 @@ bool CWriteFile::flush() return fflush(File) == 0; // 0 indicates success, otherwise EOF and errno is set } -IWriteFile* CWriteFile::createWriteFile(const io::path& fileName, bool append) +IWriteFile *CWriteFile::createWriteFile(const io::path &fileName, bool append) { - CWriteFile* file = new CWriteFile(fileName, append); + CWriteFile *file = new CWriteFile(fileName, append); if (file->isOpen()) return file; @@ -119,7 +102,5 @@ IWriteFile* CWriteFile::createWriteFile(const io::path& fileName, bool append) return 0; } - } // end namespace io } // end namespace irr - diff --git a/source/Irrlicht/CWriteFile.h b/source/Irrlicht/CWriteFile.h index cc836408..20bca089 100644 --- a/source/Irrlicht/CWriteFile.h +++ b/source/Irrlicht/CWriteFile.h @@ -14,47 +14,45 @@ namespace irr namespace io { - /*! - Class for writing a real file to disk. - */ - class CWriteFile : public IWriteFile - { - public: +/*! + Class for writing a real file to disk. +*/ +class CWriteFile : public IWriteFile +{ +public: + CWriteFile(const io::path &fileName, bool append); - CWriteFile(const io::path& fileName, bool append); + virtual ~CWriteFile(); - virtual ~CWriteFile(); + //! Reads an amount of bytes from the file. + size_t write(const void *buffer, size_t sizeToWrite) override; - //! Reads an amount of bytes from the file. - size_t write(const void* buffer, size_t sizeToWrite) override; + //! Changes position in file, returns true if successful. + bool seek(long finalPos, bool relativeMovement = false) override; - //! Changes position in file, returns true if successful. - bool seek(long finalPos, bool relativeMovement = false) override; + //! Returns the current position in the file. + long getPos() const override; - //! Returns the current position in the file. - long getPos() const override; + //! Returns name of file. + const io::path &getFileName() const override; - //! Returns name of file. - const io::path& getFileName() const override; + //! Flush the content of the buffer in the file + bool flush() override; - //! Flush the content of the buffer in the file - bool flush() override; + //! returns if file is open + bool isOpen() const; - //! returns if file is open - bool isOpen() const; + //! creator method + static IWriteFile *createWriteFile(const io::path &fileName, bool append); - //! creator method - static IWriteFile* createWriteFile(const io::path& fileName, bool append); +private: + //! opens the file + void openFile(bool append); - private: - - //! opens the file - void openFile(bool append); - - io::path Filename; - FILE* File; - long FileSize; - }; + io::path Filename; + FILE *File; + long FileSize; +}; } // end namespace io } // end namespace irr diff --git a/source/Irrlicht/CXMeshFileLoader.cpp b/source/Irrlicht/CXMeshFileLoader.cpp index 403c595b..97122531 100644 --- a/source/Irrlicht/CXMeshFileLoader.cpp +++ b/source/Irrlicht/CXMeshFileLoader.cpp @@ -2,7 +2,6 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h - #include "CXMeshFileLoader.h" #include "os.h" @@ -15,9 +14,13 @@ #ifdef _DEBUG #define _XREADER_DEBUG #endif -//#define BETTER_MESHBUFFER_SPLITTING_FOR_X +// #define BETTER_MESHBUFFER_SPLITTING_FOR_X -#define SET_ERR_AND_RETURN() do { ErrorState = true; return false; } while (0) +#define SET_ERR_AND_RETURN() \ + do { \ + ErrorState = true; \ + return false; \ + } while (0) namespace irr { @@ -25,29 +28,27 @@ namespace scene { //! Constructor -CXMeshFileLoader::CXMeshFileLoader(scene::ISceneManager* smgr) -: AnimatedMesh(0), Buffer(0), P(0), End(0), BinaryNumCount(0), Line(0), ErrorState(false), - CurFrame(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), FloatSize(0) +CXMeshFileLoader::CXMeshFileLoader(scene::ISceneManager *smgr) : + AnimatedMesh(0), Buffer(0), P(0), End(0), BinaryNumCount(0), Line(0), ErrorState(false), + CurFrame(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), FloatSize(0) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CXMeshFileLoader"); - #endif +#endif } - //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") -bool CXMeshFileLoader::isALoadableFileExtension(const io::path& filename) const +bool CXMeshFileLoader::isALoadableFileExtension(const io::path &filename) const { - return core::hasFileExtension ( filename, "x" ); + return core::hasFileExtension(filename, "x"); } - //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. -IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* file) +IAnimatedMesh *CXMeshFileLoader::createMesh(io::IReadFile *file) { if (!file) return 0; @@ -58,12 +59,9 @@ IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* file) AnimatedMesh = new CSkinnedMesh(); - if (load(file)) - { + if (load(file)) { AnimatedMesh->finalize(); - } - else - { + } else { AnimatedMesh->drop(); AnimatedMesh = 0; } @@ -76,29 +74,28 @@ IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* file) tmpString += "ms"; os::Printer::log(tmpString.c_str()); #endif - //Clear up + // Clear up - MajorVersion=0; - MinorVersion=0; - BinaryFormat=0; - BinaryNumCount=0; - FloatSize=0; - P=0; - End=0; - CurFrame=0; + MajorVersion = 0; + MinorVersion = 0; + BinaryFormat = 0; + BinaryNumCount = 0; + FloatSize = 0; + P = 0; + End = 0; + CurFrame = 0; - delete [] Buffer; + delete[] Buffer; Buffer = 0; - for (u32 i=0; iMaterials.size()) - { + if (!mesh->Materials.size()) { mesh->Materials.push_back(video::SMaterial()); mesh->Materials[0].DiffuseColor.set(0xff777777); - mesh->Materials[0].Shininess=0.f; + mesh->Materials[0].Shininess = 0.f; mesh->Materials[0].SpecularColor.set(0xff777777); mesh->Materials[0].EmissiveColor.set(0xff000000); } @@ -126,133 +121,109 @@ bool CXMeshFileLoader::load(io::IReadFile* file) #ifndef BETTER_MESHBUFFER_SPLITTING_FOR_X const u32 bufferOffset = AnimatedMesh->getMeshBufferCount(); #endif - for (i=0; iMaterials.size(); ++i) - { - mesh->Buffers.push_back( AnimatedMesh->addMeshBuffer() ); + for (i = 0; i < mesh->Materials.size(); ++i) { + mesh->Buffers.push_back(AnimatedMesh->addMeshBuffer()); mesh->Buffers.getLast()->Material = mesh->Materials[i]; - if (!mesh->HasSkinning) - { - //Set up rigid animation - if (mesh->AttachedJointID!=-1) - { - AnimatedMesh->getAllJoints()[mesh->AttachedJointID]->AttachedMeshes.push_back( AnimatedMesh->getMeshBuffers().size()-1 ); + if (!mesh->HasSkinning) { + // Set up rigid animation + if (mesh->AttachedJointID != -1) { + AnimatedMesh->getAllJoints()[mesh->AttachedJointID]->AttachedMeshes.push_back(AnimatedMesh->getMeshBuffers().size() - 1); } } } - if (!mesh->FaceMaterialIndices.size()) - { + if (!mesh->FaceMaterialIndices.size()) { mesh->FaceMaterialIndices.set_used(mesh->Indices.size() / 3); - for (i=0; iFaceMaterialIndices.size(); ++i) - mesh->FaceMaterialIndices[i]=0; + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) + mesh->FaceMaterialIndices[i] = 0; } - if (!mesh->HasVertexColors) - { - for (u32 j=0;jFaceMaterialIndices.size();++j) - { - for (u32 id=j*3+0;id<=j*3+2;++id) - { - mesh->Vertices[ mesh->Indices[id] ].Color = mesh->Buffers[mesh->FaceMaterialIndices[j]]->Material.DiffuseColor; + if (!mesh->HasVertexColors) { + for (u32 j = 0; j < mesh->FaceMaterialIndices.size(); ++j) { + for (u32 id = j * 3 + 0; id <= j * 3 + 2; ++id) { + mesh->Vertices[mesh->Indices[id]].Color = mesh->Buffers[mesh->FaceMaterialIndices[j]]->Material.DiffuseColor; } } } - #ifdef BETTER_MESHBUFFER_SPLITTING_FOR_X +#ifdef BETTER_MESHBUFFER_SPLITTING_FOR_X { - //the same vertex can be used in many different meshbuffers, but it's slow to work out + // the same vertex can be used in many different meshbuffers, but it's slow to work out - core::array< core::array< u32 > > verticesLinkIndex; + core::array> verticesLinkIndex; verticesLinkIndex.reallocate(mesh->Vertices.size()); - core::array< core::array< u16 > > verticesLinkBuffer; + core::array> verticesLinkBuffer; verticesLinkBuffer.reallocate(mesh->Vertices.size()); - for (i=0;iVertices.size();++i) - { - verticesLinkIndex.push_back( core::array< u32 >() ); - verticesLinkBuffer.push_back( core::array< u16 >() ); + for (i = 0; i < mesh->Vertices.size(); ++i) { + verticesLinkIndex.push_back(core::array()); + verticesLinkBuffer.push_back(core::array()); } - for (i=0;iFaceMaterialIndices.size();++i) - { - for (u32 id=i*3+0;id<=i*3+2;++id) - { - core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ]; - bool found=false; + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) { + for (u32 id = i * 3 + 0; id <= i * 3 + 2; ++id) { + core::array &Array = verticesLinkBuffer[mesh->Indices[id]]; + bool found = false; - for (u32 j=0; j < Array.size(); ++j) - { - if (Array[j]==mesh->FaceMaterialIndices[i]) - { - found=true; + for (u32 j = 0; j < Array.size(); ++j) { + if (Array[j] == mesh->FaceMaterialIndices[i]) { + found = true; break; } } if (!found) - Array.push_back( mesh->FaceMaterialIndices[i] ); + Array.push_back(mesh->FaceMaterialIndices[i]); } } - for (i=0;iVertices.size();++i) - { - core::array< u16 > &Array = verticesLinkBuffer[i]; + for (i = 0; i < mesh->Vertices.size(); ++i) { + core::array &Array = verticesLinkBuffer[i]; verticesLinkIndex[i].reallocate(Array.size()); - for (u32 j=0; j < Array.size(); ++j) - { - scene::SSkinMeshBuffer *buffer = mesh->Buffers[ Array[j] ]; - verticesLinkIndex[i].push_back( buffer->Vertices_Standard.size() ); - buffer->Vertices_Standard.push_back( mesh->Vertices[i] ); + for (u32 j = 0; j < Array.size(); ++j) { + scene::SSkinMeshBuffer *buffer = mesh->Buffers[Array[j]]; + verticesLinkIndex[i].push_back(buffer->Vertices_Standard.size()); + buffer->Vertices_Standard.push_back(mesh->Vertices[i]); } } - for (i=0;iFaceMaterialIndices.size();++i) - { - scene::SSkinMeshBuffer *buffer=mesh->Buffers[ mesh->FaceMaterialIndices[i] ]; + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) { + scene::SSkinMeshBuffer *buffer = mesh->Buffers[mesh->FaceMaterialIndices[i]]; - for (u32 id=i*3+0;id<=i*3+2;++id) - { - core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ]; + for (u32 id = i * 3 + 0; id <= i * 3 + 2; ++id) { + core::array &Array = verticesLinkBuffer[mesh->Indices[id]]; - for (u32 j=0;j< Array.size() ;++j) - { - if ( Array[j]== mesh->FaceMaterialIndices[i] ) - buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ][j] ); + for (u32 j = 0; j < Array.size(); ++j) { + if (Array[j] == mesh->FaceMaterialIndices[i]) + buffer->Indices.push_back(verticesLinkIndex[mesh->Indices[id]][j]); } } } - for (u32 j=0;jWeightJoint.size();++j) - { - ISkinnedMesh::SJoint* joint = AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]; - ISkinnedMesh::SWeight& weight = joint->Weights[mesh->WeightNum[j]]; + for (u32 j = 0; j < mesh->WeightJoint.size(); ++j) { + ISkinnedMesh::SJoint *joint = AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]; + ISkinnedMesh::SWeight &weight = joint->Weights[mesh->WeightNum[j]]; u32 id = weight.vertex_id; - if (id>=verticesLinkIndex.size()) - { + if (id >= verticesLinkIndex.size()) { os::Printer::log("X loader: Weight id out of range", ELL_WARNING); - id=0; - weight.strength=0.f; + id = 0; + weight.strength = 0.f; } - if (verticesLinkBuffer[id].size()==1) - { - weight.vertex_id=verticesLinkIndex[id][0]; - weight.buffer_id=verticesLinkBuffer[id][0]; - } - else if (verticesLinkBuffer[id].size() != 0) - { - for (u32 k=1; k < verticesLinkBuffer[id].size(); ++k) - { - ISkinnedMesh::SWeight* WeightClone = AnimatedMesh->addWeight(joint); + if (verticesLinkBuffer[id].size() == 1) { + weight.vertex_id = verticesLinkIndex[id][0]; + weight.buffer_id = verticesLinkBuffer[id][0]; + } else if (verticesLinkBuffer[id].size() != 0) { + for (u32 k = 1; k < verticesLinkBuffer[id].size(); ++k) { + ISkinnedMesh::SWeight *WeightClone = AnimatedMesh->addWeight(joint); WeightClone->strength = weight.strength; WeightClone->vertex_id = verticesLinkIndex[id][k]; WeightClone->buffer_id = verticesLinkBuffer[id][k]; @@ -260,150 +231,127 @@ bool CXMeshFileLoader::load(io::IReadFile* file) } } } - #else +#else { - core::array< u32 > verticesLinkIndex; - core::array< s16 > verticesLinkBuffer; + core::array verticesLinkIndex; + core::array verticesLinkBuffer; verticesLinkBuffer.set_used(mesh->Vertices.size()); // init with 0 - for (i=0;iVertices.size();++i) - { + for (i = 0; i < mesh->Vertices.size(); ++i) { // watch out for vertices which are not part of the mesh // they will keep the -1 and can lead to out-of-bounds access - verticesLinkBuffer[i]=-1; + verticesLinkBuffer[i] = -1; } bool warned = false; // store meshbuffer number per vertex - for (i=0;iFaceMaterialIndices.size();++i) - { - for (u32 id=i*3+0;id<=i*3+2;++id) - { - if ((verticesLinkBuffer[mesh->Indices[id]] != -1) && (verticesLinkBuffer[mesh->Indices[id]] != (s16)mesh->FaceMaterialIndices[i])) - { - if (!warned) - { + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) { + for (u32 id = i * 3 + 0; id <= i * 3 + 2; ++id) { + if ((verticesLinkBuffer[mesh->Indices[id]] != -1) && (verticesLinkBuffer[mesh->Indices[id]] != (s16)mesh->FaceMaterialIndices[i])) { + if (!warned) { os::Printer::log("X loader", "Duplicated vertex, animation might be corrupted.", ELL_WARNING); - warned=true; + warned = true; } const u32 tmp = mesh->Vertices.size(); - mesh->Vertices.push_back(mesh->Vertices[ mesh->Indices[id] ]); + mesh->Vertices.push_back(mesh->Vertices[mesh->Indices[id]]); mesh->Indices[id] = tmp; verticesLinkBuffer.set_used(mesh->Vertices.size()); } - verticesLinkBuffer[ mesh->Indices[id] ] = mesh->FaceMaterialIndices[i]; + verticesLinkBuffer[mesh->Indices[id]] = mesh->FaceMaterialIndices[i]; } } - if (mesh->FaceMaterialIndices.size() != 0) - { + if (mesh->FaceMaterialIndices.size() != 0) { // store vertices in buffers and remember relation in verticesLinkIndex - u32* vCountArray = new u32[mesh->Buffers.size()]; - memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32)); + u32 *vCountArray = new u32[mesh->Buffers.size()]; + memset(vCountArray, 0, mesh->Buffers.size() * sizeof(u32)); // count vertices in each buffer and reallocate - for (i=0; iVertices.size(); ++i) - { + for (i = 0; i < mesh->Vertices.size(); ++i) { if (verticesLinkBuffer[i] != -1) ++vCountArray[verticesLinkBuffer[i]]; } - if (mesh->TCoords2.size()) - { - for (i=0; i!=mesh->Buffers.size(); ++i) - { + if (mesh->TCoords2.size()) { + for (i = 0; i != mesh->Buffers.size(); ++i) { mesh->Buffers[i]->Vertices_2TCoords.reallocate(vCountArray[i]); - mesh->Buffers[i]->VertexType=video::EVT_2TCOORDS; + mesh->Buffers[i]->VertexType = video::EVT_2TCOORDS; } - } - else - { - for (i=0; i!=mesh->Buffers.size(); ++i) + } else { + for (i = 0; i != mesh->Buffers.size(); ++i) mesh->Buffers[i]->Vertices_Standard.reallocate(vCountArray[i]); } verticesLinkIndex.set_used(mesh->Vertices.size()); // actually store vertices - for (i=0; iVertices.size(); ++i) - { + for (i = 0; i < mesh->Vertices.size(); ++i) { // if a vertex is missing for some reason, just skip it - if (verticesLinkBuffer[i]==-1) + if (verticesLinkBuffer[i] == -1) continue; - scene::SSkinMeshBuffer *buffer = mesh->Buffers[ verticesLinkBuffer[i] ]; + scene::SSkinMeshBuffer *buffer = mesh->Buffers[verticesLinkBuffer[i]]; - if (mesh->TCoords2.size()) - { + if (mesh->TCoords2.size()) { verticesLinkIndex[i] = buffer->Vertices_2TCoords.size(); - buffer->Vertices_2TCoords.push_back( mesh->Vertices[i] ); + buffer->Vertices_2TCoords.push_back(mesh->Vertices[i]); // We have a problem with correct tcoord2 handling here // crash fixed for now by checking the values - buffer->Vertices_2TCoords.getLast().TCoords2=(iTCoords2.size())?mesh->TCoords2[i]:mesh->Vertices[i].TCoords; - } - else - { + buffer->Vertices_2TCoords.getLast().TCoords2 = (i < mesh->TCoords2.size()) ? mesh->TCoords2[i] : mesh->Vertices[i].TCoords; + } else { verticesLinkIndex[i] = buffer->Vertices_Standard.size(); - buffer->Vertices_Standard.push_back( mesh->Vertices[i] ); + buffer->Vertices_Standard.push_back(mesh->Vertices[i]); } } // count indices per buffer and reallocate - memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32)); - for (i=0; iFaceMaterialIndices.size(); ++i) - ++vCountArray[ mesh->FaceMaterialIndices[i] ]; - for (i=0; i!=mesh->Buffers.size(); ++i) + memset(vCountArray, 0, mesh->Buffers.size() * sizeof(u32)); + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) + ++vCountArray[mesh->FaceMaterialIndices[i]]; + for (i = 0; i != mesh->Buffers.size(); ++i) mesh->Buffers[i]->Indices.reallocate(vCountArray[i]); - delete [] vCountArray; + delete[] vCountArray; // create indices per buffer - for (i=0; iFaceMaterialIndices.size(); ++i) - { - scene::SSkinMeshBuffer *buffer = mesh->Buffers[ mesh->FaceMaterialIndices[i] ]; - for (u32 id=i*3+0; id!=i*3+3; ++id) - { - buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ] ); + for (i = 0; i < mesh->FaceMaterialIndices.size(); ++i) { + scene::SSkinMeshBuffer *buffer = mesh->Buffers[mesh->FaceMaterialIndices[i]]; + for (u32 id = i * 3 + 0; id != i * 3 + 3; ++id) { + buffer->Indices.push_back(verticesLinkIndex[mesh->Indices[id]]); } } } - for (u32 j=0; jWeightJoint.size(); ++j) - { - ISkinnedMesh::SWeight& weight = (AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]->Weights[mesh->WeightNum[j]]); + for (u32 j = 0; j < mesh->WeightJoint.size(); ++j) { + ISkinnedMesh::SWeight &weight = (AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]->Weights[mesh->WeightNum[j]]); u32 id = weight.vertex_id; - if (id>=verticesLinkIndex.size()) - { + if (id >= verticesLinkIndex.size()) { os::Printer::log("X loader: Weight id out of range", ELL_WARNING); - id=0; - weight.strength=0.f; + id = 0; + weight.strength = 0.f; } - weight.vertex_id=verticesLinkIndex[id]; - weight.buffer_id=verticesLinkBuffer[id] + bufferOffset; + weight.vertex_id = verticesLinkIndex[id]; + weight.buffer_id = verticesLinkBuffer[id] + bufferOffset; } } - #endif - +#endif } return true; } - //! Reads file into memory -bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file) +bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile *file) { const long size = file->getSize(); - if (size < 12) - { + if (size < 12) { os::Printer::log("X File is too small.", ELL_WARNING); return false; } - Buffer = new c8[size+1]; + Buffer = new c8[size + 1]; Buffer[size] = 0x0; // null-terminate //! read all into memory - if (file->read(Buffer, size) != static_cast(size)) - { + if (file->read(Buffer, size) != static_cast(size)) { os::Printer::log("Could not read from x file.", ELL_WARNING); return false; } @@ -412,8 +360,7 @@ bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file) End = Buffer + size; //! check header "xof " - if (strncmp(Buffer, "xof ", 4)!=0) - { + if (strncmp(Buffer, "xof ", 4) != 0) { os::Printer::log("Not an x file, wrong header.", ELL_WARNING); return false; } @@ -430,24 +377,22 @@ bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file) MinorVersion = core::strtoul10(tmp); //! read format - if (strncmp(&Buffer[8], "txt ", 4) ==0) + if (strncmp(&Buffer[8], "txt ", 4) == 0) BinaryFormat = false; - else if (strncmp(&Buffer[8], "bin ", 4) ==0) + else if (strncmp(&Buffer[8], "bin ", 4) == 0) BinaryFormat = true; - else - { + else { os::Printer::log("Only uncompressed x files currently supported.", ELL_WARNING); return false; } - BinaryNumCount=0; + BinaryNumCount = 0; //! read float size - if (strncmp(&Buffer[12], "0032", 4) ==0) + if (strncmp(&Buffer[12], "0032", 4) == 0) FloatSize = 4; - else if (strncmp(&Buffer[12], "0064", 4) ==0) + else if (strncmp(&Buffer[12], "0064", 4) == 0) FloatSize = 8; - else - { + else { os::Printer::log("Float size not supported.", ELL_WARNING); return false; } @@ -459,19 +404,16 @@ bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file) return true; } - //! Parses the file bool CXMeshFileLoader::parseFile() { - while(parseDataObject()) - { + while (parseDataObject()) { // loop } return !ErrorState; } - //! Parses the next Data object in the file bool CXMeshFileLoader::parseDataObject() { @@ -480,49 +422,32 @@ bool CXMeshFileLoader::parseDataObject() if (objectName.size() == 0) return false; - // parse specific object + // parse specific object #ifdef _XREADER_DEBUG os::Printer::log("debug DataObject", objectName.c_str(), ELL_DEBUG); #endif if (objectName == "template") return parseDataObjectTemplate(); - else - if (objectName == "Frame") - { - return parseDataObjectFrame( 0 ); - } - else - if (objectName == "Mesh") - { + else if (objectName == "Frame") { + return parseDataObjectFrame(0); + } else if (objectName == "Mesh") { // some meshes have no frames at all - //CurFrame = AnimatedMesh->addJoint(0); + // CurFrame = AnimatedMesh->addJoint(0); - SXMesh *mesh=new SXMesh; + SXMesh *mesh = new SXMesh; - //mesh->Buffer=AnimatedMesh->addMeshBuffer(); + // mesh->Buffer=AnimatedMesh->addMeshBuffer(); Meshes.push_back(mesh); return parseDataObjectMesh(*mesh); - } - else - if (objectName == "AnimationSet") - { + } else if (objectName == "AnimationSet") { return parseDataObjectAnimationSet(); - } - else - if (objectName == "AnimTicksPerSecond") - { + } else if (objectName == "AnimTicksPerSecond") { return parseDataObjectAnimationTicksPerSecond(); - } - else - if (objectName == "Material") - { + } else if (objectName == "Material") { return parseUnknownDataObject(); - } - else - if (objectName == "}") - { + } else if (objectName == "}") { os::Printer::log("} found in dataObject", ELL_WARNING); return true; } @@ -532,7 +457,6 @@ bool CXMeshFileLoader::parseDataObject() return parseUnknownDataObject(); } - bool CXMeshFileLoader::parseDataObjectTemplate() { #ifdef _XREADER_DEBUG @@ -542,10 +466,9 @@ bool CXMeshFileLoader::parseDataObjectTemplate() // parse a template data object. Currently not stored. core::stringc name; - if (!readHeadOfDataObject(&name)) - { + if (!readHeadOfDataObject(&name)) { os::Printer::log("Left delimiter in template data object missing.", - name.c_str(), ELL_WARNING); + name.c_str(), ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } @@ -554,8 +477,7 @@ bool CXMeshFileLoader::parseDataObjectTemplate() getNextToken(); // read and ignore data members - while(true) - { + while (true) { core::stringc s = getNextToken(); if (s == "}") @@ -568,7 +490,6 @@ bool CXMeshFileLoader::parseDataObjectTemplate() return true; } - bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent) { #ifdef _XREADER_DEBUG @@ -581,18 +502,17 @@ bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent) // Frame template instances as child objects when loading a Frame // instance. - u32 JointID=0; + u32 JointID = 0; core::stringc name; - if (!readHeadOfDataObject(&name)) - { + if (!readHeadOfDataObject(&name)) { os::Printer::log("No opening brace in Frame found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - CSkinnedMesh::SJoint *joint=0; + CSkinnedMesh::SJoint *joint = 0; if (name.size()) { auto n = AnimatedMesh->getJointNumber(name.c_str()); @@ -602,17 +522,14 @@ bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent) } } - if (!joint) - { + if (!joint) { #ifdef _XREADER_DEBUG os::Printer::log("creating joint ", name.c_str(), ELL_DEBUG); #endif - joint=AnimatedMesh->addJoint(Parent); - joint->Name=name.c_str(); - JointID=AnimatedMesh->getAllJoints().size()-1; - } - else - { + joint = AnimatedMesh->addJoint(Parent); + joint->Name = name.c_str(); + JointID = AnimatedMesh->getAllJoints().size() - 1; + } else { #ifdef _XREADER_DEBUG os::Printer::log("using joint ", name.c_str(), ELL_DEBUG); #endif @@ -623,61 +540,45 @@ bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent) // Now inside a frame. // read tokens until closing brace is reached. - while(true) - { + while (true) { core::stringc objectName = getNextToken(); #ifdef _XREADER_DEBUG os::Printer::log("debug DataObject in frame:", objectName.c_str(), ELL_DEBUG); #endif - if (objectName.size() == 0) - { + if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Frame in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); - } - else - if (objectName == "}") - { + } else if (objectName == "}") { break; // frame finished - } - else - if (objectName == "Frame") - { + } else if (objectName == "Frame") { if (!parseDataObjectFrame(joint)) return false; - } - else - if (objectName == "FrameTransformMatrix") - { + } else if (objectName == "FrameTransformMatrix") { if (!parseDataObjectTransformationMatrix(joint->LocalMatrix)) return false; - //joint->LocalAnimatedMatrix - //joint->LocalAnimatedMatrix.makeInverse(); - //joint->LocalMatrix=tmp*joint->LocalAnimatedMatrix; - } - else - if (objectName == "Mesh") - { + // joint->LocalAnimatedMatrix + // joint->LocalAnimatedMatrix.makeInverse(); + // joint->LocalMatrix=tmp*joint->LocalAnimatedMatrix; + } else if (objectName == "Mesh") { /* frame.Meshes.push_back(SXMesh()); if (!parseDataObjectMesh(frame.Meshes.getLast())) return false; */ - SXMesh *mesh=new SXMesh; + SXMesh *mesh = new SXMesh; - mesh->AttachedJointID=JointID; + mesh->AttachedJointID = JointID; Meshes.push_back(mesh); if (!parseDataObjectMesh(*mesh)) return false; - } - else - { + } else { os::Printer::log("Unknown data object in frame in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; @@ -687,15 +588,13 @@ bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent) return true; } - bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading Transformation Matrix", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -703,14 +602,12 @@ bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat) readMatrix(mat); - if (!checkForOneFollowingSemicolons()) - { + if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -719,13 +616,11 @@ bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat) return true; } - bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) { core::stringc name; - if (!readHeadOfDataObject(&name)) - { + if (!readHeadOfDataObject(&name)) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh", ELL_DEBUG); #endif @@ -743,15 +638,13 @@ bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) // read vertices mesh.Vertices.set_used(nVertices); - for (u32 n=0; n polygonfaces; u32 currentIndex = 0; - for (u32 k=0; k= mesh.Vertices.size()) - { + for (u32 j = 0; j < mesh.Indices.size(); j++) { + if (mesh.Indices[j] >= mesh.Vertices.size()) { os::Printer::log("Out of range index found in Mesh x file reader.", ELL_WARNING); SET_ERR_AND_RETURN(); } } - if (!checkForTwoFollowingSemicolons()) - { + if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Face Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } // here, other data objects may follow - while(true) - { + while (true) { core::stringc objectName = getNextToken(); - if (objectName.size() == 0) - { + if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Mesh in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); - } - else - if (objectName == "}") - { + } else if (objectName == "}") { break; // mesh finished } @@ -842,42 +721,25 @@ bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) os::Printer::log("debug DataObject in mesh", objectName.c_str(), ELL_DEBUG); #endif - if (objectName == "MeshNormals") - { + if (objectName == "MeshNormals") { if (!parseDataObjectMeshNormals(mesh)) return false; - } - else - if (objectName == "MeshTextureCoords") - { + } else if (objectName == "MeshTextureCoords") { if (!parseDataObjectMeshTextureCoords(mesh)) return false; - } - else - if (objectName == "MeshVertexColors") - { + } else if (objectName == "MeshVertexColors") { if (!parseDataObjectMeshVertexColors(mesh)) return false; - } - else - if (objectName == "MeshMaterialList") - { + } else if (objectName == "MeshMaterialList") { if (!parseDataObjectMeshMaterialList(mesh)) return false; - } - else - if (objectName == "VertexDuplicationIndices") - { + } else if (objectName == "VertexDuplicationIndices") { // we'll ignore vertex duplication indices // TODO: read them if (!parseUnknownDataObject()) return false; - } - else - if (objectName == "DeclData") - { - if (!readHeadOfDataObject()) - { + } else if (objectName == "DeclData") { + if (!readHeadOfDataObject()) { os::Printer::log("No starting brace in DeclData found.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -906,32 +768,27 @@ bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) s16 tangenttype = -1; s16 binormaltype = -1; - (void)tangentpos; // disable unused variable warnings - (void)binormalpos; // disable unused variable warnings - (void)tangenttype; // disable unused variable warnings + (void)tangentpos; // disable unused variable warnings + (void)binormalpos; // disable unused variable warnings + (void)tangenttype; // disable unused variable warnings (void)binormaltype; // disable unused variable warnings - for (j=0; j>8)&0xf)*sizeof(core::vector2df); - for (u32 j=0; j> 8) & 0xf) * sizeof(core::vector2df); + for (u32 j = 0; j < mesh.Vertices.size(); ++j) { + mesh.TCoords2.push_back(*((core::vector2df *)(dataptr))); dataptr += size; } } - delete [] data; - if (!checkForOneFollowingSemicolons()) - { + delete[] data; + if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in FVFData found.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in FVFData found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - } - else - if (objectName == "XSkinMeshHeader") - { + } else if (objectName == "XSkinMeshHeader") { if (!parseDataObjectSkinMeshHeader(mesh)) return false; - } - else - if (objectName == "SkinWeights") - { - //mesh.SkinWeights.push_back(SXSkinWeight()); - //if (!parseDataObjectSkinWeights(mesh.SkinWeights.getLast())) + } else if (objectName == "SkinWeights") { + // mesh.SkinWeights.push_back(SXSkinWeight()); + // if (!parseDataObjectSkinWeights(mesh.SkinWeights.getLast())) if (!parseDataObjectSkinWeights(mesh)) return false; - } - else - { + } else { os::Printer::log("Unknown data object in mesh in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; @@ -1091,15 +929,13 @@ bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) return true; } - bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh skin weights", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Skin Weights found in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1107,26 +943,24 @@ bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) core::stringc TransformNodeName; - if (!getNextTokenAsString(TransformNodeName)) - { + if (!getNextTokenAsString(TransformNodeName)) { os::Printer::log("Unknown syntax while reading transform node name string in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - mesh.HasSkinning=true; + mesh.HasSkinning = true; auto n = AnimatedMesh->getJointNumber(TransformNodeName.c_str()); CSkinnedMesh::SJoint *joint = n.has_value() ? AnimatedMesh->getAllJoints()[*n] : nullptr; - if (!joint) - { + if (!joint) { #ifdef _XREADER_DEBUG os::Printer::log("creating joint for skinning ", TransformNodeName.c_str(), ELL_DEBUG); #endif n = AnimatedMesh->getAllJoints().size(); - joint=AnimatedMesh->addJoint(0); - joint->Name=TransformNodeName.c_str(); + joint = AnimatedMesh->addJoint(0); + joint->Name = TransformNodeName.c_str(); } // read vertex weights @@ -1136,25 +970,24 @@ bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) u32 i; const u32 jointStart = joint->Weights.size(); - joint->Weights.reallocate(jointStart+nWeights); + joint->Weights.reallocate(jointStart + nWeights); - mesh.WeightJoint.reallocate( mesh.WeightJoint.size() + nWeights ); - mesh.WeightNum.reallocate( mesh.WeightNum.size() + nWeights ); + mesh.WeightJoint.reallocate(mesh.WeightJoint.size() + nWeights); + mesh.WeightNum.reallocate(mesh.WeightNum.size() + nWeights); - for (i=0; iWeights.size()); - CSkinnedMesh::SWeight *weight=AnimatedMesh->addWeight(joint); + CSkinnedMesh::SWeight *weight = AnimatedMesh->addWeight(joint); - weight->buffer_id=0; - weight->vertex_id=readInt(); + weight->buffer_id = 0; + weight->vertex_id = readInt(); } // read vertex weights - for (i=jointStart; iWeights[i].strength = readFloat(); // read matrix offset @@ -1162,18 +995,16 @@ bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) // transforms the mesh vertices to the space of the bone // When concatenated to the bone's transform, this provides the // world space coordinates of the mesh as affected by the bone - core::matrix4& MatrixOffset = joint->GlobalInversedMatrix; + core::matrix4 &MatrixOffset = joint->GlobalInversedMatrix; readMatrix(MatrixOffset); - if (!checkForOneFollowingSemicolons()) - { + if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Skin Weights found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Skin Weights found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1182,15 +1013,13 @@ bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) return true; } - -bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh& mesh) +bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading skin mesh header", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Skin Mesh header found in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1203,8 +1032,7 @@ bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh& mesh) if (!BinaryFormat) getNextToken(); // skip semicolon - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in skin mesh header in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1213,15 +1041,13 @@ bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh& mesh) return true; } - bool CXMeshFileLoader::parseDataObjectMeshNormals(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading mesh normals", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Normals found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1233,11 +1059,10 @@ bool CXMeshFileLoader::parseDataObjectMeshNormals(SXMesh &mesh) normals.set_used(nNormals); // read normals - for (u32 i=0; i= mesh.IndexCountPerFace.size()) + // if (nFNormals >= mesh.IndexCountPerFace.size()) if (0) // this condition doesn't work for some reason { os::Printer::log("Too many face normals found in x file", ELL_WARNING); @@ -1257,52 +1082,43 @@ bool CXMeshFileLoader::parseDataObjectMeshNormals(SXMesh &mesh) u32 normalidx = 0; core::array polygonfaces; - for (u32 k=0; k= mesh.Vertices.size()) + // if (nCoords >= mesh.Vertices.size()) if (0) // this condition doesn't work for some reason { os::Printer::log("Too many texture coords found in x file", ELL_WARNING); @@ -1334,17 +1148,15 @@ bool CXMeshFileLoader::parseDataObjectMeshTextureCoords(SXMesh &mesh) SET_ERR_AND_RETURN(); } - for (u32 i=0; i=mesh.Vertices.size()) - { + for (u32 i = 0; i < nColors; ++i) { + const u32 Index = readInt(); + if (Index >= mesh.Vertices.size()) { os::Printer::log("index value in parseDataObjectMeshVertexColors out of bounds", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1382,14 +1190,12 @@ bool CXMeshFileLoader::parseDataObjectMeshVertexColors(SXMesh &mesh) checkForOneFollowingSemicolons(); } - if (!checkForOneFollowingSemicolons()) - { + if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Vertex Colors Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Mesh Texture Coordinates Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); return false; @@ -1398,15 +1204,13 @@ bool CXMeshFileLoader::parseDataObjectMeshVertexColors(SXMesh &mesh) return true; } - bool CXMeshFileLoader::parseDataObjectMeshMaterialList(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh material list", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Material List found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1422,25 +1226,23 @@ bool CXMeshFileLoader::parseDataObjectMeshMaterialList(SXMesh &mesh) // There seems to be a compact representation of "all faces the same material" // being represented as 1;1;0;; which means 1 material, 1 face with first material // all the other faces have to obey then, so check is disabled - //if (nFaceIndices != mesh.IndexCountPerFace.size()) + // if (nFaceIndices != mesh.IndexCountPerFace.size()) // os::Printer::log("Index count per face not equal to face material index count in x file.", ELL_WARNING); // read non triangulated face indices and create triangulated ones - mesh.FaceMaterialIndices.set_used( mesh.Indices.size() / 3); + mesh.FaceMaterialIndices.set_used(mesh.Indices.size() / 3); u32 triangulatedindex = 0; u32 ind = 0; - for (u32 tfi=0; tfi= core::max_(nMaterials, 1U)) - { + if (ind >= core::max_(nMaterials, 1U)) { os::Printer::log("Out of range index found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - const u32 fc = mesh.IndexCountPerFace[tfi]/3; - for (u32 k=0; kaddJoint(0); - joint->Name=FrameName.c_str(); + joint = AnimatedMesh->addJoint(0); + joint->Name = FrameName.c_str(); } - joint->PositionKeys.reallocate(joint->PositionKeys.size()+animationDump.PositionKeys.size()); - for (u32 n=0; nPositionKeys.reallocate(joint->PositionKeys.size() + animationDump.PositionKeys.size()); + for (u32 n = 0; n < animationDump.PositionKeys.size(); ++n) { joint->PositionKeys.push_back(animationDump.PositionKeys[n]); } - joint->ScaleKeys.reallocate(joint->ScaleKeys.size()+animationDump.ScaleKeys.size()); - for (u32 n=0; nScaleKeys.reallocate(joint->ScaleKeys.size() + animationDump.ScaleKeys.size()); + for (u32 n = 0; n < animationDump.ScaleKeys.size(); ++n) { joint->ScaleKeys.push_back(animationDump.ScaleKeys[n]); } - joint->RotationKeys.reallocate(joint->RotationKeys.size()+animationDump.RotationKeys.size()); - for (u32 n=0; nRotationKeys.reallocate(joint->RotationKeys.size() + animationDump.RotationKeys.size()); + for (u32 n = 0; n < animationDump.RotationKeys.size(); ++n) { joint->RotationKeys.push_back(animationDump.RotationKeys[n]); } - } - else + } else os::Printer::log("joint name was never given", ELL_WARNING); return true; } - bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading animation key", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Animation Key found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1709,8 +1455,7 @@ bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint) const u32 keyType = readInt(); - if (keyType > 4) - { + if (keyType > 4) { os::Printer::log("Unknown key type found in Animation Key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1724,140 +1469,124 @@ bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint) if (numberOfKeys == 0) checkForOneFollowingSemicolons(); - for (u32 i=0; iaddRotationKey(joint); - key->frame=time; - key->rotation.set(X,Y,Z,W); - key->rotation.normalize(); + // read count + if (readInt() != 4) { + os::Printer::log("Expected 4 numbers in animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); + SET_ERR_AND_RETURN(); } - break; - case 1: //scale - case 2: //position - { - // read vectors - // read count - if (readInt() != 3) - { - os::Printer::log("Expected 3 numbers in animation key in x file", ELL_WARNING); - os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); - SET_ERR_AND_RETURN(); - } + f32 W = -readFloat(); + f32 X = -readFloat(); + f32 Y = -readFloat(); + f32 Z = -readFloat(); - core::vector3df vector; - readVector3(vector); - - if (!checkForTwoFollowingSemicolons()) - { - os::Printer::log("No finishing semicolon after vector animation key in x file", ELL_WARNING); - os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); - } - - if (keyType==2) - { - ISkinnedMesh::SPositionKey *key=AnimatedMesh->addPositionKey(joint); - key->frame=time; - key->position=vector; - } - else - { - ISkinnedMesh::SScaleKey *key=AnimatedMesh->addScaleKey(joint); - key->frame=time; - key->scale=vector; - } + if (!checkForTwoFollowingSemicolons()) { + os::Printer::log("No finishing semicolon after quaternion animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); } - break; + + ISkinnedMesh::SRotationKey *key = AnimatedMesh->addRotationKey(joint); + key->frame = time; + key->rotation.set(X, Y, Z, W); + key->rotation.normalize(); + } break; + case 1: // scale + case 2: // position + { + // read vectors + + // read count + if (readInt() != 3) { + os::Printer::log("Expected 3 numbers in animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); + SET_ERR_AND_RETURN(); + } + + core::vector3df vector; + readVector3(vector); + + if (!checkForTwoFollowingSemicolons()) { + os::Printer::log("No finishing semicolon after vector animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); + } + + if (keyType == 2) { + ISkinnedMesh::SPositionKey *key = AnimatedMesh->addPositionKey(joint); + key->frame = time; + key->position = vector; + } else { + ISkinnedMesh::SScaleKey *key = AnimatedMesh->addScaleKey(joint); + key->frame = time; + key->scale = vector; + } + } break; case 3: - case 4: - { - // read matrix + case 4: { + // read matrix - // read count - if (readInt() != 16) - { - os::Printer::log("Expected 16 numbers in animation key in x file", ELL_WARNING); - os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); - SET_ERR_AND_RETURN(); - } - - // read matrix - core::matrix4 mat(core::matrix4::EM4CONST_NOTHING); - readMatrix(mat); - - //mat=joint->LocalMatrix*mat; - - if (!checkForOneFollowingSemicolons()) - { - os::Printer::log("No finishing semicolon after matrix animation key in x file", ELL_WARNING); - os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); - } - - //core::vector3df rotation = mat.getRotationDegrees(); - - ISkinnedMesh::SRotationKey *keyR=AnimatedMesh->addRotationKey(joint); - keyR->frame=time; - - // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched from mat to mat.getTransposed() for downward compatibility. - // Not tested so far if this was correct or wrong before quaternion fix! - keyR->rotation= core::quaternion(mat.getTransposed()); - - ISkinnedMesh::SPositionKey *keyP=AnimatedMesh->addPositionKey(joint); - keyP->frame=time; - keyP->position=mat.getTranslation(); - -/* - core::vector3df scale=mat.getScale(); - - if (scale.X==0) - scale.X=1; - if (scale.Y==0) - scale.Y=1; - if (scale.Z==0) - scale.Z=1; - ISkinnedMesh::SScaleKey *keyS=AnimatedMesh->addScaleKey(joint); - keyS->frame=time; - keyS->scale=scale; -*/ + // read count + if (readInt() != 16) { + os::Printer::log("Expected 16 numbers in animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); + SET_ERR_AND_RETURN(); } - break; + + // read matrix + core::matrix4 mat(core::matrix4::EM4CONST_NOTHING); + readMatrix(mat); + + // mat=joint->LocalMatrix*mat; + + if (!checkForOneFollowingSemicolons()) { + os::Printer::log("No finishing semicolon after matrix animation key in x file", ELL_WARNING); + os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); + } + + // core::vector3df rotation = mat.getRotationDegrees(); + + ISkinnedMesh::SRotationKey *keyR = AnimatedMesh->addRotationKey(joint); + keyR->frame = time; + + // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched from mat to mat.getTransposed() for downward compatibility. + // Not tested so far if this was correct or wrong before quaternion fix! + keyR->rotation = core::quaternion(mat.getTransposed()); + + ISkinnedMesh::SPositionKey *keyP = AnimatedMesh->addPositionKey(joint); + keyP->frame = time; + keyP->position = mat.getTranslation(); + + /* + core::vector3df scale=mat.getScale(); + + if (scale.X==0) + scale.X=1; + if (scale.Y==0) + scale.Y=1; + if (scale.Z==0) + scale.Z=1; + ISkinnedMesh::SScaleKey *keyS=AnimatedMesh->addScaleKey(joint); + keyS->frame=time; + keyS->scale=scale; + */ + } break; } // end switch } if (!checkForOneFollowingSemicolons()) --P; - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1866,29 +1595,25 @@ bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint) return true; } - -bool CXMeshFileLoader::parseDataObjectTextureFilename(core::stringc& texturename) +bool CXMeshFileLoader::parseDataObjectTextureFilename(core::stringc &texturename) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading texture filename", ELL_DEBUG); #endif - if (!readHeadOfDataObject()) - { + if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Texture filename found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - if (!getNextTokenAsString(texturename)) - { + if (!getNextTokenAsString(texturename)) { os::Printer::log("Unknown syntax while reading texture filename string in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); } - if (!checkForClosingBrace()) - { + if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Texture filename found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING); SET_ERR_AND_RETURN(); @@ -1897,12 +1622,10 @@ bool CXMeshFileLoader::parseDataObjectTextureFilename(core::stringc& texturename return true; } - bool CXMeshFileLoader::parseUnknownDataObject() { // find opening delimiter - while(true) - { + while (true) { core::stringc t = getNextToken(); if (t.size() == 0) @@ -1916,8 +1639,7 @@ bool CXMeshFileLoader::parseUnknownDataObject() // parse until closing delimiter - while(counter) - { + while (counter) { core::stringc t = getNextToken(); if (t.size() == 0) @@ -1925,22 +1647,19 @@ bool CXMeshFileLoader::parseUnknownDataObject() if (t == "{") ++counter; - else - if (t == "}") + else if (t == "}") --counter; } return true; } - //! checks for closing curly brace, returns false if not there bool CXMeshFileLoader::checkForClosingBrace() { return (getNextToken() == "}"); } - //! checks for one following semicolon, returns false if not there bool CXMeshFileLoader::checkForOneFollowingSemicolons() { @@ -1949,24 +1668,20 @@ bool CXMeshFileLoader::checkForOneFollowingSemicolons() if (getNextToken() == ";") return true; - else - { + else { --P; return false; } } - //! checks for two following semicolons, returns false if they are not there bool CXMeshFileLoader::checkForTwoFollowingSemicolons() { if (BinaryFormat) return true; - for (u32 k=0; k<2; ++k) - { - if (getNextToken() != ";") - { + for (u32 k = 0; k < 2; ++k) { + if (getNextToken() != ";") { --P; return false; } @@ -1975,15 +1690,13 @@ bool CXMeshFileLoader::checkForTwoFollowingSemicolons() return true; } - //! reads header of dataobject including the opening brace. //! returns false if error happened, and writes name of object //! if there is one -bool CXMeshFileLoader::readHeadOfDataObject(core::stringc* outname) +bool CXMeshFileLoader::readHeadOfDataObject(core::stringc *outname) { core::stringc nameOrBrace = getNextToken(); - if (nameOrBrace != "{") - { + if (nameOrBrace != "{") { if (outname) (*outname) = nameOrBrace; @@ -1994,15 +1707,13 @@ bool CXMeshFileLoader::readHeadOfDataObject(core::stringc* outname) return true; } - //! returns next parseable token. Returns empty string if no token there core::stringc CXMeshFileLoader::getNextToken() { core::stringc s; // process binary-formatted file - if (BinaryFormat) - { + if (BinaryFormat) { // in binary mode it will only return NAME and STRING token // and (correctly) skip over other tokens. @@ -2011,101 +1722,97 @@ core::stringc CXMeshFileLoader::getNextToken() // standalone tokens switch (tok) { - case 1: - // name token - len = readBinDWord(); - s = core::stringc(P, len); - P += len; - return s; - case 2: - // string token - len = readBinDWord(); - s = core::stringc(P, len); - P += (len + 2); - return s; - case 3: - // integer token - P += 4; - return ""; - case 5: - // GUID token - P += 16; - return ""; - case 6: - len = readBinDWord(); - P += (len * 4); - return ""; - case 7: - len = readBinDWord(); - P += (len * FloatSize); - return ""; - case 0x0a: - return "{"; - case 0x0b: - return "}"; - case 0x0c: - return "("; - case 0x0d: - return ")"; - case 0x0e: - return "["; - case 0x0f: - return "]"; - case 0x10: - return "<"; - case 0x11: - return ">"; - case 0x12: - return "."; - case 0x13: - return ","; - case 0x14: - return ";"; - case 0x1f: - return "template"; - case 0x28: - return "WORD"; - case 0x29: - return "DWORD"; - case 0x2a: - return "FLOAT"; - case 0x2b: - return "DOUBLE"; - case 0x2c: - return "CHAR"; - case 0x2d: - return "UCHAR"; - case 0x2e: - return "SWORD"; - case 0x2f: - return "SDWORD"; - case 0x30: - return "void"; - case 0x31: - return "string"; - case 0x32: - return "unicode"; - case 0x33: - return "cstring"; - case 0x34: - return "array"; + case 1: + // name token + len = readBinDWord(); + s = core::stringc(P, len); + P += len; + return s; + case 2: + // string token + len = readBinDWord(); + s = core::stringc(P, len); + P += (len + 2); + return s; + case 3: + // integer token + P += 4; + return ""; + case 5: + // GUID token + P += 16; + return ""; + case 6: + len = readBinDWord(); + P += (len * 4); + return ""; + case 7: + len = readBinDWord(); + P += (len * FloatSize); + return ""; + case 0x0a: + return "{"; + case 0x0b: + return "}"; + case 0x0c: + return "("; + case 0x0d: + return ")"; + case 0x0e: + return "["; + case 0x0f: + return "]"; + case 0x10: + return "<"; + case 0x11: + return ">"; + case 0x12: + return "."; + case 0x13: + return ","; + case 0x14: + return ";"; + case 0x1f: + return "template"; + case 0x28: + return "WORD"; + case 0x29: + return "DWORD"; + case 0x2a: + return "FLOAT"; + case 0x2b: + return "DOUBLE"; + case 0x2c: + return "CHAR"; + case 0x2d: + return "UCHAR"; + case 0x2e: + return "SWORD"; + case 0x2f: + return "SDWORD"; + case 0x30: + return "void"; + case 0x31: + return "string"; + case 0x32: + return "unicode"; + case 0x33: + return "cstring"; + case 0x34: + return "array"; } } // process text-formatted file - else - { + else { findNextNoneWhiteSpace(); if (P >= End) return s; - while((P < End) && !core::isspace(P[0])) - { + while ((P < End) && !core::isspace(P[0])) { // either keep token delimiters when already holding a token, or return if first valid char - if (P[0]==';' || P[0]=='}' || P[0]=='{' || P[0]==',') - { - if (!s.size()) - { + if (P[0] == ';' || P[0] == '}' || P[0] == '{' || P[0] == ',') { + if (!s.size()) { s.append(P[0]); ++P; } @@ -2118,7 +1825,6 @@ core::stringc CXMeshFileLoader::getNextToken() return s; } - //! places pointer to next begin of a token, which must be a number, // and ignores comments void CXMeshFileLoader::findNextNoneWhiteSpaceNumber() @@ -2126,9 +1832,8 @@ void CXMeshFileLoader::findNextNoneWhiteSpaceNumber() if (BinaryFormat) return; - while((P < End) && (P[0] != '-') && (P[0] != '.') && - !( core::isdigit(P[0]))) - { + while ((P < End) && (P[0] != '-') && (P[0] != '.') && + !(core::isdigit(P[0]))) { // check if this is a comment if ((P[0] == '/' && P[1] == '/') || P[0] == '#') readUntilEndOfLine(); @@ -2137,18 +1842,15 @@ void CXMeshFileLoader::findNextNoneWhiteSpaceNumber() } } - // places pointer to next begin of a token, and ignores comments void CXMeshFileLoader::findNextNoneWhiteSpace() { if (BinaryFormat) return; - while(true) - { - while((P < End) && core::isspace(P[0])) - { - if (*P=='\n') + while (true) { + while ((P < End) && core::isspace(P[0])) { + if (*P == '\n') ++Line; ++P; } @@ -2158,20 +1860,18 @@ void CXMeshFileLoader::findNextNoneWhiteSpace() // check if this is a comment if ((P[0] == '/' && P[1] == '/') || - P[0] == '#') + P[0] == '#') readUntilEndOfLine(); else break; } } - //! reads a x file style string -bool CXMeshFileLoader::getNextTokenAsString(core::stringc& out) +bool CXMeshFileLoader::getNextTokenAsString(core::stringc &out) { - if (BinaryFormat) - { - out=getNextToken(); + if (BinaryFormat) { + out = getNextToken(); return true; } findNextNoneWhiteSpace(); @@ -2183,29 +1883,25 @@ bool CXMeshFileLoader::getNextTokenAsString(core::stringc& out) return false; ++P; - while(P < End && P[0]!='"') - { + while (P < End && P[0] != '"') { out.append(P[0]); ++P; } - if ( P[1] != ';' || P[0] != '"') + if (P[1] != ';' || P[0] != '"') return false; - P+=2; + P += 2; return true; } - void CXMeshFileLoader::readUntilEndOfLine() { if (BinaryFormat) return; - while(P < End) - { - if (P[0] == '\n' || P[0] == '\r') - { + while (P < End) { + if (P[0] == '\n' || P[0] == '\r') { ++P; ++Line; return; @@ -2215,10 +1911,9 @@ void CXMeshFileLoader::readUntilEndOfLine() } } - u16 CXMeshFileLoader::readBinWord() { - if (P>=End) + if (P >= End) return 0; #ifdef __BIG_ENDIAN__ const u16 tmp = os::Byteswap::byteswap(*(u16 *)P); @@ -2229,10 +1924,9 @@ u16 CXMeshFileLoader::readBinWord() return tmp; } - u32 CXMeshFileLoader::readBinDWord() { - if (P>=End) + if (P >= End) return 0; #ifdef __BIG_ENDIAN__ const u32 tmp = os::Byteswap::byteswap(*(u32 *)P); @@ -2243,13 +1937,10 @@ u32 CXMeshFileLoader::readBinDWord() return tmp; } - u32 CXMeshFileLoader::readInt() { - if (BinaryFormat) - { - if (!BinaryNumCount) - { + if (BinaryFormat) { + if (!BinaryNumCount) { const u16 tmp = readBinWord(); // 0x06 or 0x03 if (tmp == 0x06) BinaryNumCount = readBinDWord(); @@ -2258,21 +1949,16 @@ u32 CXMeshFileLoader::readInt() } --BinaryNumCount; return readBinDWord(); - } - else - { + } else { findNextNoneWhiteSpaceNumber(); return core::strtoul10(P, &P); } } - f32 CXMeshFileLoader::readFloat() { - if (BinaryFormat) - { - if (!BinaryNumCount) - { + if (BinaryFormat) { + if (!BinaryNumCount) { const u16 tmp = readBinWord(); // 0x07 or 0x42 if (tmp == 0x07) BinaryNumCount = readBinDWord(); @@ -2280,22 +1966,19 @@ f32 CXMeshFileLoader::readFloat() BinaryNumCount = 1; // single int } --BinaryNumCount; - if (FloatSize == 8) - { + if (FloatSize == 8) { #ifdef __BIG_ENDIAN__ - //TODO: Check if data is properly converted here + // TODO: Check if data is properly converted here f32 ctmp[2]; - ctmp[1] = os::Byteswap::byteswap(*(f32*)P); - ctmp[0] = os::Byteswap::byteswap(*(f32*)P+4); - const f32 tmp = (f32)(*(f64*)(void*)ctmp); + ctmp[1] = os::Byteswap::byteswap(*(f32 *)P); + ctmp[0] = os::Byteswap::byteswap(*(f32 *)P + 4); + const f32 tmp = (f32)(*(f64 *)(void *)ctmp); #else const f32 tmp = (f32)(*(f64 *)P); #endif P += 8; return tmp; - } - else - { + } else { #ifdef __BIG_ENDIAN__ const f32 tmp = os::Byteswap::byteswap(*(f32 *)P); #else @@ -2311,18 +1994,16 @@ f32 CXMeshFileLoader::readFloat() return ftmp; } - // read 2-dimensional vector. Stops at semicolon after second value for text file format -bool CXMeshFileLoader::readVector2(core::vector2df& vec) +bool CXMeshFileLoader::readVector2(core::vector2df &vec) { vec.X = readFloat(); vec.Y = readFloat(); return true; } - // read 3-dimensional vector. Stops at semicolon after third value for text file format -bool CXMeshFileLoader::readVector3(core::vector3df& vec) +bool CXMeshFileLoader::readVector3(core::vector3df &vec) { vec.X = readFloat(); vec.Y = readFloat(); @@ -2330,9 +2011,8 @@ bool CXMeshFileLoader::readVector3(core::vector3df& vec) return true; } - // read color without alpha value. Stops after second semicolon after blue value -bool CXMeshFileLoader::readRGB(video::SColor& color) +bool CXMeshFileLoader::readRGB(video::SColor &color) { video::SColorf tmpColor; tmpColor.r = readFloat(); @@ -2342,9 +2022,8 @@ bool CXMeshFileLoader::readRGB(video::SColor& color) return checkForOneFollowingSemicolons(); } - // read color with alpha value. Stops after second semicolon after blue value -bool CXMeshFileLoader::readRGBA(video::SColor& color) +bool CXMeshFileLoader::readRGBA(video::SColor &color) { video::SColorf tmpColor; tmpColor.r = readFloat(); @@ -2355,15 +2034,13 @@ bool CXMeshFileLoader::readRGBA(video::SColor& color) return checkForOneFollowingSemicolons(); } - // read matrix from list of floats -bool CXMeshFileLoader::readMatrix(core::matrix4& mat) +bool CXMeshFileLoader::readMatrix(core::matrix4 &mat) { - for (u32 i=0; i<16; ++i) + for (u32 i = 0; i < 16; ++i) mat[i] = readFloat(); return checkForOneFollowingSemicolons(); } - } // end namespace scene } // end namespace irr diff --git a/source/Irrlicht/CXMeshFileLoader.h b/source/Irrlicht/CXMeshFileLoader.h index 67e559df..71180627 100644 --- a/source/Irrlicht/CXMeshFileLoader.h +++ b/source/Irrlicht/CXMeshFileLoader.h @@ -8,12 +8,11 @@ #include "irrString.h" #include "CSkinnedMesh.h" - namespace irr { namespace io { - class IReadFile; +class IReadFile; } // end namespace io namespace scene { @@ -23,23 +22,23 @@ class IMeshManipulator; class CXMeshFileLoader : public IMeshLoader { public: - //! Constructor - CXMeshFileLoader(scene::ISceneManager* smgr); + CXMeshFileLoader(scene::ISceneManager *smgr); //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".cob") - bool isALoadableFileExtension(const io::path& filename) const override; + bool isALoadableFileExtension(const io::path &filename) const override; //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. - IAnimatedMesh* createMesh(io::IReadFile* file) override; + IAnimatedMesh *createMesh(io::IReadFile *file) override; struct SXMesh { - SXMesh() : MaxSkinWeightsPerVertex(0), MaxSkinWeightsPerFace(0), BoneCount(0),AttachedJointID(-1),HasSkinning(false), HasVertexColors(false) {} + SXMesh() : + MaxSkinWeightsPerVertex(0), MaxSkinWeightsPerFace(0), BoneCount(0), AttachedJointID(-1), HasSkinning(false), HasVertexColors(false) {} // this mesh contains triangulated texture data. // because in an .x file, faces can be made of more than 3 // vertices, the indices data structure is triangulated during the @@ -56,7 +55,7 @@ public: core::array IndexCountPerFace; // default 3, but could be more - core::array Buffers; + core::array Buffers; core::array Vertices; core::array TCoords2; @@ -77,10 +76,9 @@ public: }; private: + bool load(io::IReadFile *file); - bool load(io::IReadFile* file); - - bool readFileIntoMemory(io::IReadFile* file); + bool readFileIntoMemory(io::IReadFile *file); bool parseFile(); @@ -114,7 +112,7 @@ private: bool parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint); - bool parseDataObjectTextureFilename(core::stringc& texturename); + bool parseDataObjectTextureFilename(core::stringc &texturename); bool parseUnknownDataObject(); @@ -131,7 +129,7 @@ private: //! reads header of dataobject including the opening brace. //! returns false if error happened, and writes name of object //! if there is one - bool readHeadOfDataObject(core::stringc* outname=0); + bool readHeadOfDataObject(core::stringc *outname = 0); //! checks for closing curly brace, returns false if not there bool checkForClosingBrace(); @@ -143,7 +141,7 @@ private: bool checkForTwoFollowingSemicolons(); //! reads a x file style string - bool getNextTokenAsString(core::stringc& out); + bool getNextTokenAsString(core::stringc &out); void readUntilEndOfLine(); @@ -151,17 +149,17 @@ private: u32 readBinDWord(); u32 readInt(); f32 readFloat(); - bool readVector2(core::vector2df& vec); - bool readVector3(core::vector3df& vec); - bool readMatrix(core::matrix4& mat); - bool readRGB(video::SColor& color); - bool readRGBA(video::SColor& color); + bool readVector2(core::vector2df &vec); + bool readVector3(core::vector3df &vec); + bool readMatrix(core::matrix4 &mat); + bool readRGB(video::SColor &color); + bool readRGBA(video::SColor &color); - CSkinnedMesh* AnimatedMesh; + CSkinnedMesh *AnimatedMesh; - c8* Buffer; - const c8* P; - c8* End; + c8 *Buffer; + const c8 *P; + c8 *End; // counter for number arrays in binary format u32 BinaryNumCount; u32 Line; @@ -171,7 +169,7 @@ private: CSkinnedMesh::SJoint *CurFrame; - core::array Meshes; + core::array Meshes; u32 MajorVersion; u32 MinorVersion; diff --git a/source/Irrlicht/CZipReader.cpp b/source/Irrlicht/CZipReader.cpp index 9aff0fa2..049e02c3 100644 --- a/source/Irrlicht/CZipReader.cpp +++ b/source/Irrlicht/CZipReader.cpp @@ -6,7 +6,6 @@ #include "os.h" - #include "CFileList.h" #include "CReadFile.h" #include "coreutil.h" @@ -18,25 +17,24 @@ namespace irr namespace io { - // ----------------------------------------------------------------------------- // zip loader // ----------------------------------------------------------------------------- //! Constructor -CArchiveLoaderZIP::CArchiveLoaderZIP(io::IFileSystem* fs) -: FileSystem(fs) +CArchiveLoaderZIP::CArchiveLoaderZIP(io::IFileSystem *fs) : + FileSystem(fs) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CArchiveLoaderZIP"); - #endif +#endif } //! returns true if the file maybe is able to be loaded by this class -bool CArchiveLoaderZIP::isALoadableFileFormat(const io::path& filename) const +bool CArchiveLoaderZIP::isALoadableFileFormat(const io::path &filename) const { return core::hasFileExtension(filename, "zip", "pk3") || - core::hasFileExtension(filename, "gz", "tgz"); + core::hasFileExtension(filename, "gz", "tgz"); } //! Check to see if the loader can create archives of this type. @@ -45,17 +43,15 @@ bool CArchiveLoaderZIP::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) cons return (fileType == EFAT_ZIP || fileType == EFAT_GZIP); } - //! Creates an archive from the filename /** \param file File handle to check. \return Pointer to newly created archive, or 0 upon error. */ -IFileArchive* CArchiveLoaderZIP::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const +IFileArchive *CArchiveLoaderZIP::createArchive(const io::path &filename, bool ignoreCase, bool ignorePaths) const { IFileArchive *archive = 0; - io::IReadFile* file = FileSystem->createAndOpenFile(filename); + io::IReadFile *file = FileSystem->createAndOpenFile(filename); - if (file) - { + if (file) { archive = createArchive(file, ignoreCase, ignorePaths); file->drop(); } @@ -65,11 +61,10 @@ IFileArchive* CArchiveLoaderZIP::createArchive(const io::path& filename, bool ig //! creates/loads an archive from the file. //! \return Pointer to the created archive. Returns 0 if loading failed. -IFileArchive* CArchiveLoaderZIP::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const +IFileArchive *CArchiveLoaderZIP::createArchive(io::IReadFile *file, bool ignoreCase, bool ignorePaths) const { IFileArchive *archive = 0; - if (file) - { + if (file) { file->seek(0); u16 sig; @@ -92,39 +87,40 @@ IFileArchive* CArchiveLoaderZIP::createArchive(io::IReadFile* file, bool ignoreC /** Check might look into the file. \param file File handle to check. \return True if file seems to be loadable. */ -bool CArchiveLoaderZIP::isALoadableFileFormat(io::IReadFile* file) const +bool CArchiveLoaderZIP::isALoadableFileFormat(io::IReadFile *file) const { SZIPFileHeader header; - file->read( &header.Sig, 4 ); + file->read(&header.Sig, 4); #ifdef __BIG_ENDIAN__ header.Sig = os::Byteswap::byteswap(header.Sig); #endif - return header.Sig == 0x04034b50 || // ZIP - (header.Sig&0xffff) == 0x8b1f; // gzip + return header.Sig == 0x04034b50 || // ZIP + (header.Sig & 0xffff) == 0x8b1f; // gzip } // ----------------------------------------------------------------------------- // zip archive // ----------------------------------------------------------------------------- -CZipReader::CZipReader(IFileSystem* fs, IReadFile* file, bool ignoreCase, bool ignorePaths, bool isGZip) - : CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), FileSystem(fs), File(file), IsGZip(isGZip) +CZipReader::CZipReader(IFileSystem *fs, IReadFile *file, bool ignoreCase, bool ignorePaths, bool isGZip) : + CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), FileSystem(fs), File(file), IsGZip(isGZip) { - #ifdef _DEBUG +#ifdef _DEBUG setDebugName("CZipReader"); - #endif +#endif - if (File) - { + if (File) { File->grab(); // load file entries if (IsGZip) - while (scanGZipHeader()) { } + while (scanGZipHeader()) { + } else - while (scanZipHeader()) { } + while (scanZipHeader()) { + } sort(); } @@ -136,19 +132,17 @@ CZipReader::~CZipReader() File->drop(); } - //! get the archive type E_FILE_ARCHIVE_TYPE CZipReader::getType() const { return IsGZip ? EFAT_GZIP : EFAT_ZIP; } -const IFileList* CZipReader::getFileList() const +const IFileList *CZipReader::getFileList() const { return this; } - //! scans for a local header, returns false if there is no more local file header. //! The gzip file format seems to think that there can be multiple files in a gzip file //! but none @@ -160,8 +154,7 @@ bool CZipReader::scanGZipHeader() // read header SGZIPMemberHeader header; - if (File->read(&header, sizeof(SGZIPMemberHeader)) == sizeof(SGZIPMemberHeader)) - { + if (File->read(&header, sizeof(SGZIPMemberHeader)) == sizeof(SGZIPMemberHeader)) { #ifdef __BIG_ENDIAN__ header.sig = os::Byteswap::byteswap(header.sig); @@ -173,8 +166,7 @@ bool CZipReader::scanGZipHeader() return false; // now get the file info - if (header.flags & EGZF_EXTRA_FIELDS) - { + if (header.flags & EGZF_EXTRA_FIELDS) { // read lenth of extra data u16 dataLen; @@ -190,38 +182,30 @@ bool CZipReader::scanGZipHeader() io::path ZipFileName = ""; - if (header.flags & EGZF_FILE_NAME) - { + if (header.flags & EGZF_FILE_NAME) { c8 c; File->read(&c, 1); - while (c) - { + while (c) { ZipFileName.append(c); File->read(&c, 1); } - } - else - { + } else { // no file name? ZipFileName = Path; core::deletePathFromFilename(ZipFileName); // rename tgz to tar or remove gz extension - if (core::hasFileExtension(ZipFileName, "tgz")) - { - ZipFileName[ ZipFileName.size() - 2] = 'a'; - ZipFileName[ ZipFileName.size() - 1] = 'r'; - } - else if (core::hasFileExtension(ZipFileName, "gz")) - { - ZipFileName[ ZipFileName.size() - 3] = 0; + if (core::hasFileExtension(ZipFileName, "tgz")) { + ZipFileName[ZipFileName.size() - 2] = 'a'; + ZipFileName[ZipFileName.size() - 1] = 'r'; + } else if (core::hasFileExtension(ZipFileName, "gz")) { + ZipFileName[ZipFileName.size() - 3] = 0; ZipFileName.validate(); } } - if (header.flags & EGZF_COMMENT) - { - c8 c='a'; + if (header.flags & EGZF_COMMENT) { + c8 c = 'a'; while (c) File->read(&c, 1); } @@ -270,17 +254,17 @@ bool CZipReader::scanZipHeader(bool ignoreGPBits) File->read(&entry.header, sizeof(SZIPFileHeader)); #ifdef __BIG_ENDIAN__ - entry.header.Sig = os::Byteswap::byteswap(entry.header.Sig); - entry.header.VersionToExtract = os::Byteswap::byteswap(entry.header.VersionToExtract); - entry.header.GeneralBitFlag = os::Byteswap::byteswap(entry.header.GeneralBitFlag); - entry.header.CompressionMethod = os::Byteswap::byteswap(entry.header.CompressionMethod); - entry.header.LastModFileTime = os::Byteswap::byteswap(entry.header.LastModFileTime); - entry.header.LastModFileDate = os::Byteswap::byteswap(entry.header.LastModFileDate); - entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32); - entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize); - entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize); - entry.header.FilenameLength = os::Byteswap::byteswap(entry.header.FilenameLength); - entry.header.ExtraFieldLength = os::Byteswap::byteswap(entry.header.ExtraFieldLength); + entry.header.Sig = os::Byteswap::byteswap(entry.header.Sig); + entry.header.VersionToExtract = os::Byteswap::byteswap(entry.header.VersionToExtract); + entry.header.GeneralBitFlag = os::Byteswap::byteswap(entry.header.GeneralBitFlag); + entry.header.CompressionMethod = os::Byteswap::byteswap(entry.header.CompressionMethod); + entry.header.LastModFileTime = os::Byteswap::byteswap(entry.header.LastModFileTime); + entry.header.LastModFileDate = os::Byteswap::byteswap(entry.header.LastModFileDate); + entry.header.DataDescriptor.CRC32 = os::Byteswap::byteswap(entry.header.DataDescriptor.CRC32); + entry.header.DataDescriptor.CompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.CompressedSize); + entry.header.DataDescriptor.UncompressedSize = os::Byteswap::byteswap(entry.header.DataDescriptor.UncompressedSize); + entry.header.FilenameLength = os::Byteswap::byteswap(entry.header.FilenameLength); + entry.header.ExtraFieldLength = os::Byteswap::byteswap(entry.header.ExtraFieldLength); #endif if (entry.header.Sig != 0x04034b50) @@ -288,49 +272,45 @@ bool CZipReader::scanZipHeader(bool ignoreGPBits) // read filename { - c8 *tmp = new c8 [ entry.header.FilenameLength + 2 ]; + c8 *tmp = new c8[entry.header.FilenameLength + 2]; File->read(tmp, entry.header.FilenameLength); tmp[entry.header.FilenameLength] = 0; ZipFileName = tmp; - delete [] tmp; + delete[] tmp; } if (entry.header.ExtraFieldLength) File->seek(entry.header.ExtraFieldLength, true); // if bit 3 was set, use CentralDirectory for setup - if (!ignoreGPBits && entry.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR) - { + if (!ignoreGPBits && entry.header.GeneralBitFlag & ZIP_INFO_IN_DATA_DESCRIPTOR) { SZIPFileCentralDirEnd dirEnd; FileInfo.clear(); Files.clear(); // First place where the end record could be stored - File->seek(File->getSize()-22); + File->seek(File->getSize() - 22); const char endID[] = {0x50, 0x4b, 0x05, 0x06, 0x0}; - char tmp[5]={'\0'}; - bool found=false; + char tmp[5] = {'\0'}; + bool found = false; // search for the end record ID - while (!found && File->getPos()>0) - { - int seek=8; + while (!found && File->getPos() > 0) { + int seek = 8; File->read(tmp, 4); - switch (tmp[0]) - { + switch (tmp[0]) { case 0x50: - if (!strcmp(endID, tmp)) - { - seek=4; - found=true; + if (!strcmp(endID, tmp)) { + seek = 4; + found = true; } break; case 0x4b: - seek=5; + seek = 5; break; case 0x05: - seek=6; + seek = 6; break; case 0x06: - seek=7; + seek = 7; break; } File->seek(-seek, true); @@ -347,7 +327,8 @@ bool CZipReader::scanZipHeader(bool ignoreGPBits) #endif FileInfo.reallocate(dirEnd.TotalEntries); File->seek(dirEnd.Offset); - while (scanCentralDirectoryHeader()) { } + while (scanCentralDirectoryHeader()) { + } return false; } @@ -356,17 +337,16 @@ bool CZipReader::scanZipHeader(bool ignoreGPBits) // move forward length of data File->seek(entry.header.DataDescriptor.CompressedSize, true); - #ifdef _DEBUG - //os::Debuginfo::print("added file from archive", ZipFileName.c_str()); - #endif +#ifdef _DEBUG +// os::Debuginfo::print("added file from archive", ZipFileName.c_str()); +#endif - addItem(ZipFileName, entry.Offset, entry.header.DataDescriptor.UncompressedSize, ZipFileName.lastChar()=='/', FileInfo.size()); + addItem(ZipFileName, entry.Offset, entry.header.DataDescriptor.UncompressedSize, ZipFileName.lastChar() == '/', FileInfo.size()); FileInfo.push_back(entry); return true; } - //! scans for a local header, returns false if there is no more local file header. bool CZipReader::scanCentralDirectoryHeader() { @@ -400,17 +380,16 @@ bool CZipReader::scanCentralDirectoryHeader() const long pos = File->getPos(); File->seek(entry.RelativeOffsetOfLocalHeader); scanZipHeader(true); - File->seek(pos+entry.FilenameLength+entry.ExtraFieldLength+entry.FileCommentLength); - FileInfo.getLast().header.DataDescriptor.CompressedSize=entry.CompressedSize; - FileInfo.getLast().header.DataDescriptor.UncompressedSize=entry.UncompressedSize; - FileInfo.getLast().header.DataDescriptor.CRC32=entry.CRC32; - Files.getLast().Size=entry.UncompressedSize; + File->seek(pos + entry.FilenameLength + entry.ExtraFieldLength + entry.FileCommentLength); + FileInfo.getLast().header.DataDescriptor.CompressedSize = entry.CompressedSize; + FileInfo.getLast().header.DataDescriptor.UncompressedSize = entry.UncompressedSize; + FileInfo.getLast().header.DataDescriptor.CRC32 = entry.CRC32; + Files.getLast().Size = entry.UncompressedSize; return true; } - //! opens a file by file name -IReadFile* CZipReader::createAndOpenFile(const io::path& filename) +IReadFile *CZipReader::createAndOpenFile(const io::path &filename) { s32 index = findFile(filename, false); @@ -421,130 +400,119 @@ IReadFile* CZipReader::createAndOpenFile(const io::path& filename) } //! opens a file by index -IReadFile* CZipReader::createAndOpenFile(u32 index) +IReadFile *CZipReader::createAndOpenFile(u32 index) { // Irrlicht supports 0, 8, 12, 14, 99 - //0 - The file is stored (no compression) - //1 - The file is Shrunk - //2 - The file is Reduced with compression factor 1 - //3 - The file is Reduced with compression factor 2 - //4 - The file is Reduced with compression factor 3 - //5 - The file is Reduced with compression factor 4 - //6 - The file is Imploded - //7 - Reserved for Tokenizing compression algorithm - //8 - The file is Deflated - //9 - Reserved for enhanced Deflating - //10 - PKWARE Date Compression Library Imploding - //12 - bzip2 - Compression Method from libbz2, WinZip 10 - //14 - LZMA - Compression Method, WinZip 12 - //96 - Jpeg compression - Compression Method, WinZip 12 - //97 - WavPack - Compression Method, WinZip 11 - //98 - PPMd - Compression Method, WinZip 10 - //99 - AES encryption, WinZip 9 + // 0 - The file is stored (no compression) + // 1 - The file is Shrunk + // 2 - The file is Reduced with compression factor 1 + // 3 - The file is Reduced with compression factor 2 + // 4 - The file is Reduced with compression factor 3 + // 5 - The file is Reduced with compression factor 4 + // 6 - The file is Imploded + // 7 - Reserved for Tokenizing compression algorithm + // 8 - The file is Deflated + // 9 - Reserved for enhanced Deflating + // 10 - PKWARE Date Compression Library Imploding + // 12 - bzip2 - Compression Method from libbz2, WinZip 10 + // 14 - LZMA - Compression Method, WinZip 12 + // 96 - Jpeg compression - Compression Method, WinZip 12 + // 97 - WavPack - Compression Method, WinZip 11 + // 98 - PPMd - Compression Method, WinZip 10 + // 99 - AES encryption, WinZip 9 const SZipFileEntry &e = FileInfo[Files[index].ID]; char buf[64]; - s16 actualCompressionMethod=e.header.CompressionMethod; - IReadFile* decrypted=0; - u8* decryptedBuf=0; - u32 decryptedSize=e.header.DataDescriptor.CompressedSize; - switch(actualCompressionMethod) - { + s16 actualCompressionMethod = e.header.CompressionMethod; + IReadFile *decrypted = 0; + u8 *decryptedBuf = 0; + u32 decryptedSize = e.header.DataDescriptor.CompressedSize; + switch (actualCompressionMethod) { case 0: // no compression - { - if (decrypted) - return decrypted; - else - return createLimitReadFile(Files[index].FullName, File, e.Offset, decryptedSize); - } - case 8: - { - const u32 uncompressedSize = e.header.DataDescriptor.UncompressedSize; - c8* pBuf = new c8[ uncompressedSize ]; - if (!pBuf) - { - snprintf_irr ( buf, 64, "Not enough memory for decompressing %s", Files[index].FullName.c_str() ); - os::Printer::log( buf, ELL_ERROR); - if (decrypted) - decrypted->drop(); - return 0; - } - - u8 *pcData = decryptedBuf; - if (!pcData) - { - pcData = new u8[decryptedSize]; - if (!pcData) - { - snprintf_irr ( buf, 64, "Not enough memory for decompressing %s", Files[index].FullName.c_str() ); - os::Printer::log( buf, ELL_ERROR); - delete [] pBuf; - return 0; - } - - //memset(pcData, 0, decryptedSize); - File->seek(e.Offset); - File->read(pcData, decryptedSize); - } - - // Setup the inflate stream. - z_stream stream; - s32 err; - - stream.next_in = (Bytef*)pcData; - stream.avail_in = (uInt)decryptedSize; - stream.next_out = (Bytef*)pBuf; - stream.avail_out = uncompressedSize; - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - - // Perform inflation. wbits < 0 indicates no zlib header inside the data. - err = inflateInit2(&stream, -MAX_WBITS); - if (err == Z_OK) - { - err = inflate(&stream, Z_FINISH); - inflateEnd(&stream); - if (err == Z_STREAM_END) - err = Z_OK; - err = Z_OK; - inflateEnd(&stream); - } - + { + if (decrypted) + return decrypted; + else + return createLimitReadFile(Files[index].FullName, File, e.Offset, decryptedSize); + } + case 8: { + const u32 uncompressedSize = e.header.DataDescriptor.UncompressedSize; + c8 *pBuf = new c8[uncompressedSize]; + if (!pBuf) { + snprintf_irr(buf, 64, "Not enough memory for decompressing %s", Files[index].FullName.c_str()); + os::Printer::log(buf, ELL_ERROR); if (decrypted) decrypted->drop(); - else - delete[] pcData; + return 0; + } - if (err != Z_OK) - { - snprintf_irr ( buf, 64, "Error decompressing %s", Files[index].FullName.c_str() ); - os::Printer::log( buf, ELL_ERROR); - delete [] pBuf; + u8 *pcData = decryptedBuf; + if (!pcData) { + pcData = new u8[decryptedSize]; + if (!pcData) { + snprintf_irr(buf, 64, "Not enough memory for decompressing %s", Files[index].FullName.c_str()); + os::Printer::log(buf, ELL_ERROR); + delete[] pBuf; return 0; } - else - return FileSystem->createMemoryReadFile(pBuf, uncompressedSize, Files[index].FullName, true); + + // memset(pcData, 0, decryptedSize); + File->seek(e.Offset); + File->read(pcData, decryptedSize); } - case 12: - { - os::Printer::log("bzip2 decompression not supported. File cannot be read.", ELL_ERROR); + + // Setup the inflate stream. + z_stream stream; + s32 err; + + stream.next_in = (Bytef *)pcData; + stream.avail_in = (uInt)decryptedSize; + stream.next_out = (Bytef *)pBuf; + stream.avail_out = uncompressedSize; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + // Perform inflation. wbits < 0 indicates no zlib header inside the data. + err = inflateInit2(&stream, -MAX_WBITS); + if (err == Z_OK) { + err = inflate(&stream, Z_FINISH); + inflateEnd(&stream); + if (err == Z_STREAM_END) + err = Z_OK; + err = Z_OK; + inflateEnd(&stream); + } + + if (decrypted) + decrypted->drop(); + else + delete[] pcData; + + if (err != Z_OK) { + snprintf_irr(buf, 64, "Error decompressing %s", Files[index].FullName.c_str()); + os::Printer::log(buf, ELL_ERROR); + delete[] pBuf; return 0; - } - case 14: - { - os::Printer::log("lzma decompression not supported. File cannot be read.", ELL_ERROR); - return 0; - } + } else + return FileSystem->createMemoryReadFile(pBuf, uncompressedSize, Files[index].FullName, true); + } + case 12: { + os::Printer::log("bzip2 decompression not supported. File cannot be read.", ELL_ERROR); + return 0; + } + case 14: { + os::Printer::log("lzma decompression not supported. File cannot be read.", ELL_ERROR); + return 0; + } case 99: // If we come here with an encrypted file, decryption support is missing os::Printer::log("Decryption support not enabled. File cannot be read.", ELL_ERROR); return 0; default: - snprintf_irr ( buf, 64, "file has unsupported compression method. %s", Files[index].FullName.c_str() ); - os::Printer::log( buf, ELL_ERROR); + snprintf_irr(buf, 64, "file has unsupported compression method. %s", Files[index].FullName.c_str()); + os::Printer::log(buf, ELL_ERROR); return 0; }; - } } // end namespace io diff --git a/source/Irrlicht/CZipReader.h b/source/Irrlicht/CZipReader.h index efabd7a4..ad1b7344 100644 --- a/source/Irrlicht/CZipReader.h +++ b/source/Irrlicht/CZipReader.h @@ -14,209 +14,205 @@ namespace irr { namespace io { - // set if the file is encrypted - const s16 ZIP_FILE_ENCRYPTED = 0x0001; - // the fields crc-32, compressed size and uncompressed size are set to - // zero in the local header - const s16 ZIP_INFO_IN_DATA_DESCRIPTOR = 0x0008; +// set if the file is encrypted +const s16 ZIP_FILE_ENCRYPTED = 0x0001; +// the fields crc-32, compressed size and uncompressed size are set to +// zero in the local header +const s16 ZIP_INFO_IN_DATA_DESCRIPTOR = 0x0008; // byte-align structures #include "irrpack.h" - struct SZIPFileDataDescriptor - { - u32 CRC32; - u32 CompressedSize; - u32 UncompressedSize; - } PACK_STRUCT; +struct SZIPFileDataDescriptor +{ + u32 CRC32; + u32 CompressedSize; + u32 UncompressedSize; +} PACK_STRUCT; - struct SZIPFileHeader - { - u32 Sig; // 'PK0304' little endian (0x04034b50) - s16 VersionToExtract; - s16 GeneralBitFlag; - s16 CompressionMethod; - s16 LastModFileTime; - s16 LastModFileDate; - SZIPFileDataDescriptor DataDescriptor; - s16 FilenameLength; - s16 ExtraFieldLength; - // filename (variable size) - // extra field (variable size ) - } PACK_STRUCT; +struct SZIPFileHeader +{ + u32 Sig; // 'PK0304' little endian (0x04034b50) + s16 VersionToExtract; + s16 GeneralBitFlag; + s16 CompressionMethod; + s16 LastModFileTime; + s16 LastModFileDate; + SZIPFileDataDescriptor DataDescriptor; + s16 FilenameLength; + s16 ExtraFieldLength; + // filename (variable size) + // extra field (variable size ) +} PACK_STRUCT; - struct SZIPFileCentralDirFileHeader - { - u32 Sig; // 'PK0102' (0x02014b50) - u16 VersionMadeBy; - u16 VersionToExtract; - u16 GeneralBitFlag; - u16 CompressionMethod; - u16 LastModFileTime; - u16 LastModFileDate; - u32 CRC32; - u32 CompressedSize; - u32 UncompressedSize; - u16 FilenameLength; - u16 ExtraFieldLength; - u16 FileCommentLength; - u16 DiskNumberStart; - u16 InternalFileAttributes; - u32 ExternalFileAttributes; - u32 RelativeOffsetOfLocalHeader; +struct SZIPFileCentralDirFileHeader +{ + u32 Sig; // 'PK0102' (0x02014b50) + u16 VersionMadeBy; + u16 VersionToExtract; + u16 GeneralBitFlag; + u16 CompressionMethod; + u16 LastModFileTime; + u16 LastModFileDate; + u32 CRC32; + u32 CompressedSize; + u32 UncompressedSize; + u16 FilenameLength; + u16 ExtraFieldLength; + u16 FileCommentLength; + u16 DiskNumberStart; + u16 InternalFileAttributes; + u32 ExternalFileAttributes; + u32 RelativeOffsetOfLocalHeader; - // filename (variable size) - // extra field (variable size) - // file comment (variable size) + // filename (variable size) + // extra field (variable size) + // file comment (variable size) - } PACK_STRUCT; +} PACK_STRUCT; - struct SZIPFileCentralDirEnd - { - u32 Sig; // 'PK0506' end_of central dir signature // (0x06054b50) - u16 NumberDisk; // number of this disk - u16 NumberStart; // number of the disk with the start of the central directory - u16 TotalDisk; // total number of entries in the central dir on this disk - u16 TotalEntries; // total number of entries in the central dir - u32 Size; // size of the central directory - u32 Offset; // offset of start of centraldirectory with respect to the starting disk number - u16 CommentLength; // zipfile comment length - // zipfile comment (variable size) - } PACK_STRUCT; +struct SZIPFileCentralDirEnd +{ + u32 Sig; // 'PK0506' end_of central dir signature // (0x06054b50) + u16 NumberDisk; // number of this disk + u16 NumberStart; // number of the disk with the start of the central directory + u16 TotalDisk; // total number of entries in the central dir on this disk + u16 TotalEntries; // total number of entries in the central dir + u32 Size; // size of the central directory + u32 Offset; // offset of start of centraldirectory with respect to the starting disk number + u16 CommentLength; // zipfile comment length + // zipfile comment (variable size) +} PACK_STRUCT; - struct SZipFileExtraHeader - { - s16 ID; - s16 Size; - } PACK_STRUCT; +struct SZipFileExtraHeader +{ + s16 ID; + s16 Size; +} PACK_STRUCT; - struct SZipFileAESExtraData - { - s16 Version; - u8 Vendor[2]; - u8 EncryptionStrength; - s16 CompressionMode; - } PACK_STRUCT; +struct SZipFileAESExtraData +{ + s16 Version; + u8 Vendor[2]; + u8 EncryptionStrength; + s16 CompressionMode; +} PACK_STRUCT; - enum E_GZIP_FLAGS - { - EGZF_TEXT_DAT = 1, - EGZF_CRC16 = 2, - EGZF_EXTRA_FIELDS = 4, - EGZF_FILE_NAME = 8, - EGZF_COMMENT = 16 - }; +enum E_GZIP_FLAGS +{ + EGZF_TEXT_DAT = 1, + EGZF_CRC16 = 2, + EGZF_EXTRA_FIELDS = 4, + EGZF_FILE_NAME = 8, + EGZF_COMMENT = 16 +}; - struct SGZIPMemberHeader - { - u16 sig; // 0x8b1f - u8 compressionMethod; // 8 = deflate - u8 flags; - u32 time; - u8 extraFlags; // slow compress = 2, fast compress = 4 - u8 operatingSystem; - } PACK_STRUCT; +struct SGZIPMemberHeader +{ + u16 sig; // 0x8b1f + u8 compressionMethod; // 8 = deflate + u8 flags; + u32 time; + u8 extraFlags; // slow compress = 2, fast compress = 4 + u8 operatingSystem; +} PACK_STRUCT; // Default alignment #include "irrunpack.h" - //! Contains extended info about zip files in the archive - struct SZipFileEntry - { - //! Position of data in the archive file - s32 Offset; +//! Contains extended info about zip files in the archive +struct SZipFileEntry +{ + //! Position of data in the archive file + s32 Offset; - //! The header for this file containing compression info etc - SZIPFileHeader header; - }; + //! The header for this file containing compression info etc + SZIPFileHeader header; +}; - //! Archiveloader capable of loading ZIP Archives - class CArchiveLoaderZIP : public IArchiveLoader - { - public: +//! Archiveloader capable of loading ZIP Archives +class CArchiveLoaderZIP : public IArchiveLoader +{ +public: + //! Constructor + CArchiveLoaderZIP(io::IFileSystem *fs); - //! Constructor - CArchiveLoaderZIP(io::IFileSystem* fs); + //! returns true if the file maybe is able to be loaded by this class + //! based on the file extension (e.g. ".zip") + bool isALoadableFileFormat(const io::path &filename) const override; - //! returns true if the file maybe is able to be loaded by this class - //! based on the file extension (e.g. ".zip") - bool isALoadableFileFormat(const io::path& filename) const override; + //! Check if the file might be loaded by this class + /** Check might look into the file. + \param file File handle to check. + \return True if file seems to be loadable. */ + bool isALoadableFileFormat(io::IReadFile *file) const override; - //! Check if the file might be loaded by this class - /** Check might look into the file. - \param file File handle to check. - \return True if file seems to be loadable. */ - bool isALoadableFileFormat(io::IReadFile* file) const override; + //! Check to see if the loader can create archives of this type. + /** Check based on the archive type. + \param fileType The archive type to check. + \return True if the archile loader supports this type, false if not */ + bool isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const override; - //! Check to see if the loader can create archives of this type. - /** Check based on the archive type. - \param fileType The archive type to check. - \return True if the archile loader supports this type, false if not */ - bool isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const override; + //! Creates an archive from the filename + /** \param file File handle to check. + \return Pointer to newly created archive, or 0 upon error. */ + IFileArchive *createArchive(const io::path &filename, bool ignoreCase, bool ignorePaths) const override; - //! Creates an archive from the filename - /** \param file File handle to check. - \return Pointer to newly created archive, or 0 upon error. */ - IFileArchive* createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const override; + //! creates/loads an archive from the file. + //! \return Pointer to the created archive. Returns 0 if loading failed. + io::IFileArchive *createArchive(io::IReadFile *file, bool ignoreCase, bool ignorePaths) const override; - //! creates/loads an archive from the file. - //! \return Pointer to the created archive. Returns 0 if loading failed. - io::IFileArchive* createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const override; - - private: - io::IFileSystem* FileSystem; - }; +private: + io::IFileSystem *FileSystem; +}; /*! Zip file Reader written April 2002 by N.Gebhardt. */ - class CZipReader : public virtual IFileArchive, virtual CFileList - { - public: +class CZipReader : public virtual IFileArchive, virtual CFileList +{ +public: + //! constructor + CZipReader(IFileSystem *fs, IReadFile *file, bool ignoreCase, bool ignorePaths, bool isGZip = false); - //! constructor - CZipReader(IFileSystem* fs, IReadFile* file, bool ignoreCase, bool ignorePaths, bool isGZip=false); + //! destructor + virtual ~CZipReader(); - //! destructor - virtual ~CZipReader(); + //! opens a file by file name + IReadFile *createAndOpenFile(const io::path &filename) override; - //! opens a file by file name - IReadFile* createAndOpenFile(const io::path& filename) override; + //! opens a file by index + IReadFile *createAndOpenFile(u32 index) override; - //! opens a file by index - IReadFile* createAndOpenFile(u32 index) override; + //! returns the list of files + const IFileList *getFileList() const override; - //! returns the list of files - const IFileList* getFileList() const override; + //! get the archive type + E_FILE_ARCHIVE_TYPE getType() const override; - //! get the archive type - E_FILE_ARCHIVE_TYPE getType() const override; + //! return the id of the file Archive + const io::path &getArchiveName() const override { return Path; } - //! return the id of the file Archive - const io::path& getArchiveName() const override {return Path;} +protected: + //! reads the next file header from a ZIP file, returns false if there are no more headers. + /* if ignoreGPBits is set, the item will be read despite missing + file information. This is used when reading items from the central + directory. */ + bool scanZipHeader(bool ignoreGPBits = false); - protected: + //! the same but for gzip files + bool scanGZipHeader(); - //! reads the next file header from a ZIP file, returns false if there are no more headers. - /* if ignoreGPBits is set, the item will be read despite missing - file information. This is used when reading items from the central - directory. */ - bool scanZipHeader(bool ignoreGPBits=false); + bool scanCentralDirectoryHeader(); - //! the same but for gzip files - bool scanGZipHeader(); + io::IFileSystem *FileSystem; + IReadFile *File; - bool scanCentralDirectoryHeader(); - - io::IFileSystem* FileSystem; - IReadFile* File; - - // holds extended info about files - core::array FileInfo; - - bool IsGZip; - }; + // holds extended info about files + core::array FileInfo; + bool IsGZip; +}; } // end namespace io } // end namespace irr diff --git a/source/Irrlicht/IAttribute.h b/source/Irrlicht/IAttribute.h index c0f6f7b1..b0dc76ee 100644 --- a/source/Irrlicht/IAttribute.h +++ b/source/Irrlicht/IAttribute.h @@ -15,7 +15,6 @@ #include "irrArray.h" #include "EAttributes.h" - namespace irr { namespace io @@ -33,16 +32,15 @@ namespace io class IAttribute : public virtual IReferenceCounted { public: + virtual ~IAttribute(){}; - virtual ~IAttribute() {}; + virtual s32 getInt() const { return 0; } + virtual f32 getFloat() const { return 0; } + virtual bool getBool() const { return false; } - virtual s32 getInt() const { return 0; } - virtual f32 getFloat() const { return 0; } - virtual bool getBool() const { return false; } - - virtual void setInt(s32 intValue) {}; - virtual void setFloat(f32 floatValue) {}; - virtual void setBool(bool boolValue) {}; + virtual void setInt(s32 intValue){}; + virtual void setFloat(f32 floatValue){}; + virtual void setBool(bool boolValue){}; core::stringc Name; diff --git a/source/Irrlicht/Irrlicht.cpp b/source/Irrlicht/Irrlicht.cpp index 53d3f28a..cde03c34 100644 --- a/source/Irrlicht/Irrlicht.cpp +++ b/source/Irrlicht/Irrlicht.cpp @@ -2,18 +2,17 @@ // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h - -static const char* const copyright = "Irrlicht Engine (c) 2002-2017 Nikolaus Gebhardt"; // put string in binary +static const char *const copyright = "Irrlicht Engine (c) 2002-2017 Nikolaus Gebhardt"; // put string in binary #ifdef _IRR_WINDOWS_ - #include - #if defined(_DEBUG) && !defined(__GNUWIN32__) - #include - #endif // _DEBUG +#include +#if defined(_DEBUG) && !defined(__GNUWIN32__) +#include +#endif // _DEBUG #endif #include "irrlicht.h" -#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ +#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ #include "CIrrDeviceWin32.h" #endif @@ -35,125 +34,128 @@ static const char* const copyright = "Irrlicht Engine (c) 2002-2017 Nikolaus Geb namespace irr { - //! stub for calling createDeviceEx - IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDevice(video::E_DRIVER_TYPE driverType, - const core::dimension2d& windowSize, - u32 bits, bool fullscreen, - bool stencilbuffer, bool vsync, IEventReceiver* res) - { - (void)copyright; // prevent unused variable warning +//! stub for calling createDeviceEx +IRRLICHT_API IrrlichtDevice *IRRCALLCONV createDevice(video::E_DRIVER_TYPE driverType, + const core::dimension2d &windowSize, + u32 bits, bool fullscreen, + bool stencilbuffer, bool vsync, IEventReceiver *res) +{ + (void)copyright; // prevent unused variable warning - SIrrlichtCreationParameters p; - p.DriverType = driverType; - p.WindowSize = windowSize; - p.Bits = (u8)bits; - p.Fullscreen = fullscreen; - p.Stencilbuffer = stencilbuffer; - p.Vsync = vsync; - p.EventReceiver = res; + SIrrlichtCreationParameters p; + p.DriverType = driverType; + p.WindowSize = windowSize; + p.Bits = (u8)bits; + p.Fullscreen = fullscreen; + p.Stencilbuffer = stencilbuffer; + p.Vsync = vsync; + p.EventReceiver = res; - return createDeviceEx(p); - } + return createDeviceEx(p); +} - extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDeviceEx(const SIrrlichtCreationParameters& params) - { +extern "C" IRRLICHT_API IrrlichtDevice *IRRCALLCONV createDeviceEx(const SIrrlichtCreationParameters ¶ms) +{ - IrrlichtDevice* dev = 0; + IrrlichtDevice *dev = 0; -#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ - if (params.DeviceType == EIDT_WIN32 || (!dev && params.DeviceType == EIDT_BEST)) - dev = new CIrrDeviceWin32(params); +#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ + if (params.DeviceType == EIDT_WIN32 || (!dev && params.DeviceType == EIDT_BEST)) + dev = new CIrrDeviceWin32(params); #endif #ifdef _IRR_COMPILE_WITH_OSX_DEVICE_ - if (params.DeviceType == EIDT_OSX || (!dev && params.DeviceType == EIDT_BEST)) - dev = new CIrrDeviceMacOSX(params); + if (params.DeviceType == EIDT_OSX || (!dev && params.DeviceType == EIDT_BEST)) + dev = new CIrrDeviceMacOSX(params); #endif #ifdef _IRR_COMPILE_WITH_X11_DEVICE_ - if (params.DeviceType == EIDT_X11 || (!dev && params.DeviceType == EIDT_BEST)) - dev = new CIrrDeviceLinux(params); + if (params.DeviceType == EIDT_X11 || (!dev && params.DeviceType == EIDT_BEST)) + dev = new CIrrDeviceLinux(params); #endif #ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_ - if (params.DeviceType == EIDT_ANDROID || (!dev && params.DeviceType == EIDT_BEST)) - dev = new CIrrDeviceAndroid(params); + if (params.DeviceType == EIDT_ANDROID || (!dev && params.DeviceType == EIDT_BEST)) + dev = new CIrrDeviceAndroid(params); #endif #ifdef _IRR_COMPILE_WITH_SDL_DEVICE_ - if (params.DeviceType == EIDT_SDL || (!dev && params.DeviceType == EIDT_BEST)) - dev = new CIrrDeviceSDL(params); + if (params.DeviceType == EIDT_SDL || (!dev && params.DeviceType == EIDT_BEST)) + dev = new CIrrDeviceSDL(params); #endif - if (dev && !dev->getVideoDriver() && params.DriverType != video::EDT_NULL) - { - dev->closeDevice(); // destroy window - dev->run(); // consume quit message - dev->drop(); - dev = 0; - } - - return dev; + if (dev && !dev->getVideoDriver() && params.DriverType != video::EDT_NULL) { + dev->closeDevice(); // destroy window + dev->run(); // consume quit message + dev->drop(); + dev = 0; } + return dev; +} + namespace core { - const matrix4 IdentityMatrix(matrix4::EM4CONST_IDENTITY); +const matrix4 IdentityMatrix(matrix4::EM4CONST_IDENTITY); } namespace video { - SMaterial IdentityMaterial; +SMaterial IdentityMaterial; - extern "C" IRRLICHT_API bool IRRCALLCONV isDriverSupported(E_DRIVER_TYPE driver) - { - switch (driver) { - case EDT_NULL: return true; +extern "C" IRRLICHT_API bool IRRCALLCONV isDriverSupported(E_DRIVER_TYPE driver) +{ + switch (driver) { + case EDT_NULL: + return true; #ifdef ENABLE_OPENGL3 - case EDT_OPENGL3: return true; + case EDT_OPENGL3: + return true; #endif #ifdef _IRR_COMPILE_WITH_OPENGL_ - case EDT_OPENGL: return true; + case EDT_OPENGL: + return true; #endif #ifdef _IRR_COMPILE_WITH_OGLES1_ - case EDT_OGLES1: return true; + case EDT_OGLES1: + return true; #endif #ifdef _IRR_COMPILE_WITH_OGLES2_ - case EDT_OGLES2: return true; + case EDT_OGLES2: + return true; #endif #ifdef _IRR_COMPILE_WITH_WEBGL1_ - case EDT_WEBGL1: return true; + case EDT_WEBGL1: + return true; #endif - default: return false; - } + default: + return false; } } +} } // end namespace irr - #if defined(_IRR_WINDOWS_API_) && !defined(_IRR_STATIC_LIB_) -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved ) +BOOL APIENTRY DllMain(HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved) { // _crtBreakAlloc = 139; - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - #if defined(_DEBUG) && !defined(__GNUWIN32__) - _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF); - #endif - break; - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: +#if defined(_DEBUG) && !defined(__GNUWIN32__) + _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF); +#endif + break; + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; } #endif // defined(_IRR_WINDOWS_) - diff --git a/source/Irrlicht/KHR/khrplatform.h b/source/Irrlicht/KHR/khrplatform.h index 01646449..84821e08 100644 --- a/source/Irrlicht/KHR/khrplatform.h +++ b/source/Irrlicht/KHR/khrplatform.h @@ -91,7 +91,7 @@ */ #if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) -# define KHRONOS_STATIC 1 +#define KHRONOS_STATIC 1 #endif /*------------------------------------------------------------------------- @@ -100,17 +100,17 @@ * This precedes the return type of the function in the function prototype. */ #if defined(KHRONOS_STATIC) - /* If the preprocessor constant KHRONOS_STATIC is defined, make the - * header compatible with static linking. */ -# define KHRONOS_APICALL +/* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +#define KHRONOS_APICALL #elif defined(_WIN32) -# define KHRONOS_APICALL __declspec(dllimport) -#elif defined (__SYMBIAN32__) -# define KHRONOS_APICALL IMPORT_C +#define KHRONOS_APICALL __declspec(dllimport) +#elif defined(__SYMBIAN32__) +#define KHRONOS_APICALL IMPORT_C #elif defined(__ANDROID__) -# define KHRONOS_APICALL __attribute__((visibility("default"))) +#define KHRONOS_APICALL __attribute__((visibility("default"))) #else -# define KHRONOS_APICALL +#define KHRONOS_APICALL #endif /*------------------------------------------------------------------------- @@ -120,10 +120,10 @@ * name in the function prototype. */ #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) - /* Win32 but not WinCE */ -# define KHRONOS_APIENTRY __stdcall +/* Win32 but not WinCE */ +#define KHRONOS_APIENTRY __stdcall #else -# define KHRONOS_APIENTRY +#define KHRONOS_APIENTRY #endif /*------------------------------------------------------------------------- @@ -131,7 +131,7 @@ *------------------------------------------------------------------------- * This follows the closing parenthesis of the function prototype arguments. */ -#if defined (__ARMCC_2__) +#if defined(__ARMCC_2__) #define KHRONOS_APIATTRIBUTES __softfp #else #define KHRONOS_APIATTRIBUTES @@ -142,17 +142,16 @@ *-----------------------------------------------------------------------*/ #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) - /* * Using */ #include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 /* * To support platform where unsigned long cannot be used interchangeably with * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. @@ -168,57 +167,57 @@ typedef uint64_t khronos_uint64_t; #endif #endif -#elif defined(__VMS ) || defined(__sgi) +#elif defined(__VMS) || defined(__sgi) /* * Using */ #include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 #elif defined(_WIN32) && !defined(__SCITECH_SNAP__) /* * Win32 */ -typedef __int32 khronos_int32_t; -typedef unsigned __int32 khronos_uint32_t; -typedef __int64 khronos_int64_t; -typedef unsigned __int64 khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 #elif defined(__sun__) || defined(__digital__) /* * Sun or Digital */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; #if defined(__arch64__) || defined(_LP64) -typedef long int khronos_int64_t; -typedef unsigned long int khronos_uint64_t; +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; #else -typedef long long int khronos_int64_t; -typedef unsigned long long int khronos_uint64_t; +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; #endif /* __arch64__ */ -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 #elif 0 /* * Hypothetical platform with no float or int64 support */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#define KHRONOS_SUPPORT_INT64 0 -#define KHRONOS_SUPPORT_FLOAT 0 +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 #else @@ -226,23 +225,22 @@ typedef unsigned int khronos_uint32_t; * Generic fallback */ #include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 #endif - /* * Types that are (so far) the same on all platforms */ -typedef signed char khronos_int8_t; -typedef unsigned char khronos_uint8_t; -typedef signed short int khronos_int16_t; -typedef unsigned short int khronos_uint16_t; +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; /* * Types that differ between LLP64 and LP64 architectures - in LLP64, @@ -250,29 +248,29 @@ typedef unsigned short int khronos_uint16_t; * to be the only LLP64 architecture in current use. */ #ifdef KHRONOS_USE_INTPTR_T -typedef intptr_t khronos_intptr_t; -typedef uintptr_t khronos_uintptr_t; +typedef intptr_t khronos_intptr_t; +typedef uintptr_t khronos_uintptr_t; #elif defined(_WIN64) -typedef signed long long int khronos_intptr_t; +typedef signed long long int khronos_intptr_t; typedef unsigned long long int khronos_uintptr_t; #else -typedef signed long int khronos_intptr_t; -typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; #endif #if defined(_WIN64) -typedef signed long long int khronos_ssize_t; +typedef signed long long int khronos_ssize_t; typedef unsigned long long int khronos_usize_t; #else -typedef signed long int khronos_ssize_t; -typedef unsigned long int khronos_usize_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; #endif #if KHRONOS_SUPPORT_FLOAT /* * Float type */ -typedef float khronos_float_t; +typedef float khronos_float_t; #endif #if KHRONOS_SUPPORT_INT64 @@ -285,8 +283,8 @@ typedef float khronos_float_t; * 64 bit value that wraps back to 0 every 584 years. Time intervals * may be either signed or unsigned. */ -typedef khronos_uint64_t khronos_utime_nanoseconds_t; -typedef khronos_int64_t khronos_stime_nanoseconds_t; +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; #endif /* @@ -302,10 +300,11 @@ typedef khronos_int64_t khronos_stime_nanoseconds_t; * Values other than zero should be considered to be true. Therefore * comparisons should not be made against KHRONOS_TRUE. */ -typedef enum { - KHRONOS_FALSE = 0, - KHRONOS_TRUE = 1, - KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +typedef enum +{ + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM } khronos_boolean_enum_t; #endif /* __khrplatform_h_ */ diff --git a/source/Irrlicht/OpenGL/Common.h b/source/Irrlicht/OpenGL/Common.h index b21d5e7a..92445cc3 100644 --- a/source/Irrlicht/OpenGL/Common.h +++ b/source/Irrlicht/OpenGL/Common.h @@ -8,10 +8,10 @@ #include "irrTypes.h" // even though we have mt_opengl.h our driver code still uses GL_* constants #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - #include - #include +#include +#include #else - #include "vendor/gl.h" +#include "vendor/gl.h" #endif namespace irr @@ -19,37 +19,39 @@ namespace irr namespace video { - // Forward declarations. +// Forward declarations. - class COpenGLCoreFeature; +class COpenGLCoreFeature; - template - class COpenGLCoreTexture; +template +class COpenGLCoreTexture; - template - class COpenGLCoreRenderTarget; +template +class COpenGLCoreRenderTarget; - template - class COpenGLCoreCacheHandler; +template +class COpenGLCoreCacheHandler; - class COpenGL3DriverBase; - typedef COpenGLCoreTexture COpenGL3Texture; - typedef COpenGLCoreRenderTarget COpenGL3RenderTarget; - typedef COpenGLCoreCacheHandler COpenGL3CacheHandler; +class COpenGL3DriverBase; +typedef COpenGLCoreTexture COpenGL3Texture; +typedef COpenGLCoreRenderTarget COpenGL3RenderTarget; +typedef COpenGLCoreCacheHandler COpenGL3CacheHandler; - enum class OpenGLSpec: u8 { - Core, - Compat, - ES, - // WebGL, // TODO - }; +enum class OpenGLSpec : u8 +{ + Core, + Compat, + ES, + // WebGL, // TODO +}; - struct OpenGLVersion { - OpenGLSpec Spec; - u8 Major; - u8 Minor; - u8 Release; - }; +struct OpenGLVersion +{ + OpenGLSpec Spec; + u8 Major; + u8 Minor; + u8 Release; +}; } } diff --git a/source/Irrlicht/OpenGL/Driver.cpp b/source/Irrlicht/OpenGL/Driver.cpp index 04518b96..778dd71e 100644 --- a/source/Irrlicht/OpenGL/Driver.cpp +++ b/source/Irrlicht/OpenGL/Driver.cpp @@ -31,94 +31,105 @@ namespace irr { namespace video { - struct VertexAttribute { - enum class Mode { - Regular, - Normalized, - Integral, - }; - int Index; - int ComponentCount; - GLenum ComponentType; - Mode mode; - int Offset; - }; - - struct VertexType { - int VertexSize; - std::vector Attributes; - }; - - static const VertexAttribute *begin(const VertexType &type) +struct VertexAttribute +{ + enum class Mode { - return type.Attributes.data(); - } + Regular, + Normalized, + Integral, + }; + int Index; + int ComponentCount; + GLenum ComponentType; + Mode mode; + int Offset; +}; - static const VertexAttribute *end(const VertexType &type) - { - return type.Attributes.data() + type.Attributes.size(); - } +struct VertexType +{ + int VertexSize; + std::vector Attributes; +}; - static const VertexType vtStandard = { - sizeof(S3DVertex), { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, +static const VertexAttribute *begin(const VertexType &type) +{ + return type.Attributes.data(); +} + +static const VertexAttribute *end(const VertexType &type) +{ + return type.Attributes.data() + type.Attributes.size(); +} + +static const VertexType vtStandard = { + sizeof(S3DVertex), + { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, }, - }; +}; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winvalid-offsetof" - static const VertexType vt2TCoords = { - sizeof(S3DVertex2TCoords), { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)}, - {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)}, +static const VertexType vt2TCoords = { + sizeof(S3DVertex2TCoords), + { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)}, + {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)}, }, - }; +}; - static const VertexType vtTangents = { - sizeof(S3DVertexTangents), { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)}, - {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)}, - {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)}, +static const VertexType vtTangents = { + sizeof(S3DVertexTangents), + { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)}, + {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)}, + {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)}, }, - }; +}; #pragma GCC diagnostic pop - static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type) - { - switch (type) { - case EVT_STANDARD: return vtStandard; - case EVT_2TCOORDS: return vt2TCoords; - case EVT_TANGENTS: return vtTangents; - default: assert(false); - } +static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type) +{ + switch (type) { + case EVT_STANDARD: + return vtStandard; + case EVT_2TCOORDS: + return vt2TCoords; + case EVT_TANGENTS: + return vtTangents; + default: + assert(false); } +} - static const VertexType vt2DImage = { - sizeof(S3DVertex), { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, +static const VertexType vt2DImage = { + sizeof(S3DVertex), + { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, }, - }; +}; - static const VertexType vtPrimitive = { - sizeof(S3DVertex), { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, +static const VertexType vtPrimitive = { + sizeof(S3DVertex), + { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, }, - }; - +}; void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { @@ -130,13 +141,13 @@ void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum s printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message); } -COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) : - CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0), - Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias), - MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0), - CurrentRenderMode(ERM_NONE), Transformation3DChanged(true), - OGLES2ShaderPath(params.OGLES2ShaderPath), - ColorFormat(ECF_R8G8B8), ContextManager(contextManager) +COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) : + CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0), + Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias), + MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0), + CurrentRenderMode(ERM_NONE), Transformation3DChanged(true), + OGLES2ShaderPath(params.OGLES2ShaderPath), + ColorFormat(ECF_R8G8B8), ContextManager(contextManager) { #ifdef _DEBUG setDebugName("Driver"); @@ -170,8 +181,7 @@ COpenGL3DriverBase::~COpenGL3DriverBase() delete MaterialRenderer2DNoTexture; delete CacheHandler; - if (ContextManager) - { + if (ContextManager) { ContextManager->destroyContext(); ContextManager->destroySurface(); ContextManager->terminate(); @@ -179,1922 +189,1803 @@ COpenGL3DriverBase::~COpenGL3DriverBase() } } - void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count) - { - int max_quad_count = max_vertex_count / 4; - std::vector QuadsIndices; - QuadsIndices.reserve(6 * max_quad_count); - for (int k = 0; k < max_quad_count; k++) { - QuadsIndices.push_back(4 * k + 0); - QuadsIndices.push_back(4 * k + 1); - QuadsIndices.push_back(4 * k + 2); - QuadsIndices.push_back(4 * k + 0); - QuadsIndices.push_back(4 * k + 2); - QuadsIndices.push_back(4 * k + 3); - } - GL.GenBuffers(1, &QuadIndexBuffer); - GL.BindBuffer(GL_ARRAY_BUFFER, QuadIndexBuffer); - GL.BufferData(GL_ARRAY_BUFFER, sizeof(QuadsIndices[0]) * QuadsIndices.size(), QuadsIndices.data(), GL_STATIC_DRAW); - GL.BindBuffer(GL_ARRAY_BUFFER, 0); - QuadIndexCount = QuadsIndices.size(); +void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count) +{ + int max_quad_count = max_vertex_count / 4; + std::vector QuadsIndices; + QuadsIndices.reserve(6 * max_quad_count); + for (int k = 0; k < max_quad_count; k++) { + QuadsIndices.push_back(4 * k + 0); + QuadsIndices.push_back(4 * k + 1); + QuadsIndices.push_back(4 * k + 2); + QuadsIndices.push_back(4 * k + 0); + QuadsIndices.push_back(4 * k + 2); + QuadsIndices.push_back(4 * k + 3); } + GL.GenBuffers(1, &QuadIndexBuffer); + GL.BindBuffer(GL_ARRAY_BUFFER, QuadIndexBuffer); + GL.BufferData(GL_ARRAY_BUFFER, sizeof(QuadsIndices[0]) * QuadsIndices.size(), QuadsIndices.data(), GL_STATIC_DRAW); + GL.BindBuffer(GL_ARRAY_BUFFER, 0); + QuadIndexCount = QuadsIndices.size(); +} - void COpenGL3DriverBase::initVersion() { - Name = GL.GetString(GL_VERSION); - printVersion(); +void COpenGL3DriverBase::initVersion() +{ + Name = GL.GetString(GL_VERSION); + printVersion(); - // print renderer information - VendorName = GL.GetString(GL_VENDOR); - os::Printer::log("Vendor", VendorName.c_str(), ELL_INFORMATION); + // print renderer information + VendorName = GL.GetString(GL_VENDOR); + os::Printer::log("Vendor", VendorName.c_str(), ELL_INFORMATION); - Version = getVersionFromOpenGL(); - } - - bool COpenGL3DriverBase::isVersionAtLeast(int major, int minor) const noexcept { - if (Version.Major < major) - return false; - if (Version.Major > major) - return true; - return Version.Minor >= minor; - } - - bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer) - { - initVersion(); - initFeatures(); - printTextureFormats(); - - // reset cache handler - delete CacheHandler; - CacheHandler = new COpenGL3CacheHandler(this); - - StencilBuffer = stencilBuffer; - - DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits); - DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits); -// DriverAttributes->setAttribute("MaxLights", MaxLights); - DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy); -// DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes); -// DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers); -// DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets); - DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices); - DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize); - DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias); - DriverAttributes->setAttribute("Version", 100 * Version.Major + Version.Minor); - DriverAttributes->setAttribute("AntiAlias", AntiAlias); - - GL.PixelStorei(GL_PACK_ALIGNMENT, 1); - - UserClipPlane.reallocate(0); - - for (s32 i = 0; i < ETS_COUNT; ++i) - setTransform(static_cast(i), core::IdentityMatrix); - - setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f)); - GL.ClearDepthf(1.0f); - - GL.Hint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); - GL.FrontFace(GL_CW); - - // create material renderers - createMaterialRenderers(); - - // set the renderstates - setRenderStates3DMode(); - - // set fog mode - setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog); - - // create matrix for flipping textures - TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f)); - - // We need to reset once more at the beginning of the first rendering. - // This fixes problems with intermediate changes to the material during texture load. - ResetRenderStates = true; - - testGLError(__LINE__); + Version = getVersionFromOpenGL(); +} +bool COpenGL3DriverBase::isVersionAtLeast(int major, int minor) const noexcept +{ + if (Version.Major < major) + return false; + if (Version.Major > major) return true; - } + return Version.Minor >= minor; +} - void COpenGL3DriverBase::printTextureFormats() - { - char buf[128]; - for (u32 i = 0; i < static_cast(ECF_UNKNOWN); i++) { - auto &info = TextureFormats[i]; - if (!info.InternalFormat) { - snprintf_irr(buf, sizeof(buf), "%s -> unsupported", ColorFormatNames[i]); - } else { - snprintf_irr(buf, sizeof(buf), "%s -> %#06x %#06x %#06x%s", +bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d &screenSize, bool stencilBuffer) +{ + initVersion(); + initFeatures(); + printTextureFormats(); + + // reset cache handler + delete CacheHandler; + CacheHandler = new COpenGL3CacheHandler(this); + + StencilBuffer = stencilBuffer; + + DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits); + DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits); + // DriverAttributes->setAttribute("MaxLights", MaxLights); + DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy); + // DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes); + // DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers); + // DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets); + DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices); + DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize); + DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias); + DriverAttributes->setAttribute("Version", 100 * Version.Major + Version.Minor); + DriverAttributes->setAttribute("AntiAlias", AntiAlias); + + GL.PixelStorei(GL_PACK_ALIGNMENT, 1); + + UserClipPlane.reallocate(0); + + for (s32 i = 0; i < ETS_COUNT; ++i) + setTransform(static_cast(i), core::IdentityMatrix); + + setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f)); + GL.ClearDepthf(1.0f); + + GL.Hint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); + GL.FrontFace(GL_CW); + + // create material renderers + createMaterialRenderers(); + + // set the renderstates + setRenderStates3DMode(); + + // set fog mode + setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog); + + // create matrix for flipping textures + TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f)); + + // We need to reset once more at the beginning of the first rendering. + // This fixes problems with intermediate changes to the material during texture load. + ResetRenderStates = true; + + testGLError(__LINE__); + + return true; +} + +void COpenGL3DriverBase::printTextureFormats() +{ + char buf[128]; + for (u32 i = 0; i < static_cast(ECF_UNKNOWN); i++) { + auto &info = TextureFormats[i]; + if (!info.InternalFormat) { + snprintf_irr(buf, sizeof(buf), "%s -> unsupported", ColorFormatNames[i]); + } else { + snprintf_irr(buf, sizeof(buf), "%s -> %#06x %#06x %#06x%s", ColorFormatNames[i], info.InternalFormat, info.PixelFormat, info.PixelType, info.Converter ? " (c)" : ""); - } - os::Printer::log(buf, ELL_DEBUG); } + os::Printer::log(buf, ELL_DEBUG); + } +} + +void COpenGL3DriverBase::loadShaderData(const io::path &vertexShaderName, const io::path &fragmentShaderName, c8 **vertexShaderData, c8 **fragmentShaderData) +{ + io::path vsPath(OGLES2ShaderPath); + vsPath += vertexShaderName; + + io::path fsPath(OGLES2ShaderPath); + fsPath += fragmentShaderName; + + *vertexShaderData = 0; + *fragmentShaderData = 0; + + io::IReadFile *vsFile = FileSystem->createAndOpenFile(vsPath); + if (!vsFile) { + std::string warning("Warning: Missing shader files needed to simulate fixed function materials:\n"); + warning.append(vsPath.c_str()).append("\n"); + warning += "Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; + os::Printer::log(warning.c_str(), ELL_WARNING); + return; } - void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData) - { - io::path vsPath(OGLES2ShaderPath); - vsPath += vertexShaderName; - - io::path fsPath(OGLES2ShaderPath); - fsPath += fragmentShaderName; - - *vertexShaderData = 0; - *fragmentShaderData = 0; - - io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath); - if ( !vsFile ) - { - std::string warning("Warning: Missing shader files needed to simulate fixed function materials:\n"); - warning.append(vsPath.c_str()).append("\n"); - warning += "Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; - os::Printer::log(warning.c_str(), ELL_WARNING); - return; - } - - io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath); - if ( !fsFile ) - { - std::string warning("Warning: Missing shader files needed to simulate fixed function materials:\n"); - warning.append(fsPath.c_str()).append("\n"); - warning += "Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; - os::Printer::log(warning.c_str(), ELL_WARNING); - return; - } - - long size = vsFile->getSize(); - if (size) - { - *vertexShaderData = new c8[size+1]; - vsFile->read(*vertexShaderData, size); - (*vertexShaderData)[size] = 0; - } - { - auto tmp = std::string("Loaded ") + std::to_string(size) + " bytes for vertex shader " + vertexShaderName.c_str(); - os::Printer::log(tmp.c_str(), ELL_INFORMATION); - } - - size = fsFile->getSize(); - if (size) - { - // if both handles are the same we must reset the file - if (fsFile == vsFile) - fsFile->seek(0); - - *fragmentShaderData = new c8[size+1]; - fsFile->read(*fragmentShaderData, size); - (*fragmentShaderData)[size] = 0; - } - { - auto tmp = std::string("Loaded ") + std::to_string(size) + " bytes for fragment shader " + fragmentShaderName.c_str(); - os::Printer::log(tmp.c_str(), ELL_INFORMATION); - } - - vsFile->drop(); - fsFile->drop(); + io::IReadFile *fsFile = FileSystem->createAndOpenFile(fsPath); + if (!fsFile) { + std::string warning("Warning: Missing shader files needed to simulate fixed function materials:\n"); + warning.append(fsPath.c_str()).append("\n"); + warning += "Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; + os::Printer::log(warning.c_str(), ELL_WARNING); + return; } - void COpenGL3DriverBase::createMaterialRenderers() + long size = vsFile->getSize(); + if (size) { + *vertexShaderData = new c8[size + 1]; + vsFile->read(*vertexShaderData, size); + (*vertexShaderData)[size] = 0; + } { - // Create callbacks. + auto tmp = std::string("Loaded ") + std::to_string(size) + " bytes for vertex shader " + vertexShaderName.c_str(); + os::Printer::log(tmp.c_str(), ELL_INFORMATION); + } - COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB(); + size = fsFile->getSize(); + if (size) { + // if both handles are the same we must reset the file + if (fsFile == vsFile) + fsFile->seek(0); - // Create built-in materials. - // The addition order must be the same as in the E_MATERIAL_TYPE enumeration. Thus the + *fragmentShaderData = new c8[size + 1]; + fsFile->read(*fragmentShaderData, size); + (*fragmentShaderData)[size] = 0; + } + { + auto tmp = std::string("Loaded ") + std::to_string(size) + " bytes for fragment shader " + fragmentShaderName.c_str(); + os::Printer::log(tmp.c_str(), ELL_INFORMATION); + } - const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh"; + vsFile->drop(); + fsFile->drop(); +} - // EMT_SOLID - core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", +void COpenGL3DriverBase::createMaterialRenderers() +{ + // Create callbacks. + + COpenGL3MaterialSolidCB *SolidCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB *TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB *TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB *TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialOneTextureBlendCB *OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB(); + + // Create built-in materials. + // The addition order must be the same as in the E_MATERIAL_TYPE enumeration. Thus the + + const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh"; + + // EMT_SOLID + core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0); - // EMT_TRANSPARENT_ALPHA_CHANNEL - FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + // EMT_TRANSPARENT_ALPHA_CHANNEL + FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); - // EMT_TRANSPARENT_ALPHA_CHANNEL_REF - FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + // EMT_TRANSPARENT_ALPHA_CHANNEL_REF + FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0); - // EMT_TRANSPARENT_VERTEX_ALPHA - FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + // EMT_TRANSPARENT_VERTEX_ALPHA + FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); - // EMT_ONETEXTURE_BLEND - FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + // EMT_ONETEXTURE_BLEND + FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0); - // Drop callbacks. + // Drop callbacks. - SolidCB->drop(); - TransparentAlphaChannelCB->drop(); - TransparentAlphaChannelRefCB->drop(); - TransparentVertexAlphaCB->drop(); - OneTextureBlendCB->drop(); + SolidCB->drop(); + TransparentAlphaChannelCB->drop(); + TransparentAlphaChannelRefCB->drop(); + TransparentVertexAlphaCB->drop(); + OneTextureBlendCB->drop(); - // Create 2D material renderers + // Create 2D material renderers - c8* vs2DData = 0; - c8* fs2DData = 0; - loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData); - MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true); - delete[] vs2DData; - delete[] fs2DData; - vs2DData = 0; - fs2DData = 0; + c8 *vs2DData = 0; + c8 *fs2DData = 0; + loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData); + MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true); + delete[] vs2DData; + delete[] fs2DData; + vs2DData = 0; + fs2DData = 0; - loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData); - MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false); - delete[] vs2DData; - delete[] fs2DData; + loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData); + MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false); + delete[] vs2DData; + delete[] fs2DData; +} + +bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture *texture) +{ + Material.TextureLayers[layerIdx].Texture = const_cast(texture); // function uses const-pointer for texture because all draw functions use const-pointers already + return CacheHandler->getTextureCache().set(0, texture); +} + +bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData &videoData, core::rect *sourceRect) +{ + CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); + + if (ContextManager) + ContextManager->activateContext(videoData, true); + + clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); + + return true; +} + +bool COpenGL3DriverBase::endScene() +{ + CNullDriver::endScene(); + + GL.Flush(); + + if (ContextManager) + return ContextManager->swapBuffers(); + + return false; +} + +//! Returns the transformation set by setTransform +const core::matrix4 &COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const +{ + return Matrices[state]; +} + +//! sets transformation +void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) +{ + Matrices[state] = mat; + Transformation3DChanged = true; +} + +bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) +{ + if (!HWBuffer) + return false; + + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const u32 vertexCount = mb->getVertexCount(); + const E_VERTEX_TYPE vType = mb->getVertexType(); + const u32 vertexSize = getVertexPitchFromType(vType); + + const void *buffer = vertices; + size_t bufferSize = vertexSize * vertexCount; + + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_verticesID) { + GL.GenBuffers(1, &HWBuffer->vbo_verticesID); + if (!HWBuffer->vbo_verticesID) + return false; + newBuffer = true; + } else if (HWBuffer->vbo_verticesSize < bufferSize) { + newBuffer = true; } - bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture) - { - Material.TextureLayers[layerIdx].Texture = const_cast(texture); // function uses const-pointer for texture because all draw functions use const-pointers already - return CacheHandler->getTextureCache().set(0, texture); + GL.BindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); + + // copy data to graphics card + if (!newBuffer) + GL.BufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer); + else { + HWBuffer->vbo_verticesSize = bufferSize; + + GLenum usage = GL_STATIC_DRAW; + if (HWBuffer->Mapped_Index == scene::EHM_STREAM) + usage = GL_STREAM_DRAW; + else if (HWBuffer->Mapped_Index == scene::EHM_DYNAMIC) + usage = GL_DYNAMIC_DRAW; + GL.BufferData(GL_ARRAY_BUFFER, bufferSize, buffer, usage); } - bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) - { - CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); + GL.BindBuffer(GL_ARRAY_BUFFER, 0); - if (ContextManager) - ContextManager->activateContext(videoData, true); + return (!testGLError(__LINE__)); +} - clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); +bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) +{ + if (!HWBuffer) + return false; - return true; + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + + const void *indices = mb->getIndices(); + u32 indexCount = mb->getIndexCount(); + + GLenum indexSize; + switch (mb->getIndexType()) { + case (EIT_16BIT): { + indexSize = sizeof(u16); + break; } - - bool COpenGL3DriverBase::endScene() - { - CNullDriver::endScene(); - - GL.Flush(); - - if (ContextManager) - return ContextManager->swapBuffers(); - + case (EIT_32BIT): { + indexSize = sizeof(u32); + break; + } + default: { return false; } - - - //! Returns the transformation set by setTransform - const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const - { - return Matrices[state]; } - - //! sets transformation - void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) - { - Matrices[state] = mat; - Transformation3DChanged = true; - } - - - bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) - { - if (!HWBuffer) + // get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_indicesID) { + GL.GenBuffers(1, &HWBuffer->vbo_indicesID); + if (!HWBuffer->vbo_indicesID) return false; + newBuffer = true; + } else if (HWBuffer->vbo_indicesSize < indexCount * indexSize) { + newBuffer = true; + } - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void* vertices = mb->getVertices(); - const u32 vertexCount = mb->getVertexCount(); - const E_VERTEX_TYPE vType = mb->getVertexType(); - const u32 vertexSize = getVertexPitchFromType(vType); + GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - const void *buffer = vertices; - size_t bufferSize = vertexSize * vertexCount; + // copy data to graphics card + if (!newBuffer) + GL.BufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); + else { + HWBuffer->vbo_indicesSize = indexCount * indexSize; - //get or create buffer - bool newBuffer = false; - if (!HWBuffer->vbo_verticesID) - { - GL.GenBuffers(1, &HWBuffer->vbo_verticesID); - if (!HWBuffer->vbo_verticesID) return false; - newBuffer = true; - } - else if (HWBuffer->vbo_verticesSize < bufferSize) - { - newBuffer = true; + GLenum usage = GL_STATIC_DRAW; + if (HWBuffer->Mapped_Index == scene::EHM_STREAM) + usage = GL_STREAM_DRAW; + else if (HWBuffer->Mapped_Index == scene::EHM_DYNAMIC) + usage = GL_DYNAMIC_DRAW; + GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, usage); + } + + GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + return (!testGLError(__LINE__)); +} + +//! updates hardware buffer if needed +bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer) +{ + if (!HWBuffer) + return false; + + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() || !static_cast(HWBuffer)->vbo_verticesID) { + + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + + if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) + return false; } + } + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { + if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() || !static_cast(HWBuffer)->vbo_indicesID) { + + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + + if (!updateIndexHardwareBuffer((SHWBufferLink_opengl *)HWBuffer)) + return false; + } + } + + return true; +} + +//! Create hardware buffer from meshbuffer +COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer *mb) +{ + if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) + return 0; + + SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); + + // add to map + HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); + + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); + HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); + HWBuffer->vbo_verticesID = 0; + HWBuffer->vbo_indicesID = 0; + HWBuffer->vbo_verticesSize = 0; + HWBuffer->vbo_indicesSize = 0; + + if (!updateHardwareBuffer(HWBuffer)) { + deleteHardwareBuffer(HWBuffer); + return 0; + } + + return HWBuffer; +} + +void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) +{ + if (!_HWBuffer) + return; + + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); + if (HWBuffer->vbo_verticesID) { + GL.DeleteBuffers(1, &HWBuffer->vbo_verticesID); + HWBuffer->vbo_verticesID = 0; + } + if (HWBuffer->vbo_indicesID) { + GL.DeleteBuffers(1, &HWBuffer->vbo_indicesID); + HWBuffer->vbo_indicesID = 0; + } + + CNullDriver::deleteHardwareBuffer(_HWBuffer); +} + +//! Draw hardware buffer +void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer) +{ + if (!_HWBuffer) + return; + + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); + + updateHardwareBuffer(HWBuffer); // check if update is needed + + const scene::IMeshBuffer *mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const void *indexList = mb->getIndices(); + + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { GL.BindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); + vertices = 0; + } - // copy data to graphics card - if (!newBuffer) - GL.BufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer); - else - { - HWBuffer->vbo_verticesSize = bufferSize; + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) { + GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); + indexList = 0; + } - GLenum usage = GL_STATIC_DRAW; - if (HWBuffer->Mapped_Index == scene::EHM_STREAM) - usage = GL_STREAM_DRAW; - else if (HWBuffer->Mapped_Index == scene::EHM_DYNAMIC) - usage = GL_DYNAMIC_DRAW; - GL.BufferData(GL_ARRAY_BUFFER, bufferSize, buffer, usage); - } + drawVertexPrimitiveList(vertices, mb->getVertexCount(), + indexList, mb->getPrimitiveCount(), + mb->getVertexType(), mb->getPrimitiveType(), + mb->getIndexType()); + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) GL.BindBuffer(GL_ARRAY_BUFFER, 0); - return (!testGLError(__LINE__)); - } - - - bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) - { - if (!HWBuffer) - return false; - - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - - const void* indices = mb->getIndices(); - u32 indexCount = mb->getIndexCount(); - - GLenum indexSize; - switch (mb->getIndexType()) - { - case(EIT_16BIT): - { - indexSize = sizeof(u16); - break; - } - case(EIT_32BIT): - { - indexSize = sizeof(u32); - break; - } - default: - { - return false; - } - } - - //get or create buffer - bool newBuffer = false; - if (!HWBuffer->vbo_indicesID) - { - GL.GenBuffers(1, &HWBuffer->vbo_indicesID); - if (!HWBuffer->vbo_indicesID) return false; - newBuffer = true; - } - else if (HWBuffer->vbo_indicesSize < indexCount*indexSize) - { - newBuffer = true; - } - - GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - - // copy data to graphics card - if (!newBuffer) - GL.BufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); - else - { - HWBuffer->vbo_indicesSize = indexCount * indexSize; - - GLenum usage = GL_STATIC_DRAW; - if (HWBuffer->Mapped_Index == scene::EHM_STREAM) - usage = GL_STREAM_DRAW; - else if (HWBuffer->Mapped_Index == scene::EHM_DYNAMIC) - usage = GL_DYNAMIC_DRAW; - GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, usage); - } - + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} - return (!testGLError(__LINE__)); +IRenderTarget *COpenGL3DriverBase::addRenderTarget() +{ + COpenGL3RenderTarget *renderTarget = new COpenGL3RenderTarget(this); + RenderTargets.push_back(renderTarget); + + return renderTarget; +} + +// small helper function to create vertex buffer object adress offsets +static inline u8 *buffer_offset(const long offset) +{ + return ((u8 *)0 + offset); +} + +//! draws a vertex primitive list +void COpenGL3DriverBase::drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) +{ + if (!primitiveCount || !vertexCount) + return; + + if (!checkPrimitiveCount(primitiveCount)) + return; + + CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType); + + setRenderStates3DMode(); + + auto &vTypeDesc = getVertexTypeDescription(vType); + beginDraw(vTypeDesc, reinterpret_cast(vertices)); + GLenum indexSize = 0; + + switch (iType) { + case (EIT_16BIT): { + indexSize = GL_UNSIGNED_SHORT; + break; } - - - //! updates hardware buffer if needed - bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer) - { - if (!HWBuffer) - return false; - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() - || !static_cast(HWBuffer)->vbo_verticesID) - { - - HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - - if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) - return false; - } - } - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() - || !static_cast(HWBuffer)->vbo_indicesID) - { - - HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - - if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer)) - return false; - } - } - - return true; - } - - - //! Create hardware buffer from meshbuffer - COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb) - { - if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) - return 0; - - SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); - - //add to map - HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); - - HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); - HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); - HWBuffer->vbo_verticesID = 0; - HWBuffer->vbo_indicesID = 0; - HWBuffer->vbo_verticesSize = 0; - HWBuffer->vbo_indicesSize = 0; - - if (!updateHardwareBuffer(HWBuffer)) - { - deleteHardwareBuffer(HWBuffer); - return 0; - } - - return HWBuffer; - } - - - void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) - { - if (!_HWBuffer) - return; - - SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); - if (HWBuffer->vbo_verticesID) - { - GL.DeleteBuffers(1, &HWBuffer->vbo_verticesID); - HWBuffer->vbo_verticesID = 0; - } - if (HWBuffer->vbo_indicesID) - { - GL.DeleteBuffers(1, &HWBuffer->vbo_indicesID); - HWBuffer->vbo_indicesID = 0; - } - - CNullDriver::deleteHardwareBuffer(_HWBuffer); - } - - - //! Draw hardware buffer - void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer) - { - if (!_HWBuffer) - return; - - SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); - - updateHardwareBuffer(HWBuffer); //check if update is needed - - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void *vertices = mb->getVertices(); - const void *indexList = mb->getIndices(); - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - { - GL.BindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); - vertices = 0; - } - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - { - GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - indexList = 0; - } - - - drawVertexPrimitiveList(vertices, mb->getVertexCount(), - indexList, mb->getPrimitiveCount(), - mb->getVertexType(), mb->getPrimitiveType(), - mb->getIndexType()); - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - GL.BindBuffer(GL_ARRAY_BUFFER, 0); - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - - IRenderTarget* COpenGL3DriverBase::addRenderTarget() - { - COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this); - RenderTargets.push_back(renderTarget); - - return renderTarget; - } - - - // small helper function to create vertex buffer object adress offsets - static inline u8* buffer_offset(const long offset) - { - return ((u8*)0 + offset); - } - - - //! draws a vertex primitive list - void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) - { - if (!primitiveCount || !vertexCount) - return; - - if (!checkPrimitiveCount(primitiveCount)) - return; - - CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType); - - setRenderStates3DMode(); - - auto &vTypeDesc = getVertexTypeDescription(vType); - beginDraw(vTypeDesc, reinterpret_cast(vertices)); - GLenum indexSize = 0; - - switch (iType) - { - case(EIT_16BIT): - { - indexSize = GL_UNSIGNED_SHORT; - break; - } - case(EIT_32BIT): - { + case (EIT_32BIT): { #ifdef GL_OES_element_index_uint #ifndef GL_UNSIGNED_INT #define GL_UNSIGNED_INT 0x1405 #endif - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) - indexSize = GL_UNSIGNED_INT; - else + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) + indexSize = GL_UNSIGNED_INT; + else #endif - indexSize = GL_UNSIGNED_SHORT; - break; - } - } - - switch (pType) - { - case scene::EPT_POINTS: - case scene::EPT_POINT_SPRITES: - GL.DrawArrays(GL_POINTS, 0, primitiveCount); - break; - case scene::EPT_LINE_STRIP: - GL.DrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList); - break; - case scene::EPT_LINE_LOOP: - GL.DrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); - break; - case scene::EPT_LINES: - GL.DrawElements(GL_LINES, primitiveCount*2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_STRIP: - GL.DrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_FAN: - GL.DrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList); - break; - case scene::EPT_TRIANGLES: - GL.DrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList); - break; - default: - break; - } - - endDraw(vTypeDesc); + indexSize = GL_UNSIGNED_SHORT; + break; + } } + switch (pType) { + case scene::EPT_POINTS: + case scene::EPT_POINT_SPRITES: + GL.DrawArrays(GL_POINTS, 0, primitiveCount); + break; + case scene::EPT_LINE_STRIP: + GL.DrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList); + break; + case scene::EPT_LINE_LOOP: + GL.DrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); + break; + case scene::EPT_LINES: + GL.DrawElements(GL_LINES, primitiveCount * 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_STRIP: + GL.DrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_FAN: + GL.DrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLES: + GL.DrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS + : GL_TRIANGLES, + primitiveCount * 3, indexSize, indexList); + break; + default: + break; + } - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect, SColor color, + endDraw(vTypeDesc); +} + +void COpenGL3DriverBase::draw2DImage(const video::ITexture *texture, const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect, SColor color, bool useAlphaChannelOfTexture) - { - if (!texture) - return; +{ + if (!texture) + return; - if (!sourceRect.isValid()) - return; + if (!sourceRect.isValid()) + return; - SColor colors[4] = {color, color, color, color}; - draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture); - } + SColor colors[4] = {color, color, color, color}; + draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture); +} +void COpenGL3DriverBase::draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect, + const video::SColor *const colors, bool useAlphaChannelOfTexture) +{ + if (!texture) + return; - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect, - const video::SColor* const colors, bool useAlphaChannelOfTexture) - { - if (!texture) - return; - - // texcoords need to be flipped horizontally for RTTs - const bool isRTT = texture->isRenderTarget(); - const core::dimension2du& ss = texture->getOriginalSize(); - const f32 invW = 1.f / static_cast(ss.Width); - const f32 invH = 1.f / static_cast(ss.Height); - const core::rect tcoords( + // texcoords need to be flipped horizontally for RTTs + const bool isRTT = texture->isRenderTarget(); + const core::dimension2du &ss = texture->getOriginalSize(); + const f32 invW = 1.f / static_cast(ss.Width); + const f32 invH = 1.f / static_cast(ss.Height); + const core::rect tcoords( sourceRect.UpperLeftCorner.X * invW, (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH, sourceRect.LowerRightCorner.X * invW, - (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH); + (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) * invH); - const video::SColor temp[4] = - { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF - }; + const video::SColor temp[4] = + { + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF}; - const video::SColor* const useColor = colors ? colors : temp; + const video::SColor *const useColor = colors ? colors : temp; - chooseMaterial2D(); - if (!setMaterialTexture(0, texture )) - return; + chooseMaterial2D(); + if (!setMaterialTexture(0, texture)) + return; - setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || - useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, + setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || + useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, true, useAlphaChannelOfTexture); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); - if (clipRect) - { - if (!clipRect->isValid()) - return; + if (clipRect) { + if (!clipRect->isValid()) + return; - GL.Enable(GL_SCISSOR_TEST); - GL.Scissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, + GL.Enable(GL_SCISSOR_TEST); + GL.Scissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, clipRect->getWidth(), clipRect->getHeight()); - } - - f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); - - drawQuad(vt2DImage, vertices); - - if (clipRect) - GL.Disable(GL_SCISSOR_TEST); - - testGLError(__LINE__); } - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip) - { - if (!texture) + f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); + + drawQuad(vt2DImage, vertices); + + if (clipRect) + GL.Disable(GL_SCISSOR_TEST); + + testGLError(__LINE__); +} + +void COpenGL3DriverBase::draw2DImage(const video::ITexture *texture, u32 layer, bool flip) +{ + if (!texture) + return; + + chooseMaterial2D(); + if (!setMaterialTexture(0, texture)) + return; + + setRenderStates2DMode(false, true, true); + + S3DVertex quad2DVertices[4]; + + quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f); + quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f); + quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f); + quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f); + + f32 modificator = (flip) ? 1.f : 0.f; + + quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator); + quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator); + quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator); + quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator); + + quad2DVertices[0].Color = SColor(0xFFFFFFFF); + quad2DVertices[1].Color = SColor(0xFFFFFFFF); + quad2DVertices[2].Color = SColor(0xFFFFFFFF); + quad2DVertices[3].Color = SColor(0xFFFFFFFF); + + drawQuad(vt2DImage, quad2DVertices); +} + +void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, bool useAlphaChannelOfTexture) +{ + if (!texture) + return; + + chooseMaterial2D(); + if (!setMaterialTexture(0, texture)) + return; + + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); + + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); + + if (clipRect) { + if (!clipRect->isValid()) return; - chooseMaterial2D(); - if (!setMaterialTexture(0, texture )) - return; - - setRenderStates2DMode(false, true, true); - - S3DVertex quad2DVertices[4]; - - quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f); - quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f); - quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f); - quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f); - - f32 modificator = (flip) ? 1.f : 0.f; - - quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator); - quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator); - quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator); - quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator); - - quad2DVertices[0].Color = SColor(0xFFFFFFFF); - quad2DVertices[1].Color = SColor(0xFFFFFFFF); - quad2DVertices[2].Color = SColor(0xFFFFFFFF); - quad2DVertices[3].Color = SColor(0xFFFFFFFF); - - drawQuad(vt2DImage, quad2DVertices); + GL.Enable(GL_SCISSOR_TEST); + GL.Scissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, + clipRect->getWidth(), clipRect->getHeight()); } - void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, bool useAlphaChannelOfTexture) - { - if (!texture) - return; + const irr::u32 drawCount = core::min_(positions.size(), sourceRects.size()); + assert(6 * drawCount <= QuadIndexCount); // FIXME split the batch? or let it crash? - chooseMaterial2D(); - if (!setMaterialTexture(0, texture)) - return; + core::array vtx(drawCount * 4); - setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); + for (u32 i = 0; i < drawCount; i++) { + core::position2d targetPos = positions[i]; + core::position2d sourcePos = sourceRects[i].UpperLeftCorner; + // This needs to be signed as it may go negative. + core::dimension2d sourceSize(sourceRects[i].getSize()); - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + // now draw it. - if (clipRect) - { - if (!clipRect->isValid()) - return; + core::rect tcoords; + tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width; + tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height; + tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width); + tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height); - GL.Enable(GL_SCISSOR_TEST); - GL.Scissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, - clipRect->getWidth(), clipRect->getHeight()); - } + const core::rect poss(targetPos, sourceSize); - const irr::u32 drawCount = core::min_(positions.size(), sourceRects.size()); - assert(6 * drawCount <= QuadIndexCount); // FIXME split the batch? or let it crash? + f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - core::array vtx(drawCount * 4); - - for (u32 i = 0; i < drawCount; i++) - { - core::position2d targetPos = positions[i]; - core::position2d sourcePos = sourceRects[i].UpperLeftCorner; - // This needs to be signed as it may go negative. - core::dimension2d sourceSize(sourceRects[i].getSize()); - - // now draw it. - - core::rect tcoords; - tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ; - tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height; - tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width); - tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height); - - const core::rect poss(targetPos, sourceSize); - - f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - vtx.push_back(S3DVertex(left, top, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); - vtx.push_back(S3DVertex(right, top, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); - vtx.push_back(S3DVertex(right, down, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); - vtx.push_back(S3DVertex(left, down, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); - } - - GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, QuadIndexBuffer); - drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), vtx.size(), 0, 6 * drawCount); - GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - if (clipRect) - GL.Disable(GL_SCISSOR_TEST); + vtx.push_back(S3DVertex(left, top, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); + vtx.push_back(S3DVertex(right, top, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); + vtx.push_back(S3DVertex(right, down, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); + vtx.push_back(S3DVertex(left, down, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); } + GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, QuadIndexBuffer); + drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), vtx.size(), 0, 6 * drawCount); + GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - //! draw a 2d rectangle - void COpenGL3DriverBase::draw2DRectangle(SColor color, - const core::rect& position, - const core::rect* clip) + if (clipRect) + GL.Disable(GL_SCISSOR_TEST); +} + +//! draw a 2d rectangle +void COpenGL3DriverBase::draw2DRectangle(SColor color, + const core::rect &position, + const core::rect *clip) +{ + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(color.getAlpha() < 255, false, false); + + core::rect pos = position; + + if (clip) + pos.clipAgainst(*clip); + + if (!pos.isValid()) + return; + + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); + + f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0); + + drawQuad(vtPrimitive, vertices); +} + +//! draw an 2d rectangle +void COpenGL3DriverBase::draw2DRectangle(const core::rect &position, + SColor colorLeftUp, SColor colorRightUp, + SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip) +{ + core::rect pos = position; + + if (clip) + pos.clipAgainst(*clip); + + if (!pos.isValid()) + return; + + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || + colorRightUp.getAlpha() < 255 || + colorLeftDown.getAlpha() < 255 || + colorRightDown.getAlpha() < 255, + false, false); + + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); + + f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0); + + drawQuad(vtPrimitive, vertices); +} + +//! Draws a 2d line. +void COpenGL3DriverBase::draw2DLine(const core::position2d &start, + const core::position2d &end, SColor color) +{ { chooseMaterial2D(); setMaterialTexture(0, 0); setRenderStates2DMode(color.getAlpha() < 255, false, false); - core::rect pos = position; + const core::dimension2d &renderTargetSize = getCurrentRenderTargetSize(); - if (clip) - pos.clipAgainst(*clip); - - if (!pos.isValid()) - return; - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0); - - drawQuad(vtPrimitive, vertices); - } - - - //! draw an 2d rectangle - void COpenGL3DriverBase::draw2DRectangle(const core::rect& position, - SColor colorLeftUp, SColor colorRightUp, - SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip) - { - core::rect pos = position; - - if (clip) - pos.clipAgainst(*clip); - - if (!pos.isValid()) - return; - - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || - colorRightUp.getAlpha() < 255 || - colorLeftDown.getAlpha() < 255 || - colorRightDown.getAlpha() < 255, false, false); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0); - - drawQuad(vtPrimitive, vertices); - } - - - //! Draws a 2d line. - void COpenGL3DriverBase::draw2DLine(const core::position2d& start, - const core::position2d& end, SColor color) - { - { - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(color.getAlpha() < 255, false, false); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[2]; - vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1); - - drawArrays(GL_LINES, vtPrimitive, vertices, 2); - } - } - - void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]) - { - drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4); - } - - void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount) - { - beginDraw(vertexType, reinterpret_cast(vertices)); - GL.DrawArrays(primitiveType, 0, vertexCount); - endDraw(vertexType); - } - - void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount) - { - beginDraw(vertexType, reinterpret_cast(vertices)); - GL.DrawRangeElements(primitiveType, 0, vertexCount - 1, indexCount, GL_UNSIGNED_SHORT, indices); - endDraw(vertexType); - } - - void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase) - { - for (auto attr: vertexType) { - GL.EnableVertexAttribArray(attr.Index); - switch (attr.mode) { - case VertexAttribute::Mode::Regular: GL.VertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - case VertexAttribute::Mode::Normalized: GL.VertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - case VertexAttribute::Mode::Integral: GL.VertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - } - } - } - - void COpenGL3DriverBase::endDraw(const VertexType &vertexType) - { - for (auto attr: vertexType) - GL.DisableVertexAttribArray(attr.Index); - } - - ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image) - { - core::array imageArray(1); - imageArray.push_back(image); - - COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this); - - return texture; - } - - ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) - { - COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this); - - return texture; - } - - //! Sets a material. - void COpenGL3DriverBase::setMaterial(const SMaterial& material) - { - Material = material; - OverrideMaterial.apply(Material); - - for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) - { - CacheHandler->getTextureCache().set(i, material.getTexture(i)); - setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); - } - } - - //! prints error if an error happened. - bool COpenGL3DriverBase::testGLError(int code) - { -#ifdef _DEBUG - GLenum g = GL.GetError(); - switch (g) - { - case GL_NO_ERROR: - return false; - case GL_INVALID_ENUM: - os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_INVALID_VALUE: - os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_INVALID_OPERATION: - os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_OUT_OF_MEMORY: - os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); - break; - }; - return true; -#else - return false; -#endif - } - - //! prints error if an error happened. - bool COpenGL3DriverBase::testEGLError() - { -#if defined(EGL_VERSION_1_0) && defined(_DEBUG) - EGLint g = eglGetError(); - switch (g) - { - case EGL_SUCCESS: - return false; - case EGL_NOT_INITIALIZED : - os::Printer::log("Not Initialized", ELL_ERROR); - break; - case EGL_BAD_ACCESS: - os::Printer::log("Bad Access", ELL_ERROR); - break; - case EGL_BAD_ALLOC: - os::Printer::log("Bad Alloc", ELL_ERROR); - break; - case EGL_BAD_ATTRIBUTE: - os::Printer::log("Bad Attribute", ELL_ERROR); - break; - case EGL_BAD_CONTEXT: - os::Printer::log("Bad Context", ELL_ERROR); - break; - case EGL_BAD_CONFIG: - os::Printer::log("Bad Config", ELL_ERROR); - break; - case EGL_BAD_CURRENT_SURFACE: - os::Printer::log("Bad Current Surface", ELL_ERROR); - break; - case EGL_BAD_DISPLAY: - os::Printer::log("Bad Display", ELL_ERROR); - break; - case EGL_BAD_SURFACE: - os::Printer::log("Bad Surface", ELL_ERROR); - break; - case EGL_BAD_MATCH: - os::Printer::log("Bad Match", ELL_ERROR); - break; - case EGL_BAD_PARAMETER: - os::Printer::log("Bad Parameter", ELL_ERROR); - break; - case EGL_BAD_NATIVE_PIXMAP: - os::Printer::log("Bad Native Pixmap", ELL_ERROR); - break; - case EGL_BAD_NATIVE_WINDOW: - os::Printer::log("Bad Native Window", ELL_ERROR); - break; - case EGL_CONTEXT_LOST: - os::Printer::log("Context Lost", ELL_ERROR); - break; - }; - return true; -#else - return false; -#endif - } - - - void COpenGL3DriverBase::setRenderStates3DMode() - { - if ( LockRenderStateMode ) - return; - - if (CurrentRenderMode != ERM_3D) - { - // Reset Texture Stages - CacheHandler->setBlend(false); - CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - ResetRenderStates = true; - } - - if (ResetRenderStates || LastMaterial != Material) - { - // unset old material - - // unset last 3d material - if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive) - { - MaterialRenderer2DActive->OnUnsetMaterial(); - MaterialRenderer2DActive = 0; - } - else if (LastMaterial.MaterialType != Material.MaterialType && - static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); - - // set new material. - if (static_cast(Material.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( - Material, LastMaterial, ResetRenderStates, this); - - LastMaterial = Material; - CacheHandler->correctCacheMaterial(LastMaterial); - ResetRenderStates = false; - } - - if (static_cast(Material.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD); - - CurrentRenderMode = ERM_3D; - } - - //! Can be called by an IMaterialRenderer to make its work easier. - void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates) - { - // ZBuffer - switch (material.ZBuffer) - { - case ECFN_DISABLED: - CacheHandler->setDepthTest(false); - break; - case ECFN_LESSEQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_LEQUAL); - break; - case ECFN_EQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_EQUAL); - break; - case ECFN_LESS: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_LESS); - break; - case ECFN_NOTEQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_NOTEQUAL); - break; - case ECFN_GREATEREQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_GEQUAL); - break; - case ECFN_GREATER: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_GREATER); - break; - case ECFN_ALWAYS: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_ALWAYS); - break; - case ECFN_NEVER: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_NEVER); - break; - default: - break; - } - - // ZWrite - if (getWriteZBuffer(material)) - { - CacheHandler->setDepthMask(true); - } - else - { - CacheHandler->setDepthMask(false); - } - - // Back face culling - if ((material.FrontfaceCulling) && (material.BackfaceCulling)) - { - CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK); - CacheHandler->setCullFace(true); - } - else if (material.BackfaceCulling) - { - CacheHandler->setCullFaceFunc(GL_BACK); - CacheHandler->setCullFace(true); - } - else if (material.FrontfaceCulling) - { - CacheHandler->setCullFaceFunc(GL_FRONT); - CacheHandler->setCullFace(true); - } - else - { - CacheHandler->setCullFace(false); - } - - // Color Mask - CacheHandler->setColorMask(material.ColorMask); - - // Blend Equation - if (material.BlendOperation == EBO_NONE) - CacheHandler->setBlend(false); - else - { - CacheHandler->setBlend(true); - - switch (material.BlendOperation) - { - case EBO_ADD: - CacheHandler->setBlendEquation(GL_FUNC_ADD); - break; - case EBO_SUBTRACT: - CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); - break; - case EBO_REVSUBTRACT: - CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); - break; - case EBO_MIN: - if (BlendMinMaxSupported) - CacheHandler->setBlendEquation(GL_MIN); - else - os::Printer::log("Attempt to use EBO_MIN without driver support", ELL_WARNING); - break; - case EBO_MAX: - if (BlendMinMaxSupported) - CacheHandler->setBlendEquation(GL_MAX); - else - os::Printer::log("Attempt to use EBO_MAX without driver support", ELL_WARNING); - break; - default: - break; - } - } - - // Blend Factor - if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? - && material.MaterialType != EMT_ONETEXTURE_BLEND - ) - { - E_BLEND_FACTOR srcRGBFact = EBF_ZERO; - E_BLEND_FACTOR dstRGBFact = EBF_ZERO; - E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; - E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; - E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; - u32 alphaSource = 0; - - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); - - CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), - getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); - } - - // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver. - - if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) - GL.LineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); - - // Anti aliasing - if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) - { - if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) - GL.Enable(GL_SAMPLE_ALPHA_TO_COVERAGE); - else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) - GL.Disable(GL_SAMPLE_ALPHA_TO_COVERAGE); - } - - // Texture parameters - setTextureRenderStates(material, resetAllRenderStates); - } - - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates) - { - // Set textures to TU/TIU and apply filters to them - - for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) - { - const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i]; - - if (!tmpTexture) - continue; - - GLenum tmpTextureType = tmpTexture->getOpenGLTextureType(); - - CacheHandler->setActiveTexture(GL_TEXTURE0 + i); - - if (resetAllRenderstates) - tmpTexture->getStatesCache().IsCached = false; - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MagFilter != tmpTexture->getStatesCache().MagFilter) - { - E_TEXTURE_MAG_FILTER magFilter = material.TextureLayers[i].MagFilter; - GL.TexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER, - magFilter == ETMAGF_NEAREST ? GL_NEAREST : - (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); - - tmpTexture->getStatesCache().MagFilter = magFilter; - } - - if (material.UseMipMaps && tmpTexture->hasMipMaps()) - { - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MinFilter != tmpTexture->getStatesCache().MinFilter || - !tmpTexture->getStatesCache().MipMapStatus) - { - E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; - GL.TexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : - minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST : - minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); - - tmpTexture->getStatesCache().MinFilter = minFilter; - tmpTexture->getStatesCache().MipMapStatus = true; - } - } - else - { - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MinFilter != tmpTexture->getStatesCache().MinFilter || - tmpTexture->getStatesCache().MipMapStatus) - { - E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; - GL.TexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : - (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); - - tmpTexture->getStatesCache().MinFilter = minFilter; - tmpTexture->getStatesCache().MipMapStatus = false; - } - } - - if (AnisotropicFilterSupported && - (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter)) - { - GL.TexParameteri(tmpTextureType, GL.TEXTURE_MAX_ANISOTROPY, - material.TextureLayers[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); - - tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayers[i].AnisotropicFilter; - } - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].TextureWrapU != tmpTexture->getStatesCache().WrapU) - { - GL.TexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayers[i].TextureWrapU)); - tmpTexture->getStatesCache().WrapU = material.TextureLayers[i].TextureWrapU; - } - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].TextureWrapV != tmpTexture->getStatesCache().WrapV) - { - GL.TexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayers[i].TextureWrapV)); - tmpTexture->getStatesCache().WrapV = material.TextureLayers[i].TextureWrapV; - } - - tmpTexture->getStatesCache().IsCached = true; - } - } - - - // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode. - GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const - { - switch (clamp) - { - case ETC_CLAMP: - case ETC_CLAMP_TO_EDGE: - case ETC_CLAMP_TO_BORDER: - return GL_CLAMP_TO_EDGE; - case ETC_MIRROR: - return GL_REPEAT; - default: - return GL_REPEAT; - } - } - - - //! sets the needed renderstates - void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) - { - if ( LockRenderStateMode ) - return; - - COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture; - - if (CurrentRenderMode != ERM_2D) - { - // unset last 3d material - if (CurrentRenderMode == ERM_3D) - { - if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); - } - - CurrentRenderMode = ERM_2D; - } - else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer) - { - MaterialRenderer2DActive->OnUnsetMaterial(); - } - - MaterialRenderer2DActive = nextActiveRenderer; - - MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0); - LastMaterial = Material; - CacheHandler->correctCacheMaterial(LastMaterial); - - // no alphaChannel without texture - alphaChannel &= texture; - - if (alphaChannel || alpha) - { - CacheHandler->setBlend(true); - CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - CacheHandler->setBlendEquation(GL_FUNC_ADD); - } - else - CacheHandler->setBlend(false); - - Material.setTexture(0, const_cast(CacheHandler->getTextureCache().get(0))); - setTransform(ETS_TEXTURE_0, core::IdentityMatrix); - - if (texture) - { - if (OverrideMaterial2DEnabled) - setTextureRenderStates(OverrideMaterial2D, false); - else - setTextureRenderStates(InitMaterial2D, false); - } - - MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD); - } - - - void COpenGL3DriverBase::chooseMaterial2D() - { - if (!OverrideMaterial2DEnabled) - Material = InitMaterial2D; - - if (OverrideMaterial2DEnabled) - { - OverrideMaterial2D.Lighting=false; - OverrideMaterial2D.ZWriteEnable=EZW_OFF; - OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge - OverrideMaterial2D.Lighting=false; - - Material = OverrideMaterial2D; - } - } - - - //! \return Returns the name of the video driver. - const char* COpenGL3DriverBase::getName() const - { - return Name.c_str(); - } - - void COpenGL3DriverBase::setViewPort(const core::rect& area) - { - core::rect vp = area; - core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); - vp.clipAgainst(rendert); - - if (vp.getHeight() > 0 && vp.getWidth() > 0) - CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight()); - - ViewPort = vp; - } - - - void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height) - { - CacheHandler->setViewport(0, 0, width, height); - ViewPort = core::recti(0, 0, width, height); - } - - - //! Draws a 3d line. - void COpenGL3DriverBase::draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color) - { - setRenderStates3DMode(); + f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f; S3DVertex vertices[2]; - vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0); + vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1); drawArrays(GL_LINES, vtPrimitive, vertices, 2); } +} +void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]) +{ + drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4); +} - //! Only used by the internal engine. Used to notify the driver that - //! the window was resized. - void COpenGL3DriverBase::OnResize(const core::dimension2d& size) - { - CNullDriver::OnResize(size); - CacheHandler->setViewport(0, 0, size.Width, size.Height); - Transformation3DChanged = true; +void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount) +{ + beginDraw(vertexType, reinterpret_cast(vertices)); + GL.DrawArrays(primitiveType, 0, vertexCount); + endDraw(vertexType); +} + +void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount) +{ + beginDraw(vertexType, reinterpret_cast(vertices)); + GL.DrawRangeElements(primitiveType, 0, vertexCount - 1, indexCount, GL_UNSIGNED_SHORT, indices); + endDraw(vertexType); +} + +void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase) +{ + for (auto attr : vertexType) { + GL.EnableVertexAttribArray(attr.Index); + switch (attr.mode) { + case VertexAttribute::Mode::Regular: + GL.VertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); + break; + case VertexAttribute::Mode::Normalized: + GL.VertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); + break; + case VertexAttribute::Mode::Integral: + GL.VertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); + break; + } } +} +void COpenGL3DriverBase::endDraw(const VertexType &vertexType) +{ + for (auto attr : vertexType) + GL.DisableVertexAttribArray(attr.Index); +} - //! Returns type of video driver - E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const - { - return EDT_OPENGL3; +ITexture *COpenGL3DriverBase::createDeviceDependentTexture(const io::path &name, IImage *image) +{ + core::array imageArray(1); + imageArray.push_back(image); + + COpenGL3Texture *texture = new COpenGL3Texture(name, imageArray, ETT_2D, this); + + return texture; +} + +ITexture *COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) +{ + COpenGL3Texture *texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this); + + return texture; +} + +//! Sets a material. +void COpenGL3DriverBase::setMaterial(const SMaterial &material) +{ + Material = material; + OverrideMaterial.apply(Material); + + for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) { + CacheHandler->getTextureCache().set(i, material.getTexture(i)); + setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); } +} - - //! returns color format - ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const - { - return ColorFormat; - } - - - //! Get a vertex shader constant index. - s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name) - { - return getPixelShaderConstantID(name); - } - - //! Get a pixel shader constant index. - s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name) - { - os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID()."); - return -1; - } - - //! Sets a constant for the vertex shader based on an index. - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); +//! prints error if an error happened. +bool COpenGL3DriverBase::testGLError(int code) +{ +#ifdef _DEBUG + GLenum g = GL.GetError(); + switch (g) { + case GL_NO_ERROR: return false; - } + case GL_INVALID_ENUM: + os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_INVALID_VALUE: + os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_INVALID_OPERATION: + os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_OUT_OF_MEMORY: + os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); + break; + }; + return true; +#else + return false; +#endif +} - //! Int interface for the above. - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); +//! prints error if an error happened. +bool COpenGL3DriverBase::testEGLError() +{ +#if defined(EGL_VERSION_1_0) && defined(_DEBUG) + EGLint g = eglGetError(); + switch (g) { + case EGL_SUCCESS: return false; + case EGL_NOT_INITIALIZED: + os::Printer::log("Not Initialized", ELL_ERROR); + break; + case EGL_BAD_ACCESS: + os::Printer::log("Bad Access", ELL_ERROR); + break; + case EGL_BAD_ALLOC: + os::Printer::log("Bad Alloc", ELL_ERROR); + break; + case EGL_BAD_ATTRIBUTE: + os::Printer::log("Bad Attribute", ELL_ERROR); + break; + case EGL_BAD_CONTEXT: + os::Printer::log("Bad Context", ELL_ERROR); + break; + case EGL_BAD_CONFIG: + os::Printer::log("Bad Config", ELL_ERROR); + break; + case EGL_BAD_CURRENT_SURFACE: + os::Printer::log("Bad Current Surface", ELL_ERROR); + break; + case EGL_BAD_DISPLAY: + os::Printer::log("Bad Display", ELL_ERROR); + break; + case EGL_BAD_SURFACE: + os::Printer::log("Bad Surface", ELL_ERROR); + break; + case EGL_BAD_MATCH: + os::Printer::log("Bad Match", ELL_ERROR); + break; + case EGL_BAD_PARAMETER: + os::Printer::log("Bad Parameter", ELL_ERROR); + break; + case EGL_BAD_NATIVE_PIXMAP: + os::Printer::log("Bad Native Pixmap", ELL_ERROR); + break; + case EGL_BAD_NATIVE_WINDOW: + os::Printer::log("Bad Native Window", ELL_ERROR); + break; + case EGL_CONTEXT_LOST: + os::Printer::log("Context Lost", ELL_ERROR); + break; + }; + return true; +#else + return false; +#endif +} + +void COpenGL3DriverBase::setRenderStates3DMode() +{ + if (LockRenderStateMode) + return; + + if (CurrentRenderMode != ERM_3D) { + // Reset Texture Stages + CacheHandler->setBlend(false); + CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + ResetRenderStates = true; } - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); - return false; + if (ResetRenderStates || LastMaterial != Material) { + // unset old material + + // unset last 3d material + if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive) { + MaterialRenderer2DActive->OnUnsetMaterial(); + MaterialRenderer2DActive = 0; + } else if (LastMaterial.MaterialType != Material.MaterialType && + static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); + + // set new material. + if (static_cast(Material.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( + Material, LastMaterial, ResetRenderStates, this); + + LastMaterial = Material; + CacheHandler->correctCacheMaterial(LastMaterial); + ResetRenderStates = false; } - //! Sets a constant for the pixel shader based on an index. - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; + if (static_cast(Material.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD); + + CurrentRenderMode = ERM_3D; +} + +//! Can be called by an IMaterialRenderer to make its work easier. +void COpenGL3DriverBase::setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, bool resetAllRenderStates) +{ + // ZBuffer + switch (material.ZBuffer) { + case ECFN_DISABLED: + CacheHandler->setDepthTest(false); + break; + case ECFN_LESSEQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_LEQUAL); + break; + case ECFN_EQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_EQUAL); + break; + case ECFN_LESS: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_LESS); + break; + case ECFN_NOTEQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_NOTEQUAL); + break; + case ECFN_GREATEREQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_GEQUAL); + break; + case ECFN_GREATER: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_GREATER); + break; + case ECFN_ALWAYS: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_ALWAYS); + break; + case ECFN_NEVER: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_NEVER); + break; + default: + break; } - //! Int interface for the above. - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; + // ZWrite + if (getWriteZBuffer(material)) { + CacheHandler->setDepthMask(true); + } else { + CacheHandler->setDepthMask(false); } - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; + // Back face culling + if ((material.FrontfaceCulling) && (material.BackfaceCulling)) { + CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK); + CacheHandler->setCullFace(true); + } else if (material.BackfaceCulling) { + CacheHandler->setCullFaceFunc(GL_BACK); + CacheHandler->setCullFace(true); + } else if (material.FrontfaceCulling) { + CacheHandler->setCullFaceFunc(GL_FRONT); + CacheHandler->setCullFace(true); + } else { + CacheHandler->setCullFace(false); } - //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. - s32 COpenGL3DriverBase::addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, - E_GEOMETRY_SHADER_TYPE gsCompileTarget, - scene::E_PRIMITIVE_TYPE inType, - scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) - { - s32 nr = -1; - COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer( + // Color Mask + CacheHandler->setColorMask(material.ColorMask); + + // Blend Equation + if (material.BlendOperation == EBO_NONE) + CacheHandler->setBlend(false); + else { + CacheHandler->setBlend(true); + + switch (material.BlendOperation) { + case EBO_ADD: + CacheHandler->setBlendEquation(GL_FUNC_ADD); + break; + case EBO_SUBTRACT: + CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); + break; + case EBO_REVSUBTRACT: + CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + break; + case EBO_MIN: + if (BlendMinMaxSupported) + CacheHandler->setBlendEquation(GL_MIN); + else + os::Printer::log("Attempt to use EBO_MIN without driver support", ELL_WARNING); + break; + case EBO_MAX: + if (BlendMinMaxSupported) + CacheHandler->setBlendEquation(GL_MAX); + else + os::Printer::log("Attempt to use EBO_MAX without driver support", ELL_WARNING); + break; + default: + break; + } + } + + // Blend Factor + if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? + && material.MaterialType != EMT_ONETEXTURE_BLEND) { + E_BLEND_FACTOR srcRGBFact = EBF_ZERO; + E_BLEND_FACTOR dstRGBFact = EBF_ZERO; + E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; + E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; + E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; + u32 alphaSource = 0; + + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); + + CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), + getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); + } + + // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver. + + if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) + GL.LineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); + + // Anti aliasing + if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) { + if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) + GL.Enable(GL_SAMPLE_ALPHA_TO_COVERAGE); + else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) + GL.Disable(GL_SAMPLE_ALPHA_TO_COVERAGE); + } + + // Texture parameters + setTextureRenderStates(material, resetAllRenderStates); +} + +//! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. +void COpenGL3DriverBase::setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates) +{ + // Set textures to TU/TIU and apply filters to them + + for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) { + const COpenGL3Texture *tmpTexture = CacheHandler->getTextureCache()[i]; + + if (!tmpTexture) + continue; + + GLenum tmpTextureType = tmpTexture->getOpenGLTextureType(); + + CacheHandler->setActiveTexture(GL_TEXTURE0 + i); + + if (resetAllRenderstates) + tmpTexture->getStatesCache().IsCached = false; + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MagFilter != tmpTexture->getStatesCache().MagFilter) { + E_TEXTURE_MAG_FILTER magFilter = material.TextureLayers[i].MagFilter; + GL.TexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER, + magFilter == ETMAGF_NEAREST ? GL_NEAREST : (assert(magFilter == ETMAGF_LINEAR), GL_LINEAR)); + + tmpTexture->getStatesCache().MagFilter = magFilter; + } + + if (material.UseMipMaps && tmpTexture->hasMipMaps()) { + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MinFilter != tmpTexture->getStatesCache().MinFilter || + !tmpTexture->getStatesCache().MipMapStatus) { + E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; + GL.TexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, + minFilter == ETMINF_NEAREST_MIPMAP_NEAREST ? GL_NEAREST_MIPMAP_NEAREST : minFilter == ETMINF_LINEAR_MIPMAP_NEAREST ? GL_LINEAR_MIPMAP_NEAREST + : minFilter == ETMINF_NEAREST_MIPMAP_LINEAR ? GL_NEAREST_MIPMAP_LINEAR + : (assert(minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR_MIPMAP_LINEAR)); + + tmpTexture->getStatesCache().MinFilter = minFilter; + tmpTexture->getStatesCache().MipMapStatus = true; + } + } else { + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].MinFilter != tmpTexture->getStatesCache().MinFilter || + tmpTexture->getStatesCache().MipMapStatus) { + E_TEXTURE_MIN_FILTER minFilter = material.TextureLayers[i].MinFilter; + GL.TexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, + (minFilter == ETMINF_NEAREST_MIPMAP_NEAREST || minFilter == ETMINF_NEAREST_MIPMAP_LINEAR) ? GL_NEAREST : (assert(minFilter == ETMINF_LINEAR_MIPMAP_NEAREST || minFilter == ETMINF_LINEAR_MIPMAP_LINEAR), GL_LINEAR)); + + tmpTexture->getStatesCache().MinFilter = minFilter; + tmpTexture->getStatesCache().MipMapStatus = false; + } + } + + if (AnisotropicFilterSupported && + (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter)) { + GL.TexParameteri(tmpTextureType, GL.TEXTURE_MAX_ANISOTROPY, + material.TextureLayers[i].AnisotropicFilter > 1 ? core::min_(MaxAnisotropy, material.TextureLayers[i].AnisotropicFilter) : 1); + + tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayers[i].AnisotropicFilter; + } + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].TextureWrapU != tmpTexture->getStatesCache().WrapU) { + GL.TexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayers[i].TextureWrapU)); + tmpTexture->getStatesCache().WrapU = material.TextureLayers[i].TextureWrapU; + } + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayers[i].TextureWrapV != tmpTexture->getStatesCache().WrapV) { + GL.TexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayers[i].TextureWrapV)); + tmpTexture->getStatesCache().WrapV = material.TextureLayers[i].TextureWrapV; + } + + tmpTexture->getStatesCache().IsCached = true; + } +} + +// Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode. +GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const +{ + switch (clamp) { + case ETC_CLAMP: + case ETC_CLAMP_TO_EDGE: + case ETC_CLAMP_TO_BORDER: + return GL_CLAMP_TO_EDGE; + case ETC_MIRROR: + return GL_REPEAT; + default: + return GL_REPEAT; + } +} + +//! sets the needed renderstates +void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) +{ + if (LockRenderStateMode) + return; + + COpenGL3Renderer2D *nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture; + + if (CurrentRenderMode != ERM_2D) { + // unset last 3d material + if (CurrentRenderMode == ERM_3D) { + if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); + } + + CurrentRenderMode = ERM_2D; + } else if (MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer) { + MaterialRenderer2DActive->OnUnsetMaterial(); + } + + MaterialRenderer2DActive = nextActiveRenderer; + + MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0); + LastMaterial = Material; + CacheHandler->correctCacheMaterial(LastMaterial); + + // no alphaChannel without texture + alphaChannel &= texture; + + if (alphaChannel || alpha) { + CacheHandler->setBlend(true); + CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + CacheHandler->setBlendEquation(GL_FUNC_ADD); + } else + CacheHandler->setBlend(false); + + Material.setTexture(0, const_cast(CacheHandler->getTextureCache().get(0))); + setTransform(ETS_TEXTURE_0, core::IdentityMatrix); + + if (texture) { + if (OverrideMaterial2DEnabled) + setTextureRenderStates(OverrideMaterial2D, false); + else + setTextureRenderStates(InitMaterial2D, false); + } + + MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD); +} + +void COpenGL3DriverBase::chooseMaterial2D() +{ + if (!OverrideMaterial2DEnabled) + Material = InitMaterial2D; + + if (OverrideMaterial2DEnabled) { + OverrideMaterial2D.Lighting = false; + OverrideMaterial2D.ZWriteEnable = EZW_OFF; + OverrideMaterial2D.ZBuffer = ECFN_DISABLED; // it will be ECFN_DISABLED after merge + OverrideMaterial2D.Lighting = false; + + Material = OverrideMaterial2D; + } +} + +//! \return Returns the name of the video driver. +const char *COpenGL3DriverBase::getName() const +{ + return Name.c_str(); +} + +void COpenGL3DriverBase::setViewPort(const core::rect &area) +{ + core::rect vp = area; + core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); + vp.clipAgainst(rendert); + + if (vp.getHeight() > 0 && vp.getWidth() > 0) + CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight()); + + ViewPort = vp; +} + +void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height) +{ + CacheHandler->setViewport(0, 0, width, height); + ViewPort = core::recti(0, 0, width, height); +} + +//! Draws a 3d line. +void COpenGL3DriverBase::draw3DLine(const core::vector3df &start, + const core::vector3df &end, SColor color) +{ + setRenderStates3DMode(); + + S3DVertex vertices[2]; + vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0); + + drawArrays(GL_LINES, vtPrimitive, vertices, 2); +} + +//! Only used by the internal engine. Used to notify the driver that +//! the window was resized. +void COpenGL3DriverBase::OnResize(const core::dimension2d &size) +{ + CNullDriver::OnResize(size); + CacheHandler->setViewport(0, 0, size.Width, size.Height); + Transformation3DChanged = true; +} + +//! Returns type of video driver +E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const +{ + return EDT_OPENGL3; +} + +//! returns color format +ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const +{ + return ColorFormat; +} + +//! Get a vertex shader constant index. +s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8 *name) +{ + return getPixelShaderConstantID(name); +} + +//! Get a pixel shader constant index. +s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8 *name) +{ + os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID()."); + return -1; +} + +//! Sets a constant for the vertex shader based on an index. +bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32 *floats, int count) +{ + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; +} + +//! Int interface for the above. +bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32 *ints, int count) +{ + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; +} + +bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32 *ints, int count) +{ + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; +} + +//! Sets a constant for the pixel shader based on an index. +bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32 *floats, int count) +{ + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; +} + +//! Int interface for the above. +bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32 *ints, int count) +{ + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; +} + +bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32 *ints, int count) +{ + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; +} + +//! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. +s32 COpenGL3DriverBase::addHighLevelShaderMaterial( + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8 *pixelShaderProgram, + const c8 *pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8 *geometryShaderProgram, + const c8 *geometryShaderEntryPointName, + E_GEOMETRY_SHADER_TYPE gsCompileTarget, + scene::E_PRIMITIVE_TYPE inType, + scene::E_PRIMITIVE_TYPE outType, + u32 verticesOut, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) +{ + s32 nr = -1; + COpenGL3MaterialRenderer *r = new COpenGL3MaterialRenderer( this, nr, vertexShaderProgram, pixelShaderProgram, callback, baseMaterial, userData); - r->drop(); - return nr; + r->drop(); + return nr; +} + +//! Returns a pointer to the IVideoDriver interface. (Implementation for +//! IMaterialRendererServices) +IVideoDriver *COpenGL3DriverBase::getVideoDriver() +{ + return this; +} + +//! Returns pointer to the IGPUProgrammingServices interface. +IGPUProgrammingServices *COpenGL3DriverBase::getGPUProgrammingServices() +{ + return this; +} + +ITexture *COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format) +{ + // disable mip-mapping + bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + + COpenGL3Texture *renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this); + addTexture(renderTargetTexture); + renderTargetTexture->drop(); + + // restore mip-mapping + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); + + return renderTargetTexture; +} + +ITexture *COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path &name, const ECOLOR_FORMAT format) +{ + // disable mip-mapping + bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + + bool supportForFBO = (Feature.ColorAttachment > 0); + + const core::dimension2d size(sideLen, sideLen); + core::dimension2du destSize(size); + + if (!supportForFBO) { + destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); + destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); } - //! Returns a pointer to the IVideoDriver interface. (Implementation for - //! IMaterialRendererServices) - IVideoDriver* COpenGL3DriverBase::getVideoDriver() - { - return this; + COpenGL3Texture *renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this); + addTexture(renderTargetTexture); + renderTargetTexture->drop(); + + // restore mip-mapping + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); + + return renderTargetTexture; +} + +//! Returns the maximum amount of primitives +u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const +{ + return 65535; +} + +bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) +{ + if (target && target->getDriverType() != getDriverType()) { + os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR); + return false; } + core::dimension2d destRenderTargetSize(0, 0); - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices() - { - return this; + if (target) { + COpenGL3RenderTarget *renderTarget = static_cast(target); + + CacheHandler->setFBO(renderTarget->getBufferID()); + renderTarget->update(); + + destRenderTargetSize = renderTarget->getSize(); + + setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); + } else { + CacheHandler->setFBO(0); + + destRenderTargetSize = core::dimension2d(0, 0); + + setViewPortRaw(ScreenSize.Width, ScreenSize.Height); } - ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format) - { - //disable mip-mapping - bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + if (CurrentRenderTargetSize != destRenderTargetSize) { + CurrentRenderTargetSize = destRenderTargetSize; - COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this); - addTexture(renderTargetTexture); - renderTargetTexture->drop(); - - //restore mip-mapping - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); - - return renderTargetTexture; + Transformation3DChanged = true; } - ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format) - { - //disable mip-mapping - bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + CurrentRenderTarget = target; - bool supportForFBO = (Feature.ColorAttachment > 0); + clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); - const core::dimension2d size(sideLen, sideLen); - core::dimension2du destSize(size); + return true; +} - if (!supportForFBO) - { - destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); - destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); - } +void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) +{ + GLbitfield mask = 0; + u8 colorMask = 0; + bool depthMask = false; - COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this); - addTexture(renderTargetTexture); - renderTargetTexture->drop(); + CacheHandler->getColorMask(colorMask); + CacheHandler->getDepthMask(depthMask); - //restore mip-mapping - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); + if (flag & ECBF_COLOR) { + CacheHandler->setColorMask(ECP_ALL); - return renderTargetTexture; - } - - - //! Returns the maximum amount of primitives - u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const - { - return 65535; - } - - bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) - { - if (target && target->getDriverType() != getDriverType()) - { - os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR); - return false; - } - - core::dimension2d destRenderTargetSize(0, 0); - - if (target) - { - COpenGL3RenderTarget* renderTarget = static_cast(target); - - CacheHandler->setFBO(renderTarget->getBufferID()); - renderTarget->update(); - - destRenderTargetSize = renderTarget->getSize(); - - setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); - } - else - { - CacheHandler->setFBO(0); - - destRenderTargetSize = core::dimension2d(0, 0); - - setViewPortRaw(ScreenSize.Width, ScreenSize.Height); - } - - if (CurrentRenderTargetSize != destRenderTargetSize) - { - CurrentRenderTargetSize = destRenderTargetSize; - - Transformation3DChanged = true; - } - - CurrentRenderTarget = target; - - clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); - - return true; - } - - void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) - { - GLbitfield mask = 0; - u8 colorMask = 0; - bool depthMask = false; - - CacheHandler->getColorMask(colorMask); - CacheHandler->getDepthMask(depthMask); - - if (flag & ECBF_COLOR) - { - CacheHandler->setColorMask(ECP_ALL); - - const f32 inv = 1.0f / 255.0f; - GL.ClearColor(color.getRed() * inv, color.getGreen() * inv, + const f32 inv = 1.0f / 255.0f; + GL.ClearColor(color.getRed() * inv, color.getGreen() * inv, color.getBlue() * inv, color.getAlpha() * inv); - mask |= GL_COLOR_BUFFER_BIT; - } - - if (flag & ECBF_DEPTH) - { - CacheHandler->setDepthMask(true); - GL.ClearDepthf(depth); - mask |= GL_DEPTH_BUFFER_BIT; - } - - if (flag & ECBF_STENCIL) - { - GL.ClearStencil(stencil); - mask |= GL_STENCIL_BUFFER_BIT; - } - - if (mask) - GL.Clear(mask); - - CacheHandler->setColorMask(colorMask); - CacheHandler->setDepthMask(depthMask); + mask |= GL_COLOR_BUFFER_BIT; } + if (flag & ECBF_DEPTH) { + CacheHandler->setDepthMask(true); + GL.ClearDepthf(depth); + mask |= GL_DEPTH_BUFFER_BIT; + } - //! Returns an image created from the last rendered frame. - // We want to read the front buffer to get the latest render finished. - // This is not possible under ogl-es, though, so one has to call this method - // outside of the render loop only. - IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) + if (flag & ECBF_STENCIL) { + GL.ClearStencil(stencil); + mask |= GL_STENCIL_BUFFER_BIT; + } + + if (mask) + GL.Clear(mask); + + CacheHandler->setColorMask(colorMask); + CacheHandler->setDepthMask(depthMask); +} + +//! Returns an image created from the last rendered frame. +// We want to read the front buffer to get the latest render finished. +// This is not possible under ogl-es, though, so one has to call this method +// outside of the render loop only. +IImage *COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) +{ + if (target == video::ERT_MULTI_RENDER_TEXTURES || target == video::ERT_RENDER_TEXTURE || target == video::ERT_STEREO_BOTH_BUFFERS) + return 0; + + GLint internalformat = GL_RGBA; + GLint type = GL_UNSIGNED_BYTE; { - if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS) - return 0; - - GLint internalformat = GL_RGBA; - GLint type = GL_UNSIGNED_BYTE; - { -// GL.GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat); -// GL.GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type); - // there's a format we don't support ATM - if (GL_UNSIGNED_SHORT_4_4_4_4 == type) - { - internalformat = GL_RGBA; - type = GL_UNSIGNED_BYTE; - } + // GL.GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat); + // GL.GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type); + // there's a format we don't support ATM + if (GL_UNSIGNED_SHORT_4_4_4_4 == type) { + internalformat = GL_RGBA; + type = GL_UNSIGNED_BYTE; } + } - IImage* newImage = 0; - if (GL_RGBA == internalformat) - { - if (GL_UNSIGNED_BYTE == type) - newImage = new CImage(ECF_A8R8G8B8, ScreenSize); - else - newImage = new CImage(ECF_A1R5G5B5, ScreenSize); - } + IImage *newImage = 0; + if (GL_RGBA == internalformat) { + if (GL_UNSIGNED_BYTE == type) + newImage = new CImage(ECF_A8R8G8B8, ScreenSize); else - { - if (GL_UNSIGNED_BYTE == type) - newImage = new CImage(ECF_R8G8B8, ScreenSize); - else - newImage = new CImage(ECF_R5G6B5, ScreenSize); - } + newImage = new CImage(ECF_A1R5G5B5, ScreenSize); + } else { + if (GL_UNSIGNED_BYTE == type) + newImage = new CImage(ECF_R8G8B8, ScreenSize); + else + newImage = new CImage(ECF_R5G6B5, ScreenSize); + } - if (!newImage) - return 0; + if (!newImage) + return 0; - u8* pixels = static_cast(newImage->getData()); - if (!pixels) - { - newImage->drop(); - return 0; - } + u8 *pixels = static_cast(newImage->getData()); + if (!pixels) { + newImage->drop(); + return 0; + } - GL.ReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels); - testGLError(__LINE__); + GL.ReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels); + testGLError(__LINE__); - // opengl images are horizontally flipped, so we have to fix that here. - const s32 pitch = newImage->getPitch(); - u8* p2 = pixels + (ScreenSize.Height - 1) * pitch; - u8* tmpBuffer = new u8[pitch]; - for (u32 i = 0; i < ScreenSize.Height; i += 2) - { - memcpy(tmpBuffer, pixels, pitch); - memcpy(pixels, p2, pitch); - memcpy(p2, tmpBuffer, pitch); + // opengl images are horizontally flipped, so we have to fix that here. + const s32 pitch = newImage->getPitch(); + u8 *p2 = pixels + (ScreenSize.Height - 1) * pitch; + u8 *tmpBuffer = new u8[pitch]; + for (u32 i = 0; i < ScreenSize.Height; i += 2) { + memcpy(tmpBuffer, pixels, pitch); + memcpy(pixels, p2, pitch); + memcpy(p2, tmpBuffer, pitch); + pixels += pitch; + p2 -= pitch; + } + delete[] tmpBuffer; + + // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA) + if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type) { + pixels = static_cast(newImage->getData()); + for (u32 i = 0; i < ScreenSize.Height; i++) { + for (u32 j = 0; j < ScreenSize.Width; j++) { + u32 c = *(u32 *)(pixels + 4 * j); + *(u32 *)(pixels + 4 * j) = (c & 0xFF00FF00) | + ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16); + } pixels += pitch; - p2 -= pitch; } - delete [] tmpBuffer; + } - // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA) - if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type) - { - pixels = static_cast(newImage->getData()); - for (u32 i = 0; i < ScreenSize.Height; i++) + if (testGLError(__LINE__)) { + newImage->drop(); + return 0; + } + testGLError(__LINE__); + return newImage; +} + +void COpenGL3DriverBase::removeTexture(ITexture *texture) +{ + CacheHandler->getTextureCache().remove(texture); + CNullDriver::removeTexture(texture); +} + +//! Set/unset a clipping plane. +bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df &plane, bool enable) +{ + if (index >= UserClipPlane.size()) + UserClipPlane.push_back(SUserClipPlane()); + + UserClipPlane[index].Plane = plane; + UserClipPlane[index].Enabled = enable; + return true; +} + +//! Enable/disable a clipping plane. +void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable) +{ + UserClipPlane[index].Enabled = enable; +} + +//! Get the ClipPlane Count +u32 COpenGL3DriverBase::getClipPlaneCount() const +{ + return UserClipPlane.size(); +} + +const core::plane3df &COpenGL3DriverBase::getClipPlane(irr::u32 index) const +{ + if (index < UserClipPlane.size()) + return UserClipPlane[index].Plane; + else { + _IRR_DEBUG_BREAK_IF(true) // invalid index + static const core::plane3df dummy; + return dummy; + } +} + +core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const +{ + return core::dimension2du(MaxTextureSize, MaxTextureSize); +} + +GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const +{ + static GLenum const blendTable[] = { - for (u32 j = 0; j < ScreenSize.Width; j++) - { - u32 c = *(u32*) (pixels + 4 * j); - *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) | - ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16); - } - pixels += pitch; - } - } + GL_ZERO, + GL_ONE, + GL_DST_COLOR, + GL_ONE_MINUS_DST_COLOR, + GL_SRC_COLOR, + GL_ONE_MINUS_SRC_COLOR, + GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA, + GL_DST_ALPHA, + GL_ONE_MINUS_DST_ALPHA, + GL_SRC_ALPHA_SATURATE}; - if (testGLError(__LINE__)) - { - newImage->drop(); - return 0; - } - testGLError(__LINE__); - return newImage; - } + return blendTable[factor]; +} - void COpenGL3DriverBase::removeTexture(ITexture* texture) - { - CacheHandler->getTextureCache().remove(texture); - CNullDriver::removeTexture(texture); - } +bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const +{ + auto &info = TextureFormats[format]; + internalFormat = info.InternalFormat; + pixelFormat = info.PixelFormat; + pixelType = info.PixelType; + *converter = info.Converter; + return info.InternalFormat != 0; +} - //! Set/unset a clipping plane. - bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable) - { - if (index >= UserClipPlane.size()) - UserClipPlane.push_back(SUserClipPlane()); +bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const +{ + return TextureFormats[format].InternalFormat != 0; +} - UserClipPlane[index].Plane = plane; - UserClipPlane[index].Enabled = enable; - return true; - } +bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial &material) const +{ + return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); +} - //! Enable/disable a clipping plane. - void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable) - { - UserClipPlane[index].Enabled = enable; - } +const SMaterial &COpenGL3DriverBase::getCurrentMaterial() const +{ + return Material; +} - //! Get the ClipPlane Count - u32 COpenGL3DriverBase::getClipPlaneCount() const - { - return UserClipPlane.size(); - } - - const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const - { - if (index < UserClipPlane.size()) - return UserClipPlane[index].Plane; - else - { - _IRR_DEBUG_BREAK_IF(true) // invalid index - static const core::plane3df dummy; - return dummy; - } - } - - core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const - { - return core::dimension2du(MaxTextureSize, MaxTextureSize); - } - - GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const - { - static GLenum const blendTable[] = - { - GL_ZERO, - GL_ONE, - GL_DST_COLOR, - GL_ONE_MINUS_DST_COLOR, - GL_SRC_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_SRC_ALPHA, - GL_ONE_MINUS_SRC_ALPHA, - GL_DST_ALPHA, - GL_ONE_MINUS_DST_ALPHA, - GL_SRC_ALPHA_SATURATE - }; - - return blendTable[factor]; - } - - bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const - { - auto &info = TextureFormats[format]; - internalFormat = info.InternalFormat; - pixelFormat = info.PixelFormat; - pixelType = info.PixelType; - *converter = info.Converter; - return info.InternalFormat != 0; - } - - bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const - { - return TextureFormats[format].InternalFormat != 0; - } - - bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const - { - return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); - } - - const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const - { - return Material; - } - - COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const - { - return CacheHandler; - } +COpenGL3CacheHandler *COpenGL3DriverBase::getCacheHandler() const +{ + return CacheHandler; +} } // end namespace } // end namespace diff --git a/source/Irrlicht/OpenGL/Driver.h b/source/Irrlicht/OpenGL/Driver.h index 00ad98fc..b0ac8278 100644 --- a/source/Irrlicht/OpenGL/Driver.h +++ b/source/Irrlicht/OpenGL/Driver.h @@ -20,381 +20,380 @@ namespace irr { namespace video { - struct VertexType; +struct VertexType; - class COpenGL3FixedPipelineRenderer; - class COpenGL3Renderer2D; +class COpenGL3FixedPipelineRenderer; +class COpenGL3Renderer2D; - class COpenGL3DriverBase : public CNullDriver, public IMaterialRendererServices, public COpenGL3ExtensionHandler +class COpenGL3DriverBase : public CNullDriver, public IMaterialRendererServices, public COpenGL3ExtensionHandler +{ + friend class COpenGLCoreTexture; + +protected: + //! constructor (use createOpenGL3Driver instead) + COpenGL3DriverBase(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); + +public: + //! destructor + virtual ~COpenGL3DriverBase(); + + virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData &videoData = SExposedVideoData(), core::rect *sourceRect = 0) override; + + bool endScene() override; + + //! sets transformation + void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4 &mat) override; + + struct SHWBufferLink_opengl : public SHWBufferLink { - friend class COpenGLCoreTexture; - - protected: - //! constructor (use createOpenGL3Driver instead) - COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - - public: - - //! destructor - virtual ~COpenGL3DriverBase(); - - virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; - - bool endScene() override; - - //! sets transformation - void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; - - struct SHWBufferLink_opengl : public SHWBufferLink + SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer) : + SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0), vbo_verticesSize(0), vbo_indicesSize(0) { - SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer) - : SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0) - , vbo_verticesSize(0), vbo_indicesSize(0) - {} - - u32 vbo_verticesID; //tmp - u32 vbo_indicesID; //tmp - - u32 vbo_verticesSize; //tmp - u32 vbo_indicesSize; //tmp - }; - - bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - - //! updates hardware buffer if needed - bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; - - //! Create hardware buffer from mesh - SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) override; - - //! Delete hardware buffer (only some drivers can) - void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - - //! Draw hardware buffer - void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - - IRenderTarget* addRenderTarget() override; - - //! draws a vertex primitive list - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - - //! queries the features of the driver, returns true if feature is available - bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override - { - return FeatureEnabled[feature] && COpenGL3ExtensionHandler::queryFeature(feature); } - //! Sets a material. - void setMaterial(const SMaterial& material) override; + u32 vbo_verticesID; // tmp + u32 vbo_indicesID; // tmp - virtual void draw2DImage(const video::ITexture* texture, - const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect = 0, - SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; + u32 vbo_verticesSize; // tmp + u32 vbo_indicesSize; // tmp + }; - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect = 0, - const video::SColor* const colors = 0, bool useAlphaChannelOfTexture = false) override; + bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - // internally used - virtual void draw2DImage(const video::ITexture* texture, u32 layer, bool flip); + //! updates hardware buffer if needed + bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; - void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) override; + //! Create hardware buffer from mesh + SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer *mb) override; - //! draw an 2d rectangle - virtual void draw2DRectangle(SColor color, const core::rect& pos, - const core::rect* clip = 0) override; + //! Delete hardware buffer (only some drivers can) + void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - //!Draws an 2d rectangle with a gradient. - virtual void draw2DRectangle(const core::rect& pos, - SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip = 0) override; + //! Draw hardware buffer + void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - //! Draws a 2d line. - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color = SColor(255, 255, 255, 255)) override; + IRenderTarget *addRenderTarget() override; - //! Draws a 3d line. - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, - SColor color = SColor(255, 255, 255, 255)) override; + //! draws a vertex primitive list + virtual void drawVertexPrimitiveList(const void *vertices, u32 vertexCount, + const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - //! Returns the name of the video driver. - const char* getName() const override; + //! queries the features of the driver, returns true if feature is available + bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override + { + return FeatureEnabled[feature] && COpenGL3ExtensionHandler::queryFeature(feature); + } - //! Returns the maximum texture size supported. - core::dimension2du getMaxTextureSize() const override; + //! Sets a material. + void setMaterial(const SMaterial &material) override; - //! sets a viewport - void setViewPort(const core::rect& area) override; + virtual void draw2DImage(const video::ITexture *texture, + const core::position2d &destPos, + const core::rect &sourceRect, const core::rect *clipRect = 0, + SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; - //! Only used internally by the engine - void OnResize(const core::dimension2d& size) override; + virtual void draw2DImage(const video::ITexture *texture, const core::rect &destRect, + const core::rect &sourceRect, const core::rect *clipRect = 0, + const video::SColor *const colors = 0, bool useAlphaChannelOfTexture = false) override; - //! Returns type of video driver - E_DRIVER_TYPE getDriverType() const override; + // internally used + virtual void draw2DImage(const video::ITexture *texture, u32 layer, bool flip); - //! get color format of the current color buffer - ECOLOR_FORMAT getColorFormat() const override; + void draw2DImageBatch(const video::ITexture *texture, + const core::array> &positions, + const core::array> &sourceRects, + const core::rect *clipRect, + SColor color, + bool useAlphaChannelOfTexture) override; - //! Returns the transformation set by setTransform - const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; + //! draw an 2d rectangle + virtual void draw2DRectangle(SColor color, const core::rect &pos, + const core::rect *clip = 0) override; - //! Can be called by an IMaterialRenderer to make its work easier. - void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderstates) override; + //! Draws an 2d rectangle with a gradient. + virtual void draw2DRectangle(const core::rect &pos, + SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, + const core::rect *clip = 0) override; - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - void setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates); + //! Draws a 2d line. + virtual void draw2DLine(const core::position2d &start, + const core::position2d &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! Get a vertex shader constant index. - s32 getVertexShaderConstantID(const c8* name) override; + //! Draws a 3d line. + virtual void draw3DLine(const core::vector3df &start, + const core::vector3df &end, + SColor color = SColor(255, 255, 255, 255)) override; - //! Get a pixel shader constant index. - s32 getPixelShaderConstantID(const c8* name) override; + //! Returns the name of the video driver. + const char *getName() const override; - //! Sets a constant for the vertex shader based on an index. - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; + //! Returns the maximum texture size supported. + core::dimension2du getMaxTextureSize() const override; - //! Int interface for the above. - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; + //! sets a viewport + void setViewPort(const core::rect &area) override; - //! Uint interface for the above. - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; + //! Only used internally by the engine + void OnResize(const core::dimension2d &size) override; - //! Sets a constant for the pixel shader based on an index. - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; + //! Returns type of video driver + E_DRIVER_TYPE getDriverType() const override; - //! Int interface for the above. - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; + //! get color format of the current color buffer + ECOLOR_FORMAT getColorFormat() const override; - //! Uint interface for the above. - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + //! Returns the transformation set by setTransform + const core::matrix4 &getTransform(E_TRANSFORMATION_STATE state) const override; - //! Adds a new material renderer to the VideoDriver - virtual s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName = 0, - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - const c8* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = 0, - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - const c8* geometryShaderProgram = 0, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData=0) override; + //! Can be called by an IMaterialRenderer to make its work easier. + void setBasicRenderStates(const SMaterial &material, const SMaterial &lastmaterial, bool resetAllRenderstates) override; - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* getGPUProgrammingServices() override; + //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. + void setTextureRenderStates(const SMaterial &material, bool resetAllRenderstates); - //! Returns a pointer to the IVideoDriver interface. - IVideoDriver* getVideoDriver() override; + //! Get a vertex shader constant index. + s32 getVertexShaderConstantID(const c8 *name) override; - //! Returns the maximum amount of primitives - u32 getMaximalPrimitiveCount() const override; + //! Get a pixel shader constant index. + s32 getPixelShaderConstantID(const c8 *name) override; - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + //! Sets a constant for the vertex shader based on an index. + bool setVertexShaderConstant(s32 index, const f32 *floats, int count) override; - //! Creates a render target texture for a cubemap - ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) override; + //! Int interface for the above. + bool setVertexShaderConstant(s32 index, const s32 *ints, int count) override; - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), + //! Uint interface for the above. + bool setVertexShaderConstant(s32 index, const u32 *ints, int count) override; + + //! Sets a constant for the pixel shader based on an index. + bool setPixelShaderConstant(s32 index, const f32 *floats, int count) override; + + //! Int interface for the above. + bool setPixelShaderConstant(s32 index, const s32 *ints, int count) override; + + //! Uint interface for the above. + bool setPixelShaderConstant(s32 index, const u32 *ints, int count) override; + + //! Adds a new material renderer to the VideoDriver + virtual s32 addHighLevelShaderMaterial( + const c8 *vertexShaderProgram, + const c8 *vertexShaderEntryPointName = 0, + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const c8 *pixelShaderProgram = 0, + const c8 *pixelShaderEntryPointName = 0, + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + const c8 *geometryShaderProgram = 0, + const c8 *geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData = 0) override; + + //! Returns pointer to the IGPUProgrammingServices interface. + IGPUProgrammingServices *getGPUProgrammingServices() override; + + //! Returns a pointer to the IVideoDriver interface. + IVideoDriver *getVideoDriver() override; + + //! Returns the maximum amount of primitives + u32 getMaximalPrimitiveCount() const override; + + virtual ITexture *addRenderTargetTexture(const core::dimension2d &size, + const io::path &name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + + //! Creates a render target texture for a cubemap + ITexture *addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path &name, const ECOLOR_FORMAT format) override; + + virtual bool setRenderTargetEx(IRenderTarget *target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0) override; - void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; + void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; - //! Returns an image created from the last rendered frame. - IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; + //! Returns an image created from the last rendered frame. + IImage *createScreenShot(video::ECOLOR_FORMAT format = video::ECF_UNKNOWN, video::E_RENDER_TARGET target = video::ERT_FRAME_BUFFER) override; - //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) - bool testGLError(int code=0); + //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) + bool testGLError(int code = 0); - //! checks if an OGLES1 error has happened and prints it - bool testEGLError(); + //! checks if an OGLES1 error has happened and prints it + bool testEGLError(); - //! Set/unset a clipping plane. - bool setClipPlane(u32 index, const core::plane3df& plane, bool enable = false) override; + //! Set/unset a clipping plane. + bool setClipPlane(u32 index, const core::plane3df &plane, bool enable = false) override; - //! returns the current amount of user clip planes set. - u32 getClipPlaneCount() const; + //! returns the current amount of user clip planes set. + u32 getClipPlaneCount() const; - //! returns the 0 indexed Plane - const core::plane3df& getClipPlane(u32 index) const; + //! returns the 0 indexed Plane + const core::plane3df &getClipPlane(u32 index) const; - //! Enable/disable a clipping plane. - void enableClipPlane(u32 index, bool enable) override; + //! Enable/disable a clipping plane. + void enableClipPlane(u32 index, bool enable) override; - //! Returns the graphics card vendor name. - core::stringc getVendorInfo() override - { - return VendorName; - }; + //! Returns the graphics card vendor name. + core::stringc getVendorInfo() override + { + return VendorName; + }; - void removeTexture(ITexture* texture) override; + void removeTexture(ITexture *texture) override; - //! Check if the driver supports creating textures with the given color format - bool queryTextureFormat(ECOLOR_FORMAT format) const override; + //! Check if the driver supports creating textures with the given color format + bool queryTextureFormat(ECOLOR_FORMAT format) const override; - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + bool needsTransparentRenderPass(const irr::video::SMaterial &material) const override; - //! Convert E_BLEND_FACTOR to OpenGL equivalent - GLenum getGLBlend(E_BLEND_FACTOR factor) const; + //! Convert E_BLEND_FACTOR to OpenGL equivalent + GLenum getGLBlend(E_BLEND_FACTOR factor) const; - virtual bool getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const; + virtual bool getColorFormatParameters(ECOLOR_FORMAT format, GLint &internalFormat, GLenum &pixelFormat, + GLenum &pixelType, void (**converter)(const void *, s32, void *)) const; - //! Get current material. - const SMaterial& getCurrentMaterial() const; + //! Get current material. + const SMaterial &getCurrentMaterial() const; - COpenGL3CacheHandler* getCacheHandler() const; + COpenGL3CacheHandler *getCacheHandler() const; - protected: - virtual bool genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer); +protected: + virtual bool genericDriverInit(const core::dimension2d &screenSize, bool stencilBuffer); - void initVersion(); - virtual OpenGLVersion getVersionFromOpenGL() const = 0; + void initVersion(); + virtual OpenGLVersion getVersionFromOpenGL() const = 0; - virtual void initFeatures() = 0; + virtual void initFeatures() = 0; - bool isVersionAtLeast(int major, int minor = 0) const noexcept; + bool isVersionAtLeast(int major, int minor = 0) const noexcept; - void chooseMaterial2D(); + void chooseMaterial2D(); - ITexture* createDeviceDependentTexture(const io::path& name, IImage* image) override; + ITexture *createDeviceDependentTexture(const io::path &name, IImage *image) override; - ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) override; + ITexture *createDeviceDependentTextureCubemap(const io::path &name, const core::array &image) override; - //! Map Irrlicht wrap mode to OpenGL enum - GLint getTextureWrapMode(u8 clamp) const; + //! Map Irrlicht wrap mode to OpenGL enum + GLint getTextureWrapMode(u8 clamp) const; - //! sets the needed renderstates - void setRenderStates3DMode(); + //! sets the needed renderstates + void setRenderStates3DMode(); - //! sets the needed renderstates - void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); + //! sets the needed renderstates + void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); - //! Prevent setRenderStateMode calls to do anything. - // hack to allow drawing meshbuffers in 2D mode. - // Better solution would be passing this flag through meshbuffers, - // but the way this is currently implemented in Irrlicht makes this tricky to implement - void lockRenderStateMode() - { - LockRenderStateMode = true; - } + //! Prevent setRenderStateMode calls to do anything. + // hack to allow drawing meshbuffers in 2D mode. + // Better solution would be passing this flag through meshbuffers, + // but the way this is currently implemented in Irrlicht makes this tricky to implement + void lockRenderStateMode() + { + LockRenderStateMode = true; + } - //! Allow setRenderStateMode calls to work again - void unlockRenderStateMode() - { - LockRenderStateMode = false; - } + //! Allow setRenderStateMode calls to work again + void unlockRenderStateMode() + { + LockRenderStateMode = false; + } - void draw2D3DVertexPrimitiveList(const void* vertices, - u32 vertexCount, const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, - E_INDEX_TYPE iType, bool is3D); + void draw2D3DVertexPrimitiveList(const void *vertices, + u32 vertexCount, const void *indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, + E_INDEX_TYPE iType, bool is3D); - void createMaterialRenderers(); + void createMaterialRenderers(); - void loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData); + void loadShaderData(const io::path &vertexShaderName, const io::path &fragmentShaderName, c8 **vertexShaderData, c8 **fragmentShaderData); - bool setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture); + bool setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture *texture); - //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` - virtual void setViewPortRaw(u32 width, u32 height); + //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` + virtual void setViewPortRaw(u32 width, u32 height); - void drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]); - void drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount); - void drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount); - void drawElements(GLenum primitiveType, const VertexType &vertexType, uintptr_t vertices, uintptr_t indices, int indexCount); + void drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]); + void drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount); + void drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount); + void drawElements(GLenum primitiveType, const VertexType &vertexType, uintptr_t vertices, uintptr_t indices, int indexCount); - void beginDraw(const VertexType &vertexType, uintptr_t verticesBase); - void endDraw(const VertexType &vertexType); + void beginDraw(const VertexType &vertexType, uintptr_t verticesBase); + void endDraw(const VertexType &vertexType); - COpenGL3CacheHandler* CacheHandler; - core::stringc Name; - core::stringc VendorName; - SIrrlichtCreationParameters Params; - OpenGLVersion Version; + COpenGL3CacheHandler *CacheHandler; + core::stringc Name; + core::stringc VendorName; + SIrrlichtCreationParameters Params; + OpenGLVersion Version; - //! bool to make all renderstates reset if set to true. - bool ResetRenderStates; - bool LockRenderStateMode; - u8 AntiAlias; + //! bool to make all renderstates reset if set to true. + bool ResetRenderStates; + bool LockRenderStateMode; + u8 AntiAlias; - struct SUserClipPlane - { - core::plane3df Plane; - bool Enabled; - }; + struct SUserClipPlane + { + core::plane3df Plane; + bool Enabled; + }; - core::array UserClipPlane; + core::array UserClipPlane; - core::matrix4 TextureFlipMatrix; + core::matrix4 TextureFlipMatrix; - using FColorConverter = void(*)(const void *source, s32 count, void *dest); - struct STextureFormatInfo { - GLenum InternalFormat; - GLenum PixelFormat; - GLenum PixelType; - FColorConverter Converter; - }; - STextureFormatInfo TextureFormats[ECF_UNKNOWN] = {}; + using FColorConverter = void (*)(const void *source, s32 count, void *dest); + struct STextureFormatInfo + { + GLenum InternalFormat; + GLenum PixelFormat; + GLenum PixelType; + FColorConverter Converter; + }; + STextureFormatInfo TextureFormats[ECF_UNKNOWN] = {}; private: + COpenGL3Renderer2D *MaterialRenderer2DActive; + COpenGL3Renderer2D *MaterialRenderer2DTexture; + COpenGL3Renderer2D *MaterialRenderer2DNoTexture; - COpenGL3Renderer2D* MaterialRenderer2DActive; - COpenGL3Renderer2D* MaterialRenderer2DTexture; - COpenGL3Renderer2D* MaterialRenderer2DNoTexture; + core::matrix4 Matrices[ETS_COUNT]; - core::matrix4 Matrices[ETS_COUNT]; - - //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. - enum E_RENDER_MODE - { - ERM_NONE = 0, // no render state has been set yet. - ERM_2D, // 2d drawing rendermode - ERM_3D // 3d rendering mode - }; - - E_RENDER_MODE CurrentRenderMode; - bool Transformation3DChanged; - irr::io::path OGLES2ShaderPath; - - SMaterial Material, LastMaterial; - - //! Color buffer format - ECOLOR_FORMAT ColorFormat; - - IContextManager* ContextManager; - - void printTextureFormats(); - - void addDummyMaterial(E_MATERIAL_TYPE type); - - unsigned QuadIndexCount; - GLuint QuadIndexBuffer = 0; - void initQuadsIndices(int max_vertex_count = 65536); - - void debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message); - static void APIENTRY debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); + //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. + enum E_RENDER_MODE + { + ERM_NONE = 0, // no render state has been set yet. + ERM_2D, // 2d drawing rendermode + ERM_3D // 3d rendering mode }; + E_RENDER_MODE CurrentRenderMode; + bool Transformation3DChanged; + irr::io::path OGLES2ShaderPath; + + SMaterial Material, LastMaterial; + + //! Color buffer format + ECOLOR_FORMAT ColorFormat; + + IContextManager *ContextManager; + + void printTextureFormats(); + + void addDummyMaterial(E_MATERIAL_TYPE type); + + unsigned QuadIndexCount; + GLuint QuadIndexBuffer = 0; + void initQuadsIndices(int max_vertex_count = 65536); + + void debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message); + static void APIENTRY debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); +}; + } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/OpenGL/ExtensionHandler.cpp b/source/Irrlicht/OpenGL/ExtensionHandler.cpp index 594fa4a2..3ac21298 100644 --- a/source/Irrlicht/OpenGL/ExtensionHandler.cpp +++ b/source/Irrlicht/OpenGL/ExtensionHandler.cpp @@ -18,41 +18,44 @@ namespace irr { namespace video { - void COpenGL3ExtensionHandler::initExtensionsOld() - { - auto extensions_string = reinterpret_cast(GL.GetString(GL_EXTENSIONS)); - const char *pos = extensions_string; - while (const char *next = strchr(pos, ' ')) { - addExtension(std::string{pos, next}); - pos = next + 1; - } - addExtension(pos); - extensionsLoaded(); +void COpenGL3ExtensionHandler::initExtensionsOld() +{ + auto extensions_string = reinterpret_cast(GL.GetString(GL_EXTENSIONS)); + const char *pos = extensions_string; + while (const char *next = strchr(pos, ' ')) { + addExtension(std::string{pos, next}); + pos = next + 1; } + addExtension(pos); + extensionsLoaded(); +} - void COpenGL3ExtensionHandler::initExtensionsNew() - { - int ext_count = GetInteger(GL_NUM_EXTENSIONS); - for (int k = 0; k < ext_count; k++) - addExtension(reinterpret_cast(GL.GetStringi(GL_EXTENSIONS, k))); - extensionsLoaded(); - } +void COpenGL3ExtensionHandler::initExtensionsNew() +{ + int ext_count = GetInteger(GL_NUM_EXTENSIONS); + for (int k = 0; k < ext_count; k++) + addExtension(reinterpret_cast(GL.GetStringi(GL_EXTENSIONS, k))); + extensionsLoaded(); +} - void COpenGL3ExtensionHandler::addExtension(std::string &&name) { - Extensions.emplace(std::move(name)); - } +void COpenGL3ExtensionHandler::addExtension(std::string &&name) +{ + Extensions.emplace(std::move(name)); +} - bool COpenGL3ExtensionHandler::queryExtension(const std::string &name) const noexcept { - return Extensions.find(name) != Extensions.end(); - } +bool COpenGL3ExtensionHandler::queryExtension(const std::string &name) const noexcept +{ + return Extensions.find(name) != Extensions.end(); +} - void COpenGL3ExtensionHandler::extensionsLoaded() { - os::Printer::log((std::string("Loaded ") + std::to_string(Extensions.size()) + " extensions:").c_str(), ELL_DEBUG); - for (const auto &it : Extensions) - os::Printer::log((std::string(" ") + it).c_str(), ELL_DEBUG); - for (size_t j = 0; j < IRR_OGLES_Feature_Count; ++j) - FeatureAvailable[j] = queryExtension(getFeatureString(j)); - } +void COpenGL3ExtensionHandler::extensionsLoaded() +{ + os::Printer::log((std::string("Loaded ") + std::to_string(Extensions.size()) + " extensions:").c_str(), ELL_DEBUG); + for (const auto &it : Extensions) + os::Printer::log((std::string(" ") + it).c_str(), ELL_DEBUG); + for (size_t j = 0; j < IRR_OGLES_Feature_Count; ++j) + FeatureAvailable[j] = queryExtension(getFeatureString(j)); +} } // end namespace video } // end namespace irr diff --git a/source/Irrlicht/OpenGL/ExtensionHandler.h b/source/Irrlicht/OpenGL/ExtensionHandler.h index 5b6420a5..8f96f0d4 100644 --- a/source/Irrlicht/OpenGL/ExtensionHandler.h +++ b/source/Irrlicht/OpenGL/ExtensionHandler.h @@ -22,148 +22,149 @@ namespace irr namespace video { - class COpenGL3ExtensionHandler : public COGLESCoreExtensionHandler +class COpenGL3ExtensionHandler : public COGLESCoreExtensionHandler +{ +public: + COpenGL3ExtensionHandler() : + COGLESCoreExtensionHandler() {} + + void initExtensionsOld(); + void initExtensionsNew(); + + /// Checks whether a named extension is present + bool queryExtension(const std::string &name) const noexcept; + + bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const { - public: - COpenGL3ExtensionHandler() : COGLESCoreExtensionHandler() {} - - void initExtensionsOld(); - void initExtensionsNew(); - - /// Checks whether a named extension is present - bool queryExtension(const std::string &name) const noexcept; - - bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const - { - switch (feature) - { - case EVDF_RENDER_TO_TARGET: - case EVDF_HARDWARE_TL: - case EVDF_MULTITEXTURE: - case EVDF_BILINEAR_FILTER: - case EVDF_MIP_MAP: - case EVDF_MIP_MAP_AUTO_UPDATE: - case EVDF_VERTEX_SHADER_1_1: - case EVDF_PIXEL_SHADER_1_1: - case EVDF_PIXEL_SHADER_1_2: - case EVDF_PIXEL_SHADER_2_0: - case EVDF_VERTEX_SHADER_2_0: - case EVDF_ARB_GLSL: - case EVDF_TEXTURE_NSQUARE: - case EVDF_TEXTURE_NPOT: - case EVDF_FRAMEBUFFER_OBJECT: - case EVDF_VERTEX_BUFFER_OBJECT: - case EVDF_COLOR_MASK: - case EVDF_ALPHA_TO_COVERAGE: - case EVDF_POLYGON_OFFSET: - case EVDF_BLEND_OPERATIONS: - case EVDF_BLEND_SEPARATE: - case EVDF_TEXTURE_MATRIX: - case EVDF_TEXTURE_CUBEMAP: - return true; - case EVDF_ARB_VERTEX_PROGRAM_1: - case EVDF_ARB_FRAGMENT_PROGRAM_1: - case EVDF_GEOMETRY_SHADER: - case EVDF_MULTIPLE_RENDER_TARGETS: - case EVDF_MRT_BLEND: - case EVDF_MRT_COLOR_MASK: - case EVDF_MRT_BLEND_FUNC: - case EVDF_OCCLUSION_QUERY: - return false; - case EVDF_STENCIL_BUFFER: - return StencilBuffer; - default: - return false; - }; - } - - static GLint GetInteger(GLenum key) { - GLint val = 0; - GL.GetIntegerv(key, &val); - return val; + switch (feature) { + case EVDF_RENDER_TO_TARGET: + case EVDF_HARDWARE_TL: + case EVDF_MULTITEXTURE: + case EVDF_BILINEAR_FILTER: + case EVDF_MIP_MAP: + case EVDF_MIP_MAP_AUTO_UPDATE: + case EVDF_VERTEX_SHADER_1_1: + case EVDF_PIXEL_SHADER_1_1: + case EVDF_PIXEL_SHADER_1_2: + case EVDF_PIXEL_SHADER_2_0: + case EVDF_VERTEX_SHADER_2_0: + case EVDF_ARB_GLSL: + case EVDF_TEXTURE_NSQUARE: + case EVDF_TEXTURE_NPOT: + case EVDF_FRAMEBUFFER_OBJECT: + case EVDF_VERTEX_BUFFER_OBJECT: + case EVDF_COLOR_MASK: + case EVDF_ALPHA_TO_COVERAGE: + case EVDF_POLYGON_OFFSET: + case EVDF_BLEND_OPERATIONS: + case EVDF_BLEND_SEPARATE: + case EVDF_TEXTURE_MATRIX: + case EVDF_TEXTURE_CUBEMAP: + return true; + case EVDF_ARB_VERTEX_PROGRAM_1: + case EVDF_ARB_FRAGMENT_PROGRAM_1: + case EVDF_GEOMETRY_SHADER: + case EVDF_MULTIPLE_RENDER_TARGETS: + case EVDF_MRT_BLEND: + case EVDF_MRT_COLOR_MASK: + case EVDF_MRT_BLEND_FUNC: + case EVDF_OCCLUSION_QUERY: + return false; + case EVDF_STENCIL_BUFFER: + return StencilBuffer; + default: + return false; }; + } - inline void irrGlActiveTexture(GLenum texture) - { - GL.ActiveTexture(texture); - } - - inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, - GLsizei imageSize, const void* data) - { - os::Printer::log("Compressed textures aren't supported", ELL_ERROR); - } - - inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLsizei imageSize, const void* data) - { - os::Printer::log("Compressed textures aren't supported", ELL_ERROR); - } - - inline void irrGlUseProgram(GLuint prog) - { - GL.UseProgram(prog); - } - - inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) - { - GL.BindFramebuffer(target, framebuffer); - } - - inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) - { - GL.DeleteFramebuffers(n, framebuffers); - } - - inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) - { - GL.GenFramebuffers(n, framebuffers); - } - - inline GLenum irrGlCheckFramebufferStatus(GLenum target) - { - return GL.CheckFramebufferStatus(target); - } - - inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) - { - GL.FramebufferTexture2D(target, attachment, textarget, texture, level); - } - - inline void irrGlGenerateMipmap(GLenum target) - { - GL.GenerateMipmap(target); - } - - inline void irrGlDrawBuffer(GLenum mode) - { - GL.DrawBuffer(mode); - } - - inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) - { - GL.DrawBuffers(n, bufs); - } - - inline void irrGlBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) - { - GL.BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); - } - - inline void irrGlBlendEquation(GLenum mode) - { - GL.BlendEquation(mode); - } - - bool AnisotropicFilterSupported = false; - bool BlendMinMaxSupported = false; - - private: - void addExtension(std::string &&name); - void extensionsLoaded(); - - std::unordered_set Extensions; + static GLint GetInteger(GLenum key) + { + GLint val = 0; + GL.GetIntegerv(key, &val); + return val; }; + inline void irrGlActiveTexture(GLenum texture) + { + GL.ActiveTexture(texture); + } + + inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, + GLsizei imageSize, const void *data) + { + os::Printer::log("Compressed textures aren't supported", ELL_ERROR); + } + + inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, + GLenum format, GLsizei imageSize, const void *data) + { + os::Printer::log("Compressed textures aren't supported", ELL_ERROR); + } + + inline void irrGlUseProgram(GLuint prog) + { + GL.UseProgram(prog); + } + + inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) + { + GL.BindFramebuffer(target, framebuffer); + } + + inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) + { + GL.DeleteFramebuffers(n, framebuffers); + } + + inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) + { + GL.GenFramebuffers(n, framebuffers); + } + + inline GLenum irrGlCheckFramebufferStatus(GLenum target) + { + return GL.CheckFramebufferStatus(target); + } + + inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) + { + GL.FramebufferTexture2D(target, attachment, textarget, texture, level); + } + + inline void irrGlGenerateMipmap(GLenum target) + { + GL.GenerateMipmap(target); + } + + inline void irrGlDrawBuffer(GLenum mode) + { + GL.DrawBuffer(mode); + } + + inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) + { + GL.DrawBuffers(n, bufs); + } + + inline void irrGlBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) + { + GL.BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); + } + + inline void irrGlBlendEquation(GLenum mode) + { + GL.BlendEquation(mode); + } + + bool AnisotropicFilterSupported = false; + bool BlendMinMaxSupported = false; + +private: + void addExtension(std::string &&name); + void extensionsLoaded(); + + std::unordered_set Extensions; +}; + } } diff --git a/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp b/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp index d67c9efa..7c4adf71 100644 --- a/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp +++ b/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp @@ -15,14 +15,14 @@ namespace video // Base callback COpenGL3MaterialBaseCB::COpenGL3MaterialBaseCB() : - FirstUpdateBase(true), WVPMatrixID(-1), WVMatrixID(-1), NMatrixID(-1), - FogEnableID(-1), FogTypeID(-1), FogColorID(-1), FogStartID(-1), - FogEndID(-1), FogDensityID(-1), ThicknessID(-1), LightEnable(false), MaterialAmbient(SColorf(0.f, 0.f, 0.f)), MaterialDiffuse(SColorf(0.f, 0.f, 0.f)), MaterialEmissive(SColorf(0.f, 0.f, 0.f)), MaterialSpecular(SColorf(0.f, 0.f, 0.f)), - MaterialShininess(0.f), FogEnable(0), FogType(1), FogColor(SColorf(0.f, 0.f, 0.f, 1.f)), FogStart(0.f), FogEnd(0.f), FogDensity(0.f), Thickness(1.f) + FirstUpdateBase(true), WVPMatrixID(-1), WVMatrixID(-1), NMatrixID(-1), + FogEnableID(-1), FogTypeID(-1), FogColorID(-1), FogStartID(-1), + FogEndID(-1), FogDensityID(-1), ThicknessID(-1), LightEnable(false), MaterialAmbient(SColorf(0.f, 0.f, 0.f)), MaterialDiffuse(SColorf(0.f, 0.f, 0.f)), MaterialEmissive(SColorf(0.f, 0.f, 0.f)), MaterialSpecular(SColorf(0.f, 0.f, 0.f)), + MaterialShininess(0.f), FogEnable(0), FogType(1), FogColor(SColorf(0.f, 0.f, 0.f, 1.f)), FogStart(0.f), FogEnd(0.f), FogDensity(0.f), Thickness(1.f) { } -void COpenGL3MaterialBaseCB::OnSetMaterial(const SMaterial& material) +void COpenGL3MaterialBaseCB::OnSetMaterial(const SMaterial &material) { LightEnable = material.Lighting; MaterialAmbient = SColorf(material.AmbientColor); @@ -36,12 +36,11 @@ void COpenGL3MaterialBaseCB::OnSetMaterial(const SMaterial& material) Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; } -void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices *services, s32 userData) { - IVideoDriver* driver = services->getVideoDriver(); + IVideoDriver *driver = services->getVideoDriver(); - if (FirstUpdateBase) - { + if (FirstUpdateBase) { WVPMatrixID = services->getVertexShaderConstantID("uWVPMatrix"); WVMatrixID = services->getVertexShaderConstantID("uWVMatrix"); NMatrixID = services->getVertexShaderConstantID("uNMatrix"); @@ -72,8 +71,7 @@ void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, services->setPixelShaderConstant(FogEnableID, &FogEnable, 1); - if (FogEnable) - { + if (FogEnable) { SColor TempColor(0); E_FOG_TYPE TempType = EFT_FOG_LINEAR; bool TempPerFragment = false; @@ -85,7 +83,7 @@ void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, FogColor = SColorf(TempColor); services->setPixelShaderConstant(FogTypeID, &FogType, 1); - services->setPixelShaderConstant(FogColorID, reinterpret_cast(&FogColor), 4); + services->setPixelShaderConstant(FogColorID, reinterpret_cast(&FogColor), 4); services->setPixelShaderConstant(FogStartID, &FogStart, 1); services->setPixelShaderConstant(FogEndID, &FogEnd, 1); services->setPixelShaderConstant(FogDensityID, &FogDensity, 1); @@ -97,11 +95,11 @@ void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, // EMT_SOLID + EMT_TRANSPARENT_ALPHA_CHANNEL + EMT_TRANSPARENT_VERTEX_ALPHA COpenGL3MaterialSolidCB::COpenGL3MaterialSolidCB() : - FirstUpdate(true), TMatrix0ID(-1), AlphaRefID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), AlphaRef(0.5f), TextureUsage0(0), TextureUnit0(0) + FirstUpdate(true), TMatrix0ID(-1), AlphaRefID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), AlphaRef(0.5f), TextureUsage0(0), TextureUnit0(0) { } -void COpenGL3MaterialSolidCB::OnSetMaterial(const SMaterial& material) +void COpenGL3MaterialSolidCB::OnSetMaterial(const SMaterial &material) { COpenGL3MaterialBaseCB::OnSetMaterial(material); @@ -109,14 +107,13 @@ void COpenGL3MaterialSolidCB::OnSetMaterial(const SMaterial& material) TextureUsage0 = (material.TextureLayers[0].Texture) ? 1 : 0; } -void COpenGL3MaterialSolidCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +void COpenGL3MaterialSolidCB::OnSetConstants(IMaterialRendererServices *services, s32 userData) { COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - IVideoDriver* driver = services->getVideoDriver(); + IVideoDriver *driver = services->getVideoDriver(); - if (FirstUpdate) - { + if (FirstUpdate) { TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); AlphaRefID = services->getVertexShaderConstantID("uAlphaRef"); TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); @@ -136,29 +133,25 @@ void COpenGL3MaterialSolidCB::OnSetConstants(IMaterialRendererServices* services // EMT_ONETEXTURE_BLEND COpenGL3MaterialOneTextureBlendCB::COpenGL3MaterialOneTextureBlendCB() : - FirstUpdate(true), TMatrix0ID(-1), BlendTypeID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), BlendType(0), TextureUsage0(0), TextureUnit0(0) + FirstUpdate(true), TMatrix0ID(-1), BlendTypeID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), BlendType(0), TextureUsage0(0), TextureUnit0(0) { } -void COpenGL3MaterialOneTextureBlendCB::OnSetMaterial(const SMaterial& material) +void COpenGL3MaterialOneTextureBlendCB::OnSetMaterial(const SMaterial &material) { COpenGL3MaterialBaseCB::OnSetMaterial(material); BlendType = 0; - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + E_BLEND_FACTOR srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact; E_MODULATE_FUNC modulate; u32 alphaSource; unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) - { - if (alphaSource == EAS_VERTEX_COLOR) - { + if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) { + if (alphaSource == EAS_VERTEX_COLOR) { BlendType = 1; - } - else if (alphaSource == EAS_TEXTURE) - { + } else if (alphaSource == EAS_TEXTURE) { BlendType = 2; } } @@ -166,14 +159,13 @@ void COpenGL3MaterialOneTextureBlendCB::OnSetMaterial(const SMaterial& material) TextureUsage0 = (material.TextureLayers[0].Texture) ? 1 : 0; } -void COpenGL3MaterialOneTextureBlendCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +void COpenGL3MaterialOneTextureBlendCB::OnSetConstants(IMaterialRendererServices *services, s32 userData) { COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - IVideoDriver* driver = services->getVideoDriver(); + IVideoDriver *driver = services->getVideoDriver(); - if (FirstUpdate) - { + if (FirstUpdate) { TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); BlendTypeID = services->getVertexShaderConstantID("uBlendType"); TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); diff --git a/source/Irrlicht/OpenGL/FixedPipelineRenderer.h b/source/Irrlicht/OpenGL/FixedPipelineRenderer.h index 9613d20b..a07af1df 100644 --- a/source/Irrlicht/OpenGL/FixedPipelineRenderer.h +++ b/source/Irrlicht/OpenGL/FixedPipelineRenderer.h @@ -18,8 +18,8 @@ class COpenGL3MaterialBaseCB : public IShaderConstantSetCallBack public: COpenGL3MaterialBaseCB(); - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + virtual void OnSetMaterial(const SMaterial &material); + virtual void OnSetConstants(IMaterialRendererServices *services, s32 userData); protected: bool FirstUpdateBase; @@ -60,8 +60,8 @@ class COpenGL3MaterialSolidCB : public COpenGL3MaterialBaseCB public: COpenGL3MaterialSolidCB(); - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + virtual void OnSetMaterial(const SMaterial &material); + virtual void OnSetConstants(IMaterialRendererServices *services, s32 userData); protected: bool FirstUpdate; @@ -81,8 +81,8 @@ class COpenGL3MaterialOneTextureBlendCB : public COpenGL3MaterialBaseCB public: COpenGL3MaterialOneTextureBlendCB(); - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + virtual void OnSetMaterial(const SMaterial &material); + virtual void OnSetConstants(IMaterialRendererServices *services, s32 userData); protected: bool FirstUpdate; diff --git a/source/Irrlicht/OpenGL/MaterialRenderer.cpp b/source/Irrlicht/OpenGL/MaterialRenderer.cpp index 3eec62f3..51a796d4 100644 --- a/source/Irrlicht/OpenGL/MaterialRenderer.cpp +++ b/source/Irrlicht/OpenGL/MaterialRenderer.cpp @@ -20,22 +20,21 @@ namespace irr namespace video { - -COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - s32& outMaterialTypeNr, - const c8* vertexShaderProgram, - const c8* pixelShaderProgram, - IShaderConstantSetCallBack* callback, +COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase *driver, + s32 &outMaterialTypeNr, + const c8 *vertexShaderProgram, + const c8 *pixelShaderProgram, + IShaderConstantSetCallBack *callback, E_MATERIAL_TYPE baseMaterial, - s32 userData) - : Driver(driver), CallBack(callback), Alpha(false), Blending(false), Program(0), UserData(userData) + s32 userData) : + Driver(driver), + CallBack(callback), Alpha(false), Blending(false), Program(0), UserData(userData) { #ifdef _DEBUG setDebugName("MaterialRenderer"); #endif - switch (baseMaterial) - { + switch (baseMaterial) { case EMT_TRANSPARENT_VERTEX_ALPHA: case EMT_TRANSPARENT_ALPHA_CHANNEL: Alpha = true; @@ -53,14 +52,13 @@ COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, init(outMaterialTypeNr, vertexShaderProgram, pixelShaderProgram); } - -COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, s32 userData) -: Driver(driver), CallBack(callback), Alpha(false), Blending(false), Program(0), UserData(userData) +COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase *driver, + IShaderConstantSetCallBack *callback, + E_MATERIAL_TYPE baseMaterial, s32 userData) : + Driver(driver), + CallBack(callback), Alpha(false), Blending(false), Program(0), UserData(userData) { - switch (baseMaterial) - { + switch (baseMaterial) { case EMT_TRANSPARENT_VERTEX_ALPHA: case EMT_TRANSPARENT_ALPHA_CHANNEL: Alpha = true; @@ -76,20 +74,18 @@ COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, CallBack->grab(); } - COpenGL3MaterialRenderer::~COpenGL3MaterialRenderer() { if (CallBack) CallBack->drop(); - if (Program) - { + if (Program) { GLuint shaders[8]; GLint count; GL.GetAttachedShaders(Program, 8, &count, shaders); - count=core::min_(count,8); - for (GLint i=0; iaddMaterialRenderer(this); } - -bool COpenGL3MaterialRenderer::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) +bool COpenGL3MaterialRenderer::OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype) { if (CallBack && Program) CallBack->OnSetConstants(this, UserData); @@ -142,32 +137,28 @@ bool COpenGL3MaterialRenderer::OnRender(IMaterialRendererServices* service, E_VE return true; } - -void COpenGL3MaterialRenderer::OnSetMaterial(const video::SMaterial& material, - const video::SMaterial& lastMaterial, - bool resetAllRenderstates, - video::IMaterialRendererServices* services) +void COpenGL3MaterialRenderer::OnSetMaterial(const video::SMaterial &material, + const video::SMaterial &lastMaterial, + bool resetAllRenderstates, + video::IMaterialRendererServices *services) { - COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); + COpenGL3CacheHandler *cacheHandler = Driver->getCacheHandler(); cacheHandler->setProgram(Program); Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - if (Alpha) - { + if (Alpha) { cacheHandler->setBlend(true); cacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - else if (Blending) - { - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + } else if (Blending) { + E_BLEND_FACTOR srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact; E_MODULATE_FUNC modulate; u32 alphaSource; unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); cacheHandler->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), - Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); + Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); cacheHandler->setBlend(true); } @@ -176,28 +167,23 @@ void COpenGL3MaterialRenderer::OnSetMaterial(const video::SMaterial& material, CallBack->OnSetMaterial(material); } - void COpenGL3MaterialRenderer::OnUnsetMaterial() { } - bool COpenGL3MaterialRenderer::isTransparent() const { return (Alpha || Blending); } - s32 COpenGL3MaterialRenderer::getRenderCapability() const { return 0; } - -bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char* shader) +bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char *shader) { - if (Program) - { + if (Program) { GLuint shaderHandle = GL.CreateShader(shaderType); GL.ShaderSource(shaderHandle, 1, &shader, NULL); GL.CompileShader(shaderHandle); @@ -206,22 +192,20 @@ bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char* shade GL.GetShaderiv(shaderHandle, GL_COMPILE_STATUS, &status); - if (status != GL_TRUE) - { + if (status != GL_TRUE) { os::Printer::log("GLSL shader failed to compile", ELL_ERROR); - GLint maxLength=0; + GLint maxLength = 0; GLint length; GL.GetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &maxLength); - if (maxLength) - { + if (maxLength) { GLchar *infoLog = new GLchar[maxLength]; GL.GetShaderInfoLog(shaderHandle, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; @@ -233,32 +217,28 @@ bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char* shade return true; } - bool COpenGL3MaterialRenderer::linkProgram() { - if (Program) - { + if (Program) { GL.LinkProgram(Program); GLint status = 0; GL.GetProgramiv(Program, GL_LINK_STATUS, &status); - if (!status) - { + if (!status) { os::Printer::log("GLSL shader program failed to link", ELL_ERROR); - GLint maxLength=0; + GLint maxLength = 0; GLsizei length; GL.GetProgramiv(Program, GL_INFO_LOG_LENGTH, &maxLength); - if (maxLength) - { + if (maxLength) { GLchar *infoLog = new GLchar[maxLength]; GL.GetProgramInfoLog(Program, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete[] infoLog; } return false; @@ -275,8 +255,7 @@ bool COpenGL3MaterialRenderer::linkProgram() GL.GetProgramiv(Program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxlen); - if (maxlen == 0) - { + if (maxlen == 0) { os::Printer::log("GLSL: failed to retrieve uniform information", ELL_ERROR); return false; } @@ -288,23 +267,21 @@ bool COpenGL3MaterialRenderer::linkProgram() UniformInfo.clear(); UniformInfo.reallocate(num); - for (GLint i=0; i < num; ++i) - { + for (GLint i = 0; i < num; ++i) { SUniformInfo ui; memset(buf, 0, maxlen); GLint size; - GL.GetActiveUniform(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); + GL.GetActiveUniform(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); - core::stringc name = ""; + core::stringc name = ""; // array support, workaround for some bugged drivers. - for (s32 i = 0; i < maxlen; ++i) - { + for (s32 i = 0; i < maxlen; ++i) { if (buf[i] == '[' || buf[i] == '\0') break; - name += buf[i]; + name += buf[i]; } ui.name = name; @@ -313,29 +290,27 @@ bool COpenGL3MaterialRenderer::linkProgram() UniformInfo.push_back(ui); } - delete [] buf; + delete[] buf; } return true; } - -void COpenGL3MaterialRenderer::setBasicRenderStates(const SMaterial& material, - const SMaterial& lastMaterial, - bool resetAllRenderstates) +void COpenGL3MaterialRenderer::setBasicRenderStates(const SMaterial &material, + const SMaterial &lastMaterial, + bool resetAllRenderstates) { Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); } -s32 COpenGL3MaterialRenderer::getVertexShaderConstantID(const c8* name) +s32 COpenGL3MaterialRenderer::getVertexShaderConstantID(const c8 *name) { return getPixelShaderConstantID(name); } -s32 COpenGL3MaterialRenderer::getPixelShaderConstantID(const c8* name) +s32 COpenGL3MaterialRenderer::getPixelShaderConstantID(const c8 *name) { - for (u32 i = 0; i < UniformInfo.size(); ++i) - { + for (u32 i = 0; i < UniformInfo.size(); ++i) { if (UniformInfo[i].name == name) return i; } @@ -343,115 +318,109 @@ s32 COpenGL3MaterialRenderer::getPixelShaderConstantID(const c8* name) return -1; } -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const f32* floats, int count) +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const f32 *floats, int count) { return setPixelShaderConstant(index, floats, count); } -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const s32* ints, int count) +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const s32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const u32* ints, int count) +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const u32 *ints, int count) { return setPixelShaderConstant(index, ints, count); } -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const f32* floats, int count) +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const f32 *floats, int count) { - if(index < 0 || UniformInfo[index].location < 0) + if (index < 0 || UniformInfo[index].location < 0) return false; bool status = true; - switch (UniformInfo[index].type) - { - case GL_FLOAT: - GL.Uniform1fv(UniformInfo[index].location, count, floats); - break; - case GL_FLOAT_VEC2: - GL.Uniform2fv(UniformInfo[index].location, count/2, floats); - break; - case GL_FLOAT_VEC3: - GL.Uniform3fv(UniformInfo[index].location, count/3, floats); - break; - case GL_FLOAT_VEC4: - GL.Uniform4fv(UniformInfo[index].location, count/4, floats); - break; - case GL_FLOAT_MAT2: - GL.UniformMatrix2fv(UniformInfo[index].location, count/4, false, floats); - break; - case GL_FLOAT_MAT3: - GL.UniformMatrix3fv(UniformInfo[index].location, count/9, false, floats); - break; - case GL_FLOAT_MAT4: - GL.UniformMatrix4fv(UniformInfo[index].location, count/16, false, floats); - break; - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - { - if(floats) - { - const GLint id = (GLint)(*floats); - GL.Uniform1iv(UniformInfo[index].location, 1, &id); - } - else - status = false; - } - break; - default: + switch (UniformInfo[index].type) { + case GL_FLOAT: + GL.Uniform1fv(UniformInfo[index].location, count, floats); + break; + case GL_FLOAT_VEC2: + GL.Uniform2fv(UniformInfo[index].location, count / 2, floats); + break; + case GL_FLOAT_VEC3: + GL.Uniform3fv(UniformInfo[index].location, count / 3, floats); + break; + case GL_FLOAT_VEC4: + GL.Uniform4fv(UniformInfo[index].location, count / 4, floats); + break; + case GL_FLOAT_MAT2: + GL.UniformMatrix2fv(UniformInfo[index].location, count / 4, false, floats); + break; + case GL_FLOAT_MAT3: + GL.UniformMatrix3fv(UniformInfo[index].location, count / 9, false, floats); + break; + case GL_FLOAT_MAT4: + GL.UniformMatrix4fv(UniformInfo[index].location, count / 16, false, floats); + break; + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: { + if (floats) { + const GLint id = (GLint)(*floats); + GL.Uniform1iv(UniformInfo[index].location, 1, &id); + } else status = false; - break; + } break; + default: + status = false; + break; } return status; } -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const s32* ints, int count) +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const s32 *ints, int count) { - if(index < 0 || UniformInfo[index].location < 0) + if (index < 0 || UniformInfo[index].location < 0) return false; bool status = true; - switch (UniformInfo[index].type) - { - case GL_INT: - case GL_BOOL: - GL.Uniform1iv(UniformInfo[index].location, count, ints); - break; - case GL_INT_VEC2: - case GL_BOOL_VEC2: - GL.Uniform2iv(UniformInfo[index].location, count/2, ints); - break; - case GL_INT_VEC3: - case GL_BOOL_VEC3: - GL.Uniform3iv(UniformInfo[index].location, count/3, ints); - break; - case GL_INT_VEC4: - case GL_BOOL_VEC4: - GL.Uniform4iv(UniformInfo[index].location, count/4, ints); - break; - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - GL.Uniform1iv(UniformInfo[index].location, 1, ints); - break; - default: - status = false; - break; + switch (UniformInfo[index].type) { + case GL_INT: + case GL_BOOL: + GL.Uniform1iv(UniformInfo[index].location, count, ints); + break; + case GL_INT_VEC2: + case GL_BOOL_VEC2: + GL.Uniform2iv(UniformInfo[index].location, count / 2, ints); + break; + case GL_INT_VEC3: + case GL_BOOL_VEC3: + GL.Uniform3iv(UniformInfo[index].location, count / 3, ints); + break; + case GL_INT_VEC4: + case GL_BOOL_VEC4: + GL.Uniform4iv(UniformInfo[index].location, count / 4, ints); + break; + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + GL.Uniform1iv(UniformInfo[index].location, 1, ints); + break; + default: + status = false; + break; } return status; } -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const u32* ints, int count) +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const u32 *ints, int count) { os::Printer::log("Unsigned int support needs at least GLES 3.0", ELL_WARNING); return false; } -IVideoDriver* COpenGL3MaterialRenderer::getVideoDriver() +IVideoDriver *COpenGL3MaterialRenderer::getVideoDriver() { return Driver; } diff --git a/source/Irrlicht/OpenGL/MaterialRenderer.h b/source/Irrlicht/OpenGL/MaterialRenderer.h index 0d4b5504..be74461e 100644 --- a/source/Irrlicht/OpenGL/MaterialRenderer.h +++ b/source/Irrlicht/OpenGL/MaterialRenderer.h @@ -23,24 +23,23 @@ class COpenGL3DriverBase; class COpenGL3MaterialRenderer : public IMaterialRenderer, public IMaterialRendererServices { public: - COpenGL3MaterialRenderer( - COpenGL3DriverBase* driver, - s32& outMaterialTypeNr, - const c8* vertexShaderProgram = 0, - const c8* pixelShaderProgram = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = EMT_SOLID, - s32 userData = 0); + COpenGL3DriverBase *driver, + s32 &outMaterialTypeNr, + const c8 *vertexShaderProgram = 0, + const c8 *pixelShaderProgram = 0, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = EMT_SOLID, + s32 userData = 0); virtual ~COpenGL3MaterialRenderer(); GLuint getProgram() const; - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services); + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services); - virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); + virtual bool OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype); virtual void OnUnsetMaterial(); @@ -48,33 +47,32 @@ public: virtual s32 getRenderCapability() const; - void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates) override; + void setBasicRenderStates(const SMaterial &material, const SMaterial &lastMaterial, bool resetAllRenderstates) override; - s32 getVertexShaderConstantID(const c8* name) override; - s32 getPixelShaderConstantID(const c8* name) override; - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + s32 getVertexShaderConstantID(const c8 *name) override; + s32 getPixelShaderConstantID(const c8 *name) override; + bool setVertexShaderConstant(s32 index, const f32 *floats, int count) override; + bool setVertexShaderConstant(s32 index, const s32 *ints, int count) override; + bool setVertexShaderConstant(s32 index, const u32 *ints, int count) override; + bool setPixelShaderConstant(s32 index, const f32 *floats, int count) override; + bool setPixelShaderConstant(s32 index, const s32 *ints, int count) override; + bool setPixelShaderConstant(s32 index, const u32 *ints, int count) override; - IVideoDriver* getVideoDriver() override; + IVideoDriver *getVideoDriver() override; protected: + COpenGL3MaterialRenderer(COpenGL3DriverBase *driver, + IShaderConstantSetCallBack *callback = 0, + E_MATERIAL_TYPE baseMaterial = EMT_SOLID, + s32 userData = 0); - COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = EMT_SOLID, - s32 userData = 0); + void init(s32 &outMaterialTypeNr, const c8 *vertexShaderProgram, const c8 *pixelShaderProgram, bool addMaterial = true); - void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram, bool addMaterial = true); - - bool createShader(GLenum shaderType, const char* shader); + bool createShader(GLenum shaderType, const char *shader); bool linkProgram(); - COpenGL3DriverBase* Driver; - IShaderConstantSetCallBack* CallBack; + COpenGL3DriverBase *Driver; + IShaderConstantSetCallBack *CallBack; bool Alpha; bool Blending; @@ -91,6 +89,5 @@ protected: s32 UserData; }; - } } diff --git a/source/Irrlicht/OpenGL/Renderer2D.cpp b/source/Irrlicht/OpenGL/Renderer2D.cpp index 92341d11..b625feda 100644 --- a/source/Irrlicht/OpenGL/Renderer2D.cpp +++ b/source/Irrlicht/OpenGL/Renderer2D.cpp @@ -18,9 +18,9 @@ namespace irr namespace video { -COpenGL3Renderer2D::COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture) : - COpenGL3MaterialRenderer(driver, 0, EMT_SOLID), - WithTexture(withTexture) +COpenGL3Renderer2D::COpenGL3Renderer2D(const c8 *vertexShaderProgram, const c8 *pixelShaderProgram, COpenGL3DriverBase *driver, bool withTexture) : + COpenGL3MaterialRenderer(driver, 0, EMT_SOLID), + WithTexture(withTexture) { #ifdef _DEBUG setDebugName("Renderer2D"); @@ -30,15 +30,14 @@ COpenGL3Renderer2D::COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* init(Temp, vertexShaderProgram, pixelShaderProgram, false); - COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); + COpenGL3CacheHandler *cacheHandler = Driver->getCacheHandler(); cacheHandler->setProgram(Program); // These states don't change later. ThicknessID = getPixelShaderConstantID("uThickness"); - if ( WithTexture ) - { + if (WithTexture) { TextureUsageID = getPixelShaderConstantID("uTextureUsage"); s32 TextureUnitID = getPixelShaderConstantID("uTextureUnit"); @@ -56,10 +55,10 @@ COpenGL3Renderer2D::~COpenGL3Renderer2D() { } -void COpenGL3Renderer2D::OnSetMaterial(const video::SMaterial& material, - const video::SMaterial& lastMaterial, - bool resetAllRenderstates, - video::IMaterialRendererServices* services) +void COpenGL3Renderer2D::OnSetMaterial(const video::SMaterial &material, + const video::SMaterial &lastMaterial, + bool resetAllRenderstates, + video::IMaterialRendererServices *services) { Driver->getCacheHandler()->setProgram(Program); Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); @@ -67,14 +66,13 @@ void COpenGL3Renderer2D::OnSetMaterial(const video::SMaterial& material, f32 Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; setPixelShaderConstant(ThicknessID, &Thickness, 1); - if ( WithTexture ) - { + if (WithTexture) { s32 TextureUsage = material.TextureLayers[0].Texture ? 1 : 0; setPixelShaderConstant(TextureUsageID, &TextureUsage, 1); } } -bool COpenGL3Renderer2D::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) +bool COpenGL3Renderer2D::OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype) { return true; } diff --git a/source/Irrlicht/OpenGL/Renderer2D.h b/source/Irrlicht/OpenGL/Renderer2D.h index 426a8b77..6cfc7029 100644 --- a/source/Irrlicht/OpenGL/Renderer2D.h +++ b/source/Irrlicht/OpenGL/Renderer2D.h @@ -14,13 +14,13 @@ namespace video class COpenGL3Renderer2D : public COpenGL3MaterialRenderer { public: - COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture); + COpenGL3Renderer2D(const c8 *vertexShaderProgram, const c8 *pixelShaderProgram, COpenGL3DriverBase *driver, bool withTexture); ~COpenGL3Renderer2D(); - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services); + virtual void OnSetMaterial(const SMaterial &material, const SMaterial &lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices *services); - virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); + virtual bool OnRender(IMaterialRendererServices *service, E_VERTEX_TYPE vtxtype); protected: bool WithTexture; @@ -28,6 +28,5 @@ protected: s32 TextureUsageID; }; - } } diff --git a/source/Irrlicht/OpenGL3/Driver.cpp b/source/Irrlicht/OpenGL3/Driver.cpp index ee8c2894..ce5449e8 100644 --- a/source/Irrlicht/OpenGL3/Driver.cpp +++ b/source/Irrlicht/OpenGL3/Driver.cpp @@ -6,79 +6,84 @@ #include #include "mt_opengl.h" -namespace irr { -namespace video { +namespace irr +{ +namespace video +{ - E_DRIVER_TYPE COpenGL3Driver::getDriverType() const { - return EDT_OPENGL3; - } +E_DRIVER_TYPE COpenGL3Driver::getDriverType() const +{ + return EDT_OPENGL3; +} - OpenGLVersion COpenGL3Driver::getVersionFromOpenGL() const { - GLint major, minor, profile; - GL.GetIntegerv(GL_MAJOR_VERSION, &major); - GL.GetIntegerv(GL_MINOR_VERSION, &minor); - GL.GetIntegerv(GL_CONTEXT_PROFILE_MASK, &profile); - // The spec is clear a context can’t be both core and compatibility at the same time. - // However, the returned value is a mask. Ask Khronos why. -- numzero - if (profile & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) - return {OpenGLSpec::Compat, (u8)major, (u8)minor, 0}; - if (profile & GL_CONTEXT_CORE_PROFILE_BIT) - return {OpenGLSpec::Core, (u8)major, (u8)minor, 0}; - os::Printer::log("Got unrecognized OpenGL profile", ELL_ERROR); +OpenGLVersion COpenGL3Driver::getVersionFromOpenGL() const +{ + GLint major, minor, profile; + GL.GetIntegerv(GL_MAJOR_VERSION, &major); + GL.GetIntegerv(GL_MINOR_VERSION, &minor); + GL.GetIntegerv(GL_CONTEXT_PROFILE_MASK, &profile); + // The spec is clear a context can’t be both core and compatibility at the same time. + // However, the returned value is a mask. Ask Khronos why. -- numzero + if (profile & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) + return {OpenGLSpec::Compat, (u8)major, (u8)minor, 0}; + if (profile & GL_CONTEXT_CORE_PROFILE_BIT) return {OpenGLSpec::Core, (u8)major, (u8)minor, 0}; - } + os::Printer::log("Got unrecognized OpenGL profile", ELL_ERROR); + return {OpenGLSpec::Core, (u8)major, (u8)minor, 0}; +} - void COpenGL3Driver::initFeatures() { - assert (Version.Spec == OpenGLSpec::Compat); - assert (isVersionAtLeast(3, 2)); - initExtensionsNew(); +void COpenGL3Driver::initFeatures() +{ + assert(Version.Spec == OpenGLSpec::Compat); + assert(isVersionAtLeast(3, 2)); + initExtensionsNew(); - TextureFormats[ECF_A1R5G5B5] = {GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV}; // WARNING: may not be renderable - TextureFormats[ECF_R5G6B5] = {GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; // GL_RGB565 is an extension until 4.1 - TextureFormats[ECF_R8G8B8] = {GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE}; // WARNING: may not be renderable - TextureFormats[ECF_A8R8G8B8] = {GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV}; - TextureFormats[ECF_R16F] = {GL_R16F, GL_RED, GL_HALF_FLOAT}; - TextureFormats[ECF_G16R16F] = {GL_RG16F, GL_RG, GL_HALF_FLOAT}; - TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}; - TextureFormats[ECF_R32F] = {GL_R32F, GL_RED, GL_FLOAT}; - TextureFormats[ECF_G32R32F] = {GL_RG32F, GL_RG, GL_FLOAT}; - TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA32F, GL_RGBA, GL_FLOAT}; - TextureFormats[ECF_R8] = {GL_R8, GL_RED, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_R8G8] = {GL_RG8, GL_RG, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_R16] = {GL_R16, GL_RED, GL_UNSIGNED_SHORT}; - TextureFormats[ECF_R16G16] = {GL_RG16, GL_RG, GL_UNSIGNED_SHORT}; - TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; - TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; // WARNING: may not be renderable (?!) - TextureFormats[ECF_D24S8] = {GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; + TextureFormats[ECF_A1R5G5B5] = {GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV}; // WARNING: may not be renderable + TextureFormats[ECF_R5G6B5] = {GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; // GL_RGB565 is an extension until 4.1 + TextureFormats[ECF_R8G8B8] = {GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE}; // WARNING: may not be renderable + TextureFormats[ECF_A8R8G8B8] = {GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV}; + TextureFormats[ECF_R16F] = {GL_R16F, GL_RED, GL_HALF_FLOAT}; + TextureFormats[ECF_G16R16F] = {GL_RG16F, GL_RG, GL_HALF_FLOAT}; + TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}; + TextureFormats[ECF_R32F] = {GL_R32F, GL_RED, GL_FLOAT}; + TextureFormats[ECF_G32R32F] = {GL_RG32F, GL_RG, GL_FLOAT}; + TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA32F, GL_RGBA, GL_FLOAT}; + TextureFormats[ECF_R8] = {GL_R8, GL_RED, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_R8G8] = {GL_RG8, GL_RG, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_R16] = {GL_R16, GL_RED, GL_UNSIGNED_SHORT}; + TextureFormats[ECF_R16G16] = {GL_RG16, GL_RG, GL_UNSIGNED_SHORT}; + TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; + TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; // WARNING: may not be renderable (?!) + TextureFormats[ECF_D24S8] = {GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; - AnisotropicFilterSupported = isVersionAtLeast(4, 6) || queryExtension("GL_ARB_texture_filter_anisotropic") || queryExtension("GL_EXT_texture_filter_anisotropic"); - BlendMinMaxSupported = true; + AnisotropicFilterSupported = isVersionAtLeast(4, 6) || queryExtension("GL_ARB_texture_filter_anisotropic") || queryExtension("GL_EXT_texture_filter_anisotropic"); + BlendMinMaxSupported = true; - // COGLESCoreExtensionHandler::Feature - static_assert(MATERIAL_MAX_TEXTURES <= 16, "Only up to 16 textures are guaranteed"); - Feature.BlendOperation = true; - Feature.ColorAttachment = GetInteger(GL_MAX_COLOR_ATTACHMENTS); - Feature.MaxTextureUnits = MATERIAL_MAX_TEXTURES; - Feature.MultipleRenderTarget = GetInteger(GL_MAX_DRAW_BUFFERS); + // COGLESCoreExtensionHandler::Feature + static_assert(MATERIAL_MAX_TEXTURES <= 16, "Only up to 16 textures are guaranteed"); + Feature.BlendOperation = true; + Feature.ColorAttachment = GetInteger(GL_MAX_COLOR_ATTACHMENTS); + Feature.MaxTextureUnits = MATERIAL_MAX_TEXTURES; + Feature.MultipleRenderTarget = GetInteger(GL_MAX_DRAW_BUFFERS); - // COGLESCoreExtensionHandler - if (AnisotropicFilterSupported) - MaxAnisotropy = GetInteger(GL.MAX_TEXTURE_MAX_ANISOTROPY); - MaxIndices = GetInteger(GL_MAX_ELEMENTS_INDICES); - MaxTextureSize = GetInteger(GL_MAX_TEXTURE_SIZE); - GL.GetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &MaxTextureLODBias); - GL.GetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); - DimAliasedPoint[0] = 1.0f; - DimAliasedPoint[1] = 1.0f; - } + // COGLESCoreExtensionHandler + if (AnisotropicFilterSupported) + MaxAnisotropy = GetInteger(GL.MAX_TEXTURE_MAX_ANISOTROPY); + MaxIndices = GetInteger(GL_MAX_ELEMENTS_INDICES); + MaxTextureSize = GetInteger(GL_MAX_TEXTURE_SIZE); + GL.GetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &MaxTextureLODBias); + GL.GetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); + DimAliasedPoint[0] = 1.0f; + DimAliasedPoint[1] = 1.0f; +} - IVideoDriver* createOpenGL3Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("Using COpenGL3Driver", ELL_INFORMATION); - COpenGL3Driver* driver = new COpenGL3Driver(params, io, contextManager); - driver->genericDriverInit(params.WindowSize, params.Stencilbuffer); // don't call in constructor, it uses virtual function calls of driver - return driver; - } +IVideoDriver *createOpenGL3Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("Using COpenGL3Driver", ELL_INFORMATION); + COpenGL3Driver *driver = new COpenGL3Driver(params, io, contextManager); + driver->genericDriverInit(params.WindowSize, params.Stencilbuffer); // don't call in constructor, it uses virtual function calls of driver + return driver; +} } } diff --git a/source/Irrlicht/OpenGL3/Driver.h b/source/Irrlicht/OpenGL3/Driver.h index ca9e94af..f4934051 100644 --- a/source/Irrlicht/OpenGL3/Driver.h +++ b/source/Irrlicht/OpenGL3/Driver.h @@ -5,22 +5,26 @@ #pragma once #include "OpenGL/Driver.h" -namespace irr { -namespace video { +namespace irr +{ +namespace video +{ - /// OpenGL 3+ driver - /// - /// For OpenGL 3.2 and higher. Compatibility profile is required currently. - class COpenGL3Driver : public COpenGL3DriverBase { - friend IVideoDriver* createOpenGL3Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - public: - using COpenGL3DriverBase::COpenGL3DriverBase; - E_DRIVER_TYPE getDriverType() const override; +/// OpenGL 3+ driver +/// +/// For OpenGL 3.2 and higher. Compatibility profile is required currently. +class COpenGL3Driver : public COpenGL3DriverBase +{ + friend IVideoDriver *createOpenGL3Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); - protected: - OpenGLVersion getVersionFromOpenGL() const override; - void initFeatures() override; - }; +public: + using COpenGL3DriverBase::COpenGL3DriverBase; + E_DRIVER_TYPE getDriverType() const override; + +protected: + OpenGLVersion getVersionFromOpenGL() const override; + void initFeatures() override; +}; } } diff --git a/source/Irrlicht/OpenGLES2/Driver.cpp b/source/Irrlicht/OpenGLES2/Driver.cpp index 06dcdffc..6278ee9c 100644 --- a/source/Irrlicht/OpenGLES2/Driver.cpp +++ b/source/Irrlicht/OpenGLES2/Driver.cpp @@ -6,137 +6,142 @@ #include #include -namespace irr { -namespace video { +namespace irr +{ +namespace video +{ - E_DRIVER_TYPE COpenGLES2Driver::getDriverType() const { - return EDT_OGLES2; +E_DRIVER_TYPE COpenGLES2Driver::getDriverType() const +{ + return EDT_OGLES2; +} + +OpenGLVersion COpenGLES2Driver::getVersionFromOpenGL() const +{ + auto version_string = reinterpret_cast(GL.GetString(GL_VERSION)); + int major, minor; + if (sscanf(version_string, "OpenGL ES %d.%d", &major, &minor) != 2) { + os::Printer::log("Failed to parse OpenGL ES version string", version_string, ELL_ERROR); + return {OpenGLSpec::ES, 0, 0, 0}; } + return {OpenGLSpec::ES, (u8)major, (u8)minor, 0}; +} - OpenGLVersion COpenGLES2Driver::getVersionFromOpenGL() const { - auto version_string = reinterpret_cast(GL.GetString(GL_VERSION)); - int major, minor; - if (sscanf(version_string, "OpenGL ES %d.%d", &major, &minor) != 2) { - os::Printer::log("Failed to parse OpenGL ES version string", version_string, ELL_ERROR); - return {OpenGLSpec::ES, 0, 0, 0}; +void COpenGLES2Driver::initFeatures() +{ + assert(Version.Spec == OpenGLSpec::ES); + assert(Version.Major >= 2); + if (Version.Major >= 3) + initExtensionsNew(); + else + initExtensionsOld(); + + static const GLenum BGRA8_EXT = 0x93A1; + + if (Version.Major >= 3) { + // NOTE floating-point formats may not be suitable for render targets. + TextureFormats[ECF_A1R5G5B5] = {GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, CColorConverter::convert_A1R5G5B5toR5G5B5A1}; + TextureFormats[ECF_R5G6B5] = {GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; + TextureFormats[ECF_R8G8B8] = {GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_A8R8G8B8] = {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, CColorConverter::convert_A8R8G8B8toA8B8G8R8}; + TextureFormats[ECF_R16F] = {GL_R16F, GL_RED, GL_HALF_FLOAT}; + TextureFormats[ECF_G16R16F] = {GL_RG16F, GL_RG, GL_HALF_FLOAT}; + TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}; + TextureFormats[ECF_R32F] = {GL_R32F, GL_RED, GL_FLOAT}; + TextureFormats[ECF_G32R32F] = {GL_RG32F, GL_RG, GL_FLOAT}; + TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA32F, GL_RGBA, GL_FLOAT}; + TextureFormats[ECF_R8] = {GL_R8, GL_RED, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_R8G8] = {GL_RG8, GL_RG, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; + TextureFormats[ECF_D24S8] = {GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; + + if (FeatureAvailable[IRR_GL_EXT_texture_format_BGRA8888]) + TextureFormats[ECF_A8R8G8B8] = {GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE}; + else if (FeatureAvailable[IRR_GL_APPLE_texture_format_BGRA8888]) + TextureFormats[ECF_A8R8G8B8] = {BGRA8_EXT, GL_BGRA, GL_UNSIGNED_BYTE}; + + if (FeatureAvailable[IRR_GL_OES_depth32]) + TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; + } else { + // NOTE These are *texture* formats. They may or may not be suitable + // for render targets. The specs only talks on *sized* formats for the + // latter but forbids creating textures with sized internal formats, + // reserving them for renderbuffers. + + static const GLenum HALF_FLOAT_OES = 0x8D61; // not equal to GL_HALF_FLOAT + TextureFormats[ECF_A1R5G5B5] = {GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, CColorConverter::convert_A1R5G5B5toR5G5B5A1}; + TextureFormats[ECF_R5G6B5] = {GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; + TextureFormats[ECF_R8G8B8] = {GL_RGB, GL_RGB, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_A8R8G8B8] = {GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, CColorConverter::convert_A8R8G8B8toA8B8G8R8}; + + if (FeatureAvailable[IRR_GL_EXT_texture_format_BGRA8888]) + TextureFormats[ECF_A8R8G8B8] = {GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE}; + else if (FeatureAvailable[IRR_GL_APPLE_texture_format_BGRA8888]) + TextureFormats[ECF_A8R8G8B8] = {BGRA8_EXT, GL_BGRA, GL_UNSIGNED_BYTE}; + + if (FeatureAvailable[IRR_GL_OES_texture_half_float]) { + TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA, GL_RGBA, HALF_FLOAT_OES}; } - return {OpenGLSpec::ES, (u8)major, (u8)minor, 0}; - } - - void COpenGLES2Driver::initFeatures() { - assert (Version.Spec == OpenGLSpec::ES); - assert (Version.Major >= 2); - if (Version.Major >= 3) - initExtensionsNew(); - else - initExtensionsOld(); - - static const GLenum BGRA8_EXT = 0x93A1; - - if (Version.Major >= 3) { - // NOTE floating-point formats may not be suitable for render targets. - TextureFormats[ECF_A1R5G5B5] = {GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, CColorConverter::convert_A1R5G5B5toR5G5B5A1}; - TextureFormats[ECF_R5G6B5] = {GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; - TextureFormats[ECF_R8G8B8] = {GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_A8R8G8B8] = {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, CColorConverter::convert_A8R8G8B8toA8B8G8R8}; - TextureFormats[ECF_R16F] = {GL_R16F, GL_RED, GL_HALF_FLOAT}; - TextureFormats[ECF_G16R16F] = {GL_RG16F, GL_RG, GL_HALF_FLOAT}; - TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}; - TextureFormats[ECF_R32F] = {GL_R32F, GL_RED, GL_FLOAT}; - TextureFormats[ECF_G32R32F] = {GL_RG32F, GL_RG, GL_FLOAT}; - TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA32F, GL_RGBA, GL_FLOAT}; - TextureFormats[ECF_R8] = {GL_R8, GL_RED, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_R8G8] = {GL_RG8, GL_RG, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; - TextureFormats[ECF_D24S8] = {GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; - - if (FeatureAvailable[IRR_GL_EXT_texture_format_BGRA8888]) - TextureFormats[ECF_A8R8G8B8] = {GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE}; - else if (FeatureAvailable[IRR_GL_APPLE_texture_format_BGRA8888]) - TextureFormats[ECF_A8R8G8B8] = {BGRA8_EXT, GL_BGRA, GL_UNSIGNED_BYTE}; - - if (FeatureAvailable[IRR_GL_OES_depth32]) - TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; - } else { - // NOTE These are *texture* formats. They may or may not be suitable - // for render targets. The specs only talks on *sized* formats for the - // latter but forbids creating textures with sized internal formats, - // reserving them for renderbuffers. - - static const GLenum HALF_FLOAT_OES = 0x8D61; // not equal to GL_HALF_FLOAT - TextureFormats[ECF_A1R5G5B5] = {GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, CColorConverter::convert_A1R5G5B5toR5G5B5A1}; - TextureFormats[ECF_R5G6B5] = {GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}; - TextureFormats[ECF_R8G8B8] = {GL_RGB, GL_RGB, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_A8R8G8B8] = {GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, CColorConverter::convert_A8R8G8B8toA8B8G8R8}; - - if (FeatureAvailable[IRR_GL_EXT_texture_format_BGRA8888]) - TextureFormats[ECF_A8R8G8B8] = {GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE}; - else if (FeatureAvailable[IRR_GL_APPLE_texture_format_BGRA8888]) - TextureFormats[ECF_A8R8G8B8] = {BGRA8_EXT, GL_BGRA, GL_UNSIGNED_BYTE}; + if (FeatureAvailable[IRR_GL_OES_texture_float]) { + TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA, GL_RGBA, GL_FLOAT}; + } + if (FeatureAvailable[IRR_GL_EXT_texture_rg]) { + TextureFormats[ECF_R8] = {GL_RED, GL_RED, GL_UNSIGNED_BYTE}; + TextureFormats[ECF_R8G8] = {GL_RG, GL_RG, GL_UNSIGNED_BYTE}; if (FeatureAvailable[IRR_GL_OES_texture_half_float]) { - TextureFormats[ECF_A16B16G16R16F] = {GL_RGBA, GL_RGBA, HALF_FLOAT_OES}; + TextureFormats[ECF_R16F] = {GL_RED, GL_RED, HALF_FLOAT_OES}; + TextureFormats[ECF_G16R16F] = {GL_RG, GL_RG, HALF_FLOAT_OES}; } if (FeatureAvailable[IRR_GL_OES_texture_float]) { - TextureFormats[ECF_A32B32G32R32F] = {GL_RGBA, GL_RGBA, GL_FLOAT}; - } - if (FeatureAvailable[IRR_GL_EXT_texture_rg]) { - TextureFormats[ECF_R8] = {GL_RED, GL_RED, GL_UNSIGNED_BYTE}; - TextureFormats[ECF_R8G8] = {GL_RG, GL_RG, GL_UNSIGNED_BYTE}; - - if (FeatureAvailable[IRR_GL_OES_texture_half_float]) { - TextureFormats[ECF_R16F] = {GL_RED, GL_RED, HALF_FLOAT_OES}; - TextureFormats[ECF_G16R16F] = {GL_RG, GL_RG, HALF_FLOAT_OES}; - } - if (FeatureAvailable[IRR_GL_OES_texture_float]) { - TextureFormats[ECF_R32F] = {GL_RED, GL_RED, GL_FLOAT}; - TextureFormats[ECF_G32R32F] = {GL_RG, GL_RG, GL_FLOAT}; - } - } - - if (FeatureAvailable[IRR_GL_OES_depth_texture]) { - TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; - if (FeatureAvailable[IRR_GL_OES_depth32]) - TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; - if (FeatureAvailable[IRR_GL_OES_packed_depth_stencil]) - TextureFormats[ECF_D24S8] = {GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; + TextureFormats[ECF_R32F] = {GL_RED, GL_RED, GL_FLOAT}; + TextureFormats[ECF_G32R32F] = {GL_RG, GL_RG, GL_FLOAT}; } } - const bool MRTSupported = Version.Major >= 3 || queryExtension("GL_EXT_draw_buffers"); - AnisotropicFilterSupported = queryExtension("GL_EXT_texture_filter_anisotropic"); - BlendMinMaxSupported = (Version.Major >= 3) || FeatureAvailable[IRR_GL_EXT_blend_minmax]; - const bool TextureLODBiasSupported = queryExtension("GL_EXT_texture_lod_bias"); - - // COGLESCoreExtensionHandler::Feature - static_assert(MATERIAL_MAX_TEXTURES <= 8, "Only up to 8 textures are guaranteed"); - Feature.BlendOperation = true; - Feature.ColorAttachment = 1; - if (MRTSupported) - Feature.ColorAttachment = GetInteger(GL_MAX_COLOR_ATTACHMENTS); - Feature.MaxTextureUnits = MATERIAL_MAX_TEXTURES; - if (MRTSupported) - Feature.MultipleRenderTarget = GetInteger(GL_MAX_DRAW_BUFFERS); - - // COGLESCoreExtensionHandler - if (AnisotropicFilterSupported) - MaxAnisotropy = GetInteger(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); - if (Version.Major >= 3 || queryExtension("GL_EXT_draw_range_elements")) - MaxIndices = GetInteger(GL_MAX_ELEMENTS_INDICES); - MaxTextureSize = GetInteger(GL_MAX_TEXTURE_SIZE); - if (TextureLODBiasSupported) - GL.GetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &MaxTextureLODBias); - GL.GetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); // NOTE: this is not in the OpenGL ES 2.0 spec... - GL.GetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); + if (FeatureAvailable[IRR_GL_OES_depth_texture]) { + TextureFormats[ECF_D16] = {GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}; + if (FeatureAvailable[IRR_GL_OES_depth32]) + TextureFormats[ECF_D32] = {GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}; + if (FeatureAvailable[IRR_GL_OES_packed_depth_stencil]) + TextureFormats[ECF_D24S8] = {GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}; + } } - IVideoDriver* createOGLES2Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) - { - os::Printer::log("Using COpenGLES2Driver", ELL_INFORMATION); - COpenGLES2Driver* driver = new COpenGLES2Driver(params, io, contextManager); - driver->genericDriverInit(params.WindowSize, params.Stencilbuffer); // don't call in constructor, it uses virtual function calls of driver - return driver; - } + const bool MRTSupported = Version.Major >= 3 || queryExtension("GL_EXT_draw_buffers"); + AnisotropicFilterSupported = queryExtension("GL_EXT_texture_filter_anisotropic"); + BlendMinMaxSupported = (Version.Major >= 3) || FeatureAvailable[IRR_GL_EXT_blend_minmax]; + const bool TextureLODBiasSupported = queryExtension("GL_EXT_texture_lod_bias"); + + // COGLESCoreExtensionHandler::Feature + static_assert(MATERIAL_MAX_TEXTURES <= 8, "Only up to 8 textures are guaranteed"); + Feature.BlendOperation = true; + Feature.ColorAttachment = 1; + if (MRTSupported) + Feature.ColorAttachment = GetInteger(GL_MAX_COLOR_ATTACHMENTS); + Feature.MaxTextureUnits = MATERIAL_MAX_TEXTURES; + if (MRTSupported) + Feature.MultipleRenderTarget = GetInteger(GL_MAX_DRAW_BUFFERS); + + // COGLESCoreExtensionHandler + if (AnisotropicFilterSupported) + MaxAnisotropy = GetInteger(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); + if (Version.Major >= 3 || queryExtension("GL_EXT_draw_range_elements")) + MaxIndices = GetInteger(GL_MAX_ELEMENTS_INDICES); + MaxTextureSize = GetInteger(GL_MAX_TEXTURE_SIZE); + if (TextureLODBiasSupported) + GL.GetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &MaxTextureLODBias); + GL.GetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); // NOTE: this is not in the OpenGL ES 2.0 spec... + GL.GetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); +} + +IVideoDriver *createOGLES2Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager) +{ + os::Printer::log("Using COpenGLES2Driver", ELL_INFORMATION); + COpenGLES2Driver *driver = new COpenGLES2Driver(params, io, contextManager); + driver->genericDriverInit(params.WindowSize, params.Stencilbuffer); // don't call in constructor, it uses virtual function calls of driver + return driver; +} } } diff --git a/source/Irrlicht/OpenGLES2/Driver.h b/source/Irrlicht/OpenGLES2/Driver.h index 327b4cf8..003f6d45 100644 --- a/source/Irrlicht/OpenGLES2/Driver.h +++ b/source/Irrlicht/OpenGLES2/Driver.h @@ -5,22 +5,26 @@ #pragma once #include "OpenGL/Driver.h" -namespace irr { -namespace video { +namespace irr +{ +namespace video +{ - /// OpenGL ES 2+ driver - /// - /// For OpenGL ES 2.0 and higher. - class COpenGLES2Driver : public COpenGL3DriverBase { - friend IVideoDriver* createOGLES2Driver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - public: - using COpenGL3DriverBase::COpenGL3DriverBase; - E_DRIVER_TYPE getDriverType() const override; +/// OpenGL ES 2+ driver +/// +/// For OpenGL ES 2.0 and higher. +class COpenGLES2Driver : public COpenGL3DriverBase +{ + friend IVideoDriver *createOGLES2Driver(const SIrrlichtCreationParameters ¶ms, io::IFileSystem *io, IContextManager *contextManager); - protected: - OpenGLVersion getVersionFromOpenGL() const override; - void initFeatures() override; - }; +public: + using COpenGL3DriverBase::COpenGL3DriverBase; + E_DRIVER_TYPE getDriverType() const override; + +protected: + OpenGLVersion getVersionFromOpenGL() const override; + void initFeatures() override; +}; } } diff --git a/source/Irrlicht/SB3DStructs.h b/source/Irrlicht/SB3DStructs.h index 264b4753..b5e61daa 100644 --- a/source/Irrlicht/SB3DStructs.h +++ b/source/Irrlicht/SB3DStructs.h @@ -6,14 +6,15 @@ // File format designed by Mark Sibly for the Blitz3D engine and has been // declared public domain - #pragma once #include "SMaterial.h" #include "irrMath.h" -namespace irr { -namespace scene { +namespace irr +{ +namespace scene +{ struct SB3dChunkHeader { @@ -23,14 +24,14 @@ struct SB3dChunkHeader struct SB3dChunk { - SB3dChunk(const SB3dChunkHeader& header, long sp) - : length(header.size+8), startposition(sp) + SB3dChunk(const SB3dChunkHeader &header, long sp) : + length(header.size + 8), startposition(sp) { length = core::max_(length, 8); - name[0]=header.name[0]; - name[1]=header.name[1]; - name[2]=header.name[2]; - name[3]=header.name[3]; + name[0] = header.name[0]; + name[1] = header.name[1]; + name[2] = header.name[2]; + name[3] = header.name[3]; } c8 name[4]; s32 length; @@ -51,17 +52,18 @@ struct SB3dTexture struct SB3dMaterial { - SB3dMaterial() : red(1.0f), green(1.0f), - blue(1.0f), alpha(1.0f), shininess(0.0f), blend(1), - fx(0) + SB3dMaterial() : + red(1.0f), green(1.0f), + blue(1.0f), alpha(1.0f), shininess(0.0f), blend(1), + fx(0) { - for (u32 i=0; i> (2 + 3); - while (i) - { + while (i) { d[0] = value; d[1] = value; d[2] = value; @@ -54,9 +52,8 @@ inline void memset32(void * dest, const u32 value, size_t bytesize) i -= 1; } - i = (bytesize >> 2 ) & 7; - while (i) - { + i = (bytesize >> 2) & 7; + while (i) { d[0] = value; d += 1; i -= 1; @@ -65,16 +62,15 @@ inline void memset32(void * dest, const u32 value, size_t bytesize) //! a more useful memset for pixel. dest must be aligned at least to 2 byte // (standard memset only works with 8-bit values) -inline void memset16(void * dest, const u16 value, size_t bytesize) +inline void memset16(void *dest, const u16 value, size_t bytesize) { - u16 * d = (u16*) dest; + u16 *d = (u16 *)dest; size_t i; // loops unrolled to reduce the number of increments by factor ~8. i = bytesize >> (1 + 3); - while (i) - { + while (i) { d[0] = value; d[1] = value; d[2] = value; @@ -89,9 +85,8 @@ inline void memset16(void * dest, const u16 value, size_t bytesize) --i; } - i = (bytesize >> 1 ) & 7; - while (i) - { + i = (bytesize >> 1) & 7; + while (i) { d[0] = value; ++d; --i; @@ -102,8 +97,7 @@ inline void memset16(void * dest, const u16 value, size_t bytesize) static inline s32 s32_log2_s32(u32 in) { s32 ret = 0; - while (in > 1) - { + while (in > 1) { in >>= 1; ret++; } @@ -115,7 +109,7 @@ static inline s32 s32_log2_s32(u32 in) Pixel = dest * ( 1 - alpha ) + source * alpha alpha [0;256] */ -REALINLINE u32 PixelBlend32 ( const u32 c2, const u32 c1, const u32 alpha ) +REALINLINE u32 PixelBlend32(const u32 c2, const u32 c1, const u32 alpha) { u32 srcRB = c1 & 0x00FF00FF; u32 srcXG = c1 & 0x0000FF00; @@ -123,7 +117,6 @@ REALINLINE u32 PixelBlend32 ( const u32 c2, const u32 c1, const u32 alpha ) u32 dstRB = c2 & 0x00FF00FF; u32 dstXG = c2 & 0x0000FF00; - u32 rb = srcRB - dstRB; u32 xg = srcXG - dstXG; @@ -145,7 +138,7 @@ REALINLINE u32 PixelBlend32 ( const u32 c2, const u32 c1, const u32 alpha ) Pixel = dest * ( 1 - alpha ) + source * alpha alpha [0;32] */ -inline u16 PixelBlend16 ( const u16 c2, const u16 c1, const u16 alpha ) +inline u16 PixelBlend16(const u16 c2, const u16 c1, const u16 alpha) { const u16 srcRB = c1 & 0x7C1F; const u16 srcXG = c1 & 0x03E0; @@ -173,85 +166,84 @@ inline u16 PixelBlend16 ( const u16 c2, const u16 c1, const u16 alpha ) /* Pixel = c0 * (c1/31). c0 Alpha retain */ -inline u16 PixelMul16 ( const u16 c0, const u16 c1) +inline u16 PixelMul16(const u16 c0, const u16 c1) { - return (u16)((( ( (c0 & 0x7C00) * (c1 & 0x7C00) ) & 0x3E000000 ) >> 15 ) | - (( ( (c0 & 0x03E0) * (c1 & 0x03E0) ) & 0x000F8000 ) >> 10 ) | - (( ( (c0 & 0x001F) * (c1 & 0x001F) ) & 0x000003E0 ) >> 5 ) | - (c0 & 0x8000)); + return (u16)(((((c0 & 0x7C00) * (c1 & 0x7C00)) & 0x3E000000) >> 15) | + ((((c0 & 0x03E0) * (c1 & 0x03E0)) & 0x000F8000) >> 10) | + ((((c0 & 0x001F) * (c1 & 0x001F)) & 0x000003E0) >> 5) | + (c0 & 0x8000)); } /* Pixel = c0 * (c1/31). */ -inline u16 PixelMul16_2 ( u16 c0, u16 c1) +inline u16 PixelMul16_2(u16 c0, u16 c1) { - return (u16)(( ( (c0 & 0x7C00) * (c1 & 0x7C00) ) & 0x3E000000 ) >> 15 | - ( ( (c0 & 0x03E0) * (c1 & 0x03E0) ) & 0x000F8000 ) >> 10 | - ( ( (c0 & 0x001F) * (c1 & 0x001F) ) & 0x000003E0 ) >> 5 | - ( c0 & c1 & 0x8000)); + return (u16)((((c0 & 0x7C00) * (c1 & 0x7C00)) & 0x3E000000) >> 15 | + (((c0 & 0x03E0) * (c1 & 0x03E0)) & 0x000F8000) >> 10 | + (((c0 & 0x001F) * (c1 & 0x001F)) & 0x000003E0) >> 5 | + (c0 & c1 & 0x8000)); } /* Pixel = c0 * (c1/255). c0 Alpha Retain */ -REALINLINE u32 PixelMul32 ( const u32 c0, const u32 c1) +REALINLINE u32 PixelMul32(const u32 c0, const u32 c1) { - return (c0 & 0xFF000000) | - (( ( (c0 & 0x00FF0000) >> 12 ) * ( (c1 & 0x00FF0000) >> 12 ) ) & 0x00FF0000 ) | - (( ( (c0 & 0x0000FF00) * (c1 & 0x0000FF00) ) >> 16 ) & 0x0000FF00 ) | - (( ( (c0 & 0x000000FF) * (c1 & 0x000000FF) ) >> 8 ) & 0x000000FF); + return (c0 & 0xFF000000) | + ((((c0 & 0x00FF0000) >> 12) * ((c1 & 0x00FF0000) >> 12)) & 0x00FF0000) | + ((((c0 & 0x0000FF00) * (c1 & 0x0000FF00)) >> 16) & 0x0000FF00) | + ((((c0 & 0x000000FF) * (c1 & 0x000000FF)) >> 8) & 0x000000FF); } /* Pixel = c0 * (c1/255). */ -REALINLINE u32 PixelMul32_2 ( const u32 c0, const u32 c1) +REALINLINE u32 PixelMul32_2(const u32 c0, const u32 c1) { - return (( ( (c0 & 0xFF000000) >> 16 ) * ( (c1 & 0xFF000000) >> 16 ) ) & 0xFF000000 ) | - (( ( (c0 & 0x00FF0000) >> 12 ) * ( (c1 & 0x00FF0000) >> 12 ) ) & 0x00FF0000 ) | - (( ( (c0 & 0x0000FF00) * (c1 & 0x0000FF00) ) >> 16 ) & 0x0000FF00 ) | - (( ( (c0 & 0x000000FF) * (c1 & 0x000000FF) ) >> 8 ) & 0x000000FF); + return ((((c0 & 0xFF000000) >> 16) * ((c1 & 0xFF000000) >> 16)) & 0xFF000000) | + ((((c0 & 0x00FF0000) >> 12) * ((c1 & 0x00FF0000) >> 12)) & 0x00FF0000) | + ((((c0 & 0x0000FF00) * (c1 & 0x0000FF00)) >> 16) & 0x0000FF00) | + ((((c0 & 0x000000FF) * (c1 & 0x000000FF)) >> 8) & 0x000000FF); } /* Pixel = clamp ( c0 + c1, 0, 255 ) */ -REALINLINE u32 PixelAdd32 ( const u32 c2, const u32 c1) +REALINLINE u32 PixelAdd32(const u32 c2, const u32 c1) { - u32 sum = ( c2 & 0x00FFFFFF ) + ( c1 & 0x00FFFFFF ); - u32 low_bits = ( c2 ^ c1 ) & 0x00010101; - s32 carries = ( sum - low_bits ) & 0x01010100; + u32 sum = (c2 & 0x00FFFFFF) + (c1 & 0x00FFFFFF); + u32 low_bits = (c2 ^ c1) & 0x00010101; + s32 carries = (sum - low_bits) & 0x01010100; u32 modulo = sum - carries; - u32 clamp = carries - ( carries >> 8 ); + u32 clamp = carries - (carries >> 8); return modulo | clamp; } // 1 - Bit Alpha Blending -inline u16 PixelBlend16 ( const u16 c2, const u16 c1 ) +inline u16 PixelBlend16(const u16 c2, const u16 c1) { - u16 mask = ((c1 & 0x8000) >> 15 ) + 0x7fff; - return (c2 & mask ) | ( c1 & ~mask ); + u16 mask = ((c1 & 0x8000) >> 15) + 0x7fff; + return (c2 & mask) | (c1 & ~mask); } /*! Pixel = dest * ( 1 - SourceAlpha ) + source * SourceAlpha (OpenGL blending) */ -inline u32 PixelBlend32 ( const u32 c2, const u32 c1 ) +inline u32 PixelBlend32(const u32 c2, const u32 c1) { // alpha test u32 alpha = c1 & 0xFF000000; - if ( 0 == alpha ) + if (0 == alpha) return c2; - if ( 0xFF000000 == alpha ) - { + if (0xFF000000 == alpha) { return c1; } alpha >>= 24; // add highbit alpha, if ( alpha > 127 ) alpha += 1; - alpha += ( alpha >> 7); + alpha += (alpha >> 7); u32 srcRB = c1 & 0x00FF00FF; u32 srcXG = c1 & 0x0000FF00; @@ -259,7 +251,6 @@ inline u32 PixelBlend32 ( const u32 c2, const u32 c1 ) u32 dstRB = c2 & 0x00FF00FF; u32 dstXG = c2 & 0x0000FF00; - u32 rb = srcRB - dstRB; u32 xg = srcXG - dstXG; @@ -277,7 +268,6 @@ inline u32 PixelBlend32 ( const u32 c2, const u32 c1 ) return (c1 & 0xFF000000) | rb | xg; } - // 2D Region closed [x0;x1] struct AbsRectangle { @@ -288,14 +278,13 @@ struct AbsRectangle }; //! 2D Intersection test -inline bool intersect ( AbsRectangle &dest, const AbsRectangle& a, const AbsRectangle& b) +inline bool intersect(AbsRectangle &dest, const AbsRectangle &a, const AbsRectangle &b) { - dest.x0 = core::s32_max( a.x0, b.x0 ); - dest.y0 = core::s32_max( a.y0, b.y0 ); - dest.x1 = core::s32_min( a.x1, b.x1 ); - dest.y1 = core::s32_min( a.y1, b.y1 ); + dest.x0 = core::s32_max(a.x0, b.x0); + dest.y0 = core::s32_max(a.y0, b.y0); + dest.x1 = core::s32_min(a.x1, b.x1); + dest.y1 = core::s32_min(a.y1, b.y1); return dest.x0 < dest.x1 && dest.y0 < dest.y1; } - } // end namespace irr diff --git a/source/Irrlicht/os.cpp b/source/Irrlicht/os.cpp index a3087f6e..96be8dd6 100644 --- a/source/Irrlicht/os.cpp +++ b/source/Irrlicht/os.cpp @@ -7,49 +7,72 @@ #include "irrMath.h" #if defined(_IRR_COMPILE_WITH_SDL_DEVICE_) - #include - #define bswap_16(X) SDL_Swap16(X) - #define bswap_32(X) SDL_Swap32(X) - #define bswap_64(X) SDL_Swap64(X) +#include +#define bswap_16(X) SDL_Swap16(X) +#define bswap_32(X) SDL_Swap32(X) +#define bswap_64(X) SDL_Swap64(X) #elif defined(_IRR_WINDOWS_API_) && defined(_MSC_VER) - #include - #define bswap_16(X) _byteswap_ushort(X) - #define bswap_32(X) _byteswap_ulong(X) - #define bswap_64(X) _byteswap_uint64(X) +#include +#define bswap_16(X) _byteswap_ushort(X) +#define bswap_32(X) _byteswap_ulong(X) +#define bswap_64(X) _byteswap_uint64(X) #elif defined(_IRR_OSX_PLATFORM_) - #include - #define bswap_16(X) OSReadSwapInt16(&X,0) - #define bswap_32(X) OSReadSwapInt32(&X,0) - #define bswap_64(X) OSReadSwapInt64(&X,0) +#include +#define bswap_16(X) OSReadSwapInt16(&X, 0) +#define bswap_32(X) OSReadSwapInt32(&X, 0) +#define bswap_64(X) OSReadSwapInt64(&X, 0) #elif defined(__FreeBSD__) - #include - #define bswap_16(X) bswap16(X) - #define bswap_32(X) bswap32(X) - #define bswap_64(X) bswap64(X) +#include +#define bswap_16(X) bswap16(X) +#define bswap_32(X) bswap32(X) +#define bswap_64(X) bswap64(X) #elif defined(__OpenBSD__) - #include - #define bswap_16(X) letoh16(X) - #define bswap_32(X) letoh32(X) - #define bswap_64(X) letoh64(X) +#include +#define bswap_16(X) letoh16(X) +#define bswap_32(X) letoh32(X) +#define bswap_64(X) letoh64(X) #elif !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__PPC__) && !defined(_IRR_WINDOWS_API_) - #include +#include #else - #define bswap_16(X) ((((X)&0xFF) << 8) | (((X)&0xFF00) >> 8)) - #define bswap_32(X) ((((X)&0x000000FF) << 24) | (((X)&0xFF000000) >> 24) | (((X)&0x0000FF00) << 8) | (((X) &0x00FF0000) >> 8)) - #define bswap_64(X) ((((X)&0x00000000000000FF) << 56) | (((X)&0xFF00000000000000) >> 56) | (((X)&0x000000000000FF00) << 40) | (((X)&0x00FF000000000000) >> 40) | (((X)&0x0000000000FF0000) << 24) | (((X)&0x0000FF0000000000) >> 24) | (((X)&0x00000000FF000000) << 8) | (((X) &0x000000FF00000000) >> 8)) +#define bswap_16(X) ((((X) & 0xFF) << 8) | (((X) & 0xFF00) >> 8)) +#define bswap_32(X) ((((X) & 0x000000FF) << 24) | (((X) & 0xFF000000) >> 24) | (((X) & 0x0000FF00) << 8) | (((X) & 0x00FF0000) >> 8)) +#define bswap_64(X) ((((X) & 0x00000000000000FF) << 56) | (((X) & 0xFF00000000000000) >> 56) | (((X) & 0x000000000000FF00) << 40) | (((X) & 0x00FF000000000000) >> 40) | (((X) & 0x0000000000FF0000) << 24) | (((X) & 0x0000FF0000000000) >> 24) | (((X) & 0x00000000FF000000) << 8) | (((X) & 0x000000FF00000000) >> 8)) #endif namespace irr { namespace os { - u16 Byteswap::byteswap(u16 num) {return bswap_16(num);} - s16 Byteswap::byteswap(s16 num) {return bswap_16(num);} - u32 Byteswap::byteswap(u32 num) {return bswap_32(num);} - s32 Byteswap::byteswap(s32 num) {return bswap_32(num);} - u64 Byteswap::byteswap(u64 num) {return bswap_64(num);} - s64 Byteswap::byteswap(s64 num) {return bswap_64(num);} - f32 Byteswap::byteswap(f32 num) {u32 tmp=IR(num); tmp=bswap_32(tmp); return (FR(tmp));} +u16 Byteswap::byteswap(u16 num) +{ + return bswap_16(num); +} +s16 Byteswap::byteswap(s16 num) +{ + return bswap_16(num); +} +u32 Byteswap::byteswap(u32 num) +{ + return bswap_32(num); +} +s32 Byteswap::byteswap(s32 num) +{ + return bswap_32(num); +} +u64 Byteswap::byteswap(u64 num) +{ + return bswap_64(num); +} +s64 Byteswap::byteswap(s64 num) +{ + return bswap_64(num); +} +f32 Byteswap::byteswap(f32 num) +{ + u32 tmp = IR(num); + tmp = bswap_32(tmp); + return (FR(tmp)); +} } } @@ -66,42 +89,40 @@ namespace irr { namespace os { - //! prints a debuginfo string - void Printer::print(const c8* message, ELOG_LEVEL ll) - { - core::stringc tmp(message); - tmp += "\n"; - OutputDebugStringA(tmp.c_str()); - printf("%s", tmp.c_str()); +//! prints a debuginfo string +void Printer::print(const c8 *message, ELOG_LEVEL ll) +{ + core::stringc tmp(message); + tmp += "\n"; + OutputDebugStringA(tmp.c_str()); + printf("%s", tmp.c_str()); +} + +static LARGE_INTEGER HighPerformanceFreq; +static BOOL HighPerformanceTimerSupport = FALSE; + +void Timer::initTimer() +{ + HighPerformanceTimerSupport = QueryPerformanceFrequency(&HighPerformanceFreq); + initVirtualTimer(); +} + +u32 Timer::getRealTime() +{ + if (HighPerformanceTimerSupport) { + LARGE_INTEGER nTime; + BOOL queriedOK = QueryPerformanceCounter(&nTime); + + if (queriedOK) + return u32((nTime.QuadPart) * 1000 / HighPerformanceFreq.QuadPart); } - static LARGE_INTEGER HighPerformanceFreq; - static BOOL HighPerformanceTimerSupport = FALSE; - - void Timer::initTimer() - { - HighPerformanceTimerSupport = QueryPerformanceFrequency(&HighPerformanceFreq); - initVirtualTimer(); - } - - u32 Timer::getRealTime() - { - if (HighPerformanceTimerSupport) - { - LARGE_INTEGER nTime; - BOOL queriedOK = QueryPerformanceCounter(&nTime); - - if(queriedOK) - return u32((nTime.QuadPart) * 1000 / HighPerformanceFreq.QuadPart); - } - - return GetTickCount(); - } + return GetTickCount(); +} } // end namespace os - -#elif defined( _IRR_ANDROID_PLATFORM_ ) +#elif defined(_IRR_ANDROID_PLATFORM_) // ---------------------------------------------------------------- // Android version @@ -114,54 +135,52 @@ namespace irr namespace os { - //! prints a debuginfo string - void Printer::print(const c8* message, ELOG_LEVEL ll) - { - android_LogPriority LogLevel = ANDROID_LOG_UNKNOWN; +//! prints a debuginfo string +void Printer::print(const c8 *message, ELOG_LEVEL ll) +{ + android_LogPriority LogLevel = ANDROID_LOG_UNKNOWN; - switch (ll) - { - case ELL_DEBUG: - LogLevel = ANDROID_LOG_DEBUG; - break; - case ELL_INFORMATION: - LogLevel = ANDROID_LOG_INFO; - break; - case ELL_WARNING: - LogLevel = ANDROID_LOG_WARN; - break; - case ELL_ERROR: - LogLevel = ANDROID_LOG_ERROR; - break; - default: // ELL_NONE - LogLevel = ANDROID_LOG_VERBOSE; - break; - } - - // Android logcat restricts log-output and cuts the rest of the message away. But we want it all. - // On my device max-len is 1023 (+ 0 byte). Some websites claim a limit of 4096 so maybe different numbers on different devices. - const size_t maxLogLen = 1023; - size_t msgLen = strlen(message); - size_t start = 0; - while ( msgLen-start > maxLogLen ) - { - __android_log_print(LogLevel, "Irrlicht", "%.*s\n", maxLogLen, &message[start]); - start += maxLogLen; - } - __android_log_print(LogLevel, "Irrlicht", "%s\n", &message[start]); + switch (ll) { + case ELL_DEBUG: + LogLevel = ANDROID_LOG_DEBUG; + break; + case ELL_INFORMATION: + LogLevel = ANDROID_LOG_INFO; + break; + case ELL_WARNING: + LogLevel = ANDROID_LOG_WARN; + break; + case ELL_ERROR: + LogLevel = ANDROID_LOG_ERROR; + break; + default: // ELL_NONE + LogLevel = ANDROID_LOG_VERBOSE; + break; } - void Timer::initTimer() - { - initVirtualTimer(); + // Android logcat restricts log-output and cuts the rest of the message away. But we want it all. + // On my device max-len is 1023 (+ 0 byte). Some websites claim a limit of 4096 so maybe different numbers on different devices. + const size_t maxLogLen = 1023; + size_t msgLen = strlen(message); + size_t start = 0; + while (msgLen - start > maxLogLen) { + __android_log_print(LogLevel, "Irrlicht", "%.*s\n", maxLogLen, &message[start]); + start += maxLogLen; } + __android_log_print(LogLevel, "Irrlicht", "%s\n", &message[start]); +} - u32 Timer::getRealTime() - { - timeval tv; - gettimeofday(&tv, 0); - return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000); - } +void Timer::initTimer() +{ + initVirtualTimer(); +} + +u32 Timer::getRealTime() +{ + timeval tv; + gettimeofday(&tv, 0); + return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000); +} } // end namespace os #elif defined(_IRR_EMSCRIPTEN_PLATFORM_) @@ -179,41 +198,40 @@ namespace irr namespace os { - //! prints a debuginfo string - void Printer::print(const c8* message, ELOG_LEVEL ll) - { - int log_level; - switch (ll) - { - case ELL_DEBUG: - log_level=0; +//! prints a debuginfo string +void Printer::print(const c8 *message, ELOG_LEVEL ll) +{ + int log_level; + switch (ll) { + case ELL_DEBUG: + log_level = 0; break; - case ELL_INFORMATION: - log_level=0; + case ELL_INFORMATION: + log_level = 0; break; - case ELL_WARNING: - log_level=EM_LOG_WARN; - break; - case ELL_ERROR: - log_level=EM_LOG_ERROR; + case ELL_WARNING: + log_level = EM_LOG_WARN; + break; + case ELL_ERROR: + log_level = EM_LOG_ERROR; + break; + default: // ELL_NONE + log_level = 0; break; - default: // ELL_NONE - log_level=0; - break; - } - emscripten_log(log_level, "%s", message); // Note: not adding \n as emscripten_log seems to do that already. } + emscripten_log(log_level, "%s", message); // Note: not adding \n as emscripten_log seems to do that already. +} - void Timer::initTimer() - { - initVirtualTimer(); - } +void Timer::initTimer() +{ + initVirtualTimer(); +} - u32 Timer::getRealTime() - { - double time = emscripten_get_now(); - return (u32)(time); - } +u32 Timer::getRealTime() +{ + double time = emscripten_get_now(); + return (u32)(time); +} } // end namespace os #else @@ -231,135 +249,131 @@ namespace irr namespace os { - //! prints a debuginfo string - void Printer::print(const c8* message, ELOG_LEVEL ll) - { - printf("%s\n", message); - } +//! prints a debuginfo string +void Printer::print(const c8 *message, ELOG_LEVEL ll) +{ + printf("%s\n", message); +} - void Timer::initTimer() - { - initVirtualTimer(); - } +void Timer::initTimer() +{ + initVirtualTimer(); +} - u32 Timer::getRealTime() - { - timeval tv; - gettimeofday(&tv, 0); - return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000); - } +u32 Timer::getRealTime() +{ + timeval tv; + gettimeofday(&tv, 0); + return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000); +} } // end namespace os #endif // end linux / emscripten / android / windows namespace os { - // The platform independent implementation of the printer - ILogger* Printer::Logger = 0; +// The platform independent implementation of the printer +ILogger *Printer::Logger = 0; - void Printer::log(const c8* message, ELOG_LEVEL ll) - { - if (Logger) - Logger->log(message, ll); +void Printer::log(const c8 *message, ELOG_LEVEL ll) +{ + if (Logger) + Logger->log(message, ll); +} + +void Printer::log(const c8 *message, const c8 *hint, ELOG_LEVEL ll) +{ + if (Logger) + Logger->log(message, hint, ll); +} + +void Printer::log(const c8 *message, const io::path &hint, ELOG_LEVEL ll) +{ + if (Logger) + Logger->log(message, hint.c_str(), ll); +} + +// ------------------------------------------------------ +// virtual timer implementation + +f32 Timer::VirtualTimerSpeed = 1.0f; +s32 Timer::VirtualTimerStopCounter = 0; +u32 Timer::LastVirtualTime = 0; +u32 Timer::StartRealTime = 0; +u32 Timer::StaticTime = 0; + +//! returns current virtual time +u32 Timer::getTime() +{ + if (isStopped()) + return LastVirtualTime; + + return LastVirtualTime + (u32)((StaticTime - StartRealTime) * VirtualTimerSpeed); +} + +//! ticks, advances the virtual timer +void Timer::tick() +{ + StaticTime = getRealTime(); +} + +//! sets the current virtual time +void Timer::setTime(u32 time) +{ + StaticTime = getRealTime(); + LastVirtualTime = time; + StartRealTime = StaticTime; +} + +//! stops the virtual timer +void Timer::stopTimer() +{ + if (!isStopped()) { + // stop the virtual timer + LastVirtualTime = getTime(); } - void Printer::log(const c8* message, const c8* hint, ELOG_LEVEL ll) - { - if (Logger) - Logger->log(message, hint, ll); + --VirtualTimerStopCounter; +} + +//! starts the virtual timer +void Timer::startTimer() +{ + ++VirtualTimerStopCounter; + + if (!isStopped()) { + // restart virtual timer + setTime(LastVirtualTime); } +} - void Printer::log(const c8* message, const io::path& hint, ELOG_LEVEL ll) - { - if (Logger) - Logger->log(message, hint.c_str(), ll); - } +//! sets the speed of the virtual timer +void Timer::setSpeed(f32 speed) +{ + setTime(getTime()); - // ------------------------------------------------------ - // virtual timer implementation + VirtualTimerSpeed = speed; + if (VirtualTimerSpeed < 0.0f) + VirtualTimerSpeed = 0.0f; +} - f32 Timer::VirtualTimerSpeed = 1.0f; - s32 Timer::VirtualTimerStopCounter = 0; - u32 Timer::LastVirtualTime = 0; - u32 Timer::StartRealTime = 0; - u32 Timer::StaticTime = 0; +//! gets the speed of the virtual timer +f32 Timer::getSpeed() +{ + return VirtualTimerSpeed; +} - //! returns current virtual time - u32 Timer::getTime() - { - if (isStopped()) - return LastVirtualTime; +//! returns if the timer currently is stopped +bool Timer::isStopped() +{ + return VirtualTimerStopCounter < 0; +} - return LastVirtualTime + (u32)((StaticTime - StartRealTime) * VirtualTimerSpeed); - } - - //! ticks, advances the virtual timer - void Timer::tick() - { - StaticTime = getRealTime(); - } - - //! sets the current virtual time - void Timer::setTime(u32 time) - { - StaticTime = getRealTime(); - LastVirtualTime = time; - StartRealTime = StaticTime; - } - - //! stops the virtual timer - void Timer::stopTimer() - { - if (!isStopped()) - { - // stop the virtual timer - LastVirtualTime = getTime(); - } - - --VirtualTimerStopCounter; - } - - //! starts the virtual timer - void Timer::startTimer() - { - ++VirtualTimerStopCounter; - - if (!isStopped()) - { - // restart virtual timer - setTime(LastVirtualTime); - } - } - - //! sets the speed of the virtual timer - void Timer::setSpeed(f32 speed) - { - setTime(getTime()); - - VirtualTimerSpeed = speed; - if (VirtualTimerSpeed < 0.0f) - VirtualTimerSpeed = 0.0f; - } - - //! gets the speed of the virtual timer - f32 Timer::getSpeed() - { - return VirtualTimerSpeed; - } - - //! returns if the timer currently is stopped - bool Timer::isStopped() - { - return VirtualTimerStopCounter < 0; - } - - void Timer::initVirtualTimer() - { - StaticTime = getRealTime(); - StartRealTime = StaticTime; - } +void Timer::initVirtualTimer() +{ + StaticTime = getRealTime(); + StartRealTime = StaticTime; +} } // end namespace os } // end namespace irr - - diff --git a/source/Irrlicht/os.h b/source/Irrlicht/os.h index c8c23863..fcbaeddd 100644 --- a/source/Irrlicht/os.h +++ b/source/Irrlicht/os.h @@ -15,79 +15,77 @@ namespace irr namespace os { - class Byteswap - { - public: - static u16 byteswap(u16 num); - static s16 byteswap(s16 num); - static u32 byteswap(u32 num); - static s32 byteswap(s32 num); - static u64 byteswap(u64 num); - static s64 byteswap(s64 num); - static f32 byteswap(f32 num); - // prevent accidental swapping of chars - static inline u8 byteswap(u8 num) { return num; } - static inline c8 byteswap(c8 num) { return num; } - }; +class Byteswap +{ +public: + static u16 byteswap(u16 num); + static s16 byteswap(s16 num); + static u32 byteswap(u32 num); + static s32 byteswap(s32 num); + static u64 byteswap(u64 num); + static s64 byteswap(s64 num); + static f32 byteswap(f32 num); + // prevent accidental swapping of chars + static inline u8 byteswap(u8 num) { return num; } + static inline c8 byteswap(c8 num) { return num; } +}; - class Printer - { - public: - // prints out a string to the console out stdout or debug log or whatever - static void print(const c8* message, ELOG_LEVEL ll = ELL_INFORMATION); - static void log(const c8* message, ELOG_LEVEL ll = ELL_INFORMATION); - static void log(const wchar_t* message, ELOG_LEVEL ll = ELL_INFORMATION); +class Printer +{ +public: + // prints out a string to the console out stdout or debug log or whatever + static void print(const c8 *message, ELOG_LEVEL ll = ELL_INFORMATION); + static void log(const c8 *message, ELOG_LEVEL ll = ELL_INFORMATION); + static void log(const wchar_t *message, ELOG_LEVEL ll = ELL_INFORMATION); - // The string ": " is added between message and hint - static void log(const c8* message, const c8* hint, ELOG_LEVEL ll = ELL_INFORMATION); - static void log(const c8* message, const io::path& hint, ELOG_LEVEL ll = ELL_INFORMATION); - static ILogger* Logger; - }; + // The string ": " is added between message and hint + static void log(const c8 *message, const c8 *hint, ELOG_LEVEL ll = ELL_INFORMATION); + static void log(const c8 *message, const io::path &hint, ELOG_LEVEL ll = ELL_INFORMATION); + static ILogger *Logger; +}; - class Timer - { - public: +class Timer +{ +public: + //! returns the current time in milliseconds + static u32 getTime(); - //! returns the current time in milliseconds - static u32 getTime(); + //! initializes the real timer + static void initTimer(); - //! initializes the real timer - static void initTimer(); + //! sets the current virtual (game) time + static void setTime(u32 time); - //! sets the current virtual (game) time - static void setTime(u32 time); + //! stops the virtual (game) timer + static void stopTimer(); - //! stops the virtual (game) timer - static void stopTimer(); + //! starts the game timer + static void startTimer(); - //! starts the game timer - static void startTimer(); + //! sets the speed of the virtual timer + static void setSpeed(f32 speed); - //! sets the speed of the virtual timer - static void setSpeed(f32 speed); + //! gets the speed of the virtual timer + static f32 getSpeed(); - //! gets the speed of the virtual timer - static f32 getSpeed(); + //! returns if the timer currently is stopped + static bool isStopped(); - //! returns if the timer currently is stopped - static bool isStopped(); + //! makes the virtual timer update the time value based on the real time + static void tick(); - //! makes the virtual timer update the time value based on the real time - static void tick(); + //! returns the current real time in milliseconds + static u32 getRealTime(); - //! returns the current real time in milliseconds - static u32 getRealTime(); +private: + static void initVirtualTimer(); - private: - - static void initVirtualTimer(); - - static f32 VirtualTimerSpeed; - static s32 VirtualTimerStopCounter; - static u32 StartRealTime; - static u32 LastVirtualTime; - static u32 StaticTime; - }; + static f32 VirtualTimerSpeed; + static s32 VirtualTimerStopCounter; + static u32 StartRealTime; + static u32 LastVirtualTime; + static u32 StaticTime; +}; } // end namespace os } // end namespace irr