Merge "Make CreateSolidColorTexture upload pixel data" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / mesh-definition.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
18 // CLASS HEADER
19 #include <dali-scene3d/public-api/loader/mesh-definition.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/file-stream.h>
23 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/public-api/math/compile-time-math.h>
26 #include <cstring>
27 #include <fstream>
28 #include <functional>
29 #include <type_traits>
30
31 namespace Dali::Scene3D::Loader
32 {
33 namespace
34 {
35 template<bool use32BitIndices>
36 class IndexProvider
37 {
38 public:
39   using IndexType = typename std::conditional_t<use32BitIndices, uint32_t, uint16_t>;
40   IndexProvider(const uint16_t* indices)
41   : mData(reinterpret_cast<uintptr_t>(indices)),
42     mFunc(indices ? IncrementPointer : Increment)
43   {
44   }
45
46   IndexType operator()()
47   {
48     return mFunc(mData);
49   }
50
51 private:
52   static IndexType Increment(uintptr_t& data)
53   {
54     // mData was 'zero' at construct time. Just simply return counter start with 0.
55     return static_cast<IndexType>(data++);
56   }
57
58   static IndexType IncrementPointer(uintptr_t& data)
59   {
60     auto iPtr   = reinterpret_cast<const IndexType*>(data);
61     auto result = *iPtr;
62     data        = reinterpret_cast<uintptr_t>(++iPtr);
63     return result;
64   }
65
66   uintptr_t mData;
67   IndexType (*mFunc)(uintptr_t&);
68 };
69
70 const char* QUAD("quad");
71
72 ///@brief Reads a blob from the given stream @a source into @a target, which must have
73 /// at least @a descriptor.length bytes.
74 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
75 {
76   source.clear();
77   if(!source.seekg(descriptor.mOffset, std::istream::beg))
78   {
79     return false;
80   }
81
82   if(descriptor.IsConsecutive())
83   {
84     return !!source.read(reinterpret_cast<char*>(target), static_cast<std::streamsize>(static_cast<size_t>(descriptor.mLength)));
85   }
86   else
87   {
88     if(descriptor.mStride > descriptor.mElementSizeHint)
89     {
90       const uint32_t diff      = descriptor.mStride - descriptor.mElementSizeHint;
91       uint32_t       readSize  = 0;
92       uint32_t       totalSize = (descriptor.mLength / descriptor.mElementSizeHint) * descriptor.mStride;
93       while(readSize < totalSize &&
94             source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint))
95       {
96         readSize += descriptor.mStride;
97         target += descriptor.mElementSizeHint;
98         source.seekg(diff, std::istream::cur);
99       }
100       return readSize == totalSize;
101     }
102   }
103   return false;
104 }
105
106 template<typename T>
107 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
108 {
109   const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
110   for(uint32_t index = 0u; index < count; ++index)
111   {
112     uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
113     memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
114   }
115 }
116
117 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target, std::vector<uint32_t>* sparseIndices)
118 {
119   bool success = false;
120
121   if(accessor.mBlob.IsDefined())
122   {
123     success = ReadBlob(accessor.mBlob, source, target);
124     if(!success)
125     {
126       return false;
127     }
128   }
129
130   if(accessor.mSparse)
131   {
132     const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
133     const MeshDefinition::Blob& values  = accessor.mSparse->mValues;
134
135     if(!indices.IsDefined() || !values.IsDefined())
136     {
137       return false;
138     }
139
140     const auto           indicesBufferSize = indices.GetBufferSize();
141     std::vector<uint8_t> indicesBuffer(indicesBufferSize);
142     success = ReadBlob(indices, source, indicesBuffer.data());
143     if(!success)
144     {
145       return false;
146     }
147
148     const auto           valuesBufferSize = values.GetBufferSize();
149     std::vector<uint8_t> valuesBuffer(valuesBufferSize);
150     success = ReadBlob(values, source, valuesBuffer.data());
151     if(!success)
152     {
153       return false;
154     }
155
156     // If non-null sparse indices vector, prepare it for output
157     if(sparseIndices)
158     {
159       sparseIndices->resize(accessor.mSparse->mCount);
160     }
161
162     switch(indices.mElementSizeHint)
163     {
164       case 1u:
165       {
166         ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
167         if(sparseIndices)
168         {
169           // convert 8-bit indices into 32-bit
170           std::transform(indicesBuffer.begin(), indicesBuffer.end(), sparseIndices->begin(), [](const uint8_t& value) { return uint32_t(value); });
171         }
172         break;
173       }
174       case 2u:
175       {
176         ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
177         if(sparseIndices)
178         {
179           // convert 16-bit indices into 32-bit
180           std::transform(reinterpret_cast<uint16_t*>(indicesBuffer.data()),
181                          reinterpret_cast<uint16_t*>(indicesBuffer.data()) + accessor.mSparse->mCount,
182                          sparseIndices->begin(),
183                          [](const uint16_t& value) {
184                            return uint32_t(value);
185                          });
186         }
187         break;
188       }
189       case 4u:
190       {
191         ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
192         if(sparseIndices)
193         {
194           std::copy(indicesBuffer.begin(), indicesBuffer.end(), reinterpret_cast<uint8_t*>(sparseIndices->data()));
195         }
196         break;
197       }
198       default:
199       {
200         DALI_ASSERT_DEBUG(!"Unsupported type for an index");
201       }
202     }
203   }
204
205   return success;
206 }
207
208 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
209 {
210   return ReadAccessor(accessor, source, target, nullptr);
211 }
212
213 template<typename T>
214 void ReadJointAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
215 {
216   constexpr auto sizeofBlobUnit = sizeof(T) * 4;
217
218   DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
219                       accessor.mBlob.mStride >= sizeofBlobUnit) &&
220                      "Joints buffer length not a multiple of element size");
221   const auto inBufferSize  = accessor.mBlob.GetBufferSize();
222   const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
223
224   std::vector<uint8_t> buffer(outBufferSize);
225   auto                 inBuffer = buffer.data() + outBufferSize - inBufferSize;
226   if(!ReadAccessor(accessor, source, inBuffer))
227   {
228     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
229   }
230
231   if constexpr(sizeofBlobUnit != sizeof(Vector4))
232   {
233     auto       floats = reinterpret_cast<float*>(buffer.data());
234     const auto end    = inBuffer + inBufferSize;
235     while(inBuffer != end)
236     {
237       const auto value = *reinterpret_cast<T*>(inBuffer);
238       *floats          = static_cast<float>(value);
239
240       inBuffer += sizeof(T);
241       ++floats;
242     }
243   }
244   raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
245 }
246
247 template<typename T>
248 void ReadWeightAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
249 {
250   constexpr auto sizeofBlobUnit = sizeof(T) * 4;
251
252   DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
253                       accessor.mBlob.mStride >= sizeofBlobUnit) &&
254                      "weights buffer length not a multiple of element size");
255   const auto inBufferSize  = accessor.mBlob.GetBufferSize();
256   const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
257
258   std::vector<uint8_t> buffer(outBufferSize);
259   auto                 inBuffer = buffer.data() + outBufferSize - inBufferSize;
260   if(!ReadAccessor(accessor, source, inBuffer))
261   {
262     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
263   }
264
265   if constexpr(sizeofBlobUnit != sizeof(Vector4))
266   {
267     auto       floats = reinterpret_cast<float*>(buffer.data());
268     const auto end    = inBuffer + inBufferSize;
269     while(inBuffer != end)
270     {
271       const auto value = *reinterpret_cast<T*>(inBuffer);
272       // Normalize weight value. value /= 255 for uint8_t weight, and value /= 65535 for uint16_t weight.
273       *floats = static_cast<float>(value) / static_cast<float>((1 << (sizeof(T) * 8)) - 1);
274
275       inBuffer += sizeof(T);
276       ++floats;
277     }
278   }
279   raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
280 }
281
282 template<bool use32BitsIndices, typename IndexProviderType = IndexProvider<use32BitsIndices>>
283 bool GenerateNormals(MeshDefinition::RawData& raw)
284 {
285   using IndexType = typename IndexProviderType::IndexType;
286
287   // mIndicies size must be even if we use 32bit indices.
288   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
289   {
290     return false;
291   }
292
293   auto& attribs = raw.mAttribs;
294   DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
295
296   IndexProviderType getIndex(raw.mIndices.data());
297
298   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
299
300   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
301
302   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
303   auto                 normals = reinterpret_cast<Vector3*>(buffer.data());
304
305   for(uint32_t i = 0; i < numIndices; i += 3)
306   {
307     IndexType indices[]{getIndex(), getIndex(), getIndex()};
308     Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
309
310     Vector3 a = pos[1] - pos[0];
311     Vector3 b = pos[2] - pos[0];
312
313     Vector3 normal(a.Cross(b));
314     normals[indices[0]] += normal;
315     normals[indices[1]] += normal;
316     normals[indices[2]] += normal;
317   }
318
319   auto iEnd = normals + attribs[0].mNumElements;
320   while(normals != iEnd)
321   {
322     normals->Normalize();
323     ++normals;
324   }
325
326   attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
327
328   return true;
329 }
330
331 template<bool use32BitsIndices, bool useVec3, bool hasUvs, typename T = std::conditional_t<useVec3, Vector3, Vector4>, typename = std::enable_if_t<(std::is_same<T, Vector3>::value || std::is_same<T, Vector4>::value)>, typename IndexProviderType = IndexProvider<use32BitsIndices>>
332 bool GenerateTangents(MeshDefinition::RawData& raw)
333 {
334   using IndexType = typename IndexProviderType::IndexType;
335
336   // mIndicies size must be even if we use 32bit indices.
337   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
338   {
339     return false;
340   }
341
342   auto& attribs = raw.mAttribs;
343   // Required positions, normals, uvs (if we have). If not, skip generation
344   if(DALI_UNLIKELY(attribs.size() < (2 + static_cast<size_t>(hasUvs))))
345   {
346     return false;
347   }
348
349   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(T));
350   auto                 tangents = reinterpret_cast<T*>(buffer.data());
351
352   if constexpr(hasUvs)
353   {
354     IndexProviderType getIndex(raw.mIndices.data());
355
356     const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
357
358     auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
359     auto* uvs       = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
360
361     for(uint32_t i = 0; i < numIndices; i += 3)
362     {
363       IndexType indices[]{getIndex(), getIndex(), getIndex()};
364       Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
365       Vector2   uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
366
367       float x0 = pos[1].x - pos[0].x;
368       float y0 = pos[1].y - pos[0].y;
369       float z0 = pos[1].z - pos[0].z;
370
371       float x1 = pos[2].x - pos[0].x;
372       float y1 = pos[2].y - pos[0].y;
373       float z1 = pos[2].z - pos[0].z;
374
375       float s0 = uv[1].x - uv[0].x;
376       float t0 = uv[1].y - uv[0].y;
377
378       float s1 = uv[2].x - uv[0].x;
379       float t1 = uv[2].y - uv[0].y;
380
381       float   det = (s0 * t1 - t0 * s1);
382       float   r   = 1.f / ((std::abs(det) < Dali::Epsilon<1000>::value) ? (Dali::Epsilon<1000>::value * (det > 0.0f ? 1.f : -1.f)) : det);
383       Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
384       tangents[indices[0]] += T(tangent);
385       tangents[indices[1]] += T(tangent);
386       tangents[indices[2]] += T(tangent);
387     }
388   }
389
390   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
391   auto  iEnd    = normals + attribs[1].mNumElements;
392   while(normals != iEnd)
393   {
394     Vector3 tangentVec3;
395     if constexpr(hasUvs)
396     {
397       // Calculated by indexs
398       tangentVec3 = Vector3((*tangents).x, (*tangents).y, (*tangents).z);
399     }
400     else
401     {
402       // Only choiced by normal vector. by indexs
403       Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
404       tangentVec3 = t[t[1].LengthSquared() > t[0].LengthSquared()];
405     }
406
407     tangentVec3 -= *normals * normals->Dot(tangentVec3);
408     tangentVec3.Normalize();
409     if constexpr(useVec3)
410     {
411       *tangents = tangentVec3;
412     }
413     else
414     {
415       *tangents = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
416     }
417
418     ++tangents;
419     ++normals;
420   }
421   attribs.push_back({"aTangent", useVec3 ? Property::VECTOR3 : Property::VECTOR4, attribs[0].mNumElements, std::move(buffer)});
422
423   return true;
424 }
425
426 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
427 {
428   DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
429
430   // Calculate the dimensions of the texture.
431   // The total size of the texture is the length of the blend shapes blob.
432
433   textureWidth  = 0u;
434   textureHeight = 0u;
435
436   if(0u == totalTextureSize)
437   {
438     // nothing to do.
439     return;
440   }
441
442   const uint32_t pow2      = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
443   const uint32_t powWidth  = pow2 >> 1u;
444   const uint32_t powHeight = pow2 - powWidth;
445
446   textureWidth  = 1u << powWidth;
447   textureHeight = 1u << powHeight;
448 }
449
450 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
451 {
452   uint32_t geometryBufferIndex = 0u;
453   float    maxDistanceSquared  = 0.f;
454   Vector3* geometryBufferV3    = reinterpret_cast<Vector3*>(geometryBuffer);
455   for(const auto& blendShape : blendShapes)
456   {
457     if(blendShape.deltas.IsDefined())
458     {
459       DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
460                           blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
461                          "Blend Shape position buffer length not a multiple of element size");
462
463       const auto            bufferSize = blendShape.deltas.mBlob.GetBufferSize();
464       std::vector<uint8_t>  buffer(bufferSize);
465       std::vector<uint32_t> sparseIndices{};
466
467       if(ReadAccessor(blendShape.deltas, buffers[blendShape.deltas.mBufferIdx].GetBufferStream(), buffer.data(), &sparseIndices))
468       {
469         blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()), &sparseIndices);
470
471         // Calculate the difference with the original mesh.
472         // Find the max distance to normalize the deltas.
473         const auto* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
474
475         auto ProcessVertex = [&geometryBufferV3, &deltasBuffer, &maxDistanceSquared](uint32_t geometryBufferIndex, uint32_t deltaIndex) {
476           Vector3& delta = geometryBufferV3[geometryBufferIndex] = deltasBuffer[deltaIndex];
477           delta                                                  = deltasBuffer[deltaIndex];
478           return std::max(maxDistanceSquared, delta.LengthSquared());
479         };
480
481         if(sparseIndices.empty())
482         {
483           for(uint32_t index = 0u; index < numberOfVertices; ++index)
484           {
485             maxDistanceSquared = ProcessVertex(geometryBufferIndex++, index);
486           }
487         }
488         else
489         {
490           // initialize blendshape texture
491           // TODO: there may be a case when sparse accessor uses a base buffer view for initial values.
492           std::fill(geometryBufferV3 + geometryBufferIndex, geometryBufferV3 + geometryBufferIndex + numberOfVertices, Vector3::ZERO);
493           for(auto index : sparseIndices)
494           {
495             maxDistanceSquared = ProcessVertex(geometryBufferIndex + index, index);
496           }
497           geometryBufferIndex += numberOfVertices;
498         }
499       }
500     }
501
502     if(blendShape.normals.IsDefined())
503     {
504       DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
505                           blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
506                          "Blend Shape normals buffer length not a multiple of element size");
507
508       const auto            bufferSize = blendShape.normals.mBlob.GetBufferSize();
509       std::vector<uint8_t>  buffer(bufferSize);
510       std::vector<uint32_t> sparseIndices;
511
512       if(ReadAccessor(blendShape.normals, buffers[blendShape.normals.mBufferIdx].GetBufferStream(), buffer.data(), &sparseIndices))
513       {
514         blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()), &sparseIndices);
515
516         // Calculate the difference with the original mesh, and translate to make all values positive.
517         const Vector3* const deltasBuffer  = reinterpret_cast<const Vector3* const>(buffer.data());
518         auto                 ProcessVertex = [&geometryBufferV3, &deltasBuffer, &maxDistanceSquared](uint32_t geometryBufferIndex, uint32_t deltaIndex) {
519           Vector3& delta = geometryBufferV3[geometryBufferIndex] = deltasBuffer[deltaIndex];
520           delta.x *= 0.5f;
521           delta.y *= 0.5f;
522           delta.z *= 0.5f;
523
524           delta.x += 0.5f;
525           delta.y += 0.5f;
526           delta.z += 0.5f;
527         };
528
529         if(sparseIndices.empty())
530         {
531           for(uint32_t index = 0u; index < numberOfVertices; ++index)
532           {
533             ProcessVertex(geometryBufferIndex++, index);
534           }
535         }
536         else
537         {
538           std::fill(geometryBufferV3 + geometryBufferIndex, geometryBufferV3 + geometryBufferIndex + numberOfVertices, Vector3(0.5, 0.5, 0.5));
539           for(auto index : sparseIndices)
540           {
541             ProcessVertex(geometryBufferIndex + index, index);
542           }
543           geometryBufferIndex += numberOfVertices;
544         }
545       }
546     }
547
548     if(blendShape.tangents.IsDefined())
549     {
550       DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
551                           blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
552                          "Blend Shape tangents buffer length not a multiple of element size");
553
554       const auto            bufferSize = blendShape.tangents.mBlob.GetBufferSize();
555       std::vector<uint8_t>  buffer(bufferSize);
556       std::vector<uint32_t> sparseIndices;
557
558       if(ReadAccessor(blendShape.tangents, buffers[blendShape.tangents.mBufferIdx].GetBufferStream(), buffer.data(), &sparseIndices))
559       {
560         blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()), &sparseIndices);
561
562         // Calculate the difference with the original mesh, and translate to make all values positive.
563         const Vector3* const deltasBuffer  = reinterpret_cast<const Vector3* const>(buffer.data());
564         auto                 ProcessVertex = [&geometryBufferV3, &deltasBuffer, &maxDistanceSquared](uint32_t geometryBufferIndex, uint32_t deltaIndex) {
565           Vector3& delta = geometryBufferV3[geometryBufferIndex] = deltasBuffer[deltaIndex];
566           delta.x *= 0.5f;
567           delta.y *= 0.5f;
568           delta.z *= 0.5f;
569
570           delta.x += 0.5f;
571           delta.y += 0.5f;
572           delta.z += 0.5f;
573         };
574
575         if(sparseIndices.empty())
576         {
577           for(uint32_t index = 0u; index < numberOfVertices; ++index)
578           {
579             ProcessVertex(geometryBufferIndex++, index);
580           }
581         }
582         else
583         {
584           std::fill(geometryBufferV3 + geometryBufferIndex, geometryBufferV3 + geometryBufferIndex + numberOfVertices, Vector3(0.5, 0.5, 0.5));
585           for(auto index : sparseIndices)
586           {
587             ProcessVertex(geometryBufferIndex + index, index);
588           }
589           geometryBufferIndex += numberOfVertices;
590         }
591       }
592     }
593   }
594
595   geometryBufferIndex = 0u;
596
597   const float maxDistance = sqrtf(maxDistanceSquared);
598
599   const float normalizeFactor = (maxDistanceSquared < Math::MACHINE_EPSILON_100) ? 1.f : (0.5f / maxDistance);
600
601   // Calculate and store the unnormalize factor.
602   blendShapeUnnormalizeFactor = maxDistance * 2.0f;
603
604   for(const auto& blendShape : blendShapes)
605   {
606     // Normalize all the deltas and translate to a possitive value.
607     // Deltas are going to be passed to the shader in a color texture
608     // whose values that are less than zero are clamped.
609     if(blendShape.deltas.IsDefined())
610     {
611       for(uint32_t index = 0u; index < numberOfVertices; ++index)
612       {
613         Vector3& delta = geometryBufferV3[geometryBufferIndex++];
614         delta.x        = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
615         delta.y        = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
616         delta.z        = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
617       }
618     }
619
620     if(blendShape.normals.IsDefined())
621     {
622       geometryBufferIndex += numberOfVertices;
623     }
624
625     if(blendShape.tangents.IsDefined())
626     {
627       geometryBufferIndex += numberOfVertices;
628     }
629   }
630 }
631
632 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
633 {
634   auto& stream  = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
635   availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
636   return stream;
637 }
638
639 } // namespace
640
641 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
642 : mIndices{indices},
643   mValues{values},
644   mCount{count}
645 {
646 }
647
648 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
649 : mIndices(std::move(indices)),
650   mValues(std::move(values)),
651   mCount{count}
652 {
653 }
654
655 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob&       blob,
656                                    const MeshDefinition::SparseBlob& sparse,
657                                    Index                             bufferIndex)
658 : mBlob{blob},
659   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
660   mBufferIdx(bufferIndex)
661 {
662 }
663
664 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&&       blob,
665                                    MeshDefinition::SparseBlob&& sparse,
666                                    Index                        bufferIndex)
667 : mBlob{std::move(blob)},
668   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
669   mBufferIdx(bufferIndex)
670 {
671 }
672
673 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
674 {
675   min.assign(numComponents, MAXFLOAT);
676   max.assign(numComponents, -MAXFLOAT);
677   for(uint32_t i = 0; i < count; ++i)
678   {
679     for(uint32_t j = 0; j < numComponents; ++j)
680     {
681       min[j] = std::min(min[j], *values);
682       max[j] = std::max(max[j], *values);
683       values++;
684     }
685   }
686 }
687
688 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values, std::vector<uint32_t>* sparseIndices)
689 {
690   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
691   const auto numComponents = std::max(min.size(), max.size());
692
693   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
694   ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) { value = std::min(max[i], value); })
695                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { value = std::max(min[i], value); }
696                                                : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) { value = std::min(std::max(min[i], value), max[i]); }));
697
698   if(!clampFn)
699   {
700     return;
701   }
702
703   auto end = values + count * numComponents;
704   while(values != end)
705   {
706     auto     nextElement = values + numComponents;
707     uint32_t i           = 0;
708     while(values != nextElement)
709     {
710       clampFn(min.data(), max.data(), i, *values);
711       ++values;
712       ++i;
713     }
714   }
715 }
716
717 MeshDefinition::Blob::Blob(uint32_t offset, uint32_t length, uint16_t stride, uint16_t elementSizeHint, const std::vector<float>& min, const std::vector<float>& max)
718 : mOffset(offset),
719   mLength(length),
720   mStride(stride),
721   mElementSizeHint(elementSizeHint),
722   mMin(min),
723   mMax(max)
724 {
725 }
726
727 uint32_t MeshDefinition::Blob::GetBufferSize() const
728 {
729   return mLength;
730 }
731
732 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
733 {
734   ComputeMinMax(mMin, mMax, numComponents, count, values);
735 }
736
737 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values, std::vector<uint32_t>* sparseIndices) const
738 {
739   ApplyMinMax(mMin, mMax, count, values, sparseIndices);
740 }
741
742 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
743 {
744   Property::Map attribMap;
745   attribMap[mName]          = mType;
746   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
747   attribBuffer.SetData(mData.data(), mNumElements);
748
749   g.AddVertexBuffer(attribBuffer);
750 }
751
752 bool MeshDefinition::IsQuad() const
753 {
754   return CaseInsensitiveStringCompare(QUAD, mUri);
755 }
756
757 bool MeshDefinition::IsSkinned() const
758 {
759   return mJoints0.IsDefined() && mWeights0.IsDefined();
760 }
761
762 bool MeshDefinition::HasBlendShapes() const
763 {
764   return !mBlendShapes.empty();
765 }
766
767 void MeshDefinition::RequestNormals()
768 {
769   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
770 }
771
772 void MeshDefinition::RequestTangents()
773 {
774   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
775 }
776
777 MeshDefinition::RawData
778 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
779 {
780   RawData raw;
781   if(IsQuad())
782   {
783     return raw;
784   }
785
786   std::string meshPath;
787   meshPath = modelsPath + mUri;
788   std::fstream fileStream;
789   if(!mUri.empty())
790   {
791     fileStream.open(meshPath, std::ios::in | std::ios::binary);
792     if(!fileStream.is_open())
793     {
794       DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
795     }
796   }
797
798   if(mIndices.IsDefined())
799   {
800     if(MaskMatch(mFlags, U32_INDICES))
801     {
802       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
803                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
804                          "Index buffer length not a multiple of element size");
805       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
806       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
807
808       std::string path;
809       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
810       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
811       {
812         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
813       }
814     }
815     else if(MaskMatch(mFlags, U8_INDICES))
816     {
817       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
818                           mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
819                          "Index buffer length not a multiple of element size");
820       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
821       raw.mIndices.resize(indexCount); // NOTE: we need space for uint16_ts initially.
822
823       std::string path;
824       auto        u8s    = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
825       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
826       if(!ReadAccessor(mIndices, stream, u8s))
827       {
828         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
829       }
830
831       auto u16s = raw.mIndices.data();
832       auto end  = u8s + indexCount;
833       while(u8s != end)
834       {
835         *u16s = static_cast<uint16_t>(*u8s);
836         ++u16s;
837         ++u8s;
838       }
839     }
840     else
841     {
842       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
843                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
844                          "Index buffer length not a multiple of element size");
845       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
846
847       std::string path;
848       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
849       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
850       {
851         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
852       }
853     }
854   }
855
856   std::vector<Vector3> positions;
857   if(mPositions.IsDefined())
858   {
859     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
860                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
861                        "Position buffer length not a multiple of element size");
862     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
863     std::vector<uint8_t> buffer(bufferSize);
864
865     std::string path;
866     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
867     if(!ReadAccessor(mPositions, stream, buffer.data()))
868     {
869       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
870     }
871
872     uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
873     if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
874     {
875       mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
876     }
877     else
878     {
879       mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
880     }
881
882     if(HasBlendShapes())
883     {
884       positions.resize(numVector3);
885       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
886     }
887
888     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
889   }
890
891   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
892   auto       hasNormals  = mNormals.IsDefined();
893   if(hasNormals)
894   {
895     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
896                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
897                        "Normal buffer length not a multiple of element size");
898     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
899     std::vector<uint8_t> buffer(bufferSize);
900
901     std::string path;
902     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
903     if(!ReadAccessor(mNormals, stream, buffer.data()))
904     {
905       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
906     }
907
908     mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
909
910     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
911   }
912   else if(mNormals.mBlob.mLength != 0 && isTriangles)
913   {
914     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
915     static const std::function<bool(RawData&)> GenerateNormalsFunction[2] =
916       {
917         GenerateNormals<false>,
918         GenerateNormals<true>,
919       };
920     const bool generateSuccessed = GenerateNormalsFunction[MaskMatch(mFlags, U32_INDICES)](raw);
921     if(!generateSuccessed)
922     {
923       DALI_LOG_ERROR("Failed to generate normal\n");
924     }
925     else
926     {
927       hasNormals = true;
928     }
929   }
930
931   const auto hasUvs = mTexCoords.IsDefined();
932   if(hasUvs)
933   {
934     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
935                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
936                        "Normal buffer length not a multiple of element size");
937     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
938     std::vector<uint8_t> buffer(bufferSize);
939
940     std::string path;
941     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
942     if(!ReadAccessor(mTexCoords, stream, buffer.data()))
943     {
944       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
945     }
946
947     const auto uvCount = bufferSize / sizeof(Vector2);
948     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
949     {
950       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
951       auto uvEnd = uv + uvCount;
952       while(uv != uvEnd)
953       {
954         uv->y = 1.0f - uv->y;
955         ++uv;
956       }
957     }
958
959     mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(uvCount), reinterpret_cast<float*>(buffer.data()));
960
961     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
962   }
963
964   if(mTangents.IsDefined())
965   {
966     uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
967     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
968                         mTangents.mBlob.mStride >= propertySize) &&
969                        "Tangents buffer length not a multiple of element size");
970     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
971     std::vector<uint8_t> buffer(bufferSize);
972
973     std::string path;
974     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
975     if(!ReadAccessor(mTangents, stream, buffer.data()))
976     {
977       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
978     }
979     mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
980
981     raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
982   }
983   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
984   {
985     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
986     static const std::function<bool(RawData&)> GenerateTangentsFunction[2][2][2] =
987       {
988         {
989           {
990             GenerateTangents<false, false, false>,
991             GenerateTangents<false, false, true>,
992           },
993           {
994             GenerateTangents<false, true, false>,
995             GenerateTangents<false, true, true>,
996           },
997         },
998         {
999           {
1000             GenerateTangents<true, false, false>,
1001             GenerateTangents<true, false, true>,
1002           },
1003           {
1004             GenerateTangents<true, true, false>,
1005             GenerateTangents<true, true, true>,
1006           },
1007         }};
1008     const bool generateSuccessed = GenerateTangentsFunction[MaskMatch(mFlags, U32_INDICES)][mTangentType == Property::VECTOR3][hasUvs](raw);
1009     if(!generateSuccessed)
1010     {
1011       DALI_LOG_ERROR("Failed to generate tangents\n");
1012     }
1013   }
1014
1015   if(mColors.IsDefined())
1016   {
1017     uint32_t       propertySize = mColors.mBlob.mElementSizeHint;
1018     Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
1019     if(propertyType != Property::NONE)
1020     {
1021       DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
1022                           mColors.mBlob.mStride >= propertySize) &&
1023                          "Colors buffer length not a multiple of element size");
1024       const auto           bufferSize = mColors.mBlob.GetBufferSize();
1025       std::vector<uint8_t> buffer(bufferSize);
1026
1027       std::string path;
1028       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
1029       if(!ReadAccessor(mColors, stream, buffer.data()))
1030       {
1031         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
1032       }
1033       mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
1034
1035       raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
1036     }
1037   }
1038   else
1039   {
1040     std::vector<uint8_t> buffer(raw.mAttribs[0].mNumElements * sizeof(Vector4));
1041     auto                 colors = reinterpret_cast<Vector4*>(buffer.data());
1042
1043     for(uint32_t i = 0; i < raw.mAttribs[0].mNumElements; i++)
1044     {
1045       colors[i] = Vector4::ONE;
1046     }
1047
1048     raw.mAttribs.push_back({"aVertexColor", Property::VECTOR4, raw.mAttribs[0].mNumElements, std::move(buffer)});
1049   }
1050
1051   if(IsSkinned())
1052   {
1053     std::string pathJoint;
1054     auto&       streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
1055     if(MaskMatch(mFlags, U16_JOINT_IDS))
1056     {
1057       ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
1058     }
1059     else if(MaskMatch(mFlags, U8_JOINT_IDS))
1060     {
1061       ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
1062     }
1063     else
1064     {
1065       ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
1066     }
1067
1068     std::string pathWeight;
1069     auto&       streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
1070     if(MaskMatch(mFlags, U16_WEIGHT))
1071     {
1072       ReadWeightAccessor<uint16_t>(raw, mWeights0, streamWeight, pathWeight);
1073     }
1074     else if(MaskMatch(mFlags, U8_WEIGHT))
1075     {
1076       ReadWeightAccessor<uint8_t>(raw, mWeights0, streamWeight, pathWeight);
1077     }
1078     else
1079     {
1080       ReadWeightAccessor<float>(raw, mWeights0, streamWeight, pathWeight);
1081     }
1082   }
1083
1084   // Calculate the Blob for the blend shapes.
1085   Blob blendShapesBlob;
1086   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
1087   blendShapesBlob.mLength = 0u;
1088
1089   for(const auto& blendShape : mBlendShapes)
1090   {
1091     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
1092     {
1093       if(i->IsDefined())
1094       {
1095         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
1096         blendShapesBlob.mLength += i->mBlob.mLength;
1097       }
1098     }
1099   }
1100
1101   if(HasBlendShapes())
1102   {
1103     const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
1104
1105     // Calculate the size of one buffer inside the texture.
1106     raw.mBlendShapeBufferOffset = numberOfVertices;
1107
1108     bool     calculateGltf2BlendShapes = false;
1109     uint32_t textureWidth              = 0u;
1110     uint32_t textureHeight             = 0u;
1111
1112     if(!mBlendShapeHeader.IsDefined())
1113     {
1114       CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
1115       calculateGltf2BlendShapes = true;
1116     }
1117     else
1118     {
1119       uint16_t header[2u];
1120       ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
1121       textureWidth  = header[0u];
1122       textureHeight = header[1u];
1123     }
1124
1125     const uint32_t numberOfBlendShapes = mBlendShapes.size();
1126     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
1127
1128     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
1129     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
1130
1131     if(calculateGltf2BlendShapes)
1132     {
1133       CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
1134     }
1135     else
1136     {
1137       Blob unnormalizeFactorBlob;
1138       unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
1139
1140       if(blendShapesBlob.IsDefined())
1141       {
1142         if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
1143         {
1144           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
1145         }
1146       }
1147
1148       // Read the unnormalize factors.
1149       if(unnormalizeFactorBlob.IsDefined())
1150       {
1151         ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
1152       }
1153     }
1154     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
1155   }
1156
1157   return raw;
1158 }
1159
1160 MeshGeometry MeshDefinition::Load(RawData&& raw) const
1161 {
1162   MeshGeometry meshGeometry;
1163   meshGeometry.geometry = Geometry::New();
1164   meshGeometry.geometry.SetType(mPrimitiveType);
1165
1166   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
1167   {
1168     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
1169     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
1170   }
1171   else
1172   {
1173     if(!raw.mIndices.empty())
1174     {
1175       if(MaskMatch(mFlags, U32_INDICES))
1176       {
1177         // TODO : We can only store indeces as uint16_type. Send Dali::Geometry that we use it as uint32_t actual.
1178         meshGeometry.geometry.SetIndexBuffer(reinterpret_cast<const uint32_t*>(raw.mIndices.data()), raw.mIndices.size() / 2);
1179       }
1180       else
1181       {
1182         meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
1183       }
1184     }
1185
1186     for(auto& a : raw.mAttribs)
1187     {
1188       a.AttachBuffer(meshGeometry.geometry);
1189     }
1190
1191     if(HasBlendShapes())
1192     {
1193       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
1194       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1195
1196       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1197                                                      raw.mBlendShapeData.GetPixelFormat(),
1198                                                      raw.mBlendShapeData.GetWidth(),
1199                                                      raw.mBlendShapeData.GetHeight());
1200       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1201     }
1202   }
1203
1204   return meshGeometry;
1205 }
1206
1207 void MeshDefinition::RetrieveBlendShapeComponents(bool& hasPositions, bool& hasNormals, bool& hasTangents) const
1208 {
1209   for(const auto& blendShape : mBlendShapes)
1210   {
1211     hasPositions = hasPositions || blendShape.deltas.IsDefined();
1212     hasNormals   = hasNormals || blendShape.normals.IsDefined();
1213     hasTangents  = hasTangents || blendShape.tangents.IsDefined();
1214   }
1215 }
1216
1217 } // namespace Dali::Scene3D::Loader