Merge "DALi Version 2.0.32" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / public-api / mesh-definition.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 // INTERNAL INCLUDES
19 #include "dali-scene-loader/public-api/mesh-definition.h"
20
21 // EXTERNAL INCLUDES
22 #include <cstring>
23 #include <fstream>
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
25
26 namespace Dali
27 {
28 namespace SceneLoader
29 {
30 namespace
31 {
32 using Uint16Vector4 = uint16_t[4];
33
34 class IndexProvider
35 {
36 public:
37   IndexProvider(const uint16_t* indices)
38   : mData(reinterpret_cast<uintptr_t>(indices)),
39     mFunc(indices ? IncrementPointer : Increment)
40   {
41   }
42
43   uint16_t operator()()
44   {
45     return mFunc(mData);
46   }
47
48 private:
49   static uint16_t Increment(uintptr_t& data)
50   {
51     return static_cast<uint16_t>(data++);
52   }
53
54   static uint16_t IncrementPointer(uintptr_t& data)
55   {
56     auto iPtr   = reinterpret_cast<const uint16_t*>(data);
57     auto result = *iPtr;
58     data        = reinterpret_cast<uintptr_t>(++iPtr);
59     return result;
60   }
61
62   uintptr_t mData;
63   uint16_t (*mFunc)(uintptr_t&);
64 };
65
66 const std::string QUAD("quad");
67
68 ///@brief Reads a blob from the given stream @a source into @a target, which must have
69 /// at least @a descriptor.length bytes.
70 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
71 {
72   if(!source.seekg(descriptor.mOffset, std::istream::beg))
73   {
74     return false;
75   }
76
77   if(descriptor.IsConsecutive())
78   {
79     return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
80   }
81   else
82   {
83     DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint);
84     const uint32_t diff     = descriptor.mStride - descriptor.mElementSizeHint;
85     uint32_t       readSize = 0;
86     while(readSize < descriptor.mLength &&
87           source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
88           source.seekg(diff, std::istream::cur))
89     {
90       readSize += descriptor.mStride;
91       target += descriptor.mElementSizeHint;
92     }
93     return readSize == descriptor.mLength;
94   }
95 }
96
97 template<typename T>
98 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
99 {
100   const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
101   for(uint32_t index = 0u; index < count; ++index)
102   {
103     uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
104     memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
105   }
106 }
107
108 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
109 {
110   bool success = false;
111
112   if(accessor.mBlob.IsDefined())
113   {
114     success = ReadBlob(accessor.mBlob, source, target);
115     if(!success)
116     {
117       return false;
118     }
119   }
120
121   if(accessor.mSparse)
122   {
123     const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
124     const MeshDefinition::Blob& values  = accessor.mSparse->mValues;
125
126     if(!indices.IsDefined() || !values.IsDefined())
127     {
128       return false;
129     }
130
131     const auto           indicesBufferSize = indices.GetBufferSize();
132     std::vector<uint8_t> indicesBuffer(indicesBufferSize);
133     success = ReadBlob(indices, source, indicesBuffer.data());
134     if(!success)
135     {
136       return false;
137     }
138
139     const auto           valuesBufferSize = values.GetBufferSize();
140     std::vector<uint8_t> valuesBuffer(valuesBufferSize);
141     success = ReadBlob(values, source, valuesBuffer.data());
142     if(!success)
143     {
144       return false;
145     }
146
147     switch(indices.mElementSizeHint)
148     {
149       case 1u:
150       {
151         ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
152         break;
153       }
154       case 2u:
155       {
156         ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
157         break;
158       }
159       case 4u:
160       {
161         ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
162         break;
163       }
164       default:
165         DALI_ASSERT_DEBUG(!"Unsupported type for an index");
166     }
167   }
168
169   return success;
170 }
171
172 void GenerateNormals(MeshDefinition::RawData& raw)
173 {
174   auto& attribs = raw.mAttribs;
175   DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
176   IndexProvider getIndex(raw.mIndices.data());
177
178   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
179
180   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
181
182   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
183   auto                 normals = reinterpret_cast<Vector3*>(buffer.data());
184
185   for(uint32_t i = 0; i < numIndices; i += 3)
186   {
187     uint16_t indices[]{getIndex(), getIndex(), getIndex()};
188     Vector3  pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
189
190     Vector3 a = pos[1] - pos[0];
191     Vector3 b = pos[2] - pos[0];
192
193     Vector3 normal(a.Cross(b));
194     normals[indices[0]] += normal;
195     normals[indices[1]] += normal;
196     normals[indices[2]] += normal;
197   }
198
199   auto iEnd = normals + attribs[0].mNumElements;
200   while(normals != iEnd)
201   {
202     normals->Normalize();
203     ++normals;
204   }
205
206   attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
207 }
208
209 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
210 {
211   auto& attribs = raw.mAttribs;
212   DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
213   IndexProvider getIndex(raw.mIndices.data());
214
215   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
216
217   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
218   auto* uvs       = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
219
220   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
221   auto                 tangents = reinterpret_cast<Vector3*>(buffer.data());
222
223   for(uint32_t i = 0; i < numIndices; i += 3)
224   {
225     uint16_t indices[]{getIndex(), getIndex(), getIndex()};
226     Vector3  pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
227     Vector2  uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
228
229     float x0 = pos[1].x - pos[0].x;
230     float y0 = pos[1].y - pos[0].y;
231     float z0 = pos[1].z - pos[0].z;
232
233     float x1 = pos[2].x - pos[0].x;
234     float y1 = pos[2].y - pos[0].y;
235     float z1 = pos[2].z - pos[0].z;
236
237     float s0 = uv[1].x - uv[0].x;
238     float t0 = uv[1].y - uv[0].y;
239
240     float s1 = uv[2].x - uv[0].x;
241     float t1 = uv[2].y - uv[0].y;
242
243     float   r = 1.f / (s0 * t1 - t0 * s1);
244     Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
245     tangents[indices[0]] += tangent;
246     tangents[indices[1]] += tangent;
247     tangents[indices[2]] += tangent;
248   }
249
250   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
251   auto  iEnd    = normals + attribs[1].mNumElements;
252   while(normals != iEnd)
253   {
254     *tangents -= *normals * normals->Dot(*tangents);
255     tangents->Normalize();
256
257     ++tangents;
258     ++normals;
259   }
260   attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
261 }
262
263 void GenerateTangents(MeshDefinition::RawData& raw)
264 {
265   auto& attribs = raw.mAttribs;
266   DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
267
268   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
269
270   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
271   auto                 tangents = reinterpret_cast<Vector3*>(buffer.data());
272
273   auto iEnd = normals + attribs[1].mNumElements;
274   while(normals != iEnd)
275   {
276     Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
277
278     *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
279     *tangents -= *normals * normals->Dot(*tangents);
280     tangents->Normalize();
281
282     ++tangents;
283     ++normals;
284   }
285   attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
286 }
287
288 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
289 {
290   DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
291
292   // Calculate the dimensions of the texture.
293   // The total size of the texture is the length of the blend shapes blob.
294
295   textureWidth  = 0u;
296   textureHeight = 0u;
297
298   if(0u == totalTextureSize)
299   {
300     // nothing to do.
301     return;
302   }
303
304   const uint32_t pow2      = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
305   const uint32_t powWidth  = pow2 >> 1u;
306   const uint32_t powHeight = pow2 - powWidth;
307
308   textureWidth  = 1u << powWidth;
309   textureHeight = 1u << powHeight;
310 }
311
312 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
313 {
314   uint32_t geometryBufferIndex = 0u;
315   float    maxDistance         = 0.f;
316   Vector3* geometryBufferV3    = reinterpret_cast<Vector3*>(geometryBuffer);
317   for(const auto& blendShape : blendShapes)
318   {
319     if(blendShape.deltas.IsDefined())
320     {
321       DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
322                           blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
323                          "Blend Shape position buffer length not a multiple of element size");
324
325       const auto           bufferSize = blendShape.deltas.mBlob.GetBufferSize();
326       std::vector<uint8_t> buffer(bufferSize);
327       if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
328       {
329         blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
330         // Calculate the difference with the original mesh.
331         // Find the max distance to normalize the deltas.
332         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
333
334         for(uint32_t index = 0u; index < numberOfVertices; ++index)
335         {
336           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
337           delta          = deltasBuffer[index];
338
339           maxDistance = std::max(maxDistance, delta.LengthSquared());
340         }
341       }
342     }
343
344     if(blendShape.normals.IsDefined())
345     {
346       DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
347                           blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
348                          "Blend Shape normals buffer length not a multiple of element size");
349
350       const auto           bufferSize = blendShape.normals.mBlob.GetBufferSize();
351       std::vector<uint8_t> buffer(bufferSize);
352       if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
353       {
354         blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
355
356         // Calculate the difference with the original mesh, and translate to make all values positive.
357         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
358
359         for(uint32_t index = 0u; index < numberOfVertices; ++index)
360         {
361           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
362           delta          = deltasBuffer[index];
363
364           delta.x *= 0.5f;
365           delta.y *= 0.5f;
366           delta.z *= 0.5f;
367
368           delta.x += 0.5f;
369           delta.y += 0.5f;
370           delta.z += 0.5f;
371         }
372       }
373     }
374
375     if(blendShape.tangents.IsDefined())
376     {
377       DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
378                           blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
379                          "Blend Shape tangents buffer length not a multiple of element size");
380
381       const auto           bufferSize = blendShape.tangents.mBlob.GetBufferSize();
382       std::vector<uint8_t> buffer(bufferSize);
383       if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
384       {
385         blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
386
387         // Calculate the difference with the original mesh, and translate to make all values positive.
388         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
389
390         for(uint32_t index = 0u; index < numberOfVertices; ++index)
391         {
392           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
393           delta          = deltasBuffer[index];
394
395           delta.x *= 0.5f;
396           delta.y *= 0.5f;
397           delta.z *= 0.5f;
398
399           delta.x += 0.5f;
400           delta.y += 0.5f;
401           delta.z += 0.5f;
402         }
403       }
404     }
405   }
406
407   geometryBufferIndex = 0u;
408   for(const auto& blendShape : blendShapes)
409   {
410     // Normalize all the deltas and translate to a possitive value.
411     // Deltas are going to be passed to the shader in a color texture
412     // whose values that are less than zero are clamped.
413     if(blendShape.deltas.IsDefined())
414     {
415       const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
416
417       for(uint32_t index = 0u; index < numberOfVertices; ++index)
418       {
419         Vector3& delta = geometryBufferV3[geometryBufferIndex++];
420         delta.x        = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
421         delta.y        = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
422         delta.z        = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
423       }
424
425       // Calculate and store the unnormalize factor.
426       blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
427     }
428
429     if(blendShape.normals.IsDefined())
430     {
431       geometryBufferIndex += numberOfVertices;
432     }
433
434     if(blendShape.tangents.IsDefined())
435     {
436       geometryBufferIndex += numberOfVertices;
437     }
438   }
439 }
440
441 } // namespace
442
443 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
444 : mIndices{indices},
445   mValues{values},
446   mCount{count}
447 {
448 }
449
450 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob&       blob,
451                                    const MeshDefinition::SparseBlob& sparse)
452 : mBlob{blob},
453   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
454 {
455 }
456
457 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
458 {
459   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
460   const auto numComponents = std::max(min.size(), max.size());
461
462   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
463   ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
464     value = std::min(max[i], value);
465   })
466                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
467                                     value = std::max(min[i], value);
468                                   }
469                                                : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) {
470                                                    value = std::min(std::max(min[i], value), max[i]);
471                                                  }));
472
473   if(!clampFn)
474   {
475     return;
476   }
477
478   auto end = values + count * numComponents;
479   while(values != end)
480   {
481     auto     nextElement = values + numComponents;
482     uint32_t i           = 0;
483     while(values != nextElement)
484     {
485       clampFn(min.data(), max.data(), i, *values);
486       ++values;
487       ++i;
488     }
489   }
490 }
491
492 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)
493 : mOffset(offset),
494   mLength(length),
495   mStride(stride),
496   mElementSizeHint(elementSizeHint),
497   mMin(min),
498   mMax(max)
499 {
500 }
501
502 uint32_t MeshDefinition::Blob::GetBufferSize() const
503 {
504   return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
505 }
506
507 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
508 {
509   ApplyMinMax(mMin, mMax, count, values);
510 }
511
512 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
513 {
514   Property::Map attribMap;
515   attribMap[mName]          = mType;
516   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
517   attribBuffer.SetData(mData.data(), mNumElements);
518
519   g.AddVertexBuffer(attribBuffer);
520 }
521
522 bool MeshDefinition::IsQuad() const
523 {
524   return CaseInsensitiveStringCompare(QUAD, mUri);
525 }
526
527 bool MeshDefinition::IsSkinned() const
528 {
529   return mJoints0.IsDefined() && mWeights0.IsDefined();
530 }
531
532 bool MeshDefinition::HasBlendShapes() const
533 {
534   return !mBlendShapes.empty();
535 }
536
537 void MeshDefinition::RequestNormals()
538 {
539   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
540 }
541
542 void MeshDefinition::RequestTangents()
543 {
544   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
545 }
546
547 MeshDefinition::RawData
548 MeshDefinition::LoadRaw(const std::string& modelsPath) const
549 {
550   RawData raw;
551   if(IsQuad())
552   {
553     return raw;
554   }
555
556   const std::string meshPath = modelsPath + mUri;
557   std::ifstream     binFile(meshPath, std::ios::binary);
558   if(!binFile)
559   {
560     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
561   }
562
563   if(mIndices.IsDefined())
564   {
565     if(MaskMatch(mFlags, U32_INDICES))
566     {
567       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
568                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
569                          "Index buffer length not a multiple of element size");
570       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
571       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
572       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
573       {
574         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
575       }
576
577       auto u16s = raw.mIndices.data();
578       auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
579       auto end  = u32s + indexCount;
580       while(u32s != end)
581       {
582         *u16s = static_cast<uint16_t>(*u32s);
583         ++u16s;
584         ++u32s;
585       }
586
587       raw.mIndices.resize(indexCount);
588     }
589     else
590     {
591       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
592                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
593                          "Index buffer length not a multiple of element size");
594       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
595       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
596       {
597         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
598       }
599     }
600   }
601
602   std::vector<Vector3> positions;
603   if(mPositions.IsDefined())
604   {
605     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
606                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
607                        "Position buffer length not a multiple of element size");
608     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
609     std::vector<uint8_t> buffer(bufferSize);
610     if(!ReadAccessor(mPositions, binFile, buffer.data()))
611     {
612       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
613     }
614
615     uint32_t numVector3 = bufferSize / sizeof(Vector3);
616     mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
617
618     if(HasBlendShapes())
619     {
620       positions.resize(numVector3);
621       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
622     }
623
624     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
625   }
626
627   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
628   auto       hasNormals  = mNormals.IsDefined();
629   if(hasNormals)
630   {
631     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
632                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
633                        "Normal buffer length not a multiple of element size");
634     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
635     std::vector<uint8_t> buffer(bufferSize);
636     if(!ReadAccessor(mNormals, binFile, buffer.data()))
637     {
638       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
639     }
640
641     mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
642
643     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
644   }
645   else if(mNormals.mBlob.mLength != 0 && isTriangles)
646   {
647     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
648     GenerateNormals(raw);
649     hasNormals = true;
650   }
651
652   const auto hasUvs = mTexCoords.IsDefined();
653   if(hasUvs)
654   {
655     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
656                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
657                        "Normal buffer length not a multiple of element size");
658     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
659     std::vector<uint8_t> buffer(bufferSize);
660     if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
661     {
662       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
663     }
664
665     const auto uvCount = bufferSize / sizeof(Vector2);
666     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
667     {
668       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
669       auto uvEnd = uv + uvCount;
670       while(uv != uvEnd)
671       {
672         uv->y = 1.0f - uv->y;
673         ++uv;
674       }
675     }
676
677     mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
678
679     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
680   }
681
682   if(mTangents.IsDefined())
683   {
684     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % sizeof(Vector3) == 0) ||
685                         mTangents.mBlob.mStride >= sizeof(Vector3)) &&
686                        "Tangents buffer length not a multiple of element size");
687     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
688     std::vector<uint8_t> buffer(bufferSize);
689     if(!ReadAccessor(mTangents, binFile, buffer.data()))
690     {
691       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
692     }
693
694     mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
695
696     raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
697   }
698   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
699   {
700     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
701     hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
702   }
703
704   if(IsSkinned())
705   {
706     if(MaskMatch(mFlags, U16_JOINT_IDS))
707     {
708       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
709                           mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
710                          "Joints buffer length not a multiple of element size");
711       const auto           inBufferSize = mJoints0.mBlob.GetBufferSize();
712       std::vector<uint8_t> buffer(inBufferSize * 2);
713       auto                 u16s = buffer.data() + inBufferSize;
714       if(!ReadAccessor(mJoints0, binFile, u16s))
715       {
716         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
717       }
718
719       auto floats = reinterpret_cast<float*>(buffer.data());
720       auto end    = u16s + inBufferSize;
721       while(u16s != end)
722       {
723         auto value = *reinterpret_cast<uint16_t*>(u16s);
724         *floats    = static_cast<float>(value);
725
726         u16s += sizeof(uint16_t);
727         ++floats;
728       }
729       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
730     }
731     else
732     {
733       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
734                           mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
735                          "Joints buffer length not a multiple of element size");
736       const auto           bufferSize = mJoints0.mBlob.GetBufferSize();
737       std::vector<uint8_t> buffer(bufferSize);
738       if(!ReadAccessor(mJoints0, binFile, buffer.data()))
739       {
740         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
741       }
742
743       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
744     }
745
746     DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
747                         mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
748                        "Weights buffer length not a multiple of element size");
749     const auto           bufferSize = mWeights0.mBlob.GetBufferSize();
750     std::vector<uint8_t> buffer(bufferSize);
751     if(!ReadAccessor(mWeights0, binFile, buffer.data()))
752     {
753       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
754     }
755
756     raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
757   }
758
759   // Calculate the Blob for the blend shapes.
760   Blob blendShapesBlob;
761   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
762   blendShapesBlob.mLength = 0u;
763
764   for(const auto& blendShape : mBlendShapes)
765   {
766     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
767     {
768       if(i->IsDefined())
769       {
770         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
771         blendShapesBlob.mLength += i->mBlob.mLength;
772       }
773     }
774   }
775
776   if(HasBlendShapes())
777   {
778     const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
779
780     // Calculate the size of one buffer inside the texture.
781     raw.mBlendShapeBufferOffset = numberOfVertices;
782
783     bool     calculateGltf2BlendShapes = false;
784     uint32_t textureWidth              = 0u;
785     uint32_t textureHeight             = 0u;
786
787     if(!mBlendShapeHeader.IsDefined())
788     {
789       CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
790       calculateGltf2BlendShapes = true;
791     }
792     else
793     {
794       uint16_t header[2u];
795       ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
796       textureWidth  = header[0u];
797       textureHeight = header[1u];
798     }
799
800     const uint32_t numberOfBlendShapes = mBlendShapes.size();
801     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
802
803     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
804     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
805
806     if(calculateGltf2BlendShapes)
807     {
808       CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
809     }
810     else
811     {
812       Blob unnormalizeFactorBlob;
813       unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
814
815       if(blendShapesBlob.IsDefined())
816       {
817         if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
818         {
819           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
820         }
821       }
822
823       // Read the unnormalize factors.
824       if(unnormalizeFactorBlob.IsDefined())
825       {
826         ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
827       }
828     }
829     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
830   }
831
832   return raw;
833 }
834
835 MeshGeometry MeshDefinition::Load(RawData&& raw) const
836 {
837   MeshGeometry meshGeometry;
838   meshGeometry.geometry = Geometry::New();
839   meshGeometry.geometry.SetType(mPrimitiveType);
840
841   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
842   {
843     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
844     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
845   }
846   else
847   {
848     if(!raw.mIndices.empty())
849     {
850       meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
851     }
852
853     for(auto& a : raw.mAttribs)
854     {
855       a.AttachBuffer(meshGeometry.geometry);
856     }
857
858     if(HasBlendShapes())
859     {
860       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
861       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
862
863       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
864                                                      raw.mBlendShapeData.GetPixelFormat(),
865                                                      raw.mBlendShapeData.GetWidth(),
866                                                      raw.mBlendShapeData.GetHeight());
867       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
868     }
869   }
870
871   return meshGeometry;
872 }
873
874 } // namespace SceneLoader
875 } // namespace Dali