]> git.lizzy.rs Git - irrlicht.git/blob - source/Irrlicht/OpenGL/Driver.cpp
6dec58f100c1bc9e70258e66e36fea0e3d9ab8ae
[irrlicht.git] / source / Irrlicht / OpenGL / Driver.cpp
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
6
7 #include "Driver.h"
8 #include <cassert>
9 #include "CNullDriver.h"
10 #include "IContextManager.h"
11
12 #include "COpenGLCoreTexture.h"
13 #include "COpenGLCoreRenderTarget.h"
14 #include "COpenGLCoreCacheHandler.h"
15
16 #include "MaterialRenderer.h"
17 #include "FixedPipelineRenderer.h"
18 #include "Renderer2D.h"
19
20 #include "EVertexAttributes.h"
21 #include "CImage.h"
22 #include "os.h"
23
24 #ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_
25 #include "android_native_app_glue.h"
26 #endif
27
28 #include "mt_opengl.h"
29
30 namespace irr
31 {
32 namespace video
33 {
34         struct VertexAttribute {
35                 enum class Mode {
36                         Regular,
37                         Normalized,
38                         Integral,
39                 };
40                 int Index;
41                 int ComponentCount;
42                 GLenum ComponentType;
43                 Mode mode;
44                 int Offset;
45         };
46
47         struct VertexType {
48                 int VertexSize;
49                 int AttributeCount;
50                 VertexAttribute Attributes[];
51
52                 VertexType(const VertexType &) = delete;
53                 VertexType &operator= (const VertexType &) = delete;
54         };
55
56         static const VertexAttribute *begin(const VertexType &type)
57         {
58                 return type.Attributes;
59         }
60
61         static const VertexAttribute *end(const VertexType &type)
62         {
63                 return type.Attributes + type.AttributeCount;
64         }
65
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)},
72                 },
73         };
74
75 #pragma GCC diagnostic push
76 #pragma GCC diagnostic ignored "-Winvalid-offsetof"
77
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)},
85                 },
86         };
87
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)},
96                 },
97         };
98
99 #pragma GCC diagnostic pop
100
101         static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type)
102         {
103                 switch (type) {
104                         case EVT_STANDARD: return vtStandard;
105                         case EVT_2TCOORDS: return vt2TCoords;
106                         case EVT_TANGENTS: return vtTangents;
107                         default: assert(false);
108                 }
109         }
110
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)},
116                 },
117         };
118
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)},
123                 },
124         };
125
126
127 void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
128 {
129         ((COpenGL3DriverBase *)userParam)->debugCb(source, type, id, severity, length, message);
130 }
131
132 void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message)
133 {
134         printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message);
135 }
136
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)
144 {
145 #ifdef _DEBUG
146         setDebugName("Driver");
147 #endif
148
149         if (!ContextManager)
150                 return;
151
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);
159         initQuadsIndices();
160 }
161
162 COpenGL3DriverBase::~COpenGL3DriverBase()
163 {
164         deleteMaterialRenders();
165
166         CacheHandler->getTextureCache().clear();
167
168         removeAllRenderTargets();
169         deleteAllTextures();
170         removeAllOcclusionQueries();
171         removeAllHardwareBuffers();
172
173         delete MaterialRenderer2DTexture;
174         delete MaterialRenderer2DNoTexture;
175         delete CacheHandler;
176
177         if (ContextManager)
178         {
179                 ContextManager->destroyContext();
180                 ContextManager->destroySurface();
181                 ContextManager->terminate();
182                 ContextManager->drop();
183         }
184 }
185
186         void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count)
187         {
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);
197                 }
198         }
199
200         bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer)
201         {
202                 Name = glGetString(GL_VERSION);
203                 printVersion();
204
205                 // print renderer information
206                 VendorName = glGetString(GL_VENDOR);
207                 os::Printer::log(VendorName.c_str(), ELL_INFORMATION);
208
209                 // load extensions
210                 initExtensions();
211
212                 // reset cache handler
213                 delete CacheHandler;
214                 CacheHandler = new COpenGL3CacheHandler(this);
215
216                 StencilBuffer = stencilBuffer;
217
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);
230
231                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
232
233                 UserClipPlane.reallocate(0);
234
235                 for (s32 i = 0; i < ETS_COUNT; ++i)
236                         setTransform(static_cast<E_TRANSFORMATION_STATE>(i), core::IdentityMatrix);
237
238                 setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f));
239                 glClearDepthf(1.0f);
240
241                 glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
242                 glFrontFace(GL_CW);
243
244                 // create material renderers
245                 createMaterialRenderers();
246
247                 // set the renderstates
248                 setRenderStates3DMode();
249
250                 // set fog mode
251                 setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog);
252
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));
255
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;
259
260                 testGLError(__LINE__);
261
262                 return true;
263         }
264
265         void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData)
266         {
267                 io::path vsPath(OGLES2ShaderPath);
268                 vsPath += vertexShaderName;
269
270                 io::path fsPath(OGLES2ShaderPath);
271                 fsPath += fragmentShaderName;
272
273                 *vertexShaderData = 0;
274                 *fragmentShaderData = 0;
275
276                 io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath);
277                 if ( !vsFile )
278                 {
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);
283                         return;
284                 }
285
286                 io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath);
287                 if ( !fsFile )
288                 {
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);
293                         return;
294                 }
295
296                 long size = vsFile->getSize();
297                 if (size)
298                 {
299                         *vertexShaderData = new c8[size+1];
300                         vsFile->read(*vertexShaderData, size);
301                         (*vertexShaderData)[size] = 0;
302                 }
303
304                 size = fsFile->getSize();
305                 if (size)
306                 {
307                         // if both handles are the same we must reset the file
308                         if (fsFile == vsFile)
309                                 fsFile->seek(0);
310
311                         *fragmentShaderData = new c8[size+1];
312                         fsFile->read(*fragmentShaderData, size);
313                         (*fragmentShaderData)[size] = 0;
314                 }
315
316                 vsFile->drop();
317                 fsFile->drop();
318         }
319
320         void COpenGL3DriverBase::addDummyMaterial(E_MATERIAL_TYPE type) {
321                 auto index = addMaterialRenderer(getMaterialRenderer(EMT_SOLID), "DUMMY");
322                 assert(index == type);
323         }
324
325         void COpenGL3DriverBase::createMaterialRenderers()
326         {
327                 // Create callbacks.
328
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();
334
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.
338
339                 const core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh";
340
341                 // EMT_SOLID
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);
345
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);
358
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);
363
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);
368
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);
373
374                 addDummyMaterial(EMT_TRANSPARENT_REFLECTION_2_LAYER);
375
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);
380
381                 // Drop callbacks.
382
383                 SolidCB->drop();
384                 TransparentAlphaChannelCB->drop();
385                 TransparentAlphaChannelRefCB->drop();
386                 TransparentVertexAlphaCB->drop();
387                 OneTextureBlendCB->drop();
388
389                 // Create 2D material renderers
390
391                 c8* vs2DData = 0;
392                 c8* fs2DData = 0;
393                 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData);
394                 MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true);
395                 delete[] vs2DData;
396                 delete[] fs2DData;
397                 vs2DData = 0;
398                 fs2DData = 0;
399
400                 loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData);
401                 MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false);
402                 delete[] vs2DData;
403                 delete[] fs2DData;
404         }
405
406         bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture)
407         {
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);
410         }
411
412         bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
413         {
414                 CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect);
415
416                 if (ContextManager)
417                         ContextManager->activateContext(videoData, true);
418
419                 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
420
421                 return true;
422         }
423
424         bool COpenGL3DriverBase::endScene()
425         {
426                 CNullDriver::endScene();
427
428                 glFlush();
429
430                 if (ContextManager)
431                         return ContextManager->swapBuffers();
432
433                 return false;
434         }
435
436
437         //! Returns the transformation set by setTransform
438         const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const
439         {
440                 return Matrices[state];
441         }
442
443
444         //! sets transformation
445         void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
446         {
447                 Matrices[state] = mat;
448                 Transformation3DChanged = true;
449         }
450
451
452         bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
453         {
454                 if (!HWBuffer)
455                         return false;
456
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);
462
463                 const void *buffer = vertices;
464                 size_t bufferSize = vertexSize * vertexCount;
465
466                 //get or create buffer
467                 bool newBuffer = false;
468                 if (!HWBuffer->vbo_verticesID)
469                 {
470                         glGenBuffers(1, &HWBuffer->vbo_verticesID);
471                         if (!HWBuffer->vbo_verticesID) return false;
472                         newBuffer = true;
473                 }
474                 else if (HWBuffer->vbo_verticesSize < bufferSize)
475                 {
476                         newBuffer = true;
477                 }
478
479                 glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
480
481                 // copy data to graphics card
482                 if (!newBuffer)
483                         glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer);
484                 else
485                 {
486                         HWBuffer->vbo_verticesSize = bufferSize;
487
488                         if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC)
489                                 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW);
490                         else
491                                 glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW);
492                 }
493
494                 glBindBuffer(GL_ARRAY_BUFFER, 0);
495
496                 return (!testGLError(__LINE__));
497         }
498
499
500         bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer)
501         {
502                 if (!HWBuffer)
503                         return false;
504
505                 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
506
507                 const void* indices = mb->getIndices();
508                 u32 indexCount = mb->getIndexCount();
509
510                 GLenum indexSize;
511                 switch (mb->getIndexType())
512                 {
513                         case(EIT_16BIT):
514                         {
515                                 indexSize = sizeof(u16);
516                                 break;
517                         }
518                         case(EIT_32BIT):
519                         {
520                                 indexSize = sizeof(u32);
521                                 break;
522                         }
523                         default:
524                         {
525                                 return false;
526                         }
527                 }
528
529                 //get or create buffer
530                 bool newBuffer = false;
531                 if (!HWBuffer->vbo_indicesID)
532                 {
533                         glGenBuffers(1, &HWBuffer->vbo_indicesID);
534                         if (!HWBuffer->vbo_indicesID) return false;
535                         newBuffer = true;
536                 }
537                 else if (HWBuffer->vbo_indicesSize < indexCount*indexSize)
538                 {
539                         newBuffer = true;
540                 }
541
542                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
543
544                 // copy data to graphics card
545                 if (!newBuffer)
546                         glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices);
547                 else
548                 {
549                         HWBuffer->vbo_indicesSize = indexCount * indexSize;
550
551                         if (HWBuffer->Mapped_Index == scene::EHM_STATIC)
552                                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW);
553                         else
554                                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW);
555                 }
556
557                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
558
559                 return (!testGLError(__LINE__));
560         }
561
562
563         //! updates hardware buffer if needed
564         bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer)
565         {
566                 if (!HWBuffer)
567                         return false;
568
569                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
570                 {
571                         if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex()
572                                 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_verticesID)
573                         {
574
575                                 HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex();
576
577                                 if (!updateVertexHardwareBuffer(static_cast<SHWBufferLink_opengl*>(HWBuffer)))
578                                         return false;
579                         }
580                 }
581
582                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
583                 {
584                         if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index()
585                                 || !static_cast<SHWBufferLink_opengl*>(HWBuffer)->vbo_indicesID)
586                         {
587
588                                 HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index();
589
590                                 if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer))
591                                         return false;
592                         }
593                 }
594
595                 return true;
596         }
597
598
599         //! Create hardware buffer from meshbuffer
600         COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb)
601         {
602                 if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER))
603                         return 0;
604
605                 SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb);
606
607                 //add to map
608                 HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer);
609
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;
618
619                 if (!updateHardwareBuffer(HWBuffer))
620                 {
621                         deleteHardwareBuffer(HWBuffer);
622                         return 0;
623                 }
624
625                 return HWBuffer;
626         }
627
628
629         void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer)
630         {
631                 if (!_HWBuffer)
632                         return;
633
634                 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
635                 if (HWBuffer->vbo_verticesID)
636                 {
637                         glDeleteBuffers(1, &HWBuffer->vbo_verticesID);
638                         HWBuffer->vbo_verticesID = 0;
639                 }
640                 if (HWBuffer->vbo_indicesID)
641                 {
642                         glDeleteBuffers(1, &HWBuffer->vbo_indicesID);
643                         HWBuffer->vbo_indicesID = 0;
644                 }
645
646                 CNullDriver::deleteHardwareBuffer(_HWBuffer);
647         }
648
649
650         //! Draw hardware buffer
651         void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer)
652         {
653                 if (!_HWBuffer)
654                         return;
655
656                 SHWBufferLink_opengl *HWBuffer = static_cast<SHWBufferLink_opengl*>(_HWBuffer);
657
658                 updateHardwareBuffer(HWBuffer); //check if update is needed
659
660                 const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer;
661                 const void *vertices = mb->getVertices();
662                 const void *indexList = mb->getIndices();
663
664                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
665                 {
666                         glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID);
667                         vertices = 0;
668                 }
669
670                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
671                 {
672                         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID);
673                         indexList = 0;
674                 }
675
676
677                 drawVertexPrimitiveList(vertices, mb->getVertexCount(),
678                                 indexList, mb->getPrimitiveCount(),
679                                 mb->getVertexType(), mb->getPrimitiveType(),
680                                 mb->getIndexType());
681
682                 if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER)
683                         glBindBuffer(GL_ARRAY_BUFFER, 0);
684
685                 if (HWBuffer->Mapped_Index != scene::EHM_NEVER)
686                         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
687         }
688
689
690         IRenderTarget* COpenGL3DriverBase::addRenderTarget()
691         {
692                 COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this);
693                 RenderTargets.push_back(renderTarget);
694
695                 return renderTarget;
696         }
697
698
699         // small helper function to create vertex buffer object adress offsets
700         static inline u8* buffer_offset(const long offset)
701         {
702                 return ((u8*)0 + offset);
703         }
704
705
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)
710         {
711                 if (!primitiveCount || !vertexCount)
712                         return;
713
714                 if (!checkPrimitiveCount(primitiveCount))
715                         return;
716
717                 CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType);
718
719                 setRenderStates3DMode();
720
721                 auto &vTypeDesc = getVertexTypeDescription(vType);
722                 beginDraw(vTypeDesc, reinterpret_cast<uintptr_t>(vertices));
723                 GLenum indexSize = 0;
724
725                 switch (iType)
726                 {
727                         case(EIT_16BIT):
728                         {
729                                 indexSize = GL_UNSIGNED_SHORT;
730                                 break;
731                         }
732                         case(EIT_32BIT):
733                         {
734 #ifdef GL_OES_element_index_uint
735 #ifndef GL_UNSIGNED_INT
736 #define GL_UNSIGNED_INT 0x1405
737 #endif
738                                 if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint])
739                                         indexSize = GL_UNSIGNED_INT;
740                                 else
741 #endif
742                                         indexSize = GL_UNSIGNED_SHORT;
743                                 break;
744                         }
745                 }
746
747                 switch (pType)
748                 {
749                         case scene::EPT_POINTS:
750                         case scene::EPT_POINT_SPRITES:
751                                 glDrawArrays(GL_POINTS, 0, primitiveCount);
752                                 break;
753                         case scene::EPT_LINE_STRIP:
754                                 glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList);
755                                 break;
756                         case scene::EPT_LINE_LOOP:
757                                 glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList);
758                                 break;
759                         case scene::EPT_LINES:
760                                 glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList);
761                                 break;
762                         case scene::EPT_TRIANGLE_STRIP:
763                                 glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList);
764                                 break;
765                         case scene::EPT_TRIANGLE_FAN:
766                                 glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList);
767                                 break;
768                         case scene::EPT_TRIANGLES:
769                                 glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList);
770                                 break;
771                         default:
772                                 break;
773                 }
774
775                 endDraw(vTypeDesc);
776         }
777
778
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)
782         {
783                 if (!texture)
784                         return;
785
786                 if (!sourceRect.isValid())
787                         return;
788
789                 SColor colors[4] = {color, color, color, color};
790                 draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture);
791         }
792
793
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)
797         {
798                 if (!texture)
799                         return;
800
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);
811
812                 const video::SColor temp[4] =
813                 {
814                         0xFFFFFFFF,
815                         0xFFFFFFFF,
816                         0xFFFFFFFF,
817                         0xFFFFFFFF
818                 };
819
820                 const video::SColor* const useColor = colors ? colors : temp;
821
822                 chooseMaterial2D();
823                 if (!setMaterialTexture(0, texture ))
824                         return;
825
826                 setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 ||
827                         useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255,
828                         true, useAlphaChannelOfTexture);
829
830                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
831
832                 if (clipRect)
833                 {
834                         if (!clipRect->isValid())
835                                 return;
836
837                         glEnable(GL_SCISSOR_TEST);
838                         glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
839                                 clipRect->getWidth(), clipRect->getHeight());
840                 }
841
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;
846
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);
852
853                 drawQuad(vt2DImage, vertices);
854
855                 if (clipRect)
856                         glDisable(GL_SCISSOR_TEST);
857
858                 testGLError(__LINE__);
859         }
860
861         void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip)
862         {
863                 if (!texture)
864                         return;
865
866                 chooseMaterial2D();
867                 if (!setMaterialTexture(0, texture ))
868                         return;
869
870                 setRenderStates2DMode(false, true, true);
871
872                 S3DVertex quad2DVertices[4];
873
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);
878
879                 f32 modificator = (flip) ? 1.f : 0.f;
880
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);
885
886                 quad2DVertices[0].Color = SColor(0xFFFFFFFF);
887                 quad2DVertices[1].Color = SColor(0xFFFFFFFF);
888                 quad2DVertices[2].Color = SColor(0xFFFFFFFF);
889                 quad2DVertices[3].Color = SColor(0xFFFFFFFF);
890
891                 drawQuad(vt2DImage, quad2DVertices);
892         }
893
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)
899         {
900                 if (!texture)
901                         return;
902
903                 chooseMaterial2D();
904                 if (!setMaterialTexture(0, texture))
905                         return;
906
907                 setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture);
908
909                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
910
911                 if (clipRect)
912                 {
913                         if (!clipRect->isValid())
914                                 return;
915
916                         glEnable(GL_SCISSOR_TEST);
917                         glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
918                                         clipRect->getWidth(), clipRect->getHeight());
919                 }
920
921                 const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size());
922                 assert(6 * std::size_t(drawCount) <= QuadsIndices.size());
923
924                 core::array<S3DVertex> vtx(drawCount * 4);
925
926                 for (u32 i = 0; i < drawCount; i++)
927                 {
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());
932
933                         // now draw it.
934
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);
940
941                         const core::rect<s32> poss(targetPos, sourceSize);
942
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;
947
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));
960                 }
961
962                 drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), QuadsIndices.data(), 6 * drawCount);
963
964                 if (clipRect)
965                         glDisable(GL_SCISSOR_TEST);
966         }
967
968
969         //! draw a 2d rectangle
970         void COpenGL3DriverBase::draw2DRectangle(SColor color,
971                         const core::rect<s32>& position,
972                         const core::rect<s32>* clip)
973         {
974                 chooseMaterial2D();
975                 setMaterialTexture(0, 0);
976
977                 setRenderStates2DMode(color.getAlpha() < 255, false, false);
978
979                 core::rect<s32> pos = position;
980
981                 if (clip)
982                         pos.clipAgainst(*clip);
983
984                 if (!pos.isValid())
985                         return;
986
987                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
988
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;
993
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);
999
1000                 drawQuad(vtPrimitive, vertices);
1001         }
1002
1003
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)
1009         {
1010                 core::rect<s32> pos = position;
1011
1012                 if (clip)
1013                         pos.clipAgainst(*clip);
1014
1015                 if (!pos.isValid())
1016                         return;
1017
1018                 chooseMaterial2D();
1019                 setMaterialTexture(0, 0);
1020
1021                 setRenderStates2DMode(colorLeftUp.getAlpha() < 255 ||
1022                                 colorRightUp.getAlpha() < 255 ||
1023                                 colorLeftDown.getAlpha() < 255 ||
1024                                 colorRightDown.getAlpha() < 255, false, false);
1025
1026                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1027
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;
1032
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);
1038
1039                 drawQuad(vtPrimitive, vertices);
1040         }
1041
1042
1043         //! Draws a 2d line.
1044         void COpenGL3DriverBase::draw2DLine(const core::position2d<s32>& start,
1045                         const core::position2d<s32>& end, SColor color)
1046         {
1047                 if (start==end)
1048                         drawPixel(start.X, start.Y, color);
1049                 else
1050                 {
1051                         chooseMaterial2D();
1052                         setMaterialTexture(0, 0);
1053
1054                         setRenderStates2DMode(color.getAlpha() < 255, false, false);
1055
1056                         const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1057
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;
1062
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);
1066
1067                         drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1068                 }
1069         }
1070
1071
1072         //! Draws a pixel
1073         void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color)
1074         {
1075                 const core::dimension2d<u32>& renderTargetSize = getCurrentRenderTargetSize();
1076                 if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height)
1077                         return;
1078
1079                 chooseMaterial2D();
1080                 setMaterialTexture(0, 0);
1081
1082                 setRenderStates2DMode(color.getAlpha() < 255, false, false);
1083
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;
1086
1087                 S3DVertex vertices[1];
1088                 vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0);
1089
1090                 drawArrays(GL_POINTS, vtPrimitive, vertices, 1);
1091         }
1092
1093         void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4])
1094         {
1095                 drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4);
1096         }
1097
1098         void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount)
1099         {
1100                 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1101                 glDrawArrays(primitiveType, 0, vertexCount);
1102                 endDraw(vertexType);
1103         }
1104
1105         void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount)
1106         {
1107                 beginDraw(vertexType, reinterpret_cast<uintptr_t>(vertices));
1108                 glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, indices);
1109                 endDraw(vertexType);
1110         }
1111
1112         void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase)
1113         {
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;
1120                         }
1121                 }
1122         }
1123
1124         void COpenGL3DriverBase::endDraw(const VertexType &vertexType)
1125         {
1126                 for (auto attr: vertexType)
1127                         glDisableVertexAttribArray(attr.Index);
1128         }
1129
1130         ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image)
1131         {
1132                 core::array<IImage*> imageArray(1);
1133                 imageArray.push_back(image);
1134
1135                 COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this);
1136
1137                 return texture;
1138         }
1139
1140         ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array<IImage*>& image)
1141         {
1142                 COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this);
1143
1144                 return texture;
1145         }
1146
1147         //! Sets a material.
1148         void COpenGL3DriverBase::setMaterial(const SMaterial& material)
1149         {
1150                 Material = material;
1151                 OverrideMaterial.apply(Material);
1152
1153                 for (u32 i = 0; i < Feature.MaxTextureUnits; ++i)
1154                 {
1155                         CacheHandler->getTextureCache().set(i, material.getTexture(i));
1156                         setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i));
1157                 }
1158         }
1159
1160         //! prints error if an error happened.
1161         bool COpenGL3DriverBase::testGLError(int code)
1162         {
1163 #ifdef _DEBUG
1164                 GLenum g = glGetError();
1165                 switch (g)
1166                 {
1167                         case GL_NO_ERROR:
1168                                 return false;
1169                         case GL_INVALID_ENUM:
1170                                 os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR);
1171                                 break;
1172                         case GL_INVALID_VALUE:
1173                                 os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR);
1174                                 break;
1175                         case GL_INVALID_OPERATION:
1176                                 os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR);
1177                                 break;
1178                         case GL_OUT_OF_MEMORY:
1179                                 os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR);
1180                                 break;
1181                 };
1182                 return true;
1183 #else
1184                 return false;
1185 #endif
1186         }
1187
1188         //! prints error if an error happened.
1189         bool COpenGL3DriverBase::testEGLError()
1190         {
1191 #if defined(EGL_VERSION_1_0) && defined(_DEBUG)
1192                 EGLint g = eglGetError();
1193                 switch (g)
1194                 {
1195                         case EGL_SUCCESS:
1196                                 return false;
1197                         case EGL_NOT_INITIALIZED :
1198                                 os::Printer::log("Not Initialized", ELL_ERROR);
1199                                 break;
1200                         case EGL_BAD_ACCESS:
1201                                 os::Printer::log("Bad Access", ELL_ERROR);
1202                                 break;
1203                         case EGL_BAD_ALLOC:
1204                                 os::Printer::log("Bad Alloc", ELL_ERROR);
1205                                 break;
1206                         case EGL_BAD_ATTRIBUTE:
1207                                 os::Printer::log("Bad Attribute", ELL_ERROR);
1208                                 break;
1209                         case EGL_BAD_CONTEXT:
1210                                 os::Printer::log("Bad Context", ELL_ERROR);
1211                                 break;
1212                         case EGL_BAD_CONFIG:
1213                                 os::Printer::log("Bad Config", ELL_ERROR);
1214                                 break;
1215                         case EGL_BAD_CURRENT_SURFACE:
1216                                 os::Printer::log("Bad Current Surface", ELL_ERROR);
1217                                 break;
1218                         case EGL_BAD_DISPLAY:
1219                                 os::Printer::log("Bad Display", ELL_ERROR);
1220                                 break;
1221                         case EGL_BAD_SURFACE:
1222                                 os::Printer::log("Bad Surface", ELL_ERROR);
1223                                 break;
1224                         case EGL_BAD_MATCH:
1225                                 os::Printer::log("Bad Match", ELL_ERROR);
1226                                 break;
1227                         case EGL_BAD_PARAMETER:
1228                                 os::Printer::log("Bad Parameter", ELL_ERROR);
1229                                 break;
1230                         case EGL_BAD_NATIVE_PIXMAP:
1231                                 os::Printer::log("Bad Native Pixmap", ELL_ERROR);
1232                                 break;
1233                         case EGL_BAD_NATIVE_WINDOW:
1234                                 os::Printer::log("Bad Native Window", ELL_ERROR);
1235                                 break;
1236                         case EGL_CONTEXT_LOST:
1237                                 os::Printer::log("Context Lost", ELL_ERROR);
1238                                 break;
1239                 };
1240                 return true;
1241 #else
1242                 return false;
1243 #endif
1244         }
1245
1246
1247         void COpenGL3DriverBase::setRenderStates3DMode()
1248         {
1249                 if ( LockRenderStateMode )
1250                         return;
1251
1252                 if (CurrentRenderMode != ERM_3D)
1253                 {
1254                         // Reset Texture Stages
1255                         CacheHandler->setBlend(false);
1256                         CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1257
1258                         ResetRenderStates = true;
1259                 }
1260
1261                 if (ResetRenderStates || LastMaterial != Material)
1262                 {
1263                         // unset old material
1264
1265                         // unset last 3d material
1266                         if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive)
1267                         {
1268                                 MaterialRenderer2DActive->OnUnsetMaterial();
1269                                 MaterialRenderer2DActive = 0;
1270                         }
1271                         else if (LastMaterial.MaterialType != Material.MaterialType &&
1272                                         static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1273                                 MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1274
1275                         // set new material.
1276                         if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1277                                 MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial(
1278                                         Material, LastMaterial, ResetRenderStates, this);
1279
1280                         LastMaterial = Material;
1281                         CacheHandler->correctCacheMaterial(LastMaterial);
1282                         ResetRenderStates = false;
1283                 }
1284
1285                 if (static_cast<u32>(Material.MaterialType) < MaterialRenderers.size())
1286                         MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD);
1287
1288                 CurrentRenderMode = ERM_3D;
1289         }
1290
1291         //! Can be called by an IMaterialRenderer to make its work easier.
1292         void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates)
1293         {
1294                 // ZBuffer
1295                 switch (material.ZBuffer)
1296                 {
1297                         case ECFN_DISABLED:
1298                                 CacheHandler->setDepthTest(false);
1299                                 break;
1300                         case ECFN_LESSEQUAL:
1301                                 CacheHandler->setDepthTest(true);
1302                                 CacheHandler->setDepthFunc(GL_LEQUAL);
1303                                 break;
1304                         case ECFN_EQUAL:
1305                                 CacheHandler->setDepthTest(true);
1306                                 CacheHandler->setDepthFunc(GL_EQUAL);
1307                                 break;
1308                         case ECFN_LESS:
1309                                 CacheHandler->setDepthTest(true);
1310                                 CacheHandler->setDepthFunc(GL_LESS);
1311                                 break;
1312                         case ECFN_NOTEQUAL:
1313                                 CacheHandler->setDepthTest(true);
1314                                 CacheHandler->setDepthFunc(GL_NOTEQUAL);
1315                                 break;
1316                         case ECFN_GREATEREQUAL:
1317                                 CacheHandler->setDepthTest(true);
1318                                 CacheHandler->setDepthFunc(GL_GEQUAL);
1319                                 break;
1320                         case ECFN_GREATER:
1321                                 CacheHandler->setDepthTest(true);
1322                                 CacheHandler->setDepthFunc(GL_GREATER);
1323                                 break;
1324                         case ECFN_ALWAYS:
1325                                 CacheHandler->setDepthTest(true);
1326                                 CacheHandler->setDepthFunc(GL_ALWAYS);
1327                                 break;
1328                         case ECFN_NEVER:
1329                                 CacheHandler->setDepthTest(true);
1330                                 CacheHandler->setDepthFunc(GL_NEVER);
1331                                 break;
1332                         default:
1333                                 break;
1334                 }
1335
1336                 // ZWrite
1337                 if (getWriteZBuffer(material))
1338                 {
1339                         CacheHandler->setDepthMask(true);
1340                 }
1341                 else
1342                 {
1343                         CacheHandler->setDepthMask(false);
1344                 }
1345
1346                 // Back face culling
1347                 if ((material.FrontfaceCulling) && (material.BackfaceCulling))
1348                 {
1349                         CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK);
1350                         CacheHandler->setCullFace(true);
1351                 }
1352                 else if (material.BackfaceCulling)
1353                 {
1354                         CacheHandler->setCullFaceFunc(GL_BACK);
1355                         CacheHandler->setCullFace(true);
1356                 }
1357                 else if (material.FrontfaceCulling)
1358                 {
1359                         CacheHandler->setCullFaceFunc(GL_FRONT);
1360                         CacheHandler->setCullFace(true);
1361                 }
1362                 else
1363                 {
1364                         CacheHandler->setCullFace(false);
1365                 }
1366
1367                 // Color Mask
1368                 CacheHandler->setColorMask(material.ColorMask);
1369
1370                 // Blend Equation
1371                 if (material.BlendOperation == EBO_NONE)
1372                         CacheHandler->setBlend(false);
1373                 else
1374                 {
1375                         CacheHandler->setBlend(true);
1376
1377                         switch (material.BlendOperation)
1378                         {
1379                         case EBO_ADD:
1380                                 CacheHandler->setBlendEquation(GL_FUNC_ADD);
1381                                 break;
1382                         case EBO_SUBTRACT:
1383                                 CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT);
1384                                 break;
1385                         case EBO_REVSUBTRACT:
1386                                 CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
1387                                 break;
1388                         default:
1389                                 break;
1390                         }
1391                 }
1392
1393                 // Blend Factor
1394                 if (IR(material.BlendFactor) & 0xFFFFFFFF       // TODO: why the & 0xFFFFFFFF?
1395                         && material.MaterialType != EMT_ONETEXTURE_BLEND
1396                 )
1397                 {
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;
1404
1405                     unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor);
1406
1407                         CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact),
1408                                 getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact));
1409                 }
1410
1411                 // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver.
1412
1413                 if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness)
1414                         glLineWidth(core::clamp(static_cast<GLfloat>(material.Thickness), DimAliasedLine[0], DimAliasedLine[1]));
1415
1416                 // Anti aliasing
1417                 if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing)
1418                 {
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);
1423                 }
1424
1425                 // Texture parameters
1426                 setTextureRenderStates(material, resetAllRenderStates);
1427         }
1428
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)
1431         {
1432                 // Set textures to TU/TIU and apply filters to them
1433
1434                 for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i)
1435                 {
1436                         const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i];
1437
1438                         if (!tmpTexture)
1439                                 continue;
1440
1441                         GLenum tmpTextureType = tmpTexture->getOpenGLTextureType();
1442
1443                         CacheHandler->setActiveTexture(GL_TEXTURE0 + i);
1444
1445                         if (resetAllRenderstates)
1446                                 tmpTexture->getStatesCache().IsCached = false;
1447
1448                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1449                                 material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter)
1450                         {
1451                                 glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER,
1452                                         (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1453
1454                                 tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1455                                 tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1456                         }
1457
1458                         if (material.UseMipMaps && tmpTexture->hasMipMaps())
1459                         {
1460                                 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1461                                         material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus)
1462                                 {
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);
1467
1468                                         tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1469                                         tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1470                                         tmpTexture->getStatesCache().MipMapStatus = true;
1471                                 }
1472                         }
1473                         else
1474                         {
1475                                 if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter ||
1476                                         material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus)
1477                                 {
1478                                         glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER,
1479                                                 (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST);
1480
1481                                         tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter;
1482                                         tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter;
1483                                         tmpTexture->getStatesCache().MipMapStatus = false;
1484                                 }
1485                         }
1486
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))
1490                         {
1491                                 glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1492                                         material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1);
1493
1494                                 tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter;
1495                         }
1496         #endif
1497
1498                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU)
1499                         {
1500                                 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU));
1501                                 tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU;
1502                         }
1503
1504                         if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV)
1505                         {
1506                                 glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV));
1507                                 tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV;
1508                         }
1509
1510                         tmpTexture->getStatesCache().IsCached = true;
1511                 }
1512         }
1513
1514
1515         // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode.
1516         GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const
1517         {
1518                 switch (clamp)
1519                 {
1520                         case ETC_CLAMP:
1521                         case ETC_CLAMP_TO_EDGE:
1522                         case ETC_CLAMP_TO_BORDER:
1523                                 return GL_CLAMP_TO_EDGE;
1524                         case ETC_MIRROR:
1525                                 return GL_REPEAT;
1526                         default:
1527                                 return GL_REPEAT;
1528                 }
1529         }
1530
1531
1532         //! sets the needed renderstates
1533         void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel)
1534         {
1535                 if ( LockRenderStateMode )
1536                         return;
1537
1538                 COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture;
1539
1540                 if (CurrentRenderMode != ERM_2D)
1541                 {
1542                         // unset last 3d material
1543                         if (CurrentRenderMode == ERM_3D)
1544                         {
1545                                 if (static_cast<u32>(LastMaterial.MaterialType) < MaterialRenderers.size())
1546                                         MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial();
1547                         }
1548
1549                         CurrentRenderMode = ERM_2D;
1550                 }
1551                 else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer)
1552                 {
1553                         MaterialRenderer2DActive->OnUnsetMaterial();
1554                 }
1555
1556                 MaterialRenderer2DActive = nextActiveRenderer;
1557
1558                 MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0);
1559                 LastMaterial = Material;
1560                 CacheHandler->correctCacheMaterial(LastMaterial);
1561
1562                 // no alphaChannel without texture
1563                 alphaChannel &= texture;
1564
1565                 if (alphaChannel || alpha)
1566                 {
1567                         CacheHandler->setBlend(true);
1568                         CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1569                         CacheHandler->setBlendEquation(GL_FUNC_ADD);
1570                 }
1571                 else
1572                         CacheHandler->setBlend(false);
1573
1574                 Material.setTexture(0, const_cast<COpenGL3Texture*>(CacheHandler->getTextureCache().get(0)));
1575                 setTransform(ETS_TEXTURE_0, core::IdentityMatrix);
1576
1577                 if (texture)
1578                 {
1579                         if (OverrideMaterial2DEnabled)
1580                                 setTextureRenderStates(OverrideMaterial2D, false);
1581                         else
1582                                 setTextureRenderStates(InitMaterial2D, false);
1583                 }
1584
1585                 MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD);
1586         }
1587
1588
1589         void COpenGL3DriverBase::chooseMaterial2D()
1590         {
1591                 if (!OverrideMaterial2DEnabled)
1592                         Material = InitMaterial2D;
1593
1594                 if (OverrideMaterial2DEnabled)
1595                 {
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;
1600
1601                         Material = OverrideMaterial2D;
1602                 }
1603         }
1604
1605
1606         //! \return Returns the name of the video driver.
1607         const wchar_t* COpenGL3DriverBase::getName() const
1608         {
1609                 return Name.c_str();
1610         }
1611
1612         void COpenGL3DriverBase::setViewPort(const core::rect<s32>& area)
1613         {
1614                 core::rect<s32> vp = area;
1615                 core::rect<s32> rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height);
1616                 vp.clipAgainst(rendert);
1617
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());
1620
1621                 ViewPort = vp;
1622         }
1623
1624
1625         void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height)
1626         {
1627                 CacheHandler->setViewport(0, 0, width, height);
1628                 ViewPort = core::recti(0, 0, width, height);
1629         }
1630
1631
1632         //! Draws a 3d line.
1633         void COpenGL3DriverBase::draw3DLine(const core::vector3df& start,
1634                         const core::vector3df& end, SColor color)
1635         {
1636                 setRenderStates3DMode();
1637
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);
1641
1642                 drawArrays(GL_LINES, vtPrimitive, vertices, 2);
1643         }
1644
1645
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)
1649         {
1650                 CNullDriver::OnResize(size);
1651                 CacheHandler->setViewport(0, 0, size.Width, size.Height);
1652                 Transformation3DChanged = true;
1653         }
1654
1655
1656         //! Returns type of video driver
1657         E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const
1658         {
1659                 return EDT_OPENGL3;
1660         }
1661
1662
1663         //! returns color format
1664         ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const
1665         {
1666                 return ColorFormat;
1667         }
1668
1669
1670         //! Get a vertex shader constant index.
1671         s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name)
1672         {
1673                 return getPixelShaderConstantID(name);
1674         }
1675
1676         //! Get a pixel shader constant index.
1677         s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name)
1678         {
1679                 os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID().");
1680                 return -1;
1681         }
1682
1683         //! Sets a vertex shader constant.
1684         void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1685         {
1686                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1687         }
1688
1689         //! Sets a pixel shader constant.
1690         void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount)
1691         {
1692                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1693         }
1694
1695         //! Sets a constant for the vertex shader based on an index.
1696         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count)
1697         {
1698                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1699                 return false;
1700         }
1701
1702         //! Int interface for the above.
1703         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count)
1704         {
1705                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1706                 return false;
1707         }
1708
1709         bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count)
1710         {
1711                 os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant().");
1712                 return false;
1713         }
1714
1715         //! Sets a constant for the pixel shader based on an index.
1716         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count)
1717         {
1718                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1719                 return false;
1720         }
1721
1722         //! Int interface for the above.
1723         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count)
1724         {
1725                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1726                 return false;
1727         }
1728
1729         bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count)
1730         {
1731                 os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant().");
1732                 return false;
1733         }
1734
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)
1741         {
1742                 os::Printer::log("No shader support.");
1743                 return -1;
1744         }
1745
1746
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,
1760                         u32 verticesOut,
1761                         IShaderConstantSetCallBack* callback,
1762                         E_MATERIAL_TYPE baseMaterial,
1763                         s32 userData)
1764         {
1765                 s32 nr = -1;
1766                 COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer(
1767                         this, nr, vertexShaderProgram,
1768                         pixelShaderProgram,
1769                         callback, baseMaterial, userData);
1770
1771                 r->drop();
1772                 return nr;
1773         }
1774
1775         //! Returns a pointer to the IVideoDriver interface. (Implementation for
1776         //! IMaterialRendererServices)
1777         IVideoDriver* COpenGL3DriverBase::getVideoDriver()
1778         {
1779                 return this;
1780         }
1781
1782
1783         //! Returns pointer to the IGPUProgrammingServices interface.
1784         IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices()
1785         {
1786                 return this;
1787         }
1788
1789         ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d<u32>& size,
1790                 const io::path& name, const ECOLOR_FORMAT format)
1791         {
1792                 //disable mip-mapping
1793                 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1794                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1795
1796                 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this);
1797                 addTexture(renderTargetTexture);
1798                 renderTargetTexture->drop();
1799
1800                 //restore mip-mapping
1801                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1802
1803                 return renderTargetTexture;
1804         }
1805
1806         ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format)
1807         {
1808                 //disable mip-mapping
1809                 bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS);
1810                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false);
1811
1812                 bool supportForFBO = (Feature.ColorAttachment > 0);
1813
1814                 const core::dimension2d<u32> size(sideLen, sideLen);
1815                 core::dimension2du destSize(size);
1816
1817                 if (!supportForFBO)
1818                 {
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);
1821                 }
1822
1823                 COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this);
1824                 addTexture(renderTargetTexture);
1825                 renderTargetTexture->drop();
1826
1827                 //restore mip-mapping
1828                 setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels);
1829
1830                 return renderTargetTexture;
1831         }
1832
1833
1834         //! Returns the maximum amount of primitives
1835         u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const
1836         {
1837                 return 65535;
1838         }
1839
1840         bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil)
1841         {
1842                 if (target && target->getDriverType() != getDriverType())
1843                 {
1844                         os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR);
1845                         return false;
1846                 }
1847
1848                 core::dimension2d<u32> destRenderTargetSize(0, 0);
1849
1850                 if (target)
1851                 {
1852                         COpenGL3RenderTarget* renderTarget = static_cast<COpenGL3RenderTarget*>(target);
1853
1854                         CacheHandler->setFBO(renderTarget->getBufferID());
1855                         renderTarget->update();
1856
1857                         destRenderTargetSize = renderTarget->getSize();
1858
1859                         setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height);
1860                 }
1861                 else
1862                 {
1863                         CacheHandler->setFBO(0);
1864
1865                         destRenderTargetSize = core::dimension2d<u32>(0, 0);
1866
1867                         setViewPortRaw(ScreenSize.Width, ScreenSize.Height);
1868                 }
1869
1870                 if (CurrentRenderTargetSize != destRenderTargetSize)
1871                 {
1872                         CurrentRenderTargetSize = destRenderTargetSize;
1873
1874                         Transformation3DChanged = true;
1875                 }
1876
1877                 CurrentRenderTarget = target;
1878
1879                 clearBuffers(clearFlag, clearColor, clearDepth, clearStencil);
1880
1881                 return true;
1882         }
1883
1884         void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil)
1885         {
1886                 GLbitfield mask = 0;
1887                 u8 colorMask = 0;
1888                 bool depthMask = false;
1889
1890                 CacheHandler->getColorMask(colorMask);
1891                 CacheHandler->getDepthMask(depthMask);
1892
1893                 if (flag & ECBF_COLOR)
1894                 {
1895                         CacheHandler->setColorMask(ECP_ALL);
1896
1897                         const f32 inv = 1.0f / 255.0f;
1898                         glClearColor(color.getRed() * inv, color.getGreen() * inv,
1899                                 color.getBlue() * inv, color.getAlpha() * inv);
1900
1901                         mask |= GL_COLOR_BUFFER_BIT;
1902                 }
1903
1904                 if (flag & ECBF_DEPTH)
1905                 {
1906                         CacheHandler->setDepthMask(true);
1907                         glClearDepthf(depth);
1908                         mask |= GL_DEPTH_BUFFER_BIT;
1909                 }
1910
1911                 if (flag & ECBF_STENCIL)
1912                 {
1913                         glClearStencil(stencil);
1914                         mask |= GL_STENCIL_BUFFER_BIT;
1915                 }
1916
1917                 if (mask)
1918                         glClear(mask);
1919
1920                 CacheHandler->setColorMask(colorMask);
1921                 CacheHandler->setDepthMask(depthMask);
1922         }
1923
1924
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)
1930         {
1931                 if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS)
1932                         return 0;
1933
1934                 GLint internalformat = GL_RGBA;
1935                 GLint type = GL_UNSIGNED_BYTE;
1936                 {
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)
1941                         {
1942                                 internalformat = GL_RGBA;
1943                                 type = GL_UNSIGNED_BYTE;
1944                         }
1945                 }
1946
1947                 IImage* newImage = 0;
1948                 if (GL_RGBA == internalformat)
1949                 {
1950                         if (GL_UNSIGNED_BYTE == type)
1951                                 newImage = new CImage(ECF_A8R8G8B8, ScreenSize);
1952                         else
1953                                 newImage = new CImage(ECF_A1R5G5B5, ScreenSize);
1954                 }
1955                 else
1956                 {
1957                         if (GL_UNSIGNED_BYTE == type)
1958                                 newImage = new CImage(ECF_R8G8B8, ScreenSize);
1959                         else
1960                                 newImage = new CImage(ECF_R5G6B5, ScreenSize);
1961                 }
1962
1963                 if (!newImage)
1964                         return 0;
1965
1966                 u8* pixels = static_cast<u8*>(newImage->getData());
1967                 if (!pixels)
1968                 {
1969                         newImage->drop();
1970                         return 0;
1971                 }
1972
1973                 glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels);
1974                 testGLError(__LINE__);
1975
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)
1981                 {
1982                         memcpy(tmpBuffer, pixels, pitch);
1983                         memcpy(pixels, p2, pitch);
1984                         memcpy(p2, tmpBuffer, pitch);
1985                         pixels += pitch;
1986                         p2 -= pitch;
1987                 }
1988                 delete [] tmpBuffer;
1989
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)
1992                 {
1993                         pixels = static_cast<u8*>(newImage->getData());
1994                         for (u32 i = 0; i < ScreenSize.Height; i++)
1995                         {
1996                                 for (u32 j = 0; j < ScreenSize.Width; j++)
1997                                 {
1998                                         u32 c = *(u32*) (pixels + 4 * j);
1999                                         *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) |
2000                                                 ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
2001                                 }
2002                                 pixels += pitch;
2003                         }
2004                 }
2005
2006                 if (testGLError(__LINE__))
2007                 {
2008                         newImage->drop();
2009                         return 0;
2010                 }
2011                 testGLError(__LINE__);
2012                 return newImage;
2013         }
2014
2015         void COpenGL3DriverBase::removeTexture(ITexture* texture)
2016         {
2017                 CacheHandler->getTextureCache().remove(texture);
2018                 CNullDriver::removeTexture(texture);
2019         }
2020
2021         //! Set/unset a clipping plane.
2022         bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable)
2023         {
2024                 if (index >= UserClipPlane.size())
2025                         UserClipPlane.push_back(SUserClipPlane());
2026
2027                 UserClipPlane[index].Plane = plane;
2028                 UserClipPlane[index].Enabled = enable;
2029                 return true;
2030         }
2031
2032         //! Enable/disable a clipping plane.
2033         void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable)
2034         {
2035                 UserClipPlane[index].Enabled = enable;
2036         }
2037
2038         //! Get the ClipPlane Count
2039         u32 COpenGL3DriverBase::getClipPlaneCount() const
2040         {
2041                 return UserClipPlane.size();
2042         }
2043
2044         const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const
2045         {
2046                 if (index < UserClipPlane.size())
2047                         return UserClipPlane[index].Plane;
2048                 else
2049                 {
2050                         _IRR_DEBUG_BREAK_IF(true)       // invalid index
2051                         static const core::plane3df dummy;
2052                         return dummy;
2053                 }
2054         }
2055
2056         core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const
2057         {
2058                 return core::dimension2du(MaxTextureSize, MaxTextureSize);
2059         }
2060
2061         GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const
2062         {
2063                 static GLenum const blendTable[] =
2064                 {
2065                         GL_ZERO,
2066                         GL_ONE,
2067                         GL_DST_COLOR,
2068                         GL_ONE_MINUS_DST_COLOR,
2069                         GL_SRC_COLOR,
2070                         GL_ONE_MINUS_SRC_COLOR,
2071                         GL_SRC_ALPHA,
2072                         GL_ONE_MINUS_SRC_ALPHA,
2073                         GL_DST_ALPHA,
2074                         GL_ONE_MINUS_DST_ALPHA,
2075                         GL_SRC_ALPHA_SATURATE
2076                 };
2077
2078                 return blendTable[factor];
2079         }
2080
2081         bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat,
2082                 GLenum& pixelType, void(**converter)(const void*, s32, void*)) const
2083         {
2084                 bool supported = false;
2085                 pixelFormat = GL_RGBA;
2086                 pixelType = GL_UNSIGNED_BYTE;
2087                 *converter = 0;
2088
2089                 switch (format)
2090                 {
2091                 case ECF_A1R5G5B5:
2092                         supported = true;
2093                         pixelFormat = GL_RGBA;
2094                         pixelType = GL_UNSIGNED_SHORT_5_5_5_1;
2095                         *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1;
2096                         break;
2097                 case ECF_R5G6B5:
2098                         supported = true;
2099                         pixelFormat = GL_RGB;
2100                         pixelType = GL_UNSIGNED_SHORT_5_6_5;
2101                         break;
2102                 case ECF_R8G8B8:
2103                         supported = true;
2104                         pixelFormat = GL_RGB;
2105                         pixelType = GL_UNSIGNED_BYTE;
2106                         break;
2107                 case ECF_A8R8G8B8:
2108                         supported = true;
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))
2112                         {
2113                                 pixelFormat = GL_BGRA;
2114                         }
2115                         else
2116                         {
2117                                 pixelFormat = GL_RGBA;
2118                                 *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8;
2119                         }
2120                         pixelType = GL_UNSIGNED_BYTE;
2121                         break;
2122 #ifdef GL_EXT_texture_compression_s3tc
2123                 case ECF_DXT1:
2124                         supported = true;
2125                         pixelFormat = GL_RGBA;
2126                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
2127                         break;
2128                 case ECF_DXT2:
2129                 case ECF_DXT3:
2130                         supported = true;
2131                         pixelFormat = GL_RGBA;
2132                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
2133                         break;
2134                 case ECF_DXT4:
2135                 case ECF_DXT5:
2136                         supported = true;
2137                         pixelFormat = GL_RGBA;
2138                         pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
2139                         break;
2140 #endif
2141 #ifdef GL_OES_compressed_ETC1_RGB8_texture
2142                 case ECF_ETC1:
2143                         supported = true;
2144                         pixelFormat = GL_RGB;
2145                         pixelType = GL_ETC1_RGB8_OES;
2146                         break;
2147 #endif
2148 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2149                 case ECF_ETC2_RGB:
2150                         supported = true;
2151                         pixelFormat = GL_RGB;
2152                         pixelType = GL_COMPRESSED_RGB8_ETC2;
2153                         break;
2154 #endif
2155 #ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available
2156                 case ECF_ETC2_ARGB:
2157                         supported = true;
2158                         pixelFormat = GL_RGBA;
2159                         pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC;
2160                         break;
2161 #endif
2162                 case ECF_D16:
2163                         supported = true;
2164                         pixelFormat = GL_DEPTH_COMPONENT;
2165                         pixelType = GL_UNSIGNED_SHORT;
2166                         break;
2167                 case ECF_D32:
2168 #if defined(GL_OES_depth32)
2169                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32))
2170                         {
2171                                 supported = true;
2172                                 pixelFormat = GL_DEPTH_COMPONENT;
2173                                 pixelType = GL_UNSIGNED_INT;
2174                         }
2175 #endif
2176                         break;
2177                 case ECF_D24S8:
2178 #ifdef GL_OES_packed_depth_stencil
2179                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil))
2180                         {
2181                                 supported = true;
2182                                 pixelFormat = GL_DEPTH_STENCIL_OES;
2183                                 pixelType = GL_UNSIGNED_INT_24_8_OES;
2184                         }
2185 #endif
2186                         break;
2187                 case ECF_R8:
2188 #if defined(GL_EXT_texture_rg)
2189                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2190                         {
2191                                 supported = true;
2192                                 pixelFormat = GL_RED_EXT;
2193                                 pixelType = GL_UNSIGNED_BYTE;
2194                         }
2195 #endif
2196                         break;
2197                 case ECF_R8G8:
2198 #if defined(GL_EXT_texture_rg)
2199                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg))
2200                         {
2201                                 supported = true;
2202                                 pixelFormat = GL_RG_EXT;
2203                                 pixelType = GL_UNSIGNED_BYTE;
2204                         }
2205 #endif
2206                         break;
2207                 case ECF_R16:
2208                         break;
2209                 case ECF_R16G16:
2210                         break;
2211                 case ECF_R16F:
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)
2215                                 )
2216                         {
2217                                 supported = true;
2218                                 pixelFormat = GL_RED_EXT;
2219                                 pixelType = GL_HALF_FLOAT_OES ;
2220                         }
2221 #endif
2222                         break;
2223                 case ECF_G16R16F:
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)
2227                                 )
2228                         {
2229                                 supported = true;
2230                                 pixelFormat = GL_RG_EXT;
2231                                 pixelType = GL_HALF_FLOAT_OES ;
2232                         }
2233 #endif
2234                         break;
2235                 case ECF_A16B16G16R16F:
2236 #if defined(GL_OES_texture_half_float)
2237                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2238                         {
2239                                 supported = true;
2240                                 pixelFormat = GL_RGBA;
2241                                 pixelType = GL_HALF_FLOAT_OES ;
2242                         }
2243 #endif
2244                         break;
2245                 case ECF_R32F:
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)
2249                                 )
2250                         {
2251                                 supported = true;
2252                                 pixelFormat = GL_RED_EXT;
2253                                 pixelType = GL_FLOAT;
2254                         }
2255 #endif
2256                         break;
2257                 case ECF_G32R32F:
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)
2261                                 )
2262                         {
2263                                 supported = true;
2264                                 pixelFormat = GL_RG_EXT;
2265                                 pixelType = GL_FLOAT;
2266                         }
2267 #endif
2268                         break;
2269                 case ECF_A32B32G32R32F:
2270 #if defined(GL_OES_texture_float)
2271                         if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float))
2272                         {
2273                                 supported = true;
2274                                 pixelFormat = GL_RGBA;
2275                                 pixelType = GL_FLOAT ;
2276                         }
2277 #endif
2278                         break;
2279                 default:
2280                         break;
2281                 }
2282
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;
2288
2289 #ifdef _IRR_IOS_PLATFORM_
2290                 if (internalFormat == GL_BGRA)
2291                         internalFormat = GL_RGBA;
2292 #endif
2293
2294                 return supported;
2295         }
2296
2297         bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const
2298         {
2299                 GLint dummyInternalFormat;
2300                 GLenum dummyPixelFormat;
2301                 GLenum dummyPixelType;
2302                 void (*dummyConverter)(const void*, s32, void*);
2303                 return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter);
2304         }
2305
2306         bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const
2307         {
2308                 return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation();
2309         }
2310
2311         const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const
2312         {
2313                 return Material;
2314         }
2315
2316         COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const
2317         {
2318                 return CacheHandler;
2319         }
2320
2321 } // end namespace
2322 } // end namespace