2 * Copyright (c) 2021 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-scene-loader/public-api/mesh-definition.h"
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
32 using Uint16Vector4 = uint16_t[4];
37 IndexProvider(const uint16_t* indices)
38 : mData(reinterpret_cast<uintptr_t>(indices)),
39 mFunc(indices ? IncrementPointer : Increment)
49 static uint16_t Increment(uintptr_t& data)
51 return static_cast<uint16_t>(data++);
54 static uint16_t IncrementPointer(uintptr_t& data)
56 auto iPtr = reinterpret_cast<const uint16_t*>(data);
58 data = reinterpret_cast<uintptr_t>(++iPtr);
63 uint16_t (*mFunc)(uintptr_t&);
66 const std::string QUAD("quad");
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)
72 if(!source.seekg(descriptor.mOffset, std::istream::beg))
77 if(descriptor.IsConsecutive())
79 return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
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))
90 readSize += descriptor.mStride;
91 target += descriptor.mElementSizeHint;
93 return readSize == descriptor.mLength;
98 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
100 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
101 for(uint32_t index = 0u; index < count; ++index)
103 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
104 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
108 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
110 bool success = false;
112 if(accessor.mBlob.IsDefined())
114 success = ReadBlob(accessor.mBlob, source, target);
123 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
124 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
126 if(!indices.IsDefined() || !values.IsDefined())
131 const auto indicesBufferSize = indices.GetBufferSize();
132 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
133 success = ReadBlob(indices, source, indicesBuffer.data());
139 const auto valuesBufferSize = values.GetBufferSize();
140 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
141 success = ReadBlob(values, source, valuesBuffer.data());
147 switch(indices.mElementSizeHint)
151 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
156 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
161 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
165 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
172 void GenerateNormals(MeshDefinition::RawData& raw)
174 auto& attribs = raw.mAttribs;
175 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
176 IndexProvider getIndex(raw.mIndices.data());
178 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
180 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
182 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
183 auto normals = reinterpret_cast<Vector3*>(buffer.data());
185 for(uint32_t i = 0; i < numIndices; i += 3)
187 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
188 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
190 Vector3 a = pos[1] - pos[0];
191 Vector3 b = pos[2] - pos[0];
193 Vector3 normal(a.Cross(b));
194 normals[indices[0]] += normal;
195 normals[indices[1]] += normal;
196 normals[indices[2]] += normal;
199 auto iEnd = normals + attribs[0].mNumElements;
200 while(normals != iEnd)
202 normals->Normalize();
206 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
209 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
211 auto& attribs = raw.mAttribs;
212 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
213 IndexProvider getIndex(raw.mIndices.data());
215 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
217 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
218 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
220 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
221 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
223 for(uint32_t i = 0; i < numIndices; i += 3)
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]]};
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;
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;
237 float s0 = uv[1].x - uv[0].x;
238 float t0 = uv[1].y - uv[0].y;
240 float s1 = uv[2].x - uv[0].x;
241 float t1 = uv[2].y - uv[0].y;
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;
250 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
251 auto iEnd = normals + attribs[1].mNumElements;
252 while(normals != iEnd)
254 *tangents -= *normals * normals->Dot(*tangents);
255 tangents->Normalize();
260 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
263 void GenerateTangents(MeshDefinition::RawData& raw)
265 auto& attribs = raw.mAttribs;
266 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
268 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
270 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
271 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
273 auto iEnd = normals + attribs[1].mNumElements;
274 while(normals != iEnd)
276 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
278 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
279 *tangents -= *normals * normals->Dot(*tangents);
280 tangents->Normalize();
285 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
288 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
290 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
292 // Calculate the dimensions of the texture.
293 // The total size of the texture is the length of the blend shapes blob.
298 if(0u == totalTextureSize)
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;
308 textureWidth = 1u << powWidth;
309 textureHeight = 1u << powHeight;
312 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
314 uint32_t geometryBufferIndex = 0u;
315 float maxDistance = 0.f;
316 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
317 for(const auto& blendShape : blendShapes)
319 if(blendShape.deltas.IsDefined())
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");
325 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
326 std::vector<uint8_t> buffer(bufferSize);
327 if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
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());
334 for(uint32_t index = 0u; index < numberOfVertices; ++index)
336 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
337 delta = deltasBuffer[index];
339 maxDistance = std::max(maxDistance, delta.LengthSquared());
344 if(blendShape.normals.IsDefined())
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");
350 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
351 std::vector<uint8_t> buffer(bufferSize);
352 if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
354 blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
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());
359 for(uint32_t index = 0u; index < numberOfVertices; ++index)
361 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
362 delta = deltasBuffer[index];
375 if(blendShape.tangents.IsDefined())
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");
381 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
382 std::vector<uint8_t> buffer(bufferSize);
383 if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
385 blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
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());
390 for(uint32_t index = 0u; index < numberOfVertices; ++index)
392 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
393 delta = deltasBuffer[index];
407 geometryBufferIndex = 0u;
408 for(const auto& blendShape : blendShapes)
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())
415 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
417 for(uint32_t index = 0u; index < numberOfVertices; ++index)
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);
425 // Calculate and store the unnormalize factor.
426 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
429 if(blendShape.normals.IsDefined())
431 geometryBufferIndex += numberOfVertices;
434 if(blendShape.tangents.IsDefined())
436 geometryBufferIndex += numberOfVertices;
443 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
450 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
451 const MeshDefinition::SparseBlob& sparse)
453 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
457 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
459 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
460 const auto numComponents = std::max(min.size(), max.size());
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);
466 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
467 value = std::max(min[i], value);
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]);
478 auto end = values + count * numComponents;
481 auto nextElement = values + numComponents;
483 while(values != nextElement)
485 clampFn(min.data(), max.data(), i, *values);
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)
496 mElementSizeHint(elementSizeHint),
502 uint32_t MeshDefinition::Blob::GetBufferSize() const
504 return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
507 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
509 ApplyMinMax(mMin, mMax, count, values);
512 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
514 Property::Map attribMap;
515 attribMap[mName] = mType;
516 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
517 attribBuffer.SetData(mData.data(), mNumElements);
519 g.AddVertexBuffer(attribBuffer);
522 bool MeshDefinition::IsQuad() const
524 return CaseInsensitiveStringCompare(QUAD, mUri);
527 bool MeshDefinition::IsSkinned() const
529 return mJoints0.IsDefined() && mWeights0.IsDefined();
532 bool MeshDefinition::HasBlendShapes() const
534 return !mBlendShapes.empty();
537 void MeshDefinition::RequestNormals()
539 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
542 void MeshDefinition::RequestTangents()
544 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
547 MeshDefinition::RawData
548 MeshDefinition::LoadRaw(const std::string& modelsPath) const
556 const std::string meshPath = modelsPath + mUri;
557 std::ifstream binFile(meshPath, std::ios::binary);
560 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
563 if(mIndices.IsDefined())
565 if(MaskMatch(mFlags, U32_INDICES))
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())))
574 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
577 auto u16s = raw.mIndices.data();
578 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
579 auto end = u32s + indexCount;
582 *u16s = static_cast<uint16_t>(*u32s);
587 raw.mIndices.resize(indexCount);
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())))
597 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
602 std::vector<Vector3> positions;
603 if(mPositions.IsDefined())
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()))
612 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
615 uint32_t numVector3 = bufferSize / sizeof(Vector3);
616 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
620 positions.resize(numVector3);
621 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
624 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
627 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
628 auto hasNormals = mNormals.IsDefined();
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()))
638 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
641 mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
643 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
645 else if(mNormals.mBlob.mLength != 0 && isTriangles)
647 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
648 GenerateNormals(raw);
652 const auto hasUvs = mTexCoords.IsDefined();
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()))
662 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
665 const auto uvCount = bufferSize / sizeof(Vector2);
666 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
668 auto uv = reinterpret_cast<Vector2*>(buffer.data());
669 auto uvEnd = uv + uvCount;
672 uv->y = 1.0f - uv->y;
677 mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
679 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
682 if(mTangents.IsDefined())
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()))
691 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
694 mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
696 raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
698 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
700 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
701 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
706 if(MaskMatch(mFlags, U16_JOINT_IDS))
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))
716 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
719 auto floats = reinterpret_cast<float*>(buffer.data());
720 auto end = u16s + inBufferSize;
723 auto value = *reinterpret_cast<uint16_t*>(u16s);
724 *floats = static_cast<float>(value);
726 u16s += sizeof(uint16_t);
729 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
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()))
740 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
743 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
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()))
753 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
756 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
759 // Calculate the Blob for the blend shapes.
760 Blob blendShapesBlob;
761 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
762 blendShapesBlob.mLength = 0u;
764 for(const auto& blendShape : mBlendShapes)
766 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
770 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
771 blendShapesBlob.mLength += i->mBlob.mLength;
778 const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
780 // Calculate the size of one buffer inside the texture.
781 raw.mBlendShapeBufferOffset = numberOfVertices;
783 bool calculateGltf2BlendShapes = false;
784 uint32_t textureWidth = 0u;
785 uint32_t textureHeight = 0u;
787 if(!mBlendShapeHeader.IsDefined())
789 CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
790 calculateGltf2BlendShapes = true;
795 ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
796 textureWidth = header[0u];
797 textureHeight = header[1u];
800 const uint32_t numberOfBlendShapes = mBlendShapes.size();
801 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
803 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
804 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
806 if(calculateGltf2BlendShapes)
808 CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
812 Blob unnormalizeFactorBlob;
813 unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
815 if(blendShapesBlob.IsDefined())
817 if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
819 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
823 // Read the unnormalize factors.
824 if(unnormalizeFactorBlob.IsDefined())
826 ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
829 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
835 MeshGeometry MeshDefinition::Load(RawData&& raw) const
837 MeshGeometry meshGeometry;
838 meshGeometry.geometry = Geometry::New();
839 meshGeometry.geometry.SetType(mPrimitiveType);
841 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
843 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
844 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
848 if(!raw.mIndices.empty())
850 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
853 for(auto& a : raw.mAttribs)
855 a.AttachBuffer(meshGeometry.geometry);
860 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
861 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
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);
874 } // namespace SceneLoader