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>
23 #include <dali/public-api/math/math-utils.h>
25 #include "egl-graphics-controller.h"
26 #include "gles-graphics-buffer.h"
27 #include "gles-graphics-pipeline.h"
28 #include "gles-graphics-program.h"
29 #include "gles-graphics-render-pass.h"
30 #include "gles-graphics-render-target.h"
33 #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 GLES::Program* program{nullptr};
598 if(mImpl->mNewPipeline)
600 program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
602 else if(mImpl->mCurrentPipeline)
604 program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
609 const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
610 // Update program uniforms
611 program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
615 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
617 auto& renderPass = *renderPassBegin.renderPass;
618 auto& renderTarget = *renderPassBegin.renderTarget;
620 const auto& targetInfo = renderTarget.GetCreateInfo();
622 auto& gl = *mImpl->mController.GetGL();
624 if(targetInfo.surface)
627 BindFrameBuffer(GL_FRAMEBUFFER, 0);
629 else if(targetInfo.framebuffer)
631 // bind framebuffer and swap.
632 renderTarget.GetFramebuffer()->Bind();
635 // clear (ideally cache the setup)
637 // In GL we assume that the last attachment is depth/stencil (we may need
638 // to cache extra information inside GLES RenderTarget if we want to be
639 // more specific in case of MRT)
641 const auto& attachments = *renderPass.GetCreateInfo().attachments;
642 const auto& color0 = attachments[0];
644 if(color0.loadOp == AttachmentLoadOp::CLEAR)
646 mask |= GL_COLOR_BUFFER_BIT;
649 // Something goes wrong here if Alpha mask is GL_TRUE
652 const auto clearValues = renderPassBegin.clearValues.Ptr();
654 if(!Dali::Equals(mImpl->mGlStateCache.mClearColor.r, clearValues[0].color.r) ||
655 !Dali::Equals(mImpl->mGlStateCache.mClearColor.g, clearValues[0].color.g) ||
656 !Dali::Equals(mImpl->mGlStateCache.mClearColor.b, clearValues[0].color.b) ||
657 !Dali::Equals(mImpl->mGlStateCache.mClearColor.a, clearValues[0].color.a) ||
658 !mImpl->mGlStateCache.mClearColorSet)
660 gl.ClearColor(clearValues[0].color.r,
661 clearValues[0].color.g,
662 clearValues[0].color.b,
663 clearValues[0].color.a);
665 mImpl->mGlStateCache.mClearColorSet = true;
666 mImpl->mGlStateCache.mClearColor = Vector4(clearValues[0].color.r,
667 clearValues[0].color.g,
668 clearValues[0].color.b,
669 clearValues[0].color.a);
673 // check for depth stencil
674 if(attachments.size() > 1)
676 const auto& depthStencil = attachments.back();
677 if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
679 if(!mImpl->mGlStateCache.mDepthMaskEnabled)
681 mImpl->mGlStateCache.mDepthMaskEnabled = true;
684 mask |= GL_DEPTH_BUFFER_BIT;
686 if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
688 if(mImpl->mGlStateCache.mStencilMask != 0xFF)
690 mImpl->mGlStateCache.mStencilMask = 0xFF;
691 gl.StencilMask(0xFF);
693 mask |= GL_STENCIL_BUFFER_BIT;
697 SetScissorTestEnabled(true);
698 gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
699 ClearBuffer(mask, true);
700 SetScissorTestEnabled(false);
702 mImpl->mCurrentRenderPass = &renderPass;
703 mImpl->mCurrentRenderTarget = &renderTarget;
706 void Context::EndRenderPass()
708 if(mImpl->mCurrentRenderTarget)
710 if(mImpl->mCurrentRenderTarget->GetFramebuffer())
712 auto& gl = *mImpl->mController.GetGL();
718 void Context::ClearState()
720 mImpl->mCurrentTextureBindings.clear();
723 void Context::ColorMask(bool enabled)
725 if(enabled != mImpl->mGlStateCache.mColorMask)
727 mImpl->mGlStateCache.mColorMask = enabled;
729 auto& gl = *mImpl->mController.GetGL();
730 gl.ColorMask(enabled, enabled, enabled, enabled);
734 void Context::ClearStencilBuffer()
736 ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
739 void Context::ClearDepthBuffer()
741 ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
744 void Context::ClearBuffer(uint32_t mask, bool forceClear)
746 mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
749 auto& gl = *mImpl->mController.GetGL();
754 void Context::InvalidateDepthStencilBuffers()
756 auto& gl = *mImpl->mController.GetGL();
758 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
759 gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
762 void Context::SetScissorTestEnabled(bool scissorEnabled)
764 if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
766 mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
768 auto& gl = *mImpl->mController.GetGL();
771 gl.Enable(GL_SCISSOR_TEST);
775 gl.Disable(GL_SCISSOR_TEST);
780 void Context::SetStencilTestEnable(bool stencilEnable)
782 if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
784 mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
786 auto& gl = *mImpl->mController.GetGL();
789 gl.Enable(GL_STENCIL_TEST);
793 gl.Disable(GL_STENCIL_TEST);
798 void Context::StencilMask(uint32_t writeMask)
800 if(writeMask != mImpl->mGlStateCache.mStencilMask)
802 mImpl->mGlStateCache.mStencilMask = writeMask;
804 auto& gl = *mImpl->mController.GetGL();
805 gl.StencilMask(writeMask);
809 void Context::StencilFunc(Graphics::CompareOp compareOp,
811 uint32_t compareMask)
813 if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
814 reference != mImpl->mGlStateCache.mStencilFuncRef ||
815 compareMask != mImpl->mGlStateCache.mStencilFuncMask)
817 mImpl->mGlStateCache.mStencilFunc = compareOp;
818 mImpl->mGlStateCache.mStencilFuncRef = reference;
819 mImpl->mGlStateCache.mStencilFuncMask = compareMask;
821 auto& gl = *mImpl->mController.GetGL();
822 gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
826 void Context::StencilOp(Graphics::StencilOp failOp,
827 Graphics::StencilOp depthFailOp,
828 Graphics::StencilOp passOp)
830 if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
831 depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
832 passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
834 mImpl->mGlStateCache.mStencilOpFail = failOp;
835 mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
836 mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
838 auto& gl = *mImpl->mController.GetGL();
839 gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
843 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
845 if(compareOp != mImpl->mGlStateCache.mDepthFunction)
847 mImpl->mGlStateCache.mDepthFunction = compareOp;
848 auto& gl = *mImpl->mController.GetGL();
849 gl.DepthFunc(GLCompareOp(compareOp).op);
853 void Context::SetDepthTestEnable(bool depthTestEnable)
855 if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
857 mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
859 auto& gl = *mImpl->mController.GetGL();
862 gl.Enable(GL_DEPTH_TEST);
866 gl.Disable(GL_DEPTH_TEST);
871 void Context::SetDepthWriteEnable(bool depthWriteEnable)
873 if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
875 mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
877 auto& gl = *mImpl->mController.GetGL();
878 gl.DepthMask(depthWriteEnable);
882 void Context::ActiveTexture(uint32_t textureBindingIndex)
884 if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
886 mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
888 auto& gl = *mImpl->mController.GetGL();
889 gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
893 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
895 uint32_t typeId = static_cast<uint32_t>(textureTypeId);
896 if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
898 mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
900 auto& gl = *mImpl->mController.GetGL();
901 gl.BindTexture(target, textureId);
905 void Context::GenerateMipmap(GLenum target)
907 auto& gl = *mImpl->mController.GetGL();
908 gl.GenerateMipmap(target);
911 void Context::BindBuffer(GLenum target, uint32_t bufferId)
913 if(mImpl->mGlStateCache.mBoundArrayBufferId != bufferId)
915 mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
917 auto& gl = *mImpl->mController.GetGL();
918 gl.BindBuffer(target, bufferId);
922 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
924 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
925 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
926 mImpl->mGlStateCache.StencilBufferWriteEnabled());
928 auto& gl = *mImpl->mController.GetGL();
929 gl.DrawBuffers(count, buffers);
932 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
934 mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
936 auto& gl = *mImpl->mController.GetGL();
937 gl.BindFramebuffer(target, bufferId);
940 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
942 auto& gl = *mImpl->mController.GetGL();
943 gl.GenFramebuffers(count, framebuffers);
945 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
948 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
950 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
952 auto& gl = *mImpl->mController.GetGL();
953 gl.DeleteFramebuffers(count, framebuffers);
956 GLStateCache& Context::GetGLStateCache()
958 return mImpl->mGlStateCache;
961 void Context::GlContextCreated()
963 if(!mImpl->mGlContextCreated)
965 mImpl->mGlContextCreated = true;
967 // Set the initial GL state
968 mImpl->InitializeGlState();
972 void Context::GlContextDestroyed()
974 mImpl->mGlContextCreated = false;
977 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
979 // Since the pipeline is deleted, invalidate the cached pipeline.
980 if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
982 mImpl->mCurrentPipeline = nullptr;
986 void Context::PrepareForNativeRendering()
988 // this should be pretty much constant
989 auto display = eglGetCurrentDisplay();
990 auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
991 auto readSurface = eglGetCurrentSurface(EGL_READ);
992 auto context = eglGetCurrentContext();
994 // push the surface and context data to the impl
995 // It's needed to restore context
996 if(!mImpl->mCacheEGLGraphicsContext)
998 mImpl->mCacheDrawWriteSurface = drawSurface;
999 mImpl->mCacheDrawReadSurface = readSurface;
1000 mImpl->mCacheEGLGraphicsContext = context;
1003 if(!mImpl->mNativeDrawContext)
1005 EGLint configId{0u};
1007 eglGetConfigs(display, nullptr, 0, &size);
1008 std::vector<EGLConfig> configs;
1009 configs.resize(size);
1010 eglGetConfigs(display, configs.data(), configs.size(), &size);
1012 eglQueryContext(display, context, EGL_CONFIG_ID, &configId);
1014 auto version = int(mImpl->mController.GetGLESVersion());
1016 std::vector<EGLint> attribs;
1017 attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1018 attribs.push_back(version / 10);
1019 attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1020 attribs.push_back(version % 10);
1021 attribs.push_back(EGL_NONE);
1023 mImpl->mNativeDrawContext = eglCreateContext(display, configs[configId], mImpl->mController.GetSharedContext(), attribs.data());
1026 eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1029 void Context::RestoreFromNativeRendering()
1031 auto display = eglGetCurrentDisplay();
1033 // bring back original context
1034 eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1037 } // namespace Dali::Graphics::GLES