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 DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint);
86 const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
87 uint32_t readSize = 0;
88 while(readSize < descriptor.mLength &&
89 source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
90 source.seekg(diff, std::istream::cur))
92 readSize += descriptor.mStride;
93 target += descriptor.mElementSizeHint;
95 return readSize == descriptor.mLength;
100 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
102 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
103 for(uint32_t index = 0u; index < count; ++index)
105 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
106 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
110 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
112 bool success = false;
114 if(accessor.mBlob.IsDefined())
116 success = ReadBlob(accessor.mBlob, source, target);
125 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
126 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
128 if(!indices.IsDefined() || !values.IsDefined())
133 const auto indicesBufferSize = indices.GetBufferSize();
134 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
135 success = ReadBlob(indices, source, indicesBuffer.data());
141 const auto valuesBufferSize = values.GetBufferSize();
142 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
143 success = ReadBlob(values, source, valuesBuffer.data());
149 switch(indices.mElementSizeHint)
153 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
158 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
163 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
167 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
174 void GenerateNormals(MeshDefinition::RawData& raw)
176 auto& attribs = raw.mAttribs;
177 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
178 IndexProvider getIndex(raw.mIndices.data());
180 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
182 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
184 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
185 auto normals = reinterpret_cast<Vector3*>(buffer.data());
187 for(uint32_t i = 0; i < numIndices; i += 3)
189 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
190 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
192 Vector3 a = pos[1] - pos[0];
193 Vector3 b = pos[2] - pos[0];
195 Vector3 normal(a.Cross(b));
196 normals[indices[0]] += normal;
197 normals[indices[1]] += normal;
198 normals[indices[2]] += normal;
201 auto iEnd = normals + attribs[0].mNumElements;
202 while(normals != iEnd)
204 normals->Normalize();
208 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
211 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
213 auto& attribs = raw.mAttribs;
214 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
215 IndexProvider getIndex(raw.mIndices.data());
217 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
219 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
220 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
222 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
223 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
225 for(uint32_t i = 0; i < numIndices; i += 3)
227 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
228 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
229 Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
231 float x0 = pos[1].x - pos[0].x;
232 float y0 = pos[1].y - pos[0].y;
233 float z0 = pos[1].z - pos[0].z;
235 float x1 = pos[2].x - pos[0].x;
236 float y1 = pos[2].y - pos[0].y;
237 float z1 = pos[2].z - pos[0].z;
239 float s0 = uv[1].x - uv[0].x;
240 float t0 = uv[1].y - uv[0].y;
242 float s1 = uv[2].x - uv[0].x;
243 float t1 = uv[2].y - uv[0].y;
245 float r = 1.f / (s0 * t1 - t0 * s1);
246 Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
247 tangents[indices[0]] += tangent;
248 tangents[indices[1]] += tangent;
249 tangents[indices[2]] += tangent;
252 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
253 auto iEnd = normals + attribs[1].mNumElements;
254 while(normals != iEnd)
256 *tangents -= *normals * normals->Dot(*tangents);
257 tangents->Normalize();
262 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
265 void GenerateTangents(MeshDefinition::RawData& raw)
267 auto& attribs = raw.mAttribs;
268 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
270 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
272 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
273 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
275 auto iEnd = normals + attribs[1].mNumElements;
276 while(normals != iEnd)
278 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
280 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
281 *tangents -= *normals * normals->Dot(*tangents);
282 tangents->Normalize();
287 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
290 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
292 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
294 // Calculate the dimensions of the texture.
295 // The total size of the texture is the length of the blend shapes blob.
300 if(0u == totalTextureSize)
306 const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
307 const uint32_t powWidth = pow2 >> 1u;
308 const uint32_t powHeight = pow2 - powWidth;
310 textureWidth = 1u << powWidth;
311 textureHeight = 1u << powHeight;
314 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
316 uint32_t geometryBufferIndex = 0u;
317 float maxDistance = 0.f;
318 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
319 for(const auto& blendShape : blendShapes)
321 if(blendShape.deltas.IsDefined())
323 DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
324 blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
325 "Blend Shape position buffer length not a multiple of element size");
327 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
328 std::vector<uint8_t> buffer(bufferSize);
329 if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
331 blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
332 // Calculate the difference with the original mesh.
333 // Find the max distance to normalize the deltas.
334 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
336 for(uint32_t index = 0u; index < numberOfVertices; ++index)
338 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
339 delta = deltasBuffer[index];
341 maxDistance = std::max(maxDistance, delta.LengthSquared());
346 if(blendShape.normals.IsDefined())
348 DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
349 blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
350 "Blend Shape normals buffer length not a multiple of element size");
352 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
353 std::vector<uint8_t> buffer(bufferSize);
354 if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
356 blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
358 // Calculate the difference with the original mesh, and translate to make all values positive.
359 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
361 for(uint32_t index = 0u; index < numberOfVertices; ++index)
363 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
364 delta = deltasBuffer[index];
377 if(blendShape.tangents.IsDefined())
379 DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
380 blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
381 "Blend Shape tangents buffer length not a multiple of element size");
383 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
384 std::vector<uint8_t> buffer(bufferSize);
385 if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
387 blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
389 // Calculate the difference with the original mesh, and translate to make all values positive.
390 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
392 for(uint32_t index = 0u; index < numberOfVertices; ++index)
394 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
395 delta = deltasBuffer[index];
409 geometryBufferIndex = 0u;
410 for(const auto& blendShape : blendShapes)
412 // Normalize all the deltas and translate to a possitive value.
413 // Deltas are going to be passed to the shader in a color texture
414 // whose values that are less than zero are clamped.
415 if(blendShape.deltas.IsDefined())
417 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
419 for(uint32_t index = 0u; index < numberOfVertices; ++index)
421 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
422 delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
423 delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
424 delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
427 // Calculate and store the unnormalize factor.
428 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
431 if(blendShape.normals.IsDefined())
433 geometryBufferIndex += numberOfVertices;
436 if(blendShape.tangents.IsDefined())
438 geometryBufferIndex += numberOfVertices;
445 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
452 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
453 const MeshDefinition::SparseBlob& sparse)
455 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
459 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
461 min.assign(numComponents, MAXFLOAT);
462 max.assign(numComponents, -MAXFLOAT);
463 for(uint32_t i = 0; i < count; ++i)
465 for(uint32_t j = 0; j < numComponents; ++j)
467 min[j] = std::min(min[j], *values);
468 max[j] = std::max(max[j], *values);
474 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
476 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
477 const auto numComponents = std::max(min.size(), max.size());
479 using ClampFn = void (*)(const float*, const float*, uint32_t, float&);
480 ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
481 value = std::min(max[i], value);
483 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
484 value = std::max(min[i], value);
486 : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) {
487 value = std::min(std::max(min[i], value), max[i]);
495 auto end = values + count * numComponents;
498 auto nextElement = values + numComponents;
500 while(values != nextElement)
502 clampFn(min.data(), max.data(), i, *values);
509 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)
513 mElementSizeHint(elementSizeHint),
519 uint32_t MeshDefinition::Blob::GetBufferSize() const
521 return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
524 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
526 ComputeMinMax(mMin, mMax, numComponents, count, values);
529 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
531 ApplyMinMax(mMin, mMax, count, values);
534 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
536 Property::Map attribMap;
537 attribMap[mName] = mType;
538 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
539 attribBuffer.SetData(mData.data(), mNumElements);
541 g.AddVertexBuffer(attribBuffer);
544 bool MeshDefinition::IsQuad() const
546 return CaseInsensitiveStringCompare(QUAD, mUri);
549 bool MeshDefinition::IsSkinned() const
551 return mJoints0.IsDefined() && mWeights0.IsDefined();
554 bool MeshDefinition::HasBlendShapes() const
556 return !mBlendShapes.empty();
559 void MeshDefinition::RequestNormals()
561 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
564 void MeshDefinition::RequestTangents()
566 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
569 MeshDefinition::RawData
570 MeshDefinition::LoadRaw(const std::string& modelsPath)
578 const std::string meshPath = modelsPath + mUri;
579 std::ifstream binFile(meshPath, std::ios::binary);
582 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
585 if(mIndices.IsDefined())
587 if(MaskMatch(mFlags, U32_INDICES))
589 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
590 mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
591 "Index buffer length not a multiple of element size");
592 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
593 raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
594 if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
596 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
599 auto u16s = raw.mIndices.data();
600 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
601 auto end = u32s + indexCount;
604 *u16s = static_cast<uint16_t>(*u32s);
609 raw.mIndices.resize(indexCount);
613 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
614 mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
615 "Index buffer length not a multiple of element size");
616 raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
617 if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
619 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
624 std::vector<Vector3> positions;
625 if(mPositions.IsDefined())
627 DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
628 mPositions.mBlob.mStride >= sizeof(Vector3)) &&
629 "Position buffer length not a multiple of element size");
630 const auto bufferSize = mPositions.mBlob.GetBufferSize();
631 std::vector<uint8_t> buffer(bufferSize);
632 if(!ReadAccessor(mPositions, binFile, buffer.data()))
634 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
637 uint32_t numVector3 = bufferSize / sizeof(Vector3);
638 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
640 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
644 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
649 positions.resize(numVector3);
650 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
653 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
656 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
657 auto hasNormals = mNormals.IsDefined();
660 DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
661 mNormals.mBlob.mStride >= sizeof(Vector3)) &&
662 "Normal buffer length not a multiple of element size");
663 const auto bufferSize = mNormals.mBlob.GetBufferSize();
664 std::vector<uint8_t> buffer(bufferSize);
665 if(!ReadAccessor(mNormals, binFile, buffer.data()))
667 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
670 mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
672 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
674 else if(mNormals.mBlob.mLength != 0 && isTriangles)
676 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
677 GenerateNormals(raw);
681 const auto hasUvs = mTexCoords.IsDefined();
684 DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
685 mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
686 "Normal buffer length not a multiple of element size");
687 const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
688 std::vector<uint8_t> buffer(bufferSize);
689 if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
691 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
694 const auto uvCount = bufferSize / sizeof(Vector2);
695 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
697 auto uv = reinterpret_cast<Vector2*>(buffer.data());
698 auto uvEnd = uv + uvCount;
701 uv->y = 1.0f - uv->y;
706 mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
708 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
711 if(mTangents.IsDefined())
713 uint32_t propertySize = (mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3);
714 DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
715 mTangents.mBlob.mStride >= propertySize) &&
716 "Tangents buffer length not a multiple of element size");
717 const auto bufferSize = mTangents.mBlob.GetBufferSize();
718 std::vector<uint8_t> buffer(bufferSize);
719 if(!ReadAccessor(mTangents, binFile, buffer.data()))
721 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
723 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
725 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
727 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
729 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
730 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
733 if(mColors.IsDefined())
735 uint32_t propertySize = mColors.mBlob.mElementSizeHint;
736 Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
737 if(propertyType != Property::NONE)
739 DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
740 mColors.mBlob.mStride >= propertySize) &&
741 "Colors buffer length not a multiple of element size");
742 const auto bufferSize = mColors.mBlob.GetBufferSize();
743 std::vector<uint8_t> buffer(bufferSize);
744 if(!ReadAccessor(mColors, binFile, buffer.data()))
746 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << meshPath << "'.";
748 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
750 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
756 if(MaskMatch(mFlags, U16_JOINT_IDS))
758 DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
759 mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
760 "Joints buffer length not a multiple of element size");
761 const auto inBufferSize = mJoints0.mBlob.GetBufferSize();
762 std::vector<uint8_t> buffer(inBufferSize * 2);
763 auto u16s = buffer.data() + inBufferSize;
764 if(!ReadAccessor(mJoints0, binFile, u16s))
766 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
769 auto floats = reinterpret_cast<float*>(buffer.data());
770 auto end = u16s + inBufferSize;
773 auto value = *reinterpret_cast<uint16_t*>(u16s);
774 *floats = static_cast<float>(value);
776 u16s += sizeof(uint16_t);
779 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
783 DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
784 mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
785 "Joints buffer length not a multiple of element size");
786 const auto bufferSize = mJoints0.mBlob.GetBufferSize();
787 std::vector<uint8_t> buffer(bufferSize);
788 if(!ReadAccessor(mJoints0, binFile, buffer.data()))
790 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
793 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
796 DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
797 mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
798 "Weights buffer length not a multiple of element size");
799 const auto bufferSize = mWeights0.mBlob.GetBufferSize();
800 std::vector<uint8_t> buffer(bufferSize);
801 if(!ReadAccessor(mWeights0, binFile, buffer.data()))
803 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
806 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
809 // Calculate the Blob for the blend shapes.
810 Blob blendShapesBlob;
811 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
812 blendShapesBlob.mLength = 0u;
814 for(const auto& blendShape : mBlendShapes)
816 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
820 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
821 blendShapesBlob.mLength += i->mBlob.mLength;
828 const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
830 // Calculate the size of one buffer inside the texture.
831 raw.mBlendShapeBufferOffset = numberOfVertices;
833 bool calculateGltf2BlendShapes = false;
834 uint32_t textureWidth = 0u;
835 uint32_t textureHeight = 0u;
837 if(!mBlendShapeHeader.IsDefined())
839 CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
840 calculateGltf2BlendShapes = true;
845 ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
846 textureWidth = header[0u];
847 textureHeight = header[1u];
850 const uint32_t numberOfBlendShapes = mBlendShapes.size();
851 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
853 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
854 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
856 if(calculateGltf2BlendShapes)
858 CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
862 Blob unnormalizeFactorBlob;
863 unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
865 if(blendShapesBlob.IsDefined())
867 if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
869 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
873 // Read the unnormalize factors.
874 if(unnormalizeFactorBlob.IsDefined())
876 ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
879 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
885 MeshGeometry MeshDefinition::Load(RawData&& raw) const
887 MeshGeometry meshGeometry;
888 meshGeometry.geometry = Geometry::New();
889 meshGeometry.geometry.SetType(mPrimitiveType);
891 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
893 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
894 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
898 if(!raw.mIndices.empty())
900 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
903 for(auto& a : raw.mAttribs)
905 a.AttachBuffer(meshGeometry.geometry);
910 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
911 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
913 meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
914 raw.mBlendShapeData.GetPixelFormat(),
915 raw.mBlendShapeData.GetWidth(),
916 raw.mBlendShapeData.GetHeight());
917 meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
924 } // namespace Loader
925 } // namespace Scene3D