1 // Copyright (C) 2023 Vitaliy Lobachevskiy
2 // Copyright (C) 2014 Patryk Nadrowski
3 // Copyright (C) 2009-2010 Amundis
4 // This file is part of the "Irrlicht Engine".
5 // For conditions of distribution and use, see copyright notice in Irrlicht.h
9 #include "CNullDriver.h"
10 #include "IContextManager.h"
12 #include "COpenGLCoreTexture.h"
13 #include "COpenGLCoreRenderTarget.h"
14 #include "COpenGLCoreCacheHandler.h"
16 #include "MaterialRenderer.h"
17 #include "FixedPipelineRenderer.h"
18 #include "Renderer2D.h"
20 #include "EVertexAttributes.h"
24 #ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_
25 #include "android_native_app_glue.h"
28 #include "mt_opengl.h"
34 struct VertexAttribute {
50 VertexAttribute Attributes[];
52 VertexType(const VertexType &) = delete;
53 VertexType &operator= (const VertexType &) = delete;
56 static const VertexAttribute *begin(const VertexType &type)
58 return type.Attributes;
61 static const VertexAttribute *end(const VertexType &type)
63 return type.Attributes + type.AttributeCount;
66 static constexpr VertexType vtStandard = {
67 sizeof(S3DVertex), 4, {
68 {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
69 {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)},
70 {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
71 {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)},
75 #pragma GCC diagnostic push
76 #pragma GCC diagnostic ignored "-Winvalid-offsetof"
78 static constexpr VertexType vt2TCoords = {
79 sizeof(S3DVertex2TCoords), 5, {
80 {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)},
81 {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)},
82 {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)},
83 {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)},
84 {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)},
88 static constexpr VertexType vtTangents = {
89 sizeof(S3DVertexTangents), 6, {
90 {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)},
91 {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)},
92 {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)},
93 {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)},
94 {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)},
95 {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)},
99 #pragma GCC diagnostic pop
101 static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type)
104 case EVT_STANDARD: return vtStandard;
105 case EVT_2TCOORDS: return vt2TCoords;
106 case EVT_TANGENTS: return vtTangents;
107 default: assert(false);
111 static constexpr VertexType vt2DImage = {
112 sizeof(S3DVertex), 3, {
113 {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
114 {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
115 {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)},
119 static constexpr VertexType vtPrimitive = {
120 sizeof(S3DVertex), 2, {
121 {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)},
122 {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)},
127 void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
129 ((COpenGL3DriverBase *)userParam)->debugCb(source, type, id, severity, length, message);
132 void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message)
134 printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message);
137 COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) :
138 CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0),
139 Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias),
140 MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0),
141 CurrentRenderMode(ERM_NONE), Transformation3DChanged(true),
142 OGLES2ShaderPath(params.OGLES2ShaderPath),
143 ColorFormat(ECF_R8G8B8), ContextManager(contextManager)
146 setDebugName("Driver");
152 ContextManager->grab();
153 ContextManager->generateSurface();
154 ContextManager->generateContext();
155 ExposedData = ContextManager->getContext();
156 ContextManager->activateContext(ExposedData, false);
157 GL.LoadAllProcedures(ContextManager);
158 GL.DebugMessageCallback(debugCb, this);
162 COpenGL3DriverBase::~COpenGL3DriverBase()
164 deleteMaterialRenders();
166 CacheHandler->getTextureCache().clear();
168 removeAllRenderTargets();
170 removeAllOcclusionQueries();
171 removeAllHardwareBuffers();
173 delete MaterialRenderer2DTexture;
174 delete MaterialRenderer2DNoTexture;
179 ContextManager->destroyContext();
180 ContextManager->destroySurface();
181 ContextManager->terminate();
182 ContextManager->drop();
186 void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count)
188 int max_quad_count = max_vertex_count / 4;
189 QuadsIndices.reserve(6 * max_quad_count);
190 for (int k = 0; k < max_quad_count; k++) {
191 QuadsIndices.push_back(4 * k + 0);
192 QuadsIndices.push_back(4 * k + 1);
193 QuadsIndices.push_back(4 * k + 2);
194 QuadsIndices.push_back(4 * k + 0);
195 QuadsIndices.push_back(4 * k + 2);
196 QuadsIndices.push_back(4 * k + 3);
200 bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer)
202 Name = glGetString(GL_VERSION);
205 // print renderer information
206 VendorName = glGetString(GL_VENDOR);
207 os::Printer::log(VendorName.c_str(), ELL_INFORMATION);
212 // reset cache handler
214 CacheHandler = new COpenGL3CacheHandler(this);
216 StencilBuffer = stencilBuffer;
218 DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits);
219 DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits);
220 // DriverAttributes->setAttribute("MaxLights", MaxLights);
221 DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy);
222 // DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes);
223 // DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers);
224 // DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets);
225 DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices);
226 DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize);
227 DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias);
228 DriverAttributes->setAttribute("Version", Version);
229 DriverAttributes->setAttribute("AntiAlias", AntiAlias);
231 glPixelStorei(GL_PACK_ALIGNMENT, 1);
233 UserClipPlane.reallocate(0);
235 for (s32 i = 0; i < ETS_COUNT; ++i)
236 setTransform(static_cast<E_TRANSFORMATION_STATE>(i), core::IdentityMatrix);
238 setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f));
241 glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
244 // create material renderers
245 createMaterialRenderers();
247 // set the renderstates
248 setRenderStates3DMode();
251 setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
253 // create matrix for flipping textures
254 TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f));
256 // We need to reset once more at the beginning of the first rendering.
257 // This fixes problems with intermediate changes to the material during texture load.
258 ResetRenderStates = true;
260 testGLError(__LINE__);
265 void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData)
267 io::path vsPath(OGLES2ShaderPath);
268 vsPath += vertexShaderName;
270 io::path fsPath(OGLES2ShaderPath);
271 fsPath += fragmentShaderName;
273 *vertexShaderData = 0;
274 *fragmentShaderData = 0;
276 io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath);
279 core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
280 warning += core::stringw(vsPath) + L"\n";
281 warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
282 os::Printer::log(warning.c_str(), ELL_WARNING);
286 io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath);
289 core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
290 warning += core::stringw(fsPath) + L"\n";
291 warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
292 os::Printer::log(warning.c_str(), ELL_WARNING);
296 long size = vsFile->getSize();
299 *vertexShaderData = new c8[size+1];
300 vsFile->read(*vertexShaderData, size);
301 (*vertexShaderData)[size] = 0;
304 size = fsFile->getSize();
307 // if both handles are the same we must reset the file
308 if (fsFile == vsFile)
311 *fragmentShaderData = new c8[size+1];
312 fsFile->read(*fragmentShaderData, size);
313 (*fragmentShaderData)[size] = 0;
320 void COpenGL3DriverBase::addDummyMaterial(E_MATERIAL_TYPE type) {
321 auto index = addMaterialRenderer(getMaterialRenderer(EMT_SOLID), "DUMMY");
322 assert(index == type);
325 void COpenGL3DriverBase::createMaterialRenderers()
329 COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB();
330 COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB();
331 COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB();
332 COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB();
333 COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB();
335 // Create built-in materials.
336 // The addition order must be the same as in the E_MATERIAL_TYPE enumeration. Thus the
337 // addDummyMaterial calls for materials no longer supported.
339 const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh";
342 core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh";
343 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
344 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0);
346 addDummyMaterial(EMT_SOLID_2_LAYER);
347 addDummyMaterial(EMT_LIGHTMAP);
348 addDummyMaterial(EMT_LIGHTMAP_ADD);
349 addDummyMaterial(EMT_LIGHTMAP_M2);
350 addDummyMaterial(EMT_LIGHTMAP_M4);
351 addDummyMaterial(EMT_LIGHTMAP_LIGHTING);
352 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M2);
353 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M4);
354 addDummyMaterial(EMT_DETAIL_MAP);
355 addDummyMaterial(EMT_SPHERE_MAP);
356 addDummyMaterial(EMT_REFLECTION_2_LAYER);
357 addDummyMaterial(EMT_TRANSPARENT_ADD_COLOR);
359 // EMT_TRANSPARENT_ALPHA_CHANNEL
360 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh";
361 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
362 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
364 // EMT_TRANSPARENT_ALPHA_CHANNEL_REF
365 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh";
366 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
367 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0);
369 // EMT_TRANSPARENT_VERTEX_ALPHA
370 FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh";
371 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
372 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
374 addDummyMaterial(EMT_TRANSPARENT_REFLECTION_2_LAYER);
376 // EMT_ONETEXTURE_BLEND
377 FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh";
378 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
379 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0);
384 TransparentAlphaChannelCB->drop();
385 TransparentAlphaChannelRefCB->drop();
386 TransparentVertexAlphaCB->drop();
387 OneTextureBlendCB->drop();
389 // Create 2D material renderers
393 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData);
394 MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true);
400 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData);
401 MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false);
406 bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture)
408 Material.TextureLayer[layerIdx].Texture = const_cast<ITexture*>(texture); // function uses const-pointer for texture because all draw functions use const-pointers already
409 return CacheHandler->getTextureCache().set(0, texture);
412 bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
414 CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect);
417 ContextManager->activateContext(videoData, true);
419 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
424 bool COpenGL3DriverBase::endScene()
426 CNullDriver::endScene();
431 return ContextManager->swapBuffers();
437 //! Returns the transformation set by setTransform
438 const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const
440 return Matrices[state];
444 //! sets transformation
445 void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
447 Matrices[state] = mat;
448 Transformation3DChanged = true;
452 bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
457 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
458 const void* vertices = mb->getVertices();
459 const u32 vertexCount = mb->getVertexCount();
460 const E_VERTEX_TYPE vType = mb->getVertexType();
461 const u32 vertexSize = getVertexPitchFromType(vType);
463 const void *buffer = vertices;
464 size_t bufferSize = vertexSize * vertexCount;
466 //get or create buffer
467 bool newBuffer = false;
468 if (!HWBuffer->vbo_verticesID)
470 glGenBuffers(1, &HWBuffer->vbo_verticesID);
471 if (!HWBuffer->vbo_verticesID) return false;
474 else if (HWBuffer->vbo_verticesSize < bufferSize)
479 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
481 // copy data to graphics card
483 glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer);
486 HWBuffer->vbo_verticesSize = bufferSize;
488 if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC)
489 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW);
491 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW);
494 glBindBuffer(GL_ARRAY_BUFFER, 0);
496 return (!testGLError(__LINE__));
500 bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
505 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
507 const void* indices = mb->getIndices();
508 u32 indexCount = mb->getIndexCount();
511 switch (mb->getIndexType())
515 indexSize = sizeof(u16);
520 indexSize = sizeof(u32);
529 //get or create buffer
530 bool newBuffer = false;
531 if (!HWBuffer->vbo_indicesID)
533 glGenBuffers(1, &HWBuffer->vbo_indicesID);
534 if (!HWBuffer->vbo_indicesID) return false;
537 else if (HWBuffer->vbo_indicesSize < indexCount*indexSize)
542 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
544 // copy data to graphics card
546 glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices);
549 HWBuffer->vbo_indicesSize = indexCount * indexSize;
551 if (HWBuffer->Mapped_Index == scene::EHM_STATIC)
552 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW);
554 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW);
557 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
559 return (!testGLError(__LINE__));
563 //! updates hardware buffer if needed
564 bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer)
569 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
571 if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex()
572 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_verticesID)
575 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
577 if (!updateVertexHardwareBuffer(static_cast<SHWBufferLink_opengl*>(HWBuffer)))
582 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
584 if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index()
585 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_indicesID)
588 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
590 if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer))
599 //! Create hardware buffer from meshbuffer
600 COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb)
602 if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER))
605 SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb);
608 HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer);
610 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
611 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
612 HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex();
613 HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index();
614 HWBuffer->vbo_verticesID = 0;
615 HWBuffer->vbo_indicesID = 0;
616 HWBuffer->vbo_verticesSize = 0;
617 HWBuffer->vbo_indicesSize = 0;
619 if (!updateHardwareBuffer(HWBuffer))
621 deleteHardwareBuffer(HWBuffer);
629 void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer)
634 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
635 if (HWBuffer->vbo_verticesID)
637 glDeleteBuffers(1, &HWBuffer->vbo_verticesID);
638 HWBuffer->vbo_verticesID = 0;
640 if (HWBuffer->vbo_indicesID)
642 glDeleteBuffers(1, &HWBuffer->vbo_indicesID);
643 HWBuffer->vbo_indicesID = 0;
646 CNullDriver::deleteHardwareBuffer(_HWBuffer);
650 //! Draw hardware buffer
651 void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer)
656 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
658 updateHardwareBuffer(HWBuffer); //check if update is needed
660 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
661 const void *vertices = mb->getVertices();
662 const void *indexList = mb->getIndices();
664 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
666 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
670 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
672 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
677 drawVertexPrimitiveList(vertices, mb->getVertexCount(),
678 indexList, mb->getPrimitiveCount(),
679 mb->getVertexType(), mb->getPrimitiveType(),
682 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
683 glBindBuffer(GL_ARRAY_BUFFER, 0);
685 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
686 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
690 IRenderTarget* COpenGL3DriverBase::addRenderTarget()
692 COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this);
693 RenderTargets.push_back(renderTarget);
699 // small helper function to create vertex buffer object adress offsets
700 static inline u8* buffer_offset(const long offset)
702 return ((u8*)0 + offset);
706 //! draws a vertex primitive list
707 void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
708 const void* indexList, u32 primitiveCount,
709 E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
711 if (!primitiveCount || !vertexCount)
714 if (!checkPrimitiveCount(primitiveCount))
717 CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType);
719 setRenderStates3DMode();
721 auto &vTypeDesc = getVertexTypeDescription(vType);
722 beginDraw(vTypeDesc, reinterpret_cast<uintptr_t>(vertices));
723 GLenum indexSize = 0;
729 indexSize = GL_UNSIGNED_SHORT;
734 #ifdef GL_OES_element_index_uint
735 #ifndef GL_UNSIGNED_INT
736 #define GL_UNSIGNED_INT 0x1405
738 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint])
739 indexSize = GL_UNSIGNED_INT;
742 indexSize = GL_UNSIGNED_SHORT;
749 case scene::EPT_POINTS:
750 case scene::EPT_POINT_SPRITES:
751 glDrawArrays(GL_POINTS, 0, primitiveCount);
753 case scene::EPT_LINE_STRIP:
754 glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList);
756 case scene::EPT_LINE_LOOP:
757 glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList);
759 case scene::EPT_LINES:
760 glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList);
762 case scene::EPT_TRIANGLE_STRIP:
763 glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList);
765 case scene::EPT_TRIANGLE_FAN:
766 glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList);
768 case scene::EPT_TRIANGLES:
769 glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList);
779 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
780 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect, SColor color,
781 bool useAlphaChannelOfTexture)
786 if (!sourceRect.isValid())
789 SColor colors[4] = {color, color, color, color};
790 draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture);
794 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
795 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect,
796 const video::SColor* const colors, bool useAlphaChannelOfTexture)
801 // texcoords need to be flipped horizontally for RTTs
802 const bool isRTT = texture->isRenderTarget();
803 const core::dimension2du& ss = texture->getOriginalSize();
804 const f32 invW = 1.f / static_cast<f32>(ss.Width);
805 const f32 invH = 1.f / static_cast<f32>(ss.Height);
806 const core::rect<f32> tcoords(
807 sourceRect.UpperLeftCorner.X * invW,
808 (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH,
809 sourceRect.LowerRightCorner.X * invW,
810 (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH);
812 const video::SColor temp[4] =
820 const video::SColor* const useColor = colors ? colors : temp;
823 if (!setMaterialTexture(0, texture ))
826 setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 ||
827 useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255,
828 true, useAlphaChannelOfTexture);
830 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
834 if (!clipRect->isValid())
837 glEnable(GL_SCISSOR_TEST);
838 glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
839 clipRect->getWidth(), clipRect->getHeight());
842 f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
843 f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
844 f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
845 f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
847 S3DVertex vertices[4];
848 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y);
849 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y);
850 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y);
851 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y);
853 drawQuad(vt2DImage, vertices);
856 glDisable(GL_SCISSOR_TEST);
858 testGLError(__LINE__);
861 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip)
867 if (!setMaterialTexture(0, texture ))
870 setRenderStates2DMode(false, true, true);
872 S3DVertex quad2DVertices[4];
874 quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f);
875 quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f);
876 quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f);
877 quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f);
879 f32 modificator = (flip) ? 1.f : 0.f;
881 quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator);
882 quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator);
883 quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator);
884 quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator);
886 quad2DVertices[0].Color = SColor(0xFFFFFFFF);
887 quad2DVertices[1].Color = SColor(0xFFFFFFFF);
888 quad2DVertices[2].Color = SColor(0xFFFFFFFF);
889 quad2DVertices[3].Color = SColor(0xFFFFFFFF);
891 drawQuad(vt2DImage, quad2DVertices);
894 void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture,
895 const core::array<core::position2d<s32> >& positions,
896 const core::array<core::rect<s32> >& sourceRects,
897 const core::rect<s32>* clipRect,
898 SColor color, bool useAlphaChannelOfTexture)
904 if (!setMaterialTexture(0, texture))
907 setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture);
909 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
913 if (!clipRect->isValid())
916 glEnable(GL_SCISSOR_TEST);
917 glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
918 clipRect->getWidth(), clipRect->getHeight());
921 const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size());
922 assert(6 * std::size_t(drawCount) <= QuadsIndices.size());
924 core::array<S3DVertex> vtx(drawCount * 4);
926 for (u32 i = 0; i < drawCount; i++)
928 core::position2d<s32> targetPos = positions[i];
929 core::position2d<s32> sourcePos = sourceRects[i].UpperLeftCorner;
930 // This needs to be signed as it may go negative.
931 core::dimension2d<s32> sourceSize(sourceRects[i].getSize());
935 core::rect<f32> tcoords;
936 tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ;
937 tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height;
938 tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width);
939 tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height);
941 const core::rect<s32> poss(targetPos, sourceSize);
943 f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
944 f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
945 f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
946 f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
948 vtx.push_back(S3DVertex(left, top, 0.0f,
949 0.0f, 0.0f, 0.0f, color,
950 tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y));
951 vtx.push_back(S3DVertex(right, top, 0.0f,
952 0.0f, 0.0f, 0.0f, color,
953 tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y));
954 vtx.push_back(S3DVertex(right, down, 0.0f,
955 0.0f, 0.0f, 0.0f, color,
956 tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y));
957 vtx.push_back(S3DVertex(left, down, 0.0f,
958 0.0f, 0.0f, 0.0f, color,
959 tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y));
962 drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), QuadsIndices.data(), 6 * drawCount);
965 glDisable(GL_SCISSOR_TEST);
969 //! draw a 2d rectangle
970 void COpenGL3DriverBase::draw2DRectangle(SColor color,
971 const core::rect<s32>& position,
972 const core::rect<s32>* clip)
975 setMaterialTexture(0, 0);
977 setRenderStates2DMode(color.getAlpha() < 255, false, false);
979 core::rect<s32> pos = position;
982 pos.clipAgainst(*clip);
987 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
989 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
990 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
991 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
992 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
994 S3DVertex vertices[4];
995 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0);
996 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0);
997 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0);
998 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0);
1000 drawQuad(vtPrimitive, vertices);
1004 //! draw an 2d rectangle
1005 void COpenGL3DriverBase::draw2DRectangle(const core::rect<s32>& position,
1006 SColor colorLeftUp, SColor colorRightUp,
1007 SColor colorLeftDown, SColor colorRightDown,
1008 const core::rect<s32>* clip)
1010 core::rect<s32> pos = position;
1013 pos.clipAgainst(*clip);
1019 setMaterialTexture(0, 0);
1021 setRenderStates2DMode(colorLeftUp.getAlpha() < 255 ||
1022 colorRightUp.getAlpha() < 255 ||
1023 colorLeftDown.getAlpha() < 255 ||
1024 colorRightDown.getAlpha() < 255, false, false);
1026 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1028 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1029 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1030 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1031 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1033 S3DVertex vertices[4];
1034 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0);
1035 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0);
1036 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0);
1037 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0);
1039 drawQuad(vtPrimitive, vertices);
1043 //! Draws a 2d line.
1044 void COpenGL3DriverBase::draw2DLine(const core::position2d<s32>& start,
1045 const core::position2d<s32>& end, SColor color)
1048 drawPixel(start.X, start.Y, color);
1052 setMaterialTexture(0, 0);
1054 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1056 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1058 f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1059 f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1060 f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1061 f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1063 S3DVertex vertices[2];
1064 vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0);
1065 vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1);
1067 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1073 void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color)
1075 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1076 if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height)
1080 setMaterialTexture(0, 0);
1082 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1084 f32 X = (f32)x / (f32)renderTargetSize.Width * 2.f - 1.f;
1085 f32 Y = 2.f - (f32)y / (f32)renderTargetSize.Height * 2.f - 1.f;
1087 S3DVertex vertices[1];
1088 vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0);
1090 drawArrays(GL_POINTS, vtPrimitive, vertices, 1);
1093 void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4])
1095 drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4);
1098 void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount)
1100 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1101 glDrawArrays(primitiveType, 0, vertexCount);
1102 endDraw(vertexType);
1105 void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount)
1107 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1108 glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, indices);
1109 endDraw(vertexType);
1112 void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase)
1114 for (auto attr: vertexType) {
1115 glEnableVertexAttribArray(attr.Index);
1116 switch (attr.mode) {
1117 case VertexAttribute::Mode::Regular: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1118 case VertexAttribute::Mode::Normalized: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1119 case VertexAttribute::Mode::Integral: glVertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1124 void COpenGL3DriverBase::endDraw(const VertexType &vertexType)
1126 for (auto attr: vertexType)
1127 glDisableVertexAttribArray(attr.Index);
1130 ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image)
1132 core::array<IImage*> imageArray(1);
1133 imageArray.push_back(image);
1135 COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this);
1140 ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array<IImage*>& image)
1142 COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this);
1147 //! Sets a material.
1148 void COpenGL3DriverBase::setMaterial(const SMaterial& material)
1150 Material = material;
1151 OverrideMaterial.apply(Material);
1153 for (u32 i = 0; i < Feature.MaxTextureUnits; ++i)
1155 CacheHandler->getTextureCache().set(i, material.getTexture(i));
1156 setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i));
1160 //! prints error if an error happened.
1161 bool COpenGL3DriverBase::testGLError(int code)
1164 GLenum g = glGetError();
1169 case GL_INVALID_ENUM:
1170 os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR);
1172 case GL_INVALID_VALUE:
1173 os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR);
1175 case GL_INVALID_OPERATION:
1176 os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR);
1178 case GL_OUT_OF_MEMORY:
1179 os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR);
1188 //! prints error if an error happened.
1189 bool COpenGL3DriverBase::testEGLError()
1191 #if defined(EGL_VERSION_1_0) && defined(_DEBUG)
1192 EGLint g = eglGetError();
1197 case EGL_NOT_INITIALIZED :
1198 os::Printer::log("Not Initialized", ELL_ERROR);
1200 case EGL_BAD_ACCESS:
1201 os::Printer::log("Bad Access", ELL_ERROR);
1204 os::Printer::log("Bad Alloc", ELL_ERROR);
1206 case EGL_BAD_ATTRIBUTE:
1207 os::Printer::log("Bad Attribute", ELL_ERROR);
1209 case EGL_BAD_CONTEXT:
1210 os::Printer::log("Bad Context", ELL_ERROR);
1212 case EGL_BAD_CONFIG:
1213 os::Printer::log("Bad Config", ELL_ERROR);
1215 case EGL_BAD_CURRENT_SURFACE:
1216 os::Printer::log("Bad Current Surface", ELL_ERROR);
1218 case EGL_BAD_DISPLAY:
1219 os::Printer::log("Bad Display", ELL_ERROR);
1221 case EGL_BAD_SURFACE:
1222 os::Printer::log("Bad Surface", ELL_ERROR);
1225 os::Printer::log("Bad Match", ELL_ERROR);
1227 case EGL_BAD_PARAMETER:
1228 os::Printer::log("Bad Parameter", ELL_ERROR);
1230 case EGL_BAD_NATIVE_PIXMAP:
1231 os::Printer::log("Bad Native Pixmap", ELL_ERROR);
1233 case EGL_BAD_NATIVE_WINDOW:
1234 os::Printer::log("Bad Native Window", ELL_ERROR);
1236 case EGL_CONTEXT_LOST:
1237 os::Printer::log("Context Lost", ELL_ERROR);
1247 void COpenGL3DriverBase::setRenderStates3DMode()
1249 if ( LockRenderStateMode )
1252 if (CurrentRenderMode != ERM_3D)
1254 // Reset Texture Stages
1255 CacheHandler->setBlend(false);
1256 CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1258 ResetRenderStates = true;
1261 if (ResetRenderStates || LastMaterial != Material)
1263 // unset old material
1265 // unset last 3d material
1266 if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive)
1268 MaterialRenderer2DActive->OnUnsetMaterial();
1269 MaterialRenderer2DActive = 0;
1271 else if (LastMaterial.MaterialType != Material.MaterialType &&
1272 static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1273 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1275 // set new material.
1276 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1277 MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial(
1278 Material, LastMaterial, ResetRenderStates, this);
1280 LastMaterial = Material;
1281 CacheHandler->correctCacheMaterial(LastMaterial);
1282 ResetRenderStates = false;
1285 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1286 MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD);
1288 CurrentRenderMode = ERM_3D;
1291 //! Can be called by an IMaterialRenderer to make its work easier.
1292 void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates)
1295 switch (material.ZBuffer)
1298 CacheHandler->setDepthTest(false);
1300 case ECFN_LESSEQUAL:
1301 CacheHandler->setDepthTest(true);
1302 CacheHandler->setDepthFunc(GL_LEQUAL);
1305 CacheHandler->setDepthTest(true);
1306 CacheHandler->setDepthFunc(GL_EQUAL);
1309 CacheHandler->setDepthTest(true);
1310 CacheHandler->setDepthFunc(GL_LESS);
1313 CacheHandler->setDepthTest(true);
1314 CacheHandler->setDepthFunc(GL_NOTEQUAL);
1316 case ECFN_GREATEREQUAL:
1317 CacheHandler->setDepthTest(true);
1318 CacheHandler->setDepthFunc(GL_GEQUAL);
1321 CacheHandler->setDepthTest(true);
1322 CacheHandler->setDepthFunc(GL_GREATER);
1325 CacheHandler->setDepthTest(true);
1326 CacheHandler->setDepthFunc(GL_ALWAYS);
1329 CacheHandler->setDepthTest(true);
1330 CacheHandler->setDepthFunc(GL_NEVER);
1337 if (getWriteZBuffer(material))
1339 CacheHandler->setDepthMask(true);
1343 CacheHandler->setDepthMask(false);
1346 // Back face culling
1347 if ((material.FrontfaceCulling) && (material.BackfaceCulling))
1349 CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK);
1350 CacheHandler->setCullFace(true);
1352 else if (material.BackfaceCulling)
1354 CacheHandler->setCullFaceFunc(GL_BACK);
1355 CacheHandler->setCullFace(true);
1357 else if (material.FrontfaceCulling)
1359 CacheHandler->setCullFaceFunc(GL_FRONT);
1360 CacheHandler->setCullFace(true);
1364 CacheHandler->setCullFace(false);
1368 CacheHandler->setColorMask(material.ColorMask);
1371 if (material.BlendOperation == EBO_NONE)
1372 CacheHandler->setBlend(false);
1375 CacheHandler->setBlend(true);
1377 switch (material.BlendOperation)
1380 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1383 CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT);
1385 case EBO_REVSUBTRACT:
1386 CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
1394 if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF?
1395 && material.MaterialType != EMT_ONETEXTURE_BLEND
1398 E_BLEND_FACTOR srcRGBFact = EBF_ZERO;
1399 E_BLEND_FACTOR dstRGBFact = EBF_ZERO;
1400 E_BLEND_FACTOR srcAlphaFact = EBF_ZERO;
1401 E_BLEND_FACTOR dstAlphaFact = EBF_ZERO;
1402 E_MODULATE_FUNC modulo = EMFN_MODULATE_1X;
1403 u32 alphaSource = 0;
1405 unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor);
1407 CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact),
1408 getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact));
1411 // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver.
1413 if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness)
1414 glLineWidth(core::clamp(static_cast<GLfloat>(material.Thickness), DimAliasedLine[0], DimAliasedLine[1]));
1417 if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing)
1419 if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1420 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1421 else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1422 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1425 // Texture parameters
1426 setTextureRenderStates(material, resetAllRenderStates);
1429 //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call.
1430 void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates)
1432 // Set textures to TU/TIU and apply filters to them
1434 for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i)
1436 const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i];
1441 GLenum tmpTextureType = tmpTexture->getOpenGLTextureType();
1443 CacheHandler->setActiveTexture(GL_TEXTURE0 + i);
1445 if (resetAllRenderstates)
1446 tmpTexture->getStatesCache().IsCached = false;
1448 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1449 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter)
1451 glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER,
1452 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1454 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1455 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1458 if (material.UseMipMaps && tmpTexture->hasMipMaps())
1460 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1461 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus)
1463 glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1464 material.TextureLayer[i].TrilinearFilter ? GL_LINEAR_MIPMAP_LINEAR :
1465 material.TextureLayer[i].BilinearFilter ? GL_LINEAR_MIPMAP_NEAREST :
1466 GL_NEAREST_MIPMAP_NEAREST);
1468 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1469 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1470 tmpTexture->getStatesCache().MipMapStatus = true;
1475 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1476 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus)
1478 glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1479 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1481 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1482 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1483 tmpTexture->getStatesCache().MipMapStatus = false;
1487 #ifdef GL_EXT_texture_filter_anisotropic
1488 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] &&
1489 (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter))
1491 glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1492 material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1);
1494 tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter;
1498 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU)
1500 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU));
1501 tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU;
1504 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV)
1506 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV));
1507 tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV;
1510 tmpTexture->getStatesCache().IsCached = true;
1515 // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode.
1516 GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const
1521 case ETC_CLAMP_TO_EDGE:
1522 case ETC_CLAMP_TO_BORDER:
1523 return GL_CLAMP_TO_EDGE;
1532 //! sets the needed renderstates
1533 void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel)
1535 if ( LockRenderStateMode )
1538 COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture;
1540 if (CurrentRenderMode != ERM_2D)
1542 // unset last 3d material
1543 if (CurrentRenderMode == ERM_3D)
1545 if (static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1546 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1549 CurrentRenderMode = ERM_2D;
1551 else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer)
1553 MaterialRenderer2DActive->OnUnsetMaterial();
1556 MaterialRenderer2DActive = nextActiveRenderer;
1558 MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0);
1559 LastMaterial = Material;
1560 CacheHandler->correctCacheMaterial(LastMaterial);
1562 // no alphaChannel without texture
1563 alphaChannel &= texture;
1565 if (alphaChannel || alpha)
1567 CacheHandler->setBlend(true);
1568 CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1569 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1572 CacheHandler->setBlend(false);
1574 Material.setTexture(0, const_cast<COpenGL3Texture*>(CacheHandler->getTextureCache().get(0)));
1575 setTransform(ETS_TEXTURE_0, core::IdentityMatrix);
1579 if (OverrideMaterial2DEnabled)
1580 setTextureRenderStates(OverrideMaterial2D, false);
1582 setTextureRenderStates(InitMaterial2D, false);
1585 MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD);
1589 void COpenGL3DriverBase::chooseMaterial2D()
1591 if (!OverrideMaterial2DEnabled)
1592 Material = InitMaterial2D;
1594 if (OverrideMaterial2DEnabled)
1596 OverrideMaterial2D.Lighting=false;
1597 OverrideMaterial2D.ZWriteEnable=EZW_OFF;
1598 OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge
1599 OverrideMaterial2D.Lighting=false;
1601 Material = OverrideMaterial2D;
1606 //! \return Returns the name of the video driver.
1607 const wchar_t* COpenGL3DriverBase::getName() const
1609 return Name.c_str();
1612 void COpenGL3DriverBase::setViewPort(const core::rect<s32>& area)
1614 core::rect<s32> vp = area;
1615 core::rect<s32> rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
1616 vp.clipAgainst(rendert);
1618 if (vp.getHeight() > 0 && vp.getWidth() > 0)
1619 CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight());
1625 void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height)
1627 CacheHandler->setViewport(0, 0, width, height);
1628 ViewPort = core::recti(0, 0, width, height);
1632 //! Draws a 3d line.
1633 void COpenGL3DriverBase::draw3DLine(const core::vector3df& start,
1634 const core::vector3df& end, SColor color)
1636 setRenderStates3DMode();
1638 S3DVertex vertices[2];
1639 vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0);
1640 vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0);
1642 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1646 //! Only used by the internal engine. Used to notify the driver that
1647 //! the window was resized.
1648 void COpenGL3DriverBase::OnResize(const core::dimension2d<u32>& size)
1650 CNullDriver::OnResize(size);
1651 CacheHandler->setViewport(0, 0, size.Width, size.Height);
1652 Transformation3DChanged = true;
1656 //! Returns type of video driver
1657 E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const
1663 //! returns color format
1664 ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const
1670 //! Get a vertex shader constant index.
1671 s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name)
1673 return getPixelShaderConstantID(name);
1676 //! Get a pixel shader constant index.
1677 s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name)
1679 os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID().");
1683 //! Sets a vertex shader constant.
1684 void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1686 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1689 //! Sets a pixel shader constant.
1690 void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1692 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1695 //! Sets a constant for the vertex shader based on an index.
1696 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count)
1698 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1702 //! Int interface for the above.
1703 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count)
1705 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1709 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count)
1711 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1715 //! Sets a constant for the pixel shader based on an index.
1716 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count)
1718 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1722 //! Int interface for the above.
1723 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count)
1725 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1729 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count)
1731 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1735 //! Adds a new material renderer to the VideoDriver, using pixel and/or
1736 //! vertex shaders to render geometry.
1737 s32 COpenGL3DriverBase::addShaderMaterial(const c8* vertexShaderProgram,
1738 const c8* pixelShaderProgram,
1739 IShaderConstantSetCallBack* callback,
1740 E_MATERIAL_TYPE baseMaterial, s32 userData)
1742 os::Printer::log("No shader support.");
1747 //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
1748 s32 COpenGL3DriverBase::addHighLevelShaderMaterial(
1749 const c8* vertexShaderProgram,
1750 const c8* vertexShaderEntryPointName,
1751 E_VERTEX_SHADER_TYPE vsCompileTarget,
1752 const c8* pixelShaderProgram,
1753 const c8* pixelShaderEntryPointName,
1754 E_PIXEL_SHADER_TYPE psCompileTarget,
1755 const c8* geometryShaderProgram,
1756 const c8* geometryShaderEntryPointName,
1757 E_GEOMETRY_SHADER_TYPE gsCompileTarget,
1758 scene::E_PRIMITIVE_TYPE inType,
1759 scene::E_PRIMITIVE_TYPE outType,
1761 IShaderConstantSetCallBack* callback,
1762 E_MATERIAL_TYPE baseMaterial,
1766 COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer(
1767 this, nr, vertexShaderProgram,
1769 callback, baseMaterial, userData);
1775 //! Returns a pointer to the IVideoDriver interface. (Implementation for
1776 //! IMaterialRendererServices)
1777 IVideoDriver* COpenGL3DriverBase::getVideoDriver()
1783 //! Returns pointer to the IGPUProgrammingServices interface.
1784 IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices()
1789 ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d<u32>& size,
1790 const io::path& name, const ECOLOR_FORMAT format)
1792 //disable mip-mapping
1793 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1794 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1796 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this);
1797 addTexture(renderTargetTexture);
1798 renderTargetTexture->drop();
1800 //restore mip-mapping
1801 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1803 return renderTargetTexture;
1806 ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format)
1808 //disable mip-mapping
1809 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1810 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1812 bool supportForFBO = (Feature.ColorAttachment > 0);
1814 const core::dimension2d<u32> size(sideLen, sideLen);
1815 core::dimension2du destSize(size);
1819 destSize = core::dimension2d<u32>(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height));
1820 destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false);
1823 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this);
1824 addTexture(renderTargetTexture);
1825 renderTargetTexture->drop();
1827 //restore mip-mapping
1828 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1830 return renderTargetTexture;
1834 //! Returns the maximum amount of primitives
1835 u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const
1840 bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil)
1842 if (target && target->getDriverType() != getDriverType())
1844 os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR);
1848 core::dimension2d<u32> destRenderTargetSize(0, 0);
1852 COpenGL3RenderTarget* renderTarget = static_cast<COpenGL3RenderTarget*>(target);
1854 CacheHandler->setFBO(renderTarget->getBufferID());
1855 renderTarget->update();
1857 destRenderTargetSize = renderTarget->getSize();
1859 setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height);
1863 CacheHandler->setFBO(0);
1865 destRenderTargetSize = core::dimension2d<u32>(0, 0);
1867 setViewPortRaw(ScreenSize.Width, ScreenSize.Height);
1870 if (CurrentRenderTargetSize != destRenderTargetSize)
1872 CurrentRenderTargetSize = destRenderTargetSize;
1874 Transformation3DChanged = true;
1877 CurrentRenderTarget = target;
1879 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
1884 void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil)
1886 GLbitfield mask = 0;
1888 bool depthMask = false;
1890 CacheHandler->getColorMask(colorMask);
1891 CacheHandler->getDepthMask(depthMask);
1893 if (flag & ECBF_COLOR)
1895 CacheHandler->setColorMask(ECP_ALL);
1897 const f32 inv = 1.0f / 255.0f;
1898 glClearColor(color.getRed() * inv, color.getGreen() * inv,
1899 color.getBlue() * inv, color.getAlpha() * inv);
1901 mask |= GL_COLOR_BUFFER_BIT;
1904 if (flag & ECBF_DEPTH)
1906 CacheHandler->setDepthMask(true);
1907 glClearDepthf(depth);
1908 mask |= GL_DEPTH_BUFFER_BIT;
1911 if (flag & ECBF_STENCIL)
1913 glClearStencil(stencil);
1914 mask |= GL_STENCIL_BUFFER_BIT;
1920 CacheHandler->setColorMask(colorMask);
1921 CacheHandler->setDepthMask(depthMask);
1925 //! Returns an image created from the last rendered frame.
1926 // We want to read the front buffer to get the latest render finished.
1927 // This is not possible under ogl-es, though, so one has to call this method
1928 // outside of the render loop only.
1929 IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target)
1931 if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS)
1934 GLint internalformat = GL_RGBA;
1935 GLint type = GL_UNSIGNED_BYTE;
1937 // glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat);
1938 // glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
1939 // there's a format we don't support ATM
1940 if (GL_UNSIGNED_SHORT_4_4_4_4 == type)
1942 internalformat = GL_RGBA;
1943 type = GL_UNSIGNED_BYTE;
1947 IImage* newImage = 0;
1948 if (GL_RGBA == internalformat)
1950 if (GL_UNSIGNED_BYTE == type)
1951 newImage = new CImage(ECF_A8R8G8B8, ScreenSize);
1953 newImage = new CImage(ECF_A1R5G5B5, ScreenSize);
1957 if (GL_UNSIGNED_BYTE == type)
1958 newImage = new CImage(ECF_R8G8B8, ScreenSize);
1960 newImage = new CImage(ECF_R5G6B5, ScreenSize);
1966 u8* pixels = static_cast<u8*>(newImage->getData());
1973 glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels);
1974 testGLError(__LINE__);
1976 // opengl images are horizontally flipped, so we have to fix that here.
1977 const s32 pitch = newImage->getPitch();
1978 u8* p2 = pixels + (ScreenSize.Height - 1) * pitch;
1979 u8* tmpBuffer = new u8[pitch];
1980 for (u32 i = 0; i < ScreenSize.Height; i += 2)
1982 memcpy(tmpBuffer, pixels, pitch);
1983 memcpy(pixels, p2, pitch);
1984 memcpy(p2, tmpBuffer, pitch);
1988 delete [] tmpBuffer;
1990 // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA)
1991 if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type)
1993 pixels = static_cast<u8*>(newImage->getData());
1994 for (u32 i = 0; i < ScreenSize.Height; i++)
1996 for (u32 j = 0; j < ScreenSize.Width; j++)
1998 u32 c = *(u32*) (pixels + 4 * j);
1999 *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) |
2000 ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
2006 if (testGLError(__LINE__))
2011 testGLError(__LINE__);
2015 void COpenGL3DriverBase::removeTexture(ITexture* texture)
2017 CacheHandler->getTextureCache().remove(texture);
2018 CNullDriver::removeTexture(texture);
2021 //! Set/unset a clipping plane.
2022 bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
2024 if (index >= UserClipPlane.size())
2025 UserClipPlane.push_back(SUserClipPlane());
2027 UserClipPlane[index].Plane = plane;
2028 UserClipPlane[index].Enabled = enable;
2032 //! Enable/disable a clipping plane.
2033 void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable)
2035 UserClipPlane[index].Enabled = enable;
2038 //! Get the ClipPlane Count
2039 u32 COpenGL3DriverBase::getClipPlaneCount() const
2041 return UserClipPlane.size();
2044 const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const
2046 if (index < UserClipPlane.size())
2047 return UserClipPlane[index].Plane;
2050 _IRR_DEBUG_BREAK_IF(true) // invalid index
2051 static const core::plane3df dummy;
2056 core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const
2058 return core::dimension2du(MaxTextureSize, MaxTextureSize);
2061 GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const
2063 static GLenum const blendTable[] =
2068 GL_ONE_MINUS_DST_COLOR,
2070 GL_ONE_MINUS_SRC_COLOR,
2072 GL_ONE_MINUS_SRC_ALPHA,
2074 GL_ONE_MINUS_DST_ALPHA,
2075 GL_SRC_ALPHA_SATURATE
2078 return blendTable[factor];
2081 bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat,
2082 GLenum& pixelType, void(**converter)(const void*, s32, void*)) const
2084 bool supported = false;
2085 pixelFormat = GL_RGBA;
2086 pixelType = GL_UNSIGNED_BYTE;
2093 pixelFormat = GL_RGBA;
2094 pixelType = GL_UNSIGNED_SHORT_5_5_5_1;
2095 *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1;
2099 pixelFormat = GL_RGB;
2100 pixelType = GL_UNSIGNED_SHORT_5_6_5;
2104 pixelFormat = GL_RGB;
2105 pixelType = GL_UNSIGNED_BYTE;
2109 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) ||
2110 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) ||
2111 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888))
2113 pixelFormat = GL_BGRA;
2117 pixelFormat = GL_RGBA;
2118 *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8;
2120 pixelType = GL_UNSIGNED_BYTE;
2122 #ifdef GL_EXT_texture_compression_s3tc
2125 pixelFormat = GL_RGBA;
2126 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
2131 pixelFormat = GL_RGBA;
2132 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
2137 pixelFormat = GL_RGBA;
2138 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
2141 #ifdef GL_OES_compressed_ETC1_RGB8_texture
2144 pixelFormat = GL_RGB;
2145 pixelType = GL_ETC1_RGB8_OES;
2148 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2151 pixelFormat = GL_RGB;
2152 pixelType = GL_COMPRESSED_RGB8_ETC2;
2155 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2158 pixelFormat = GL_RGBA;
2159 pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC;
2164 pixelFormat = GL_DEPTH_COMPONENT;
2165 pixelType = GL_UNSIGNED_SHORT;
2168 #if defined(GL_OES_depth32)
2169 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32))
2172 pixelFormat = GL_DEPTH_COMPONENT;
2173 pixelType = GL_UNSIGNED_INT;
2178 #ifdef GL_OES_packed_depth_stencil
2179 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil))
2182 pixelFormat = GL_DEPTH_STENCIL_OES;
2183 pixelType = GL_UNSIGNED_INT_24_8_OES;
2188 #if defined(GL_EXT_texture_rg)
2189 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2192 pixelFormat = GL_RED_EXT;
2193 pixelType = GL_UNSIGNED_BYTE;
2198 #if defined(GL_EXT_texture_rg)
2199 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2202 pixelFormat = GL_RG_EXT;
2203 pixelType = GL_UNSIGNED_BYTE;
2212 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2213 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2214 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2218 pixelFormat = GL_RED_EXT;
2219 pixelType = GL_HALF_FLOAT_OES ;
2224 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2225 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2226 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2230 pixelFormat = GL_RG_EXT;
2231 pixelType = GL_HALF_FLOAT_OES ;
2235 case ECF_A16B16G16R16F:
2236 #if defined(GL_OES_texture_half_float)
2237 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2240 pixelFormat = GL_RGBA;
2241 pixelType = GL_HALF_FLOAT_OES ;
2246 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2247 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2248 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2252 pixelFormat = GL_RED_EXT;
2253 pixelType = GL_FLOAT;
2258 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2259 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2260 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2264 pixelFormat = GL_RG_EXT;
2265 pixelType = GL_FLOAT;
2269 case ECF_A32B32G32R32F:
2270 #if defined(GL_OES_texture_float)
2271 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2274 pixelFormat = GL_RGBA;
2275 pixelType = GL_FLOAT ;
2283 // ES 2.0 says internalFormat must match pixelFormat (chapter 3.7.1 in Spec).
2284 // Doesn't mention if "match" means "equal" or some other way of matching, but
2285 // some bug on Emscripten and browsing discussions by others lead me to believe
2286 // it means they have to be equal. Note that this was different in OpenGL.
2287 internalFormat = pixelFormat;
2289 #ifdef _IRR_IOS_PLATFORM_
2290 if (internalFormat == GL_BGRA)
2291 internalFormat = GL_RGBA;
2297 bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const
2299 GLint dummyInternalFormat;
2300 GLenum dummyPixelFormat;
2301 GLenum dummyPixelType;
2302 void (*dummyConverter)(const void*, s32, void*);
2303 return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter);
2306 bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const
2308 return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation();
2311 const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const
2316 COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const
2318 return CacheHandler;