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.
17 #include "dali-scene3d/public-api/loader/gltf2-loader.h"
19 #include "dali-scene3d/internal/loader/gltf2-asset.h"
20 #include "dali-scene3d/public-api/loader/load-result.h"
21 #include "dali-scene3d/public-api/loader/resource-bundle.h"
22 #include "dali-scene3d/public-api/loader/scene-definition.h"
23 #include "dali-scene3d/public-api/loader/shader-definition-factory.h"
24 #include "dali-scene3d/public-api/loader/utils.h"
25 #include "dali/public-api/math/quaternion.h"
27 #define ENUM_STRING_MAPPING(t, x) \
43 const std::string POSITION_PROPERTY("position");
44 const std::string ORIENTATION_PROPERTY("orientation");
45 const std::string SCALE_PROPERTY("scale");
46 const std::string BLEND_SHAPE_WEIGHTS_UNIFORM("uBlendShapeWeight");
47 const std::string MRENDERER_MODEL_IDENTIFICATION("M-Renderer");
48 const std::string ROOT_NODE_NAME("RootNode");
49 const Vector3 SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
51 constexpr float DEFAULT_INTENSITY = 0.5f;
53 const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
59 Geometry::TRIANGLE_STRIP,
60 Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
62 struct AttributeMapping
64 gt::Attribute::Type mType;
65 MeshDefinition::Accessor MeshDefinition::*mAccessor;
66 uint16_t mElementSizeRequired;
67 } ATTRIBUTE_MAPPINGS[]{
68 {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
69 {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
70 {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
71 {gt::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
72 {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
73 {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
76 std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
79 SetRefReaderObject(proxy);
81 auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
83 for(auto& animation : results)
85 for(auto& channel : animation.mChannels)
87 channel.mSampler.UpdateVector(animation.mSamplers);
94 void ApplyAccessorMinMax(const gt::Accessor& acc, float* values)
96 DALI_ASSERT_ALWAYS(acc.mMax.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
97 DALI_ASSERT_ALWAYS(acc.mMin.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
98 MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
101 const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
102 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
103 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
105 const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
106 .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
107 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
108 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
109 .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
110 .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
112 const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
113 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
114 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
116 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
117 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
118 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
119 .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
121 const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
122 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
123 .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
124 .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
126 const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
127 .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
128 gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
129 >::Accessor::mBufferView))
130 .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
131 js::Read::Number<uint32_t>,
132 >::Accessor::mByteOffset))
133 .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
134 js::Read::Enum<gt::Component::Type>,
135 >::Accessor::mComponentType))
136 .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
137 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
138 .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
139 .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
140 .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
141 .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
142 .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
144 const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
145 .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
146 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
147 .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
148 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
150 const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
151 .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
152 .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
153 .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
154 .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
156 const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
157 .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
158 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
160 const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
161 .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
162 .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
163 .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
164 .Register(*js::MakeProperty("strength", js::Read::Number<float>, >::TextureInfo::mStrength)));
166 const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
167 .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
168 .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
169 .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
170 .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
171 .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
173 const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
174 .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
175 .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
176 .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
177 .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
178 .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
179 .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
180 .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
181 .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff)));
183 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
185 auto& jo = js::Cast<json_object_s>(j);
186 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
191 auto jstr = *i->name;
192 result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
198 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
200 auto& jo = js::Cast<json_array_s>(j);
201 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
203 result.reserve(jo.length);
208 result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
215 const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
216 .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
217 .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
218 .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
219 .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
220 .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
222 const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
223 .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
224 .Register(*js::MakeProperty("primitives",
225 js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
226 >::Mesh::mPrimitives))
227 .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
229 const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
230 .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
231 .Register(*js::MakeProperty("inverseBindMatrices",
232 gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
233 >::Skin::mInverseBindMatrices))
234 .Register(*js::MakeProperty("skeleton",
235 gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
236 >::Skin::mSkeleton))
237 .Register(*js::MakeProperty("joints",
238 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
239 >::Skin::mJoints)));
241 const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
242 .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
243 .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
244 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
245 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
247 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
248 .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
249 .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
250 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
251 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
253 const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
254 .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
255 .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
256 .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
257 .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
259 const auto NODE_READER = std::move(js::Reader<gt::Node>()
260 .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
261 .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
262 .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
263 .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
264 .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
265 .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
266 .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
267 .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
268 .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
270 const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
271 .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
272 .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
273 .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
275 const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
276 .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
277 .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
279 const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
280 .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
281 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
283 const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
284 .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
285 .Register(*js::MakeProperty("samplers",
286 js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
287 >::Animation::mSamplers))
288 .Register(*js::MakeProperty("channels",
289 js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
290 >::Animation::mChannels)));
292 const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
293 .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
294 .Register(*js::MakeProperty("nodes",
295 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
296 >::Scene::mNodes)));
298 const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
299 .Register(*js::MakeProperty("buffers",
300 js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
301 >::Document::mBuffers))
302 .Register(*js::MakeProperty("bufferViews",
303 js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
304 >::Document::mBufferViews))
305 .Register(*js::MakeProperty("accessors",
306 js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
307 >::Document::mAccessors))
308 .Register(*js::MakeProperty("images",
309 js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
310 >::Document::mImages))
311 .Register(*js::MakeProperty("samplers",
312 js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
313 >::Document::mSamplers))
314 .Register(*js::MakeProperty("textures",
315 js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
316 >::Document::mTextures))
317 .Register(*js::MakeProperty("materials",
318 js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
319 >::Document::mMaterials))
320 .Register(*js::MakeProperty("meshes",
321 js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
322 >::Document::mMeshes))
323 .Register(*js::MakeProperty("skins",
324 js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
325 >::Document::mSkins))
326 .Register(*js::MakeProperty("cameras",
327 js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
328 >::Document::mCameras))
329 .Register(*js::MakeProperty("nodes",
330 js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
331 >::Document::mNodes))
332 .Register(*js::MakeProperty("animations",
334 >::Document::mAnimations))
335 .Register(*js::MakeProperty("scenes",
336 js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
337 >::Document::mScenes))
338 .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
346 bool operator<(const NodeMapping& mapping, Index gltfIdx)
348 return mapping.gltfIdx < gltfIdx;
351 class NodeIndexMapper
354 NodeIndexMapper() = default;
355 NodeIndexMapper(const NodeIndexMapper&) = delete;
356 NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
358 ///@brief Registers a mapping of the @a gltfIdx of a node to its @a runtimeIdx .
359 ///@note If the indices are the same, the registration is omitted, in order to
360 /// save growing a vector.
361 void RegisterMapping(Index gltfIdx, Index runtimeIdx)
363 if(gltfIdx != runtimeIdx)
365 auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
366 DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
367 mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
371 ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
372 Index GetRuntimeId(Index gltfIdx) const
374 auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
375 return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
379 std::vector<NodeMapping> mNodes;
382 struct ConversionContext
387 Index mDefaultMaterial;
389 std::vector<Index> mMeshIds;
390 NodeIndexMapper mNodeIndices;
393 SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
397 case gt::Wrap::REPEAT:
398 return SamplerFlags::WRAP_REPEAT;
399 case gt::Wrap::CLAMP_TO_EDGE:
400 return SamplerFlags::WRAP_CLAMP;
401 case gt::Wrap::MIRRORED_REPEAT:
402 return SamplerFlags::WRAP_MIRROR;
404 throw std::runtime_error("Invalid wrap type.");
408 SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
412 return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
416 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
417 // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
418 // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
419 // properties, if not in some extension -, we will simply assume linear filtering.
420 return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
421 (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
425 TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm)
427 return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)};
430 void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials)
432 MaterialDefinition matDef;
434 auto& pbr = m.mPbrMetallicRoughness;
435 if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
437 matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
440 if(m.mAlphaMode == gt::AlphaMode::MASK)
442 matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff)));
445 matDef.mBaseColorFactor = pbr.mBaseColorFactor;
447 matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture + !!m.mOcclusionTexture + !!m.mEmissiveTexture);
448 if(pbr.mBaseColorTexture)
450 const auto semantic = MaterialDefinition::ALBEDO;
451 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)});
452 // TODO: and there had better be one
453 matDef.mFlags |= semantic;
457 matDef.mNeedAlbedoTexture = false;
460 matDef.mMetallic = pbr.mMetallicFactor;
461 matDef.mRoughness = pbr.mRoughnessFactor;
463 if(pbr.mMetallicRoughnessTexture)
465 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
466 MaterialDefinition::GLTF_CHANNELS;
467 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)});
468 // TODO: and there had better be one
469 matDef.mFlags |= semantic;
473 matDef.mNeedMetallicRoughnessTexture = false;
476 matDef.mNormalScale = m.mNormalTexture.mScale;
479 const auto semantic = MaterialDefinition::NORMAL;
480 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)});
481 // TODO: and there had better be one
482 matDef.mFlags |= semantic;
486 matDef.mNeedNormalTexture = false;
489 // TODO: handle doubleSided
490 if(m.mOcclusionTexture)
492 const auto semantic = MaterialDefinition::OCCLUSION;
493 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mOcclusionTexture)});
494 // TODO: and there had better be one
495 matDef.mFlags |= semantic;
496 matDef.mOcclusionStrength = m.mOcclusionTexture.mStrength;
499 if(m.mEmissiveTexture)
501 const auto semantic = MaterialDefinition::EMISSIVE;
502 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mEmissiveTexture)});
503 // TODO: and there had better be one
504 matDef.mFlags |= semantic;
505 matDef.mEmissiveFactor = m.mEmissiveFactor;
508 outMaterials.emplace_back(std::move(matDef), TextureSet());
511 void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx)
513 auto& outMaterials = cctx.mOutput.mResources.mMaterials;
514 outMaterials.reserve(doc.mMaterials.size());
516 for(auto& m : doc.mMaterials)
518 ConvertMaterial(m, outMaterials);
522 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
524 DALI_ASSERT_ALWAYS((acc.mBufferView &&
525 (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
526 (acc.mSparse && !acc.mBufferView));
528 DALI_ASSERT_ALWAYS(!acc.mSparse ||
529 ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
530 (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
532 MeshDefinition::SparseBlob sparseBlob;
535 const gt::Accessor::Sparse& sparse = *acc.mSparse;
536 const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
537 const gt::BufferViewClient& values = sparse.mValues;
539 MeshDefinition::Blob indicesBlob(
540 indices.mBufferView->mByteOffset + indices.mByteOffset,
541 sparse.mCount * indices.GetBytesPerComponent(),
542 static_cast<uint16_t>(indices.mBufferView->mByteStride),
543 static_cast<uint16_t>(indices.GetBytesPerComponent()),
546 MeshDefinition::Blob valuesBlob(
547 values.mBufferView->mByteOffset + values.mByteOffset,
548 sparse.mCount * acc.GetElementSizeBytes(),
549 static_cast<uint16_t>(values.mBufferView->mByteStride),
550 static_cast<uint16_t>(acc.GetElementSizeBytes()),
554 sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
557 uint32_t bufferViewOffset = 0u;
558 uint32_t bufferViewStride = 0u;
561 bufferViewOffset = acc.mBufferView->mByteOffset;
562 bufferViewStride = acc.mBufferView->mByteStride;
565 return MeshDefinition::Accessor{
566 std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
567 acc.GetBytesLength(),
568 static_cast<uint16_t>(bufferViewStride),
569 static_cast<uint16_t>(acc.GetElementSizeBytes()),
572 std::move(sparseBlob)};
575 void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx)
577 uint32_t meshCount = 0;
578 cctx.mMeshIds.reserve(doc.mMeshes.size());
579 for(auto& m : doc.mMeshes)
581 cctx.mMeshIds.push_back(meshCount);
582 meshCount += m.mPrimitives.size();
585 auto& outMeshes = cctx.mOutput.mResources.mMeshes;
586 outMeshes.reserve(meshCount);
587 for(auto& m : doc.mMeshes)
589 for(auto& p : m.mPrimitives)
591 MeshDefinition meshDef;
593 auto& attribs = p.mAttributes;
594 meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
595 meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode];
597 auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
598 meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
599 // glTF2 support vector4 tangent for mesh.
600 // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
601 meshDef.mTangentType = Property::VECTOR4;
603 const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
604 for(auto& am : ATTRIBUTE_MAPPINGS)
606 auto iFind = attribs.find(am.mType);
607 if(iFind != attribs.end())
609 DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0);
610 auto& accessor = meshDef.*(am.mAccessor);
611 accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
613 if(iFind->first == gt::Attribute::JOINTS_0)
615 meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
616 DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
619 else if(needNormalsTangents)
623 case gt::Attribute::NORMAL:
624 meshDef.RequestNormals();
627 case gt::Attribute::TANGENT:
628 meshDef.RequestTangents();
639 meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices);
640 meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
641 DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
644 if(!p.mTargets.empty())
646 meshDef.mBlendShapes.reserve(p.mTargets.size());
647 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
648 for(const auto& target : p.mTargets)
650 MeshDefinition::BlendShape blendShape;
652 auto endIt = target.end();
653 auto it = target.find(gt::Attribute::POSITION);
656 blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
658 it = target.find(gt::Attribute::NORMAL);
661 blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
663 it = target.find(gt::Attribute::TANGENT);
666 blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
669 if(!m.mWeights.empty())
671 blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()];
674 meshDef.mBlendShapes.push_back(std::move(blendShape));
678 outMeshes.push_back({std::move(meshDef), MeshGeometry{}});
683 ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cctx)
685 auto modelNode = new ModelNode();
687 modelNode->mShaderIdx = 0; // TODO: further thought
689 auto materialIdx = prim.mMaterial.GetIndex();
690 if(INVALID_INDEX == materialIdx)
692 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
693 if(INVALID_INDEX == cctx.mDefaultMaterial)
695 auto& outMaterials = cctx.mOutput.mResources.mMaterials;
696 cctx.mDefaultMaterial = outMaterials.size();
698 ConvertMaterial(gt::Material{}, outMaterials);
701 materialIdx = cctx.mDefaultMaterial;
704 modelNode->mMaterialIdx = materialIdx;
709 void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
711 camParams.isPerspective = camera.mType.compare("perspective") == 0;
712 if(camParams.isPerspective)
714 auto& perspective = camera.mPerspective;
715 camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
716 camParams.zNear = perspective.mZNear;
717 camParams.zFar = perspective.mZFar;
718 // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
722 auto& ortho = camera.mOrthographic;
723 camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f;
724 camParams.zNear = ortho.mZNear;
725 camParams.zFar = ortho.mZFar;
729 void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx, bool isMRendererModel)
731 auto& output = cctx.mOutput;
732 auto& scene = output.mScene;
733 auto& resources = output.mResources;
735 const auto idx = scene.GetNodeCount();
736 auto weakNode = scene.AddNode([&]() {
737 std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
739 nodeDef->mParentIdx = parentIdx;
740 nodeDef->mName = node.mName;
741 if(nodeDef->mName.empty())
743 // TODO: Production quality generation of unique names.
744 nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
747 if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
749 nodeDef->mPosition = node.mTranslation;
750 nodeDef->mOrientation = node.mRotation;
751 nodeDef->mScale = node.mScale;
753 if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
755 nodeDef->mScale *= 0.01f;
763 ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
766 cctx.mNodeIndices.RegisterMapping(gltfIdx, idx);
768 Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
769 if(node.mMesh && !node.mMesh->mPrimitives.empty())
771 auto& mesh = *node.mMesh;
773 auto iPrim = mesh.mPrimitives.begin();
774 auto modelNode = MakeModelNode(*iPrim, cctx);
775 auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
776 modelNode->mMeshIdx = meshIdx;
778 weakNode->mRenderable.reset(modelNode);
780 DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
781 resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
782 resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
784 // As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es.
785 while(++iPrim != mesh.mPrimitives.end())
787 std::unique_ptr<NodeDefinition> child{new NodeDefinition};
788 child->mParentIdx = idx;
790 auto childModel = MakeModelNode(*iPrim, cctx);
793 childModel->mMeshIdx = meshIdx;
795 child->mRenderable.reset(childModel);
797 scene.AddNode(std::move(child));
799 DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
800 resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
801 resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
807 CameraParameters camParams;
808 ConvertCamera(*node.mCamera, camParams);
810 camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
811 output.mCameraParameters.push_back(camParams);
814 for(auto& n : node.mChildren)
816 ConvertNode(*n, n.GetIndex(), idx, cctx, isMRendererModel);
820 void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx, bool isMRendererModel)
822 auto& outScene = cctx.mOutput.mScene;
823 Index rootIdx = outScene.GetNodeCount();
824 switch(scene.mNodes.size())
830 ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx, isMRendererModel);
831 outScene.AddRootNode(rootIdx);
836 std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
837 sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
839 outScene.AddNode(std::move(sceneRoot));
840 outScene.AddRootNode(rootIdx);
842 for(auto& n : scene.mNodes)
844 ConvertNode(*n, n.GetIndex(), rootIdx, cctx, isMRendererModel);
851 void ConvertNodes(const gt::Document& doc, ConversionContext& cctx, bool isMRendererModel)
853 ConvertSceneNodes(*doc.mScene, cctx, isMRendererModel);
855 for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
857 ConvertSceneNodes(doc.mScenes[i], cctx, isMRendererModel);
860 for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
862 ConvertSceneNodes(doc.mScenes[i], cctx, isMRendererModel);
867 void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
869 std::ifstream animationBinaryFile(path, std::ifstream::binary);
871 if(!animationBinaryFile.is_open())
873 throw std::runtime_error("Failed to load " + path);
876 animationBinaryFile.seekg(offset);
877 animationBinaryFile.read(reinterpret_cast<char*>(dataBuffer.Begin()), size);
878 animationBinaryFile.close();
882 float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
884 inputDataBuffer.Resize(input.mCount);
885 outputDataBuffer.Resize(output.mCount);
887 const uint32_t inputDataBufferSize = input.GetBytesLength();
888 const uint32_t outputDataBufferSize = output.GetBytesLength();
890 LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
891 LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
892 ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
894 return inputDataBuffer[input.mCount - 1u];
898 float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
900 const gltf2::Accessor& input = *channel.mSampler->mInput;
901 const gltf2::Accessor& output = *channel.mSampler->mOutput;
903 Vector<float> inputDataBuffer;
904 Vector<T> outputDataBuffer;
906 const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
908 for(uint32_t i = 0; i < input.mCount; ++i)
910 keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
916 float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector<Dali::Scene3D::Loader::AnimatedProperty>& properties)
918 const gltf2::Accessor& input = *channel.mSampler->mInput;
919 const gltf2::Accessor& output = *channel.mSampler->mOutput;
921 Vector<float> inputDataBuffer;
922 Vector<float> outputDataBuffer;
924 const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
926 char weightNameBuffer[32];
927 auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
928 char* const pWeightName = weightNameBuffer + prefixSize;
929 const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
930 for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
932 AnimatedProperty& animatedProperty = properties[propertyIndex++];
934 animatedProperty.mNodeName = nodeName;
935 snprintf(pWeightName, remainingSize, "%d]", weightIndex);
936 animatedProperty.mPropertyName = std::string(weightNameBuffer);
938 animatedProperty.mKeyFrames = KeyFrames::New();
939 for(uint32_t i = 0; i < input.mCount; ++i)
941 animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
944 animatedProperty.mTimePeriod = {0.f, duration};
950 void ConvertAnimations(const gt::Document& doc, ConversionContext& cctx)
952 auto& output = cctx.mOutput;
954 output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
956 for(const auto& animation : doc.mAnimations)
958 AnimationDefinition animationDef;
960 if(!animation.mName.empty())
962 animationDef.mName = animation.mName;
965 uint32_t numberOfProperties = 0u;
967 for(const auto& channel : animation.mChannels)
969 numberOfProperties += channel.mSampler->mOutput->mCount;
971 animationDef.mProperties.resize(numberOfProperties);
973 Index propertyIndex = 0u;
974 for(const auto& channel : animation.mChannels)
976 std::string nodeName;
977 if(!channel.mTarget.mNode->mName.empty())
979 nodeName = channel.mTarget.mNode->mName;
983 Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
984 nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
987 float duration = 0.f;
989 switch(channel.mTarget.mPath)
991 case gt::Animation::Channel::Target::TRANSLATION:
993 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
995 animatedProperty.mNodeName = nodeName;
996 animatedProperty.mPropertyName = POSITION_PROPERTY;
998 animatedProperty.mKeyFrames = KeyFrames::New();
999 duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1001 animatedProperty.mTimePeriod = {0.f, duration};
1004 case gt::Animation::Channel::Target::ROTATION:
1006 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1008 animatedProperty.mNodeName = nodeName;
1009 animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1011 animatedProperty.mKeyFrames = KeyFrames::New();
1012 duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1014 animatedProperty.mTimePeriod = {0.f, duration};
1017 case gt::Animation::Channel::Target::SCALE:
1019 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1021 animatedProperty.mNodeName = nodeName;
1022 animatedProperty.mPropertyName = SCALE_PROPERTY;
1024 animatedProperty.mKeyFrames = KeyFrames::New();
1025 duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1027 animatedProperty.mTimePeriod = {0.f, duration};
1030 case gt::Animation::Channel::Target::WEIGHTS:
1032 duration = LoadBlendShapeKeyFrames(cctx.mPath, channel, nodeName, propertyIndex, animationDef.mProperties);
1038 // nothing to animate.
1043 animationDef.mDuration = std::max(duration, animationDef.mDuration);
1048 output.mAnimationDefinitions.push_back(std::move(animationDef));
1052 void ProcessSkins(const gt::Document& doc, ConversionContext& cctx)
1054 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1055 // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1056 // otherwise we'll set identity matrices for inverse bind pose.
1057 struct IInverseBindMatrixProvider
1059 virtual ~IInverseBindMatrixProvider()
1062 virtual void Provide(Matrix& ibm) = 0;
1065 struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1067 std::ifstream mStream;
1068 const uint32_t mElementSizeBytes;
1070 InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
1071 : mStream(path + std::string(accessor.mBufferView->mBuffer->mUri), std::ios::binary),
1072 mElementSizeBytes(accessor.GetElementSizeBytes())
1074 DALI_ASSERT_ALWAYS(mStream);
1075 DALI_ASSERT_DEBUG(accessor.mType == gt::AccessorType::MAT4 && accessor.mComponentType == gt::Component::FLOAT);
1077 mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset);
1080 virtual void Provide(Matrix& ibm) override
1082 DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), mElementSizeBytes));
1086 struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1088 virtual void Provide(Matrix& ibm) override
1090 ibm = Matrix::IDENTITY;
1094 auto& resources = cctx.mOutput.mResources;
1095 resources.mSkeletons.reserve(doc.mSkins.size());
1097 for(auto& s : doc.mSkins)
1099 std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1100 if(s.mInverseBindMatrices)
1102 ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath));
1106 ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1109 SkeletonDefinition skeleton;
1110 if(s.mSkeleton.GetIndex() != INVALID_INDEX)
1112 skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
1115 skeleton.mJoints.resize(s.mJoints.size());
1116 auto iJoint = skeleton.mJoints.begin();
1117 for(auto& j : s.mJoints)
1119 iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex());
1121 ibmProvider->Provide(iJoint->mInverseBindMatrix);
1126 resources.mSkeletons.push_back(std::move(skeleton));
1130 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
1132 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
1134 auto nodeDef = scene.GetNode(i0);
1135 if(auto renderable = nodeDef->mRenderable.get())
1137 renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef);
1142 void SetObjectReaders()
1144 js::SetObjectReader(BUFFER_READER);
1145 js::SetObjectReader(BUFFER_VIEW_READER);
1146 js::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1147 js::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1148 js::SetObjectReader(ACCESSOR_SPARSE_READER);
1149 js::SetObjectReader(ACCESSOR_READER);
1150 js::SetObjectReader(IMAGE_READER);
1151 js::SetObjectReader(SAMPLER_READER);
1152 js::SetObjectReader(TEXURE_READER);
1153 js::SetObjectReader(TEXURE_INFO_READER);
1154 js::SetObjectReader(MATERIAL_PBR_READER);
1155 js::SetObjectReader(MATERIAL_READER);
1156 js::SetObjectReader(MESH_PRIMITIVE_READER);
1157 js::SetObjectReader(MESH_READER);
1158 js::SetObjectReader(SKIN_READER);
1159 js::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1160 js::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1161 js::SetObjectReader(CAMERA_READER);
1162 js::SetObjectReader(NODE_READER);
1163 js::SetObjectReader(ANIMATION_SAMPLER_READER);
1164 js::SetObjectReader(ANIMATION_TARGET_READER);
1165 js::SetObjectReader(ANIMATION_CHANNEL_READER);
1166 js::SetObjectReader(ANIMATION_READER);
1167 js::SetObjectReader(SCENE_READER);
1170 void SetDefaultEnvironmentMap(const gt::Document& doc, ConversionContext& cctx)
1172 EnvironmentDefinition envDef;
1173 envDef.mUseBrdfTexture = true;
1174 envDef.mIblIntensity = DEFAULT_INTENSITY;
1175 cctx.mOutput.mResources.mEnvironmentMaps.push_back({std::move(envDef), EnvironmentDefinition::Textures()});
1180 void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
1182 bool failed = false;
1183 auto js = LoadTextFile(url.c_str(), &failed);
1186 throw std::runtime_error("Failed to load " + url);
1189 json::unique_ptr root(json_parse(js.c_str(), js.size()));
1192 throw std::runtime_error("Failed to parse " + url);
1195 static bool setObjectReaders = true;
1196 if(setObjectReaders)
1198 // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1200 setObjectReaders = false;
1205 auto& rootObj = js::Cast<json_object_s>(*root);
1206 auto jsAsset = js::FindObjectChild("asset", rootObj);
1208 auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1211 doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1214 bool isMRendererModel(false);
1215 auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1216 if(jsAssetGenerator)
1218 doc.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1219 isMRendererModel = (doc.mAsset.mGenerator.find(MRENDERER_MODEL_IDENTIFICATION) != std::string_view::npos);
1222 gt::SetRefReaderObject(doc);
1223 DOCUMENT_READER.Read(rootObj, doc);
1225 auto path = url.substr(0, url.rfind('/') + 1);
1226 ConversionContext cctx{params, path, INVALID_INDEX};
1228 ConvertMaterials(doc, cctx);
1229 ConvertMeshes(doc, cctx);
1230 ConvertNodes(doc, cctx, isMRendererModel);
1231 ConvertAnimations(doc, cctx);
1232 ProcessSkins(doc, cctx);
1233 ProduceShaders(shaderFactory, params.mScene);
1234 params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
1236 // Set Default Environment map
1237 SetDefaultEnvironmentMap(doc, cctx);
1240 } // namespace Loader
1241 } // namespace Scene3D