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/integration-api/debug.h>
26 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
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)
75 if(!source.seekg(descriptor.mOffset, std::istream::beg))
80 if(descriptor.IsConsecutive())
82 return !!source.read(reinterpret_cast<char*>(target), static_cast<std::streamsize>(static_cast<size_t>(descriptor.mLength)));
86 if(descriptor.mStride > descriptor.mElementSizeHint)
88 const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
89 uint32_t readSize = 0;
90 uint32_t totalSize = (descriptor.mLength / descriptor.mElementSizeHint) * descriptor.mStride;
91 while(readSize < totalSize &&
92 source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
93 source.seekg(diff, std::istream::cur))
95 readSize += descriptor.mStride;
96 target += descriptor.mElementSizeHint;
98 return readSize == totalSize;
105 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
107 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
108 for(uint32_t index = 0u; index < count; ++index)
110 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
111 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
115 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
117 bool success = false;
119 if(accessor.mBlob.IsDefined())
121 success = ReadBlob(accessor.mBlob, source, target);
130 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
131 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
133 if(!indices.IsDefined() || !values.IsDefined())
138 const auto indicesBufferSize = indices.GetBufferSize();
139 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
140 success = ReadBlob(indices, source, indicesBuffer.data());
146 const auto valuesBufferSize = values.GetBufferSize();
147 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
148 success = ReadBlob(values, source, valuesBuffer.data());
154 switch(indices.mElementSizeHint)
158 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
163 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
168 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
172 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
180 void ReadJointAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
182 constexpr auto sizeofBlobUnit = sizeof(T) * 4;
184 DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
185 accessor.mBlob.mStride >= sizeofBlobUnit) &&
186 "Joints buffer length not a multiple of element size");
187 const auto inBufferSize = accessor.mBlob.GetBufferSize();
188 const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
190 std::vector<uint8_t> buffer(outBufferSize);
191 auto inBuffer = buffer.data() + outBufferSize - inBufferSize;
192 if(!ReadAccessor(accessor, source, inBuffer))
194 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
197 if constexpr(sizeofBlobUnit != sizeof(Vector4))
199 auto floats = reinterpret_cast<float*>(buffer.data());
200 const auto end = inBuffer + inBufferSize;
201 while(inBuffer != end)
203 const auto value = *reinterpret_cast<T*>(inBuffer);
204 *floats = static_cast<float>(value);
206 inBuffer += sizeof(T);
210 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
213 void GenerateNormals(MeshDefinition::RawData& raw)
215 auto& attribs = raw.mAttribs;
216 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
217 IndexProvider getIndex(raw.mIndices.data());
219 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
221 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
223 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
224 auto normals = reinterpret_cast<Vector3*>(buffer.data());
226 for(uint32_t i = 0; i < numIndices; i += 3)
228 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
229 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
231 Vector3 a = pos[1] - pos[0];
232 Vector3 b = pos[2] - pos[0];
234 Vector3 normal(a.Cross(b));
235 normals[indices[0]] += normal;
236 normals[indices[1]] += normal;
237 normals[indices[2]] += normal;
240 auto iEnd = normals + attribs[0].mNumElements;
241 while(normals != iEnd)
243 normals->Normalize();
247 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
250 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
252 auto& attribs = raw.mAttribs;
253 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
254 IndexProvider getIndex(raw.mIndices.data());
256 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
258 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
259 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
261 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
262 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
264 for(uint32_t i = 0; i < numIndices; i += 3)
266 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
267 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
268 Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
270 float x0 = pos[1].x - pos[0].x;
271 float y0 = pos[1].y - pos[0].y;
272 float z0 = pos[1].z - pos[0].z;
274 float x1 = pos[2].x - pos[0].x;
275 float y1 = pos[2].y - pos[0].y;
276 float z1 = pos[2].z - pos[0].z;
278 float s0 = uv[1].x - uv[0].x;
279 float t0 = uv[1].y - uv[0].y;
281 float s1 = uv[2].x - uv[0].x;
282 float t1 = uv[2].y - uv[0].y;
284 float r = 1.f / (s0 * t1 - t0 * s1);
285 Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
286 tangents[indices[0]] += tangent;
287 tangents[indices[1]] += tangent;
288 tangents[indices[2]] += tangent;
291 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
292 auto iEnd = normals + attribs[1].mNumElements;
293 while(normals != iEnd)
295 *tangents -= *normals * normals->Dot(*tangents);
296 tangents->Normalize();
301 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
304 void GenerateTangents(MeshDefinition::RawData& raw)
306 auto& attribs = raw.mAttribs;
307 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
309 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
311 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
312 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
314 auto iEnd = normals + attribs[1].mNumElements;
315 while(normals != iEnd)
317 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
319 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
320 *tangents -= *normals * normals->Dot(*tangents);
321 tangents->Normalize();
326 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
329 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
331 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
333 // Calculate the dimensions of the texture.
334 // The total size of the texture is the length of the blend shapes blob.
339 if(0u == totalTextureSize)
345 const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
346 const uint32_t powWidth = pow2 >> 1u;
347 const uint32_t powHeight = pow2 - powWidth;
349 textureWidth = 1u << powWidth;
350 textureHeight = 1u << powHeight;
353 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
355 uint32_t geometryBufferIndex = 0u;
356 float maxDistance = 0.f;
357 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
358 for(const auto& blendShape : blendShapes)
360 if(blendShape.deltas.IsDefined())
362 DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
363 blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
364 "Blend Shape position buffer length not a multiple of element size");
366 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
367 std::vector<uint8_t> buffer(bufferSize);
368 if(ReadAccessor(blendShape.deltas, buffers[blendShape.deltas.mBufferIdx].GetBufferStream(), buffer.data()))
370 blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
371 // Calculate the difference with the original mesh.
372 // Find the max distance to normalize the deltas.
373 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
375 for(uint32_t index = 0u; index < numberOfVertices; ++index)
377 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
378 delta = deltasBuffer[index];
380 maxDistance = std::max(maxDistance, delta.LengthSquared());
385 if(blendShape.normals.IsDefined())
387 DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
388 blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
389 "Blend Shape normals buffer length not a multiple of element size");
391 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
392 std::vector<uint8_t> buffer(bufferSize);
393 if(ReadAccessor(blendShape.normals, buffers[blendShape.normals.mBufferIdx].GetBufferStream(), buffer.data()))
395 blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
397 // Calculate the difference with the original mesh, and translate to make all values positive.
398 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
400 for(uint32_t index = 0u; index < numberOfVertices; ++index)
402 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
403 delta = deltasBuffer[index];
416 if(blendShape.tangents.IsDefined())
418 DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
419 blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
420 "Blend Shape tangents buffer length not a multiple of element size");
422 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
423 std::vector<uint8_t> buffer(bufferSize);
424 if(ReadAccessor(blendShape.tangents, buffers[blendShape.tangents.mBufferIdx].GetBufferStream(), buffer.data()))
426 blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
428 // Calculate the difference with the original mesh, and translate to make all values positive.
429 const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
431 for(uint32_t index = 0u; index < numberOfVertices; ++index)
433 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
434 delta = deltasBuffer[index];
448 geometryBufferIndex = 0u;
449 for(const auto& blendShape : blendShapes)
451 // Normalize all the deltas and translate to a possitive value.
452 // Deltas are going to be passed to the shader in a color texture
453 // whose values that are less than zero are clamped.
454 if(blendShape.deltas.IsDefined())
456 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
458 for(uint32_t index = 0u; index < numberOfVertices; ++index)
460 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
461 delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
462 delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
463 delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
466 // Calculate and store the unnormalize factor.
467 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
470 if(blendShape.normals.IsDefined())
472 geometryBufferIndex += numberOfVertices;
475 if(blendShape.tangents.IsDefined())
477 geometryBufferIndex += numberOfVertices;
482 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
484 auto& stream = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
485 availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
491 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
498 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
499 : mIndices(std::move(indices)),
500 mValues(std::move(values)),
505 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
506 const MeshDefinition::SparseBlob& sparse,
509 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
510 mBufferIdx(bufferIndex)
514 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&& blob,
515 MeshDefinition::SparseBlob&& sparse,
517 : mBlob{std::move(blob)},
518 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
519 mBufferIdx(bufferIndex)
523 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
525 min.assign(numComponents, MAXFLOAT);
526 max.assign(numComponents, -MAXFLOAT);
527 for(uint32_t i = 0; i < count; ++i)
529 for(uint32_t j = 0; j < numComponents; ++j)
531 min[j] = std::min(min[j], *values);
532 max[j] = std::max(max[j], *values);
538 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
540 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
541 const auto numComponents = std::max(min.size(), max.size());
543 using ClampFn = void (*)(const float*, const float*, uint32_t, float&);
544 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); })
545 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { value = std::max(min[i], value); }
546 : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) { value = std::min(std::max(min[i], value), max[i]); }));
553 auto end = values + count * numComponents;
556 auto nextElement = values + numComponents;
558 while(values != nextElement)
560 clampFn(min.data(), max.data(), i, *values);
567 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)
571 mElementSizeHint(elementSizeHint),
577 uint32_t MeshDefinition::Blob::GetBufferSize() const
582 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
584 ComputeMinMax(mMin, mMax, numComponents, count, values);
587 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
589 ApplyMinMax(mMin, mMax, count, values);
592 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
594 Property::Map attribMap;
595 attribMap[mName] = mType;
596 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
597 attribBuffer.SetData(mData.data(), mNumElements);
599 g.AddVertexBuffer(attribBuffer);
602 bool MeshDefinition::IsQuad() const
604 return CaseInsensitiveStringCompare(QUAD, mUri);
607 bool MeshDefinition::IsSkinned() const
609 return mJoints0.IsDefined() && mWeights0.IsDefined();
612 bool MeshDefinition::HasBlendShapes() const
614 return !mBlendShapes.empty();
617 void MeshDefinition::RequestNormals()
619 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
622 void MeshDefinition::RequestTangents()
624 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
627 MeshDefinition::RawData
628 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
636 std::string meshPath;
637 meshPath = modelsPath + mUri;
638 std::fstream fileStream;
641 fileStream.open(meshPath, std::ios::in | std::ios::binary);
642 if(!fileStream.is_open())
644 DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
648 if(mIndices.IsDefined())
650 if(MaskMatch(mFlags, U32_INDICES))
652 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
653 mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
654 "Index buffer length not a multiple of element size");
655 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
656 raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
659 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
660 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
662 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
665 auto u16s = raw.mIndices.data();
666 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
667 auto end = u32s + indexCount;
670 *u16s = static_cast<uint16_t>(*u32s);
675 raw.mIndices.resize(indexCount);
677 else if(MaskMatch(mFlags, U8_INDICES))
679 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
680 mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
681 "Index buffer length not a multiple of element size");
682 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
683 raw.mIndices.resize(indexCount); // NOTE: we need space for uint32_ts initially.
686 auto u8s = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
687 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
688 if(!ReadAccessor(mIndices, stream, u8s))
690 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
693 auto u16s = raw.mIndices.data();
694 auto end = u8s + indexCount;
697 *u16s = static_cast<uint16_t>(*u8s);
704 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
705 mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
706 "Index buffer length not a multiple of element size");
707 raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
710 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
711 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
713 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
718 std::vector<Vector3> positions;
719 if(mPositions.IsDefined())
721 DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
722 mPositions.mBlob.mStride >= sizeof(Vector3)) &&
723 "Position buffer length not a multiple of element size");
724 const auto bufferSize = mPositions.mBlob.GetBufferSize();
725 std::vector<uint8_t> buffer(bufferSize);
728 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
729 if(!ReadAccessor(mPositions, stream, buffer.data()))
731 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
734 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
735 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
737 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
741 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
746 positions.resize(numVector3);
747 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
750 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
753 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
754 auto hasNormals = mNormals.IsDefined();
757 DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
758 mNormals.mBlob.mStride >= sizeof(Vector3)) &&
759 "Normal buffer length not a multiple of element size");
760 const auto bufferSize = mNormals.mBlob.GetBufferSize();
761 std::vector<uint8_t> buffer(bufferSize);
764 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
765 if(!ReadAccessor(mNormals, stream, buffer.data()))
767 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
770 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
772 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
774 else if(mNormals.mBlob.mLength != 0 && isTriangles)
776 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
777 GenerateNormals(raw);
781 const auto hasUvs = mTexCoords.IsDefined();
784 DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
785 mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
786 "Normal buffer length not a multiple of element size");
787 const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
788 std::vector<uint8_t> buffer(bufferSize);
791 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
792 if(!ReadAccessor(mTexCoords, stream, buffer.data()))
794 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
797 const auto uvCount = bufferSize / sizeof(Vector2);
798 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
800 auto uv = reinterpret_cast<Vector2*>(buffer.data());
801 auto uvEnd = uv + uvCount;
804 uv->y = 1.0f - uv->y;
809 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector2)), reinterpret_cast<float*>(buffer.data()));
811 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
814 if(mTangents.IsDefined())
816 uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
817 DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
818 mTangents.mBlob.mStride >= propertySize) &&
819 "Tangents buffer length not a multiple of element size");
820 const auto bufferSize = mTangents.mBlob.GetBufferSize();
821 std::vector<uint8_t> buffer(bufferSize);
824 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
825 if(!ReadAccessor(mTangents, stream, buffer.data()))
827 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
829 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
831 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
833 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
835 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
836 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
839 if(mColors.IsDefined())
841 uint32_t propertySize = mColors.mBlob.mElementSizeHint;
842 Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
843 if(propertyType != Property::NONE)
845 DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
846 mColors.mBlob.mStride >= propertySize) &&
847 "Colors buffer length not a multiple of element size");
848 const auto bufferSize = mColors.mBlob.GetBufferSize();
849 std::vector<uint8_t> buffer(bufferSize);
852 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
853 if(!ReadAccessor(mColors, stream, buffer.data()))
855 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
857 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
859 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
865 std::string pathJoint;
866 auto& streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
867 if(MaskMatch(mFlags, U16_JOINT_IDS))
869 ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
871 else if(MaskMatch(mFlags, U8_JOINT_IDS))
873 ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
877 ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
880 DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
881 mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
882 "Weights buffer length not a multiple of element size");
883 const auto bufferSize = mWeights0.mBlob.GetBufferSize();
884 std::vector<uint8_t> buffer(bufferSize);
886 std::string pathWeight;
887 auto& streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
888 if(!ReadAccessor(mWeights0, streamWeight, buffer.data()))
890 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << pathWeight << "'.";
893 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
896 // Calculate the Blob for the blend shapes.
897 Blob blendShapesBlob;
898 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
899 blendShapesBlob.mLength = 0u;
901 for(const auto& blendShape : mBlendShapes)
903 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
907 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
908 blendShapesBlob.mLength += i->mBlob.mLength;
915 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
917 // Calculate the size of one buffer inside the texture.
918 raw.mBlendShapeBufferOffset = numberOfVertices;
920 bool calculateGltf2BlendShapes = false;
921 uint32_t textureWidth = 0u;
922 uint32_t textureHeight = 0u;
924 if(!mBlendShapeHeader.IsDefined())
926 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
927 calculateGltf2BlendShapes = true;
932 ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
933 textureWidth = header[0u];
934 textureHeight = header[1u];
937 const uint32_t numberOfBlendShapes = mBlendShapes.size();
938 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
940 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
941 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
943 if(calculateGltf2BlendShapes)
945 CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
949 Blob unnormalizeFactorBlob;
950 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
952 if(blendShapesBlob.IsDefined())
954 if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
956 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
960 // Read the unnormalize factors.
961 if(unnormalizeFactorBlob.IsDefined())
963 ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
966 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
972 MeshGeometry MeshDefinition::Load(RawData&& raw) const
974 MeshGeometry meshGeometry;
975 meshGeometry.geometry = Geometry::New();
976 meshGeometry.geometry.SetType(mPrimitiveType);
978 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
980 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
981 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
985 if(!raw.mIndices.empty())
987 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
990 for(auto& a : raw.mAttribs)
992 a.AttachBuffer(meshGeometry.geometry);
997 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
998 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1000 meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1001 raw.mBlendShapeData.GetPixelFormat(),
1002 raw.mBlendShapeData.GetWidth(),
1003 raw.mBlendShapeData.GetHeight());
1004 meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1008 return meshGeometry;
1011 } // namespace Loader
1012 } // namespace Scene3D