Merge "TextureUploadManager implement" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / egl-graphics-controller.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // CLASS HEADER
18 #include <dali/internal/graphics/gles-impl/egl-graphics-controller.h>
19
20 // EXTERNAL INCLUDES
21 #include <dali/public-api/common/dali-common.h>
22
23 // INTERNAL INCLUDES
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>
42
43 #include <dali/internal/graphics/gles/egl-graphics.h>
44
45 #include <any>
46
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>
50 DUMP_FRAME_INIT();
51
52 namespace Dali::Graphics
53 {
54 namespace
55 {
56 /**
57  * @brief Custom deleter for all Graphics objects created
58  * with use of the Controller.
59  *
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()).
64  */
65 template<typename T>
66 struct GLESDeleter
67 {
68   GLESDeleter() = default;
69
70   void operator()(T* object)
71   {
72     // Discard resource (add it to discard queue)
73     object->DiscardResource();
74   }
75 };
76
77 /**
78  * @brief Helper function allocating graphics object
79  *
80  * @param[in] info Create info structure
81  * @param[in] controller Controller object
82  * @param[out] out Unique pointer to the return object
83  */
84 template<class GLESType, class GfxCreateInfo, class T>
85 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
86 {
87   // Use allocator
88   using Type = typename T::element_type;
89   using UPtr = Graphics::UniquePtr<Type>;
90   if(info.allocationCallbacks)
91   {
92     auto* memory = info.allocationCallbacks->allocCallback(
93       sizeof(GLESType),
94       0,
95       info.allocationCallbacks->userData);
96     return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
97   }
98   else // Use standard allocator
99   {
100     // We are given all object for recycling
101     if(oldObject)
102     {
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))
106       {
107         return UPtr(reusedObject, GLESDeleter<GLESType>());
108       }
109       else
110       {
111         // can't reuse so kill object by giving it back to original
112         // unique pointer.
113         oldObject.reset(reusedObject);
114       }
115     }
116
117     // Create brand new object
118     return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
119   }
120 }
121
122 template<class T0, class T1>
123 T0* CastObject(T1* apiObject)
124 {
125   return static_cast<T0*>(apiObject);
126 }
127
128 // Maximum size of texture upload buffer.
129 const uint32_t TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB = 1;
130
131 } // namespace
132
133 EglGraphicsController::EglGraphicsController()
134 : mTextureDependencyChecker(*this),
135   mSyncPool(*this)
136 {
137 }
138
139 EglGraphicsController::~EglGraphicsController()
140 {
141   while(!mPresentationCommandBuffers.empty())
142   {
143     auto presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
144     delete presentCommandBuffer;
145     mPresentationCommandBuffers.pop();
146   }
147 }
148
149 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
150 {
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();
155 }
156
157 void EglGraphicsController::Initialize(Integration::GraphicsSyncAbstraction&    syncImplementation,
158                                        Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
159                                        Internal::Adaptor::GraphicsInterface&    graphicsInterface)
160 {
161   DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 2\n");
162   auto* syncImplPtr = static_cast<Internal::Adaptor::EglSyncImplementation*>(&syncImplementation);
163
164   mEglSyncImplementation      = syncImplPtr;
165   mGlContextHelperAbstraction = &glContextHelperAbstraction;
166   mGraphics                   = &graphicsInterface;
167 }
168
169 void EglGraphicsController::FrameStart()
170 {
171   mCapacity = 0; // Reset the command buffer capacity at the start of the frame.
172 }
173
174 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
175 {
176   for(auto& cmdbuf : submitInfo.cmdBuffer)
177   {
178     // Push command buffers
179     auto* commandBuffer = static_cast<GLES::CommandBuffer*>(cmdbuf);
180     mCapacity += commandBuffer->GetCapacity();
181     mCommandQueue.push(commandBuffer);
182   }
183
184   // If flush bit set, flush all pending tasks
185   if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
186   {
187     Flush();
188   }
189 }
190
191 void EglGraphicsController::WaitIdle()
192 {
193   Flush();
194 }
195
196 void EglGraphicsController::PresentRenderTarget(RenderTarget* renderTarget)
197 {
198   GLES::CommandBuffer* presentCommandBuffer{nullptr};
199   if(mPresentationCommandBuffers.empty())
200   {
201     CommandBufferCreateInfo info;
202     info.SetLevel(CommandBufferLevel::PRIMARY);
203     info.fixedCapacity   = 1; // only one command
204     presentCommandBuffer = new GLES::CommandBuffer(info, *this);
205   }
206   else
207   {
208     presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
209     presentCommandBuffer->Reset();
210     mPresentationCommandBuffers.pop();
211   }
212   presentCommandBuffer->PresentRenderTarget(static_cast<GLES::RenderTarget*>(renderTarget));
213   SubmitInfo submitInfo;
214   submitInfo.cmdBuffer = {presentCommandBuffer};
215   submitInfo.flags     = 0 | SubmitFlagBits::FLUSH;
216   SubmitCommandBuffers(submitInfo);
217 }
218
219 void EglGraphicsController::ResolvePresentRenderTarget(GLES::RenderTarget* renderTarget)
220 {
221   mCurrentContext->InvalidateDepthStencilBuffers();
222
223   auto* rt = static_cast<GLES::RenderTarget*>(renderTarget);
224   if(rt->GetCreateInfo().surface)
225   {
226     auto* surfaceInterface = reinterpret_cast<Dali::RenderSurfaceInterface*>(rt->GetCreateInfo().surface);
227     surfaceInterface->MakeContextCurrent();
228     surfaceInterface->PostRender();
229   }
230 }
231
232 void EglGraphicsController::PostRender()
233 {
234   mTextureDependencyChecker.Reset();
235   mSyncPool.AgeSyncObjects();
236 }
237
238 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
239 {
240   DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
241   return *mGlAbstraction;
242 }
243
244 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
245 {
246   DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
247   return *mGlContextHelperAbstraction;
248 }
249
250 Internal::Adaptor::EglSyncImplementation& EglGraphicsController::GetEglSyncImplementation()
251 {
252   DALI_ASSERT_DEBUG(mEglSyncImplementation && "Sync implementation not initialized");
253   return *mEglSyncImplementation;
254 }
255
256 Graphics::UniquePtr<CommandBuffer> EglGraphicsController::CreateCommandBuffer(
257   const CommandBufferCreateInfo&       commandBufferCreateInfo,
258   Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
259 {
260   return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
261 }
262
263 Graphics::UniquePtr<RenderPass> EglGraphicsController::CreateRenderPass(const RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<RenderPass>&& oldRenderPass)
264 {
265   return NewObject<GLES::RenderPass>(renderPassCreateInfo, *this, std::move(oldRenderPass));
266 }
267
268 Graphics::UniquePtr<Texture>
269 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
270 {
271   return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
272 }
273
274 Graphics::UniquePtr<Buffer> EglGraphicsController::CreateBuffer(
275   const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
276 {
277   return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
278 }
279
280 Graphics::UniquePtr<Framebuffer> EglGraphicsController::CreateFramebuffer(
281   const FramebufferCreateInfo& framebufferCreateInfo, Graphics::UniquePtr<Framebuffer>&& oldFramebuffer)
282 {
283   return NewObject<GLES::Framebuffer>(framebufferCreateInfo, *this, std::move(oldFramebuffer));
284 }
285
286 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(
287   const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
288 {
289   // Create pipeline cache if needed
290   if(!mPipelineCache)
291   {
292     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
293   }
294
295   return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
296 }
297
298 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(
299   const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
300 {
301   // Create program cache if needed
302   if(!mPipelineCache)
303   {
304     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
305   }
306
307   return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
308 }
309
310 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
311 {
312   return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
313 }
314
315 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
316 {
317   return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
318 }
319
320 Graphics::UniquePtr<RenderTarget> EglGraphicsController::CreateRenderTarget(const RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<RenderTarget>&& oldRenderTarget)
321 {
322   return NewObject<GLES::RenderTarget>(renderTargetCreateInfo, *this, std::move(oldRenderTarget));
323 }
324
325 Graphics::UniquePtr<SyncObject> EglGraphicsController::CreateSyncObject(const SyncObjectCreateInfo& syncObjectCreateInfo,
326                                                                         UniquePtr<SyncObject>&&     oldSyncObject)
327 {
328   if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
329   {
330     return NewObject<EGL::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
331   }
332   else
333   {
334     return NewObject<GLES::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
335   }
336 }
337
338 MemoryRequirements EglGraphicsController::GetBufferMemoryRequirements(Buffer& buffer) const
339 {
340   MemoryRequirements requirements{};
341
342   auto gl = GetGL();
343   if(gl)
344   {
345     GLint align;
346     gl->GetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align);
347     requirements.alignment = align;
348   }
349   return requirements;
350 }
351
352 TextureProperties EglGraphicsController::GetTextureProperties(const Texture& texture)
353 {
354   const GLES::Texture* glesTexture = static_cast<const GLES::Texture*>(&texture);
355   auto                 createInfo  = glesTexture->GetCreateInfo();
356
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
363
364   return properties;
365 }
366
367 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
368 {
369   return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
370 }
371
372 void EglGraphicsController::CreateSurfaceContext(Dali::RenderSurfaceInterface* surface)
373 {
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))));
376 }
377
378 void EglGraphicsController::DeleteSurfaceContext(Dali::RenderSurfaceInterface* surface)
379 {
380   mSurfaceContexts.erase(std::remove_if(
381                            mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return surface == iter.first; }),
382                          mSurfaceContexts.end());
383 }
384
385 void EglGraphicsController::ActivateResourceContext()
386 {
387   mCurrentContext = mContext.get();
388   mCurrentContext->GlContextCreated();
389   if(!mSharedContext)
390   {
391     auto eglGraphics = dynamic_cast<Dali::Internal::Adaptor::EglGraphics*>(mGraphics);
392     if(eglGraphics)
393     {
394       mSharedContext = eglGraphics->GetEglImplementation().GetContext();
395     }
396   }
397 }
398
399 void EglGraphicsController::ActivateSurfaceContext(Dali::RenderSurfaceInterface* surface)
400 {
401   if(surface && mGraphics->IsResourceContextSupported())
402   {
403     auto iter = std::find_if(mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return (iter.first == surface); });
404
405     if(iter != mSurfaceContexts.end())
406     {
407       mCurrentContext = iter->second.get();
408       mCurrentContext->GlContextCreated();
409     }
410   }
411 }
412
413 void EglGraphicsController::AddTexture(GLES::Texture& texture)
414 {
415   // Assuming we are on the correct context
416   mCreateTextureQueue.push(&texture);
417 }
418
419 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
420 {
421   // Assuming we are on the correct context
422   mCreateBufferQueue.push(&buffer);
423 }
424
425 void EglGraphicsController::AddFramebuffer(GLES::Framebuffer& framebuffer)
426 {
427   // Assuming we are on the correct context
428   mCreateFramebufferQueue.push(&framebuffer);
429 }
430
431 void EglGraphicsController::ProcessDiscardQueues()
432 {
433   // Process textures
434   ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
435
436   // Process buffers
437   ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
438
439   // Process Framebuffers
440   ProcessDiscardQueue<GLES::Framebuffer>(mDiscardFramebufferQueue);
441
442   // Process RenderPass
443   ProcessDiscardQueue<GLES::RenderPass>(mDiscardRenderPassQueue);
444
445   // Process RenderTarget
446   ProcessDiscardQueue<GLES::RenderTarget>(mDiscardRenderTargetQueue);
447
448   // Process pipelines
449   ProcessDiscardQueue(mDiscardPipelineQueue);
450
451   // Process programs
452   ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
453
454   // Process shaders
455   ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
456
457   // Process samplers
458   ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
459
460   // Process command buffers
461   ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
462 }
463
464 void EglGraphicsController::ProcessCreateQueues()
465 {
466   // Process textures
467   ProcessCreateQueue(mCreateTextureQueue);
468
469   // Process buffers
470   ProcessCreateQueue(mCreateBufferQueue);
471
472   // Process framebuffers
473   ProcessCreateQueue(mCreateFramebufferQueue);
474 }
475
476 void EglGraphicsController::ProcessCommandBuffer(const GLES::CommandBuffer& commandBuffer)
477 {
478   auto       count    = 0u;
479   const auto commands = commandBuffer.GetCommands(count);
480   for(auto i = 0u; i < count; ++i)
481   {
482     auto& cmd = commands[i];
483     // process command
484     switch(cmd.type)
485     {
486       case GLES::CommandType::FLUSH:
487       {
488         // Nothing to do here
489         break;
490       }
491       case GLES::CommandType::BIND_TEXTURES:
492       {
493         mCurrentContext->BindTextures(cmd.bindTextures.textureBindings.Ptr(), cmd.bindTextures.textureBindingsCount);
494         break;
495       }
496       case GLES::CommandType::BIND_VERTEX_BUFFERS:
497       {
498         auto bindings = cmd.bindVertexBuffers.vertexBufferBindings.Ptr();
499         mCurrentContext->BindVertexBuffers(bindings, cmd.bindVertexBuffers.vertexBufferBindingsCount);
500         break;
501       }
502       case GLES::CommandType::BIND_UNIFORM_BUFFER:
503       {
504         auto& bindings = cmd.bindUniformBuffers;
505         mCurrentContext->BindUniformBuffers(bindings.uniformBufferBindingsCount ? bindings.uniformBufferBindings.Ptr() : nullptr, bindings.uniformBufferBindingsCount, bindings.standaloneUniformsBufferBinding);
506         break;
507       }
508       case GLES::CommandType::BIND_INDEX_BUFFER:
509       {
510         mCurrentContext->BindIndexBuffer(cmd.bindIndexBuffer);
511         break;
512       }
513       case GLES::CommandType::BIND_SAMPLERS:
514       {
515         break;
516       }
517       case GLES::CommandType::BIND_PIPELINE:
518       {
519         auto pipeline = static_cast<const GLES::Pipeline*>(cmd.bindPipeline.pipeline);
520         mCurrentContext->BindPipeline(pipeline);
521         break;
522       }
523       case GLES::CommandType::DRAW:
524       {
525         mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
526         break;
527       }
528       case GLES::CommandType::DRAW_INDEXED:
529       {
530         mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
531         break;
532       }
533       case GLES::CommandType::DRAW_INDEXED_INDIRECT:
534       {
535         mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
536         break;
537       }
538       case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
539       {
540         mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
541         break;
542       }
543       case GLES::CommandType::SET_SCISSOR_TEST:
544       {
545         mCurrentContext->SetScissorTestEnabled(cmd.scissorTest.enable);
546         break;
547       }
548       case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
549       {
550         mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
551         break;
552       }
553
554       case GLES::CommandType::SET_COLOR_MASK:
555       {
556         mCurrentContext->ColorMask(cmd.colorMask.enabled);
557         break;
558       }
559       case GLES::CommandType::CLEAR_STENCIL_BUFFER:
560       {
561         mCurrentContext->ClearStencilBuffer();
562         break;
563       }
564       case GLES::CommandType::CLEAR_DEPTH_BUFFER:
565       {
566         mCurrentContext->ClearDepthBuffer();
567         break;
568       }
569
570       case GLES::CommandType::SET_STENCIL_TEST_ENABLE:
571       {
572         mCurrentContext->SetStencilTestEnable(cmd.stencilTest.enabled);
573         break;
574       }
575
576       case GLES::CommandType::SET_STENCIL_FUNC:
577       {
578         mCurrentContext->StencilFunc(cmd.stencilFunc.compareOp,
579                                      cmd.stencilFunc.reference,
580                                      cmd.stencilFunc.compareMask);
581         break;
582       }
583
584       case GLES::CommandType::SET_STENCIL_WRITE_MASK:
585       {
586         mCurrentContext->StencilMask(cmd.stencilWriteMask.mask);
587         break;
588       }
589
590       case GLES::CommandType::SET_STENCIL_OP:
591       {
592         mCurrentContext->StencilOp(cmd.stencilOp.failOp,
593                                    cmd.stencilOp.depthFailOp,
594                                    cmd.stencilOp.passOp);
595         break;
596       }
597
598       case GLES::CommandType::SET_DEPTH_COMPARE_OP:
599       {
600         mCurrentContext->SetDepthCompareOp(cmd.depth.compareOp);
601         break;
602       }
603       case GLES::CommandType::SET_DEPTH_TEST_ENABLE:
604       {
605         mCurrentContext->SetDepthTestEnable(cmd.depth.testEnabled);
606         break;
607       }
608       case GLES::CommandType::SET_DEPTH_WRITE_ENABLE:
609       {
610         mCurrentContext->SetDepthWriteEnable(cmd.depth.writeEnabled);
611         break;
612       }
613
614       case GLES::CommandType::BEGIN_RENDERPASS:
615       {
616         auto&       renderTarget = *cmd.beginRenderPass.renderTarget;
617         const auto& targetInfo   = renderTarget.GetCreateInfo();
618
619         if(targetInfo.surface)
620         {
621           // switch to surface context
622           mGraphics->ActivateSurfaceContext(static_cast<Dali::RenderSurfaceInterface*>(targetInfo.surface));
623         }
624         else if(targetInfo.framebuffer)
625         {
626           // switch to resource context
627           mGraphics->ActivateResourceContext();
628         }
629
630         mCurrentContext->BeginRenderPass(cmd.beginRenderPass);
631
632         break;
633       }
634       case GLES::CommandType::END_RENDERPASS:
635       {
636         mCurrentContext->EndRenderPass(mTextureDependencyChecker);
637
638         // This sync object is to enable cpu to wait for rendering to complete, not gpu.
639         // It's only needed for reading the framebuffer texture in the client.
640         auto syncObject = const_cast<GLES::SyncObject*>(static_cast<const GLES::SyncObject*>(cmd.endRenderPass.syncObject));
641         if(syncObject)
642         {
643           syncObject->InitializeResource();
644         }
645         break;
646       }
647       case GLES::CommandType::PRESENT_RENDER_TARGET:
648       {
649         ResolvePresentRenderTarget(cmd.presentRenderTarget.targetToPresent);
650
651         // The command buffer will be pushed into the queue of presentation command buffers
652         // for further reuse.
653         if(commandBuffer.GetCreateInfo().fixedCapacity == 1)
654         {
655           mPresentationCommandBuffers.push(&commandBuffer);
656         }
657         break;
658       }
659       case GLES::CommandType::EXECUTE_COMMAND_BUFFERS:
660       {
661         // Process secondary command buffers
662         // todo: check validity of the secondaries
663         //       there are operations which are illigal to be done
664         //       within secondaries.
665         auto buffers = cmd.executeCommandBuffers.buffers.Ptr();
666         for(auto j = 0u; j < cmd.executeCommandBuffers.buffersCount; ++j)
667         {
668           auto& buf = buffers[j];
669           ProcessCommandBuffer(*static_cast<const GLES::CommandBuffer*>(buf));
670         }
671         break;
672       }
673       case GLES::CommandType::DRAW_NATIVE:
674       {
675         auto* info = &cmd.drawNative.drawNativeInfo;
676
677         mCurrentContext->PrepareForNativeRendering();
678
679         if(info->glesNativeInfo.eglSharedContextStoragePointer)
680         {
681           auto* anyContext = reinterpret_cast<std::any*>(info->glesNativeInfo.eglSharedContextStoragePointer);
682           *anyContext      = mSharedContext;
683         }
684
685         CallbackBase::ExecuteReturn<bool>(*info->callback, info->userData);
686
687         mCurrentContext->RestoreFromNativeRendering();
688         break;
689       }
690     }
691   }
692 }
693
694 void EglGraphicsController::ProcessCommandQueues()
695 {
696   DUMP_FRAME_START();
697
698   while(!mCommandQueue.empty())
699   {
700     auto cmdBuf = mCommandQueue.front();
701     mCommandQueue.pop();
702     DUMP_FRAME_COMMAND_BUFFER(cmdBuf);
703     ProcessCommandBuffer(*cmdBuf);
704   }
705
706   DUMP_FRAME_END();
707 }
708
709 void EglGraphicsController::ProcessTextureUpdateQueue()
710 {
711   while(!mTextureUpdateRequests.empty())
712   {
713     TextureUpdateRequest& request = mTextureUpdateRequests.front();
714
715     auto& info   = request.first;
716     auto& source = request.second;
717
718     switch(source.sourceType)
719     {
720       case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
721       case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
722       {
723         // GPU memory must be already allocated.
724
725         // Check if it needs conversion
726         auto*       texture            = static_cast<GLES::Texture*>(info.dstTexture);
727         const auto& createInfo         = texture->GetCreateInfo();
728         auto        srcFormat          = GLES::GLTextureFormatType(info.srcFormat).format;
729         auto        srcType            = GLES::GLTextureFormatType(info.srcFormat).type;
730         auto        destInternalFormat = GLES::GLTextureFormatType(createInfo.format).internalFormat;
731         auto        destFormat         = GLES::GLTextureFormatType(createInfo.format).format;
732
733         // From render-texture.cpp
734         const bool isSubImage(info.dstOffset2D.x != 0 || info.dstOffset2D.y != 0 ||
735                               info.srcExtent2D.width != (createInfo.size.width / (1 << info.level)) ||
736                               info.srcExtent2D.height != (createInfo.size.height / (1 << info.level)));
737
738         uint8_t* sourceBuffer;
739         if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
740         {
741           sourceBuffer = reinterpret_cast<uint8_t*>(source.memorySource.memory);
742         }
743         else
744         {
745           // Get buffer of PixelData
746           Dali::Integration::PixelDataBuffer pixelBufferData = Dali::Integration::GetPixelDataBuffer(source.pixelDataSource.pixelData);
747
748           sourceBuffer = pixelBufferData.buffer + info.srcOffset;
749         }
750
751         auto                 sourceStride = info.srcStride;
752         std::vector<uint8_t> tempBuffer;
753
754         if(mGlAbstraction->TextureRequiresConverting(srcFormat, destFormat, isSubImage))
755         {
756           // Convert RGB to RGBA if necessary.
757           if(texture->TryConvertPixelData(sourceBuffer, info.srcFormat, createInfo.format, info.srcSize, info.srcStride, info.srcExtent2D.width, info.srcExtent2D.height, tempBuffer))
758           {
759             sourceBuffer = &tempBuffer[0];
760             sourceStride = 0u; // Converted buffer compacted. make stride as 0.
761             srcFormat    = destFormat;
762             srcType      = GLES::GLTextureFormatType(createInfo.format).type;
763           }
764         }
765
766         // Calculate the maximum mipmap level for the texture
767         texture->SetMaxMipMapLevel(std::max(texture->GetMaxMipMapLevel(), info.level));
768
769         GLenum bindTarget{GL_TEXTURE_2D};
770         GLenum target{GL_TEXTURE_2D};
771
772         if(createInfo.textureType == Graphics::TextureType::TEXTURE_CUBEMAP)
773         {
774           bindTarget = GL_TEXTURE_CUBE_MAP;
775           target     = GL_TEXTURE_CUBE_MAP_POSITIVE_X + info.layer;
776         }
777
778         mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
779         mGlAbstraction->PixelStorei(GL_UNPACK_ROW_LENGTH, sourceStride);
780
781         mCurrentContext->BindTexture(bindTarget, texture->GetTextureTypeId(), texture->GetGLTexture());
782
783         if(!isSubImage)
784         {
785           if(!texture->IsCompressed())
786           {
787             mGlAbstraction->TexImage2D(target,
788                                        info.level,
789                                        destInternalFormat,
790                                        info.srcExtent2D.width,
791                                        info.srcExtent2D.height,
792                                        0,
793                                        srcFormat,
794                                        srcType,
795                                        sourceBuffer);
796           }
797           else
798           {
799             mGlAbstraction->CompressedTexImage2D(target,
800                                                  info.level,
801                                                  destInternalFormat,
802                                                  info.srcExtent2D.width,
803                                                  info.srcExtent2D.height,
804                                                  0,
805                                                  info.srcSize,
806                                                  sourceBuffer);
807           }
808         }
809         else
810         {
811           if(!texture->IsCompressed())
812           {
813             mGlAbstraction->TexSubImage2D(target,
814                                           info.level,
815                                           info.dstOffset2D.x,
816                                           info.dstOffset2D.y,
817                                           info.srcExtent2D.width,
818                                           info.srcExtent2D.height,
819                                           srcFormat,
820                                           srcType,
821                                           sourceBuffer);
822           }
823           else
824           {
825             mGlAbstraction->CompressedTexSubImage2D(target,
826                                                     info.level,
827                                                     info.dstOffset2D.x,
828                                                     info.dstOffset2D.y,
829                                                     info.srcExtent2D.width,
830                                                     info.srcExtent2D.height,
831                                                     srcFormat,
832                                                     info.srcSize,
833                                                     sourceBuffer);
834           }
835         }
836
837         if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
838         {
839           // free staging memory
840           free(source.memorySource.memory);
841         }
842         break;
843       }
844       default:
845       {
846         // TODO: other sources
847         break;
848       }
849     }
850
851     mTextureUpdateRequests.pop();
852   }
853 }
854
855 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>&       updateInfoList,
856                                            const std::vector<TextureUpdateSourceInfo>& sourceList)
857 {
858   // Store updates
859   for(auto& info : updateInfoList)
860   {
861     mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
862     auto& pair = mTextureUpdateRequests.back();
863     switch(pair.second.sourceType)
864     {
865       case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
866       {
867         auto& info   = pair.first;
868         auto& source = pair.second;
869
870         // allocate staging memory and copy the data
871         // TODO: using PBO with GLES3, this is just naive
872         // oldschool way
873
874         uint8_t* stagingBuffer = reinterpret_cast<uint8_t*>(malloc(info.srcSize));
875
876         uint8_t* srcMemory = &reinterpret_cast<uint8_t*>(source.memorySource.memory)[info.srcOffset];
877
878         std::copy(srcMemory, srcMemory + info.srcSize, stagingBuffer);
879
880         mTextureUploadTotalCPUMemoryUsed += info.srcSize;
881
882         // store staging buffer
883         source.memorySource.memory = stagingBuffer;
884         break;
885       }
886       case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
887       {
888         // Increase CPU memory usage since ownership of PixelData is now on mTextureUpdateRequests.
889         mTextureUploadTotalCPUMemoryUsed += info.srcSize;
890         break;
891       }
892       case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
893       {
894         // TODO, with PBO support
895         break;
896       }
897       case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
898       {
899         // TODO texture 2 texture in-GPU copy
900         break;
901       }
902     }
903   }
904
905   // If upload buffer exceeds maximum size, flush.
906   if(mTextureUploadTotalCPUMemoryUsed > TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB * 1024 * 1024)
907   {
908     Flush();
909     mTextureUploadTotalCPUMemoryUsed = 0;
910   }
911 }
912
913 void EglGraphicsController::ProcessTextureMipmapGenerationQueue()
914 {
915   while(!mTextureMipmapGenerationRequests.empty())
916   {
917     auto* texture = mTextureMipmapGenerationRequests.front();
918
919     mCurrentContext->BindTexture(texture->GetGlTarget(), texture->GetTextureTypeId(), texture->GetGLTexture());
920     mCurrentContext->GenerateMipmap(texture->GetGlTarget());
921
922     mTextureMipmapGenerationRequests.pop();
923   }
924 }
925
926 void EglGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
927 {
928   mTextureMipmapGenerationRequests.push(static_cast<const GLES::Texture*>(&texture));
929 }
930
931 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
932 {
933   // Mapping buffer requires the object to be created NOW
934   // Workaround - flush now, otherwise there will be given a staging buffer
935   // in case when the buffer is not there yet
936   if(!mCreateBufferQueue.empty())
937   {
938     mGraphics->ActivateResourceContext();
939     ProcessCreateQueues();
940   }
941
942   if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
943   {
944     return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
945   }
946   else
947   {
948     return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
949   }
950 }
951
952 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
953 {
954   return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
955 }
956
957 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
958 {
959   return *mPipelineCache;
960 }
961
962 Graphics::Texture* EglGraphicsController::CreateTextureByResourceId(uint32_t resourceId, const Graphics::TextureCreateInfo& createInfo)
963 {
964   Graphics::Texture*                     ret = nullptr;
965   Graphics::UniquePtr<Graphics::Texture> texture;
966
967   auto iter = mExternalTextureResources.find(resourceId);
968   DALI_ASSERT_ALWAYS(iter == mExternalTextureResources.end());
969
970   texture = CreateTexture(createInfo, std::move(texture));
971
972   ret = texture.get();
973
974   mExternalTextureResources.insert(std::make_pair(resourceId, std::move(texture)));
975
976   return ret;
977 }
978
979 void EglGraphicsController::DiscardTextureFromResourceId(uint32_t resourceId)
980 {
981   auto iter = mExternalTextureResources.find(resourceId);
982   if(iter != mExternalTextureResources.end())
983   {
984     mExternalTextureResources.erase(iter);
985   }
986 }
987
988 Graphics::Texture* EglGraphicsController::GetTextureFromResourceId(uint32_t resourceId)
989 {
990   Graphics::Texture* ret = nullptr;
991
992   auto iter = mExternalTextureResources.find(resourceId);
993   if(iter != mExternalTextureResources.end())
994   {
995     ret = iter->second.get();
996   }
997
998   return ret;
999 }
1000
1001 Graphics::UniquePtr<Graphics::Texture> EglGraphicsController::ReleaseTextureFromResourceId(uint32_t resourceId)
1002 {
1003   Graphics::UniquePtr<Graphics::Texture> texture;
1004
1005   auto iter = mExternalTextureResources.find(resourceId);
1006   if(iter != mExternalTextureResources.end())
1007   {
1008     texture = std::move(iter->second);
1009     mExternalTextureResources.erase(iter);
1010   }
1011
1012   return texture;
1013 }
1014
1015 } // namespace Dali::Graphics