Merge "Merge branch 'devel/master' into devel/graphics" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / gles-graphics-texture.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 // CLASS HEADER
19 #include "gles-graphics-texture.h"
20
21 // EXTERNAL INCLUDES
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 <vector>
26
27 // INTERNAL INCLUDES
28 #include "egl-graphics-controller.h"
29 #include "gles-graphics-sampler.h"
30 #include "gles-graphics-types.h"
31
32 namespace
33 {
34 // These match the GL specification
35 //const int32_t GL_MINIFY_DEFAULT  = GL_NEAREST_MIPMAP_LINEAR;
36 //const int32_t GL_MAGNIFY_DEFAULT = GL_LINEAR;
37 const int32_t GL_WRAP_DEFAULT = GL_CLAMP_TO_EDGE;
38
39 // These are the Dali defaults
40 const int32_t DALI_MINIFY_DEFAULT  = GL_LINEAR;
41 const int32_t DALI_MAGNIFY_DEFAULT = GL_LINEAR;
42 } // namespace
43
44 namespace Dali::Graphics::GLES
45 {
46 struct ColorConversion
47 {
48   Format srcFormat;
49   Format destFormat;
50   std::vector<uint8_t> (*pConversionFunc)(const void*, uint32_t, uint32_t, uint32_t, uint32_t);
51   void (*pConversionWriteFunc)(const void*, uint32_t, uint32_t, uint32_t, uint32_t, void*);
52 };
53
54 inline void WriteRGB32ToRGBA32(const void* pData, uint32_t sizeInBytes, uint32_t width, uint32_t height, uint32_t rowStride, void* pOutput)
55 {
56   auto inData  = reinterpret_cast<const uint8_t*>(pData);
57   auto outData = reinterpret_cast<uint8_t*>(pOutput);
58   auto outIdx  = 0u;
59   for(auto i = 0u; i < sizeInBytes; i += 3)
60   {
61     outData[outIdx]     = inData[i];
62     outData[outIdx + 1] = inData[i + 1];
63     outData[outIdx + 2] = inData[i + 2];
64     outData[outIdx + 3] = 0xff;
65     outIdx += 4;
66   }
67 }
68
69 /**
70  * Converts RGB to RGBA
71  */
72 inline std::vector<uint8_t> ConvertRGB32ToRGBA32(const void* pData, uint32_t sizeInBytes, uint32_t width, uint32_t height, uint32_t rowStride)
73 {
74   std::vector<uint8_t> rgbaBuffer{};
75   rgbaBuffer.resize(width * height * 4);
76   WriteRGB32ToRGBA32(pData, sizeInBytes, width, height, rowStride, &rgbaBuffer[0]);
77   return rgbaBuffer;
78 }
79
80 /**
81  * Format conversion table
82  */
83 static const std::vector<ColorConversion> COLOR_CONVERSION_TABLE = {
84   {Format::R8G8B8_UNORM, Format::R8G8B8A8_UNORM, ConvertRGB32ToRGBA32, WriteRGB32ToRGBA32}};
85
86 /**
87  * Constructor
88  */
89 Texture::Texture(const Graphics::TextureCreateInfo& createInfo, Graphics::EglGraphicsController& controller)
90 : TextureResource(createInfo, controller)
91 {
92   // If there is any data, move it into staging buffer
93   if(mCreateInfo.data && mCreateInfo.dataSize)
94   {
95     mStagingBuffer.resize(size_t(mCreateInfo.dataSize));
96     std::copy(reinterpret_cast<char*>(mCreateInfo.data),
97               reinterpret_cast<char*>(mCreateInfo.data) + mCreateInfo.dataSize,
98               mStagingBuffer.begin());
99   }
100
101   // Add texture to the Resource queue
102   mController.AddTexture(*this);
103 }
104
105 bool Texture::InitializeResource()
106 {
107   if(mCreateInfo.nativeImagePtr)
108   {
109     return InitializeNativeImage();
110   }
111   return InitializeTexture();
112 }
113
114 bool Texture::InitializeNativeImage()
115 {
116   auto   gl = mController.GetGL();
117   GLuint texture{0};
118
119   if(!gl)
120   {
121     // Do nothing during shutdown
122     return false;
123   }
124
125   NativeImageInterfacePtr nativeImage = mCreateInfo.nativeImagePtr;
126   bool                    created     = nativeImage->CreateResource();
127   mGlTarget                           = nativeImage->GetTextureTarget();
128   if(created)
129   {
130     gl->GenTextures(1, &texture);
131     gl->BindTexture(mGlTarget, texture);
132
133     gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1); // We always use tightly packed data
134
135     // Apply default sampling parameters
136     gl->TexParameteri(mGlTarget, GL_TEXTURE_MIN_FILTER, DALI_MINIFY_DEFAULT);
137     gl->TexParameteri(mGlTarget, GL_TEXTURE_MAG_FILTER, DALI_MAGNIFY_DEFAULT);
138     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_S, GL_WRAP_DEFAULT);
139     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_T, GL_WRAP_DEFAULT);
140
141     // platform specific implementation decides on what GL extension to use
142     if(nativeImage->TargetTexture() != 0u)
143     {
144       gl->DeleteTextures(1, &texture);
145       nativeImage->DestroyResource();
146       texture = 0u;
147       created = false;
148     }
149     else
150     {
151       mTextureId = texture;
152     }
153   }
154   else
155   {
156     DALI_LOG_ERROR("Native Image: InitializeNativeImage, CreateResource() failed\n");
157   }
158
159   return created; // WARNING! May be false! Needs handling! (Well, initialized on bind)
160 }
161
162 bool Texture::InitializeTexture()
163 {
164   auto gl = mController.GetGL();
165   if(!gl)
166   {
167     // Do nothing during shutdown
168     return false;
169   }
170
171   GLuint texture{0};
172
173   mGlTarget     = GLTextureTarget(mCreateInfo.textureType).target;
174   mIsCompressed = Graphics::GLES::FormatCompression(mCreateInfo.format).compressed;
175
176   switch(mCreateInfo.textureType)
177   {
178     // Texture 2D
179     case Graphics::TextureType::TEXTURE_2D:
180     {
181       Graphics::GLES::GLTextureFormatType format(mCreateInfo.format);
182
183       // TODO: find better condition, with this test the L8 doesn't work
184       if(1) //format.format && format.type)
185       {
186         // Bind texture
187         gl->GenTextures(1, &texture);
188         gl->BindTexture(GL_TEXTURE_2D, texture);
189
190         // Allocate memory for the texture
191         if(!mIsCompressed)
192         {
193           gl->TexImage2D(GL_TEXTURE_2D,
194                          0,
195                          format.internalFormat,
196                          mCreateInfo.size.width,
197                          mCreateInfo.size.height,
198                          0,
199                          format.format,
200                          format.type,
201                          (mCreateInfo.data ? mStagingBuffer.data() : nullptr));
202         }
203         else
204         {
205           gl->CompressedTexImage2D(GL_TEXTURE_2D,
206                                    0,
207                                    format.internalFormat,
208                                    mCreateInfo.size.width,
209                                    mCreateInfo.size.height,
210                                    0,
211                                    mCreateInfo.dataSize,
212                                    (mCreateInfo.data ? mStagingBuffer.data() : nullptr));
213         }
214
215         // Clear staging buffer if there was any
216         mStagingBuffer.clear();
217         mTextureId = texture;
218
219         // Default texture filtering (to be set later via command buffer binding)
220         gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Graphics::GLES::GLSamplerFilterAndMipMapMode(Graphics::SamplerFilter::LINEAR, SamplerMipmapMode::NONE));
221         gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, Graphics::GLES::GLSamplerFilterAndMipMapMode(Graphics::SamplerFilter::LINEAR, SamplerMipmapMode::NONE));
222         gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_WRAP_DEFAULT);
223         gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_WRAP_DEFAULT);
224       }
225       break;
226     }
227     // Texture Cubemap
228     case Graphics::TextureType::TEXTURE_CUBEMAP:
229     {
230       Graphics::GLES::GLTextureFormatType format(mCreateInfo.format);
231
232       if(format.format && format.type)
233       {
234         // Bind texture
235         gl->GenTextures(1, &texture);
236         gl->BindTexture(GL_TEXTURE_CUBE_MAP, texture);
237         gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1); // We always use tightly packed data
238
239         gl->TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, Graphics::GLES::GLSamplerFilterAndMipMapMode(Graphics::SamplerFilter::LINEAR, SamplerMipmapMode::NONE));
240         gl->TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, Graphics::GLES::GLSamplerFilterAndMipMapMode(Graphics::SamplerFilter::LINEAR, SamplerMipmapMode::NONE));
241         gl->TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_WRAP_DEFAULT);
242         gl->TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_WRAP_DEFAULT);
243
244         // Allocate memory for the texture
245         for(uint32_t i = 0; i < 6; ++i)
246         {
247           if(!mIsCompressed)
248           {
249             gl->TexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
250                            0,
251                            format.internalFormat,
252                            mCreateInfo.size.width,
253                            mCreateInfo.size.height,
254                            0,
255                            format.format,
256                            format.type,
257                            (mCreateInfo.data ? mStagingBuffer.data() : nullptr));
258           }
259           else
260           {
261             gl->CompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
262                                      0,
263                                      format.internalFormat,
264                                      mCreateInfo.size.width,
265                                      mCreateInfo.size.height,
266                                      0,
267                                      mCreateInfo.dataSize,
268                                      (mCreateInfo.data ? mStagingBuffer.data() : nullptr));
269           }
270         }
271
272         // Clear staging buffer if there was any
273         mStagingBuffer.clear();
274
275         mTextureId = texture;
276
277         gl->TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_WRAP_DEFAULT);
278       }
279       break;
280     }
281     default:
282     {
283       // nothing?
284     }
285   }
286   return true;
287 }
288
289 void Texture::DestroyResource()
290 {
291   auto gl = mController.GetGL();
292   if(!gl)
293   {
294     return;
295   }
296
297   // This is a proper destructor
298   if(mTextureId)
299   {
300     gl->DeleteTextures(1, &mTextureId);
301   }
302   if(mCreateInfo.nativeImagePtr)
303   {
304     mCreateInfo.nativeImagePtr->DestroyResource();
305   }
306 }
307
308 void Texture::DiscardResource()
309 {
310   mController.DiscardResource(this);
311 }
312
313 void Texture::Bind(const TextureBinding& binding) const
314 {
315   auto gl = mController.GetGL();
316   if(!gl)
317   {
318     // Do nothing during shutdown
319     return;
320   }
321
322   gl->ActiveTexture(GL_TEXTURE0 + binding.binding);
323   gl->BindTexture(mGlTarget, mTextureId);
324
325   // For GLES2 if there is a sampler set in the binding
326   if(binding.sampler)
327   {
328     // Non-default.
329     auto*       sampler           = static_cast<const GLES::Sampler*>(binding.sampler);
330     const auto& samplerCreateInfo = sampler->GetCreateInfo();
331
332     auto mipMapMode = samplerCreateInfo.mipMapMode;
333
334     gl->TexParameteri(mGlTarget, GL_TEXTURE_MIN_FILTER, GLSamplerFilterAndMipMapMode(samplerCreateInfo.minFilter, mipMapMode).glFilter);
335     gl->TexParameteri(mGlTarget, GL_TEXTURE_MAG_FILTER, GLSamplerFilter(samplerCreateInfo.magFilter).glFilter);
336     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_S, GLAddressMode(samplerCreateInfo.addressModeU).texParameter);
337     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_T, GLAddressMode(samplerCreateInfo.addressModeV).texParameter);
338     if(mGlTarget == GL_TEXTURE_CUBE_MAP)
339     {
340       gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_R, GLAddressMode(samplerCreateInfo.addressModeW).texParameter);
341     }
342   }
343   else
344   {
345     gl->TexParameteri(mGlTarget, GL_TEXTURE_MIN_FILTER, DALI_MINIFY_DEFAULT);
346     gl->TexParameteri(mGlTarget, GL_TEXTURE_MAG_FILTER, DALI_MAGNIFY_DEFAULT);
347     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_S, GL_WRAP_DEFAULT);
348     gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_T, GL_WRAP_DEFAULT);
349     if(mGlTarget == GL_TEXTURE_CUBE_MAP)
350     {
351       gl->TexParameteri(mGlTarget, GL_TEXTURE_WRAP_R, GL_WRAP_DEFAULT);
352     }
353   }
354
355   if(mMaxMipMapLevel)
356   {
357     gl->TexParameteri(mGlTarget, GL_TEXTURE_MAX_LEVEL, mMaxMipMapLevel);
358   }
359 }
360
361 void Texture::Prepare()
362 {
363   NativeImageInterfacePtr nativeImage = mCreateInfo.nativeImagePtr;
364   if(nativeImage)
365   {
366     if(nativeImage->SourceChanged())
367     {
368       // Update size
369       uint32_t width  = mCreateInfo.nativeImagePtr->GetWidth();
370       uint32_t height = mCreateInfo.nativeImagePtr->GetHeight();
371       mCreateInfo.SetSize({width, height}); // Size may change
372     }
373
374     nativeImage->PrepareTexture();
375   }
376 }
377
378 /**
379  * This function tests whether format is supported by the driver. If possible it applies
380  * format conversion to suitable supported pixel format.
381  */
382 bool Texture::TryConvertPixelData(const void* pData, Graphics::Format srcFormat, Graphics::Format destFormat, uint32_t sizeInBytes, uint32_t width, uint32_t height, std::vector<uint8_t>& outputBuffer)
383 {
384   // No need to convert
385   if(srcFormat == destFormat)
386   {
387     return false;
388   }
389
390   auto it = std::find_if(COLOR_CONVERSION_TABLE.begin(), COLOR_CONVERSION_TABLE.end(), [&](auto& item) {
391     return item.srcFormat == srcFormat && item.destFormat == destFormat;
392   });
393
394   // No suitable format, return empty array
395   if(it == COLOR_CONVERSION_TABLE.end())
396   {
397     return false;
398   }
399   auto begin = reinterpret_cast<const uint8_t*>(pData);
400
401   outputBuffer = std::move(it->pConversionFunc(begin, sizeInBytes, width, height, 0u));
402   return !outputBuffer.empty();
403 }
404
405 } // namespace Dali::Graphics::GLES