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 std::vector<GLushort> QuadsIndices;
190 QuadsIndices.reserve(6 * max_quad_count);
191 for (int k = 0; k < max_quad_count; k++) {
192 QuadsIndices.push_back(4 * k + 0);
193 QuadsIndices.push_back(4 * k + 1);
194 QuadsIndices.push_back(4 * k + 2);
195 QuadsIndices.push_back(4 * k + 0);
196 QuadsIndices.push_back(4 * k + 2);
197 QuadsIndices.push_back(4 * k + 3);
199 glGenBuffers(1, &QuadIndexBuffer);
200 glBindBuffer(GL_ARRAY_BUFFER, QuadIndexBuffer);
201 glBufferData(GL_ARRAY_BUFFER, sizeof(QuadsIndices[0]) * QuadsIndices.size(), QuadsIndices.data(), GL_STATIC_DRAW);
202 glBindBuffer(GL_ARRAY_BUFFER, 0);
203 QuadIndexCount = QuadsIndices.size();
206 bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer)
208 Name = glGetString(GL_VERSION);
211 // print renderer information
212 VendorName = glGetString(GL_VENDOR);
213 os::Printer::log(VendorName.c_str(), ELL_INFORMATION);
218 // reset cache handler
220 CacheHandler = new COpenGL3CacheHandler(this);
222 StencilBuffer = stencilBuffer;
224 DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits);
225 DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits);
226 // DriverAttributes->setAttribute("MaxLights", MaxLights);
227 DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy);
228 // DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes);
229 // DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers);
230 // DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets);
231 DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices);
232 DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize);
233 DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias);
234 DriverAttributes->setAttribute("Version", Version);
235 DriverAttributes->setAttribute("AntiAlias", AntiAlias);
237 glPixelStorei(GL_PACK_ALIGNMENT, 1);
239 UserClipPlane.reallocate(0);
241 for (s32 i = 0; i < ETS_COUNT; ++i)
242 setTransform(static_cast<E_TRANSFORMATION_STATE>(i), core::IdentityMatrix);
244 setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f));
247 glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
250 // create material renderers
251 createMaterialRenderers();
253 // set the renderstates
254 setRenderStates3DMode();
257 setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
259 // create matrix for flipping textures
260 TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f));
262 // We need to reset once more at the beginning of the first rendering.
263 // This fixes problems with intermediate changes to the material during texture load.
264 ResetRenderStates = true;
266 testGLError(__LINE__);
271 void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData)
273 io::path vsPath(OGLES2ShaderPath);
274 vsPath += vertexShaderName;
276 io::path fsPath(OGLES2ShaderPath);
277 fsPath += fragmentShaderName;
279 *vertexShaderData = 0;
280 *fragmentShaderData = 0;
282 io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath);
285 core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
286 warning += core::stringw(vsPath) + L"\n";
287 warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
288 os::Printer::log(warning.c_str(), ELL_WARNING);
292 io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath);
295 core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n");
296 warning += core::stringw(fsPath) + L"\n";
297 warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath";
298 os::Printer::log(warning.c_str(), ELL_WARNING);
302 long size = vsFile->getSize();
305 *vertexShaderData = new c8[size+1];
306 vsFile->read(*vertexShaderData, size);
307 (*vertexShaderData)[size] = 0;
310 size = fsFile->getSize();
313 // if both handles are the same we must reset the file
314 if (fsFile == vsFile)
317 *fragmentShaderData = new c8[size+1];
318 fsFile->read(*fragmentShaderData, size);
319 (*fragmentShaderData)[size] = 0;
326 void COpenGL3DriverBase::addDummyMaterial(E_MATERIAL_TYPE type) {
327 auto index = addMaterialRenderer(getMaterialRenderer(EMT_SOLID), "DUMMY");
328 assert(index == type);
331 void COpenGL3DriverBase::createMaterialRenderers()
335 COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB();
336 COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB();
337 COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB();
338 COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB();
339 COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB();
341 // Create built-in materials.
342 // The addition order must be the same as in the E_MATERIAL_TYPE enumeration. Thus the
343 // addDummyMaterial calls for materials no longer supported.
345 const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh";
348 core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh";
349 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
350 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0);
352 addDummyMaterial(EMT_SOLID_2_LAYER);
353 addDummyMaterial(EMT_LIGHTMAP);
354 addDummyMaterial(EMT_LIGHTMAP_ADD);
355 addDummyMaterial(EMT_LIGHTMAP_M2);
356 addDummyMaterial(EMT_LIGHTMAP_M4);
357 addDummyMaterial(EMT_LIGHTMAP_LIGHTING);
358 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M2);
359 addDummyMaterial(EMT_LIGHTMAP_LIGHTING_M4);
360 addDummyMaterial(EMT_DETAIL_MAP);
361 addDummyMaterial(EMT_SPHERE_MAP);
362 addDummyMaterial(EMT_REFLECTION_2_LAYER);
363 addDummyMaterial(EMT_TRANSPARENT_ADD_COLOR);
365 // EMT_TRANSPARENT_ALPHA_CHANNEL
366 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh";
367 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
368 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
370 // EMT_TRANSPARENT_ALPHA_CHANNEL_REF
371 FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh";
372 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
373 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0);
375 // EMT_TRANSPARENT_VERTEX_ALPHA
376 FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh";
377 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
378 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0);
380 addDummyMaterial(EMT_TRANSPARENT_REFLECTION_2_LAYER);
382 // EMT_ONETEXTURE_BLEND
383 FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh";
384 addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main",
385 EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0);
390 TransparentAlphaChannelCB->drop();
391 TransparentAlphaChannelRefCB->drop();
392 TransparentVertexAlphaCB->drop();
393 OneTextureBlendCB->drop();
395 // Create 2D material renderers
399 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData);
400 MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true);
406 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData);
407 MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false);
412 bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture)
414 Material.TextureLayer[layerIdx].Texture = const_cast<ITexture*>(texture); // function uses const-pointer for texture because all draw functions use const-pointers already
415 return CacheHandler->getTextureCache().set(0, texture);
418 bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
420 CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect);
423 ContextManager->activateContext(videoData, true);
425 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
430 bool COpenGL3DriverBase::endScene()
432 CNullDriver::endScene();
437 return ContextManager->swapBuffers();
443 //! Returns the transformation set by setTransform
444 const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const
446 return Matrices[state];
450 //! sets transformation
451 void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
453 Matrices[state] = mat;
454 Transformation3DChanged = true;
458 bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
463 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
464 const void* vertices = mb->getVertices();
465 const u32 vertexCount = mb->getVertexCount();
466 const E_VERTEX_TYPE vType = mb->getVertexType();
467 const u32 vertexSize = getVertexPitchFromType(vType);
469 const void *buffer = vertices;
470 size_t bufferSize = vertexSize * vertexCount;
472 //get or create buffer
473 bool newBuffer = false;
474 if (!HWBuffer->vbo_verticesID)
476 glGenBuffers(1, &HWBuffer->vbo_verticesID);
477 if (!HWBuffer->vbo_verticesID) return false;
480 else if (HWBuffer->vbo_verticesSize < bufferSize)
485 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
487 // copy data to graphics card
489 glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer);
492 HWBuffer->vbo_verticesSize = bufferSize;
494 if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC)
495 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW);
497 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW);
500 glBindBuffer(GL_ARRAY_BUFFER, 0);
502 return (!testGLError(__LINE__));
506 bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
511 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
513 const void* indices = mb->getIndices();
514 u32 indexCount = mb->getIndexCount();
517 switch (mb->getIndexType())
521 indexSize = sizeof(u16);
526 indexSize = sizeof(u32);
535 //get or create buffer
536 bool newBuffer = false;
537 if (!HWBuffer->vbo_indicesID)
539 glGenBuffers(1, &HWBuffer->vbo_indicesID);
540 if (!HWBuffer->vbo_indicesID) return false;
543 else if (HWBuffer->vbo_indicesSize < indexCount*indexSize)
548 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
550 // copy data to graphics card
552 glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices);
555 HWBuffer->vbo_indicesSize = indexCount * indexSize;
557 if (HWBuffer->Mapped_Index == scene::EHM_STATIC)
558 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW);
560 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW);
563 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
565 return (!testGLError(__LINE__));
569 //! updates hardware buffer if needed
570 bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer)
575 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
577 if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex()
578 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_verticesID)
581 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
583 if (!updateVertexHardwareBuffer(static_cast<SHWBufferLink_opengl*>(HWBuffer)))
588 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
590 if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index()
591 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_indicesID)
594 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
596 if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer))
605 //! Create hardware buffer from meshbuffer
606 COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb)
608 if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER))
611 SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb);
614 HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer);
616 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
617 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
618 HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex();
619 HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index();
620 HWBuffer->vbo_verticesID = 0;
621 HWBuffer->vbo_indicesID = 0;
622 HWBuffer->vbo_verticesSize = 0;
623 HWBuffer->vbo_indicesSize = 0;
625 if (!updateHardwareBuffer(HWBuffer))
627 deleteHardwareBuffer(HWBuffer);
635 void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer)
640 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
641 if (HWBuffer->vbo_verticesID)
643 glDeleteBuffers(1, &HWBuffer->vbo_verticesID);
644 HWBuffer->vbo_verticesID = 0;
646 if (HWBuffer->vbo_indicesID)
648 glDeleteBuffers(1, &HWBuffer->vbo_indicesID);
649 HWBuffer->vbo_indicesID = 0;
652 CNullDriver::deleteHardwareBuffer(_HWBuffer);
656 //! Draw hardware buffer
657 void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer)
662 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
664 updateHardwareBuffer(HWBuffer); //check if update is needed
666 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
667 const void *vertices = mb->getVertices();
668 const void *indexList = mb->getIndices();
670 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
672 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
676 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
678 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
683 drawVertexPrimitiveList(vertices, mb->getVertexCount(),
684 indexList, mb->getPrimitiveCount(),
685 mb->getVertexType(), mb->getPrimitiveType(),
688 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
689 glBindBuffer(GL_ARRAY_BUFFER, 0);
691 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
692 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
696 IRenderTarget* COpenGL3DriverBase::addRenderTarget()
698 COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this);
699 RenderTargets.push_back(renderTarget);
705 // small helper function to create vertex buffer object adress offsets
706 static inline u8* buffer_offset(const long offset)
708 return ((u8*)0 + offset);
712 //! draws a vertex primitive list
713 void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
714 const void* indexList, u32 primitiveCount,
715 E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
717 if (!primitiveCount || !vertexCount)
720 if (!checkPrimitiveCount(primitiveCount))
723 CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType);
725 setRenderStates3DMode();
727 auto &vTypeDesc = getVertexTypeDescription(vType);
728 beginDraw(vTypeDesc, reinterpret_cast<uintptr_t>(vertices));
729 GLenum indexSize = 0;
735 indexSize = GL_UNSIGNED_SHORT;
740 #ifdef GL_OES_element_index_uint
741 #ifndef GL_UNSIGNED_INT
742 #define GL_UNSIGNED_INT 0x1405
744 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint])
745 indexSize = GL_UNSIGNED_INT;
748 indexSize = GL_UNSIGNED_SHORT;
755 case scene::EPT_POINTS:
756 case scene::EPT_POINT_SPRITES:
757 glDrawArrays(GL_POINTS, 0, primitiveCount);
759 case scene::EPT_LINE_STRIP:
760 glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList);
762 case scene::EPT_LINE_LOOP:
763 glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList);
765 case scene::EPT_LINES:
766 glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList);
768 case scene::EPT_TRIANGLE_STRIP:
769 glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList);
771 case scene::EPT_TRIANGLE_FAN:
772 glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList);
774 case scene::EPT_TRIANGLES:
775 glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList);
785 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
786 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect, SColor color,
787 bool useAlphaChannelOfTexture)
792 if (!sourceRect.isValid())
795 SColor colors[4] = {color, color, color, color};
796 draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture);
800 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
801 const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect,
802 const video::SColor* const colors, bool useAlphaChannelOfTexture)
807 // texcoords need to be flipped horizontally for RTTs
808 const bool isRTT = texture->isRenderTarget();
809 const core::dimension2du& ss = texture->getOriginalSize();
810 const f32 invW = 1.f / static_cast<f32>(ss.Width);
811 const f32 invH = 1.f / static_cast<f32>(ss.Height);
812 const core::rect<f32> tcoords(
813 sourceRect.UpperLeftCorner.X * invW,
814 (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH,
815 sourceRect.LowerRightCorner.X * invW,
816 (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH);
818 const video::SColor temp[4] =
826 const video::SColor* const useColor = colors ? colors : temp;
829 if (!setMaterialTexture(0, texture ))
832 setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 ||
833 useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255,
834 true, useAlphaChannelOfTexture);
836 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
840 if (!clipRect->isValid())
843 glEnable(GL_SCISSOR_TEST);
844 glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
845 clipRect->getWidth(), clipRect->getHeight());
848 f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
849 f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
850 f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
851 f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
853 S3DVertex vertices[4];
854 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y);
855 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y);
856 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y);
857 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y);
859 drawQuad(vt2DImage, vertices);
862 glDisable(GL_SCISSOR_TEST);
864 testGLError(__LINE__);
867 void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip)
873 if (!setMaterialTexture(0, texture ))
876 setRenderStates2DMode(false, true, true);
878 S3DVertex quad2DVertices[4];
880 quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f);
881 quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f);
882 quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f);
883 quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f);
885 f32 modificator = (flip) ? 1.f : 0.f;
887 quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator);
888 quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator);
889 quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator);
890 quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator);
892 quad2DVertices[0].Color = SColor(0xFFFFFFFF);
893 quad2DVertices[1].Color = SColor(0xFFFFFFFF);
894 quad2DVertices[2].Color = SColor(0xFFFFFFFF);
895 quad2DVertices[3].Color = SColor(0xFFFFFFFF);
897 drawQuad(vt2DImage, quad2DVertices);
900 void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture,
901 const core::array<core::position2d<s32> >& positions,
902 const core::array<core::rect<s32> >& sourceRects,
903 const core::rect<s32>* clipRect,
904 SColor color, bool useAlphaChannelOfTexture)
910 if (!setMaterialTexture(0, texture))
913 setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture);
915 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
919 if (!clipRect->isValid())
922 glEnable(GL_SCISSOR_TEST);
923 glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
924 clipRect->getWidth(), clipRect->getHeight());
927 const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size());
928 assert(6 * drawCount <= QuadIndexCount); // FIXME split the batch? or let it crash?
930 core::array<S3DVertex> vtx(drawCount * 4);
932 for (u32 i = 0; i < drawCount; i++)
934 core::position2d<s32> targetPos = positions[i];
935 core::position2d<s32> sourcePos = sourceRects[i].UpperLeftCorner;
936 // This needs to be signed as it may go negative.
937 core::dimension2d<s32> sourceSize(sourceRects[i].getSize());
941 core::rect<f32> tcoords;
942 tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ;
943 tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height;
944 tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width);
945 tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height);
947 const core::rect<s32> poss(targetPos, sourceSize);
949 f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
950 f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
951 f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
952 f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
954 vtx.push_back(S3DVertex(left, top, 0.0f,
955 0.0f, 0.0f, 0.0f, color,
956 tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y));
957 vtx.push_back(S3DVertex(right, top, 0.0f,
958 0.0f, 0.0f, 0.0f, color,
959 tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y));
960 vtx.push_back(S3DVertex(right, down, 0.0f,
961 0.0f, 0.0f, 0.0f, color,
962 tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y));
963 vtx.push_back(S3DVertex(left, down, 0.0f,
964 0.0f, 0.0f, 0.0f, color,
965 tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y));
968 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, QuadIndexBuffer);
969 drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), vtx.size(), 0, 6 * drawCount);
970 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
973 glDisable(GL_SCISSOR_TEST);
977 //! draw a 2d rectangle
978 void COpenGL3DriverBase::draw2DRectangle(SColor color,
979 const core::rect<s32>& position,
980 const core::rect<s32>* clip)
983 setMaterialTexture(0, 0);
985 setRenderStates2DMode(color.getAlpha() < 255, false, false);
987 core::rect<s32> pos = position;
990 pos.clipAgainst(*clip);
995 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
997 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
998 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
999 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1000 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1002 S3DVertex vertices[4];
1003 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0);
1004 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0);
1005 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0);
1006 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0);
1008 drawQuad(vtPrimitive, vertices);
1012 //! draw an 2d rectangle
1013 void COpenGL3DriverBase::draw2DRectangle(const core::rect<s32>& position,
1014 SColor colorLeftUp, SColor colorRightUp,
1015 SColor colorLeftDown, SColor colorRightDown,
1016 const core::rect<s32>* clip)
1018 core::rect<s32> pos = position;
1021 pos.clipAgainst(*clip);
1027 setMaterialTexture(0, 0);
1029 setRenderStates2DMode(colorLeftUp.getAlpha() < 255 ||
1030 colorRightUp.getAlpha() < 255 ||
1031 colorLeftDown.getAlpha() < 255 ||
1032 colorRightDown.getAlpha() < 255, false, false);
1034 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1036 f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1037 f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1038 f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1039 f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1041 S3DVertex vertices[4];
1042 vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0);
1043 vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0);
1044 vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0);
1045 vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0);
1047 drawQuad(vtPrimitive, vertices);
1051 //! Draws a 2d line.
1052 void COpenGL3DriverBase::draw2DLine(const core::position2d<s32>& start,
1053 const core::position2d<s32>& end, SColor color)
1056 drawPixel(start.X, start.Y, color);
1060 setMaterialTexture(0, 0);
1062 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1064 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1066 f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1067 f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f;
1068 f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1069 f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f;
1071 S3DVertex vertices[2];
1072 vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0);
1073 vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1);
1075 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1081 void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color)
1083 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1084 if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height)
1088 setMaterialTexture(0, 0);
1090 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1092 f32 X = (f32)x / (f32)renderTargetSize.Width * 2.f - 1.f;
1093 f32 Y = 2.f - (f32)y / (f32)renderTargetSize.Height * 2.f - 1.f;
1095 S3DVertex vertices[1];
1096 vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0);
1098 drawArrays(GL_POINTS, vtPrimitive, vertices, 1);
1101 void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4])
1103 drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4);
1106 void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount)
1108 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1109 glDrawArrays(primitiveType, 0, vertexCount);
1110 endDraw(vertexType);
1113 void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount, const u16 *indices, int indexCount)
1115 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1116 glDrawRangeElements(primitiveType, 0, vertexCount - 1, indexCount, GL_UNSIGNED_SHORT, indices);
1117 endDraw(vertexType);
1120 void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase)
1122 for (auto attr: vertexType) {
1123 glEnableVertexAttribArray(attr.Index);
1124 switch (attr.mode) {
1125 case VertexAttribute::Mode::Regular: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1126 case VertexAttribute::Mode::Normalized: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1127 case VertexAttribute::Mode::Integral: glVertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast<void *>(verticesBase + attr.Offset)); break;
1132 void COpenGL3DriverBase::endDraw(const VertexType &vertexType)
1134 for (auto attr: vertexType)
1135 glDisableVertexAttribArray(attr.Index);
1138 ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image)
1140 core::array<IImage*> imageArray(1);
1141 imageArray.push_back(image);
1143 COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this);
1148 ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array<IImage*>& image)
1150 COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this);
1155 //! Sets a material.
1156 void COpenGL3DriverBase::setMaterial(const SMaterial& material)
1158 Material = material;
1159 OverrideMaterial.apply(Material);
1161 for (u32 i = 0; i < Feature.MaxTextureUnits; ++i)
1163 CacheHandler->getTextureCache().set(i, material.getTexture(i));
1164 setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i));
1168 //! prints error if an error happened.
1169 bool COpenGL3DriverBase::testGLError(int code)
1172 GLenum g = glGetError();
1177 case GL_INVALID_ENUM:
1178 os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR);
1180 case GL_INVALID_VALUE:
1181 os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR);
1183 case GL_INVALID_OPERATION:
1184 os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR);
1186 case GL_OUT_OF_MEMORY:
1187 os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR);
1196 //! prints error if an error happened.
1197 bool COpenGL3DriverBase::testEGLError()
1199 #if defined(EGL_VERSION_1_0) && defined(_DEBUG)
1200 EGLint g = eglGetError();
1205 case EGL_NOT_INITIALIZED :
1206 os::Printer::log("Not Initialized", ELL_ERROR);
1208 case EGL_BAD_ACCESS:
1209 os::Printer::log("Bad Access", ELL_ERROR);
1212 os::Printer::log("Bad Alloc", ELL_ERROR);
1214 case EGL_BAD_ATTRIBUTE:
1215 os::Printer::log("Bad Attribute", ELL_ERROR);
1217 case EGL_BAD_CONTEXT:
1218 os::Printer::log("Bad Context", ELL_ERROR);
1220 case EGL_BAD_CONFIG:
1221 os::Printer::log("Bad Config", ELL_ERROR);
1223 case EGL_BAD_CURRENT_SURFACE:
1224 os::Printer::log("Bad Current Surface", ELL_ERROR);
1226 case EGL_BAD_DISPLAY:
1227 os::Printer::log("Bad Display", ELL_ERROR);
1229 case EGL_BAD_SURFACE:
1230 os::Printer::log("Bad Surface", ELL_ERROR);
1233 os::Printer::log("Bad Match", ELL_ERROR);
1235 case EGL_BAD_PARAMETER:
1236 os::Printer::log("Bad Parameter", ELL_ERROR);
1238 case EGL_BAD_NATIVE_PIXMAP:
1239 os::Printer::log("Bad Native Pixmap", ELL_ERROR);
1241 case EGL_BAD_NATIVE_WINDOW:
1242 os::Printer::log("Bad Native Window", ELL_ERROR);
1244 case EGL_CONTEXT_LOST:
1245 os::Printer::log("Context Lost", ELL_ERROR);
1255 void COpenGL3DriverBase::setRenderStates3DMode()
1257 if ( LockRenderStateMode )
1260 if (CurrentRenderMode != ERM_3D)
1262 // Reset Texture Stages
1263 CacheHandler->setBlend(false);
1264 CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1266 ResetRenderStates = true;
1269 if (ResetRenderStates || LastMaterial != Material)
1271 // unset old material
1273 // unset last 3d material
1274 if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive)
1276 MaterialRenderer2DActive->OnUnsetMaterial();
1277 MaterialRenderer2DActive = 0;
1279 else if (LastMaterial.MaterialType != Material.MaterialType &&
1280 static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1281 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1283 // set new material.
1284 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1285 MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial(
1286 Material, LastMaterial, ResetRenderStates, this);
1288 LastMaterial = Material;
1289 CacheHandler->correctCacheMaterial(LastMaterial);
1290 ResetRenderStates = false;
1293 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1294 MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD);
1296 CurrentRenderMode = ERM_3D;
1299 //! Can be called by an IMaterialRenderer to make its work easier.
1300 void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates)
1303 switch (material.ZBuffer)
1306 CacheHandler->setDepthTest(false);
1308 case ECFN_LESSEQUAL:
1309 CacheHandler->setDepthTest(true);
1310 CacheHandler->setDepthFunc(GL_LEQUAL);
1313 CacheHandler->setDepthTest(true);
1314 CacheHandler->setDepthFunc(GL_EQUAL);
1317 CacheHandler->setDepthTest(true);
1318 CacheHandler->setDepthFunc(GL_LESS);
1321 CacheHandler->setDepthTest(true);
1322 CacheHandler->setDepthFunc(GL_NOTEQUAL);
1324 case ECFN_GREATEREQUAL:
1325 CacheHandler->setDepthTest(true);
1326 CacheHandler->setDepthFunc(GL_GEQUAL);
1329 CacheHandler->setDepthTest(true);
1330 CacheHandler->setDepthFunc(GL_GREATER);
1333 CacheHandler->setDepthTest(true);
1334 CacheHandler->setDepthFunc(GL_ALWAYS);
1337 CacheHandler->setDepthTest(true);
1338 CacheHandler->setDepthFunc(GL_NEVER);
1345 if (getWriteZBuffer(material))
1347 CacheHandler->setDepthMask(true);
1351 CacheHandler->setDepthMask(false);
1354 // Back face culling
1355 if ((material.FrontfaceCulling) && (material.BackfaceCulling))
1357 CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK);
1358 CacheHandler->setCullFace(true);
1360 else if (material.BackfaceCulling)
1362 CacheHandler->setCullFaceFunc(GL_BACK);
1363 CacheHandler->setCullFace(true);
1365 else if (material.FrontfaceCulling)
1367 CacheHandler->setCullFaceFunc(GL_FRONT);
1368 CacheHandler->setCullFace(true);
1372 CacheHandler->setCullFace(false);
1376 CacheHandler->setColorMask(material.ColorMask);
1379 if (material.BlendOperation == EBO_NONE)
1380 CacheHandler->setBlend(false);
1383 CacheHandler->setBlend(true);
1385 switch (material.BlendOperation)
1388 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1391 CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT);
1393 case EBO_REVSUBTRACT:
1394 CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
1402 if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF?
1403 && material.MaterialType != EMT_ONETEXTURE_BLEND
1406 E_BLEND_FACTOR srcRGBFact = EBF_ZERO;
1407 E_BLEND_FACTOR dstRGBFact = EBF_ZERO;
1408 E_BLEND_FACTOR srcAlphaFact = EBF_ZERO;
1409 E_BLEND_FACTOR dstAlphaFact = EBF_ZERO;
1410 E_MODULATE_FUNC modulo = EMFN_MODULATE_1X;
1411 u32 alphaSource = 0;
1413 unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor);
1415 CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact),
1416 getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact));
1419 // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver.
1421 if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness)
1422 glLineWidth(core::clamp(static_cast<GLfloat>(material.Thickness), DimAliasedLine[0], DimAliasedLine[1]));
1425 if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing)
1427 if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1428 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1429 else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE)
1430 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1433 // Texture parameters
1434 setTextureRenderStates(material, resetAllRenderStates);
1437 //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call.
1438 void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates)
1440 // Set textures to TU/TIU and apply filters to them
1442 for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i)
1444 const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i];
1449 GLenum tmpTextureType = tmpTexture->getOpenGLTextureType();
1451 CacheHandler->setActiveTexture(GL_TEXTURE0 + i);
1453 if (resetAllRenderstates)
1454 tmpTexture->getStatesCache().IsCached = false;
1456 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1457 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter)
1459 glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER,
1460 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1462 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1463 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1466 if (material.UseMipMaps && tmpTexture->hasMipMaps())
1468 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1469 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus)
1471 glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1472 material.TextureLayer[i].TrilinearFilter ? GL_LINEAR_MIPMAP_LINEAR :
1473 material.TextureLayer[i].BilinearFilter ? GL_LINEAR_MIPMAP_NEAREST :
1474 GL_NEAREST_MIPMAP_NEAREST);
1476 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1477 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1478 tmpTexture->getStatesCache().MipMapStatus = true;
1483 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1484 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus)
1486 glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1487 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1489 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1490 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1491 tmpTexture->getStatesCache().MipMapStatus = false;
1495 #ifdef GL_EXT_texture_filter_anisotropic
1496 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] &&
1497 (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter))
1499 glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1500 material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1);
1502 tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter;
1506 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU)
1508 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU));
1509 tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU;
1512 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV)
1514 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV));
1515 tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV;
1518 tmpTexture->getStatesCache().IsCached = true;
1523 // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode.
1524 GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const
1529 case ETC_CLAMP_TO_EDGE:
1530 case ETC_CLAMP_TO_BORDER:
1531 return GL_CLAMP_TO_EDGE;
1540 //! sets the needed renderstates
1541 void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel)
1543 if ( LockRenderStateMode )
1546 COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture;
1548 if (CurrentRenderMode != ERM_2D)
1550 // unset last 3d material
1551 if (CurrentRenderMode == ERM_3D)
1553 if (static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1554 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1557 CurrentRenderMode = ERM_2D;
1559 else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer)
1561 MaterialRenderer2DActive->OnUnsetMaterial();
1564 MaterialRenderer2DActive = nextActiveRenderer;
1566 MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0);
1567 LastMaterial = Material;
1568 CacheHandler->correctCacheMaterial(LastMaterial);
1570 // no alphaChannel without texture
1571 alphaChannel &= texture;
1573 if (alphaChannel || alpha)
1575 CacheHandler->setBlend(true);
1576 CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1577 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1580 CacheHandler->setBlend(false);
1582 Material.setTexture(0, const_cast<COpenGL3Texture*>(CacheHandler->getTextureCache().get(0)));
1583 setTransform(ETS_TEXTURE_0, core::IdentityMatrix);
1587 if (OverrideMaterial2DEnabled)
1588 setTextureRenderStates(OverrideMaterial2D, false);
1590 setTextureRenderStates(InitMaterial2D, false);
1593 MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD);
1597 void COpenGL3DriverBase::chooseMaterial2D()
1599 if (!OverrideMaterial2DEnabled)
1600 Material = InitMaterial2D;
1602 if (OverrideMaterial2DEnabled)
1604 OverrideMaterial2D.Lighting=false;
1605 OverrideMaterial2D.ZWriteEnable=EZW_OFF;
1606 OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge
1607 OverrideMaterial2D.Lighting=false;
1609 Material = OverrideMaterial2D;
1614 //! \return Returns the name of the video driver.
1615 const wchar_t* COpenGL3DriverBase::getName() const
1617 return Name.c_str();
1620 void COpenGL3DriverBase::setViewPort(const core::rect<s32>& area)
1622 core::rect<s32> vp = area;
1623 core::rect<s32> rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
1624 vp.clipAgainst(rendert);
1626 if (vp.getHeight() > 0 && vp.getWidth() > 0)
1627 CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight());
1633 void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height)
1635 CacheHandler->setViewport(0, 0, width, height);
1636 ViewPort = core::recti(0, 0, width, height);
1640 //! Draws a 3d line.
1641 void COpenGL3DriverBase::draw3DLine(const core::vector3df& start,
1642 const core::vector3df& end, SColor color)
1644 setRenderStates3DMode();
1646 S3DVertex vertices[2];
1647 vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0);
1648 vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0);
1650 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1654 //! Only used by the internal engine. Used to notify the driver that
1655 //! the window was resized.
1656 void COpenGL3DriverBase::OnResize(const core::dimension2d<u32>& size)
1658 CNullDriver::OnResize(size);
1659 CacheHandler->setViewport(0, 0, size.Width, size.Height);
1660 Transformation3DChanged = true;
1664 //! Returns type of video driver
1665 E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const
1671 //! returns color format
1672 ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const
1678 //! Get a vertex shader constant index.
1679 s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name)
1681 return getPixelShaderConstantID(name);
1684 //! Get a pixel shader constant index.
1685 s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name)
1687 os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID().");
1691 //! Sets a vertex shader constant.
1692 void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1694 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1697 //! Sets a pixel shader constant.
1698 void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1700 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1703 //! Sets a constant for the vertex shader based on an index.
1704 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count)
1706 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1710 //! Int interface for the above.
1711 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count)
1713 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1717 bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count)
1719 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1723 //! Sets a constant for the pixel shader based on an index.
1724 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count)
1726 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1730 //! Int interface for the above.
1731 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count)
1733 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1737 bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count)
1739 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1743 //! Adds a new material renderer to the VideoDriver, using pixel and/or
1744 //! vertex shaders to render geometry.
1745 s32 COpenGL3DriverBase::addShaderMaterial(const c8* vertexShaderProgram,
1746 const c8* pixelShaderProgram,
1747 IShaderConstantSetCallBack* callback,
1748 E_MATERIAL_TYPE baseMaterial, s32 userData)
1750 os::Printer::log("No shader support.");
1755 //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
1756 s32 COpenGL3DriverBase::addHighLevelShaderMaterial(
1757 const c8* vertexShaderProgram,
1758 const c8* vertexShaderEntryPointName,
1759 E_VERTEX_SHADER_TYPE vsCompileTarget,
1760 const c8* pixelShaderProgram,
1761 const c8* pixelShaderEntryPointName,
1762 E_PIXEL_SHADER_TYPE psCompileTarget,
1763 const c8* geometryShaderProgram,
1764 const c8* geometryShaderEntryPointName,
1765 E_GEOMETRY_SHADER_TYPE gsCompileTarget,
1766 scene::E_PRIMITIVE_TYPE inType,
1767 scene::E_PRIMITIVE_TYPE outType,
1769 IShaderConstantSetCallBack* callback,
1770 E_MATERIAL_TYPE baseMaterial,
1774 COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer(
1775 this, nr, vertexShaderProgram,
1777 callback, baseMaterial, userData);
1783 //! Returns a pointer to the IVideoDriver interface. (Implementation for
1784 //! IMaterialRendererServices)
1785 IVideoDriver* COpenGL3DriverBase::getVideoDriver()
1791 //! Returns pointer to the IGPUProgrammingServices interface.
1792 IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices()
1797 ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d<u32>& size,
1798 const io::path& name, const ECOLOR_FORMAT format)
1800 //disable mip-mapping
1801 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1802 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1804 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this);
1805 addTexture(renderTargetTexture);
1806 renderTargetTexture->drop();
1808 //restore mip-mapping
1809 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1811 return renderTargetTexture;
1814 ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format)
1816 //disable mip-mapping
1817 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1818 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1820 bool supportForFBO = (Feature.ColorAttachment > 0);
1822 const core::dimension2d<u32> size(sideLen, sideLen);
1823 core::dimension2du destSize(size);
1827 destSize = core::dimension2d<u32>(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height));
1828 destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false);
1831 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this);
1832 addTexture(renderTargetTexture);
1833 renderTargetTexture->drop();
1835 //restore mip-mapping
1836 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1838 return renderTargetTexture;
1842 //! Returns the maximum amount of primitives
1843 u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const
1848 bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil)
1850 if (target && target->getDriverType() != getDriverType())
1852 os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR);
1856 core::dimension2d<u32> destRenderTargetSize(0, 0);
1860 COpenGL3RenderTarget* renderTarget = static_cast<COpenGL3RenderTarget*>(target);
1862 CacheHandler->setFBO(renderTarget->getBufferID());
1863 renderTarget->update();
1865 destRenderTargetSize = renderTarget->getSize();
1867 setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height);
1871 CacheHandler->setFBO(0);
1873 destRenderTargetSize = core::dimension2d<u32>(0, 0);
1875 setViewPortRaw(ScreenSize.Width, ScreenSize.Height);
1878 if (CurrentRenderTargetSize != destRenderTargetSize)
1880 CurrentRenderTargetSize = destRenderTargetSize;
1882 Transformation3DChanged = true;
1885 CurrentRenderTarget = target;
1887 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
1892 void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil)
1894 GLbitfield mask = 0;
1896 bool depthMask = false;
1898 CacheHandler->getColorMask(colorMask);
1899 CacheHandler->getDepthMask(depthMask);
1901 if (flag & ECBF_COLOR)
1903 CacheHandler->setColorMask(ECP_ALL);
1905 const f32 inv = 1.0f / 255.0f;
1906 glClearColor(color.getRed() * inv, color.getGreen() * inv,
1907 color.getBlue() * inv, color.getAlpha() * inv);
1909 mask |= GL_COLOR_BUFFER_BIT;
1912 if (flag & ECBF_DEPTH)
1914 CacheHandler->setDepthMask(true);
1915 glClearDepthf(depth);
1916 mask |= GL_DEPTH_BUFFER_BIT;
1919 if (flag & ECBF_STENCIL)
1921 glClearStencil(stencil);
1922 mask |= GL_STENCIL_BUFFER_BIT;
1928 CacheHandler->setColorMask(colorMask);
1929 CacheHandler->setDepthMask(depthMask);
1933 //! Returns an image created from the last rendered frame.
1934 // We want to read the front buffer to get the latest render finished.
1935 // This is not possible under ogl-es, though, so one has to call this method
1936 // outside of the render loop only.
1937 IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target)
1939 if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS)
1942 GLint internalformat = GL_RGBA;
1943 GLint type = GL_UNSIGNED_BYTE;
1945 // glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat);
1946 // glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type);
1947 // there's a format we don't support ATM
1948 if (GL_UNSIGNED_SHORT_4_4_4_4 == type)
1950 internalformat = GL_RGBA;
1951 type = GL_UNSIGNED_BYTE;
1955 IImage* newImage = 0;
1956 if (GL_RGBA == internalformat)
1958 if (GL_UNSIGNED_BYTE == type)
1959 newImage = new CImage(ECF_A8R8G8B8, ScreenSize);
1961 newImage = new CImage(ECF_A1R5G5B5, ScreenSize);
1965 if (GL_UNSIGNED_BYTE == type)
1966 newImage = new CImage(ECF_R8G8B8, ScreenSize);
1968 newImage = new CImage(ECF_R5G6B5, ScreenSize);
1974 u8* pixels = static_cast<u8*>(newImage->getData());
1981 glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels);
1982 testGLError(__LINE__);
1984 // opengl images are horizontally flipped, so we have to fix that here.
1985 const s32 pitch = newImage->getPitch();
1986 u8* p2 = pixels + (ScreenSize.Height - 1) * pitch;
1987 u8* tmpBuffer = new u8[pitch];
1988 for (u32 i = 0; i < ScreenSize.Height; i += 2)
1990 memcpy(tmpBuffer, pixels, pitch);
1991 memcpy(pixels, p2, pitch);
1992 memcpy(p2, tmpBuffer, pitch);
1996 delete [] tmpBuffer;
1998 // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA)
1999 if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type)
2001 pixels = static_cast<u8*>(newImage->getData());
2002 for (u32 i = 0; i < ScreenSize.Height; i++)
2004 for (u32 j = 0; j < ScreenSize.Width; j++)
2006 u32 c = *(u32*) (pixels + 4 * j);
2007 *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) |
2008 ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
2014 if (testGLError(__LINE__))
2019 testGLError(__LINE__);
2023 void COpenGL3DriverBase::removeTexture(ITexture* texture)
2025 CacheHandler->getTextureCache().remove(texture);
2026 CNullDriver::removeTexture(texture);
2029 //! Set/unset a clipping plane.
2030 bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
2032 if (index >= UserClipPlane.size())
2033 UserClipPlane.push_back(SUserClipPlane());
2035 UserClipPlane[index].Plane = plane;
2036 UserClipPlane[index].Enabled = enable;
2040 //! Enable/disable a clipping plane.
2041 void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable)
2043 UserClipPlane[index].Enabled = enable;
2046 //! Get the ClipPlane Count
2047 u32 COpenGL3DriverBase::getClipPlaneCount() const
2049 return UserClipPlane.size();
2052 const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const
2054 if (index < UserClipPlane.size())
2055 return UserClipPlane[index].Plane;
2058 _IRR_DEBUG_BREAK_IF(true) // invalid index
2059 static const core::plane3df dummy;
2064 core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const
2066 return core::dimension2du(MaxTextureSize, MaxTextureSize);
2069 GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const
2071 static GLenum const blendTable[] =
2076 GL_ONE_MINUS_DST_COLOR,
2078 GL_ONE_MINUS_SRC_COLOR,
2080 GL_ONE_MINUS_SRC_ALPHA,
2082 GL_ONE_MINUS_DST_ALPHA,
2083 GL_SRC_ALPHA_SATURATE
2086 return blendTable[factor];
2089 bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat,
2090 GLenum& pixelType, void(**converter)(const void*, s32, void*)) const
2092 bool supported = false;
2093 pixelFormat = GL_RGBA;
2094 pixelType = GL_UNSIGNED_BYTE;
2101 pixelFormat = GL_RGBA;
2102 pixelType = GL_UNSIGNED_SHORT_5_5_5_1;
2103 *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1;
2107 pixelFormat = GL_RGB;
2108 pixelType = GL_UNSIGNED_SHORT_5_6_5;
2112 pixelFormat = GL_RGB;
2113 pixelType = GL_UNSIGNED_BYTE;
2117 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) ||
2118 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) ||
2119 queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888))
2121 pixelFormat = GL_BGRA;
2125 pixelFormat = GL_RGBA;
2126 *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8;
2128 pixelType = GL_UNSIGNED_BYTE;
2130 #ifdef GL_EXT_texture_compression_s3tc
2133 pixelFormat = GL_RGBA;
2134 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
2139 pixelFormat = GL_RGBA;
2140 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
2145 pixelFormat = GL_RGBA;
2146 pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
2149 #ifdef GL_OES_compressed_ETC1_RGB8_texture
2152 pixelFormat = GL_RGB;
2153 pixelType = GL_ETC1_RGB8_OES;
2156 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2159 pixelFormat = GL_RGB;
2160 pixelType = GL_COMPRESSED_RGB8_ETC2;
2163 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2166 pixelFormat = GL_RGBA;
2167 pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC;
2172 pixelFormat = GL_DEPTH_COMPONENT;
2173 pixelType = GL_UNSIGNED_SHORT;
2176 #if defined(GL_OES_depth32)
2177 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32))
2180 pixelFormat = GL_DEPTH_COMPONENT;
2181 pixelType = GL_UNSIGNED_INT;
2186 #ifdef GL_OES_packed_depth_stencil
2187 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil))
2190 pixelFormat = GL_DEPTH_STENCIL_OES;
2191 pixelType = GL_UNSIGNED_INT_24_8_OES;
2196 #if defined(GL_EXT_texture_rg)
2197 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2200 pixelFormat = GL_RED_EXT;
2201 pixelType = GL_UNSIGNED_BYTE;
2206 #if defined(GL_EXT_texture_rg)
2207 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2210 pixelFormat = GL_RG_EXT;
2211 pixelType = GL_UNSIGNED_BYTE;
2220 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2221 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2222 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2226 pixelFormat = GL_RED_EXT;
2227 pixelType = GL_HALF_FLOAT_OES ;
2232 #if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg)
2233 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2234 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)
2238 pixelFormat = GL_RG_EXT;
2239 pixelType = GL_HALF_FLOAT_OES ;
2243 case ECF_A16B16G16R16F:
2244 #if defined(GL_OES_texture_half_float)
2245 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2248 pixelFormat = GL_RGBA;
2249 pixelType = GL_HALF_FLOAT_OES ;
2254 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2255 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2256 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2260 pixelFormat = GL_RED_EXT;
2261 pixelType = GL_FLOAT;
2266 #if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg)
2267 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)
2268 && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float)
2272 pixelFormat = GL_RG_EXT;
2273 pixelType = GL_FLOAT;
2277 case ECF_A32B32G32R32F:
2278 #if defined(GL_OES_texture_float)
2279 if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2282 pixelFormat = GL_RGBA;
2283 pixelType = GL_FLOAT ;
2291 // ES 2.0 says internalFormat must match pixelFormat (chapter 3.7.1 in Spec).
2292 // Doesn't mention if "match" means "equal" or some other way of matching, but
2293 // some bug on Emscripten and browsing discussions by others lead me to believe
2294 // it means they have to be equal. Note that this was different in OpenGL.
2295 internalFormat = pixelFormat;
2297 #ifdef _IRR_IOS_PLATFORM_
2298 if (internalFormat == GL_BGRA)
2299 internalFormat = GL_RGBA;
2305 bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const
2307 GLint dummyInternalFormat;
2308 GLenum dummyPixelFormat;
2309 GLenum dummyPixelType;
2310 void (*dummyConverter)(const void*, s32, void*);
2311 return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter);
2314 bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const
2316 return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation();
2319 const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const
2324 COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const
2326 return CacheHandler;