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/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>
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"
35 #include <EGL/eglext.h>
37 #include <unordered_map>
39 namespace Dali::Graphics::GLES
43 explicit Impl(EglGraphicsController& controller)
44 : mController(controller)
51 * Binds (and creates) VAO
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.
57 void BindProgramVAO(const GLES::ProgramImpl* program, const VertexInputState& vertexInputState)
59 // Calculate attributes location hash unordered.
61 for(const auto& attr : vertexInputState.attributes)
63 hash ^= std::hash<uint32_t>{}(attr.location);
66 auto& gl = *mController.GetGL();
67 auto iter = mProgramVAOMap.find(program);
68 if(iter != mProgramVAOMap.end())
70 auto attributeIter = iter->second.find(hash);
71 if(attributeIter != iter->second.end())
73 if(mProgramVAOCurrentState != attributeIter->second)
75 mProgramVAOCurrentState = attributeIter->second;
76 gl.BindVertexArray(attributeIter->second);
83 gl.GenVertexArrays(1, &vao);
84 gl.BindVertexArray(vao);
85 mProgramVAOMap[program][hash] = vao;
86 for(const auto& attr : vertexInputState.attributes)
88 gl.EnableVertexAttribArray(attr.location);
91 mProgramVAOCurrentState = vao;
95 * Sets the initial GL state.
97 void InitializeGlState()
99 auto& gl = *mController.GetGL();
101 mGlStateCache.mClearColorSet = false;
102 mGlStateCache.mColorMask = true;
103 mGlStateCache.mStencilMask = 0xFF;
104 mGlStateCache.mBlendEnabled = false;
105 mGlStateCache.mDepthBufferEnabled = false;
106 mGlStateCache.mDepthMaskEnabled = false;
107 mGlStateCache.mScissorTestEnabled = false;
108 mGlStateCache.mStencilBufferEnabled = false;
110 gl.Disable(GL_DITHER);
112 mGlStateCache.mBoundArrayBufferId = 0;
113 mGlStateCache.mBoundElementArrayBufferId = 0;
114 mGlStateCache.mActiveTextureUnit = 0;
116 mGlStateCache.mBlendFuncSeparateSrcRGB = BlendFactor::ONE;
117 mGlStateCache.mBlendFuncSeparateDstRGB = BlendFactor::ZERO;
118 mGlStateCache.mBlendFuncSeparateSrcAlpha = BlendFactor::ONE;
119 mGlStateCache.mBlendFuncSeparateDstAlpha = BlendFactor::ZERO;
121 // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
122 mGlStateCache.mBlendEquationSeparateModeRGB = BlendOp::ADD;
123 mGlStateCache.mBlendEquationSeparateModeAlpha = BlendOp::ADD;
125 mGlStateCache.mCullFaceMode = CullMode::NONE; //By default cullface is disabled, front face is set to CCW and cull face is set to back
127 //Initialze vertex attribute cache
128 memset(&mGlStateCache.mVertexAttributeCachedState, 0, sizeof(mGlStateCache.mVertexAttributeCachedState));
129 memset(&mGlStateCache.mVertexAttributeCurrentState, 0, sizeof(mGlStateCache.mVertexAttributeCurrentState));
131 //Initialize bound 2d texture cache
132 memset(&mGlStateCache.mBoundTextureId, 0, sizeof(mGlStateCache.mBoundTextureId));
134 mGlStateCache.mFrameBufferStateCache.Reset();
138 * Flushes vertex attribute location changes to the driver
140 void FlushVertexAttributeLocations()
142 auto& gl = *mController.GetGL();
144 for(unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i)
146 // see if the cached state is different to the actual state
147 if(mGlStateCache.mVertexAttributeCurrentState[i] != mGlStateCache.mVertexAttributeCachedState[i])
149 // it's different so make the change to the driver and update the cached state
150 mGlStateCache.mVertexAttributeCurrentState[i] = mGlStateCache.mVertexAttributeCachedState[i];
152 if(mGlStateCache.mVertexAttributeCurrentState[i])
154 gl.EnableVertexAttribArray(i);
158 gl.DisableVertexAttribArray(i);
165 * Either enables or disables a vertex attribute location in the cache
166 * The cahnges won't take affect until FlushVertexAttributeLocations is called
167 * @param location attribute location
168 * @param state attribute state
170 void SetVertexAttributeLocation(unsigned int location, bool state)
172 auto& gl = *mController.GetGL();
174 if(location >= MAX_ATTRIBUTE_CACHE_SIZE)
176 // not cached, make the gl call through context
179 gl.EnableVertexAttribArray(location);
183 gl.DisableVertexAttribArray(location);
188 // set the cached state, it will be set at the next draw call
189 // if it's different from the current driver state
190 mGlStateCache.mVertexAttributeCachedState[location] = state;
194 EglGraphicsController& mController;
196 const GLES::PipelineImpl* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
197 const GLES::PipelineImpl* mNewPipeline{nullptr}; ///< New pipeline to be set on flush
199 std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
200 std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
201 GLES::IndexBufferBindingDescriptor mCurrentIndexBufferBinding{};
203 struct VertexBufferBinding
205 GLES::Buffer* buffer{nullptr};
209 // Currently bound buffers
210 std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
212 // Currently bound UBOs (check if it's needed per program!)
213 std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
214 UniformBufferBindingDescriptor mCurrentStandaloneUBOBinding{};
216 // Current render pass and render target
217 const GLES::RenderTarget* mCurrentRenderTarget{nullptr};
218 const GLES::RenderPass* mCurrentRenderPass{nullptr};
220 // Each context must have own VAOs as they cannot be shared
221 std::unordered_map<const GLES::ProgramImpl*, std::map<std::size_t, uint32_t>> mProgramVAOMap; ///< GL program-VAO map
222 uint32_t mProgramVAOCurrentState{0u}; ///< Currently bound VAO
223 GLStateCache mGlStateCache{}; ///< GL status cache
225 bool mGlContextCreated{false}; ///< True if the OpenGL context has been created
227 EGLContext mNativeDrawContext{0u}; ///< Native rendering EGL context compatible with window context
229 EGLSurface mCacheDrawReadSurface{0u}; ///< cached 'read' surface
230 EGLSurface mCacheDrawWriteSurface{0u}; ///< cached 'write' surface
231 EGLContext mCacheEGLGraphicsContext{0u}; ///< cached window context
234 Context::Context(EglGraphicsController& controller)
236 mImpl = std::make_unique<Impl>(controller);
241 // Destroy native rendering context if one exists
242 if(mImpl->mNativeDrawContext)
244 eglDestroyContext(eglGetCurrentDisplay(), mImpl->mNativeDrawContext);
245 mImpl->mNativeDrawContext = EGL_NO_CONTEXT;
249 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall, GLES::TextureDependencyChecker& dependencyChecker)
251 auto& gl = *mImpl->mController.GetGL();
253 static const bool hasGLES3(mImpl->mController.GetGLESVersion() >= GLESVersion::GLES_30);
255 // early out if neither current nor new pipelines are set
256 // this behaviour may be valid so no assert
257 if(!mImpl->mCurrentPipeline && !mImpl->mNewPipeline)
262 // Execute states if pipeline is changed
263 const auto currentProgram = mImpl->mCurrentPipeline ? static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program) : nullptr;
265 // case when new pipeline has been set
266 const GLES::Program* newProgram = nullptr;
268 if(mImpl->mNewPipeline)
270 newProgram = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
273 if(!currentProgram && !newProgram)
275 // Early out if we have no program for this pipeline.
276 DALI_LOG_ERROR("No program defined for pipeline\n");
280 if(mImpl->mNewPipeline && mImpl->mCurrentPipeline != mImpl->mNewPipeline)
282 if(!currentProgram || currentProgram->GetImplementation()->GetGlProgram() != newProgram->GetImplementation()->GetGlProgram())
284 mImpl->mNewPipeline->Bind(newProgram->GetImplementation()->GetGlProgram());
290 // Resolve rasterization state
291 ResolveRasterizationState();
294 // Resolve uniform buffers
295 ResolveUniformBuffers();
298 // Map binding# to sampler location
299 const auto& reflection = !newProgram ? currentProgram->GetReflection() : newProgram->GetReflection();
300 const auto& samplers = reflection.GetSamplers();
301 for(const auto& binding : mImpl->mCurrentTextureBindings)
303 auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
305 // Texture may not have been initialized yet...(tbm_surface timing issue?)
306 if(!texture->GetGLTexture())
308 // Attempt to reinitialize
309 // @todo need to put this somewhere else where it isn't const.
310 // Maybe post it back on end of initialize queue if initialization fails?
311 texture->InitializeResource();
314 // Warning, this may cause glWaitSync to occur on the GPU.
315 dependencyChecker.CheckNeedsSync(this, texture);
317 texture->Bind(binding);
319 texture->Prepare(); // @todo also non-const.
321 if(binding.binding < samplers.size()) // binding maps to texture unit. (texture bindings should also be in binding order)
323 // Offset is set to the lexical offset within the frag shader, map it to the texture unit
324 // @todo Explicitly set the texture unit through the graphics interface
325 gl.Uniform1i(samplers[binding.binding].location, samplers[binding.binding].offset);
329 // for each attribute bind vertices
331 const auto& pipelineState = mImpl->mNewPipeline ? mImpl->mNewPipeline->GetCreateInfo() : mImpl->mCurrentPipeline->GetCreateInfo();
332 const auto& vertexInputState = pipelineState.vertexInputState;
336 mImpl->BindProgramVAO(static_cast<const GLES::Program*>(pipelineState.programState->program)->GetImplementation(), *vertexInputState);
339 for(const auto& attr : vertexInputState->attributes)
344 mImpl->SetVertexAttributeLocation(attr.location, true);
347 const auto& bufferSlot = mImpl->mCurrentVertexBufferBindings[attr.binding];
348 const auto& bufferBinding = vertexInputState->bufferBindings[attr.binding];
350 auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
353 BindBuffer(GL_ARRAY_BUFFER, glesBuffer);
355 gl.VertexAttribPointer(attr.location,
356 GLVertexFormat(attr.format).size,
357 GLVertexFormat(attr.format).format,
359 bufferBinding.stride,
360 reinterpret_cast<void*>(attr.offset));
364 const auto& ia = pipelineState.inputAssemblyState;
369 switch(drawCall.type)
371 case DrawCallDescriptor::Type::DRAW:
373 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
374 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
375 mImpl->mGlStateCache.StencilBufferWriteEnabled());
376 // For GLES3+ we use VAO, for GLES2 internal cache
379 mImpl->FlushVertexAttributeLocations();
382 gl.DrawArrays(GLESTopology(ia->topology),
383 drawCall.draw.firstVertex,
384 drawCall.draw.vertexCount);
387 case DrawCallDescriptor::Type::DRAW_INDEXED:
389 const auto& binding = mImpl->mCurrentIndexBufferBinding;
390 BindBuffer(GL_ELEMENT_ARRAY_BUFFER, binding.buffer->GetGLBuffer());
392 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
393 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
394 mImpl->mGlStateCache.StencilBufferWriteEnabled());
396 // For GLES3+ we use VAO, for GLES2 internal cache
399 mImpl->FlushVertexAttributeLocations();
402 auto indexBufferFormat = GLIndexFormat(binding.format).format;
403 gl.DrawElements(GLESTopology(ia->topology),
404 drawCall.drawIndexed.indexCount,
406 reinterpret_cast<void*>(binding.offset));
409 case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
418 if(mImpl->mNewPipeline)
420 mImpl->mCurrentPipeline = mImpl->mNewPipeline;
421 mImpl->mNewPipeline = nullptr;
425 void Context::BindTextures(const Graphics::TextureBinding* bindings, uint32_t count)
427 // for each texture allocate slot
428 for(auto i = 0u; i < count; ++i)
430 auto& binding = bindings[i];
432 // Resize binding array if needed
433 if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
435 mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
437 // Store the binding details
438 mImpl->mCurrentTextureBindings[binding.binding] = binding;
442 void Context::BindVertexBuffers(const GLES::VertexBufferBindingDescriptor* bindings, uint32_t count)
444 if(count > mImpl->mCurrentVertexBufferBindings.size())
446 mImpl->mCurrentVertexBufferBindings.resize(count);
448 // Copy only set slots
449 std::copy_if(bindings, bindings + count, mImpl->mCurrentVertexBufferBindings.begin(), [](auto& item) {
450 return (nullptr != item.buffer);
454 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
456 mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
459 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
461 DALI_ASSERT_ALWAYS(newPipeline && "Invalid pipeline");
462 mImpl->mNewPipeline = &newPipeline->GetPipeline();
465 void Context::BindUniformBuffers(const UniformBufferBindingDescriptor* uboBindings,
467 const UniformBufferBindingDescriptor& standaloneBindings)
469 if(standaloneBindings.buffer)
471 mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
474 if(uboCount >= mImpl->mCurrentUBOBindings.size())
476 mImpl->mCurrentUBOBindings.resize(uboCount + 1);
479 auto it = uboBindings;
480 for(auto i = 0u; i < uboCount; ++i)
484 mImpl->mCurrentUBOBindings[i] = *it;
489 void Context::ResolveBlendState()
491 const auto& currentBlendState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().colorBlendState : nullptr;
492 const auto& newBlendState = mImpl->mNewPipeline->GetCreateInfo().colorBlendState;
494 // TODO: prevent leaking the state
500 auto& gl = *mImpl->mController.GetGL();
502 if(!currentBlendState || currentBlendState->blendEnable != newBlendState->blendEnable)
504 if(newBlendState->blendEnable != mImpl->mGlStateCache.mBlendEnabled)
506 mImpl->mGlStateCache.mBlendEnabled = newBlendState->blendEnable;
507 newBlendState->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
511 if(!newBlendState->blendEnable)
516 BlendFactor newSrcRGB(newBlendState->srcColorBlendFactor);
517 BlendFactor newDstRGB(newBlendState->dstColorBlendFactor);
518 BlendFactor newSrcAlpha(newBlendState->srcAlphaBlendFactor);
519 BlendFactor newDstAlpha(newBlendState->dstAlphaBlendFactor);
521 if(!currentBlendState ||
522 currentBlendState->srcColorBlendFactor != newSrcRGB ||
523 currentBlendState->dstColorBlendFactor != newDstRGB ||
524 currentBlendState->srcAlphaBlendFactor != newSrcAlpha ||
525 currentBlendState->dstAlphaBlendFactor != newDstAlpha)
527 if((mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB != newSrcRGB) ||
528 (mImpl->mGlStateCache.mBlendFuncSeparateDstRGB != newDstRGB) ||
529 (mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha != newSrcAlpha) ||
530 (mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha != newDstAlpha))
532 mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB = newSrcRGB;
533 mImpl->mGlStateCache.mBlendFuncSeparateDstRGB = newDstRGB;
534 mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha = newSrcAlpha;
535 mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha = newDstAlpha;
537 if(newSrcRGB == newSrcAlpha && newDstRGB == newDstAlpha)
539 gl.BlendFunc(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB));
543 gl.BlendFuncSeparate(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB), GLBlendFunc(newSrcAlpha), GLBlendFunc(newDstAlpha));
548 if(!currentBlendState ||
549 currentBlendState->colorBlendOp != newBlendState->colorBlendOp ||
550 currentBlendState->alphaBlendOp != newBlendState->alphaBlendOp)
552 if(mImpl->mGlStateCache.mBlendEquationSeparateModeRGB != newBlendState->colorBlendOp ||
553 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha != newBlendState->alphaBlendOp)
555 mImpl->mGlStateCache.mBlendEquationSeparateModeRGB = newBlendState->colorBlendOp;
556 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha = newBlendState->alphaBlendOp;
558 if(newBlendState->colorBlendOp == newBlendState->alphaBlendOp)
560 gl.BlendEquation(GLBlendOp(newBlendState->colorBlendOp));
561 if(newBlendState->colorBlendOp >= Graphics::ADVANCED_BLEND_OPTIONS_START)
568 gl.BlendEquationSeparate(GLBlendOp(newBlendState->colorBlendOp), GLBlendOp(newBlendState->alphaBlendOp));
574 void Context::ResolveRasterizationState()
576 const auto& currentRasterizationState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().rasterizationState : nullptr;
577 const auto& newRasterizationState = mImpl->mNewPipeline->GetCreateInfo().rasterizationState;
579 // TODO: prevent leaking the state
580 if(!newRasterizationState)
585 auto& gl = *mImpl->mController.GetGL();
587 if(!currentRasterizationState ||
588 currentRasterizationState->cullMode != newRasterizationState->cullMode)
590 if(mImpl->mGlStateCache.mCullFaceMode != newRasterizationState->cullMode)
592 mImpl->mGlStateCache.mCullFaceMode = newRasterizationState->cullMode;
593 if(newRasterizationState->cullMode == CullMode::NONE)
595 gl.Disable(GL_CULL_FACE);
599 gl.Enable(GL_CULL_FACE);
600 gl.CullFace(GLCullMode(newRasterizationState->cullMode));
604 // TODO: implement polygon mode (fill, line, points)
605 // seems like we don't support it (no glPolygonMode())
608 void Context::ResolveUniformBuffers()
610 // Resolve standalone uniforms if we have binding
611 if(mImpl->mCurrentStandaloneUBOBinding.buffer)
613 ResolveStandaloneUniforms();
617 void Context::ResolveStandaloneUniforms()
619 // Find reflection for program
620 const GLES::Program* program{nullptr};
622 if(mImpl->mNewPipeline)
624 program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
626 else if(mImpl->mCurrentPipeline)
628 program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
633 const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
634 // Update program uniforms
635 program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
639 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
641 auto& renderPass = *renderPassBegin.renderPass;
642 auto& renderTarget = *renderPassBegin.renderTarget;
644 const auto& targetInfo = renderTarget.GetCreateInfo();
646 auto& gl = *mImpl->mController.GetGL();
648 if(targetInfo.surface)
651 BindFrameBuffer(GL_FRAMEBUFFER, 0);
653 else if(targetInfo.framebuffer)
655 // bind framebuffer and swap.
656 auto framebuffer = renderTarget.GetFramebuffer();
660 // clear (ideally cache the setup)
662 // In GL we assume that the last attachment is depth/stencil (we may need
663 // to cache extra information inside GLES RenderTarget if we want to be
664 // more specific in case of MRT)
666 const auto& attachments = *renderPass.GetCreateInfo().attachments;
667 const auto& color0 = attachments[0];
670 if(color0.loadOp == AttachmentLoadOp::CLEAR)
672 mask |= GL_COLOR_BUFFER_BIT;
675 // Something goes wrong here if Alpha mask is GL_TRUE
678 const auto clearValues = renderPassBegin.clearValues.Ptr();
680 if(!Dali::Equals(mImpl->mGlStateCache.mClearColor.r, clearValues[0].color.r) ||
681 !Dali::Equals(mImpl->mGlStateCache.mClearColor.g, clearValues[0].color.g) ||
682 !Dali::Equals(mImpl->mGlStateCache.mClearColor.b, clearValues[0].color.b) ||
683 !Dali::Equals(mImpl->mGlStateCache.mClearColor.a, clearValues[0].color.a) ||
684 !mImpl->mGlStateCache.mClearColorSet)
686 gl.ClearColor(clearValues[0].color.r,
687 clearValues[0].color.g,
688 clearValues[0].color.b,
689 clearValues[0].color.a);
691 mImpl->mGlStateCache.mClearColorSet = true;
692 mImpl->mGlStateCache.mClearColor = Vector4(clearValues[0].color.r,
693 clearValues[0].color.g,
694 clearValues[0].color.b,
695 clearValues[0].color.a);
699 // check for depth stencil
700 if(attachments.size() > 1)
702 const auto& depthStencil = attachments.back();
703 if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
705 if(!mImpl->mGlStateCache.mDepthMaskEnabled)
707 mImpl->mGlStateCache.mDepthMaskEnabled = true;
710 mask |= GL_DEPTH_BUFFER_BIT;
712 if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
714 if(mImpl->mGlStateCache.mStencilMask != 0xFF)
716 mImpl->mGlStateCache.mStencilMask = 0xFF;
717 gl.StencilMask(0xFF);
719 mask |= GL_STENCIL_BUFFER_BIT;
723 SetScissorTestEnabled(true);
724 gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
725 ClearBuffer(mask, true);
726 SetScissorTestEnabled(false);
728 mImpl->mCurrentRenderPass = &renderPass;
729 mImpl->mCurrentRenderTarget = &renderTarget;
732 void Context::EndRenderPass(GLES::TextureDependencyChecker& dependencyChecker)
734 if(mImpl->mCurrentRenderTarget)
736 GLES::Framebuffer* framebuffer = mImpl->mCurrentRenderTarget->GetFramebuffer();
739 auto& gl = *mImpl->mController.GetGL();
742 /* @todo Full dependency checking would need to store textures in Begin, and create
743 * fence objects here; but we're going to draw all fbos on shared context in serial,
744 * so no real need (yet). Might want to consider ensuring order of render passes,
745 * but that needs doing in the controller, and would need doing before ProcessCommandQueues.
747 * Currently up to the client to create render tasks in the right order.
750 /* Create fence sync objects. Other contexts can then wait on these fences before reading
753 dependencyChecker.AddTextures(this, framebuffer);
758 void Context::ClearState()
760 mImpl->mCurrentTextureBindings.clear();
763 void Context::ColorMask(bool enabled)
765 if(enabled != mImpl->mGlStateCache.mColorMask)
767 mImpl->mGlStateCache.mColorMask = enabled;
769 auto& gl = *mImpl->mController.GetGL();
770 gl.ColorMask(enabled, enabled, enabled, enabled);
774 void Context::ClearStencilBuffer()
776 ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
779 void Context::ClearDepthBuffer()
781 ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
784 void Context::ClearBuffer(uint32_t mask, bool forceClear)
786 mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
789 auto& gl = *mImpl->mController.GetGL();
794 void Context::InvalidateDepthStencilBuffers()
796 auto& gl = *mImpl->mController.GetGL();
798 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
799 gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
802 void Context::SetScissorTestEnabled(bool scissorEnabled)
804 if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
806 mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
808 auto& gl = *mImpl->mController.GetGL();
811 gl.Enable(GL_SCISSOR_TEST);
815 gl.Disable(GL_SCISSOR_TEST);
820 void Context::SetStencilTestEnable(bool stencilEnable)
822 if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
824 mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
826 auto& gl = *mImpl->mController.GetGL();
829 gl.Enable(GL_STENCIL_TEST);
833 gl.Disable(GL_STENCIL_TEST);
838 void Context::StencilMask(uint32_t writeMask)
840 if(writeMask != mImpl->mGlStateCache.mStencilMask)
842 mImpl->mGlStateCache.mStencilMask = writeMask;
844 auto& gl = *mImpl->mController.GetGL();
845 gl.StencilMask(writeMask);
849 void Context::StencilFunc(Graphics::CompareOp compareOp,
851 uint32_t compareMask)
853 if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
854 reference != mImpl->mGlStateCache.mStencilFuncRef ||
855 compareMask != mImpl->mGlStateCache.mStencilFuncMask)
857 mImpl->mGlStateCache.mStencilFunc = compareOp;
858 mImpl->mGlStateCache.mStencilFuncRef = reference;
859 mImpl->mGlStateCache.mStencilFuncMask = compareMask;
861 auto& gl = *mImpl->mController.GetGL();
862 gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
866 void Context::StencilOp(Graphics::StencilOp failOp,
867 Graphics::StencilOp depthFailOp,
868 Graphics::StencilOp passOp)
870 if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
871 depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
872 passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
874 mImpl->mGlStateCache.mStencilOpFail = failOp;
875 mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
876 mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
878 auto& gl = *mImpl->mController.GetGL();
879 gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
883 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
885 if(compareOp != mImpl->mGlStateCache.mDepthFunction)
887 mImpl->mGlStateCache.mDepthFunction = compareOp;
888 auto& gl = *mImpl->mController.GetGL();
889 gl.DepthFunc(GLCompareOp(compareOp).op);
893 void Context::SetDepthTestEnable(bool depthTestEnable)
895 if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
897 mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
899 auto& gl = *mImpl->mController.GetGL();
902 gl.Enable(GL_DEPTH_TEST);
906 gl.Disable(GL_DEPTH_TEST);
911 void Context::SetDepthWriteEnable(bool depthWriteEnable)
913 if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
915 mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
917 auto& gl = *mImpl->mController.GetGL();
918 gl.DepthMask(depthWriteEnable);
922 void Context::ActiveTexture(uint32_t textureBindingIndex)
924 if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
926 mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
928 auto& gl = *mImpl->mController.GetGL();
929 gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
933 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
935 uint32_t typeId = static_cast<uint32_t>(textureTypeId);
936 if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
938 mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
940 auto& gl = *mImpl->mController.GetGL();
941 gl.BindTexture(target, textureId);
945 void Context::GenerateMipmap(GLenum target)
947 auto& gl = *mImpl->mController.GetGL();
948 gl.GenerateMipmap(target);
951 void Context::BindBuffer(GLenum target, uint32_t bufferId)
955 case GL_ARRAY_BUFFER:
957 if(mImpl->mGlStateCache.mBoundArrayBufferId == bufferId)
961 mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
964 case GL_ELEMENT_ARRAY_BUFFER:
966 if(mImpl->mGlStateCache.mBoundElementArrayBufferId == bufferId)
970 mImpl->mGlStateCache.mBoundElementArrayBufferId = bufferId;
975 // Cache miss. Bind buffer.
976 auto& gl = *mImpl->mController.GetGL();
977 gl.BindBuffer(target, bufferId);
980 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
982 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
983 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
984 mImpl->mGlStateCache.StencilBufferWriteEnabled());
986 auto& gl = *mImpl->mController.GetGL();
987 gl.DrawBuffers(count, buffers);
990 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
992 mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
994 auto& gl = *mImpl->mController.GetGL();
995 gl.BindFramebuffer(target, bufferId);
998 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
1000 auto& gl = *mImpl->mController.GetGL();
1001 gl.GenFramebuffers(count, framebuffers);
1003 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
1006 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
1008 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
1010 auto& gl = *mImpl->mController.GetGL();
1011 gl.DeleteFramebuffers(count, framebuffers);
1014 GLStateCache& Context::GetGLStateCache()
1016 return mImpl->mGlStateCache;
1019 void Context::GlContextCreated()
1021 if(!mImpl->mGlContextCreated)
1023 mImpl->mGlContextCreated = true;
1025 // Set the initial GL state
1026 mImpl->InitializeGlState();
1030 void Context::GlContextDestroyed()
1032 mImpl->mGlContextCreated = false;
1035 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
1037 // Since the pipeline is deleted, invalidate the cached pipeline.
1038 if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
1040 mImpl->mCurrentPipeline = nullptr;
1043 // Remove cached VAO map
1044 auto* gl = mImpl->mController.GetGL();
1047 const auto* program = pipeline->GetCreateInfo().programState->program;
1050 const auto* programImpl = static_cast<const GLES::Program*>(program)->GetImplementation();
1053 auto iter = mImpl->mProgramVAOMap.find(programImpl);
1054 if(iter != mImpl->mProgramVAOMap.end())
1056 for(auto& attributeHashPair : iter->second)
1058 auto vao = attributeHashPair.second;
1059 gl->DeleteVertexArrays(1, &vao);
1060 if(mImpl->mProgramVAOCurrentState == vao)
1062 mImpl->mProgramVAOCurrentState = 0u;
1065 mImpl->mProgramVAOMap.erase(iter);
1072 void Context::PrepareForNativeRendering()
1074 // this should be pretty much constant
1075 auto display = eglGetCurrentDisplay();
1076 auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
1077 auto readSurface = eglGetCurrentSurface(EGL_READ);
1078 auto context = eglGetCurrentContext();
1080 // push the surface and context data to the impl
1081 // It's needed to restore context
1082 if(!mImpl->mCacheEGLGraphicsContext)
1084 mImpl->mCacheDrawWriteSurface = drawSurface;
1085 mImpl->mCacheDrawReadSurface = readSurface;
1086 mImpl->mCacheEGLGraphicsContext = context;
1089 if(!mImpl->mNativeDrawContext)
1091 EGLint configId{0u};
1092 eglQueryContext(display, mImpl->mController.GetSharedContext(), EGL_CONFIG_ID, &configId);
1094 EGLint configAttribs[3];
1095 configAttribs[0] = EGL_CONFIG_ID;
1096 configAttribs[1] = configId;
1097 configAttribs[2] = EGL_NONE;
1101 if(eglChooseConfig(display, configAttribs, &config, 1, &numConfigs) != EGL_TRUE)
1103 DALI_LOG_ERROR("eglChooseConfig failed!\n");
1107 auto version = int(mImpl->mController.GetGLESVersion());
1109 std::vector<EGLint> attribs;
1110 attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1111 attribs.push_back(version / 10);
1112 attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1113 attribs.push_back(version % 10);
1114 attribs.push_back(EGL_NONE);
1116 mImpl->mNativeDrawContext = eglCreateContext(display, config, mImpl->mController.GetSharedContext(), attribs.data());
1117 if(mImpl->mNativeDrawContext == EGL_NO_CONTEXT)
1119 DALI_LOG_ERROR("eglCreateContext failed!\n");
1124 eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1127 void Context::RestoreFromNativeRendering()
1129 auto display = eglGetCurrentDisplay();
1131 // bring back original context
1132 eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1135 } // namespace Dali::Graphics::GLES