2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-scene3d/public-api/loader/mesh-definition.h>
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>
28 #include <type_traits>
30 namespace Dali::Scene3D::Loader
34 template<bool use32BitIndices>
38 using IndexType = typename std::conditional_t<use32BitIndices, uint32_t, uint16_t>;
39 IndexProvider(const uint16_t* indices)
40 : mData(reinterpret_cast<uintptr_t>(indices)),
41 mFunc(indices ? IncrementPointer : Increment)
45 IndexType operator()()
51 static IndexType Increment(uintptr_t& data)
53 // mData was 'zero' at construct time. Just simply return counter start with 0.
54 return static_cast<IndexType>(data++);
57 static IndexType IncrementPointer(uintptr_t& data)
59 auto iPtr = reinterpret_cast<const IndexType*>(data);
61 data = reinterpret_cast<uintptr_t>(++iPtr);
66 IndexType (*mFunc)(uintptr_t&);
69 const char* QUAD("quad");
71 ///@brief Reads a blob from the given stream @a source into @a target, which must have
72 /// at least @a descriptor.length bytes.
73 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
76 if(!source.seekg(descriptor.mOffset, std::istream::beg))
81 if(descriptor.IsConsecutive())
83 return !!source.read(reinterpret_cast<char*>(target), static_cast<std::streamsize>(static_cast<size_t>(descriptor.mLength)));
87 if(descriptor.mStride > descriptor.mElementSizeHint)
89 const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
90 uint32_t readSize = 0;
91 uint32_t totalSize = (descriptor.mLength / descriptor.mElementSizeHint) * descriptor.mStride;
92 while(readSize < totalSize &&
93 source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint))
95 readSize += descriptor.mStride;
96 target += descriptor.mElementSizeHint;
97 source.seekg(diff, std::istream::cur);
99 return readSize == totalSize;
106 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
108 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
109 for(uint32_t index = 0u; index < count; ++index)
111 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
112 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
116 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
118 bool success = false;
120 if(accessor.mBlob.IsDefined())
122 success = ReadBlob(accessor.mBlob, source, target);
131 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
132 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
134 if(!indices.IsDefined() || !values.IsDefined())
139 const auto indicesBufferSize = indices.GetBufferSize();
140 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
141 success = ReadBlob(indices, source, indicesBuffer.data());
147 const auto valuesBufferSize = values.GetBufferSize();
148 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
149 success = ReadBlob(values, source, valuesBuffer.data());
155 switch(indices.mElementSizeHint)
159 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
164 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
169 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
173 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
181 void ReadJointAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
183 constexpr auto sizeofBlobUnit = sizeof(T) * 4;
185 DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
186 accessor.mBlob.mStride >= sizeofBlobUnit) &&
187 "Joints buffer length not a multiple of element size");
188 const auto inBufferSize = accessor.mBlob.GetBufferSize();
189 const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
191 std::vector<uint8_t> buffer(outBufferSize);
192 auto inBuffer = buffer.data() + outBufferSize - inBufferSize;
193 if(!ReadAccessor(accessor, source, inBuffer))
195 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
198 if constexpr(sizeofBlobUnit != sizeof(Vector4))
200 auto floats = reinterpret_cast<float*>(buffer.data());
201 const auto end = inBuffer + inBufferSize;
202 while(inBuffer != end)
204 const auto value = *reinterpret_cast<T*>(inBuffer);
205 *floats = static_cast<float>(value);
207 inBuffer += sizeof(T);
211 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
215 void ReadWeightAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
217 constexpr auto sizeofBlobUnit = sizeof(T) * 4;
219 DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
220 accessor.mBlob.mStride >= sizeofBlobUnit) &&
221 "weights buffer length not a multiple of element size");
222 const auto inBufferSize = accessor.mBlob.GetBufferSize();
223 const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
225 std::vector<uint8_t> buffer(outBufferSize);
226 auto inBuffer = buffer.data() + outBufferSize - inBufferSize;
227 if(!ReadAccessor(accessor, source, inBuffer))
229 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
232 if constexpr(sizeofBlobUnit != sizeof(Vector4))
234 auto floats = reinterpret_cast<float*>(buffer.data());
235 const auto end = inBuffer + inBufferSize;
236 while(inBuffer != end)
238 const auto value = *reinterpret_cast<T*>(inBuffer);
239 // Normalize weight value. value /= 255 for uint8_t weight, and value /= 65535 for uint16_t weight.
240 *floats = static_cast<float>(value) / static_cast<float>((1 << (sizeof(T) * 8)) - 1);
242 inBuffer += sizeof(T);
246 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
249 template<bool use32BitsIndices, typename IndexProviderType = IndexProvider<use32BitsIndices>>
250 bool GenerateNormals(MeshDefinition::RawData& raw)
252 using IndexType = typename IndexProviderType::IndexType;
254 // mIndicies size must be even if we use 32bit indices.
255 if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
260 auto& attribs = raw.mAttribs;
261 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
263 IndexProviderType getIndex(raw.mIndices.data());
265 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
267 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
269 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
270 auto normals = reinterpret_cast<Vector3*>(buffer.data());
272 for(uint32_t i = 0; i < numIndices; i += 3)
274 IndexType indices[]{getIndex(), getIndex(), getIndex()};
275 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
277 Vector3 a = pos[1] - pos[0];
278 Vector3 b = pos[2] - pos[0];
280 Vector3 normal(a.Cross(b));
281 normals[indices[0]] += normal;
282 normals[indices[1]] += normal;
283 normals[indices[2]] += normal;
286 auto iEnd = normals + attribs[0].mNumElements;
287 while(normals != iEnd)
289 normals->Normalize();
293 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
298 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>>
299 bool GenerateTangents(MeshDefinition::RawData& raw)
301 using IndexType = typename IndexProviderType::IndexType;
303 // mIndicies size must be even if we use 32bit indices.
304 if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
309 auto& attribs = raw.mAttribs;
310 // Required positions, normals, uvs (if we have). If not, skip generation
311 if(DALI_UNLIKELY(attribs.size() < (2 + static_cast<size_t>(hasUvs))))
316 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(T));
317 auto tangents = reinterpret_cast<T*>(buffer.data());
321 IndexProviderType getIndex(raw.mIndices.data());
323 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
325 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
326 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
328 for(uint32_t i = 0; i < numIndices; i += 3)
330 IndexType indices[]{getIndex(), getIndex(), getIndex()};
331 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
332 Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
334 float x0 = pos[1].x - pos[0].x;
335 float y0 = pos[1].y - pos[0].y;
336 float z0 = pos[1].z - pos[0].z;
338 float x1 = pos[2].x - pos[0].x;
339 float y1 = pos[2].y - pos[0].y;
340 float z1 = pos[2].z - pos[0].z;
342 float s0 = uv[1].x - uv[0].x;
343 float t0 = uv[1].y - uv[0].y;
345 float s1 = uv[2].x - uv[0].x;
346 float t1 = uv[2].y - uv[0].y;
348 float det = (s0 * t1 - t0 * s1);
349 float r = 1.f / ((std::abs(det) < Dali::Epsilon<1000>::value) ? (Dali::Epsilon<1000>::value * (det > 0.0f ? 1.f : -1.f)) : det);
350 Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
351 tangents[indices[0]] += T(tangent);
352 tangents[indices[1]] += T(tangent);
353 tangents[indices[2]] += T(tangent);
357 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
358 auto iEnd = normals + attribs[1].mNumElements;
359 while(normals != iEnd)
364 // Calculated by indexs
365 tangentVec3 = Vector3((*tangents).x, (*tangents).y, (*tangents).z);
369 // Only choiced by normal vector. by indexs
370 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
371 tangentVec3 = t[t[1].LengthSquared() > t[0].LengthSquared()];
374 tangentVec3 -= *normals * normals->Dot(tangentVec3);
375 tangentVec3.Normalize();
376 if constexpr(useVec3)
378 *tangents = tangentVec3;
382 *tangents = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
388 attribs.push_back({"aTangent", useVec3 ? Property::VECTOR3 : Property::VECTOR4, attribs[0].mNumElements, std::move(buffer)});
393 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
395 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
397 // Calculate the dimensions of the texture.
398 // The total size of the texture is the length of the blend shapes blob.
403 if(0u == totalTextureSize)
409 const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
410 const uint32_t powWidth = pow2 >> 1u;
411 const uint32_t powHeight = pow2 - powWidth;
413 textureWidth = 1u << powWidth;
414 textureHeight = 1u << powHeight;
417 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
419 uint32_t geometryBufferIndex = 0u;
420 float maxDistance = 0.f;
421 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
422 for(const auto& blendShape : blendShapes)
424 if(blendShape.deltas.IsDefined())
426 DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
427 blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
428 "Blend Shape position buffer length not a multiple of element size");
430 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
431 std::vector<uint8_t> buffer(bufferSize);
432 if(ReadAccessor(blendShape.deltas, buffers[blendShape.deltas.mBufferIdx].GetBufferStream(), buffer.data()))
434 blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
435 // Calculate the difference with the original mesh.
436 // Find the max distance to normalize the deltas.
437 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
439 for(uint32_t index = 0u; index < numberOfVertices; ++index)
441 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
442 delta = deltasBuffer[index];
444 maxDistance = std::max(maxDistance, delta.LengthSquared());
449 if(blendShape.normals.IsDefined())
451 DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
452 blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
453 "Blend Shape normals buffer length not a multiple of element size");
455 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
456 std::vector<uint8_t> buffer(bufferSize);
457 if(ReadAccessor(blendShape.normals, buffers[blendShape.normals.mBufferIdx].GetBufferStream(), buffer.data()))
459 blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
461 // Calculate the difference with the original mesh, and translate to make all values positive.
462 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
464 for(uint32_t index = 0u; index < numberOfVertices; ++index)
466 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
467 delta = deltasBuffer[index];
480 if(blendShape.tangents.IsDefined())
482 DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
483 blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
484 "Blend Shape tangents buffer length not a multiple of element size");
486 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
487 std::vector<uint8_t> buffer(bufferSize);
488 if(ReadAccessor(blendShape.tangents, buffers[blendShape.tangents.mBufferIdx].GetBufferStream(), buffer.data()))
490 blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
492 // Calculate the difference with the original mesh, and translate to make all values positive.
493 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
495 for(uint32_t index = 0u; index < numberOfVertices; ++index)
497 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
498 delta = deltasBuffer[index];
512 geometryBufferIndex = 0u;
513 for(const auto& blendShape : blendShapes)
515 // Normalize all the deltas and translate to a possitive value.
516 // Deltas are going to be passed to the shader in a color texture
517 // whose values that are less than zero are clamped.
518 if(blendShape.deltas.IsDefined())
520 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
522 for(uint32_t index = 0u; index < numberOfVertices; ++index)
524 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
525 delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
526 delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
527 delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
530 // Calculate and store the unnormalize factor.
531 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
534 if(blendShape.normals.IsDefined())
536 geometryBufferIndex += numberOfVertices;
539 if(blendShape.tangents.IsDefined())
541 geometryBufferIndex += numberOfVertices;
546 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
548 auto& stream = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
549 availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
555 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
562 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
563 : mIndices(std::move(indices)),
564 mValues(std::move(values)),
569 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
570 const MeshDefinition::SparseBlob& sparse,
573 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
574 mBufferIdx(bufferIndex)
578 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&& blob,
579 MeshDefinition::SparseBlob&& sparse,
581 : mBlob{std::move(blob)},
582 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
583 mBufferIdx(bufferIndex)
587 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
589 min.assign(numComponents, MAXFLOAT);
590 max.assign(numComponents, -MAXFLOAT);
591 for(uint32_t i = 0; i < count; ++i)
593 for(uint32_t j = 0; j < numComponents; ++j)
595 min[j] = std::min(min[j], *values);
596 max[j] = std::max(max[j], *values);
602 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
604 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
605 const auto numComponents = std::max(min.size(), max.size());
607 using ClampFn = void (*)(const float*, const float*, uint32_t, float&);
608 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); })
609 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { value = std::max(min[i], value); }
610 : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) { value = std::min(std::max(min[i], value), max[i]); }));
617 auto end = values + count * numComponents;
620 auto nextElement = values + numComponents;
622 while(values != nextElement)
624 clampFn(min.data(), max.data(), i, *values);
631 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)
635 mElementSizeHint(elementSizeHint),
641 uint32_t MeshDefinition::Blob::GetBufferSize() const
646 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
648 ComputeMinMax(mMin, mMax, numComponents, count, values);
651 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
653 ApplyMinMax(mMin, mMax, count, values);
656 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
658 Property::Map attribMap;
659 attribMap[mName] = mType;
660 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
661 attribBuffer.SetData(mData.data(), mNumElements);
663 g.AddVertexBuffer(attribBuffer);
666 bool MeshDefinition::IsQuad() const
668 return CaseInsensitiveStringCompare(QUAD, mUri);
671 bool MeshDefinition::IsSkinned() const
673 return mJoints0.IsDefined() && mWeights0.IsDefined();
676 bool MeshDefinition::HasBlendShapes() const
678 return !mBlendShapes.empty();
681 void MeshDefinition::RequestNormals()
683 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
686 void MeshDefinition::RequestTangents()
688 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
691 MeshDefinition::RawData
692 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
700 std::string meshPath;
701 meshPath = modelsPath + mUri;
702 std::fstream fileStream;
705 fileStream.open(meshPath, std::ios::in | std::ios::binary);
706 if(!fileStream.is_open())
708 DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
712 if(mIndices.IsDefined())
714 if(MaskMatch(mFlags, U32_INDICES))
716 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
717 mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
718 "Index buffer length not a multiple of element size");
719 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
720 raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
723 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
724 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
726 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
729 else if(MaskMatch(mFlags, U8_INDICES))
731 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
732 mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
733 "Index buffer length not a multiple of element size");
734 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
735 raw.mIndices.resize(indexCount); // NOTE: we need space for uint16_ts initially.
738 auto u8s = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
739 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
740 if(!ReadAccessor(mIndices, stream, u8s))
742 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
745 auto u16s = raw.mIndices.data();
746 auto end = u8s + indexCount;
749 *u16s = static_cast<uint16_t>(*u8s);
756 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
757 mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
758 "Index buffer length not a multiple of element size");
759 raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
762 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
763 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
765 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
770 std::vector<Vector3> positions;
771 if(mPositions.IsDefined())
773 DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
774 mPositions.mBlob.mStride >= sizeof(Vector3)) &&
775 "Position buffer length not a multiple of element size");
776 const auto bufferSize = mPositions.mBlob.GetBufferSize();
777 std::vector<uint8_t> buffer(bufferSize);
780 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
781 if(!ReadAccessor(mPositions, stream, buffer.data()))
783 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
786 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
787 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
789 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
793 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
798 positions.resize(numVector3);
799 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
802 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
805 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
806 auto hasNormals = mNormals.IsDefined();
809 DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
810 mNormals.mBlob.mStride >= sizeof(Vector3)) &&
811 "Normal buffer length not a multiple of element size");
812 const auto bufferSize = mNormals.mBlob.GetBufferSize();
813 std::vector<uint8_t> buffer(bufferSize);
816 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
817 if(!ReadAccessor(mNormals, stream, buffer.data()))
819 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
822 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
824 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
826 else if(mNormals.mBlob.mLength != 0 && isTriangles)
828 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
829 static const std::function<bool(RawData&)> GenerateNormalsFunction[2] =
831 GenerateNormals<false>,
832 GenerateNormals<true>,
834 const bool generateSuccessed = GenerateNormalsFunction[MaskMatch(mFlags, U32_INDICES)](raw);
835 if(!generateSuccessed)
837 DALI_LOG_ERROR("Failed to generate normal\n");
845 const auto hasUvs = mTexCoords.IsDefined();
848 DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
849 mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
850 "Normal buffer length not a multiple of element size");
851 const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
852 std::vector<uint8_t> buffer(bufferSize);
855 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
856 if(!ReadAccessor(mTexCoords, stream, buffer.data()))
858 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
861 const auto uvCount = bufferSize / sizeof(Vector2);
862 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
864 auto uv = reinterpret_cast<Vector2*>(buffer.data());
865 auto uvEnd = uv + uvCount;
868 uv->y = 1.0f - uv->y;
873 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(uvCount), reinterpret_cast<float*>(buffer.data()));
875 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
878 if(mTangents.IsDefined())
880 uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
881 DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
882 mTangents.mBlob.mStride >= propertySize) &&
883 "Tangents buffer length not a multiple of element size");
884 const auto bufferSize = mTangents.mBlob.GetBufferSize();
885 std::vector<uint8_t> buffer(bufferSize);
888 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
889 if(!ReadAccessor(mTangents, stream, buffer.data()))
891 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
893 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
895 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
897 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
899 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
900 static const std::function<bool(RawData&)> GenerateTangentsFunction[2][2][2] =
904 GenerateTangents<false, false, false>,
905 GenerateTangents<false, false, true>,
908 GenerateTangents<false, true, false>,
909 GenerateTangents<false, true, true>,
914 GenerateTangents<true, false, false>,
915 GenerateTangents<true, false, true>,
918 GenerateTangents<true, true, false>,
919 GenerateTangents<true, true, true>,
922 const bool generateSuccessed = GenerateTangentsFunction[MaskMatch(mFlags, U32_INDICES)][mTangentType == Property::VECTOR3][hasUvs](raw);
923 if(!generateSuccessed)
925 DALI_LOG_ERROR("Failed to generate tangents\n");
929 if(mColors.IsDefined())
931 uint32_t propertySize = mColors.mBlob.mElementSizeHint;
932 Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
933 if(propertyType != Property::NONE)
935 DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
936 mColors.mBlob.mStride >= propertySize) &&
937 "Colors buffer length not a multiple of element size");
938 const auto bufferSize = mColors.mBlob.GetBufferSize();
939 std::vector<uint8_t> buffer(bufferSize);
942 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
943 if(!ReadAccessor(mColors, stream, buffer.data()))
945 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
947 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
949 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
954 std::vector<uint8_t> buffer(raw.mAttribs[0].mNumElements * sizeof(Vector4));
955 auto colors = reinterpret_cast<Vector4*>(buffer.data());
957 for(uint32_t i = 0; i < raw.mAttribs[0].mNumElements; i++)
959 colors[i] = Vector4::ONE;
962 raw.mAttribs.push_back({"aVertexColor", Property::VECTOR4, raw.mAttribs[0].mNumElements, std::move(buffer)});
967 std::string pathJoint;
968 auto& streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
969 if(MaskMatch(mFlags, U16_JOINT_IDS))
971 ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
973 else if(MaskMatch(mFlags, U8_JOINT_IDS))
975 ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
979 ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
982 std::string pathWeight;
983 auto& streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
984 if(MaskMatch(mFlags, U16_WEIGHT))
986 ReadWeightAccessor<uint16_t>(raw, mWeights0, streamWeight, pathWeight);
988 else if(MaskMatch(mFlags, U8_WEIGHT))
990 ReadWeightAccessor<uint8_t>(raw, mWeights0, streamWeight, pathWeight);
994 ReadWeightAccessor<float>(raw, mWeights0, streamWeight, pathWeight);
998 // Calculate the Blob for the blend shapes.
999 Blob blendShapesBlob;
1000 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
1001 blendShapesBlob.mLength = 0u;
1003 for(const auto& blendShape : mBlendShapes)
1005 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
1009 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
1010 blendShapesBlob.mLength += i->mBlob.mLength;
1015 if(HasBlendShapes())
1017 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
1019 // Calculate the size of one buffer inside the texture.
1020 raw.mBlendShapeBufferOffset = numberOfVertices;
1022 bool calculateGltf2BlendShapes = false;
1023 uint32_t textureWidth = 0u;
1024 uint32_t textureHeight = 0u;
1026 if(!mBlendShapeHeader.IsDefined())
1028 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
1029 calculateGltf2BlendShapes = true;
1033 uint16_t header[2u];
1034 ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
1035 textureWidth = header[0u];
1036 textureHeight = header[1u];
1039 const uint32_t numberOfBlendShapes = mBlendShapes.size();
1040 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
1042 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
1043 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
1045 if(calculateGltf2BlendShapes)
1047 CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
1051 Blob unnormalizeFactorBlob;
1052 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
1054 if(blendShapesBlob.IsDefined())
1056 if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
1058 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
1062 // Read the unnormalize factors.
1063 if(unnormalizeFactorBlob.IsDefined())
1065 ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
1068 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
1074 MeshGeometry MeshDefinition::Load(RawData&& raw) const
1076 MeshGeometry meshGeometry;
1077 meshGeometry.geometry = Geometry::New();
1078 meshGeometry.geometry.SetType(mPrimitiveType);
1080 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
1082 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
1083 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
1087 if(!raw.mIndices.empty())
1089 if(MaskMatch(mFlags, U32_INDICES))
1091 // TODO : We can only store indeces as uint16_type. Send Dali::Geometry that we use it as uint32_t actual.
1092 meshGeometry.geometry.SetIndexBuffer(reinterpret_cast<const uint32_t*>(raw.mIndices.data()), raw.mIndices.size() / 2);
1096 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
1100 for(auto& a : raw.mAttribs)
1102 a.AttachBuffer(meshGeometry.geometry);
1105 if(HasBlendShapes())
1107 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
1108 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1110 meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1111 raw.mBlendShapeData.GetPixelFormat(),
1112 raw.mBlendShapeData.GetWidth(),
1113 raw.mBlendShapeData.GetHeight());
1114 meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1118 return meshGeometry;
1121 void MeshDefinition::RetrieveBlendShapeComponents(bool& hasPositions, bool& hasNormals, bool& hasTangents) const
1123 for(const auto& blendShape : mBlendShapes)
1125 hasPositions = hasPositions || blendShape.deltas.IsDefined();
1126 hasNormals = hasNormals || blendShape.normals.IsDefined();
1127 hasTangents = hasTangents || blendShape.tangents.IsDefined();
1131 } // namespace Dali::Scene3D::Loader