2 * Copyright (c) 2024 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 <dali/internal/graphics/gles-impl/egl-graphics-controller.h>
21 #include <dali/integration-api/trace.h>
22 #include <dali/public-api/common/dali-common.h>
25 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/integration-api/gl-abstraction.h>
28 #include <dali/integration-api/gl-defines.h>
29 #include <dali/integration-api/graphics-sync-abstraction.h>
30 #include <dali/integration-api/pixel-data-integ.h>
31 #include <dali/internal/graphics/gles-impl/egl-sync-object.h>
32 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
33 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
34 #include <dali/internal/graphics/gles-impl/gles-graphics-program.h>
35 #include <dali/internal/graphics/gles-impl/gles-graphics-render-pass.h>
36 #include <dali/internal/graphics/gles-impl/gles-graphics-render-target.h>
37 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
38 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
39 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
40 #include <dali/internal/graphics/gles-impl/gles-sync-object.h>
41 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
42 #include <dali/internal/graphics/gles/egl-sync-implementation.h>
44 #include <dali/internal/graphics/gles/egl-graphics.h>
48 // Uncomment the following define to turn on frame dumping
49 //#define ENABLE_COMMAND_BUFFER_FRAME_DUMP 1
50 #include <dali/internal/graphics/gles-impl/egl-graphics-controller-debug.h>
53 namespace Dali::Graphics
58 * @brief Custom deleter for all Graphics objects created
59 * with use of the Controller.
61 * When Graphics object dies the unique pointer (Graphics::UniquePtr)
62 * doesn't destroy it directly but passes the ownership back
63 * to the Controller. The GLESDeleter is responsible for passing
64 * the object to the discard queue (by calling Resource::DiscardResource()).
69 GLESDeleter() = default;
71 void operator()(T* object)
73 // Discard resource (add it to discard queue)
74 object->DiscardResource();
79 * @brief Helper function allocating graphics object
81 * @param[in] info Create info structure
82 * @param[in] controller Controller object
83 * @param[out] out Unique pointer to the return object
85 template<class GLESType, class GfxCreateInfo, class T>
86 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
89 using Type = typename T::element_type;
90 using UPtr = Graphics::UniquePtr<Type>;
91 if(info.allocationCallbacks)
93 auto* memory = info.allocationCallbacks->allocCallback(
96 info.allocationCallbacks->userData);
97 return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
99 else // Use standard allocator
101 // We are given all object for recycling
104 auto reusedObject = oldObject.release();
105 // If succeeded, attach the object to the unique_ptr and return it back
106 if(static_cast<GLESType*>(reusedObject)->TryRecycle(info, controller))
108 return UPtr(reusedObject, GLESDeleter<GLESType>());
112 // can't reuse so kill object by giving it back to original
114 oldObject.reset(reusedObject);
118 // Create brand new object
119 return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
123 template<class T0, class T1>
124 T0* CastObject(T1* apiObject)
126 return static_cast<T0*>(apiObject);
129 // Maximum size of texture upload buffer.
130 const uint32_t TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB = 1;
132 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_EGL, false);
135 EglGraphicsController::EglGraphicsController()
136 : mTextureDependencyChecker(*this),
141 EglGraphicsController::~EglGraphicsController()
143 while(!mPresentationCommandBuffers.empty())
145 auto presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
146 delete presentCommandBuffer;
147 mPresentationCommandBuffers.pop();
151 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
153 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 1\n");
154 mGlAbstraction = &glAbstraction;
155 mContext = std::make_unique<GLES::Context>(*this);
156 mCurrentContext = mContext.get();
159 void EglGraphicsController::Initialize(Integration::GraphicsSyncAbstraction& syncImplementation,
160 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
161 Internal::Adaptor::GraphicsInterface& graphicsInterface)
163 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 2\n");
164 auto* syncImplPtr = static_cast<Internal::Adaptor::EglSyncImplementation*>(&syncImplementation);
166 mEglSyncImplementation = syncImplPtr;
167 mGlContextHelperAbstraction = &glContextHelperAbstraction;
168 mGraphics = &graphicsInterface;
171 void EglGraphicsController::FrameStart()
173 mCapacity = 0; // Reset the command buffer capacity at the start of the frame.
176 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
178 for(auto& cmdbuf : submitInfo.cmdBuffer)
180 // Push command buffers
181 auto* commandBuffer = static_cast<GLES::CommandBuffer*>(cmdbuf);
182 mCapacity += commandBuffer->GetCapacity();
183 mCommandQueue.push(commandBuffer);
186 // If flush bit set, flush all pending tasks
187 if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
193 void EglGraphicsController::WaitIdle()
198 void EglGraphicsController::PresentRenderTarget(RenderTarget* renderTarget)
200 GLES::CommandBuffer* presentCommandBuffer{nullptr};
201 if(mPresentationCommandBuffers.empty())
203 CommandBufferCreateInfo info;
204 info.SetLevel(CommandBufferLevel::PRIMARY);
205 info.fixedCapacity = 1; // only one command
206 presentCommandBuffer = new GLES::CommandBuffer(info, *this);
210 presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
211 presentCommandBuffer->Reset();
212 mPresentationCommandBuffers.pop();
214 presentCommandBuffer->PresentRenderTarget(static_cast<GLES::RenderTarget*>(renderTarget));
215 SubmitInfo submitInfo;
216 submitInfo.cmdBuffer = {presentCommandBuffer};
217 submitInfo.flags = 0 | SubmitFlagBits::FLUSH;
218 SubmitCommandBuffers(submitInfo);
221 void EglGraphicsController::ResolvePresentRenderTarget(GLES::RenderTarget* renderTarget)
223 mCurrentContext->InvalidateDepthStencilBuffers();
225 auto* rt = static_cast<GLES::RenderTarget*>(renderTarget);
226 if(rt->GetCreateInfo().surface)
228 auto* surfaceInterface = reinterpret_cast<Dali::RenderSurfaceInterface*>(rt->GetCreateInfo().surface);
229 surfaceInterface->MakeContextCurrent();
230 surfaceInterface->PostRender();
234 void EglGraphicsController::PostRender()
236 mTextureDependencyChecker.Reset();
237 mSyncPool.AgeSyncObjects();
240 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
242 DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
243 return *mGlAbstraction;
246 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
248 DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
249 return *mGlContextHelperAbstraction;
252 Internal::Adaptor::EglSyncImplementation& EglGraphicsController::GetEglSyncImplementation()
254 DALI_ASSERT_DEBUG(mEglSyncImplementation && "Sync implementation not initialized");
255 return *mEglSyncImplementation;
258 Graphics::UniquePtr<CommandBuffer> EglGraphicsController::CreateCommandBuffer(
259 const CommandBufferCreateInfo& commandBufferCreateInfo,
260 Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
262 return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
265 Graphics::UniquePtr<RenderPass> EglGraphicsController::CreateRenderPass(const RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<RenderPass>&& oldRenderPass)
267 return NewObject<GLES::RenderPass>(renderPassCreateInfo, *this, std::move(oldRenderPass));
270 Graphics::UniquePtr<Texture>
271 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
273 return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
276 Graphics::UniquePtr<Buffer> EglGraphicsController::CreateBuffer(
277 const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
279 return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
282 Graphics::UniquePtr<Framebuffer> EglGraphicsController::CreateFramebuffer(
283 const FramebufferCreateInfo& framebufferCreateInfo, Graphics::UniquePtr<Framebuffer>&& oldFramebuffer)
285 return NewObject<GLES::Framebuffer>(framebufferCreateInfo, *this, std::move(oldFramebuffer));
288 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(
289 const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
291 // Create pipeline cache if needed
294 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
297 return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
300 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(
301 const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
303 // Create pipeline cache if needed
306 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
309 return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
312 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
314 // Create pipeline cache if needed
317 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
319 return mPipelineCache->GetShader(shaderCreateInfo, std::move(oldShader));
322 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
324 return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
327 Graphics::UniquePtr<RenderTarget> EglGraphicsController::CreateRenderTarget(const RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<RenderTarget>&& oldRenderTarget)
329 return NewObject<GLES::RenderTarget>(renderTargetCreateInfo, *this, std::move(oldRenderTarget));
332 Graphics::UniquePtr<SyncObject> EglGraphicsController::CreateSyncObject(const SyncObjectCreateInfo& syncObjectCreateInfo,
333 UniquePtr<SyncObject>&& oldSyncObject)
335 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
337 return NewObject<EGL::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
341 return NewObject<GLES::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
345 MemoryRequirements EglGraphicsController::GetBufferMemoryRequirements(Buffer& buffer) const
347 MemoryRequirements requirements{};
353 gl->GetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align);
354 requirements.alignment = align;
359 TextureProperties EglGraphicsController::GetTextureProperties(const Texture& texture)
361 const GLES::Texture* glesTexture = static_cast<const GLES::Texture*>(&texture);
362 const auto& createInfo = glesTexture->GetCreateInfo();
364 TextureProperties properties{};
365 properties.format = createInfo.format;
366 properties.compressed = glesTexture->IsCompressed();
367 properties.extent2D = createInfo.size;
368 properties.nativeHandle = glesTexture->GetGLTexture();
369 // TODO: Skip format1, emulated, packed, directWriteAccessEnabled of TextureProperties for now
374 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
376 return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
379 void EglGraphicsController::CreateSurfaceContext(Dali::RenderSurfaceInterface* surface)
381 std::unique_ptr<GLES::Context> context = std::make_unique<GLES::Context>(*this);
382 mSurfaceContexts.push_back(std::move(std::make_pair(surface, std::move(context))));
385 void EglGraphicsController::DeleteSurfaceContext(Dali::RenderSurfaceInterface* surface)
387 mSurfaceContexts.erase(std::remove_if(
388 mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return surface == iter.first; }),
389 mSurfaceContexts.end());
392 void EglGraphicsController::ActivateResourceContext()
394 mCurrentContext = mContext.get();
395 mCurrentContext->GlContextCreated();
398 auto eglGraphics = dynamic_cast<Dali::Internal::Adaptor::EglGraphics*>(mGraphics);
401 mSharedContext = eglGraphics->GetEglImplementation().GetContext();
406 void EglGraphicsController::ActivateSurfaceContext(Dali::RenderSurfaceInterface* surface)
408 if(surface && mGraphics->IsResourceContextSupported())
410 auto iter = std::find_if(mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return (iter.first == surface); });
412 if(iter != mSurfaceContexts.end())
414 mCurrentContext = iter->second.get();
415 mCurrentContext->GlContextCreated();
420 void EglGraphicsController::AddTexture(GLES::Texture& texture)
422 // Assuming we are on the correct context
423 mCreateTextureQueue.push(&texture);
426 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
428 // Assuming we are on the correct context
429 mCreateBufferQueue.push(&buffer);
432 void EglGraphicsController::AddFramebuffer(GLES::Framebuffer& framebuffer)
434 // Assuming we are on the correct context
435 mCreateFramebufferQueue.push(&framebuffer);
438 void EglGraphicsController::ProcessDiscardQueues()
440 DALI_TRACE_SCOPE(gTraceFilter, "DALI_EGL_CONTROLLER_DISCARD_QUEUE");
443 ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
446 ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
448 // Process Framebuffers
449 ProcessDiscardQueue<GLES::Framebuffer>(mDiscardFramebufferQueue);
451 // Process RenderPass
452 ProcessDiscardQueue<GLES::RenderPass>(mDiscardRenderPassQueue);
454 // Process RenderTarget
455 ProcessDiscardQueue<GLES::RenderTarget>(mDiscardRenderTargetQueue);
458 if(mPipelineCache && !mDiscardPipelineQueue.empty())
460 mPipelineCache->MarkPipelineCacheFlushRequired();
462 ProcessDiscardQueue(mDiscardPipelineQueue);
465 if(mPipelineCache && !mDiscardProgramQueue.empty())
467 mPipelineCache->MarkProgramCacheFlushRequired();
469 ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
472 ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
475 ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
477 // Process command buffers
478 ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
481 void EglGraphicsController::ProcessCreateQueues()
483 DALI_TRACE_SCOPE(gTraceFilter, "DALI_EGL_CONTROLLER_CREATE_QUEUE");
485 ProcessCreateQueue(mCreateTextureQueue);
488 ProcessCreateQueue(mCreateBufferQueue);
490 // Process framebuffers
491 ProcessCreateQueue(mCreateFramebufferQueue);
494 void EglGraphicsController::ProcessCommandBuffer(const GLES::CommandBuffer& commandBuffer)
497 const auto commands = commandBuffer.GetCommands(count);
499 DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_EGL_CONTROLLER_PROCESS", [&](std::ostringstream& oss) {
500 oss << "[commandCount:" << count << "]";
503 for(auto i = 0u; i < count; ++i)
505 auto& cmd = commands[i];
509 case GLES::CommandType::FLUSH:
511 // Nothing to do here
514 case GLES::CommandType::BIND_TEXTURES:
516 mCurrentContext->BindTextures(cmd.bindTextures.textureBindings.Ptr(), cmd.bindTextures.textureBindingsCount);
519 case GLES::CommandType::BIND_VERTEX_BUFFERS:
521 auto bindings = cmd.bindVertexBuffers.vertexBufferBindings.Ptr();
522 mCurrentContext->BindVertexBuffers(bindings, cmd.bindVertexBuffers.vertexBufferBindingsCount);
525 case GLES::CommandType::BIND_UNIFORM_BUFFER:
527 auto& bindings = cmd.bindUniformBuffers;
528 mCurrentContext->BindUniformBuffers(bindings.uniformBufferBindingsCount ? bindings.uniformBufferBindings.Ptr() : nullptr, bindings.uniformBufferBindingsCount, bindings.standaloneUniformsBufferBinding);
531 case GLES::CommandType::BIND_INDEX_BUFFER:
533 mCurrentContext->BindIndexBuffer(cmd.bindIndexBuffer);
536 case GLES::CommandType::BIND_SAMPLERS:
540 case GLES::CommandType::BIND_PIPELINE:
542 auto pipeline = static_cast<const GLES::Pipeline*>(cmd.bindPipeline.pipeline);
543 mCurrentContext->BindPipeline(pipeline);
546 case GLES::CommandType::DRAW:
548 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
551 case GLES::CommandType::DRAW_INDEXED:
553 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
556 case GLES::CommandType::DRAW_INDEXED_INDIRECT:
558 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
561 case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
563 mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
566 case GLES::CommandType::SET_SCISSOR_TEST:
568 mCurrentContext->SetScissorTestEnabled(cmd.scissorTest.enable);
571 case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
573 mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
577 case GLES::CommandType::SET_COLOR_MASK:
579 mCurrentContext->ColorMask(cmd.colorMask.enabled);
582 case GLES::CommandType::CLEAR_STENCIL_BUFFER:
584 mCurrentContext->ClearStencilBuffer();
587 case GLES::CommandType::CLEAR_DEPTH_BUFFER:
589 mCurrentContext->ClearDepthBuffer();
593 case GLES::CommandType::SET_STENCIL_TEST_ENABLE:
595 mCurrentContext->SetStencilTestEnable(cmd.stencilTest.enabled);
599 case GLES::CommandType::SET_STENCIL_FUNC:
601 mCurrentContext->StencilFunc(cmd.stencilFunc.compareOp,
602 cmd.stencilFunc.reference,
603 cmd.stencilFunc.compareMask);
607 case GLES::CommandType::SET_STENCIL_WRITE_MASK:
609 mCurrentContext->StencilMask(cmd.stencilWriteMask.mask);
613 case GLES::CommandType::SET_STENCIL_OP:
615 mCurrentContext->StencilOp(cmd.stencilOp.failOp,
616 cmd.stencilOp.depthFailOp,
617 cmd.stencilOp.passOp);
621 case GLES::CommandType::SET_DEPTH_COMPARE_OP:
623 mCurrentContext->SetDepthCompareOp(cmd.depth.compareOp);
626 case GLES::CommandType::SET_DEPTH_TEST_ENABLE:
628 mCurrentContext->SetDepthTestEnable(cmd.depth.testEnabled);
631 case GLES::CommandType::SET_DEPTH_WRITE_ENABLE:
633 mCurrentContext->SetDepthWriteEnable(cmd.depth.writeEnabled);
637 case GLES::CommandType::BEGIN_RENDERPASS:
639 auto& renderTarget = *cmd.beginRenderPass.renderTarget;
640 const auto& targetInfo = renderTarget.GetCreateInfo();
642 if(targetInfo.surface)
644 // switch to surface context
645 mGraphics->ActivateSurfaceContext(static_cast<Dali::RenderSurfaceInterface*>(targetInfo.surface));
647 else if(targetInfo.framebuffer)
649 // switch to resource context
650 mGraphics->ActivateResourceContext();
653 mCurrentContext->BeginRenderPass(cmd.beginRenderPass);
657 case GLES::CommandType::END_RENDERPASS:
659 mCurrentContext->EndRenderPass(mTextureDependencyChecker);
661 // This sync object is to enable cpu to wait for rendering to complete, not gpu.
662 // It's only needed for reading the framebuffer texture in the client.
663 auto syncObject = const_cast<GLES::SyncObject*>(static_cast<const GLES::SyncObject*>(cmd.endRenderPass.syncObject));
666 syncObject->InitializeResource();
670 case GLES::CommandType::PRESENT_RENDER_TARGET:
672 ResolvePresentRenderTarget(cmd.presentRenderTarget.targetToPresent);
674 // The command buffer will be pushed into the queue of presentation command buffers
675 // for further reuse.
676 if(commandBuffer.GetCreateInfo().fixedCapacity == 1)
678 mPresentationCommandBuffers.push(&commandBuffer);
682 case GLES::CommandType::EXECUTE_COMMAND_BUFFERS:
684 // Process secondary command buffers
685 // todo: check validity of the secondaries
686 // there are operations which are illigal to be done
687 // within secondaries.
688 auto buffers = cmd.executeCommandBuffers.buffers.Ptr();
689 for(auto j = 0u; j < cmd.executeCommandBuffers.buffersCount; ++j)
691 auto& buf = buffers[j];
692 ProcessCommandBuffer(*static_cast<const GLES::CommandBuffer*>(buf));
696 case GLES::CommandType::DRAW_NATIVE:
698 auto* info = &cmd.drawNative.drawNativeInfo;
700 mCurrentContext->PrepareForNativeRendering();
702 if(info->glesNativeInfo.eglSharedContextStoragePointer)
704 auto* anyContext = reinterpret_cast<std::any*>(info->glesNativeInfo.eglSharedContextStoragePointer);
705 *anyContext = mSharedContext;
708 CallbackBase::ExecuteReturn<bool>(*info->callback, info->userData);
710 mCurrentContext->RestoreFromNativeRendering();
715 DALI_TRACE_END(gTraceFilter, "DALI_EGL_CONTROLLER_PROCESS");
718 void EglGraphicsController::ProcessCommandQueues()
722 while(!mCommandQueue.empty())
724 auto cmdBuf = mCommandQueue.front();
726 DUMP_FRAME_COMMAND_BUFFER(cmdBuf);
727 ProcessCommandBuffer(*cmdBuf);
733 void EglGraphicsController::ProcessTextureUpdateQueue()
735 if(mTextureUpdateRequests.empty())
739 DALI_TRACE_SCOPE(gTraceFilter, "DALI_EGL_CONTROLLER_TEXTURE_UPDATE");
740 while(!mTextureUpdateRequests.empty())
742 TextureUpdateRequest& request = mTextureUpdateRequests.front();
744 auto& info = request.first;
745 auto& source = request.second;
747 switch(source.sourceType)
749 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
750 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
752 // GPU memory must be already allocated.
754 // Check if it needs conversion
755 auto* texture = static_cast<GLES::Texture*>(info.dstTexture);
756 const auto& createInfo = texture->GetCreateInfo();
757 auto srcFormat = GLES::GLTextureFormatType(info.srcFormat).format;
758 auto srcType = GLES::GLTextureFormatType(info.srcFormat).type;
759 auto destInternalFormat = GLES::GLTextureFormatType(createInfo.format).internalFormat;
760 auto destFormat = GLES::GLTextureFormatType(createInfo.format).format;
762 // From render-texture.cpp
763 const bool isSubImage(info.dstOffset2D.x != 0 || info.dstOffset2D.y != 0 ||
764 info.srcExtent2D.width != (createInfo.size.width / (1 << info.level)) ||
765 info.srcExtent2D.height != (createInfo.size.height / (1 << info.level)));
767 uint8_t* sourceBuffer = nullptr;
768 bool sourceBufferReleaseRequired = false;
769 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
771 sourceBuffer = reinterpret_cast<uint8_t*>(source.memorySource.memory);
772 sourceBufferReleaseRequired = true;
776 Dali::Integration::PixelDataBuffer pixelBufferData = Dali::Integration::GetPixelDataBuffer(source.pixelDataSource.pixelData);
778 sourceBuffer = pixelBufferData.buffer + info.srcOffset;
779 sourceBufferReleaseRequired = Dali::Integration::IsPixelDataReleaseAfterUpload(source.pixelDataSource.pixelData) && info.srcOffset == 0u;
782 auto sourceStride = info.srcStride;
783 std::vector<uint8_t> tempBuffer;
785 if(mGlAbstraction->TextureRequiresConverting(srcFormat, destFormat, isSubImage))
787 // Convert RGB to RGBA if necessary.
788 if(texture->TryConvertPixelData(sourceBuffer, info.srcFormat, createInfo.format, info.srcSize, info.srcStride, info.srcExtent2D.width, info.srcExtent2D.height, tempBuffer))
790 sourceBuffer = &tempBuffer[0];
791 sourceStride = 0u; // Converted buffer compacted. make stride as 0.
792 srcFormat = destFormat;
793 srcType = GLES::GLTextureFormatType(createInfo.format).type;
797 // Calculate the maximum mipmap level for the texture
798 texture->SetMaxMipMapLevel(std::max(texture->GetMaxMipMapLevel(), info.level));
800 GLenum bindTarget{GL_TEXTURE_2D};
801 GLenum target{GL_TEXTURE_2D};
803 if(createInfo.textureType == Graphics::TextureType::TEXTURE_CUBEMAP)
805 bindTarget = GL_TEXTURE_CUBE_MAP;
806 target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + info.layer;
809 mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
810 mGlAbstraction->PixelStorei(GL_UNPACK_ROW_LENGTH, sourceStride);
812 mCurrentContext->BindTexture(bindTarget, texture->GetTextureTypeId(), texture->GetGLTexture());
816 if(!texture->IsCompressed())
818 mGlAbstraction->TexImage2D(target,
821 info.srcExtent2D.width,
822 info.srcExtent2D.height,
830 mGlAbstraction->CompressedTexImage2D(target,
833 info.srcExtent2D.width,
834 info.srcExtent2D.height,
842 if(!texture->IsCompressed())
844 mGlAbstraction->TexSubImage2D(target,
848 info.srcExtent2D.width,
849 info.srcExtent2D.height,
856 mGlAbstraction->CompressedTexSubImage2D(target,
860 info.srcExtent2D.width,
861 info.srcExtent2D.height,
868 if(sourceBufferReleaseRequired && sourceBuffer != nullptr)
870 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
872 free(reinterpret_cast<void*>(sourceBuffer));
876 Dali::Integration::ReleasePixelDataBuffer(source.pixelDataSource.pixelData);
883 // TODO: other sources
888 mTextureUpdateRequests.pop();
892 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>& updateInfoList,
893 const std::vector<TextureUpdateSourceInfo>& sourceList)
896 for(auto& info : updateInfoList)
898 mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
899 auto& pair = mTextureUpdateRequests.back();
900 switch(pair.second.sourceType)
902 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
904 auto& info = pair.first;
905 auto& source = pair.second;
907 // allocate staging memory and copy the data
908 // TODO: using PBO with GLES3, this is just naive
911 uint8_t* stagingBuffer = reinterpret_cast<uint8_t*>(malloc(info.srcSize));
913 uint8_t* srcMemory = &reinterpret_cast<uint8_t*>(source.memorySource.memory)[info.srcOffset];
915 std::copy(srcMemory, srcMemory + info.srcSize, stagingBuffer);
917 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
919 // store staging buffer
920 source.memorySource.memory = stagingBuffer;
923 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
925 // Increase CPU memory usage since ownership of PixelData is now on mTextureUpdateRequests.
926 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
929 case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
931 // TODO, with PBO support
934 case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
936 // TODO texture 2 texture in-GPU copy
942 // If upload buffer exceeds maximum size, flush.
943 if(mTextureUploadTotalCPUMemoryUsed > TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB * 1024 * 1024)
946 mTextureUploadTotalCPUMemoryUsed = 0;
950 void EglGraphicsController::ProcessTextureMipmapGenerationQueue()
952 if(mTextureMipmapGenerationRequests.empty())
956 DALI_TRACE_SCOPE(gTraceFilter, "DALI_EGL_CONTROLLER_TEXTURE_MIPMAP");
957 while(!mTextureMipmapGenerationRequests.empty())
959 auto* texture = mTextureMipmapGenerationRequests.front();
961 mCurrentContext->BindTexture(texture->GetGlTarget(), texture->GetTextureTypeId(), texture->GetGLTexture());
962 mCurrentContext->GenerateMipmap(texture->GetGlTarget());
964 mTextureMipmapGenerationRequests.pop();
968 void EglGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
970 mTextureMipmapGenerationRequests.push(static_cast<const GLES::Texture*>(&texture));
973 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
975 // Mapping buffer requires the object to be created NOW
976 // Workaround - flush now, otherwise there will be given a staging buffer
977 // in case when the buffer is not there yet
978 if(!mCreateBufferQueue.empty())
980 mGraphics->ActivateResourceContext();
981 ProcessCreateQueues();
984 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
986 return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
990 return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
994 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
996 return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
999 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
1001 return *mPipelineCache;
1004 Graphics::Texture* EglGraphicsController::CreateTextureByResourceId(uint32_t resourceId, const Graphics::TextureCreateInfo& createInfo)
1006 Graphics::Texture* ret = nullptr;
1007 Graphics::UniquePtr<Graphics::Texture> texture;
1009 auto iter = mExternalTextureResources.find(resourceId);
1010 DALI_ASSERT_ALWAYS(iter == mExternalTextureResources.end());
1012 texture = CreateTexture(createInfo, std::move(texture));
1014 ret = texture.get();
1016 mExternalTextureResources.insert(std::make_pair(resourceId, std::move(texture)));
1021 void EglGraphicsController::DiscardTextureFromResourceId(uint32_t resourceId)
1023 auto iter = mExternalTextureResources.find(resourceId);
1024 if(iter != mExternalTextureResources.end())
1026 mExternalTextureResources.erase(iter);
1030 Graphics::Texture* EglGraphicsController::GetTextureFromResourceId(uint32_t resourceId)
1032 Graphics::Texture* ret = nullptr;
1034 auto iter = mExternalTextureResources.find(resourceId);
1035 if(iter != mExternalTextureResources.end())
1037 ret = iter->second.get();
1043 Graphics::UniquePtr<Graphics::Texture> EglGraphicsController::ReleaseTextureFromResourceId(uint32_t resourceId)
1045 Graphics::UniquePtr<Graphics::Texture> texture;
1047 auto iter = mExternalTextureResources.find(resourceId);
1048 if(iter != mExternalTextureResources.end())
1050 texture = std::move(iter->second);
1051 mExternalTextureResources.erase(iter);
1057 } // namespace Dali::Graphics