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.
18 #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>
26 #include <dali/integration-api/debug.h>
28 #define ENUM_STRING_MAPPING(t, x) \
44 const std::string POSITION_PROPERTY("position");
45 const std::string ORIENTATION_PROPERTY("orientation");
46 const std::string SCALE_PROPERTY("scale");
47 const std::string BLEND_SHAPE_WEIGHTS_UNIFORM("uBlendShapeWeight");
48 const std::string MRENDERER_MODEL_IDENTIFICATION("M-Renderer");
49 const std::string ROOT_NODE_NAME("RootNode");
50 const Vector3 SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
52 const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
58 Geometry::TRIANGLE_STRIP,
59 Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
61 struct AttributeMapping
63 gt::Attribute::Type mType;
64 MeshDefinition::Accessor MeshDefinition::*mAccessor;
65 uint16_t mElementSizeRequired;
66 } ATTRIBUTE_MAPPINGS[]{
67 {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
68 {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
69 {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
70 {gt::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
71 {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
72 {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
75 std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
78 SetRefReaderObject(proxy);
80 auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
82 for(auto& animation : results)
84 for(auto& channel : animation.mChannels)
86 channel.mSampler.UpdateVector(animation.mSamplers);
93 void ApplyAccessorMinMax(const gt::Accessor& acc, float* values)
95 DALI_ASSERT_ALWAYS(acc.mMax.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
96 DALI_ASSERT_ALWAYS(acc.mMin.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
97 MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
100 const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
101 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
102 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
104 const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
105 .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
106 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
107 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
108 .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
109 .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
111 const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
112 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
113 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
115 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
116 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
117 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
118 .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
120 const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
121 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
122 .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
123 .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
125 const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
126 .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
127 gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
128 >::Accessor::mBufferView))
129 .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
130 js::Read::Number<uint32_t>,
131 >::Accessor::mByteOffset))
132 .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
133 js::Read::Enum<gt::Component::Type>,
134 >::Accessor::mComponentType))
135 .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
136 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
137 .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
138 .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
139 .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
140 .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
141 .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
143 const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
144 .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
145 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
146 .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
147 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
149 const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
150 .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
151 .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
152 .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
153 .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
155 const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
156 .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
157 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
159 const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
160 .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
161 .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
162 .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
163 .Register(*js::MakeProperty("strength", js::Read::Number<float>, >::TextureInfo::mStrength)));
165 const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
166 .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
167 .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
168 .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
169 .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
170 .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
172 const auto MATERIAL_SPECULAR_READER = std::move(js::Reader<gt::MaterialSpecular>()
173 .Register(*js::MakeProperty("specularFactor", js::Read::Number<float>, >::MaterialSpecular::mSpecularFactor))
174 .Register(*js::MakeProperty("specularTexture", js::ObjectReader<gt::TextureInfo>::Read, >::MaterialSpecular::mSpecularTexture))
175 .Register(*js::MakeProperty("specularColorFactor", gt::ReadDaliVector<Vector3>, >::MaterialSpecular::mSpecularColorFactor))
176 .Register(*js::MakeProperty("specularColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::MaterialSpecular::mSpecularColorTexture)));
178 const auto MATERIAL_IOR_READER = std::move(js::Reader<gt::MaterialIor>()
179 .Register(*js::MakeProperty("ior", js::Read::Number<float>, >::MaterialIor::mIor)));
182 const auto MATERIAL_EXTENSION_READER = std::move(js::Reader<gt::MaterialExtensions>()
183 .Register(*js::MakeProperty("KHR_materials_ior", js::ObjectReader<gt::MaterialIor>::Read, >::MaterialExtensions::mMaterialIor))
184 .Register(*js::MakeProperty("KHR_materials_specular", js::ObjectReader<gt::MaterialSpecular>::Read, >::MaterialExtensions::mMaterialSpecular)));
186 const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
187 .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
188 .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
189 .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
190 .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
191 .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
192 .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
193 .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
194 .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff))
195 .Register(*js::MakeProperty("doubleSided", js::Read::Boolean, >::Material::mDoubleSided))
196 .Register(*js::MakeProperty("extensions", js::ObjectReader<gt::MaterialExtensions>::Read, >::Material::mMaterialExtensions)));
198 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
200 auto& jo = js::Cast<json_object_s>(j);
201 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
206 auto jstr = *i->name;
207 result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
213 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
215 auto& jo = js::Cast<json_array_s>(j);
216 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
218 result.reserve(jo.length);
223 result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
230 const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
231 .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
232 .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
233 .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
234 .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
235 .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
237 const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
238 .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
239 .Register(*js::MakeProperty("primitives",
240 js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
241 >::Mesh::mPrimitives))
242 .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
244 const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
245 .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
246 .Register(*js::MakeProperty("inverseBindMatrices",
247 gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
248 >::Skin::mInverseBindMatrices))
249 .Register(*js::MakeProperty("skeleton",
250 gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
251 >::Skin::mSkeleton))
252 .Register(*js::MakeProperty("joints",
253 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
254 >::Skin::mJoints)));
256 const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
257 .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
258 .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
259 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
260 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
262 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
263 .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
264 .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
265 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
266 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
268 const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
269 .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
270 .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
271 .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
272 .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
274 const auto NODE_READER = std::move(js::Reader<gt::Node>()
275 .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
276 .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
277 .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
278 .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
279 .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
280 .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
281 .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
282 .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
283 .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
285 const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
286 .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
287 .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
288 .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
290 const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
291 .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
292 .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
294 const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
295 .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
296 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
298 const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
299 .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
300 .Register(*js::MakeProperty("samplers",
301 js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
302 >::Animation::mSamplers))
303 .Register(*js::MakeProperty("channels",
304 js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
305 >::Animation::mChannels)));
307 const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
308 .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
309 .Register(*js::MakeProperty("nodes",
310 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
311 >::Scene::mNodes)));
313 const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
314 .Register(*js::MakeProperty("buffers",
315 js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
316 >::Document::mBuffers))
317 .Register(*js::MakeProperty("bufferViews",
318 js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
319 >::Document::mBufferViews))
320 .Register(*js::MakeProperty("accessors",
321 js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
322 >::Document::mAccessors))
323 .Register(*js::MakeProperty("images",
324 js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
325 >::Document::mImages))
326 .Register(*js::MakeProperty("samplers",
327 js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
328 >::Document::mSamplers))
329 .Register(*js::MakeProperty("textures",
330 js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
331 >::Document::mTextures))
332 .Register(*js::MakeProperty("materials",
333 js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
334 >::Document::mMaterials))
335 .Register(*js::MakeProperty("meshes",
336 js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
337 >::Document::mMeshes))
338 .Register(*js::MakeProperty("skins",
339 js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
340 >::Document::mSkins))
341 .Register(*js::MakeProperty("cameras",
342 js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
343 >::Document::mCameras))
344 .Register(*js::MakeProperty("nodes",
345 js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
346 >::Document::mNodes))
347 .Register(*js::MakeProperty("animations",
349 >::Document::mAnimations))
350 .Register(*js::MakeProperty("scenes",
351 js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
352 >::Document::mScenes))
353 .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
361 bool operator<(const NodeMapping& mapping, Index gltfIdx)
363 return mapping.gltfIdx < gltfIdx;
366 class NodeIndexMapper
369 NodeIndexMapper() = default;
370 NodeIndexMapper(const NodeIndexMapper&) = delete;
371 NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
373 ///@brief Registers a mapping of the @a gltfIdx of a node to its @a runtimeIdx .
374 ///@note If the indices are the same, the registration is omitted, in order to
375 /// save growing a vector.
376 void RegisterMapping(Index gltfIdx, Index runtimeIdx)
378 if(gltfIdx != runtimeIdx)
380 auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
381 DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
382 mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
386 ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
387 Index GetRuntimeId(Index gltfIdx) const
389 auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
390 return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
394 std::vector<NodeMapping> mNodes;
397 struct ConversionContext
402 Index mDefaultMaterial;
404 std::vector<Index> mMeshIds;
405 NodeIndexMapper mNodeIndices;
408 SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
412 case gt::Wrap::REPEAT:
413 return SamplerFlags::WRAP_REPEAT;
414 case gt::Wrap::CLAMP_TO_EDGE:
415 return SamplerFlags::WRAP_CLAMP;
416 case gt::Wrap::MIRRORED_REPEAT:
417 return SamplerFlags::WRAP_MIRROR;
419 throw std::runtime_error("Invalid wrap type.");
423 SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
427 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);
431 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
432 // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
433 // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
434 // properties, if not in some extension -, we will simply assume linear filtering.
435 return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
436 (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
440 TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm)
442 return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)};
445 void ConvertMaterial(const gt::Material& material, decltype(ResourceBundle::mMaterials)& outMaterials)
447 MaterialDefinition matDef;
449 auto& pbr = material.mPbrMetallicRoughness;
450 if(pbr.mBaseColorFactor.a < 1.f)
452 matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
455 if(material.mAlphaMode == gt::AlphaMode::MASK)
457 matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, material.mAlphaCutoff)));
460 matDef.mBaseColorFactor = pbr.mBaseColorFactor;
462 matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!material.mNormalTexture + !!material.mOcclusionTexture + !!material.mEmissiveTexture);
463 if(pbr.mBaseColorTexture)
465 const auto semantic = MaterialDefinition::ALBEDO;
466 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)});
467 // TODO: and there had better be one
468 matDef.mFlags |= semantic;
472 matDef.mNeedAlbedoTexture = false;
475 matDef.mMetallic = pbr.mMetallicFactor;
476 matDef.mRoughness = pbr.mRoughnessFactor;
478 if(pbr.mMetallicRoughnessTexture)
480 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
481 MaterialDefinition::GLTF_CHANNELS;
482 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)});
483 // TODO: and there had better be one
484 matDef.mFlags |= semantic;
488 matDef.mNeedMetallicRoughnessTexture = false;
491 matDef.mNormalScale = material.mNormalTexture.mScale;
492 if(material.mNormalTexture)
494 const auto semantic = MaterialDefinition::NORMAL;
495 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mNormalTexture)});
496 // TODO: and there had better be one
497 matDef.mFlags |= semantic;
501 matDef.mNeedNormalTexture = false;
504 if(material.mOcclusionTexture)
506 const auto semantic = MaterialDefinition::OCCLUSION;
507 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mOcclusionTexture)});
508 // TODO: and there had better be one
509 matDef.mFlags |= semantic;
510 matDef.mOcclusionStrength = material.mOcclusionTexture.mStrength;
513 if(material.mEmissiveTexture)
515 const auto semantic = MaterialDefinition::EMISSIVE;
516 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mEmissiveTexture)});
517 // TODO: and there had better be one
518 matDef.mFlags |= semantic;
519 matDef.mEmissiveFactor = material.mEmissiveFactor;
522 if(material.mMaterialExtensions.mMaterialIor.mIor < MAXFLOAT)
524 float ior = material.mMaterialExtensions.mMaterialIor.mIor;
525 matDef.mDielectricSpecular = powf((ior-1.0f)/(ior+1.0f), 2.0f);
527 matDef.mSpecularFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularFactor;
528 matDef.mSpecularColorFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularColorFactor;
530 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)
532 const auto semantic = MaterialDefinition::SPECULAR;
533 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)});
534 matDef.mFlags |= semantic;
537 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)
539 const auto semantic = MaterialDefinition::SPECULAR_COLOR;
540 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)});
541 matDef.mFlags |= semantic;
544 matDef.mDoubleSided = material.mDoubleSided;
546 outMaterials.emplace_back(std::move(matDef), TextureSet());
549 void ConvertMaterials(const gt::Document& doc, ConversionContext& context)
551 auto& outMaterials = context.mOutput.mResources.mMaterials;
552 outMaterials.reserve(doc.mMaterials.size());
554 for(auto& m : doc.mMaterials)
556 ConvertMaterial(m, outMaterials);
560 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
562 DALI_ASSERT_ALWAYS((acc.mBufferView &&
563 (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
564 (acc.mSparse && !acc.mBufferView));
566 DALI_ASSERT_ALWAYS(!acc.mSparse ||
567 ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
568 (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
570 MeshDefinition::SparseBlob sparseBlob;
573 const gt::Accessor::Sparse& sparse = *acc.mSparse;
574 const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
575 const gt::BufferViewClient& values = sparse.mValues;
577 MeshDefinition::Blob indicesBlob(
578 indices.mBufferView->mByteOffset + indices.mByteOffset,
579 sparse.mCount * indices.GetBytesPerComponent(),
580 static_cast<uint16_t>(indices.mBufferView->mByteStride),
581 static_cast<uint16_t>(indices.GetBytesPerComponent()),
584 MeshDefinition::Blob valuesBlob(
585 values.mBufferView->mByteOffset + values.mByteOffset,
586 sparse.mCount * acc.GetElementSizeBytes(),
587 static_cast<uint16_t>(values.mBufferView->mByteStride),
588 static_cast<uint16_t>(acc.GetElementSizeBytes()),
592 sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
595 uint32_t bufferViewOffset = 0u;
596 uint32_t bufferViewStride = 0u;
599 bufferViewOffset = acc.mBufferView->mByteOffset;
600 bufferViewStride = acc.mBufferView->mByteStride;
603 return MeshDefinition::Accessor{
604 std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
605 acc.GetBytesLength(),
606 static_cast<uint16_t>(bufferViewStride),
607 static_cast<uint16_t>(acc.GetElementSizeBytes()),
610 std::move(sparseBlob)};
613 void ConvertMeshes(const gt::Document& doc, ConversionContext& context)
615 uint32_t meshCount = 0;
616 context.mMeshIds.reserve(doc.mMeshes.size());
617 for(auto& mesh : doc.mMeshes)
619 context.mMeshIds.push_back(meshCount);
620 meshCount += mesh.mPrimitives.size();
623 auto& outMeshes = context.mOutput.mResources.mMeshes;
624 outMeshes.reserve(meshCount);
625 for(auto& mesh : doc.mMeshes)
627 for(auto& primitive : mesh.mPrimitives)
629 MeshDefinition meshDefinition;
631 auto& attribs = primitive.mAttributes;
632 meshDefinition.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
633 meshDefinition.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[primitive.mMode];
635 auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
636 meshDefinition.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
637 // glTF2 support vector4 tangent for mesh.
638 // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
639 meshDefinition.mTangentType = Property::VECTOR4;
641 const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
642 for(auto& am : ATTRIBUTE_MAPPINGS)
644 auto iFind = attribs.find(am.mType);
645 if(iFind != attribs.end())
647 DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDefinition.mUri) == 0);
648 auto& accessor = meshDefinition.*(am.mAccessor);
649 accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
651 if(iFind->first == gt::Attribute::JOINTS_0)
653 meshDefinition.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
654 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
657 else if(needNormalsTangents)
661 case gt::Attribute::NORMAL:
662 meshDefinition.RequestNormals();
665 case gt::Attribute::TANGENT:
666 meshDefinition.RequestTangents();
675 if(primitive.mIndices)
677 meshDefinition.mIndices = ConvertMeshPrimitiveAccessor(*primitive.mIndices);
678 meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
679 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U32_INDICES) || primitive.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
682 if(!primitive.mTargets.empty())
684 meshDefinition.mBlendShapes.reserve(primitive.mTargets.size());
685 meshDefinition.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
686 for(const auto& target : primitive.mTargets)
688 MeshDefinition::BlendShape blendShape;
690 auto endIt = target.end();
691 auto it = target.find(gt::Attribute::POSITION);
694 blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
696 it = target.find(gt::Attribute::NORMAL);
699 blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
701 it = target.find(gt::Attribute::TANGENT);
704 blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
707 if(!mesh.mWeights.empty())
709 blendShape.weight = mesh.mWeights[meshDefinition.mBlendShapes.size()];
712 meshDefinition.mBlendShapes.push_back(std::move(blendShape));
716 outMeshes.push_back({std::move(meshDefinition), MeshGeometry{}});
721 ModelRenderable* MakeModelRenderable(const gt::Mesh::Primitive& prim, ConversionContext& context)
723 auto modelRenderable = new ModelRenderable();
725 modelRenderable->mShaderIdx = 0; // TODO: further thought
727 auto materialIdx = prim.mMaterial.GetIndex();
728 if(INVALID_INDEX == materialIdx)
730 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
731 if(INVALID_INDEX == context.mDefaultMaterial)
733 auto& outMaterials = context.mOutput.mResources.mMaterials;
734 context.mDefaultMaterial = outMaterials.size();
736 ConvertMaterial(gt::Material{}, outMaterials);
739 materialIdx = context.mDefaultMaterial;
742 modelRenderable->mMaterialIdx = materialIdx;
744 return modelRenderable;
747 void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
749 camParams.isPerspective = camera.mType.compare("perspective") == 0;
750 if(camParams.isPerspective)
752 auto& perspective = camera.mPerspective;
753 camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
754 camParams.zNear = perspective.mZNear;
755 camParams.zFar = perspective.mZFar;
756 // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
760 auto& ortho = camera.mOrthographic;
761 camParams.orthographicSize = ortho.mYMag * .5f;
762 camParams.aspectRatio = ortho.mXMag / ortho.mYMag;
763 camParams.zNear = ortho.mZNear;
764 camParams.zFar = ortho.mZFar;
768 void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& context, bool isMRendererModel)
770 auto& output = context.mOutput;
771 auto& scene = output.mScene;
772 auto& resources = output.mResources;
774 const auto idx = scene.GetNodeCount();
775 auto weakNode = scene.AddNode([&]() {
776 std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
778 nodeDef->mParentIdx = parentIdx;
779 nodeDef->mName = node.mName;
780 if(nodeDef->mName.empty())
782 // TODO: Production quality generation of unique names.
783 nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
786 if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
788 nodeDef->mPosition = node.mTranslation;
789 nodeDef->mOrientation = node.mRotation;
790 nodeDef->mScale = node.mScale;
792 if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
794 nodeDef->mScale *= 0.01f;
802 ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
805 context.mNodeIndices.RegisterMapping(gltfIdx, idx);
807 Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
810 auto& mesh = *node.mMesh;
811 uint32_t primitiveCount = mesh.mPrimitives.size();
812 auto meshIdx = context.mMeshIds[node.mMesh.GetIndex()];
813 weakNode->mRenderables.reserve(primitiveCount);
814 for(uint32_t i = 0; i < primitiveCount; ++i)
816 std::unique_ptr<NodeDefinition::Renderable> renderable;
817 auto modelRenderable = MakeModelRenderable(mesh.mPrimitives[i], context);
818 modelRenderable->mMeshIdx = meshIdx + i;
820 DALI_ASSERT_DEBUG(resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == INVALID_INDEX ||
821 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == skeletonIdx);
822 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx = skeletonIdx;
824 renderable.reset(modelRenderable);
825 weakNode->mRenderables.push_back(std::move(renderable));
831 CameraParameters camParams;
832 ConvertCamera(*node.mCamera, camParams);
834 camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
835 output.mCameraParameters.push_back(camParams);
838 for(auto& n : node.mChildren)
840 ConvertNode(*n, n.GetIndex(), idx, context, isMRendererModel);
844 void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& context, bool isMRendererModel)
846 auto& outScene = context.mOutput.mScene;
847 Index rootIdx = outScene.GetNodeCount();
848 switch(scene.mNodes.size())
854 ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, context, isMRendererModel);
855 outScene.AddRootNode(rootIdx);
860 std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
861 sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
863 outScene.AddNode(std::move(sceneRoot));
864 outScene.AddRootNode(rootIdx);
866 for(auto& n : scene.mNodes)
868 ConvertNode(*n, n.GetIndex(), rootIdx, context, isMRendererModel);
875 void ConvertNodes(const gt::Document& doc, ConversionContext& context, bool isMRendererModel)
877 ConvertSceneNodes(*doc.mScene, context, isMRendererModel);
879 for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
881 ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
884 for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
886 ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
891 void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
893 std::ifstream animationBinaryFile(path, std::ifstream::binary);
895 if(!animationBinaryFile.is_open())
897 throw std::runtime_error("Failed to load " + path);
900 animationBinaryFile.seekg(offset);
901 animationBinaryFile.read(reinterpret_cast<char*>(dataBuffer.Begin()), size);
902 animationBinaryFile.close();
906 float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
908 inputDataBuffer.Resize(input.mCount);
909 outputDataBuffer.Resize(output.mCount);
911 const uint32_t inputDataBufferSize = input.GetBytesLength();
912 const uint32_t outputDataBufferSize = output.GetBytesLength();
914 LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
915 LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
916 ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
918 return inputDataBuffer[input.mCount - 1u];
922 float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
924 const gltf2::Accessor& input = *channel.mSampler->mInput;
925 const gltf2::Accessor& output = *channel.mSampler->mOutput;
927 Vector<float> inputDataBuffer;
928 Vector<T> outputDataBuffer;
930 const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
932 for(uint32_t i = 0; i < input.mCount; ++i)
934 keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
940 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)
942 const gltf2::Accessor& input = *channel.mSampler->mInput;
943 const gltf2::Accessor& output = *channel.mSampler->mOutput;
945 Vector<float> inputDataBuffer;
946 Vector<float> outputDataBuffer;
948 const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
950 char weightNameBuffer[32];
951 auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
952 char* const pWeightName = weightNameBuffer + prefixSize;
953 const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
954 for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
956 AnimatedProperty& animatedProperty = properties[propertyIndex++];
958 animatedProperty.mNodeName = nodeName;
959 snprintf(pWeightName, remainingSize, "%d]", weightIndex);
960 animatedProperty.mPropertyName = std::string(weightNameBuffer);
962 animatedProperty.mKeyFrames = KeyFrames::New();
963 for(uint32_t i = 0; i < input.mCount; ++i)
965 animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
968 animatedProperty.mTimePeriod = {0.f, duration};
974 void ConvertAnimations(const gt::Document& doc, ConversionContext& context)
976 auto& output = context.mOutput;
978 output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
980 for(const auto& animation : doc.mAnimations)
982 AnimationDefinition animationDef;
984 if(!animation.mName.empty())
986 animationDef.mName = animation.mName;
989 uint32_t numberOfProperties = 0u;
991 for(const auto& channel : animation.mChannels)
993 numberOfProperties += channel.mSampler->mOutput->mCount;
995 animationDef.mProperties.resize(numberOfProperties);
997 Index propertyIndex = 0u;
998 for(const auto& channel : animation.mChannels)
1000 std::string nodeName;
1001 if(!channel.mTarget.mNode->mName.empty())
1003 nodeName = channel.mTarget.mNode->mName;
1007 Index index = context.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
1008 nodeName = context.mOutput.mScene.GetNode(index)->mName;
1011 float duration = 0.f;
1013 switch(channel.mTarget.mPath)
1015 case gt::Animation::Channel::Target::TRANSLATION:
1017 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1019 animatedProperty.mNodeName = nodeName;
1020 animatedProperty.mPropertyName = POSITION_PROPERTY;
1022 animatedProperty.mKeyFrames = KeyFrames::New();
1023 duration = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1025 animatedProperty.mTimePeriod = {0.f, duration};
1028 case gt::Animation::Channel::Target::ROTATION:
1030 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1032 animatedProperty.mNodeName = nodeName;
1033 animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1035 animatedProperty.mKeyFrames = KeyFrames::New();
1036 duration = LoadKeyFrames<Quaternion>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1038 animatedProperty.mTimePeriod = {0.f, duration};
1041 case gt::Animation::Channel::Target::SCALE:
1043 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1045 animatedProperty.mNodeName = nodeName;
1046 animatedProperty.mPropertyName = SCALE_PROPERTY;
1048 animatedProperty.mKeyFrames = KeyFrames::New();
1049 duration = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1051 animatedProperty.mTimePeriod = {0.f, duration};
1054 case gt::Animation::Channel::Target::WEIGHTS:
1056 duration = LoadBlendShapeKeyFrames(context.mPath, channel, nodeName, propertyIndex, animationDef.mProperties);
1062 // nothing to animate.
1067 animationDef.mDuration = std::max(duration, animationDef.mDuration);
1072 output.mAnimationDefinitions.push_back(std::move(animationDef));
1076 void ProcessSkins(const gt::Document& doc, ConversionContext& context)
1078 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1079 // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1080 // otherwise we'll set identity matrices for inverse bind pose.
1081 struct IInverseBindMatrixProvider
1083 virtual ~IInverseBindMatrixProvider()
1086 virtual void Provide(Matrix& ibm) = 0;
1089 struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1091 std::ifstream mStream;
1092 const uint32_t mElementSizeBytes;
1094 InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
1095 : mStream(path + std::string(accessor.mBufferView->mBuffer->mUri), std::ios::binary),
1096 mElementSizeBytes(accessor.GetElementSizeBytes())
1098 DALI_ASSERT_ALWAYS(mStream);
1099 DALI_ASSERT_DEBUG(accessor.mType == gt::AccessorType::MAT4 && accessor.mComponentType == gt::Component::FLOAT);
1101 mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset);
1104 virtual void Provide(Matrix& ibm) override
1106 DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), mElementSizeBytes));
1110 struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1112 virtual void Provide(Matrix& ibm) override
1114 ibm = Matrix::IDENTITY;
1118 auto& resources = context.mOutput.mResources;
1119 resources.mSkeletons.reserve(doc.mSkins.size());
1121 for(auto& s : doc.mSkins)
1123 std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1124 if(s.mInverseBindMatrices)
1126 ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, context.mPath));
1130 ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1133 SkeletonDefinition skeleton;
1134 if(s.mSkeleton.GetIndex() != INVALID_INDEX)
1136 skeleton.mRootNodeIdx = context.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
1139 skeleton.mJoints.resize(s.mJoints.size());
1140 auto iJoint = skeleton.mJoints.begin();
1141 for(auto& j : s.mJoints)
1143 iJoint->mNodeIdx = context.mNodeIndices.GetRuntimeId(j.GetIndex());
1145 ibmProvider->Provide(iJoint->mInverseBindMatrix);
1150 resources.mSkeletons.push_back(std::move(skeleton));
1154 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
1156 uint32_t nodeCount = scene.GetNodeCount();
1157 for(uint32_t i = 0; i < nodeCount; ++i)
1159 auto nodeDef = scene.GetNode(i);
1160 for(auto& renderable : nodeDef->mRenderables)
1162 if(shaderFactory.ProduceShader(*renderable) == INVALID_INDEX)
1164 DALI_LOG_ERROR("Fail to produce shader\n");
1170 void SetObjectReaders()
1172 js::SetObjectReader(BUFFER_READER);
1173 js::SetObjectReader(BUFFER_VIEW_READER);
1174 js::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1175 js::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1176 js::SetObjectReader(ACCESSOR_SPARSE_READER);
1177 js::SetObjectReader(ACCESSOR_READER);
1178 js::SetObjectReader(IMAGE_READER);
1179 js::SetObjectReader(SAMPLER_READER);
1180 js::SetObjectReader(TEXURE_READER);
1181 js::SetObjectReader(TEXURE_INFO_READER);
1182 js::SetObjectReader(MATERIAL_PBR_READER);
1183 js::SetObjectReader(MATERIAL_SPECULAR_READER);
1184 js::SetObjectReader(MATERIAL_IOR_READER);
1185 js::SetObjectReader(MATERIAL_EXTENSION_READER);
1186 js::SetObjectReader(MATERIAL_READER);
1187 js::SetObjectReader(MESH_PRIMITIVE_READER);
1188 js::SetObjectReader(MESH_READER);
1189 js::SetObjectReader(SKIN_READER);
1190 js::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1191 js::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1192 js::SetObjectReader(CAMERA_READER);
1193 js::SetObjectReader(NODE_READER);
1194 js::SetObjectReader(ANIMATION_SAMPLER_READER);
1195 js::SetObjectReader(ANIMATION_TARGET_READER);
1196 js::SetObjectReader(ANIMATION_CHANNEL_READER);
1197 js::SetObjectReader(ANIMATION_READER);
1198 js::SetObjectReader(SCENE_READER);
1201 void SetDefaultEnvironmentMap(const gt::Document& doc, ConversionContext& context)
1203 EnvironmentDefinition envDef;
1204 envDef.mUseBrdfTexture = true;
1205 envDef.mIblIntensity = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
1206 context.mOutput.mResources.mEnvironmentMaps.push_back({std::move(envDef), EnvironmentDefinition::Textures()});
1211 void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
1213 bool failed = false;
1214 auto js = LoadTextFile(url.c_str(), &failed);
1217 throw std::runtime_error("Failed to load " + url);
1220 json::unique_ptr root(json_parse(js.c_str(), js.size()));
1223 throw std::runtime_error("Failed to parse " + url);
1226 static bool setObjectReaders = true;
1227 if(setObjectReaders)
1229 // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1231 setObjectReaders = false;
1236 auto& rootObj = js::Cast<json_object_s>(*root);
1237 auto jsAsset = js::FindObjectChild("asset", rootObj);
1239 auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1242 doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1245 bool isMRendererModel(false);
1246 auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1247 if(jsAssetGenerator)
1249 doc.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1250 isMRendererModel = (doc.mAsset.mGenerator.find(MRENDERER_MODEL_IDENTIFICATION) != std::string_view::npos);
1253 gt::SetRefReaderObject(doc);
1254 DOCUMENT_READER.Read(rootObj, doc);
1256 auto path = url.substr(0, url.rfind('/') + 1);
1257 ConversionContext context{params, path, INVALID_INDEX};
1259 ConvertMaterials(doc, context);
1260 ConvertMeshes(doc, context);
1261 ConvertNodes(doc, context, isMRendererModel);
1262 ConvertAnimations(doc, context);
1263 ProcessSkins(doc, context);
1264 ProduceShaders(shaderFactory, params.mScene);
1265 params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
1267 // Set Default Environment map
1268 SetDefaultEnvironmentMap(doc, context);
1271 } // namespace Loader
1272 } // namespace Scene3D