2 * Copyright (c) 2023 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/public-api/common/dali-common.h>
24 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/integration-api/gl-abstraction.h>
27 #include <dali/integration-api/gl-defines.h>
28 #include <dali/integration-api/graphics-sync-abstraction.h>
29 #include <dali/integration-api/pixel-data-integ.h>
30 #include <dali/internal/graphics/gles-impl/egl-sync-object.h>
31 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
32 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
33 #include <dali/internal/graphics/gles-impl/gles-graphics-program.h>
34 #include <dali/internal/graphics/gles-impl/gles-graphics-render-pass.h>
35 #include <dali/internal/graphics/gles-impl/gles-graphics-render-target.h>
36 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
37 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
38 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
39 #include <dali/internal/graphics/gles-impl/gles-sync-object.h>
40 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
41 #include <dali/internal/graphics/gles/egl-sync-implementation.h>
43 #include <dali/internal/graphics/gles/egl-graphics.h>
47 // Uncomment the following define to turn on frame dumping
48 //#define ENABLE_COMMAND_BUFFER_FRAME_DUMP 1
49 #include <dali/internal/graphics/gles-impl/egl-graphics-controller-debug.h>
52 namespace Dali::Graphics
57 * @brief Custom deleter for all Graphics objects created
58 * with use of the Controller.
60 * When Graphics object dies the unique pointer (Graphics::UniquePtr)
61 * doesn't destroy it directly but passes the ownership back
62 * to the Controller. The GLESDeleter is responsible for passing
63 * the object to the discard queue (by calling Resource::DiscardResource()).
68 GLESDeleter() = default;
70 void operator()(T* object)
72 // Discard resource (add it to discard queue)
73 object->DiscardResource();
78 * @brief Helper function allocating graphics object
80 * @param[in] info Create info structure
81 * @param[in] controller Controller object
82 * @param[out] out Unique pointer to the return object
84 template<class GLESType, class GfxCreateInfo, class T>
85 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
88 using Type = typename T::element_type;
89 using UPtr = Graphics::UniquePtr<Type>;
90 if(info.allocationCallbacks)
92 auto* memory = info.allocationCallbacks->allocCallback(
95 info.allocationCallbacks->userData);
96 return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
98 else // Use standard allocator
100 // We are given all object for recycling
103 auto reusedObject = oldObject.release();
104 // If succeeded, attach the object to the unique_ptr and return it back
105 if(static_cast<GLESType*>(reusedObject)->TryRecycle(info, controller))
107 return UPtr(reusedObject, GLESDeleter<GLESType>());
111 // can't reuse so kill object by giving it back to original
113 oldObject.reset(reusedObject);
117 // Create brand new object
118 return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
122 template<class T0, class T1>
123 T0* CastObject(T1* apiObject)
125 return static_cast<T0*>(apiObject);
128 // Maximum size of texture upload buffer.
129 const uint32_t TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB = 1;
133 EglGraphicsController::EglGraphicsController()
134 : mTextureDependencyChecker(*this),
139 EglGraphicsController::~EglGraphicsController()
141 while(!mPresentationCommandBuffers.empty())
143 auto presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
144 delete presentCommandBuffer;
145 mPresentationCommandBuffers.pop();
149 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
151 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 1\n");
152 mGlAbstraction = &glAbstraction;
153 mContext = std::make_unique<GLES::Context>(*this);
154 mCurrentContext = mContext.get();
157 void EglGraphicsController::Initialize(Integration::GraphicsSyncAbstraction& syncImplementation,
158 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
159 Internal::Adaptor::GraphicsInterface& graphicsInterface)
161 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 2\n");
162 auto* syncImplPtr = static_cast<Internal::Adaptor::EglSyncImplementation*>(&syncImplementation);
164 mEglSyncImplementation = syncImplPtr;
165 mGlContextHelperAbstraction = &glContextHelperAbstraction;
166 mGraphics = &graphicsInterface;
169 void EglGraphicsController::FrameStart()
171 mCapacity = 0; // Reset the command buffer capacity at the start of the frame.
174 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
176 for(auto& cmdbuf : submitInfo.cmdBuffer)
178 // Push command buffers
179 auto* commandBuffer = static_cast<GLES::CommandBuffer*>(cmdbuf);
180 mCapacity += commandBuffer->GetCapacity();
181 mCommandQueue.push(commandBuffer);
184 // If flush bit set, flush all pending tasks
185 if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
191 void EglGraphicsController::WaitIdle()
196 void EglGraphicsController::PresentRenderTarget(RenderTarget* renderTarget)
198 GLES::CommandBuffer* presentCommandBuffer{nullptr};
199 if(mPresentationCommandBuffers.empty())
201 CommandBufferCreateInfo info;
202 info.SetLevel(CommandBufferLevel::PRIMARY);
203 info.fixedCapacity = 1; // only one command
204 presentCommandBuffer = new GLES::CommandBuffer(info, *this);
208 presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
209 presentCommandBuffer->Reset();
210 mPresentationCommandBuffers.pop();
212 presentCommandBuffer->PresentRenderTarget(static_cast<GLES::RenderTarget*>(renderTarget));
213 SubmitInfo submitInfo;
214 submitInfo.cmdBuffer = {presentCommandBuffer};
215 submitInfo.flags = 0 | SubmitFlagBits::FLUSH;
216 SubmitCommandBuffers(submitInfo);
219 void EglGraphicsController::ResolvePresentRenderTarget(GLES::RenderTarget* renderTarget)
221 mCurrentContext->InvalidateDepthStencilBuffers();
223 auto* rt = static_cast<GLES::RenderTarget*>(renderTarget);
224 if(rt->GetCreateInfo().surface)
226 auto* surfaceInterface = reinterpret_cast<Dali::RenderSurfaceInterface*>(rt->GetCreateInfo().surface);
227 surfaceInterface->MakeContextCurrent();
228 surfaceInterface->PostRender();
232 void EglGraphicsController::PostRender()
234 mTextureDependencyChecker.Reset();
235 mSyncPool.AgeSyncObjects();
238 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
240 DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
241 return *mGlAbstraction;
244 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
246 DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
247 return *mGlContextHelperAbstraction;
250 Internal::Adaptor::EglSyncImplementation& EglGraphicsController::GetEglSyncImplementation()
252 DALI_ASSERT_DEBUG(mEglSyncImplementation && "Sync implementation not initialized");
253 return *mEglSyncImplementation;
256 Graphics::UniquePtr<CommandBuffer> EglGraphicsController::CreateCommandBuffer(
257 const CommandBufferCreateInfo& commandBufferCreateInfo,
258 Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
260 return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
263 Graphics::UniquePtr<RenderPass> EglGraphicsController::CreateRenderPass(const RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<RenderPass>&& oldRenderPass)
265 return NewObject<GLES::RenderPass>(renderPassCreateInfo, *this, std::move(oldRenderPass));
268 Graphics::UniquePtr<Texture>
269 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
271 return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
274 Graphics::UniquePtr<Buffer> EglGraphicsController::CreateBuffer(
275 const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
277 return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
280 Graphics::UniquePtr<Framebuffer> EglGraphicsController::CreateFramebuffer(
281 const FramebufferCreateInfo& framebufferCreateInfo, Graphics::UniquePtr<Framebuffer>&& oldFramebuffer)
283 return NewObject<GLES::Framebuffer>(framebufferCreateInfo, *this, std::move(oldFramebuffer));
286 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(
287 const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
289 // Create pipeline cache if needed
292 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
295 return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
298 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(
299 const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
301 // Create program cache if needed
304 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
307 return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
310 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
312 return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
315 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
317 return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
320 Graphics::UniquePtr<RenderTarget> EglGraphicsController::CreateRenderTarget(const RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<RenderTarget>&& oldRenderTarget)
322 return NewObject<GLES::RenderTarget>(renderTargetCreateInfo, *this, std::move(oldRenderTarget));
325 Graphics::UniquePtr<SyncObject> EglGraphicsController::CreateSyncObject(const SyncObjectCreateInfo& syncObjectCreateInfo,
326 UniquePtr<SyncObject>&& oldSyncObject)
328 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
330 return NewObject<EGL::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
334 return NewObject<GLES::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
338 MemoryRequirements EglGraphicsController::GetBufferMemoryRequirements(Buffer& buffer) const
340 MemoryRequirements requirements{};
346 gl->GetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align);
347 requirements.alignment = align;
352 TextureProperties EglGraphicsController::GetTextureProperties(const Texture& texture)
354 const GLES::Texture* glesTexture = static_cast<const GLES::Texture*>(&texture);
355 auto createInfo = glesTexture->GetCreateInfo();
357 TextureProperties properties{};
358 properties.format = createInfo.format;
359 properties.compressed = glesTexture->IsCompressed();
360 properties.extent2D = createInfo.size;
361 properties.nativeHandle = glesTexture->GetGLTexture();
362 // TODO: Skip format1, emulated, packed, directWriteAccessEnabled of TextureProperties for now
367 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
369 return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
372 void EglGraphicsController::CreateSurfaceContext(Dali::RenderSurfaceInterface* surface)
374 std::unique_ptr<GLES::Context> context = std::make_unique<GLES::Context>(*this);
375 mSurfaceContexts.push_back(std::move(std::make_pair(surface, std::move(context))));
378 void EglGraphicsController::DeleteSurfaceContext(Dali::RenderSurfaceInterface* surface)
380 mSurfaceContexts.erase(std::remove_if(
381 mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return surface == iter.first; }),
382 mSurfaceContexts.end());
385 void EglGraphicsController::ActivateResourceContext()
387 mCurrentContext = mContext.get();
388 mCurrentContext->GlContextCreated();
391 auto eglGraphics = dynamic_cast<Dali::Internal::Adaptor::EglGraphics*>(mGraphics);
394 mSharedContext = eglGraphics->GetEglImplementation().GetContext();
399 void EglGraphicsController::ActivateSurfaceContext(Dali::RenderSurfaceInterface* surface)
401 if(surface && mGraphics->IsResourceContextSupported())
403 auto iter = std::find_if(mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return (iter.first == surface); });
405 if(iter != mSurfaceContexts.end())
407 mCurrentContext = iter->second.get();
408 mCurrentContext->GlContextCreated();
413 void EglGraphicsController::AddTexture(GLES::Texture& texture)
415 // Assuming we are on the correct context
416 mCreateTextureQueue.push(&texture);
419 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
421 // Assuming we are on the correct context
422 mCreateBufferQueue.push(&buffer);
425 void EglGraphicsController::AddFramebuffer(GLES::Framebuffer& framebuffer)
427 // Assuming we are on the correct context
428 mCreateFramebufferQueue.push(&framebuffer);
431 void EglGraphicsController::ProcessDiscardQueues()
434 ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
437 ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
439 // Process Framebuffers
440 ProcessDiscardQueue<GLES::Framebuffer>(mDiscardFramebufferQueue);
442 // Process RenderPass
443 ProcessDiscardQueue<GLES::RenderPass>(mDiscardRenderPassQueue);
445 // Process RenderTarget
446 ProcessDiscardQueue<GLES::RenderTarget>(mDiscardRenderTargetQueue);
449 if(mPipelineCache && !mDiscardPipelineQueue.empty())
451 mPipelineCache->MarkPipelineCacheFlushRequired();
453 ProcessDiscardQueue(mDiscardPipelineQueue);
456 if(mPipelineCache && !mDiscardProgramQueue.empty())
458 mPipelineCache->MarkProgramCacheFlushRequired();
460 ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
463 ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
466 ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
468 // Process command buffers
469 ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
472 void EglGraphicsController::ProcessCreateQueues()
475 ProcessCreateQueue(mCreateTextureQueue);
478 ProcessCreateQueue(mCreateBufferQueue);
480 // Process framebuffers
481 ProcessCreateQueue(mCreateFramebufferQueue);
484 void EglGraphicsController::ProcessCommandBuffer(const GLES::CommandBuffer& commandBuffer)
487 const auto commands = commandBuffer.GetCommands(count);
488 for(auto i = 0u; i < count; ++i)
490 auto& cmd = commands[i];
494 case GLES::CommandType::FLUSH:
496 // Nothing to do here
499 case GLES::CommandType::BIND_TEXTURES:
501 mCurrentContext->BindTextures(cmd.bindTextures.textureBindings.Ptr(), cmd.bindTextures.textureBindingsCount);
504 case GLES::CommandType::BIND_VERTEX_BUFFERS:
506 auto bindings = cmd.bindVertexBuffers.vertexBufferBindings.Ptr();
507 mCurrentContext->BindVertexBuffers(bindings, cmd.bindVertexBuffers.vertexBufferBindingsCount);
510 case GLES::CommandType::BIND_UNIFORM_BUFFER:
512 auto& bindings = cmd.bindUniformBuffers;
513 mCurrentContext->BindUniformBuffers(bindings.uniformBufferBindingsCount ? bindings.uniformBufferBindings.Ptr() : nullptr, bindings.uniformBufferBindingsCount, bindings.standaloneUniformsBufferBinding);
516 case GLES::CommandType::BIND_INDEX_BUFFER:
518 mCurrentContext->BindIndexBuffer(cmd.bindIndexBuffer);
521 case GLES::CommandType::BIND_SAMPLERS:
525 case GLES::CommandType::BIND_PIPELINE:
527 auto pipeline = static_cast<const GLES::Pipeline*>(cmd.bindPipeline.pipeline);
528 mCurrentContext->BindPipeline(pipeline);
531 case GLES::CommandType::DRAW:
533 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
536 case GLES::CommandType::DRAW_INDEXED:
538 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
541 case GLES::CommandType::DRAW_INDEXED_INDIRECT:
543 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
546 case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
548 mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
551 case GLES::CommandType::SET_SCISSOR_TEST:
553 mCurrentContext->SetScissorTestEnabled(cmd.scissorTest.enable);
556 case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
558 mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
562 case GLES::CommandType::SET_COLOR_MASK:
564 mCurrentContext->ColorMask(cmd.colorMask.enabled);
567 case GLES::CommandType::CLEAR_STENCIL_BUFFER:
569 mCurrentContext->ClearStencilBuffer();
572 case GLES::CommandType::CLEAR_DEPTH_BUFFER:
574 mCurrentContext->ClearDepthBuffer();
578 case GLES::CommandType::SET_STENCIL_TEST_ENABLE:
580 mCurrentContext->SetStencilTestEnable(cmd.stencilTest.enabled);
584 case GLES::CommandType::SET_STENCIL_FUNC:
586 mCurrentContext->StencilFunc(cmd.stencilFunc.compareOp,
587 cmd.stencilFunc.reference,
588 cmd.stencilFunc.compareMask);
592 case GLES::CommandType::SET_STENCIL_WRITE_MASK:
594 mCurrentContext->StencilMask(cmd.stencilWriteMask.mask);
598 case GLES::CommandType::SET_STENCIL_OP:
600 mCurrentContext->StencilOp(cmd.stencilOp.failOp,
601 cmd.stencilOp.depthFailOp,
602 cmd.stencilOp.passOp);
606 case GLES::CommandType::SET_DEPTH_COMPARE_OP:
608 mCurrentContext->SetDepthCompareOp(cmd.depth.compareOp);
611 case GLES::CommandType::SET_DEPTH_TEST_ENABLE:
613 mCurrentContext->SetDepthTestEnable(cmd.depth.testEnabled);
616 case GLES::CommandType::SET_DEPTH_WRITE_ENABLE:
618 mCurrentContext->SetDepthWriteEnable(cmd.depth.writeEnabled);
622 case GLES::CommandType::BEGIN_RENDERPASS:
624 auto& renderTarget = *cmd.beginRenderPass.renderTarget;
625 const auto& targetInfo = renderTarget.GetCreateInfo();
627 if(targetInfo.surface)
629 // switch to surface context
630 mGraphics->ActivateSurfaceContext(static_cast<Dali::RenderSurfaceInterface*>(targetInfo.surface));
632 else if(targetInfo.framebuffer)
634 // switch to resource context
635 mGraphics->ActivateResourceContext();
638 mCurrentContext->BeginRenderPass(cmd.beginRenderPass);
642 case GLES::CommandType::END_RENDERPASS:
644 mCurrentContext->EndRenderPass(mTextureDependencyChecker);
646 // This sync object is to enable cpu to wait for rendering to complete, not gpu.
647 // It's only needed for reading the framebuffer texture in the client.
648 auto syncObject = const_cast<GLES::SyncObject*>(static_cast<const GLES::SyncObject*>(cmd.endRenderPass.syncObject));
651 syncObject->InitializeResource();
655 case GLES::CommandType::PRESENT_RENDER_TARGET:
657 ResolvePresentRenderTarget(cmd.presentRenderTarget.targetToPresent);
659 // The command buffer will be pushed into the queue of presentation command buffers
660 // for further reuse.
661 if(commandBuffer.GetCreateInfo().fixedCapacity == 1)
663 mPresentationCommandBuffers.push(&commandBuffer);
667 case GLES::CommandType::EXECUTE_COMMAND_BUFFERS:
669 // Process secondary command buffers
670 // todo: check validity of the secondaries
671 // there are operations which are illigal to be done
672 // within secondaries.
673 auto buffers = cmd.executeCommandBuffers.buffers.Ptr();
674 for(auto j = 0u; j < cmd.executeCommandBuffers.buffersCount; ++j)
676 auto& buf = buffers[j];
677 ProcessCommandBuffer(*static_cast<const GLES::CommandBuffer*>(buf));
681 case GLES::CommandType::DRAW_NATIVE:
683 auto* info = &cmd.drawNative.drawNativeInfo;
685 mCurrentContext->PrepareForNativeRendering();
687 if(info->glesNativeInfo.eglSharedContextStoragePointer)
689 auto* anyContext = reinterpret_cast<std::any*>(info->glesNativeInfo.eglSharedContextStoragePointer);
690 *anyContext = mSharedContext;
693 CallbackBase::ExecuteReturn<bool>(*info->callback, info->userData);
695 mCurrentContext->RestoreFromNativeRendering();
702 void EglGraphicsController::ProcessCommandQueues()
706 while(!mCommandQueue.empty())
708 auto cmdBuf = mCommandQueue.front();
710 DUMP_FRAME_COMMAND_BUFFER(cmdBuf);
711 ProcessCommandBuffer(*cmdBuf);
717 void EglGraphicsController::ProcessTextureUpdateQueue()
719 while(!mTextureUpdateRequests.empty())
721 TextureUpdateRequest& request = mTextureUpdateRequests.front();
723 auto& info = request.first;
724 auto& source = request.second;
726 switch(source.sourceType)
728 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
729 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
731 // GPU memory must be already allocated.
733 // Check if it needs conversion
734 auto* texture = static_cast<GLES::Texture*>(info.dstTexture);
735 const auto& createInfo = texture->GetCreateInfo();
736 auto srcFormat = GLES::GLTextureFormatType(info.srcFormat).format;
737 auto srcType = GLES::GLTextureFormatType(info.srcFormat).type;
738 auto destInternalFormat = GLES::GLTextureFormatType(createInfo.format).internalFormat;
739 auto destFormat = GLES::GLTextureFormatType(createInfo.format).format;
741 // From render-texture.cpp
742 const bool isSubImage(info.dstOffset2D.x != 0 || info.dstOffset2D.y != 0 ||
743 info.srcExtent2D.width != (createInfo.size.width / (1 << info.level)) ||
744 info.srcExtent2D.height != (createInfo.size.height / (1 << info.level)));
746 uint8_t* sourceBuffer;
747 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
749 sourceBuffer = reinterpret_cast<uint8_t*>(source.memorySource.memory);
753 // Get buffer of PixelData
754 Dali::Integration::PixelDataBuffer pixelBufferData = Dali::Integration::GetPixelDataBuffer(source.pixelDataSource.pixelData);
756 sourceBuffer = pixelBufferData.buffer + info.srcOffset;
759 auto sourceStride = info.srcStride;
760 std::vector<uint8_t> tempBuffer;
762 if(mGlAbstraction->TextureRequiresConverting(srcFormat, destFormat, isSubImage))
764 // Convert RGB to RGBA if necessary.
765 if(texture->TryConvertPixelData(sourceBuffer, info.srcFormat, createInfo.format, info.srcSize, info.srcStride, info.srcExtent2D.width, info.srcExtent2D.height, tempBuffer))
767 sourceBuffer = &tempBuffer[0];
768 sourceStride = 0u; // Converted buffer compacted. make stride as 0.
769 srcFormat = destFormat;
770 srcType = GLES::GLTextureFormatType(createInfo.format).type;
774 // Calculate the maximum mipmap level for the texture
775 texture->SetMaxMipMapLevel(std::max(texture->GetMaxMipMapLevel(), info.level));
777 GLenum bindTarget{GL_TEXTURE_2D};
778 GLenum target{GL_TEXTURE_2D};
780 if(createInfo.textureType == Graphics::TextureType::TEXTURE_CUBEMAP)
782 bindTarget = GL_TEXTURE_CUBE_MAP;
783 target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + info.layer;
786 mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
787 mGlAbstraction->PixelStorei(GL_UNPACK_ROW_LENGTH, sourceStride);
789 mCurrentContext->BindTexture(bindTarget, texture->GetTextureTypeId(), texture->GetGLTexture());
793 if(!texture->IsCompressed())
795 mGlAbstraction->TexImage2D(target,
798 info.srcExtent2D.width,
799 info.srcExtent2D.height,
807 mGlAbstraction->CompressedTexImage2D(target,
810 info.srcExtent2D.width,
811 info.srcExtent2D.height,
819 if(!texture->IsCompressed())
821 mGlAbstraction->TexSubImage2D(target,
825 info.srcExtent2D.width,
826 info.srcExtent2D.height,
833 mGlAbstraction->CompressedTexSubImage2D(target,
837 info.srcExtent2D.width,
838 info.srcExtent2D.height,
845 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
847 // free staging memory
848 free(source.memorySource.memory);
854 // TODO: other sources
859 mTextureUpdateRequests.pop();
863 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>& updateInfoList,
864 const std::vector<TextureUpdateSourceInfo>& sourceList)
867 for(auto& info : updateInfoList)
869 mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
870 auto& pair = mTextureUpdateRequests.back();
871 switch(pair.second.sourceType)
873 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
875 auto& info = pair.first;
876 auto& source = pair.second;
878 // allocate staging memory and copy the data
879 // TODO: using PBO with GLES3, this is just naive
882 uint8_t* stagingBuffer = reinterpret_cast<uint8_t*>(malloc(info.srcSize));
884 uint8_t* srcMemory = &reinterpret_cast<uint8_t*>(source.memorySource.memory)[info.srcOffset];
886 std::copy(srcMemory, srcMemory + info.srcSize, stagingBuffer);
888 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
890 // store staging buffer
891 source.memorySource.memory = stagingBuffer;
894 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
896 // Increase CPU memory usage since ownership of PixelData is now on mTextureUpdateRequests.
897 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
900 case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
902 // TODO, with PBO support
905 case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
907 // TODO texture 2 texture in-GPU copy
913 // If upload buffer exceeds maximum size, flush.
914 if(mTextureUploadTotalCPUMemoryUsed > TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB * 1024 * 1024)
917 mTextureUploadTotalCPUMemoryUsed = 0;
921 void EglGraphicsController::ProcessTextureMipmapGenerationQueue()
923 while(!mTextureMipmapGenerationRequests.empty())
925 auto* texture = mTextureMipmapGenerationRequests.front();
927 mCurrentContext->BindTexture(texture->GetGlTarget(), texture->GetTextureTypeId(), texture->GetGLTexture());
928 mCurrentContext->GenerateMipmap(texture->GetGlTarget());
930 mTextureMipmapGenerationRequests.pop();
934 void EglGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
936 mTextureMipmapGenerationRequests.push(static_cast<const GLES::Texture*>(&texture));
939 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
941 // Mapping buffer requires the object to be created NOW
942 // Workaround - flush now, otherwise there will be given a staging buffer
943 // in case when the buffer is not there yet
944 if(!mCreateBufferQueue.empty())
946 mGraphics->ActivateResourceContext();
947 ProcessCreateQueues();
950 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
952 return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
956 return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
960 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
962 return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
965 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
967 return *mPipelineCache;
970 Graphics::Texture* EglGraphicsController::CreateTextureByResourceId(uint32_t resourceId, const Graphics::TextureCreateInfo& createInfo)
972 Graphics::Texture* ret = nullptr;
973 Graphics::UniquePtr<Graphics::Texture> texture;
975 auto iter = mExternalTextureResources.find(resourceId);
976 DALI_ASSERT_ALWAYS(iter == mExternalTextureResources.end());
978 texture = CreateTexture(createInfo, std::move(texture));
982 mExternalTextureResources.insert(std::make_pair(resourceId, std::move(texture)));
987 void EglGraphicsController::DiscardTextureFromResourceId(uint32_t resourceId)
989 auto iter = mExternalTextureResources.find(resourceId);
990 if(iter != mExternalTextureResources.end())
992 mExternalTextureResources.erase(iter);
996 Graphics::Texture* EglGraphicsController::GetTextureFromResourceId(uint32_t resourceId)
998 Graphics::Texture* ret = nullptr;
1000 auto iter = mExternalTextureResources.find(resourceId);
1001 if(iter != mExternalTextureResources.end())
1003 ret = iter->second.get();
1009 Graphics::UniquePtr<Graphics::Texture> EglGraphicsController::ReleaseTextureFromResourceId(uint32_t resourceId)
1011 Graphics::UniquePtr<Graphics::Texture> texture;
1013 auto iter = mExternalTextureResources.find(resourceId);
1014 if(iter != mExternalTextureResources.end())
1016 texture = std::move(iter->second);
1017 mExternalTextureResources.erase(iter);
1023 } // namespace Dali::Graphics