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/gltf2-loader.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/images/image-operations.h>
24 #include <dali/public-api/math/quaternion.h>
25 #include <dali/devel-api/threading/mutex.h>
29 #include <dali-scene3d/internal/loader/gltf2-asset.h>
30 #include <dali-scene3d/public-api/loader/load-result.h>
31 #include <dali-scene3d/public-api/loader/resource-bundle.h>
32 #include <dali-scene3d/public-api/loader/scene-definition.h>
33 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
34 #include <dali-scene3d/public-api/loader/utils.h>
47 Dali::Mutex gInitializeMutex;
48 Dali::Mutex gReadMutex;
50 const std::string POSITION_PROPERTY("position");
51 const std::string ORIENTATION_PROPERTY("orientation");
52 const std::string SCALE_PROPERTY("scale");
53 const std::string BLEND_SHAPE_WEIGHTS_UNIFORM("uBlendShapeWeight");
54 const std::string MRENDERER_MODEL_IDENTIFICATION("M-Renderer");
55 const std::string ROOT_NODE_NAME("RootNode");
56 const Vector3 SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
58 const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
64 Geometry::TRIANGLE_STRIP,
65 Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
67 struct AttributeMapping
69 gt::Attribute::Type mType;
70 MeshDefinition::Accessor MeshDefinition::*mAccessor;
71 uint16_t mElementSizeRequired;
72 } ATTRIBUTE_MAPPINGS[]{
73 {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
74 {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
75 {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
76 {gt::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
77 {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
78 {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
81 std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
83 auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
85 for(auto& animation : results)
87 for(auto& channel : animation.mChannels)
89 channel.mSampler.UpdateVector(animation.mSamplers);
96 void ApplyAccessorMinMax(const gt::Accessor& acc, float* values)
98 DALI_ASSERT_ALWAYS(acc.mMax.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
99 DALI_ASSERT_ALWAYS(acc.mMin.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
100 MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
103 const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
104 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
105 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
107 const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
108 .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
109 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
110 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
111 .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
112 .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
114 const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
115 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
116 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
118 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
119 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
120 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
121 .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
123 const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
124 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
125 .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
126 .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
128 const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
129 .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
130 gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
131 >::Accessor::mBufferView))
132 .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
133 js::Read::Number<uint32_t>,
134 >::Accessor::mByteOffset))
135 .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
136 js::Read::Enum<gt::Component::Type>,
137 >::Accessor::mComponentType))
138 .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
139 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
140 .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
141 .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
142 .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
143 .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
144 .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
146 const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
147 .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
148 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
149 .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
150 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
152 const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
153 .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
154 .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
155 .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
156 .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
158 const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
159 .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
160 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
162 const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
163 .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
164 .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
165 .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
166 .Register(*js::MakeProperty("strength", js::Read::Number<float>, >::TextureInfo::mStrength)));
168 const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
169 .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
170 .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
171 .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
172 .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
173 .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
175 const auto MATERIAL_SPECULAR_READER = std::move(js::Reader<gt::MaterialSpecular>()
176 .Register(*js::MakeProperty("specularFactor", js::Read::Number<float>, >::MaterialSpecular::mSpecularFactor))
177 .Register(*js::MakeProperty("specularTexture", js::ObjectReader<gt::TextureInfo>::Read, >::MaterialSpecular::mSpecularTexture))
178 .Register(*js::MakeProperty("specularColorFactor", gt::ReadDaliVector<Vector3>, >::MaterialSpecular::mSpecularColorFactor))
179 .Register(*js::MakeProperty("specularColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::MaterialSpecular::mSpecularColorTexture)));
181 const auto MATERIAL_IOR_READER = std::move(js::Reader<gt::MaterialIor>()
182 .Register(*js::MakeProperty("ior", js::Read::Number<float>, >::MaterialIor::mIor)));
184 const auto MATERIAL_EXTENSION_READER = std::move(js::Reader<gt::MaterialExtensions>()
185 .Register(*js::MakeProperty("KHR_materials_ior", js::ObjectReader<gt::MaterialIor>::Read, >::MaterialExtensions::mMaterialIor))
186 .Register(*js::MakeProperty("KHR_materials_specular", js::ObjectReader<gt::MaterialSpecular>::Read, >::MaterialExtensions::mMaterialSpecular)));
188 const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
189 .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
190 .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
191 .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
192 .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
193 .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
194 .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
195 .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
196 .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff))
197 .Register(*js::MakeProperty("doubleSided", js::Read::Boolean, >::Material::mDoubleSided))
198 .Register(*js::MakeProperty("extensions", js::ObjectReader<gt::MaterialExtensions>::Read, >::Material::mMaterialExtensions)));
200 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
202 auto& jo = js::Cast<json_object_s>(j);
203 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
208 auto jstr = *i->name;
209 result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
215 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
217 auto& jo = js::Cast<json_array_s>(j);
218 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
220 result.reserve(jo.length);
225 result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
232 const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
233 .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
234 .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
235 .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
236 .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
237 .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
239 const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
240 .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
241 .Register(*js::MakeProperty("primitives",
242 js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
243 >::Mesh::mPrimitives))
244 .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
246 const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
247 .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
248 .Register(*js::MakeProperty("inverseBindMatrices",
249 gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
250 >::Skin::mInverseBindMatrices))
251 .Register(*js::MakeProperty("skeleton",
252 gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
253 >::Skin::mSkeleton))
254 .Register(*js::MakeProperty("joints",
255 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
256 >::Skin::mJoints)));
258 const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
259 .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
260 .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
261 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
262 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
264 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
265 .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
266 .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
267 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
268 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
270 const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
271 .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
272 .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
273 .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
274 .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
276 const auto NODE_READER = std::move(js::Reader<gt::Node>()
277 .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
278 .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
279 .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
280 .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
281 .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
282 .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
283 .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
284 .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
285 .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
287 const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
288 .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
289 .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
290 .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
292 const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
293 .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
294 .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
296 const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
297 .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
298 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
300 const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
301 .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
302 .Register(*js::MakeProperty("samplers",
303 js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
304 >::Animation::mSamplers))
305 .Register(*js::MakeProperty("channels",
306 js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
307 >::Animation::mChannels)));
309 const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
310 .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
311 .Register(*js::MakeProperty("nodes",
312 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
313 >::Scene::mNodes)));
315 const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
316 .Register(*js::MakeProperty("buffers",
317 js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
318 >::Document::mBuffers))
319 .Register(*js::MakeProperty("bufferViews",
320 js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
321 >::Document::mBufferViews))
322 .Register(*js::MakeProperty("accessors",
323 js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
324 >::Document::mAccessors))
325 .Register(*js::MakeProperty("images",
326 js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
327 >::Document::mImages))
328 .Register(*js::MakeProperty("samplers",
329 js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
330 >::Document::mSamplers))
331 .Register(*js::MakeProperty("textures",
332 js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
333 >::Document::mTextures))
334 .Register(*js::MakeProperty("materials",
335 js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
336 >::Document::mMaterials))
337 .Register(*js::MakeProperty("meshes",
338 js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
339 >::Document::mMeshes))
340 .Register(*js::MakeProperty("skins",
341 js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
342 >::Document::mSkins))
343 .Register(*js::MakeProperty("cameras",
344 js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
345 >::Document::mCameras))
346 .Register(*js::MakeProperty("nodes",
347 js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
348 >::Document::mNodes))
349 .Register(*js::MakeProperty("animations",
351 >::Document::mAnimations))
352 .Register(*js::MakeProperty("scenes",
353 js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
354 >::Document::mScenes))
355 .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
363 bool operator<(const NodeMapping& mapping, Index gltfIdx)
365 return mapping.gltfIdx < gltfIdx;
368 class NodeIndexMapper
371 NodeIndexMapper() = default;
372 NodeIndexMapper(const NodeIndexMapper&) = delete;
373 NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
375 ///@brief Registers a mapping of the @a gltfIdx of a node to its @a runtimeIdx .
376 ///@note If the indices are the same, the registration is omitted, in order to
377 /// save growing a vector.
378 void RegisterMapping(Index gltfIdx, Index runtimeIdx)
380 if(gltfIdx != runtimeIdx)
382 auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
383 DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
384 mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
388 ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
389 Index GetRuntimeId(Index gltfIdx) const
391 auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
392 return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
396 std::vector<NodeMapping> mNodes;
399 struct ConversionContext
404 Index mDefaultMaterial;
406 std::vector<Index> mMeshIds;
407 NodeIndexMapper mNodeIndices;
410 SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
414 case gt::Wrap::REPEAT:
415 return SamplerFlags::WRAP_REPEAT;
416 case gt::Wrap::CLAMP_TO_EDGE:
417 return SamplerFlags::WRAP_CLAMP;
418 case gt::Wrap::MIRRORED_REPEAT:
419 return SamplerFlags::WRAP_MIRROR;
421 throw std::runtime_error("Invalid wrap type.");
425 SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
429 return ((s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2)) |
430 ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) |
431 (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) |
432 (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
436 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
437 // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
438 // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
439 // properties, if not in some extension -, we will simply assume linear filtering.
440 return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
441 (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
445 TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm, const ImageMetadata& metaData = ImageMetadata())
447 return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
450 void ConvertMaterial(const gt::Material& material, const std::unordered_map<std::string, ImageMetadata>& imageMetaData, decltype(ResourceBundle::mMaterials)& outMaterials)
452 auto getTextureMetaData = [](const std::unordered_map<std::string, ImageMetadata>& metaData, const gt::TextureInfo& info) {
453 if(auto search = metaData.find(info.mTexture->mSource->mUri.data()); search != metaData.end())
455 return search->second;
459 return ImageMetadata();
463 MaterialDefinition matDef;
465 auto& pbr = material.mPbrMetallicRoughness;
466 if(material.mAlphaMode == gt::AlphaMode::BLEND)
468 matDef.mIsOpaque = false;
469 matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
471 else if(material.mAlphaMode == gt::AlphaMode::MASK)
473 matDef.mIsMask = true;
474 matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, material.mAlphaCutoff)));
477 matDef.mBaseColorFactor = pbr.mBaseColorFactor;
479 matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!material.mNormalTexture + !!material.mOcclusionTexture + !!material.mEmissiveTexture);
480 if(pbr.mBaseColorTexture)
482 const auto semantic = MaterialDefinition::ALBEDO;
483 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture, getTextureMetaData(imageMetaData, pbr.mBaseColorTexture))});
484 // TODO: and there had better be one
485 matDef.mFlags |= semantic;
489 matDef.mNeedAlbedoTexture = false;
492 matDef.mMetallic = pbr.mMetallicFactor;
493 matDef.mRoughness = pbr.mRoughnessFactor;
495 if(pbr.mMetallicRoughnessTexture)
497 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
498 MaterialDefinition::GLTF_CHANNELS;
499 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture, getTextureMetaData(imageMetaData, pbr.mMetallicRoughnessTexture))});
500 // TODO: and there had better be one
501 matDef.mFlags |= semantic;
505 matDef.mNeedMetallicRoughnessTexture = false;
508 matDef.mNormalScale = material.mNormalTexture.mScale;
509 if(material.mNormalTexture)
511 const auto semantic = MaterialDefinition::NORMAL;
512 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mNormalTexture, getTextureMetaData(imageMetaData, material.mNormalTexture))});
513 // TODO: and there had better be one
514 matDef.mFlags |= semantic;
518 matDef.mNeedNormalTexture = false;
521 if(material.mOcclusionTexture)
523 const auto semantic = MaterialDefinition::OCCLUSION;
524 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mOcclusionTexture, getTextureMetaData(imageMetaData, material.mOcclusionTexture))});
525 // TODO: and there had better be one
526 matDef.mFlags |= semantic;
527 matDef.mOcclusionStrength = material.mOcclusionTexture.mStrength;
530 if(material.mEmissiveTexture)
532 const auto semantic = MaterialDefinition::EMISSIVE;
533 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mEmissiveTexture, getTextureMetaData(imageMetaData, material.mEmissiveTexture))});
534 // TODO: and there had better be one
535 matDef.mFlags |= semantic;
536 matDef.mEmissiveFactor = material.mEmissiveFactor;
539 if(material.mMaterialExtensions.mMaterialIor.mIor < MAXFLOAT)
541 float ior = material.mMaterialExtensions.mMaterialIor.mIor;
542 matDef.mDielectricSpecular = powf((ior - 1.0f) / (ior + 1.0f), 2.0f);
544 matDef.mSpecularFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularFactor;
545 matDef.mSpecularColorFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularColorFactor;
547 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)
549 const auto semantic = MaterialDefinition::SPECULAR;
550 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture))});
551 matDef.mFlags |= semantic;
554 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)
556 const auto semantic = MaterialDefinition::SPECULAR_COLOR;
557 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture))});
558 matDef.mFlags |= semantic;
561 matDef.mDoubleSided = material.mDoubleSided;
563 outMaterials.emplace_back(std::move(matDef), TextureSet());
566 void ConvertMaterials(const gt::Document& doc, ConversionContext& context)
568 auto& imageMetaData = context.mOutput.mSceneMetadata.mImageMetadata;
570 auto& outMaterials = context.mOutput.mResources.mMaterials;
571 outMaterials.reserve(doc.mMaterials.size());
573 for(auto& m : doc.mMaterials)
575 ConvertMaterial(m, imageMetaData, outMaterials);
579 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
581 DALI_ASSERT_ALWAYS((acc.mBufferView &&
582 (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
583 (acc.mSparse && !acc.mBufferView));
585 DALI_ASSERT_ALWAYS(!acc.mSparse ||
586 ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
587 (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
589 MeshDefinition::SparseBlob sparseBlob;
592 const gt::Accessor::Sparse& sparse = *acc.mSparse;
593 const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
594 const gt::BufferViewClient& values = sparse.mValues;
596 MeshDefinition::Blob indicesBlob(
597 indices.mBufferView->mByteOffset + indices.mByteOffset,
598 sparse.mCount * indices.GetBytesPerComponent(),
599 static_cast<uint16_t>(indices.mBufferView->mByteStride),
600 static_cast<uint16_t>(indices.GetBytesPerComponent()),
603 MeshDefinition::Blob valuesBlob(
604 values.mBufferView->mByteOffset + values.mByteOffset,
605 sparse.mCount * acc.GetElementSizeBytes(),
606 static_cast<uint16_t>(values.mBufferView->mByteStride),
607 static_cast<uint16_t>(acc.GetElementSizeBytes()),
611 sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
614 uint32_t bufferViewOffset = 0u;
615 uint32_t bufferViewStride = 0u;
618 bufferViewOffset = acc.mBufferView->mByteOffset;
619 bufferViewStride = acc.mBufferView->mByteStride;
622 return MeshDefinition::Accessor{
623 std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
624 acc.GetBytesLength(),
625 static_cast<uint16_t>(bufferViewStride),
626 static_cast<uint16_t>(acc.GetElementSizeBytes()),
629 std::move(sparseBlob)};
632 void ConvertMeshes(const gt::Document& doc, ConversionContext& context)
634 uint32_t meshCount = 0;
635 context.mMeshIds.reserve(doc.mMeshes.size());
636 for(auto& mesh : doc.mMeshes)
638 context.mMeshIds.push_back(meshCount);
639 meshCount += mesh.mPrimitives.size();
642 auto& outMeshes = context.mOutput.mResources.mMeshes;
643 outMeshes.reserve(meshCount);
644 for(auto& mesh : doc.mMeshes)
646 for(auto& primitive : mesh.mPrimitives)
648 MeshDefinition meshDefinition;
650 auto& attribs = primitive.mAttributes;
651 meshDefinition.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
652 meshDefinition.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[primitive.mMode];
654 auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
655 meshDefinition.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
656 // glTF2 support vector4 tangent for mesh.
657 // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
658 meshDefinition.mTangentType = Property::VECTOR4;
660 const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
661 for(auto& am : ATTRIBUTE_MAPPINGS)
663 auto iFind = attribs.find(am.mType);
664 if(iFind != attribs.end())
666 DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDefinition.mUri) == 0);
667 auto& accessor = meshDefinition.*(am.mAccessor);
668 accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
670 if(iFind->first == gt::Attribute::JOINTS_0)
672 meshDefinition.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
673 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
676 else if(needNormalsTangents)
680 case gt::Attribute::NORMAL:
681 meshDefinition.RequestNormals();
684 case gt::Attribute::TANGENT:
685 meshDefinition.RequestTangents();
694 if(primitive.mIndices)
696 meshDefinition.mIndices = ConvertMeshPrimitiveAccessor(*primitive.mIndices);
697 meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
698 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U32_INDICES) || primitive.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
701 if(!primitive.mTargets.empty())
703 meshDefinition.mBlendShapes.reserve(primitive.mTargets.size());
704 meshDefinition.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
705 for(const auto& target : primitive.mTargets)
707 MeshDefinition::BlendShape blendShape;
709 auto endIt = target.end();
710 auto it = target.find(gt::Attribute::POSITION);
713 blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
715 it = target.find(gt::Attribute::NORMAL);
718 blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
720 it = target.find(gt::Attribute::TANGENT);
723 blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
726 if(!mesh.mWeights.empty())
728 blendShape.weight = mesh.mWeights[meshDefinition.mBlendShapes.size()];
731 meshDefinition.mBlendShapes.push_back(std::move(blendShape));
735 outMeshes.push_back({std::move(meshDefinition), MeshGeometry{}});
740 ModelRenderable* MakeModelRenderable(const gt::Mesh::Primitive& prim, ConversionContext& context)
742 auto modelRenderable = new ModelRenderable();
744 modelRenderable->mShaderIdx = 0; // TODO: further thought
746 auto materialIdx = prim.mMaterial.GetIndex();
747 if(INVALID_INDEX == materialIdx)
749 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
750 if(INVALID_INDEX == context.mDefaultMaterial)
752 auto& outMaterials = context.mOutput.mResources.mMaterials;
753 context.mDefaultMaterial = outMaterials.size();
755 ConvertMaterial(gt::Material{}, context.mOutput.mSceneMetadata.mImageMetadata, outMaterials);
758 materialIdx = context.mDefaultMaterial;
761 modelRenderable->mMaterialIdx = materialIdx;
763 return modelRenderable;
766 void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
768 camParams.isPerspective = camera.mType.compare("perspective") == 0;
769 if(camParams.isPerspective)
771 auto& perspective = camera.mPerspective;
772 camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
773 camParams.zNear = perspective.mZNear;
774 camParams.zFar = perspective.mZFar;
775 // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
779 auto& ortho = camera.mOrthographic;
780 camParams.orthographicSize = ortho.mYMag * .5f;
781 camParams.aspectRatio = ortho.mXMag / ortho.mYMag;
782 camParams.zNear = ortho.mZNear;
783 camParams.zFar = ortho.mZFar;
787 void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& context, bool isMRendererModel)
789 auto& output = context.mOutput;
790 auto& scene = output.mScene;
791 auto& resources = output.mResources;
793 const auto idx = scene.GetNodeCount();
794 auto weakNode = scene.AddNode([&]() {
795 std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
797 nodeDef->mParentIdx = parentIdx;
798 nodeDef->mName = node.mName;
799 if(nodeDef->mName.empty())
801 // TODO: Production quality generation of unique names.
802 nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
805 if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
807 nodeDef->mPosition = node.mTranslation;
808 nodeDef->mOrientation = node.mRotation;
809 nodeDef->mScale = node.mScale;
811 if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
813 nodeDef->mScale *= 0.01f;
821 ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
824 context.mNodeIndices.RegisterMapping(gltfIdx, idx);
826 Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
829 auto& mesh = *node.mMesh;
830 uint32_t primitiveCount = mesh.mPrimitives.size();
831 auto meshIdx = context.mMeshIds[node.mMesh.GetIndex()];
832 weakNode->mRenderables.reserve(primitiveCount);
833 for(uint32_t i = 0; i < primitiveCount; ++i)
835 std::unique_ptr<NodeDefinition::Renderable> renderable;
836 auto modelRenderable = MakeModelRenderable(mesh.mPrimitives[i], context);
837 modelRenderable->mMeshIdx = meshIdx + i;
839 DALI_ASSERT_DEBUG(resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == INVALID_INDEX ||
840 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == skeletonIdx);
841 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx = skeletonIdx;
843 renderable.reset(modelRenderable);
844 weakNode->mRenderables.push_back(std::move(renderable));
850 CameraParameters camParams;
851 ConvertCamera(*node.mCamera, camParams);
853 camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
854 output.mCameraParameters.push_back(camParams);
857 for(auto& n : node.mChildren)
859 ConvertNode(*n, n.GetIndex(), idx, context, isMRendererModel);
863 void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& context, bool isMRendererModel)
865 auto& outScene = context.mOutput.mScene;
866 Index rootIdx = outScene.GetNodeCount();
867 switch(scene.mNodes.size())
873 ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, context, isMRendererModel);
874 outScene.AddRootNode(rootIdx);
879 std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
880 sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
882 outScene.AddNode(std::move(sceneRoot));
883 outScene.AddRootNode(rootIdx);
885 for(auto& n : scene.mNodes)
887 ConvertNode(*n, n.GetIndex(), rootIdx, context, isMRendererModel);
894 void ConvertNodes(const gt::Document& doc, ConversionContext& context, bool isMRendererModel)
896 if(!doc.mScenes.empty())
898 uint32_t rootSceneIndex = 0u;
901 rootSceneIndex = doc.mScene.GetIndex();
903 ConvertSceneNodes(doc.mScenes[rootSceneIndex], context, isMRendererModel);
905 for(uint32_t i = 0, i1 = rootSceneIndex; i < i1; ++i)
907 ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
910 for(uint32_t i = rootSceneIndex + 1; i < doc.mScenes.size(); ++i)
912 ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
918 void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
920 std::ifstream animationBinaryFile(path, std::ifstream::binary);
922 if(!animationBinaryFile.is_open())
924 throw std::runtime_error("Failed to load " + path);
927 animationBinaryFile.seekg(offset);
928 animationBinaryFile.read(reinterpret_cast<char*>(dataBuffer.Begin()), size);
929 animationBinaryFile.close();
933 float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
935 inputDataBuffer.Resize(input.mCount);
936 outputDataBuffer.Resize(output.mCount);
938 const uint32_t inputDataBufferSize = input.GetBytesLength();
939 const uint32_t outputDataBufferSize = output.GetBytesLength();
941 LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
942 LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
943 ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
945 return inputDataBuffer[input.mCount - 1u];
949 float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
951 const gltf2::Accessor& input = *channel.mSampler->mInput;
952 const gltf2::Accessor& output = *channel.mSampler->mOutput;
954 Vector<float> inputDataBuffer;
955 Vector<T> outputDataBuffer;
957 const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
959 for(uint32_t i = 0; i < input.mCount; ++i)
961 keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
967 float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, Index nodeIndex, uint32_t& propertyIndex, std::vector<Dali::Scene3D::Loader::AnimatedProperty>& properties)
969 const gltf2::Accessor& input = *channel.mSampler->mInput;
970 const gltf2::Accessor& output = *channel.mSampler->mOutput;
972 Vector<float> inputDataBuffer;
973 Vector<float> outputDataBuffer;
975 const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
977 char weightNameBuffer[32];
978 auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
979 char* const pWeightName = weightNameBuffer + prefixSize;
980 const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
981 for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
983 AnimatedProperty& animatedProperty = properties[propertyIndex++];
985 animatedProperty.mNodeIndex = nodeIndex;
986 snprintf(pWeightName, remainingSize, "%d]", weightIndex);
987 animatedProperty.mPropertyName = std::string(weightNameBuffer);
989 animatedProperty.mKeyFrames = KeyFrames::New();
990 for(uint32_t i = 0; i < input.mCount; ++i)
992 animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
995 animatedProperty.mTimePeriod = {0.f, duration};
1001 void ConvertAnimations(const gt::Document& doc, ConversionContext& context)
1003 auto& output = context.mOutput;
1005 output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
1007 for(const auto& animation : doc.mAnimations)
1009 AnimationDefinition animationDef;
1011 if(!animation.mName.empty())
1013 animationDef.mName = animation.mName;
1016 uint32_t numberOfProperties = 0u;
1017 for(const auto& channel : animation.mChannels)
1019 if(channel.mTarget.mPath == gt::Animation::Channel::Target::WEIGHTS)
1021 numberOfProperties += channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount;
1025 numberOfProperties++;
1028 animationDef.mProperties.resize(numberOfProperties);
1030 Index propertyIndex = 0u;
1031 for(const auto& channel : animation.mChannels)
1033 Index nodeIndex = context.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
1034 float duration = 0.f;
1036 switch(channel.mTarget.mPath)
1038 case gt::Animation::Channel::Target::TRANSLATION:
1040 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1042 animatedProperty.mNodeIndex = nodeIndex;
1043 animatedProperty.mPropertyName = POSITION_PROPERTY;
1045 animatedProperty.mKeyFrames = KeyFrames::New();
1046 duration = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1048 animatedProperty.mTimePeriod = {0.f, duration};
1051 case gt::Animation::Channel::Target::ROTATION:
1053 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1055 animatedProperty.mNodeIndex = nodeIndex;
1056 animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1058 animatedProperty.mKeyFrames = KeyFrames::New();
1059 duration = LoadKeyFrames<Quaternion>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1061 animatedProperty.mTimePeriod = {0.f, duration};
1064 case gt::Animation::Channel::Target::SCALE:
1066 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1068 animatedProperty.mNodeIndex = nodeIndex;
1069 animatedProperty.mPropertyName = SCALE_PROPERTY;
1071 animatedProperty.mKeyFrames = KeyFrames::New();
1072 duration = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1074 animatedProperty.mTimePeriod = {0.f, duration};
1077 case gt::Animation::Channel::Target::WEIGHTS:
1079 duration = LoadBlendShapeKeyFrames(context.mPath, channel, nodeIndex, propertyIndex, animationDef.mProperties);
1085 // nothing to animate.
1090 animationDef.mDuration = std::max(duration, animationDef.mDuration);
1095 output.mAnimationDefinitions.push_back(std::move(animationDef));
1099 void ProcessSkins(const gt::Document& doc, ConversionContext& context)
1101 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1102 // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1103 // otherwise we'll set identity matrices for inverse bind pose.
1104 struct IInverseBindMatrixProvider
1106 virtual ~IInverseBindMatrixProvider()
1109 virtual void Provide(Matrix& ibm) = 0;
1112 struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1114 std::ifstream mStream;
1115 const uint32_t mElementSizeBytes;
1117 InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
1118 : mStream(path + std::string(accessor.mBufferView->mBuffer->mUri), std::ios::binary),
1119 mElementSizeBytes(accessor.GetElementSizeBytes())
1121 DALI_ASSERT_ALWAYS(mStream);
1122 DALI_ASSERT_DEBUG(accessor.mType == gt::AccessorType::MAT4 && accessor.mComponentType == gt::Component::FLOAT);
1124 mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset);
1127 virtual void Provide(Matrix& ibm) override
1129 DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), mElementSizeBytes));
1133 struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1135 virtual void Provide(Matrix& ibm) override
1137 ibm = Matrix::IDENTITY;
1141 auto& resources = context.mOutput.mResources;
1142 resources.mSkeletons.reserve(doc.mSkins.size());
1144 for(auto& s : doc.mSkins)
1146 std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1147 if(s.mInverseBindMatrices)
1149 ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, context.mPath));
1153 ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1156 SkeletonDefinition skeleton;
1157 if(s.mSkeleton.GetIndex() != INVALID_INDEX)
1159 skeleton.mRootNodeIdx = context.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
1162 skeleton.mJoints.resize(s.mJoints.size());
1163 auto iJoint = skeleton.mJoints.begin();
1164 for(auto& j : s.mJoints)
1166 iJoint->mNodeIdx = context.mNodeIndices.GetRuntimeId(j.GetIndex());
1168 ibmProvider->Provide(iJoint->mInverseBindMatrix);
1173 resources.mSkeletons.push_back(std::move(skeleton));
1177 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
1179 uint32_t nodeCount = scene.GetNodeCount();
1180 for(uint32_t i = 0; i < nodeCount; ++i)
1182 auto nodeDef = scene.GetNode(i);
1183 for(auto& renderable : nodeDef->mRenderables)
1185 if(shaderFactory.ProduceShader(*renderable) == INVALID_INDEX)
1187 DALI_LOG_ERROR("Fail to produce shader\n");
1193 void SetObjectReaders()
1195 js::SetObjectReader(BUFFER_READER);
1196 js::SetObjectReader(BUFFER_VIEW_READER);
1197 js::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1198 js::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1199 js::SetObjectReader(ACCESSOR_SPARSE_READER);
1200 js::SetObjectReader(ACCESSOR_READER);
1201 js::SetObjectReader(IMAGE_READER);
1202 js::SetObjectReader(SAMPLER_READER);
1203 js::SetObjectReader(TEXURE_READER);
1204 js::SetObjectReader(TEXURE_INFO_READER);
1205 js::SetObjectReader(MATERIAL_PBR_READER);
1206 js::SetObjectReader(MATERIAL_SPECULAR_READER);
1207 js::SetObjectReader(MATERIAL_IOR_READER);
1208 js::SetObjectReader(MATERIAL_EXTENSION_READER);
1209 js::SetObjectReader(MATERIAL_READER);
1210 js::SetObjectReader(MESH_PRIMITIVE_READER);
1211 js::SetObjectReader(MESH_READER);
1212 js::SetObjectReader(SKIN_READER);
1213 js::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1214 js::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1215 js::SetObjectReader(CAMERA_READER);
1216 js::SetObjectReader(NODE_READER);
1217 js::SetObjectReader(ANIMATION_SAMPLER_READER);
1218 js::SetObjectReader(ANIMATION_TARGET_READER);
1219 js::SetObjectReader(ANIMATION_CHANNEL_READER);
1220 js::SetObjectReader(ANIMATION_READER);
1221 js::SetObjectReader(SCENE_READER);
1224 void SetDefaultEnvironmentMap(const gt::Document& doc, ConversionContext& context)
1226 EnvironmentDefinition envDef;
1227 envDef.mUseBrdfTexture = true;
1228 envDef.mIblIntensity = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
1229 context.mOutput.mResources.mEnvironmentMaps.push_back({std::move(envDef), EnvironmentDefinition::Textures()});
1234 void InitializeGltfLoader()
1236 // Set ObjectReader only once (for all gltf loading).
1237 static bool setObjectReadersRequired = true;
1239 Mutex::ScopedLock lock(gInitializeMutex);
1240 if(setObjectReadersRequired)
1242 // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1244 setObjectReadersRequired = false;
1249 void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
1251 bool failed = false;
1252 auto js = LoadTextFile(url.c_str(), &failed);
1255 throw std::runtime_error("Failed to load " + url);
1258 json::unique_ptr root(json_parse(js.c_str(), js.size()));
1261 throw std::runtime_error("Failed to parse " + url);
1266 auto& rootObj = js::Cast<json_object_s>(*root);
1267 auto jsAsset = js::FindObjectChild("asset", rootObj);
1269 auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1272 doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1275 bool isMRendererModel(false);
1276 auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1277 if(jsAssetGenerator)
1279 doc.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1280 isMRendererModel = (doc.mAsset.mGenerator.find(MRENDERER_MODEL_IDENTIFICATION) != std::string_view::npos);
1284 Mutex::ScopedLock lock(gReadMutex);
1285 gt::SetRefReaderObject(doc);
1286 DOCUMENT_READER.Read(rootObj, doc);
1289 auto path = url.substr(0, url.rfind('/') + 1);
1290 ConversionContext context{params, path, INVALID_INDEX};
1292 ConvertMaterials(doc, context);
1293 ConvertMeshes(doc, context);
1294 ConvertNodes(doc, context, isMRendererModel);
1295 ConvertAnimations(doc, context);
1296 ProcessSkins(doc, context);
1297 ProduceShaders(shaderFactory, params.mScene);
1298 params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
1300 // Set Default Environment map
1301 SetDefaultEnvironmentMap(doc, context);
1304 } // namespace Loader
1305 } // namespace Scene3D