2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "gles-context.h"
19 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
20 #include <dali/integration-api/gl-abstraction.h>
21 #include <dali/integration-api/gl-defines.h>
22 #include <dali/internal/graphics/common/graphics-interface.h>
24 #include "egl-graphics-controller.h"
25 #include "gles-graphics-buffer.h"
26 #include "gles-graphics-pipeline.h"
27 #include "gles-graphics-program.h"
28 #include "gles-graphics-render-pass.h"
29 #include "gles-graphics-render-target.h"
32 #include <EGL/eglext.h>
36 namespace Dali::Graphics::GLES
40 explicit Impl(EglGraphicsController& controller)
41 : mController(controller)
48 * Binds (and creates) VAO
50 * VAO is fixed per program so it has to be created only once assuming
51 * that VertexInputState has been set correctly for the pipeline.
54 void BindProgramVAO(GLES::ProgramImpl* program, const VertexInputState& vertexInputState)
56 auto& gl = *mController.GetGL();
57 auto iter = mProgramVAOMap.find(program);
58 if(iter != mProgramVAOMap.end())
60 if(mProgramVAOCurrentState != iter->second)
62 mProgramVAOCurrentState = iter->second;
63 gl.BindVertexArray(iter->second);
69 gl.GenVertexArrays(1, &vao);
70 gl.BindVertexArray(vao);
71 mProgramVAOMap[program] = vao;
72 for(const auto& attr : vertexInputState.attributes)
74 gl.EnableVertexAttribArray(attr.location);
77 mProgramVAOCurrentState = vao;
81 * Sets the initial GL state.
83 void InitializeGlState()
85 auto& gl = *mController.GetGL();
87 mGlStateCache.mClearColorSet = false;
88 mGlStateCache.mColorMask = true;
89 mGlStateCache.mStencilMask = 0xFF;
90 mGlStateCache.mBlendEnabled = false;
91 mGlStateCache.mDepthBufferEnabled = false;
92 mGlStateCache.mDepthMaskEnabled = false;
93 mGlStateCache.mScissorTestEnabled = false;
94 mGlStateCache.mStencilBufferEnabled = false;
96 gl.Disable(GL_DITHER);
98 mGlStateCache.mBoundArrayBufferId = 0;
99 mGlStateCache.mBoundElementArrayBufferId = 0;
100 mGlStateCache.mActiveTextureUnit = 0;
102 mGlStateCache.mBlendFuncSeparateSrcRGB = BlendFactor::ONE;
103 mGlStateCache.mBlendFuncSeparateDstRGB = BlendFactor::ZERO;
104 mGlStateCache.mBlendFuncSeparateSrcAlpha = BlendFactor::ONE;
105 mGlStateCache.mBlendFuncSeparateDstAlpha = BlendFactor::ZERO;
107 // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
108 mGlStateCache.mBlendEquationSeparateModeRGB = BlendOp::ADD;
109 mGlStateCache.mBlendEquationSeparateModeAlpha = BlendOp::ADD;
111 mGlStateCache.mCullFaceMode = CullMode::NONE; //By default cullface is disabled, front face is set to CCW and cull face is set to back
113 //Initialze vertex attribute cache
114 memset(&mGlStateCache.mVertexAttributeCachedState, 0, sizeof(mGlStateCache.mVertexAttributeCachedState));
115 memset(&mGlStateCache.mVertexAttributeCurrentState, 0, sizeof(mGlStateCache.mVertexAttributeCurrentState));
117 //Initialize bound 2d texture cache
118 memset(&mGlStateCache.mBoundTextureId, 0, sizeof(mGlStateCache.mBoundTextureId));
120 mGlStateCache.mFrameBufferStateCache.Reset();
124 * Flushes vertex attribute location changes to the driver
126 void FlushVertexAttributeLocations()
128 auto& gl = *mController.GetGL();
130 for(unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i)
132 // see if the cached state is different to the actual state
133 if(mGlStateCache.mVertexAttributeCurrentState[i] != mGlStateCache.mVertexAttributeCachedState[i])
135 // it's different so make the change to the driver and update the cached state
136 mGlStateCache.mVertexAttributeCurrentState[i] = mGlStateCache.mVertexAttributeCachedState[i];
138 if(mGlStateCache.mVertexAttributeCurrentState[i])
140 gl.EnableVertexAttribArray(i);
144 gl.DisableVertexAttribArray(i);
151 * Either enables or disables a vertex attribute location in the cache
152 * The cahnges won't take affect until FlushVertexAttributeLocations is called
153 * @param location attribute location
154 * @param state attribute state
156 void SetVertexAttributeLocation(unsigned int location, bool state)
158 auto& gl = *mController.GetGL();
160 if(location >= MAX_ATTRIBUTE_CACHE_SIZE)
162 // not cached, make the gl call through context
165 gl.EnableVertexAttribArray(location);
169 gl.DisableVertexAttribArray(location);
174 // set the cached state, it will be set at the next draw call
175 // if it's different from the current driver state
176 mGlStateCache.mVertexAttributeCachedState[location] = state;
180 EglGraphicsController& mController;
182 const GLES::PipelineImpl* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
183 const GLES::PipelineImpl* mNewPipeline{nullptr}; ///< New pipeline to be set on flush
185 std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
186 std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
187 GLES::IndexBufferBindingDescriptor mCurrentIndexBufferBinding{};
189 struct VertexBufferBinding
191 GLES::Buffer* buffer{nullptr};
195 // Currently bound buffers
196 std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
198 // Currently bound UBOs (check if it's needed per program!)
199 std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
200 UniformBufferBindingDescriptor mCurrentStandaloneUBOBinding{};
202 // Current render pass and render target
203 const GLES::RenderTarget* mCurrentRenderTarget{nullptr};
204 const GLES::RenderPass* mCurrentRenderPass{nullptr};
206 // Each context must have own VAOs as they cannot be shared
207 std::map<GLES::ProgramImpl*, uint32_t> mProgramVAOMap; ///< GL program-VAO map
208 uint32_t mProgramVAOCurrentState{0u}; ///< Currently bound VAO
209 GLStateCache mGlStateCache{}; ///< GL status cache
211 bool mGlContextCreated{false}; ///< True if the OpenGL context has been created
213 EGLContext mNativeDrawContext{0u}; ///< Native rendering EGL context compatible with window context
215 EGLSurface mCacheDrawReadSurface{0u}; ///< cached 'read' surface
216 EGLSurface mCacheDrawWriteSurface{0u}; ///< cached 'write' surface
217 EGLContext mCacheEGLGraphicsContext{0u}; ///< cached window context
220 Context::Context(EglGraphicsController& controller)
222 mImpl = std::make_unique<Impl>(controller);
227 // Destroy native rendering context if one exists
228 if(mImpl->mNativeDrawContext)
230 eglDestroyContext(eglGetCurrentDisplay(), mImpl->mNativeDrawContext);
231 mImpl->mNativeDrawContext = EGL_NO_CONTEXT;
235 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall)
237 auto& gl = *mImpl->mController.GetGL();
239 static const bool hasGLES3(mImpl->mController.GetGLESVersion() >= GLESVersion::GLES_30);
241 // early out if neither current nor new pipelines are set
242 // this behaviour may be valid so no assert
243 if(!mImpl->mCurrentPipeline && !mImpl->mNewPipeline)
248 // Execute states if pipeline is changed
249 const auto currentProgram = mImpl->mCurrentPipeline ? static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program) : nullptr;
251 // case when new pipeline has been set
252 const GLES::Program* newProgram = nullptr;
254 if(mImpl->mNewPipeline)
256 newProgram = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
259 if(mImpl->mNewPipeline && mImpl->mCurrentPipeline != mImpl->mNewPipeline)
261 if(!currentProgram || currentProgram->GetImplementation()->GetGlProgram() != newProgram->GetImplementation()->GetGlProgram())
263 mImpl->mNewPipeline->Bind(newProgram->GetImplementation()->GetGlProgram());
269 // Resolve rasterization state
270 ResolveRasterizationState();
273 // Resolve uniform buffers
274 ResolveUniformBuffers();
277 // Map binding# to sampler location
278 const auto& reflection = !newProgram ? currentProgram->GetReflection() : newProgram->GetReflection();
279 const auto& samplers = reflection.GetSamplers();
280 for(const auto& binding : mImpl->mCurrentTextureBindings)
282 auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
284 // Texture may not have been initialized yet...(tbm_surface timing issue?)
285 if(!texture->GetGLTexture())
287 // Attempt to reinitialize
288 // @todo need to put this somewhere else where it isn't const.
289 // Maybe post it back on end of initialize queue if initialization fails?
290 texture->InitializeResource();
293 texture->Bind(binding);
295 texture->Prepare(); // @todo also non-const.
297 if(binding.binding < samplers.size()) // binding maps to texture unit. (texture bindings should also be in binding order)
299 // Offset is set to the lexical offset within the frag shader, map it to the texture unit
300 // @todo Explicitly set the texture unit through the graphics interface
301 gl.Uniform1i(samplers[binding.binding].location, samplers[binding.binding].offset);
305 // for each attribute bind vertices
307 const auto& pipelineState = mImpl->mNewPipeline ? mImpl->mNewPipeline->GetCreateInfo() : mImpl->mCurrentPipeline->GetCreateInfo();
308 const auto& vertexInputState = pipelineState.vertexInputState;
312 mImpl->BindProgramVAO(static_cast<const GLES::Program*>(pipelineState.programState->program)->GetImplementation(), *vertexInputState);
315 for(const auto& attr : vertexInputState->attributes)
320 mImpl->SetVertexAttributeLocation(attr.location, true);
323 const auto& bufferSlot = mImpl->mCurrentVertexBufferBindings[attr.binding];
324 const auto& bufferBinding = vertexInputState->bufferBindings[attr.binding];
326 auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
329 BindBuffer(GL_ARRAY_BUFFER, glesBuffer);
331 gl.VertexAttribPointer(attr.location,
332 GLVertexFormat(attr.format).size,
333 GLVertexFormat(attr.format).format,
335 bufferBinding.stride,
336 reinterpret_cast<void*>(attr.offset));
340 const auto& ia = pipelineState.inputAssemblyState;
345 switch(drawCall.type)
347 case DrawCallDescriptor::Type::DRAW:
349 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
350 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
351 mImpl->mGlStateCache.StencilBufferWriteEnabled());
352 // For GLES3+ we use VAO, for GLES2 internal cache
355 mImpl->FlushVertexAttributeLocations();
358 gl.DrawArrays(GLESTopology(ia->topology),
359 drawCall.draw.firstVertex,
360 drawCall.draw.vertexCount);
363 case DrawCallDescriptor::Type::DRAW_INDEXED:
365 const auto& binding = mImpl->mCurrentIndexBufferBinding;
366 BindBuffer(GL_ELEMENT_ARRAY_BUFFER, binding.buffer->GetGLBuffer());
368 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
369 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
370 mImpl->mGlStateCache.StencilBufferWriteEnabled());
372 // For GLES3+ we use VAO, for GLES2 internal cache
375 mImpl->FlushVertexAttributeLocations();
378 auto indexBufferFormat = GLIndexFormat(binding.format).format;
379 gl.DrawElements(GLESTopology(ia->topology),
380 drawCall.drawIndexed.indexCount,
382 reinterpret_cast<void*>(binding.offset));
385 case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
394 if(mImpl->mNewPipeline)
396 mImpl->mCurrentPipeline = mImpl->mNewPipeline;
397 mImpl->mNewPipeline = nullptr;
401 void Context::BindTextures(const Graphics::TextureBinding* bindings, uint32_t count)
403 // for each texture allocate slot
404 for(auto i = 0u; i < count; ++i)
406 auto& binding = bindings[i];
408 // Resize binding array if needed
409 if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
411 mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
413 // Store the binding details
414 mImpl->mCurrentTextureBindings[binding.binding] = binding;
418 void Context::BindVertexBuffers(const GLES::VertexBufferBindingDescriptor* bindings, uint32_t count)
420 if(count > mImpl->mCurrentVertexBufferBindings.size())
422 mImpl->mCurrentVertexBufferBindings.resize(count);
424 // Copy only set slots
425 std::copy_if(bindings, bindings + count, mImpl->mCurrentVertexBufferBindings.begin(), [](auto& item) {
426 return (nullptr != item.buffer);
430 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
432 mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
435 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
437 DALI_ASSERT_ALWAYS(newPipeline && "Invalid pipeline");
438 mImpl->mNewPipeline = &newPipeline->GetPipeline();
441 void Context::BindUniformBuffers(const UniformBufferBindingDescriptor* uboBindings,
443 const UniformBufferBindingDescriptor& standaloneBindings)
445 if(standaloneBindings.buffer)
447 mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
450 if(uboCount >= mImpl->mCurrentUBOBindings.size())
452 mImpl->mCurrentUBOBindings.resize(uboCount + 1);
455 auto it = uboBindings;
456 for(auto i = 0u; i < uboCount; ++i)
460 mImpl->mCurrentUBOBindings[i] = *it;
465 void Context::ResolveBlendState()
467 const auto& currentBlendState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().colorBlendState : nullptr;
468 const auto& newBlendState = mImpl->mNewPipeline->GetCreateInfo().colorBlendState;
470 // TODO: prevent leaking the state
476 auto& gl = *mImpl->mController.GetGL();
478 if(!currentBlendState || currentBlendState->blendEnable != newBlendState->blendEnable)
480 if(newBlendState->blendEnable != mImpl->mGlStateCache.mBlendEnabled)
482 mImpl->mGlStateCache.mBlendEnabled = newBlendState->blendEnable;
483 newBlendState->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
487 if(!newBlendState->blendEnable)
492 BlendFactor newSrcRGB(newBlendState->srcColorBlendFactor);
493 BlendFactor newDstRGB(newBlendState->dstColorBlendFactor);
494 BlendFactor newSrcAlpha(newBlendState->srcAlphaBlendFactor);
495 BlendFactor newDstAlpha(newBlendState->dstAlphaBlendFactor);
497 if(!currentBlendState ||
498 currentBlendState->srcColorBlendFactor != newSrcRGB ||
499 currentBlendState->dstColorBlendFactor != newDstRGB ||
500 currentBlendState->srcAlphaBlendFactor != newSrcAlpha ||
501 currentBlendState->dstAlphaBlendFactor != newDstAlpha)
503 if((mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB != newSrcRGB) ||
504 (mImpl->mGlStateCache.mBlendFuncSeparateDstRGB != newDstRGB) ||
505 (mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha != newSrcAlpha) ||
506 (mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha != newDstAlpha))
508 mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB = newSrcRGB;
509 mImpl->mGlStateCache.mBlendFuncSeparateDstRGB = newDstRGB;
510 mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha = newSrcAlpha;
511 mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha = newDstAlpha;
513 if(newSrcRGB == newSrcAlpha && newDstRGB == newDstAlpha)
515 gl.BlendFunc(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB));
519 gl.BlendFuncSeparate(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB), GLBlendFunc(newSrcAlpha), GLBlendFunc(newDstAlpha));
524 if(!currentBlendState ||
525 currentBlendState->colorBlendOp != newBlendState->colorBlendOp ||
526 currentBlendState->alphaBlendOp != newBlendState->alphaBlendOp)
528 if(mImpl->mGlStateCache.mBlendEquationSeparateModeRGB != newBlendState->colorBlendOp ||
529 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha != newBlendState->alphaBlendOp)
531 mImpl->mGlStateCache.mBlendEquationSeparateModeRGB = newBlendState->colorBlendOp;
532 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha = newBlendState->alphaBlendOp;
534 if(newBlendState->colorBlendOp == newBlendState->alphaBlendOp)
536 gl.BlendEquation(GLBlendOp(newBlendState->colorBlendOp));
537 if(newBlendState->colorBlendOp >= Graphics::ADVANCED_BLEND_OPTIONS_START)
544 gl.BlendEquationSeparate(GLBlendOp(newBlendState->colorBlendOp), GLBlendOp(newBlendState->alphaBlendOp));
550 void Context::ResolveRasterizationState()
552 const auto& currentRasterizationState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().rasterizationState : nullptr;
553 const auto& newRasterizationState = mImpl->mNewPipeline->GetCreateInfo().rasterizationState;
555 // TODO: prevent leaking the state
556 if(!newRasterizationState)
561 auto& gl = *mImpl->mController.GetGL();
563 if(!currentRasterizationState ||
564 currentRasterizationState->cullMode != newRasterizationState->cullMode)
566 if(mImpl->mGlStateCache.mCullFaceMode != newRasterizationState->cullMode)
568 mImpl->mGlStateCache.mCullFaceMode = newRasterizationState->cullMode;
569 if(newRasterizationState->cullMode == CullMode::NONE)
571 gl.Disable(GL_CULL_FACE);
575 gl.Enable(GL_CULL_FACE);
576 gl.CullFace(GLCullMode(newRasterizationState->cullMode));
580 // TODO: implement polygon mode (fill, line, points)
581 // seems like we don't support it (no glPolygonMode())
584 void Context::ResolveUniformBuffers()
586 // Resolve standalone uniforms if we have binding
587 if(mImpl->mCurrentStandaloneUBOBinding.buffer)
589 ResolveStandaloneUniforms();
593 void Context::ResolveStandaloneUniforms()
595 // Find reflection for program
596 const auto program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
597 const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
599 // Update program uniforms
600 program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
603 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
605 auto& renderPass = *renderPassBegin.renderPass;
606 auto& renderTarget = *renderPassBegin.renderTarget;
608 const auto& targetInfo = renderTarget.GetCreateInfo();
610 auto& gl = *mImpl->mController.GetGL();
612 if(targetInfo.surface)
615 BindFrameBuffer(GL_FRAMEBUFFER, 0);
617 else if(targetInfo.framebuffer)
619 // bind framebuffer and swap.
620 renderTarget.GetFramebuffer()->Bind();
623 // clear (ideally cache the setup)
625 // In GL we assume that the last attachment is depth/stencil (we may need
626 // to cache extra information inside GLES RenderTarget if we want to be
627 // more specific in case of MRT)
629 const auto& attachments = *renderPass.GetCreateInfo().attachments;
630 const auto& color0 = attachments[0];
632 if(color0.loadOp == AttachmentLoadOp::CLEAR)
634 mask |= GL_COLOR_BUFFER_BIT;
637 // Something goes wrong here if Alpha mask is GL_TRUE
640 const auto clearValues = renderPassBegin.clearValues.Ptr();
642 if(!mImpl->mGlStateCache.mClearColorSet ||
643 mImpl->mGlStateCache.mClearColor.r != clearValues[0].color.r ||
644 mImpl->mGlStateCache.mClearColor.g != clearValues[0].color.g ||
645 mImpl->mGlStateCache.mClearColor.b != clearValues[0].color.b ||
646 mImpl->mGlStateCache.mClearColor.a != clearValues[0].color.a)
648 gl.ClearColor(clearValues[0].color.r,
649 clearValues[0].color.g,
650 clearValues[0].color.b,
651 clearValues[0].color.a);
653 mImpl->mGlStateCache.mClearColorSet = true;
654 mImpl->mGlStateCache.mClearColor = Vector4(clearValues[0].color.r,
655 clearValues[0].color.g,
656 clearValues[0].color.b,
657 clearValues[0].color.a);
661 // check for depth stencil
662 if(attachments.size() > 1)
664 const auto& depthStencil = attachments.back();
665 if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
667 if(!mImpl->mGlStateCache.mDepthMaskEnabled)
669 mImpl->mGlStateCache.mDepthMaskEnabled = true;
672 mask |= GL_DEPTH_BUFFER_BIT;
674 if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
676 if(mImpl->mGlStateCache.mStencilMask != 0xFF)
678 mImpl->mGlStateCache.mStencilMask = 0xFF;
679 gl.StencilMask(0xFF);
681 mask |= GL_STENCIL_BUFFER_BIT;
685 SetScissorTestEnabled(true);
686 gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
687 ClearBuffer(mask, true);
688 SetScissorTestEnabled(false);
690 mImpl->mCurrentRenderPass = &renderPass;
691 mImpl->mCurrentRenderTarget = &renderTarget;
694 void Context::EndRenderPass()
696 if(mImpl->mCurrentRenderTarget)
698 if(mImpl->mCurrentRenderTarget->GetFramebuffer())
700 auto& gl = *mImpl->mController.GetGL();
706 void Context::ClearState()
708 mImpl->mCurrentTextureBindings.clear();
711 void Context::ColorMask(bool enabled)
713 if(enabled != mImpl->mGlStateCache.mColorMask)
715 mImpl->mGlStateCache.mColorMask = enabled;
717 auto& gl = *mImpl->mController.GetGL();
718 gl.ColorMask(enabled, enabled, enabled, enabled);
722 void Context::ClearStencilBuffer()
724 ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
727 void Context::ClearDepthBuffer()
729 ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
732 void Context::ClearBuffer(uint32_t mask, bool forceClear)
734 mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
737 auto& gl = *mImpl->mController.GetGL();
742 void Context::InvalidateDepthStencilBuffers()
744 auto& gl = *mImpl->mController.GetGL();
746 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
747 gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
750 void Context::SetScissorTestEnabled(bool scissorEnabled)
752 if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
754 mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
756 auto& gl = *mImpl->mController.GetGL();
759 gl.Enable(GL_SCISSOR_TEST);
763 gl.Disable(GL_SCISSOR_TEST);
768 void Context::SetStencilTestEnable(bool stencilEnable)
770 if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
772 mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
774 auto& gl = *mImpl->mController.GetGL();
777 gl.Enable(GL_STENCIL_TEST);
781 gl.Disable(GL_STENCIL_TEST);
786 void Context::StencilMask(uint32_t writeMask)
788 if(writeMask != mImpl->mGlStateCache.mStencilMask)
790 mImpl->mGlStateCache.mStencilMask = writeMask;
792 auto& gl = *mImpl->mController.GetGL();
793 gl.StencilMask(writeMask);
797 void Context::StencilFunc(Graphics::CompareOp compareOp,
799 uint32_t compareMask)
801 if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
802 reference != mImpl->mGlStateCache.mStencilFuncRef ||
803 compareMask != mImpl->mGlStateCache.mStencilFuncMask)
805 mImpl->mGlStateCache.mStencilFunc = compareOp;
806 mImpl->mGlStateCache.mStencilFuncRef = reference;
807 mImpl->mGlStateCache.mStencilFuncMask = compareMask;
809 auto& gl = *mImpl->mController.GetGL();
810 gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
814 void Context::StencilOp(Graphics::StencilOp failOp,
815 Graphics::StencilOp depthFailOp,
816 Graphics::StencilOp passOp)
818 if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
819 depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
820 passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
822 mImpl->mGlStateCache.mStencilOpFail = failOp;
823 mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
824 mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
826 auto& gl = *mImpl->mController.GetGL();
827 gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
831 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
833 if(compareOp != mImpl->mGlStateCache.mDepthFunction)
835 mImpl->mGlStateCache.mDepthFunction = compareOp;
836 auto& gl = *mImpl->mController.GetGL();
837 gl.DepthFunc(GLCompareOp(compareOp).op);
841 void Context::SetDepthTestEnable(bool depthTestEnable)
843 if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
845 mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
847 auto& gl = *mImpl->mController.GetGL();
850 gl.Enable(GL_DEPTH_TEST);
854 gl.Disable(GL_DEPTH_TEST);
859 void Context::SetDepthWriteEnable(bool depthWriteEnable)
861 if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
863 mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
865 auto& gl = *mImpl->mController.GetGL();
866 gl.DepthMask(depthWriteEnable);
870 void Context::ActiveTexture(uint32_t textureBindingIndex)
872 if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
874 mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
876 auto& gl = *mImpl->mController.GetGL();
877 gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
881 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
883 uint32_t typeId = static_cast<uint32_t>(textureTypeId);
884 if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
886 mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
888 auto& gl = *mImpl->mController.GetGL();
889 gl.BindTexture(target, textureId);
893 void Context::GenerateMipmap(GLenum target)
895 auto& gl = *mImpl->mController.GetGL();
896 gl.GenerateMipmap(target);
899 void Context::BindBuffer(GLenum target, uint32_t bufferId)
901 if(mImpl->mGlStateCache.mBoundArrayBufferId != bufferId)
903 mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
905 auto& gl = *mImpl->mController.GetGL();
906 gl.BindBuffer(target, bufferId);
910 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
912 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
913 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
914 mImpl->mGlStateCache.StencilBufferWriteEnabled());
916 auto& gl = *mImpl->mController.GetGL();
917 gl.DrawBuffers(count, buffers);
920 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
922 mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
924 auto& gl = *mImpl->mController.GetGL();
925 gl.BindFramebuffer(target, bufferId);
928 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
930 auto& gl = *mImpl->mController.GetGL();
931 gl.GenFramebuffers(count, framebuffers);
933 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
936 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
938 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
940 auto& gl = *mImpl->mController.GetGL();
941 gl.DeleteFramebuffers(count, framebuffers);
944 GLStateCache& Context::GetGLStateCache()
946 return mImpl->mGlStateCache;
949 void Context::GlContextCreated()
951 if(!mImpl->mGlContextCreated)
953 mImpl->mGlContextCreated = true;
955 // Set the initial GL state
956 mImpl->InitializeGlState();
960 void Context::GlContextDestroyed()
962 mImpl->mGlContextCreated = false;
965 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
967 // Since the pipeline is deleted, invalidate the cached pipeline.
968 if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
970 mImpl->mCurrentPipeline = nullptr;
974 void Context::PrepareForNativeRendering()
976 // this should be pretty much constant
977 auto display = eglGetCurrentDisplay();
978 auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
979 auto readSurface = eglGetCurrentSurface(EGL_READ);
980 auto context = eglGetCurrentContext();
982 // push the surface and context data to the impl
983 // It's needed to restore context
984 if(!mImpl->mCacheEGLGraphicsContext)
986 mImpl->mCacheDrawWriteSurface = drawSurface;
987 mImpl->mCacheDrawReadSurface = readSurface;
988 mImpl->mCacheEGLGraphicsContext = context;
991 if(!mImpl->mNativeDrawContext)
995 eglGetConfigs(display, nullptr, 0, &size);
996 std::vector<EGLConfig> configs;
997 configs.resize(size);
998 eglGetConfigs(display, configs.data(), configs.size(), &size);
1000 eglQueryContext(display, context, EGL_CONFIG_ID, &configId);
1002 auto version = int(mImpl->mController.GetGLESVersion());
1004 std::vector<EGLint> attribs;
1005 attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1006 attribs.push_back(version / 10);
1007 attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1008 attribs.push_back(version % 10);
1009 attribs.push_back(EGL_NONE);
1011 mImpl->mNativeDrawContext = eglCreateContext(display, configs[configId], EGL_NO_CONTEXT, attribs.data());
1014 eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1017 void Context::RestoreFromNativeRendering()
1019 auto display = eglGetCurrentDisplay();
1021 // bring back original context
1022 eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1025 } // namespace Dali::Graphics::GLES