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