Merge branch 'devel/graphics' into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / gles-context.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
18 #include "gles-context.h"
19 #include <dali/integration-api/gl-abstraction.h>
20 #include <dali/integration-api/gl-defines.h>
21 #include "gles-graphics-buffer.h"
22 #include "gles-graphics-command-buffer.h"
23 #include "gles-graphics-pipeline.h"
24 #include "gles-graphics-program.h"
25
26 namespace Dali::Graphics::GLES
27 {
28 struct Context::Impl
29 {
30   Impl(EglGraphicsController& controller)
31   : mController(controller)
32   {
33   }
34
35   ~Impl() = default;
36
37   EglGraphicsController& mController;
38
39   const GLES::Pipeline* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
40   const GLES::Pipeline* mNewPipeline{nullptr};     ///< New pipeline to be set on flush
41
42   std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
43   std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
44   GLES::IndexBufferBindingDescriptor    mCurrentIndexBufferBinding{};
45
46   struct VertexBufferBinding
47   {
48     GLES::Buffer* buffer{nullptr};
49     uint32_t      offset{0u};
50   };
51
52   // Currently bound buffers
53   std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
54
55   // Currently bound UBOs (check if it's needed per program!)
56   std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
57   UniformBufferBindingDescriptor              mCurrentStandaloneUBOBinding{};
58 };
59
60 Context::Context(EglGraphicsController& controller)
61 {
62   mImpl = std::make_unique<Impl>(controller);
63 }
64
65 Context::~Context() = default;
66
67 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall)
68 {
69   auto& gl = *mImpl->mController.GetGL();
70
71   // Change pipeline
72   if(mImpl->mNewPipeline)
73   {
74     // Execute states if different
75     mImpl->mCurrentPipeline = mImpl->mNewPipeline;
76     mImpl->mNewPipeline     = nullptr;
77   }
78   mImpl->mCurrentPipeline->GetPipeline().Bind(nullptr);
79
80   // Blend state
81   ResolveBlendState();
82
83   // Resolve rasterization state
84   ResolveRasterizationState();
85
86   // Resolve uniform buffers
87   ResolveUniformBuffers();
88
89   // Bind textures
90   for(const auto& binding : mImpl->mCurrentTextureBindings)
91   {
92     auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
93
94     // Texture may not have been initialized yet...(tbm_surface timing issue?)
95     if(!texture->GetGLTexture())
96     {
97       // Attempt to reinitialize
98       // @todo need to put this somewhere else where it isn't const.
99       // Maybe post it back on end of initialize queue if initialization fails?
100       texture->InitializeResource();
101     }
102
103     texture->Bind(binding);
104     texture->Prepare(); // @todo also non-const.
105   }
106
107   // for each attribute bind vertices
108   const auto& pipelineState = mImpl->mCurrentPipeline->GetCreateInfo();
109   const auto& vi            = pipelineState.vertexInputState;
110   for(const auto& attr : vi->attributes)
111   {
112     // Enable location
113     gl.EnableVertexAttribArray(attr.location);
114     const auto& bufferSlot    = mImpl->mCurrentVertexBufferBindings[attr.binding];
115     const auto& bufferBinding = vi->bufferBindings[attr.binding];
116
117     auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
118
119     // Bind buffer
120     gl.BindBuffer(GL_ARRAY_BUFFER, glesBuffer);
121     gl.VertexAttribPointer(attr.location,
122                            GLVertexFormat(attr.format).size,
123                            GLVertexFormat(attr.format).format,
124                            GL_FALSE,
125                            bufferBinding.stride,
126                            reinterpret_cast<void*>(attr.offset));
127   }
128
129   // Resolve topology
130   const auto& ia = mImpl->mCurrentPipeline->GetCreateInfo().inputAssemblyState;
131
132   // Bind uniforms
133
134   // Resolve draw call
135   switch(drawCall.type)
136   {
137     case DrawCallDescriptor::Type::DRAW:
138     {
139       gl.DrawArrays(GLESTopology(ia->topology),
140                     drawCall.draw.firstVertex,
141                     drawCall.draw.vertexCount);
142       break;
143     }
144     case DrawCallDescriptor::Type::DRAW_INDEXED:
145     {
146       const auto& binding    = mImpl->mCurrentIndexBufferBinding;
147       const auto* glesBuffer = binding.buffer;
148       gl.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, glesBuffer->GetGLBuffer());
149       auto indexBufferFormat = GLIndexFormat(binding.format).format;
150       gl.DrawElements(GLESTopology(ia->topology),
151                       drawCall.drawIndexed.indexCount,
152                       indexBufferFormat,
153                       reinterpret_cast<void*>(binding.offset));
154       break;
155     }
156     case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
157     {
158       break;
159     }
160   }
161 }
162
163 void Context::BindTextures(const std::vector<Graphics::TextureBinding>& bindings)
164 {
165   // for each texture allocate slot
166   for(const auto& binding : bindings)
167   {
168     // Resize binding array if needed
169     if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
170     {
171       mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
172     }
173     // Store the binding details
174     mImpl->mCurrentTextureBindings[binding.binding] = binding;
175   }
176 }
177
178 void Context::BindVertexBuffers(const std::vector<GLES::VertexBufferBindingDescriptor>& bindings)
179 {
180   if(bindings.size() > mImpl->mCurrentVertexBufferBindings.size())
181   {
182     mImpl->mCurrentVertexBufferBindings.resize(bindings.size());
183   }
184   // Copy only set slots
185   std::copy_if(bindings.begin(), bindings.end(), mImpl->mCurrentVertexBufferBindings.begin(), [](auto& item) {
186     return (nullptr != item.buffer);
187   });
188 }
189
190 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
191 {
192   mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
193 }
194
195 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
196 {
197   mImpl->mNewPipeline = newPipeline;
198 }
199
200 void Context::BindUniformBuffers(const std::vector<UniformBufferBindingDescriptor>& uboBindings,
201                                  const UniformBufferBindingDescriptor&              standaloneBindings)
202 {
203   if(standaloneBindings.buffer)
204   {
205     mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
206   }
207
208   if(uboBindings.size() >= mImpl->mCurrentUBOBindings.size())
209   {
210     mImpl->mCurrentUBOBindings.resize(uboBindings.size() + 1);
211   }
212
213   auto it = uboBindings.begin();
214   for(auto i = 0u; i < uboBindings.size(); ++i)
215   {
216     if(it->buffer)
217     {
218       mImpl->mCurrentUBOBindings[i] = *it;
219     }
220   }
221 }
222
223 void Context::ResolveBlendState()
224 {
225   const auto& state = mImpl->mCurrentPipeline->GetCreateInfo();
226   const auto& bs    = state.colorBlendState;
227   auto&       gl    = *mImpl->mController.GetGL();
228
229   // TODO: prevent leaking the state
230   if(!bs)
231   {
232     return;
233   }
234
235   bs->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
236   if(!bs->blendEnable)
237   {
238     return;
239   }
240
241   gl.BlendFunc(GLBlendFunc(bs->srcColorBlendFactor), GLBlendFunc(bs->dstColorBlendFactor));
242
243   if((GLBlendFunc(bs->srcColorBlendFactor) == GLBlendFunc(bs->srcAlphaBlendFactor)) &&
244      (GLBlendFunc(bs->dstColorBlendFactor) == GLBlendFunc(bs->dstAlphaBlendFactor)))
245   {
246     gl.BlendFunc(GLBlendFunc(bs->srcColorBlendFactor), GLBlendFunc(bs->dstColorBlendFactor));
247   }
248   else
249   {
250     gl.BlendFuncSeparate(GLBlendFunc(bs->srcColorBlendFactor),
251                          GLBlendFunc(bs->dstColorBlendFactor),
252                          GLBlendFunc(bs->srcAlphaBlendFactor),
253                          GLBlendFunc(bs->dstAlphaBlendFactor));
254   }
255   if(GLBlendOp(bs->colorBlendOp) == GLBlendOp(bs->alphaBlendOp))
256   {
257     gl.BlendEquation(GLBlendOp(bs->colorBlendOp));
258   }
259   else
260   {
261     gl.BlendEquationSeparate(GLBlendOp(bs->colorBlendOp), GLBlendOp(bs->alphaBlendOp));
262   }
263 }
264
265 void Context::ResolveRasterizationState()
266 {
267   const auto& state = mImpl->mCurrentPipeline->GetCreateInfo();
268   const auto& rs    = state.rasterizationState;
269   auto&       gl    = *mImpl->mController.GetGL();
270
271   // TODO: prevent leaking the state
272   if(!rs)
273   {
274     return;
275   }
276
277   if(rs->cullMode == CullMode::NONE)
278   {
279     gl.Disable(GL_CULL_FACE);
280   }
281   else
282   {
283     gl.Enable(GL_CULL_FACE);
284     gl.CullFace(GLCullMode(rs->cullMode));
285   }
286
287   // TODO: implement polygon mode (fill, line, points)
288   //       seems like we don't support it (no glPolygonMode())
289 }
290
291 void Context::ResolveUniformBuffers()
292 {
293   // Resolve standalone uniforms if we have binding
294   if(mImpl->mCurrentStandaloneUBOBinding.buffer)
295   {
296     ResolveStandaloneUniforms();
297   }
298 }
299
300 void Context::ResolveStandaloneUniforms()
301 {
302   auto& gl = *mImpl->mController.GetGL();
303
304   // Find reflection for program
305   const auto program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
306
307   const auto& reflection = program->GetReflection();
308
309   auto extraInfos = reflection.GetStandaloneUniformExtraInfo();
310
311   const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress());
312
313   for(const auto& info : extraInfos)
314   {
315     auto type   = GLTypeConversion(info.type).type;
316     auto offset = info.offset;
317     switch(type)
318     {
319       case GLType::FLOAT_VEC2:
320       {
321         gl.Uniform2fv(info.location, info.arraySize, reinterpret_cast<const float*>(&ptr[offset]));
322         break;
323       }
324       case GLType::FLOAT_VEC3:
325       {
326         gl.Uniform3fv(info.location, info.arraySize, reinterpret_cast<const float*>(&ptr[offset]));
327         break;
328       }
329       case GLType::FLOAT_VEC4:
330       {
331         gl.Uniform4fv(info.location, info.arraySize, reinterpret_cast<const float*>(&ptr[offset]));
332         break;
333       }
334       case GLType::INT_VEC2:
335       {
336         gl.Uniform2iv(info.location, info.arraySize, reinterpret_cast<const GLint*>(&ptr[offset]));
337         break;
338       }
339       case GLType::INT_VEC3:
340       {
341         gl.Uniform3iv(info.location, info.arraySize, reinterpret_cast<const GLint*>(&ptr[offset]));
342         break;
343       }
344       case GLType::INT_VEC4:
345       {
346         gl.Uniform4iv(info.location, info.arraySize, reinterpret_cast<const GLint*>(&ptr[offset]));
347         break;
348       }
349       case GLType::BOOL:
350       {
351         // not supported by DALi
352         break;
353       }
354       case GLType::BOOL_VEC2:
355       {
356         // not supported by DALi
357         break;
358       }
359       case GLType::BOOL_VEC3:
360       {
361         // not supported by DALi
362         break;
363       }
364       case GLType::BOOL_VEC4:
365       {
366         // not supported by DALi
367         break;
368       }
369       case GLType::FLOAT:
370       {
371         gl.Uniform1fv(info.location, info.arraySize, reinterpret_cast<const float*>(&ptr[offset]));
372         break;
373       }
374       case GLType::FLOAT_MAT2:
375       {
376         gl.UniformMatrix2fv(info.location, info.arraySize, GL_FALSE, reinterpret_cast<const float*>(&ptr[offset]));
377         break;
378       }
379       case GLType::FLOAT_MAT3:
380       {
381         gl.UniformMatrix3fv(info.location, info.arraySize, GL_FALSE, reinterpret_cast<const float*>(&ptr[offset]));
382         break;
383       }
384       case GLType::FLOAT_MAT4:
385       {
386         gl.UniformMatrix4fv(info.location, info.arraySize, GL_FALSE, reinterpret_cast<const float*>(&ptr[offset]));
387         break;
388       }
389       case GLType::SAMPLER_2D:
390       {
391         break;
392       }
393       case GLType::SAMPLER_CUBE:
394       {
395         break;
396       }
397       default:
398       {
399       }
400     }
401   }
402 }
403
404 } // namespace Dali::Graphics::GLES