2 * Copyright (c) 2022 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"
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
34 using Uint16Vector4 = uint16_t[4];
39 IndexProvider(const uint16_t* indices)
40 : mData(reinterpret_cast<uintptr_t>(indices)),
41 mFunc(indices ? IncrementPointer : Increment)
51 static uint16_t Increment(uintptr_t& data)
53 return static_cast<uint16_t>(data++);
56 static uint16_t IncrementPointer(uintptr_t& data)
58 auto iPtr = reinterpret_cast<const uint16_t*>(data);
60 data = reinterpret_cast<uintptr_t>(++iPtr);
65 uint16_t (*mFunc)(uintptr_t&);
68 const std::string QUAD("quad");
70 ///@brief Reads a blob from the given stream @a source into @a target, which must have
71 /// at least @a descriptor.length bytes.
72 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
74 if(!source.seekg(descriptor.mOffset, std::istream::beg))
79 if(descriptor.IsConsecutive())
81 return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
85 if(descriptor.mStride > descriptor.mElementSizeHint)
87 const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
88 uint32_t readSize = 0;
89 uint32_t totalSize = (descriptor.mLength / descriptor.mElementSizeHint) * descriptor.mStride;
90 while(readSize < totalSize &&
91 source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
92 source.seekg(diff, std::istream::cur))
94 readSize += descriptor.mStride;
95 target += descriptor.mElementSizeHint;
97 return readSize == totalSize;
104 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
106 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
107 for(uint32_t index = 0u; index < count; ++index)
109 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
110 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
114 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
116 bool success = false;
118 if(accessor.mBlob.IsDefined())
120 success = ReadBlob(accessor.mBlob, source, target);
129 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
130 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
132 if(!indices.IsDefined() || !values.IsDefined())
137 const auto indicesBufferSize = indices.GetBufferSize();
138 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
139 success = ReadBlob(indices, source, indicesBuffer.data());
145 const auto valuesBufferSize = values.GetBufferSize();
146 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
147 success = ReadBlob(values, source, valuesBuffer.data());
153 switch(indices.mElementSizeHint)
157 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
162 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
167 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
171 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
178 void GenerateNormals(MeshDefinition::RawData& raw)
180 auto& attribs = raw.mAttribs;
181 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
182 IndexProvider getIndex(raw.mIndices.data());
184 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
186 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
188 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
189 auto normals = reinterpret_cast<Vector3*>(buffer.data());
191 for(uint32_t i = 0; i < numIndices; i += 3)
193 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
194 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
196 Vector3 a = pos[1] - pos[0];
197 Vector3 b = pos[2] - pos[0];
199 Vector3 normal(a.Cross(b));
200 normals[indices[0]] += normal;
201 normals[indices[1]] += normal;
202 normals[indices[2]] += normal;
205 auto iEnd = normals + attribs[0].mNumElements;
206 while(normals != iEnd)
208 normals->Normalize();
212 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
215 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
217 auto& attribs = raw.mAttribs;
218 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
219 IndexProvider getIndex(raw.mIndices.data());
221 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
223 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
224 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
226 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
227 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
229 for(uint32_t i = 0; i < numIndices; i += 3)
231 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
232 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
233 Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
235 float x0 = pos[1].x - pos[0].x;
236 float y0 = pos[1].y - pos[0].y;
237 float z0 = pos[1].z - pos[0].z;
239 float x1 = pos[2].x - pos[0].x;
240 float y1 = pos[2].y - pos[0].y;
241 float z1 = pos[2].z - pos[0].z;
243 float s0 = uv[1].x - uv[0].x;
244 float t0 = uv[1].y - uv[0].y;
246 float s1 = uv[2].x - uv[0].x;
247 float t1 = uv[2].y - uv[0].y;
249 float r = 1.f / (s0 * t1 - t0 * s1);
250 Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
251 tangents[indices[0]] += tangent;
252 tangents[indices[1]] += tangent;
253 tangents[indices[2]] += tangent;
256 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
257 auto iEnd = normals + attribs[1].mNumElements;
258 while(normals != iEnd)
260 *tangents -= *normals * normals->Dot(*tangents);
261 tangents->Normalize();
266 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
269 void GenerateTangents(MeshDefinition::RawData& raw)
271 auto& attribs = raw.mAttribs;
272 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
274 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
276 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
277 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
279 auto iEnd = normals + attribs[1].mNumElements;
280 while(normals != iEnd)
282 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
284 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
285 *tangents -= *normals * normals->Dot(*tangents);
286 tangents->Normalize();
291 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
294 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
296 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
298 // Calculate the dimensions of the texture.
299 // The total size of the texture is the length of the blend shapes blob.
304 if(0u == totalTextureSize)
310 const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
311 const uint32_t powWidth = pow2 >> 1u;
312 const uint32_t powHeight = pow2 - powWidth;
314 textureWidth = 1u << powWidth;
315 textureHeight = 1u << powHeight;
318 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
320 uint32_t geometryBufferIndex = 0u;
321 float maxDistance = 0.f;
322 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
323 for(const auto& blendShape : blendShapes)
325 if(blendShape.deltas.IsDefined())
327 DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
328 blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
329 "Blend Shape position buffer length not a multiple of element size");
331 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
332 std::vector<uint8_t> buffer(bufferSize);
333 if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
335 blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
336 // Calculate the difference with the original mesh.
337 // Find the max distance to normalize the deltas.
338 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
340 for(uint32_t index = 0u; index < numberOfVertices; ++index)
342 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
343 delta = deltasBuffer[index];
345 maxDistance = std::max(maxDistance, delta.LengthSquared());
350 if(blendShape.normals.IsDefined())
352 DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
353 blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
354 "Blend Shape normals buffer length not a multiple of element size");
356 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
357 std::vector<uint8_t> buffer(bufferSize);
358 if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
360 blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
362 // Calculate the difference with the original mesh, and translate to make all values positive.
363 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
365 for(uint32_t index = 0u; index < numberOfVertices; ++index)
367 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
368 delta = deltasBuffer[index];
381 if(blendShape.tangents.IsDefined())
383 DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
384 blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
385 "Blend Shape tangents buffer length not a multiple of element size");
387 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
388 std::vector<uint8_t> buffer(bufferSize);
389 if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
391 blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
393 // Calculate the difference with the original mesh, and translate to make all values positive.
394 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
396 for(uint32_t index = 0u; index < numberOfVertices; ++index)
398 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
399 delta = deltasBuffer[index];
413 geometryBufferIndex = 0u;
414 for(const auto& blendShape : blendShapes)
416 // Normalize all the deltas and translate to a possitive value.
417 // Deltas are going to be passed to the shader in a color texture
418 // whose values that are less than zero are clamped.
419 if(blendShape.deltas.IsDefined())
421 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
423 for(uint32_t index = 0u; index < numberOfVertices; ++index)
425 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
426 delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
427 delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
428 delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
431 // Calculate and store the unnormalize factor.
432 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
435 if(blendShape.normals.IsDefined())
437 geometryBufferIndex += numberOfVertices;
440 if(blendShape.tangents.IsDefined())
442 geometryBufferIndex += numberOfVertices;
449 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
456 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
457 : mIndices(std::move(indices)),
458 mValues(std::move(values)),
463 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
464 const MeshDefinition::SparseBlob& sparse)
466 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
470 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&& blob,
471 MeshDefinition::SparseBlob&& sparse)
472 : mBlob{std::move(blob)},
473 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr}
477 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
479 min.assign(numComponents, MAXFLOAT);
480 max.assign(numComponents, -MAXFLOAT);
481 for(uint32_t i = 0; i < count; ++i)
483 for(uint32_t j = 0; j < numComponents; ++j)
485 min[j] = std::min(min[j], *values);
486 max[j] = std::max(max[j], *values);
492 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
494 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
495 const auto numComponents = std::max(min.size(), max.size());
497 using ClampFn = void (*)(const float*, const float*, uint32_t, float&);
498 ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
499 value = std::min(max[i], value);
501 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
502 value = std::max(min[i], value);
504 : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) {
505 value = std::min(std::max(min[i], value), max[i]);
513 auto end = values + count * numComponents;
516 auto nextElement = values + numComponents;
518 while(values != nextElement)
520 clampFn(min.data(), max.data(), i, *values);
527 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)
531 mElementSizeHint(elementSizeHint),
537 uint32_t MeshDefinition::Blob::GetBufferSize() const
542 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
544 ComputeMinMax(mMin, mMax, numComponents, count, values);
547 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
549 ApplyMinMax(mMin, mMax, count, values);
552 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
554 Property::Map attribMap;
555 attribMap[mName] = mType;
556 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
557 attribBuffer.SetData(mData.data(), mNumElements);
559 g.AddVertexBuffer(attribBuffer);
562 bool MeshDefinition::IsQuad() const
564 return CaseInsensitiveStringCompare(QUAD, mUri);
567 bool MeshDefinition::IsSkinned() const
569 return mJoints0.IsDefined() && mWeights0.IsDefined();
572 bool MeshDefinition::HasBlendShapes() const
574 return !mBlendShapes.empty();
577 void MeshDefinition::RequestNormals()
579 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
582 void MeshDefinition::RequestTangents()
584 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
587 MeshDefinition::RawData
588 MeshDefinition::LoadRaw(const std::string& modelsPath)
596 const std::string meshPath = modelsPath + mUri;
597 std::ifstream binFile(meshPath, std::ios::binary);
600 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
603 if(mIndices.IsDefined())
605 if(MaskMatch(mFlags, U32_INDICES))
607 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
608 mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
609 "Index buffer length not a multiple of element size");
610 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
611 raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
612 if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
614 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
617 auto u16s = raw.mIndices.data();
618 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
619 auto end = u32s + indexCount;
622 *u16s = static_cast<uint16_t>(*u32s);
627 raw.mIndices.resize(indexCount);
631 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
632 mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
633 "Index buffer length not a multiple of element size");
634 raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
635 if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
637 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
642 std::vector<Vector3> positions;
643 if(mPositions.IsDefined())
645 DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
646 mPositions.mBlob.mStride >= sizeof(Vector3)) &&
647 "Position buffer length not a multiple of element size");
648 const auto bufferSize = mPositions.mBlob.GetBufferSize();
649 std::vector<uint8_t> buffer(bufferSize);
650 if(!ReadAccessor(mPositions, binFile, buffer.data()))
652 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
655 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
656 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
658 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
662 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
667 positions.resize(numVector3);
668 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
671 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
674 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
675 auto hasNormals = mNormals.IsDefined();
678 DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
679 mNormals.mBlob.mStride >= sizeof(Vector3)) &&
680 "Normal buffer length not a multiple of element size");
681 const auto bufferSize = mNormals.mBlob.GetBufferSize();
682 std::vector<uint8_t> buffer(bufferSize);
683 if(!ReadAccessor(mNormals, binFile, buffer.data()))
685 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
688 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
690 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
692 else if(mNormals.mBlob.mLength != 0 && isTriangles)
694 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
695 GenerateNormals(raw);
699 const auto hasUvs = mTexCoords.IsDefined();
702 DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
703 mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
704 "Normal buffer length not a multiple of element size");
705 const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
706 std::vector<uint8_t> buffer(bufferSize);
707 if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
709 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
712 const auto uvCount = bufferSize / sizeof(Vector2);
713 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
715 auto uv = reinterpret_cast<Vector2*>(buffer.data());
716 auto uvEnd = uv + uvCount;
719 uv->y = 1.0f - uv->y;
724 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector2)), reinterpret_cast<float*>(buffer.data()));
726 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
729 if(mTangents.IsDefined())
731 uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
732 DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
733 mTangents.mBlob.mStride >= propertySize) &&
734 "Tangents buffer length not a multiple of element size");
735 const auto bufferSize = mTangents.mBlob.GetBufferSize();
736 std::vector<uint8_t> buffer(bufferSize);
737 if(!ReadAccessor(mTangents, binFile, buffer.data()))
739 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
741 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
743 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
745 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
747 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
748 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
751 if(mColors.IsDefined())
753 uint32_t propertySize = mColors.mBlob.mElementSizeHint;
754 Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
755 if(propertyType != Property::NONE)
757 DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
758 mColors.mBlob.mStride >= propertySize) &&
759 "Colors buffer length not a multiple of element size");
760 const auto bufferSize = mColors.mBlob.GetBufferSize();
761 std::vector<uint8_t> buffer(bufferSize);
762 if(!ReadAccessor(mColors, binFile, buffer.data()))
764 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << meshPath << "'.";
766 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
768 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
774 if(MaskMatch(mFlags, U16_JOINT_IDS))
776 DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
777 mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
778 "Joints buffer length not a multiple of element size");
779 const auto inBufferSize = mJoints0.mBlob.GetBufferSize();
780 std::vector<uint8_t> buffer(inBufferSize * 2);
781 auto u16s = buffer.data() + inBufferSize;
782 if(!ReadAccessor(mJoints0, binFile, u16s))
784 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
787 auto floats = reinterpret_cast<float*>(buffer.data());
788 auto end = u16s + inBufferSize;
791 auto value = *reinterpret_cast<uint16_t*>(u16s);
792 *floats = static_cast<float>(value);
794 u16s += sizeof(uint16_t);
797 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
801 DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
802 mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
803 "Joints buffer length not a multiple of element size");
804 const auto bufferSize = mJoints0.mBlob.GetBufferSize();
805 std::vector<uint8_t> buffer(bufferSize);
806 if(!ReadAccessor(mJoints0, binFile, buffer.data()))
808 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
811 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
814 DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
815 mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
816 "Weights buffer length not a multiple of element size");
817 const auto bufferSize = mWeights0.mBlob.GetBufferSize();
818 std::vector<uint8_t> buffer(bufferSize);
819 if(!ReadAccessor(mWeights0, binFile, buffer.data()))
821 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
824 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
827 // Calculate the Blob for the blend shapes.
828 Blob blendShapesBlob;
829 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
830 blendShapesBlob.mLength = 0u;
832 for(const auto& blendShape : mBlendShapes)
834 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
838 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
839 blendShapesBlob.mLength += i->mBlob.mLength;
846 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
848 // Calculate the size of one buffer inside the texture.
849 raw.mBlendShapeBufferOffset = numberOfVertices;
851 bool calculateGltf2BlendShapes = false;
852 uint32_t textureWidth = 0u;
853 uint32_t textureHeight = 0u;
855 if(!mBlendShapeHeader.IsDefined())
857 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
858 calculateGltf2BlendShapes = true;
863 ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
864 textureWidth = header[0u];
865 textureHeight = header[1u];
868 const uint32_t numberOfBlendShapes = mBlendShapes.size();
869 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
871 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
872 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
874 if(calculateGltf2BlendShapes)
876 CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
880 Blob unnormalizeFactorBlob;
881 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
883 if(blendShapesBlob.IsDefined())
885 if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
887 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
891 // Read the unnormalize factors.
892 if(unnormalizeFactorBlob.IsDefined())
894 ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
897 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
903 MeshGeometry MeshDefinition::Load(RawData&& raw) const
905 MeshGeometry meshGeometry;
906 meshGeometry.geometry = Geometry::New();
907 meshGeometry.geometry.SetType(mPrimitiveType);
909 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
911 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
912 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
916 if(!raw.mIndices.empty())
918 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
921 for(auto& a : raw.mAttribs)
923 a.AttachBuffer(meshGeometry.geometry);
928 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
929 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
931 meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
932 raw.mBlendShapeData.GetPixelFormat(),
933 raw.mBlendShapeData.GetWidth(),
934 raw.mBlendShapeData.GetHeight());
935 meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
942 } // namespace Loader
943 } // namespace Scene3D