Merge branch 'devel/master' into tizen
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / gles-context.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 #include "gles-context.h"
19 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
20 #include <dali/integration-api/debug.h>
21 #include <dali/integration-api/gl-abstraction.h>
22 #include <dali/integration-api/gl-defines.h>
23 #include <dali/internal/graphics/common/graphics-interface.h>
24 #include <dali/public-api/math/math-utils.h>
25
26 #include "egl-graphics-controller.h"
27 #include "gles-graphics-buffer.h"
28 #include "gles-graphics-pipeline.h"
29 #include "gles-graphics-program.h"
30 #include "gles-graphics-render-pass.h"
31 #include "gles-graphics-render-target.h"
32 #include "gles-texture-dependency-checker.h"
33
34 #include <EGL/egl.h>
35 #include <EGL/eglext.h>
36 #include <map>
37 #include <unordered_map>
38
39 namespace Dali::Graphics::GLES
40 {
41 struct Context::Impl
42 {
43   explicit Impl(EglGraphicsController& controller)
44   : mController(controller)
45   {
46   }
47
48   ~Impl() = default;
49
50   /**
51    * Binds (and creates) VAO
52    *
53    * VAO is fixed per program so it has to be created only once assuming
54    * that VertexInputState has been set correctly for the pipeline.
55    *
56    */
57   void BindProgramVAO(const GLES::ProgramImpl* program, const VertexInputState& vertexInputState)
58   {
59     // Calculate attributes location hash unordered.
60     std::size_t hash = 0;
61     for(const auto& attr : vertexInputState.attributes)
62     {
63       hash ^= std::hash<uint32_t>{}(attr.location);
64     }
65
66     auto& gl   = *mController.GetGL();
67     auto  iter = mProgramVAOMap.find(program);
68     if(iter != mProgramVAOMap.end())
69     {
70       auto attributeIter = iter->second.find(hash);
71       if(attributeIter != iter->second.end())
72       {
73         if(mProgramVAOCurrentState != attributeIter->second)
74         {
75           mProgramVAOCurrentState = attributeIter->second;
76           gl.BindVertexArray(attributeIter->second);
77
78           // Binding VAO seems to reset the index buffer binding so the cache must be reset
79           mGlStateCache.mBoundElementArrayBufferId = 0;
80         }
81         return;
82       }
83     }
84
85     uint32_t vao;
86     gl.GenVertexArrays(1, &vao);
87     gl.BindVertexArray(vao);
88
89     // Binding VAO seems to reset the index buffer binding so the cache must be reset
90     mGlStateCache.mBoundElementArrayBufferId = 0;
91
92     mProgramVAOMap[program][hash] = vao;
93     for(const auto& attr : vertexInputState.attributes)
94     {
95       gl.EnableVertexAttribArray(attr.location);
96     }
97
98     mProgramVAOCurrentState = vao;
99   }
100
101   /**
102    * Sets the initial GL state.
103    */
104   void InitializeGlState()
105   {
106     auto& gl = *mController.GetGL();
107
108     mGlStateCache.mClearColorSet        = false;
109     mGlStateCache.mColorMask            = true;
110     mGlStateCache.mStencilMask          = 0xFF;
111     mGlStateCache.mBlendEnabled         = false;
112     mGlStateCache.mDepthBufferEnabled   = false;
113     mGlStateCache.mDepthMaskEnabled     = false;
114     mGlStateCache.mScissorTestEnabled   = false;
115     mGlStateCache.mStencilBufferEnabled = false;
116
117     gl.Disable(GL_DITHER);
118
119     mGlStateCache.mBoundArrayBufferId        = 0;
120     mGlStateCache.mBoundElementArrayBufferId = 0;
121     mGlStateCache.mActiveTextureUnit         = 0;
122
123     mGlStateCache.mBlendFuncSeparateSrcRGB   = BlendFactor::ONE;
124     mGlStateCache.mBlendFuncSeparateDstRGB   = BlendFactor::ZERO;
125     mGlStateCache.mBlendFuncSeparateSrcAlpha = BlendFactor::ONE;
126     mGlStateCache.mBlendFuncSeparateDstAlpha = BlendFactor::ZERO;
127
128     // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
129     mGlStateCache.mBlendEquationSeparateModeRGB   = BlendOp::ADD;
130     mGlStateCache.mBlendEquationSeparateModeAlpha = BlendOp::ADD;
131
132     mGlStateCache.mCullFaceMode = CullMode::NONE; //By default cullface is disabled, front face is set to CCW and cull face is set to back
133
134     //Initialze vertex attribute cache
135     memset(&mGlStateCache.mVertexAttributeCachedState, 0, sizeof(mGlStateCache.mVertexAttributeCachedState));
136     memset(&mGlStateCache.mVertexAttributeCurrentState, 0, sizeof(mGlStateCache.mVertexAttributeCurrentState));
137
138     //Initialize bound 2d texture cache
139     memset(&mGlStateCache.mBoundTextureId, 0, sizeof(mGlStateCache.mBoundTextureId));
140
141     mGlStateCache.mFrameBufferStateCache.Reset();
142   }
143
144   /**
145    * Flushes vertex attribute location changes to the driver
146    */
147   void FlushVertexAttributeLocations()
148   {
149     auto& gl = *mController.GetGL();
150
151     for(unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i)
152     {
153       // see if the cached state is different to the actual state
154       if(mGlStateCache.mVertexAttributeCurrentState[i] != mGlStateCache.mVertexAttributeCachedState[i])
155       {
156         // it's different so make the change to the driver and update the cached state
157         mGlStateCache.mVertexAttributeCurrentState[i] = mGlStateCache.mVertexAttributeCachedState[i];
158
159         if(mGlStateCache.mVertexAttributeCurrentState[i])
160         {
161           gl.EnableVertexAttribArray(i);
162         }
163         else
164         {
165           gl.DisableVertexAttribArray(i);
166         }
167       }
168     }
169   }
170
171   /**
172    * Either enables or disables a vertex attribute location in the cache
173    * The cahnges won't take affect until FlushVertexAttributeLocations is called
174    * @param location attribute location
175    * @param state attribute state
176    */
177   void SetVertexAttributeLocation(unsigned int location, bool state)
178   {
179     auto& gl = *mController.GetGL();
180
181     if(location >= MAX_ATTRIBUTE_CACHE_SIZE)
182     {
183       // not cached, make the gl call through context
184       if(state)
185       {
186         gl.EnableVertexAttribArray(location);
187       }
188       else
189       {
190         gl.DisableVertexAttribArray(location);
191       }
192     }
193     else
194     {
195       // set the cached state, it will be set at the next draw call
196       // if it's different from the current driver state
197       mGlStateCache.mVertexAttributeCachedState[location] = state;
198     }
199   }
200
201   EglGraphicsController& mController;
202
203   const GLES::PipelineImpl* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
204   const GLES::PipelineImpl* mNewPipeline{nullptr};     ///< New pipeline to be set on flush
205
206   std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
207   std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
208   GLES::IndexBufferBindingDescriptor    mCurrentIndexBufferBinding{};
209
210   struct VertexBufferBinding
211   {
212     GLES::Buffer* buffer{nullptr};
213     uint32_t      offset{0u};
214   };
215
216   // Currently bound buffers
217   std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
218
219   // Currently bound UBOs (check if it's needed per program!)
220   std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
221   UniformBufferBindingDescriptor              mCurrentStandaloneUBOBinding{};
222
223   // Current render pass and render target
224   const GLES::RenderTarget* mCurrentRenderTarget{nullptr};
225   const GLES::RenderPass*   mCurrentRenderPass{nullptr};
226
227   // Each context must have own VAOs as they cannot be shared
228   std::unordered_map<const GLES::ProgramImpl*, std::map<std::size_t, uint32_t>> mProgramVAOMap;              ///< GL program-VAO map
229   uint32_t                                                                      mProgramVAOCurrentState{0u}; ///< Currently bound VAO
230   GLStateCache                                                                  mGlStateCache{};             ///< GL status cache
231
232   bool mGlContextCreated{false}; ///< True if the OpenGL context has been created
233
234   EGLContext mNativeDrawContext{0u}; ///< Native rendering EGL context compatible with window context
235
236   EGLSurface mCacheDrawReadSurface{0u};    ///< cached 'read' surface
237   EGLSurface mCacheDrawWriteSurface{0u};   ///< cached 'write' surface
238   EGLContext mCacheEGLGraphicsContext{0u}; ///< cached window context
239 };
240
241 Context::Context(EglGraphicsController& controller)
242 {
243   mImpl = std::make_unique<Impl>(controller);
244 }
245
246 Context::~Context()
247 {
248   // Destroy native rendering context if one exists
249   if(mImpl->mNativeDrawContext)
250   {
251     eglDestroyContext(eglGetCurrentDisplay(), mImpl->mNativeDrawContext);
252     mImpl->mNativeDrawContext = EGL_NO_CONTEXT;
253   }
254 }
255
256 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall, GLES::TextureDependencyChecker& dependencyChecker)
257 {
258   auto& gl = *mImpl->mController.GetGL();
259
260   static const bool hasGLES3(mImpl->mController.GetGLESVersion() >= GLESVersion::GLES_30);
261
262   // early out if neither current nor new pipelines are set
263   // this behaviour may be valid so no assert
264   if(!mImpl->mCurrentPipeline && !mImpl->mNewPipeline)
265   {
266     return;
267   }
268
269   // Execute states if pipeline is changed
270   const auto currentProgram = mImpl->mCurrentPipeline ? static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program) : nullptr;
271
272   // case when new pipeline has been set
273   const GLES::Program* newProgram = nullptr;
274
275   if(mImpl->mNewPipeline)
276   {
277     newProgram = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
278   }
279
280   if(!currentProgram && !newProgram)
281   {
282     // Early out if we have no program for this pipeline.
283     DALI_LOG_ERROR("No program defined for pipeline\n");
284     return;
285   }
286
287   if(mImpl->mNewPipeline && mImpl->mCurrentPipeline != mImpl->mNewPipeline)
288   {
289     if(!currentProgram || currentProgram->GetImplementation()->GetGlProgram() != newProgram->GetImplementation()->GetGlProgram())
290     {
291       mImpl->mNewPipeline->Bind(newProgram->GetImplementation()->GetGlProgram());
292     }
293
294     // Blend state
295     ResolveBlendState();
296
297     // Resolve rasterization state
298     ResolveRasterizationState();
299   }
300
301   // Resolve uniform buffers
302   ResolveUniformBuffers();
303
304   // Bind textures
305   // Map binding# to sampler location
306   const auto& reflection = !newProgram ? currentProgram->GetReflection() : newProgram->GetReflection();
307   const auto& samplers   = reflection.GetSamplers();
308   for(const auto& binding : mImpl->mCurrentTextureBindings)
309   {
310     auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
311
312     // Texture may not have been initialized yet...(tbm_surface timing issue?)
313     if(!texture->GetGLTexture())
314     {
315       // Attempt to reinitialize
316       // @todo need to put this somewhere else where it isn't const.
317       // Maybe post it back on end of initialize queue if initialization fails?
318       texture->InitializeResource();
319     }
320
321     // Warning, this may cause glWaitSync to occur on the GPU.
322     dependencyChecker.CheckNeedsSync(this, texture);
323
324     texture->Bind(binding);
325
326     texture->Prepare(); // @todo also non-const.
327
328     if(binding.binding < samplers.size()) // binding maps to texture unit. (texture bindings should also be in binding order)
329     {
330       // Offset is set to the lexical offset within the frag shader, map it to the texture unit
331       // @todo Explicitly set the texture unit through the graphics interface
332       gl.Uniform1i(samplers[binding.binding].location, samplers[binding.binding].offset);
333     }
334   }
335
336   // for each attribute bind vertices
337
338   const auto& pipelineState    = mImpl->mNewPipeline ? mImpl->mNewPipeline->GetCreateInfo() : mImpl->mCurrentPipeline->GetCreateInfo();
339   const auto& vertexInputState = pipelineState.vertexInputState;
340
341   if(hasGLES3)
342   {
343     mImpl->BindProgramVAO(static_cast<const GLES::Program*>(pipelineState.programState->program)->GetImplementation(), *vertexInputState);
344   }
345
346   for(const auto& attr : vertexInputState->attributes)
347   {
348     // Enable location
349     if(!hasGLES3)
350     {
351       mImpl->SetVertexAttributeLocation(attr.location, true);
352     }
353
354     const auto& bufferSlot    = mImpl->mCurrentVertexBufferBindings[attr.binding];
355     const auto& bufferBinding = vertexInputState->bufferBindings[attr.binding];
356
357     auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
358
359     // Bind buffer
360     BindBuffer(GL_ARRAY_BUFFER, glesBuffer);
361
362     gl.VertexAttribPointer(attr.location,
363                            GLVertexFormat(attr.format).size,
364                            GLVertexFormat(attr.format).format,
365                            GL_FALSE,
366                            bufferBinding.stride,
367                            reinterpret_cast<void*>(attr.offset));
368   }
369
370   // Resolve topology
371   const auto& ia = pipelineState.inputAssemblyState;
372
373   // Bind uniforms
374
375   // Resolve draw call
376   switch(drawCall.type)
377   {
378     case DrawCallDescriptor::Type::DRAW:
379     {
380       mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
381                                                                 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
382                                                                 mImpl->mGlStateCache.StencilBufferWriteEnabled());
383       // For GLES3+ we use VAO, for GLES2 internal cache
384       if(!hasGLES3)
385       {
386         mImpl->FlushVertexAttributeLocations();
387       }
388
389       gl.DrawArrays(GLESTopology(ia->topology),
390                     drawCall.draw.firstVertex,
391                     drawCall.draw.vertexCount);
392       break;
393     }
394     case DrawCallDescriptor::Type::DRAW_INDEXED:
395     {
396       const auto& binding = mImpl->mCurrentIndexBufferBinding;
397       BindBuffer(GL_ELEMENT_ARRAY_BUFFER, binding.buffer->GetGLBuffer());
398
399       mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
400                                                                 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
401                                                                 mImpl->mGlStateCache.StencilBufferWriteEnabled());
402
403       // For GLES3+ we use VAO, for GLES2 internal cache
404       if(!hasGLES3)
405       {
406         mImpl->FlushVertexAttributeLocations();
407       }
408
409       auto indexBufferFormat = GLIndexFormat(binding.format).format;
410       gl.DrawElements(GLESTopology(ia->topology),
411                       drawCall.drawIndexed.indexCount,
412                       indexBufferFormat,
413                       reinterpret_cast<void*>(binding.offset));
414       break;
415     }
416     case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
417     {
418       break;
419     }
420   }
421
422   ClearState();
423
424   // Change pipeline
425   if(mImpl->mNewPipeline)
426   {
427     mImpl->mCurrentPipeline = mImpl->mNewPipeline;
428     mImpl->mNewPipeline     = nullptr;
429   }
430 }
431
432 void Context::BindTextures(const Graphics::TextureBinding* bindings, uint32_t count)
433 {
434   // for each texture allocate slot
435   for(auto i = 0u; i < count; ++i)
436   {
437     auto& binding = bindings[i];
438
439     // Resize binding array if needed
440     if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
441     {
442       mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
443     }
444     // Store the binding details
445     mImpl->mCurrentTextureBindings[binding.binding] = binding;
446   }
447 }
448
449 void Context::BindVertexBuffers(const GLES::VertexBufferBindingDescriptor* bindings, uint32_t count)
450 {
451   if(count > mImpl->mCurrentVertexBufferBindings.size())
452   {
453     mImpl->mCurrentVertexBufferBindings.resize(count);
454   }
455   // Copy only set slots
456   std::copy_if(bindings, bindings + count, mImpl->mCurrentVertexBufferBindings.begin(), [](auto& item) {
457     return (nullptr != item.buffer);
458   });
459 }
460
461 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
462 {
463   mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
464 }
465
466 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
467 {
468   DALI_ASSERT_ALWAYS(newPipeline && "Invalid pipeline");
469   mImpl->mNewPipeline = &newPipeline->GetPipeline();
470 }
471
472 void Context::BindUniformBuffers(const UniformBufferBindingDescriptor* uboBindings,
473                                  uint32_t                              uboCount,
474                                  const UniformBufferBindingDescriptor& standaloneBindings)
475 {
476   if(standaloneBindings.buffer)
477   {
478     mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
479   }
480
481   if(uboCount >= mImpl->mCurrentUBOBindings.size())
482   {
483     mImpl->mCurrentUBOBindings.resize(uboCount + 1);
484   }
485
486   auto it = uboBindings;
487   for(auto i = 0u; i < uboCount; ++i)
488   {
489     if(it->buffer)
490     {
491       mImpl->mCurrentUBOBindings[i] = *it;
492     }
493   }
494 }
495
496 void Context::ResolveBlendState()
497 {
498   const auto& currentBlendState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().colorBlendState : nullptr;
499   const auto& newBlendState     = mImpl->mNewPipeline->GetCreateInfo().colorBlendState;
500
501   // TODO: prevent leaking the state
502   if(!newBlendState)
503   {
504     return;
505   }
506
507   auto& gl = *mImpl->mController.GetGL();
508
509   if(!currentBlendState || currentBlendState->blendEnable != newBlendState->blendEnable)
510   {
511     if(newBlendState->blendEnable != mImpl->mGlStateCache.mBlendEnabled)
512     {
513       mImpl->mGlStateCache.mBlendEnabled = newBlendState->blendEnable;
514       newBlendState->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
515     }
516   }
517
518   if(!newBlendState->blendEnable)
519   {
520     return;
521   }
522
523   BlendFactor newSrcRGB(newBlendState->srcColorBlendFactor);
524   BlendFactor newDstRGB(newBlendState->dstColorBlendFactor);
525   BlendFactor newSrcAlpha(newBlendState->srcAlphaBlendFactor);
526   BlendFactor newDstAlpha(newBlendState->dstAlphaBlendFactor);
527
528   if(!currentBlendState ||
529      currentBlendState->srcColorBlendFactor != newSrcRGB ||
530      currentBlendState->dstColorBlendFactor != newDstRGB ||
531      currentBlendState->srcAlphaBlendFactor != newSrcAlpha ||
532      currentBlendState->dstAlphaBlendFactor != newDstAlpha)
533   {
534     if((mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB != newSrcRGB) ||
535        (mImpl->mGlStateCache.mBlendFuncSeparateDstRGB != newDstRGB) ||
536        (mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha != newSrcAlpha) ||
537        (mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha != newDstAlpha))
538     {
539       mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB   = newSrcRGB;
540       mImpl->mGlStateCache.mBlendFuncSeparateDstRGB   = newDstRGB;
541       mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha = newSrcAlpha;
542       mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha = newDstAlpha;
543
544       if(newSrcRGB == newSrcAlpha && newDstRGB == newDstAlpha)
545       {
546         gl.BlendFunc(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB));
547       }
548       else
549       {
550         gl.BlendFuncSeparate(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB), GLBlendFunc(newSrcAlpha), GLBlendFunc(newDstAlpha));
551       }
552     }
553   }
554
555   if(!currentBlendState ||
556      currentBlendState->colorBlendOp != newBlendState->colorBlendOp ||
557      currentBlendState->alphaBlendOp != newBlendState->alphaBlendOp)
558   {
559     if(mImpl->mGlStateCache.mBlendEquationSeparateModeRGB != newBlendState->colorBlendOp ||
560        mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha != newBlendState->alphaBlendOp)
561     {
562       mImpl->mGlStateCache.mBlendEquationSeparateModeRGB   = newBlendState->colorBlendOp;
563       mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha = newBlendState->alphaBlendOp;
564
565       if(newBlendState->colorBlendOp == newBlendState->alphaBlendOp)
566       {
567         gl.BlendEquation(GLBlendOp(newBlendState->colorBlendOp));
568         if(newBlendState->colorBlendOp >= Graphics::ADVANCED_BLEND_OPTIONS_START)
569         {
570           gl.BlendBarrier();
571         }
572       }
573       else
574       {
575         gl.BlendEquationSeparate(GLBlendOp(newBlendState->colorBlendOp), GLBlendOp(newBlendState->alphaBlendOp));
576       }
577     }
578   }
579 }
580
581 void Context::ResolveRasterizationState()
582 {
583   const auto& currentRasterizationState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().rasterizationState : nullptr;
584   const auto& newRasterizationState     = mImpl->mNewPipeline->GetCreateInfo().rasterizationState;
585
586   // TODO: prevent leaking the state
587   if(!newRasterizationState)
588   {
589     return;
590   }
591
592   auto& gl = *mImpl->mController.GetGL();
593
594   if(!currentRasterizationState ||
595      currentRasterizationState->cullMode != newRasterizationState->cullMode)
596   {
597     if(mImpl->mGlStateCache.mCullFaceMode != newRasterizationState->cullMode)
598     {
599       mImpl->mGlStateCache.mCullFaceMode = newRasterizationState->cullMode;
600       if(newRasterizationState->cullMode == CullMode::NONE)
601       {
602         gl.Disable(GL_CULL_FACE);
603       }
604       else
605       {
606         gl.Enable(GL_CULL_FACE);
607         gl.CullFace(GLCullMode(newRasterizationState->cullMode));
608       }
609     }
610   }
611   // TODO: implement polygon mode (fill, line, points)
612   //       seems like we don't support it (no glPolygonMode())
613 }
614
615 void Context::ResolveUniformBuffers()
616 {
617   // Resolve standalone uniforms if we have binding
618   if(mImpl->mCurrentStandaloneUBOBinding.buffer)
619   {
620     ResolveStandaloneUniforms();
621   }
622 }
623
624 void Context::ResolveStandaloneUniforms()
625 {
626   // Find reflection for program
627   const GLES::Program* program{nullptr};
628
629   if(mImpl->mNewPipeline)
630   {
631     program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
632   }
633   else if(mImpl->mCurrentPipeline)
634   {
635     program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
636   }
637
638   if(program)
639   {
640     const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
641     // Update program uniforms
642     program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
643   }
644 }
645
646 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
647 {
648   auto& renderPass   = *renderPassBegin.renderPass;
649   auto& renderTarget = *renderPassBegin.renderTarget;
650
651   const auto& targetInfo = renderTarget.GetCreateInfo();
652
653   auto& gl = *mImpl->mController.GetGL();
654
655   if(targetInfo.surface)
656   {
657     // Bind surface FB
658     BindFrameBuffer(GL_FRAMEBUFFER, 0);
659   }
660   else if(targetInfo.framebuffer)
661   {
662     // bind framebuffer and swap.
663     auto framebuffer = renderTarget.GetFramebuffer();
664     framebuffer->Bind();
665   }
666
667   // clear (ideally cache the setup)
668
669   // In GL we assume that the last attachment is depth/stencil (we may need
670   // to cache extra information inside GLES RenderTarget if we want to be
671   // more specific in case of MRT)
672
673   const auto& attachments = *renderPass.GetCreateInfo().attachments;
674   const auto& color0      = attachments[0];
675   GLuint      mask        = 0;
676
677   if(color0.loadOp == AttachmentLoadOp::CLEAR)
678   {
679     mask |= GL_COLOR_BUFFER_BIT;
680
681     // Set clear color
682     // Something goes wrong here if Alpha mask is GL_TRUE
683     ColorMask(true);
684
685     const auto clearValues = renderPassBegin.clearValues.Ptr();
686
687     if(!Dali::Equals(mImpl->mGlStateCache.mClearColor.r, clearValues[0].color.r) ||
688        !Dali::Equals(mImpl->mGlStateCache.mClearColor.g, clearValues[0].color.g) ||
689        !Dali::Equals(mImpl->mGlStateCache.mClearColor.b, clearValues[0].color.b) ||
690        !Dali::Equals(mImpl->mGlStateCache.mClearColor.a, clearValues[0].color.a) ||
691        !mImpl->mGlStateCache.mClearColorSet)
692     {
693       gl.ClearColor(clearValues[0].color.r,
694                     clearValues[0].color.g,
695                     clearValues[0].color.b,
696                     clearValues[0].color.a);
697
698       mImpl->mGlStateCache.mClearColorSet = true;
699       mImpl->mGlStateCache.mClearColor    = Vector4(clearValues[0].color.r,
700                                                  clearValues[0].color.g,
701                                                  clearValues[0].color.b,
702                                                  clearValues[0].color.a);
703     }
704   }
705
706   // check for depth stencil
707   if(attachments.size() > 1)
708   {
709     const auto& depthStencil = attachments.back();
710     if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
711     {
712       if(!mImpl->mGlStateCache.mDepthMaskEnabled)
713       {
714         mImpl->mGlStateCache.mDepthMaskEnabled = true;
715         gl.DepthMask(true);
716       }
717       mask |= GL_DEPTH_BUFFER_BIT;
718     }
719     if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
720     {
721       if(mImpl->mGlStateCache.mStencilMask != 0xFF)
722       {
723         mImpl->mGlStateCache.mStencilMask = 0xFF;
724         gl.StencilMask(0xFF);
725       }
726       mask |= GL_STENCIL_BUFFER_BIT;
727     }
728   }
729
730   SetScissorTestEnabled(true);
731   gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
732   ClearBuffer(mask, true);
733   SetScissorTestEnabled(false);
734
735   mImpl->mCurrentRenderPass   = &renderPass;
736   mImpl->mCurrentRenderTarget = &renderTarget;
737 }
738
739 void Context::EndRenderPass(GLES::TextureDependencyChecker& dependencyChecker)
740 {
741   if(mImpl->mCurrentRenderTarget)
742   {
743     GLES::Framebuffer* framebuffer = mImpl->mCurrentRenderTarget->GetFramebuffer();
744     if(framebuffer)
745     {
746       auto& gl = *mImpl->mController.GetGL();
747       gl.Flush();
748
749       /* @todo Full dependency checking would need to store textures in Begin, and create
750        * fence objects here; but we're going to draw all fbos on shared context in serial,
751        * so no real need (yet). Might want to consider ensuring order of render passes,
752        * but that needs doing in the controller, and would need doing before ProcessCommandQueues.
753        *
754        * Currently up to the client to create render tasks in the right order.
755        */
756
757       /* Create fence sync objects. Other contexts can then wait on these fences before reading
758        * textures.
759        */
760       dependencyChecker.AddTextures(this, framebuffer);
761     }
762   }
763 }
764
765 void Context::ClearState()
766 {
767   mImpl->mCurrentTextureBindings.clear();
768 }
769
770 void Context::ColorMask(bool enabled)
771 {
772   if(enabled != mImpl->mGlStateCache.mColorMask)
773   {
774     mImpl->mGlStateCache.mColorMask = enabled;
775
776     auto& gl = *mImpl->mController.GetGL();
777     gl.ColorMask(enabled, enabled, enabled, enabled);
778   }
779 }
780
781 void Context::ClearStencilBuffer()
782 {
783   ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
784 }
785
786 void Context::ClearDepthBuffer()
787 {
788   ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
789 }
790
791 void Context::ClearBuffer(uint32_t mask, bool forceClear)
792 {
793   mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
794   if(mask > 0)
795   {
796     auto& gl = *mImpl->mController.GetGL();
797     gl.Clear(mask);
798   }
799 }
800
801 void Context::InvalidateDepthStencilBuffers()
802 {
803   auto& gl = *mImpl->mController.GetGL();
804
805   GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
806   gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
807 }
808
809 void Context::SetScissorTestEnabled(bool scissorEnabled)
810 {
811   if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
812   {
813     mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
814
815     auto& gl = *mImpl->mController.GetGL();
816     if(scissorEnabled)
817     {
818       gl.Enable(GL_SCISSOR_TEST);
819     }
820     else
821     {
822       gl.Disable(GL_SCISSOR_TEST);
823     }
824   }
825 }
826
827 void Context::SetStencilTestEnable(bool stencilEnable)
828 {
829   if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
830   {
831     mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
832
833     auto& gl = *mImpl->mController.GetGL();
834     if(stencilEnable)
835     {
836       gl.Enable(GL_STENCIL_TEST);
837     }
838     else
839     {
840       gl.Disable(GL_STENCIL_TEST);
841     }
842   }
843 }
844
845 void Context::StencilMask(uint32_t writeMask)
846 {
847   if(writeMask != mImpl->mGlStateCache.mStencilMask)
848   {
849     mImpl->mGlStateCache.mStencilMask = writeMask;
850
851     auto& gl = *mImpl->mController.GetGL();
852     gl.StencilMask(writeMask);
853   }
854 }
855
856 void Context::StencilFunc(Graphics::CompareOp compareOp,
857                           uint32_t            reference,
858                           uint32_t            compareMask)
859 {
860   if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
861      reference != mImpl->mGlStateCache.mStencilFuncRef ||
862      compareMask != mImpl->mGlStateCache.mStencilFuncMask)
863   {
864     mImpl->mGlStateCache.mStencilFunc     = compareOp;
865     mImpl->mGlStateCache.mStencilFuncRef  = reference;
866     mImpl->mGlStateCache.mStencilFuncMask = compareMask;
867
868     auto& gl = *mImpl->mController.GetGL();
869     gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
870   }
871 }
872
873 void Context::StencilOp(Graphics::StencilOp failOp,
874                         Graphics::StencilOp depthFailOp,
875                         Graphics::StencilOp passOp)
876 {
877   if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
878      depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
879      passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
880   {
881     mImpl->mGlStateCache.mStencilOpFail      = failOp;
882     mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
883     mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
884
885     auto& gl = *mImpl->mController.GetGL();
886     gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
887   }
888 }
889
890 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
891 {
892   if(compareOp != mImpl->mGlStateCache.mDepthFunction)
893   {
894     mImpl->mGlStateCache.mDepthFunction = compareOp;
895     auto& gl                            = *mImpl->mController.GetGL();
896     gl.DepthFunc(GLCompareOp(compareOp).op);
897   }
898 }
899
900 void Context::SetDepthTestEnable(bool depthTestEnable)
901 {
902   if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
903   {
904     mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
905
906     auto& gl = *mImpl->mController.GetGL();
907     if(depthTestEnable)
908     {
909       gl.Enable(GL_DEPTH_TEST);
910     }
911     else
912     {
913       gl.Disable(GL_DEPTH_TEST);
914     }
915   }
916 }
917
918 void Context::SetDepthWriteEnable(bool depthWriteEnable)
919 {
920   if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
921   {
922     mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
923
924     auto& gl = *mImpl->mController.GetGL();
925     gl.DepthMask(depthWriteEnable);
926   }
927 }
928
929 void Context::ActiveTexture(uint32_t textureBindingIndex)
930 {
931   if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
932   {
933     mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
934
935     auto& gl = *mImpl->mController.GetGL();
936     gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
937   }
938 }
939
940 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
941 {
942   uint32_t typeId = static_cast<uint32_t>(textureTypeId);
943   if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
944   {
945     mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
946
947     auto& gl = *mImpl->mController.GetGL();
948     gl.BindTexture(target, textureId);
949   }
950 }
951
952 void Context::GenerateMipmap(GLenum target)
953 {
954   auto& gl = *mImpl->mController.GetGL();
955   gl.GenerateMipmap(target);
956 }
957
958 void Context::BindBuffer(GLenum target, uint32_t bufferId)
959 {
960   switch(target)
961   {
962     case GL_ARRAY_BUFFER:
963     {
964       if(mImpl->mGlStateCache.mBoundArrayBufferId == bufferId)
965       {
966         return;
967       }
968       mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
969       break;
970     }
971     case GL_ELEMENT_ARRAY_BUFFER:
972     {
973       if(mImpl->mGlStateCache.mBoundElementArrayBufferId == bufferId)
974       {
975         return;
976       }
977       mImpl->mGlStateCache.mBoundElementArrayBufferId = bufferId;
978       break;
979     }
980   }
981
982   // Cache miss. Bind buffer.
983   auto& gl = *mImpl->mController.GetGL();
984   gl.BindBuffer(target, bufferId);
985 }
986
987 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
988 {
989   mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
990                                                             mImpl->mGlStateCache.DepthBufferWriteEnabled(),
991                                                             mImpl->mGlStateCache.StencilBufferWriteEnabled());
992
993   auto& gl = *mImpl->mController.GetGL();
994   gl.DrawBuffers(count, buffers);
995 }
996
997 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
998 {
999   mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
1000
1001   auto& gl = *mImpl->mController.GetGL();
1002   gl.BindFramebuffer(target, bufferId);
1003 }
1004
1005 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
1006 {
1007   auto& gl = *mImpl->mController.GetGL();
1008   gl.GenFramebuffers(count, framebuffers);
1009
1010   mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
1011 }
1012
1013 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
1014 {
1015   mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
1016
1017   auto& gl = *mImpl->mController.GetGL();
1018   gl.DeleteFramebuffers(count, framebuffers);
1019 }
1020
1021 GLStateCache& Context::GetGLStateCache()
1022 {
1023   return mImpl->mGlStateCache;
1024 }
1025
1026 void Context::GlContextCreated()
1027 {
1028   if(!mImpl->mGlContextCreated)
1029   {
1030     mImpl->mGlContextCreated = true;
1031
1032     // Set the initial GL state
1033     mImpl->InitializeGlState();
1034   }
1035 }
1036
1037 void Context::GlContextDestroyed()
1038 {
1039   mImpl->mGlContextCreated = false;
1040 }
1041
1042 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
1043 {
1044   // Since the pipeline is deleted, invalidate the cached pipeline.
1045   if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
1046   {
1047     mImpl->mCurrentPipeline = nullptr;
1048   }
1049
1050   // Remove cached VAO map
1051   auto* gl = mImpl->mController.GetGL();
1052   if(gl)
1053   {
1054     const auto* program = pipeline->GetCreateInfo().programState->program;
1055     if(program)
1056     {
1057       const auto* programImpl = static_cast<const GLES::Program*>(program)->GetImplementation();
1058       if(programImpl)
1059       {
1060         auto iter = mImpl->mProgramVAOMap.find(programImpl);
1061         if(iter != mImpl->mProgramVAOMap.end())
1062         {
1063           for(auto& attributeHashPair : iter->second)
1064           {
1065             auto vao = attributeHashPair.second;
1066             gl->DeleteVertexArrays(1, &vao);
1067             if(mImpl->mProgramVAOCurrentState == vao)
1068             {
1069               mImpl->mProgramVAOCurrentState = 0u;
1070             }
1071           }
1072           mImpl->mProgramVAOMap.erase(iter);
1073         }
1074       }
1075     }
1076   }
1077 }
1078
1079 void Context::PrepareForNativeRendering()
1080 {
1081   // this should be pretty much constant
1082   auto display     = eglGetCurrentDisplay();
1083   auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
1084   auto readSurface = eglGetCurrentSurface(EGL_READ);
1085   auto context     = eglGetCurrentContext();
1086
1087   // push the surface and context data to the impl
1088   // It's needed to restore context
1089   if(!mImpl->mCacheEGLGraphicsContext)
1090   {
1091     mImpl->mCacheDrawWriteSurface   = drawSurface;
1092     mImpl->mCacheDrawReadSurface    = readSurface;
1093     mImpl->mCacheEGLGraphicsContext = context;
1094   }
1095
1096   if(!mImpl->mNativeDrawContext)
1097   {
1098     EGLint configId{0u};
1099     eglQueryContext(display, mImpl->mController.GetSharedContext(), EGL_CONFIG_ID, &configId);
1100
1101     EGLint configAttribs[3];
1102     configAttribs[0] = EGL_CONFIG_ID;
1103     configAttribs[1] = configId;
1104     configAttribs[2] = EGL_NONE;
1105
1106     EGLConfig config;
1107     EGLint    numConfigs;
1108     if(eglChooseConfig(display, configAttribs, &config, 1, &numConfigs) != EGL_TRUE)
1109     {
1110       DALI_LOG_ERROR("eglChooseConfig failed!\n");
1111       return;
1112     }
1113
1114     auto version = int(mImpl->mController.GetGLESVersion());
1115
1116     std::vector<EGLint> attribs;
1117     attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1118     attribs.push_back(version / 10);
1119     attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1120     attribs.push_back(version % 10);
1121     attribs.push_back(EGL_NONE);
1122
1123     mImpl->mNativeDrawContext = eglCreateContext(display, config, mImpl->mController.GetSharedContext(), attribs.data());
1124     if(mImpl->mNativeDrawContext == EGL_NO_CONTEXT)
1125     {
1126       DALI_LOG_ERROR("eglCreateContext failed!\n");
1127       return;
1128     }
1129   }
1130
1131   eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1132 }
1133
1134 void Context::RestoreFromNativeRendering()
1135 {
1136   auto display = eglGetCurrentDisplay();
1137
1138   // bring back original context
1139   eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1140 }
1141
1142 } // namespace Dali::Graphics::GLES