Merge branch 'devel/graphics' into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / egl-graphics-controller.cpp
1 /*
2  * Copyright (c) 2021 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/debug.h>
22 #include <dali/integration-api/gl-abstraction.h>
23 #include <dali/integration-api/gl-defines.h>
24 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
25 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
26 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
27 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
28 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
29 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
30 #include <dali/public-api/common/dali-common.h>
31 #include "gles-graphics-program.h"
32
33 namespace Dali::Graphics
34 {
35 namespace
36 {
37 /**
38  * @brief Custom deleter for all Graphics objects created
39  * with use of the Controller.
40  *
41  * When Graphics object dies the unique pointer (Graphics::UniquePtr)
42  * doesn't destroy it directly but passes the ownership back
43  * to the Controller. The GLESDeleter is responsible for passing
44  * the object to the discard queue (by calling Resource::DiscardResource()).
45  */
46 template<typename T>
47 struct GLESDeleter
48 {
49   GLESDeleter() = default;
50
51   void operator()(T* object)
52   {
53     // Discard resource (add it to discard queue)
54     object->DiscardResource();
55   }
56 };
57
58 /**
59  * @brief Helper function allocating graphics object
60  *
61  * @param[in] info Create info structure
62  * @param[in] controller Controller object
63  * @param[out] out Unique pointer to the return object
64  */
65 template<class GLESType, class GfxCreateInfo, class T>
66 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
67 {
68   // Use allocator
69   using Type = typename T::element_type;
70   using UPtr = Graphics::UniquePtr<Type>;
71   if(info.allocationCallbacks)
72   {
73     auto* memory = info.allocationCallbacks->allocCallback(
74       sizeof(GLESType),
75       0,
76       info.allocationCallbacks->userData);
77     return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
78   }
79   else // Use standard allocator
80   {
81     return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
82   }
83 }
84
85 template<class T0, class T1>
86 T0* CastObject(T1* apiObject)
87 {
88   return static_cast<T0*>(apiObject);
89 }
90
91 } // namespace
92
93 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
94 {
95   DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #1\n");
96   mGlAbstraction = &glAbstraction;
97   mContext       = std::make_unique<GLES::Context>(*this);
98 }
99
100 void EglGraphicsController::Initialize(Integration::GlSyncAbstraction&          glSyncAbstraction,
101                                        Integration::GlContextHelperAbstraction& glContextHelperAbstraction)
102 {
103   DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #2\n");
104   mGlSyncAbstraction          = &glSyncAbstraction;
105   mGlContextHelperAbstraction = &glContextHelperAbstraction;
106 }
107
108 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
109 {
110   for(auto& cmdbuf : submitInfo.cmdBuffer)
111   {
112     // Push command buffers
113     mCommandQueue.push(static_cast<GLES::CommandBuffer*>(cmdbuf));
114   }
115
116   // If flush bit set, flush all pending tasks
117   if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
118   {
119     Flush();
120   }
121 }
122
123 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
124 {
125   DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
126   return *mGlAbstraction;
127 }
128
129 Integration::GlSyncAbstraction& EglGraphicsController::GetGlSyncAbstraction()
130 {
131   DALI_ASSERT_DEBUG(mGlSyncAbstraction && "Graphics controller not initialized");
132   return *mGlSyncAbstraction;
133 }
134
135 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
136 {
137   DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
138   return *mGlContextHelperAbstraction;
139 }
140
141 Graphics::UniquePtr<CommandBuffer>
142 EglGraphicsController::CreateCommandBuffer(const CommandBufferCreateInfo&       commandBufferCreateInfo,
143                                            Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
144 {
145   return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
146 }
147
148 Graphics::UniquePtr<Texture>
149 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
150 {
151   return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
152 }
153
154 Graphics::UniquePtr<Buffer>
155 EglGraphicsController::CreateBuffer(const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
156 {
157   return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
158 }
159
160 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
161 {
162   // Create pipeline cache if needed
163   if(!mPipelineCache)
164   {
165     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
166   }
167
168   return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
169 }
170
171 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
172 {
173   // Create program cache if needed
174   if(!mPipelineCache)
175   {
176     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
177   }
178
179   return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
180 }
181
182 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
183 {
184   return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
185 }
186
187 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
188 {
189   return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
190 }
191
192 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
193 {
194   return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
195 }
196
197 void EglGraphicsController::AddTexture(GLES::Texture& texture)
198 {
199   // Assuming we are on the correct context
200   mCreateTextureQueue.push(&texture);
201 }
202
203 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
204 {
205   // Assuming we are on the correct context
206   mCreateBufferQueue.push(&buffer);
207 }
208
209 void EglGraphicsController::ProcessDiscardQueues()
210 {
211   // Process textures
212   ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
213
214   // Process buffers
215   ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
216
217   // Process pipelines
218   ProcessDiscardQueue<GLES::Pipeline>(mDiscardPipelineQueue);
219
220   // Process programs
221   ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
222 }
223
224 void EglGraphicsController::ProcessCreateQueues()
225 {
226   // Process textures
227   ProcessCreateQueue(mCreateTextureQueue);
228
229   // Process buffers
230   ProcessCreateQueue(mCreateBufferQueue);
231 }
232
233 void EglGraphicsController::ProcessCommandQueues()
234 {
235   // TODO: command queue per context, sync between queues should be
236   // done externally
237
238   while(!mCommandQueue.empty())
239   {
240     auto cmdBuf = mCommandQueue.front();
241     mCommandQueue.pop();
242
243     for(auto& cmd : cmdBuf->GetCommands())
244     {
245       // process command
246       switch(cmd.type)
247       {
248         case GLES::CommandType::FLUSH:
249         {
250           // Nothing to do here
251           break;
252         }
253         case GLES::CommandType::BIND_TEXTURES:
254         {
255           mContext->BindTextures(cmd.bindTextures.textureBindings);
256           break;
257         }
258         case GLES::CommandType::BIND_VERTEX_BUFFERS:
259         {
260           auto& bindings = cmd.bindVertexBuffers.vertexBufferBindings;
261           mContext->BindVertexBuffers(bindings);
262           break;
263         }
264         case GLES::CommandType::BIND_UNIFORM_BUFFER:
265         {
266           auto& bindings = cmd.bindUniformBuffers;
267           mContext->BindUniformBuffers(bindings.uniformBufferBindings, bindings.standaloneUniformsBufferBinding);
268           break;
269         }
270         case GLES::CommandType::BIND_INDEX_BUFFER:
271         {
272           mContext->BindIndexBuffer(cmd.bindIndexBuffer);
273           break;
274         }
275         case GLES::CommandType::BIND_SAMPLERS:
276         {
277           break;
278         }
279         case GLES::CommandType::BIND_PIPELINE:
280         {
281           mContext->BindPipeline(cmd.bindPipeline.pipeline);
282           break;
283         }
284         case GLES::CommandType::DRAW:
285         {
286           mContext->Flush(false, cmd.draw);
287           break;
288         }
289         case GLES::CommandType::DRAW_INDEXED:
290         {
291           mContext->Flush(false, cmd.draw);
292           break;
293         }
294         case GLES::CommandType::DRAW_INDEXED_INDIRECT:
295         {
296           mContext->Flush(false, cmd.draw);
297           break;
298         }
299         case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
300         {
301           mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
302           break;
303         }
304         case GLES::CommandType::SET_SCISSOR_TEST:
305         {
306           if(cmd.scissorTest.enable)
307           {
308             mGlAbstraction->Enable(GL_SCISSOR_TEST);
309           }
310           else
311           {
312             mGlAbstraction->Disable(GL_SCISSOR_TEST);
313           }
314           break;
315         }
316         case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
317         {
318           mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
319           break;
320         }
321       }
322     }
323   }
324 }
325
326 void EglGraphicsController::ProcessTextureUpdateQueue()
327 {
328   while(!mTextureUpdateRequests.empty())
329   {
330     TextureUpdateRequest& request = mTextureUpdateRequests.front();
331
332     auto& info   = request.first;
333     auto& source = request.second;
334
335     if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
336     {
337       // GPU memory must be already allocated (glTexImage2D())
338       auto*       texture    = static_cast<GLES::Texture*>(info.dstTexture);
339       const auto& createInfo = texture->GetCreateInfo();
340
341       mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
342
343       mGlAbstraction->BindTexture(GL_TEXTURE_2D, texture->GetGLTexture());
344       mGlAbstraction->TexSubImage2D(GL_TEXTURE_2D,
345                                     info.level,
346                                     info.dstOffset2D.x,
347                                     info.dstOffset2D.y,
348                                     info.srcExtent2D.width,
349                                     info.srcExtent2D.height,
350                                     GLES::GLTextureFormatType(createInfo.format).format,
351                                     GLES::GLTextureFormatType(createInfo.format).type,
352                                     source.memorySource.memory);
353
354       // free staging memory
355       free(source.memorySource.memory);
356     }
357     else
358     {
359       // TODO: other sources
360     }
361
362     mTextureUpdateRequests.pop();
363   }
364 }
365
366 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>&       updateInfoList,
367                                            const std::vector<TextureUpdateSourceInfo>& sourceList)
368 {
369   // Store updates
370   for(auto& info : updateInfoList)
371   {
372     mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
373     auto& pair = mTextureUpdateRequests.back();
374     switch(pair.second.sourceType)
375     {
376       case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
377       {
378         auto& info   = pair.first;
379         auto& source = pair.second;
380
381         // allocate staging memory and copy the data
382         // TODO: using PBO with GLES3, this is just naive
383         // oldschool way
384
385         char* stagingBuffer = reinterpret_cast<char*>(malloc(info.srcSize));
386         std::copy(&reinterpret_cast<char*>(source.memorySource.memory)[info.srcOffset],
387                   reinterpret_cast<char*>(source.memorySource.memory) + info.srcSize,
388                   stagingBuffer);
389
390         // store staging buffer
391         source.memorySource.memory = stagingBuffer;
392         break;
393       }
394       case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
395       {
396         // TODO, with PBO support
397         break;
398       }
399       case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
400       {
401         // TODO texture 2 texture in-GPU copy
402         break;
403       }
404     }
405   }
406 }
407
408 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
409 {
410   // Mapping buffer requires the object to be created NOW
411   // Workaround - flush now, otherwise there will be given a staging buffer
412   // in case when the buffer is not there yet
413   ProcessCreateQueues();
414
415   if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
416   {
417     return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
418   }
419   else
420   {
421     return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
422   }
423 }
424
425 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
426 {
427   return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
428 }
429
430 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
431 {
432   return *mPipelineCache;
433 }
434
435 } // namespace Dali::Graphics