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), 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)
545 { value = std::min(max[i], value); })
546 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value)
547 { value = std::max(min[i], value); }
548 : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value)
549 { value = std::min(std::max(min[i], value), max[i]); }));
556 auto end = values + count * numComponents;
559 auto nextElement = values + numComponents;
561 while(values != nextElement)
563 clampFn(min.data(), max.data(), i, *values);
570 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)
574 mElementSizeHint(elementSizeHint),
580 uint32_t MeshDefinition::Blob::GetBufferSize() const
585 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
587 ComputeMinMax(mMin, mMax, numComponents, count, values);
590 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
592 ApplyMinMax(mMin, mMax, count, values);
595 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
597 Property::Map attribMap;
598 attribMap[mName] = mType;
599 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
600 attribBuffer.SetData(mData.data(), mNumElements);
602 g.AddVertexBuffer(attribBuffer);
605 bool MeshDefinition::IsQuad() const
607 return CaseInsensitiveStringCompare(QUAD, mUri);
610 bool MeshDefinition::IsSkinned() const
612 return mJoints0.IsDefined() && mWeights0.IsDefined();
615 bool MeshDefinition::HasBlendShapes() const
617 return !mBlendShapes.empty();
620 void MeshDefinition::RequestNormals()
622 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
625 void MeshDefinition::RequestTangents()
627 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
630 MeshDefinition::RawData
631 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
639 std::string meshPath;
640 meshPath = modelsPath + mUri;
641 std::fstream fileStream;
644 fileStream.open(meshPath, std::ios::in | std::ios::binary);
645 if(!fileStream.is_open())
647 DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
651 if(mIndices.IsDefined())
653 if(MaskMatch(mFlags, U32_INDICES))
655 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
656 mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
657 "Index buffer length not a multiple of element size");
658 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
659 raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
662 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
663 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
665 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
668 auto u16s = raw.mIndices.data();
669 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
670 auto end = u32s + indexCount;
673 *u16s = static_cast<uint16_t>(*u32s);
678 raw.mIndices.resize(indexCount);
680 else if(MaskMatch(mFlags, U8_INDICES))
682 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
683 mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
684 "Index buffer length not a multiple of element size");
685 const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
686 raw.mIndices.resize(indexCount); // NOTE: we need space for uint32_ts initially.
689 auto u8s = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
690 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
691 if(!ReadAccessor(mIndices, stream, u8s))
693 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
696 auto u16s = raw.mIndices.data();
697 auto end = u8s + indexCount;
700 *u16s = static_cast<uint16_t>(*u8s);
707 DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
708 mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
709 "Index buffer length not a multiple of element size");
710 raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
714 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
715 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
717 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
722 std::vector<Vector3> positions;
723 if(mPositions.IsDefined())
725 DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
726 mPositions.mBlob.mStride >= sizeof(Vector3)) &&
727 "Position buffer length not a multiple of element size");
728 const auto bufferSize = mPositions.mBlob.GetBufferSize();
729 std::vector<uint8_t> buffer(bufferSize);
732 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
733 if(!ReadAccessor(mPositions, stream, buffer.data()))
735 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
738 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
739 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
741 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
745 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
750 positions.resize(numVector3);
751 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
754 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
757 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
758 auto hasNormals = mNormals.IsDefined();
761 DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
762 mNormals.mBlob.mStride >= sizeof(Vector3)) &&
763 "Normal buffer length not a multiple of element size");
764 const auto bufferSize = mNormals.mBlob.GetBufferSize();
765 std::vector<uint8_t> buffer(bufferSize);
768 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
769 if(!ReadAccessor(mNormals, stream, buffer.data()))
771 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
774 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
776 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
778 else if(mNormals.mBlob.mLength != 0 && isTriangles)
780 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
781 GenerateNormals(raw);
785 const auto hasUvs = mTexCoords.IsDefined();
788 DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
789 mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
790 "Normal buffer length not a multiple of element size");
791 const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
792 std::vector<uint8_t> buffer(bufferSize);
795 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
796 if(!ReadAccessor(mTexCoords, stream, buffer.data()))
798 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
801 const auto uvCount = bufferSize / sizeof(Vector2);
802 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
804 auto uv = reinterpret_cast<Vector2*>(buffer.data());
805 auto uvEnd = uv + uvCount;
808 uv->y = 1.0f - uv->y;
813 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector2)), reinterpret_cast<float*>(buffer.data()));
815 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
818 if(mTangents.IsDefined())
820 uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
821 DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
822 mTangents.mBlob.mStride >= propertySize) &&
823 "Tangents buffer length not a multiple of element size");
824 const auto bufferSize = mTangents.mBlob.GetBufferSize();
825 std::vector<uint8_t> buffer(bufferSize);
828 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
829 if(!ReadAccessor(mTangents, stream, buffer.data()))
831 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
833 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
835 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
837 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
839 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
840 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
843 if(mColors.IsDefined())
845 uint32_t propertySize = mColors.mBlob.mElementSizeHint;
846 Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
847 if(propertyType != Property::NONE)
849 DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
850 mColors.mBlob.mStride >= propertySize) &&
851 "Colors buffer length not a multiple of element size");
852 const auto bufferSize = mColors.mBlob.GetBufferSize();
853 std::vector<uint8_t> buffer(bufferSize);
856 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
857 if(!ReadAccessor(mColors, stream, buffer.data()))
859 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
861 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
863 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
869 std::string pathJoint;
870 auto& streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
871 if(MaskMatch(mFlags, U16_JOINT_IDS))
873 ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
875 else if(MaskMatch(mFlags, U8_JOINT_IDS))
877 ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
881 ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
884 DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
885 mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
886 "Weights buffer length not a multiple of element size");
887 const auto bufferSize = mWeights0.mBlob.GetBufferSize();
888 std::vector<uint8_t> buffer(bufferSize);
890 std::string pathWeight;
891 auto& streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
892 if(!ReadAccessor(mWeights0, streamWeight, buffer.data()))
894 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << pathWeight << "'.";
897 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
900 // Calculate the Blob for the blend shapes.
901 Blob blendShapesBlob;
902 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
903 blendShapesBlob.mLength = 0u;
905 for(const auto& blendShape : mBlendShapes)
907 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
911 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
912 blendShapesBlob.mLength += i->mBlob.mLength;
919 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
921 // Calculate the size of one buffer inside the texture.
922 raw.mBlendShapeBufferOffset = numberOfVertices;
924 bool calculateGltf2BlendShapes = false;
925 uint32_t textureWidth = 0u;
926 uint32_t textureHeight = 0u;
928 if(!mBlendShapeHeader.IsDefined())
930 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
931 calculateGltf2BlendShapes = true;
936 ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
937 textureWidth = header[0u];
938 textureHeight = header[1u];
941 const uint32_t numberOfBlendShapes = mBlendShapes.size();
942 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
944 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
945 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
947 if(calculateGltf2BlendShapes)
949 CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
953 Blob unnormalizeFactorBlob;
954 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
956 if(blendShapesBlob.IsDefined())
958 if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
960 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
964 // Read the unnormalize factors.
965 if(unnormalizeFactorBlob.IsDefined())
967 ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
970 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
976 MeshGeometry MeshDefinition::Load(RawData&& raw) const
978 MeshGeometry meshGeometry;
979 meshGeometry.geometry = Geometry::New();
980 meshGeometry.geometry.SetType(mPrimitiveType);
982 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
984 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
985 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
989 if(!raw.mIndices.empty())
991 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
994 for(auto& a : raw.mAttribs)
996 a.AttachBuffer(meshGeometry.geometry);
1001 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
1002 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1004 meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1005 raw.mBlendShapeData.GetPixelFormat(),
1006 raw.mBlendShapeData.GetWidth(),
1007 raw.mBlendShapeData.GetHeight());
1008 meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1012 return meshGeometry;
1015 } // namespace Loader
1016 } // namespace Scene3D