96925cc03650405490ff292ff2c760c88d7aaad0
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / internal / loader / gltf2-util.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-scene3d/internal/loader/gltf2-util.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23
24 using namespace Dali::Scene3D::Loader;
25
26 namespace Dali::Scene3D::Loader::Internal
27 {
28 namespace Gltf2Util
29 {
30 static constexpr std::string_view MRENDERER_MODEL_IDENTIFICATION = "M-Renderer";
31 static constexpr std::string_view POSITION_PROPERTY              = "position";
32 static constexpr std::string_view ORIENTATION_PROPERTY           = "orientation";
33 static constexpr std::string_view SCALE_PROPERTY                 = "scale";
34 static constexpr std::string_view BLEND_SHAPE_WEIGHTS_UNIFORM    = "uBlendShapeWeight";
35 static constexpr std::string_view ROOT_NODE_NAME                 = "RootNode";
36 static const Vector3              SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
37
38 static const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
39   Geometry::POINTS,
40   Geometry::LINES,
41   Geometry::LINE_LOOP,
42   Geometry::LINE_STRIP,
43   Geometry::TRIANGLES,
44   Geometry::TRIANGLE_STRIP,
45   Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
46
47 static struct AttributeMapping
48 {
49   gltf2::Attribute::Type   mType;
50   MeshDefinition::Accessor MeshDefinition::*mAccessor;
51   uint16_t                                  mElementSizeRequired;
52 } ATTRIBUTE_MAPPINGS[]{
53   {gltf2::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
54   {gltf2::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
55   {gltf2::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
56   {gltf2::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
57   {gltf2::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
58   {gltf2::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
59 };
60
61 std::vector<gltf2::Animation> ReadAnimationArray(const json_value_s& j)
62 {
63   auto results = json::Read::Array<gltf2::Animation, json::ObjectReader<gltf2::Animation>::Read>(j);
64
65   for(auto& animation : results)
66   {
67     for(auto& channel : animation.mChannels)
68     {
69       channel.mSampler.UpdateVector(animation.mSamplers);
70     }
71   }
72
73   return results;
74 }
75
76 void ApplyAccessorMinMax(const gltf2::Accessor& acc, float* values)
77 {
78   DALI_ASSERT_ALWAYS(acc.mMax.empty() || gltf2::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
79   DALI_ASSERT_ALWAYS(acc.mMin.empty() || gltf2::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
80   MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
81 }
82
83 const auto BUFFER_READER = std::move(json::Reader<gltf2::Buffer>()
84                                        .Register(*json::MakeProperty("byteLength", json::Read::Number<uint32_t>, &gltf2::Buffer::mByteLength))
85                                        .Register(*json::MakeProperty("uri", json::Read::StringView, &gltf2::Buffer::mUri)));
86
87 const auto BUFFER_VIEW_READER = std::move(json::Reader<gltf2::BufferView>()
88                                             .Register(*json::MakeProperty("buffer", gltf2::RefReader<gltf2::Document>::Read<gltf2::Buffer, &gltf2::Document::mBuffers>, &gltf2::BufferView::mBuffer))
89                                             .Register(*json::MakeProperty("byteOffset", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteOffset))
90                                             .Register(*json::MakeProperty("byteLength", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteLength))
91                                             .Register(*json::MakeProperty("byteStride", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteStride))
92                                             .Register(*json::MakeProperty("target", json::Read::Number<uint32_t>, &gltf2::BufferView::mTarget)));
93
94 const auto BUFFER_VIEW_CLIENT_READER = std::move(json::Reader<gltf2::BufferViewClient>()
95                                                    .Register(*json::MakeProperty("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::BufferViewClient::mBufferView))
96                                                    .Register(*json::MakeProperty("byteOffset", json::Read::Number<uint32_t>, &gltf2::BufferViewClient::mByteOffset)));
97
98 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(json::Reader<gltf2::ComponentTypedBufferViewClient>()
99                                                                    .Register(*new json::Property<gltf2::ComponentTypedBufferViewClient, gltf2::Ref<gltf2::BufferView>>("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::ComponentTypedBufferViewClient::mBufferView))
100                                                                    .Register(*new json::Property<gltf2::ComponentTypedBufferViewClient, uint32_t>("byteOffset", json::Read::Number<uint32_t>, &gltf2::ComponentTypedBufferViewClient::mByteOffset))
101                                                                    .Register(*json::MakeProperty("componentType", json::Read::Enum<gltf2::Component::Type>, &gltf2::ComponentTypedBufferViewClient::mComponentType)));
102
103 const auto ACCESSOR_SPARSE_READER = std::move(json::Reader<gltf2::Accessor::Sparse>()
104                                                 .Register(*json::MakeProperty("count", json::Read::Number<uint32_t>, &gltf2::Accessor::Sparse::mCount))
105                                                 .Register(*json::MakeProperty("indices", json::ObjectReader<gltf2::ComponentTypedBufferViewClient>::Read, &gltf2::Accessor::Sparse::mIndices))
106                                                 .Register(*json::MakeProperty("values", json::ObjectReader<gltf2::BufferViewClient>::Read, &gltf2::Accessor::Sparse::mValues)));
107
108 const auto ACCESSOR_READER = std::move(json::Reader<gltf2::Accessor>()
109                                          .Register(*new json::Property<gltf2::Accessor, gltf2::Ref<gltf2::BufferView>>("bufferView",
110                                                                                                                        gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>,
111                                                                                                                        &gltf2::Accessor::mBufferView))
112                                          .Register(*new json::Property<gltf2::Accessor, uint32_t>("byteOffset",
113                                                                                                   json::Read::Number<uint32_t>,
114                                                                                                   &gltf2::Accessor::mByteOffset))
115                                          .Register(*new json::Property<gltf2::Accessor, gltf2::Component::Type>("componentType",
116                                                                                                                 json::Read::Enum<gltf2::Component::Type>,
117                                                                                                                 &gltf2::Accessor::mComponentType))
118                                          .Register(*new json::Property<gltf2::Accessor, std::string_view>("name", json::Read::StringView, &gltf2::Accessor::mName))
119                                          .Register(*json::MakeProperty("count", json::Read::Number<uint32_t>, &gltf2::Accessor::mCount))
120                                          .Register(*json::MakeProperty("normalized", json::Read::Boolean, &gltf2::Accessor::mNormalized))
121                                          .Register(*json::MakeProperty("type", gltf2::ReadStringEnum<gltf2::AccessorType>, &gltf2::Accessor::mType))
122                                          .Register(*json::MakeProperty("min", json::Read::Array<float, json::Read::Number>, &gltf2::Accessor::mMin))
123                                          .Register(*json::MakeProperty("max", json::Read::Array<float, json::Read::Number>, &gltf2::Accessor::mMax))
124                                          .Register(*new json::Property<gltf2::Accessor, gltf2::Accessor::Sparse>("sparse", json::ObjectReader<gltf2::Accessor::Sparse>::Read, &gltf2::Accessor::SetSparse)));
125
126 const auto IMAGE_READER = std::move(json::Reader<gltf2::Image>()
127                                       .Register(*new json::Property<gltf2::Image, std::string_view>("name", json::Read::StringView, &gltf2::Material::mName))
128                                       .Register(*json::MakeProperty("uri", json::Read::StringView, &gltf2::Image::mUri))
129                                       .Register(*json::MakeProperty("mimeType", json::Read::StringView, &gltf2::Image::mMimeType))
130                                       .Register(*json::MakeProperty("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::Image::mBufferView)));
131
132 const auto SAMPLER_READER = std::move(json::Reader<gltf2::Sampler>()
133                                         .Register(*json::MakeProperty("minFilter", json::Read::Enum<gltf2::Filter::Type>, &gltf2::Sampler::mMinFilter))
134                                         .Register(*json::MakeProperty("magFilter", json::Read::Enum<gltf2::Filter::Type>, &gltf2::Sampler::mMagFilter))
135                                         .Register(*json::MakeProperty("wrapS", json::Read::Enum<gltf2::Wrap::Type>, &gltf2::Sampler::mWrapS))
136                                         .Register(*json::MakeProperty("wrapT", json::Read::Enum<gltf2::Wrap::Type>, &gltf2::Sampler::mWrapT)));
137
138 const auto TEXURE_READER = std::move(json::Reader<gltf2::Texture>()
139                                        .Register(*json::MakeProperty("source", gltf2::RefReader<gltf2::Document>::Read<gltf2::Image, &gltf2::Document::mImages>, &gltf2::Texture::mSource))
140                                        .Register(*json::MakeProperty("sampler", gltf2::RefReader<gltf2::Document>::Read<gltf2::Sampler, &gltf2::Document::mSamplers>, &gltf2::Texture::mSampler)));
141
142 const auto TEXURE_INFO_READER = std::move(json::Reader<gltf2::TextureInfo>()
143                                             .Register(*json::MakeProperty("index", gltf2::RefReader<gltf2::Document>::Read<gltf2::Texture, &gltf2::Document::mTextures>, &gltf2::TextureInfo::mTexture))
144                                             .Register(*json::MakeProperty("texCoord", json::Read::Number<uint32_t>, &gltf2::TextureInfo::mTexCoord))
145                                             .Register(*json::MakeProperty("scale", json::Read::Number<float>, &gltf2::TextureInfo::mScale))
146                                             .Register(*json::MakeProperty("strength", json::Read::Number<float>, &gltf2::TextureInfo::mStrength)));
147
148 const auto MATERIAL_PBR_READER = std::move(json::Reader<gltf2::Material::Pbr>()
149                                              .Register(*json::MakeProperty("baseColorFactor", gltf2::ReadDaliVector<Vector4>, &gltf2::Material::Pbr::mBaseColorFactor))
150                                              .Register(*json::MakeProperty("baseColorTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::Pbr::mBaseColorTexture))
151                                              .Register(*json::MakeProperty("metallicFactor", json::Read::Number<float>, &gltf2::Material::Pbr::mMetallicFactor))
152                                              .Register(*json::MakeProperty("roughnessFactor", json::Read::Number<float>, &gltf2::Material::Pbr::mRoughnessFactor))
153                                              .Register(*json::MakeProperty("metallicRoughnessTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::Pbr::mMetallicRoughnessTexture)));
154
155 const auto MATERIAL_SPECULAR_READER = std::move(json::Reader<gltf2::MaterialSpecular>()
156                                                   .Register(*json::MakeProperty("specularFactor", json::Read::Number<float>, &gltf2::MaterialSpecular::mSpecularFactor))
157                                                   .Register(*json::MakeProperty("specularTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::MaterialSpecular::mSpecularTexture))
158                                                   .Register(*json::MakeProperty("specularColorFactor", gltf2::ReadDaliVector<Vector3>, &gltf2::MaterialSpecular::mSpecularColorFactor))
159                                                   .Register(*json::MakeProperty("specularColorTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::MaterialSpecular::mSpecularColorTexture)));
160
161 const auto MATERIAL_IOR_READER = std::move(json::Reader<gltf2::MaterialIor>()
162                                              .Register(*json::MakeProperty("ior", json::Read::Number<float>, &gltf2::MaterialIor::mIor)));
163
164 const auto MATERIAL_EXTENSION_READER = std::move(json::Reader<gltf2::MaterialExtensions>()
165                                                    .Register(*json::MakeProperty("KHR_materials_ior", json::ObjectReader<gltf2::MaterialIor>::Read, &gltf2::MaterialExtensions::mMaterialIor))
166                                                    .Register(*json::MakeProperty("KHR_materials_specular", json::ObjectReader<gltf2::MaterialSpecular>::Read, &gltf2::MaterialExtensions::mMaterialSpecular)));
167
168 const auto MATERIAL_READER = std::move(json::Reader<gltf2::Material>()
169                                          .Register(*new json::Property<gltf2::Material, std::string_view>("name", json::Read::StringView, &gltf2::Material::mName))
170                                          .Register(*json::MakeProperty("pbrMetallicRoughness", json::ObjectReader<gltf2::Material::Pbr>::Read, &gltf2::Material::mPbrMetallicRoughness))
171                                          .Register(*json::MakeProperty("normalTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mNormalTexture))
172                                          .Register(*json::MakeProperty("occlusionTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mOcclusionTexture))
173                                          .Register(*json::MakeProperty("emissiveTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mEmissiveTexture))
174                                          .Register(*json::MakeProperty("emissiveFactor", gltf2::ReadDaliVector<Vector3>, &gltf2::Material::mEmissiveFactor))
175                                          .Register(*json::MakeProperty("alphaMode", gltf2::ReadStringEnum<gltf2::AlphaMode>, &gltf2::Material::mAlphaMode))
176                                          .Register(*json::MakeProperty("alphaCutoff", json::Read::Number<float>, &gltf2::Material::mAlphaCutoff))
177                                          .Register(*json::MakeProperty("doubleSided", json::Read::Boolean, &gltf2::Material::mDoubleSided))
178                                          .Register(*json::MakeProperty("extensions", json::ObjectReader<gltf2::MaterialExtensions>::Read, &gltf2::Material::mMaterialExtensions)));
179
180 std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
181 {
182   auto&                                                         jo = json::Cast<json_object_s>(j);
183   std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>> result;
184
185   auto i = jo.start;
186   while(i)
187   {
188     auto jstr                                                           = *i->name;
189     result[gltf2::Attribute::FromString(jstr.string, jstr.string_size)] = gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>(*i->value);
190     i                                                                   = i->next;
191   }
192   return result;
193 }
194
195 std::vector<std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
196 {
197   auto&                                                                      jo = json::Cast<json_array_s>(j);
198   std::vector<std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>>> result;
199
200   result.reserve(jo.length);
201
202   auto i = jo.start;
203   while(i)
204   {
205     result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
206     i = i->next;
207   }
208
209   return result;
210 }
211
212 const auto MESH_PRIMITIVE_READER = std::move(json::Reader<gltf2::Mesh::Primitive>()
213                                                .Register(*json::MakeProperty("attributes", ReadMeshPrimitiveAttributes, &gltf2::Mesh::Primitive::mAttributes))
214                                                .Register(*json::MakeProperty("indices", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Mesh::Primitive::mIndices))
215                                                .Register(*json::MakeProperty("material", gltf2::RefReader<gltf2::Document>::Read<gltf2::Material, &gltf2::Document::mMaterials>, &gltf2::Mesh::Primitive::mMaterial))
216                                                .Register(*json::MakeProperty("mode", json::Read::Enum<gltf2::Mesh::Primitive::Mode>, &gltf2::Mesh::Primitive::mMode))
217                                                .Register(*json::MakeProperty("targets", ReadMeshPrimitiveTargets, &gltf2::Mesh::Primitive::mTargets)));
218
219 const auto MESH_READER = std::move(json::Reader<gltf2::Mesh>()
220                                      .Register(*new json::Property<gltf2::Mesh, std::string_view>("name", json::Read::StringView, &gltf2::Mesh::mName))
221                                      .Register(*json::MakeProperty("primitives",
222                                                                    json::Read::Array<gltf2::Mesh::Primitive, json::ObjectReader<gltf2::Mesh::Primitive>::Read>,
223                                                                    &gltf2::Mesh::mPrimitives))
224                                      .Register(*json::MakeProperty("weights", json::Read::Array<float, json::Read::Number>, &gltf2::Mesh::mWeights)));
225
226 const auto SKIN_READER = std::move(json::Reader<gltf2::Skin>()
227                                      .Register(*new json::Property<gltf2::Skin, std::string_view>("name", json::Read::StringView, &gltf2::Skin::mName))
228                                      .Register(*json::MakeProperty("inverseBindMatrices",
229                                                                    gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>,
230                                                                    &gltf2::Skin::mInverseBindMatrices))
231                                      .Register(*json::MakeProperty("skeleton",
232                                                                    gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>,
233                                                                    &gltf2::Skin::mSkeleton))
234                                      .Register(*json::MakeProperty("joints",
235                                                                    json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>,
236                                                                    &gltf2::Skin::mJoints)));
237
238 const auto CAMERA_PERSPECTIVE_READER = std::move(json::Reader<gltf2::Camera::Perspective>()
239                                                    .Register(*json::MakeProperty("aspectRatio", json::Read::Number<float>, &gltf2::Camera::Perspective::mAspectRatio))
240                                                    .Register(*json::MakeProperty("yfov", json::Read::Number<float>, &gltf2::Camera::Perspective::mYFov))
241                                                    .Register(*json::MakeProperty("zfar", json::Read::Number<float>, &gltf2::Camera::Perspective::mZFar))
242                                                    .Register(*json::MakeProperty("znear", json::Read::Number<float>, &gltf2::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
243
244 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(json::Reader<gltf2::Camera::Orthographic>()
245                                                     .Register(*json::MakeProperty("xmag", json::Read::Number<float>, &gltf2::Camera::Orthographic::mXMag))
246                                                     .Register(*json::MakeProperty("ymag", json::Read::Number<float>, &gltf2::Camera::Orthographic::mYMag))
247                                                     .Register(*json::MakeProperty("zfar", json::Read::Number<float>, &gltf2::Camera::Orthographic::mZFar))
248                                                     .Register(*json::MakeProperty("znear", json::Read::Number<float>, &gltf2::Camera::Orthographic::mZNear)));
249
250 const auto CAMERA_READER = std::move(json::Reader<gltf2::Camera>()
251                                        .Register(*new json::Property<gltf2::Camera, std::string_view>("name", json::Read::StringView, &gltf2::Camera::mName))
252                                        .Register(*json::MakeProperty("type", json::Read::StringView, &gltf2::Camera::mType))
253                                        .Register(*json::MakeProperty("perspective", json::ObjectReader<gltf2::Camera::Perspective>::Read, &gltf2::Camera::mPerspective))
254                                        .Register(*json::MakeProperty("orthographic", json::ObjectReader<gltf2::Camera::Orthographic>::Read, &gltf2::Camera::mOrthographic)));
255
256 const auto NODE_READER = std::move(json::Reader<gltf2::Node>()
257                                      .Register(*new json::Property<gltf2::Node, std::string_view>("name", json::Read::StringView, &gltf2::Node::mName))
258                                      .Register(*json::MakeProperty("translation", gltf2::ReadDaliVector<Vector3>, &gltf2::Node::mTranslation))
259                                      .Register(*json::MakeProperty("rotation", gltf2::ReadQuaternion, &gltf2::Node::mRotation))
260                                      .Register(*json::MakeProperty("scale", gltf2::ReadDaliVector<Vector3>, &gltf2::Node::mScale))
261                                      .Register(*new json::Property<gltf2::Node, Matrix>("matrix", gltf2::ReadDaliVector<Matrix>, &gltf2::Node::SetMatrix))
262                                      .Register(*json::MakeProperty("camera", gltf2::RefReader<gltf2::Document>::Read<gltf2::Camera, &gltf2::Document::mCameras>, &gltf2::Node::mCamera))
263                                      .Register(*json::MakeProperty("children", json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>, &gltf2::Node::mChildren))
264                                      .Register(*json::MakeProperty("mesh", gltf2::RefReader<gltf2::Document>::Read<gltf2::Mesh, &gltf2::Document::mMeshes>, &gltf2::Node::mMesh))
265                                      .Register(*json::MakeProperty("skin", gltf2::RefReader<gltf2::Document>::Read<gltf2::Skin, &gltf2::Document::mSkins>, &gltf2::Node::mSkin)));
266
267 const auto ANIMATION_SAMPLER_READER = std::move(json::Reader<gltf2::Animation::Sampler>()
268                                                   .Register(*json::MakeProperty("input", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Animation::Sampler::mInput))
269                                                   .Register(*json::MakeProperty("output", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Animation::Sampler::mOutput))
270                                                   .Register(*json::MakeProperty("interpolation", gltf2::ReadStringEnum<gltf2::Animation::Sampler::Interpolation>, &gltf2::Animation::Sampler::mInterpolation)));
271
272 const auto ANIMATION_TARGET_READER = std::move(json::Reader<gltf2::Animation::Channel::Target>()
273                                                  .Register(*json::MakeProperty("node", gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>, &gltf2::Animation::Channel::Target::mNode))
274                                                  .Register(*json::MakeProperty("path", gltf2::ReadStringEnum<gltf2::Animation::Channel::Target>, &gltf2::Animation::Channel::Target::mPath)));
275
276 const auto ANIMATION_CHANNEL_READER = std::move(json::Reader<gltf2::Animation::Channel>()
277                                                   .Register(*json::MakeProperty("target", json::ObjectReader<gltf2::Animation::Channel::Target>::Read, &gltf2::Animation::Channel::mTarget))
278                                                   .Register(*json::MakeProperty("sampler", gltf2::RefReader<gltf2::Animation>::Read<gltf2::Animation::Sampler, &gltf2::Animation::mSamplers>, &gltf2::Animation::Channel::mSampler)));
279
280 const auto ANIMATION_READER = std::move(json::Reader<gltf2::Animation>()
281                                           .Register(*new json::Property<gltf2::Animation, std::string_view>("name", json::Read::StringView, &gltf2::Animation::mName))
282                                           .Register(*json::MakeProperty("samplers",
283                                                                         json::Read::Array<gltf2::Animation::Sampler, json::ObjectReader<gltf2::Animation::Sampler>::Read>,
284                                                                         &gltf2::Animation::mSamplers))
285                                           .Register(*json::MakeProperty("channels",
286                                                                         json::Read::Array<gltf2::Animation::Channel, json::ObjectReader<gltf2::Animation::Channel>::Read>,
287                                                                         &gltf2::Animation::mChannels)));
288
289 const auto SCENE_READER = std::move(json::Reader<gltf2::Scene>()
290                                       .Register(*new json::Property<gltf2::Scene, std::string_view>("name", json::Read::StringView, &gltf2::Scene::mName))
291                                       .Register(*json::MakeProperty("nodes",
292                                                                     json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>,
293                                                                     &gltf2::Scene::mNodes)));
294
295 const auto DOCUMENT_READER = std::move(json::Reader<gltf2::Document>()
296                                          .Register(*json::MakeProperty("buffers",
297                                                                        json::Read::Array<gltf2::Buffer, json::ObjectReader<gltf2::Buffer>::Read>,
298                                                                        &gltf2::Document::mBuffers))
299                                          .Register(*json::MakeProperty("bufferViews",
300                                                                        json::Read::Array<gltf2::BufferView, json::ObjectReader<gltf2::BufferView>::Read>,
301                                                                        &gltf2::Document::mBufferViews))
302                                          .Register(*json::MakeProperty("accessors",
303                                                                        json::Read::Array<gltf2::Accessor, json::ObjectReader<gltf2::Accessor>::Read>,
304                                                                        &gltf2::Document::mAccessors))
305                                          .Register(*json::MakeProperty("images",
306                                                                        json::Read::Array<gltf2::Image, json::ObjectReader<gltf2::Image>::Read>,
307                                                                        &gltf2::Document::mImages))
308                                          .Register(*json::MakeProperty("samplers",
309                                                                        json::Read::Array<gltf2::Sampler, json::ObjectReader<gltf2::Sampler>::Read>,
310                                                                        &gltf2::Document::mSamplers))
311                                          .Register(*json::MakeProperty("textures",
312                                                                        json::Read::Array<gltf2::Texture, json::ObjectReader<gltf2::Texture>::Read>,
313                                                                        &gltf2::Document::mTextures))
314                                          .Register(*json::MakeProperty("materials",
315                                                                        json::Read::Array<gltf2::Material, json::ObjectReader<gltf2::Material>::Read>,
316                                                                        &gltf2::Document::mMaterials))
317                                          .Register(*json::MakeProperty("meshes",
318                                                                        json::Read::Array<gltf2::Mesh, json::ObjectReader<gltf2::Mesh>::Read>,
319                                                                        &gltf2::Document::mMeshes))
320                                          .Register(*json::MakeProperty("skins",
321                                                                        json::Read::Array<gltf2::Skin, json::ObjectReader<gltf2::Skin>::Read>,
322                                                                        &gltf2::Document::mSkins))
323                                          .Register(*json::MakeProperty("cameras",
324                                                                        json::Read::Array<gltf2::Camera, json::ObjectReader<gltf2::Camera>::Read>,
325                                                                        &gltf2::Document::mCameras))
326                                          .Register(*json::MakeProperty("nodes",
327                                                                        json::Read::Array<gltf2::Node, json::ObjectReader<gltf2::Node>::Read>,
328                                                                        &gltf2::Document::mNodes))
329                                          .Register(*json::MakeProperty("animations",
330                                                                        ReadAnimationArray,
331                                                                        &gltf2::Document::mAnimations))
332                                          .Register(*json::MakeProperty("scenes",
333                                                                        json::Read::Array<gltf2::Scene, json::ObjectReader<gltf2::Scene>::Read>,
334                                                                        &gltf2::Document::mScenes))
335                                          .Register(*json::MakeProperty("scene", gltf2::RefReader<gltf2::Document>::Read<gltf2::Scene, &gltf2::Document::mScenes>, &gltf2::Document::mScene)));
336
337 void ConvertBuffer(const gltf2::Buffer& buffer, decltype(ResourceBundle::mBuffers)& outBuffers, const std::string& resourcePath)
338 {
339   BufferDefinition bufferDefinition;
340
341   bufferDefinition.mResourcePath = resourcePath;
342   bufferDefinition.mUri          = buffer.mUri;
343   bufferDefinition.mByteLength   = buffer.mByteLength;
344
345   outBuffers.emplace_back(std::move(bufferDefinition));
346 }
347
348 void ConvertBuffers(const gltf2::Document& doc, ConversionContext& context)
349 {
350   auto& outBuffers = context.mOutput.mResources.mBuffers;
351   outBuffers.reserve(doc.mBuffers.size());
352
353   for(auto& buffer : doc.mBuffers)
354   {
355     if(buffer.mUri.empty())
356     {
357       continue;
358     }
359     ConvertBuffer(buffer, outBuffers, context.mPath);
360   }
361 }
362
363 SamplerFlags::Type ConvertWrapMode(gltf2::Wrap::Type wrapMode)
364 {
365   switch(wrapMode)
366   {
367     case gltf2::Wrap::REPEAT:
368       return SamplerFlags::WRAP_REPEAT;
369     case gltf2::Wrap::CLAMP_TO_EDGE:
370       return SamplerFlags::WRAP_CLAMP;
371     case gltf2::Wrap::MIRRORED_REPEAT:
372       return SamplerFlags::WRAP_MIRROR;
373     default:
374       throw std::runtime_error("Invalid wrap type.");
375   }
376 }
377
378 SamplerFlags::Type ConvertSampler(const gltf2::Ref<gltf2::Sampler>& sampler)
379 {
380   if(sampler)
381   {
382     return ((sampler->mMinFilter < gltf2::Filter::NEAREST_MIPMAP_NEAREST) ? (sampler->mMinFilter - gltf2::Filter::NEAREST) : ((sampler->mMinFilter - gltf2::Filter::NEAREST_MIPMAP_NEAREST) + 2)) |
383            ((sampler->mMagFilter - gltf2::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) |
384            (ConvertWrapMode(sampler->mWrapS) << SamplerFlags::WRAP_S_SHIFT) |
385            (ConvertWrapMode(sampler->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
386   }
387   else
388   {
389     // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
390     // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
391     // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
392     // properties, if not in some extension -, we will simply assume linear filtering.
393     return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
394            (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
395   }
396 }
397
398 TextureDefinition ConvertTextureInfo(const gltf2::TextureInfo& mm, ConversionContext& context, const ImageMetadata& metaData = ImageMetadata())
399 {
400   TextureDefinition textureDefinition;
401   std::string       uri = std::string(mm.mTexture->mSource->mUri);
402   if(uri.empty())
403   {
404     uint32_t bufferIndex = mm.mTexture->mSource->mBufferView->mBuffer.GetIndex();
405     if(bufferIndex != INVALID_INDEX && context.mOutput.mResources.mBuffers[bufferIndex].IsAvailable())
406     {
407       auto& stream = context.mOutput.mResources.mBuffers[bufferIndex].GetBufferStream();
408       stream.clear();
409       stream.seekg(mm.mTexture->mSource->mBufferView->mByteOffset, stream.beg);
410       std::vector<uint8_t> dataBuffer;
411       dataBuffer.resize(mm.mTexture->mSource->mBufferView->mByteLength);
412       stream.read(reinterpret_cast<char*>(dataBuffer.data()), static_cast<std::streamsize>(static_cast<size_t>(mm.mTexture->mSource->mBufferView->mByteLength)));
413       return TextureDefinition{std::move(dataBuffer), ConvertSampler(mm.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
414     }
415     return TextureDefinition();
416   }
417   else
418   {
419     return TextureDefinition{uri, ConvertSampler(mm.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
420   }
421 }
422
423 void ConvertMaterial(const gltf2::Material& material, const std::unordered_map<std::string, ImageMetadata>& imageMetaData, decltype(ResourceBundle::mMaterials)& outMaterials, ConversionContext& context)
424 {
425   auto getTextureMetaData = [](const std::unordered_map<std::string, ImageMetadata>& metaData, const gltf2::TextureInfo& info) {
426     if(!info.mTexture->mSource->mUri.empty())
427     {
428       if(auto search = metaData.find(info.mTexture->mSource->mUri.data()); search != metaData.end())
429       {
430         return search->second;
431       }
432     }
433     return ImageMetadata();
434   };
435
436   MaterialDefinition matDef;
437
438   auto& pbr = material.mPbrMetallicRoughness;
439   if(material.mAlphaMode == gltf2::AlphaMode::BLEND)
440   {
441     matDef.mIsOpaque = false;
442     matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
443   }
444   else if(material.mAlphaMode == gltf2::AlphaMode::MASK)
445   {
446     matDef.mIsMask = true;
447     matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, material.mAlphaCutoff)));
448   }
449
450   matDef.mBaseColorFactor = pbr.mBaseColorFactor;
451
452   matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!material.mNormalTexture + !!material.mOcclusionTexture + !!material.mEmissiveTexture);
453   if(pbr.mBaseColorTexture)
454   {
455     const auto semantic = MaterialDefinition::ALBEDO;
456     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture, context, getTextureMetaData(imageMetaData, pbr.mBaseColorTexture))});
457     // TODO: and there had better be one
458     matDef.mFlags |= semantic;
459   }
460   else
461   {
462     matDef.mNeedAlbedoTexture = false;
463   }
464
465   matDef.mMetallic  = pbr.mMetallicFactor;
466   matDef.mRoughness = pbr.mRoughnessFactor;
467
468   if(pbr.mMetallicRoughnessTexture)
469   {
470     const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
471                           MaterialDefinition::GLTF_CHANNELS;
472     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture, context, getTextureMetaData(imageMetaData, pbr.mMetallicRoughnessTexture))});
473     // TODO: and there had better be one
474     matDef.mFlags |= semantic;
475   }
476   else
477   {
478     matDef.mNeedMetallicRoughnessTexture = false;
479   }
480
481   matDef.mNormalScale = material.mNormalTexture.mScale;
482   if(material.mNormalTexture)
483   {
484     const auto semantic = MaterialDefinition::NORMAL;
485     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mNormalTexture, context, getTextureMetaData(imageMetaData, material.mNormalTexture))});
486     // TODO: and there had better be one
487     matDef.mFlags |= semantic;
488   }
489   else
490   {
491     matDef.mNeedNormalTexture = false;
492   }
493
494   if(material.mOcclusionTexture)
495   {
496     const auto semantic = MaterialDefinition::OCCLUSION;
497     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mOcclusionTexture, context, getTextureMetaData(imageMetaData, material.mOcclusionTexture))});
498     // TODO: and there had better be one
499     matDef.mFlags |= semantic;
500     matDef.mOcclusionStrength = material.mOcclusionTexture.mStrength;
501   }
502
503   if(material.mEmissiveTexture)
504   {
505     const auto semantic = MaterialDefinition::EMISSIVE;
506     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mEmissiveTexture, context, getTextureMetaData(imageMetaData, material.mEmissiveTexture))});
507     // TODO: and there had better be one
508     matDef.mFlags |= semantic;
509     matDef.mEmissiveFactor = material.mEmissiveFactor;
510   }
511
512   if(!Dali::Equals(material.mMaterialExtensions.mMaterialIor.mIor, gltf2::UNDEFINED_FLOAT_VALUE))
513   {
514     float ior                  = material.mMaterialExtensions.mMaterialIor.mIor;
515     matDef.mDielectricSpecular = powf((ior - 1.0f) / (ior + 1.0f), 2.0f);
516   }
517   matDef.mSpecularFactor      = material.mMaterialExtensions.mMaterialSpecular.mSpecularFactor;
518   matDef.mSpecularColorFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularColorFactor;
519
520   if(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)
521   {
522     const auto semantic = MaterialDefinition::SPECULAR;
523     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture, context, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture))});
524     matDef.mFlags |= semantic;
525   }
526
527   if(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)
528   {
529     const auto semantic = MaterialDefinition::SPECULAR_COLOR;
530     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture, context, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture))});
531     matDef.mFlags |= semantic;
532   }
533
534   matDef.mDoubleSided = material.mDoubleSided;
535
536   outMaterials.emplace_back(std::move(matDef), TextureSet());
537 }
538
539 void ConvertMaterials(const gltf2::Document& doc, ConversionContext& context)
540 {
541   auto& imageMetaData = context.mOutput.mSceneMetadata.mImageMetadata;
542
543   auto& outMaterials = context.mOutput.mResources.mMaterials;
544   outMaterials.reserve(doc.mMaterials.size());
545
546   for(auto& m : doc.mMaterials)
547   {
548     ConvertMaterial(m, imageMetaData, outMaterials, context);
549   }
550 }
551
552 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gltf2::Accessor& acc)
553 {
554   DALI_ASSERT_ALWAYS((acc.mBufferView &&
555                       (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
556                      (acc.mSparse && !acc.mBufferView));
557
558   DALI_ASSERT_ALWAYS(!acc.mSparse ||
559                      ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
560                       (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
561
562   MeshDefinition::SparseBlob sparseBlob;
563   if(acc.mSparse)
564   {
565     const gltf2::Accessor::Sparse&               sparse  = *acc.mSparse;
566     const gltf2::ComponentTypedBufferViewClient& indices = sparse.mIndices;
567     const gltf2::BufferViewClient&               values  = sparse.mValues;
568
569     MeshDefinition::Blob indicesBlob(
570       indices.mBufferView->mByteOffset + indices.mByteOffset,
571       sparse.mCount * indices.GetBytesPerComponent(),
572       static_cast<uint16_t>(indices.mBufferView->mByteStride),
573       static_cast<uint16_t>(indices.GetBytesPerComponent()),
574       {},
575       {});
576     MeshDefinition::Blob valuesBlob(
577       values.mBufferView->mByteOffset + values.mByteOffset,
578       sparse.mCount * acc.GetElementSizeBytes(),
579       static_cast<uint16_t>(values.mBufferView->mByteStride),
580       static_cast<uint16_t>(acc.GetElementSizeBytes()),
581       {},
582       {});
583
584     sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
585   }
586
587   uint32_t bufferViewOffset = 0u;
588   uint32_t bufferViewStride = 0u;
589   if(acc.mBufferView)
590   {
591     bufferViewOffset = acc.mBufferView->mByteOffset;
592     bufferViewStride = acc.mBufferView->mByteStride;
593   }
594
595   return MeshDefinition::Accessor{
596     std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
597                                    acc.GetBytesLength(),
598                                    static_cast<uint16_t>(bufferViewStride),
599                                    static_cast<uint16_t>(acc.GetElementSizeBytes()),
600                                    acc.mMin,
601                                    acc.mMax}),
602     std::move(sparseBlob),
603     acc.mBufferView ? acc.mBufferView->mBuffer.GetIndex() : 0};
604 }
605
606 void ConvertMeshes(const gltf2::Document& doc, ConversionContext& context)
607 {
608   uint32_t meshCount = 0;
609   context.mMeshIds.reserve(doc.mMeshes.size());
610   for(auto& mesh : doc.mMeshes)
611   {
612     context.mMeshIds.push_back(meshCount);
613     meshCount += mesh.mPrimitives.size();
614   }
615
616   auto& outMeshes = context.mOutput.mResources.mMeshes;
617   outMeshes.reserve(meshCount);
618   for(auto& mesh : doc.mMeshes)
619   {
620     for(auto& primitive : mesh.mPrimitives)
621     {
622       MeshDefinition meshDefinition;
623
624       auto& attribs                 = primitive.mAttributes;
625       meshDefinition.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[primitive.mMode];
626
627       auto& accPositions        = *attribs.find(gltf2::Attribute::POSITION)->second;
628       meshDefinition.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
629       // glTF2 support vector4 tangent for mesh.
630       // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
631       meshDefinition.mTangentType = Property::VECTOR4;
632
633       const bool needNormalsTangents = accPositions.mType == gltf2::AccessorType::VEC3;
634       for(auto& am : ATTRIBUTE_MAPPINGS)
635       {
636         auto iFind = attribs.find(am.mType);
637         if(iFind != attribs.end())
638         {
639           auto& accessor = meshDefinition.*(am.mAccessor);
640           accessor       = ConvertMeshPrimitiveAccessor(*iFind->second);
641
642           if(iFind->first == gltf2::Attribute::JOINTS_0)
643           {
644             meshDefinition.mFlags |= (iFind->second->mComponentType == gltf2::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
645             meshDefinition.mFlags |= (iFind->second->mComponentType == gltf2::Component::UNSIGNED_BYTE) * MeshDefinition::U8_JOINT_IDS;
646             DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U16_JOINT_IDS) || MaskMatch(meshDefinition.mFlags, MeshDefinition::U8_JOINT_IDS) || iFind->second->mComponentType == gltf2::Component::FLOAT);
647           }
648         }
649         else if(needNormalsTangents)
650         {
651           switch(am.mType)
652           {
653             case gltf2::Attribute::NORMAL:
654               meshDefinition.RequestNormals();
655               break;
656
657             case gltf2::Attribute::TANGENT:
658               meshDefinition.RequestTangents();
659               break;
660
661             default:
662               break;
663           }
664         }
665       }
666
667       if(primitive.mIndices)
668       {
669         meshDefinition.mIndices = ConvertMeshPrimitiveAccessor(*primitive.mIndices);
670         meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
671         meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_BYTE) * MeshDefinition::U8_INDICES;
672         DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U32_INDICES) || MaskMatch(meshDefinition.mFlags, MeshDefinition::U8_INDICES) || primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_SHORT);
673       }
674
675       if(!primitive.mTargets.empty())
676       {
677         meshDefinition.mBlendShapes.reserve(primitive.mTargets.size());
678         meshDefinition.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
679         for(const auto& target : primitive.mTargets)
680         {
681           MeshDefinition::BlendShape blendShape;
682
683           auto endIt = target.end();
684           auto it    = target.find(gltf2::Attribute::POSITION);
685           if(it != endIt)
686           {
687             blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
688           }
689           it = target.find(gltf2::Attribute::NORMAL);
690           if(it != endIt)
691           {
692             blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
693           }
694           it = target.find(gltf2::Attribute::TANGENT);
695           if(it != endIt)
696           {
697             blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
698           }
699
700           if(!mesh.mWeights.empty())
701           {
702             blendShape.weight = mesh.mWeights[meshDefinition.mBlendShapes.size()];
703           }
704
705           meshDefinition.mBlendShapes.push_back(std::move(blendShape));
706         }
707       }
708
709       outMeshes.push_back({std::move(meshDefinition), MeshGeometry{}});
710     }
711   }
712 }
713
714 ModelRenderable* MakeModelRenderable(const gltf2::Mesh::Primitive& prim, ConversionContext& context)
715 {
716   auto modelRenderable = new ModelRenderable();
717
718   modelRenderable->mShaderIdx = 0; // TODO: further thought
719
720   auto materialIdx = prim.mMaterial.GetIndex();
721   if(INVALID_INDEX == materialIdx)
722   {
723     // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
724     if(INVALID_INDEX == context.mDefaultMaterial)
725     {
726       auto& outMaterials       = context.mOutput.mResources.mMaterials;
727       context.mDefaultMaterial = outMaterials.size();
728
729       ConvertMaterial(gltf2::Material{}, context.mOutput.mSceneMetadata.mImageMetadata, outMaterials, context);
730     }
731
732     materialIdx = context.mDefaultMaterial;
733   }
734
735   modelRenderable->mMaterialIdx = materialIdx;
736
737   return modelRenderable;
738 }
739
740 void ConvertCamera(const gltf2::Camera& camera, CameraParameters& camParams)
741 {
742   camParams.isPerspective = camera.mType.compare("perspective") == 0;
743   if(camParams.isPerspective)
744   {
745     auto& perspective = camera.mPerspective;
746     if(!Dali::Equals(perspective.mYFov, gltf2::UNDEFINED_FLOAT_VALUE))
747     {
748       camParams.yFovDegree = Degree(Radian(perspective.mYFov));
749     }
750     else
751     {
752       camParams.yFovDegree = Degree(gltf2::UNDEFINED_FLOAT_VALUE);
753     }
754     camParams.zNear = perspective.mZNear;
755     camParams.zFar  = perspective.mZFar;
756     // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
757   }
758   else
759   {
760     auto& ortho = camera.mOrthographic;
761     if(!Dali::Equals(ortho.mYMag, gltf2::UNDEFINED_FLOAT_VALUE) && !Dali::Equals(ortho.mXMag, gltf2::UNDEFINED_FLOAT_VALUE))
762     {
763       camParams.orthographicSize = ortho.mYMag * .5f;
764       camParams.aspectRatio      = ortho.mXMag / ortho.mYMag;
765     }
766     else
767     {
768       camParams.orthographicSize = gltf2::UNDEFINED_FLOAT_VALUE;
769       camParams.aspectRatio      = gltf2::UNDEFINED_FLOAT_VALUE;
770     }
771     camParams.zNear = ortho.mZNear;
772     camParams.zFar  = ortho.mZFar;
773   }
774 }
775
776 void ConvertNode(gltf2::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& context, bool isMRendererModel)
777 {
778   auto& output    = context.mOutput;
779   auto& scene     = output.mScene;
780   auto& resources = output.mResources;
781
782   const auto idx      = scene.GetNodeCount();
783   auto       weakNode = scene.AddNode([&]() {
784     std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
785
786     nodeDef->mParentIdx = parentIdx;
787     nodeDef->mName      = node.mName;
788     if(nodeDef->mName.empty())
789     {
790       // TODO: Production quality generation of unique names.
791       nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
792     }
793
794     if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
795     {
796       nodeDef->mPosition    = node.mTranslation;
797       nodeDef->mOrientation = node.mRotation;
798       nodeDef->mScale       = node.mScale;
799
800       if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
801       {
802         nodeDef->mScale *= 0.01f;
803       }
804     }
805
806     return nodeDef; }());
807   if(!weakNode)
808   {
809     ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
810   }
811
812   context.mNodeIndices.RegisterMapping(gltfIdx, idx);
813
814   Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
815   if(node.mMesh)
816   {
817     auto&    mesh           = *node.mMesh;
818     uint32_t primitiveCount = mesh.mPrimitives.size();
819     auto     meshIdx        = context.mMeshIds[node.mMesh.GetIndex()];
820     weakNode->mRenderables.reserve(primitiveCount);
821     for(uint32_t i = 0; i < primitiveCount; ++i)
822     {
823       std::unique_ptr<NodeDefinition::Renderable> renderable;
824       auto                                        modelRenderable = MakeModelRenderable(mesh.mPrimitives[i], context);
825       modelRenderable->mMeshIdx                                   = meshIdx + i;
826
827       DALI_ASSERT_DEBUG(resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == INVALID_INDEX ||
828                         resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == skeletonIdx);
829       resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx = skeletonIdx;
830
831       renderable.reset(modelRenderable);
832       weakNode->mRenderables.push_back(std::move(renderable));
833     }
834   }
835
836   if(node.mCamera)
837   {
838     CameraParameters camParams;
839     ConvertCamera(*node.mCamera, camParams);
840
841     camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
842     output.mCameraParameters.push_back(camParams);
843   }
844
845   for(auto& n : node.mChildren)
846   {
847     ConvertNode(*n, n.GetIndex(), idx, context, isMRendererModel);
848   }
849 }
850
851 void ConvertSceneNodes(const gltf2::Scene& scene, ConversionContext& context, bool isMRendererModel)
852 {
853   auto& outScene = context.mOutput.mScene;
854   Index rootIdx  = outScene.GetNodeCount();
855   switch(scene.mNodes.size())
856   {
857     case 0:
858       break;
859
860     case 1:
861       ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, context, isMRendererModel);
862       outScene.AddRootNode(rootIdx);
863       break;
864
865     default:
866     {
867       std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
868       sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
869
870       outScene.AddNode(std::move(sceneRoot));
871       outScene.AddRootNode(rootIdx);
872
873       for(auto& n : scene.mNodes)
874       {
875         ConvertNode(*n, n.GetIndex(), rootIdx, context, isMRendererModel);
876       }
877       break;
878     }
879   }
880 }
881
882 void ConvertNodes(const gltf2::Document& doc, ConversionContext& context, bool isMRendererModel)
883 {
884   if(!doc.mScenes.empty())
885   {
886     uint32_t rootSceneIndex = 0u;
887     if(doc.mScene)
888     {
889       rootSceneIndex = doc.mScene.GetIndex();
890     }
891     ConvertSceneNodes(doc.mScenes[rootSceneIndex], context, isMRendererModel);
892
893     for(uint32_t i = 0, i1 = rootSceneIndex; i < i1; ++i)
894     {
895       ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
896     }
897
898     for(uint32_t i = rootSceneIndex + 1; i < doc.mScenes.size(); ++i)
899     {
900       ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
901     }
902   }
903 }
904
905 template<typename T>
906 void LoadDataFromAccessor(ConversionContext& context, uint32_t bufferIndex, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
907 {
908   if(bufferIndex >= context.mOutput.mResources.mBuffers.size())
909   {
910     DALI_LOG_ERROR("Invailid buffer index\n");
911     return;
912   }
913
914   auto& buffer = context.mOutput.mResources.mBuffers[bufferIndex];
915   if(!buffer.IsAvailable())
916   {
917     DALI_LOG_ERROR("Failed to load from buffer stream.\n");
918   }
919   auto& stream = buffer.GetBufferStream();
920   stream.clear();
921   stream.seekg(offset, stream.beg);
922   stream.read(reinterpret_cast<char*>(dataBuffer.Begin()), static_cast<std::streamsize>(static_cast<size_t>(size)));
923 }
924
925 template<typename T>
926 float LoadDataFromAccessors(ConversionContext& context, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
927 {
928   inputDataBuffer.Resize(input.mCount);
929   outputDataBuffer.Resize(output.mCount);
930
931   const uint32_t inputDataBufferSize  = input.GetBytesLength();
932   const uint32_t outputDataBufferSize = output.GetBytesLength();
933
934   LoadDataFromAccessor<float>(context, output.mBufferView->mBuffer.GetIndex(), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
935   LoadDataFromAccessor<T>(context, output.mBufferView->mBuffer.GetIndex(), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
936   ApplyAccessorMinMax(input, reinterpret_cast<float*>(inputDataBuffer.begin()));
937   ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
938
939   return inputDataBuffer[input.mCount - 1u];
940 }
941
942 template<typename T>
943 float LoadKeyFrames(ConversionContext& context, const gltf2::Animation::Channel& channel, KeyFrames& keyFrames, gltf2::Animation::Channel::Target::Type type)
944 {
945   const gltf2::Accessor& input  = *channel.mSampler->mInput;
946   const gltf2::Accessor& output = *channel.mSampler->mOutput;
947
948   Vector<float> inputDataBuffer;
949   Vector<T>     outputDataBuffer;
950
951   const float duration = std::max(LoadDataFromAccessors<T>(context, input, output, inputDataBuffer, outputDataBuffer), AnimationDefinition::MIN_DURATION_SECONDS);
952
953   // Set first frame value as first keyframe (gltf animation spec)
954   if(input.mCount > 0 && !Dali::EqualsZero(inputDataBuffer[0]))
955   {
956     keyFrames.Add(0.0f, outputDataBuffer[0]);
957   }
958
959   for(uint32_t i = 0; i < input.mCount; ++i)
960   {
961     keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
962   }
963
964   return duration;
965 }
966
967 float LoadBlendShapeKeyFrames(ConversionContext& context, const gltf2::Animation::Channel& channel, Index nodeIndex, uint32_t& propertyIndex, std::vector<Dali::Scene3D::Loader::AnimatedProperty>& properties)
968 {
969   const gltf2::Accessor& input  = *channel.mSampler->mInput;
970   const gltf2::Accessor& output = *channel.mSampler->mOutput;
971
972   Vector<float> inputDataBuffer;
973   Vector<float> outputDataBuffer;
974
975   const float duration = std::max(LoadDataFromAccessors<float>(context, input, output, inputDataBuffer, outputDataBuffer), AnimationDefinition::MIN_DURATION_SECONDS);
976
977   char        weightNameBuffer[32];
978   auto        prefixSize    = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.data());
979   char* const pWeightName   = weightNameBuffer + prefixSize;
980   const auto  remainingSize = sizeof(weightNameBuffer) - prefixSize;
981   for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
982   {
983     AnimatedProperty& animatedProperty = properties[propertyIndex++];
984
985     animatedProperty.mNodeIndex = nodeIndex;
986     snprintf(pWeightName, remainingSize, "%d]", weightIndex);
987     animatedProperty.mPropertyName = std::string(weightNameBuffer);
988
989     animatedProperty.mKeyFrames = KeyFrames::New();
990
991     // Set first frame value as first keyframe (gltf animation spec)
992     if(input.mCount > 0 && !Dali::EqualsZero(inputDataBuffer[0]))
993     {
994       animatedProperty.mKeyFrames.Add(0.0f, outputDataBuffer[weightIndex]);
995     }
996
997     for(uint32_t i = 0; i < input.mCount; ++i)
998     {
999       animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
1000     }
1001
1002     animatedProperty.mTimePeriod = {0.f, duration};
1003   }
1004
1005   return duration;
1006 }
1007
1008 void ConvertAnimations(const gltf2::Document& doc, ConversionContext& context)
1009 {
1010   auto& output = context.mOutput;
1011
1012   output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
1013
1014   for(const auto& animation : doc.mAnimations)
1015   {
1016     AnimationDefinition animationDef;
1017
1018     if(!animation.mName.empty())
1019     {
1020       animationDef.mName = animation.mName;
1021     }
1022
1023     uint32_t numberOfProperties = 0u;
1024     for(const auto& channel : animation.mChannels)
1025     {
1026       if(channel.mTarget.mPath == gltf2::Animation::Channel::Target::WEIGHTS)
1027       {
1028         numberOfProperties += channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount;
1029       }
1030       else
1031       {
1032         numberOfProperties++;
1033       }
1034     }
1035     animationDef.mProperties.resize(numberOfProperties);
1036
1037     Index propertyIndex = 0u;
1038     for(const auto& channel : animation.mChannels)
1039     {
1040       Index nodeIndex = context.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
1041       float duration  = 0.f;
1042
1043       switch(channel.mTarget.mPath)
1044       {
1045         case gltf2::Animation::Channel::Target::TRANSLATION:
1046         {
1047           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1048
1049           animatedProperty.mNodeIndex    = nodeIndex;
1050           animatedProperty.mPropertyName = POSITION_PROPERTY;
1051
1052           animatedProperty.mKeyFrames = KeyFrames::New();
1053           duration                    = LoadKeyFrames<Vector3>(context, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1054
1055           animatedProperty.mTimePeriod = {0.f, duration};
1056           break;
1057         }
1058         case gltf2::Animation::Channel::Target::ROTATION:
1059         {
1060           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1061
1062           animatedProperty.mNodeIndex    = nodeIndex;
1063           animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1064
1065           animatedProperty.mKeyFrames = KeyFrames::New();
1066           duration                    = LoadKeyFrames<Quaternion>(context, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1067
1068           animatedProperty.mTimePeriod = {0.f, duration};
1069           break;
1070         }
1071         case gltf2::Animation::Channel::Target::SCALE:
1072         {
1073           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1074
1075           animatedProperty.mNodeIndex    = nodeIndex;
1076           animatedProperty.mPropertyName = SCALE_PROPERTY;
1077
1078           animatedProperty.mKeyFrames = KeyFrames::New();
1079           duration                    = LoadKeyFrames<Vector3>(context, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1080
1081           animatedProperty.mTimePeriod = {0.f, duration};
1082           break;
1083         }
1084         case gltf2::Animation::Channel::Target::WEIGHTS:
1085         {
1086           duration = LoadBlendShapeKeyFrames(context, channel, nodeIndex, propertyIndex, animationDef.mProperties);
1087
1088           break;
1089         }
1090         default:
1091         {
1092           // nothing to animate.
1093           break;
1094         }
1095       }
1096
1097       animationDef.mDuration = std::max(duration, animationDef.mDuration);
1098
1099       ++propertyIndex;
1100     }
1101
1102     output.mAnimationDefinitions.push_back(std::move(animationDef));
1103   }
1104 }
1105
1106 void ProcessSkins(const gltf2::Document& doc, ConversionContext& context)
1107 {
1108   // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1109   // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1110   // otherwise we'll set identity matrices for inverse bind pose.
1111   struct IInverseBindMatrixProvider
1112   {
1113     virtual ~IInverseBindMatrixProvider()
1114     {
1115     }
1116     virtual void Provide(Matrix& ibm) = 0;
1117   };
1118
1119   struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1120   {
1121     std::istream&  mStream;
1122     const uint32_t mElementSizeBytes;
1123
1124     InverseBindMatrixAccessor(const gltf2::Accessor& accessor, ConversionContext& context)
1125     : mStream(context.mOutput.mResources.mBuffers[accessor.mBufferView->mBuffer.GetIndex()].GetBufferStream()),
1126       mElementSizeBytes(accessor.GetElementSizeBytes())
1127     {
1128       DALI_ASSERT_DEBUG(accessor.mType == gltf2::AccessorType::MAT4 && accessor.mComponentType == gltf2::Component::FLOAT);
1129
1130       if(!mStream.rdbuf()->in_avail())
1131       {
1132         DALI_LOG_ERROR("Failed to load from stream\n");
1133       }
1134       mStream.clear();
1135       mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset, mStream.beg);
1136     }
1137
1138     virtual void Provide(Matrix& ibm) override
1139     {
1140       DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), static_cast<std::streamsize>(static_cast<size_t>(mElementSizeBytes))));
1141     }
1142   };
1143
1144   struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1145   {
1146     virtual void Provide(Matrix& ibm) override
1147     {
1148       ibm = Matrix::IDENTITY;
1149     }
1150   };
1151
1152   auto& resources = context.mOutput.mResources;
1153   resources.mSkeletons.reserve(doc.mSkins.size());
1154
1155   for(auto& skin : doc.mSkins)
1156   {
1157     std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1158     if(skin.mInverseBindMatrices)
1159     {
1160       ibmProvider.reset(new InverseBindMatrixAccessor(*skin.mInverseBindMatrices, context));
1161     }
1162     else
1163     {
1164       ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1165     }
1166
1167     SkeletonDefinition skeleton;
1168     if(skin.mSkeleton.GetIndex() != INVALID_INDEX)
1169     {
1170       skeleton.mRootNodeIdx = context.mNodeIndices.GetRuntimeId(skin.mSkeleton.GetIndex());
1171     }
1172
1173     skeleton.mJoints.resize(skin.mJoints.size());
1174     auto iJoint = skeleton.mJoints.begin();
1175     for(auto& joint : skin.mJoints)
1176     {
1177       iJoint->mNodeIdx = context.mNodeIndices.GetRuntimeId(joint.GetIndex());
1178
1179       ibmProvider->Provide(iJoint->mInverseBindMatrix);
1180
1181       ++iJoint;
1182     }
1183
1184     resources.mSkeletons.push_back(std::move(skeleton));
1185   }
1186 }
1187
1188 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, Dali::Scene3D::Loader::SceneDefinition& scene)
1189 {
1190   uint32_t nodeCount = scene.GetNodeCount();
1191   for(uint32_t i = 0; i < nodeCount; ++i)
1192   {
1193     auto nodeDef = scene.GetNode(i);
1194     for(auto& renderable : nodeDef->mRenderables)
1195     {
1196       if(shaderFactory.ProduceShader(*renderable) == INVALID_INDEX)
1197       {
1198         DALI_LOG_ERROR("Fail to produce shader\n");
1199       }
1200     }
1201   }
1202 }
1203
1204 void SetObjectReaders()
1205 {
1206   json::SetObjectReader(BUFFER_READER);
1207   json::SetObjectReader(BUFFER_VIEW_READER);
1208   json::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1209   json::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1210   json::SetObjectReader(ACCESSOR_SPARSE_READER);
1211   json::SetObjectReader(ACCESSOR_READER);
1212   json::SetObjectReader(IMAGE_READER);
1213   json::SetObjectReader(SAMPLER_READER);
1214   json::SetObjectReader(TEXURE_READER);
1215   json::SetObjectReader(TEXURE_INFO_READER);
1216   json::SetObjectReader(MATERIAL_PBR_READER);
1217   json::SetObjectReader(MATERIAL_SPECULAR_READER);
1218   json::SetObjectReader(MATERIAL_IOR_READER);
1219   json::SetObjectReader(MATERIAL_EXTENSION_READER);
1220   json::SetObjectReader(MATERIAL_READER);
1221   json::SetObjectReader(MESH_PRIMITIVE_READER);
1222   json::SetObjectReader(MESH_READER);
1223   json::SetObjectReader(SKIN_READER);
1224   json::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1225   json::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1226   json::SetObjectReader(CAMERA_READER);
1227   json::SetObjectReader(NODE_READER);
1228   json::SetObjectReader(ANIMATION_SAMPLER_READER);
1229   json::SetObjectReader(ANIMATION_TARGET_READER);
1230   json::SetObjectReader(ANIMATION_CHANNEL_READER);
1231   json::SetObjectReader(ANIMATION_READER);
1232   json::SetObjectReader(SCENE_READER);
1233 }
1234
1235 void SetDefaultEnvironmentMap(const gltf2::Document& doc, ConversionContext& context)
1236 {
1237   EnvironmentDefinition envDef;
1238   envDef.mUseBrdfTexture = true;
1239   envDef.mIblIntensity   = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
1240   context.mOutput.mResources.mEnvironmentMaps.push_back({std::move(envDef), EnvironmentDefinition::Textures()});
1241 }
1242
1243 void InitializeGltfLoader()
1244 {
1245   static Dali::Mutex gInitializeMutex;
1246   // Set ObjectReader only once (for all gltf loading).
1247   static bool setObjectReadersRequired = true;
1248   {
1249     Mutex::ScopedLock lock(gInitializeMutex);
1250     if(setObjectReadersRequired)
1251     {
1252       // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1253       SetObjectReaders();
1254       setObjectReadersRequired = false;
1255     }
1256   }
1257 }
1258
1259 const std::string_view GetRendererModelIdentification()
1260 {
1261   return MRENDERER_MODEL_IDENTIFICATION;
1262 }
1263
1264 void ReadDocument(const json_object_s& jsonObject, gltf2::Document& document)
1265 {
1266   DOCUMENT_READER.Read(jsonObject, document);
1267 }
1268
1269 void ReadDocumentFromParsedData(const json_object_s& jsonObject, gltf2::Document& document)
1270 {
1271   static Dali::Mutex gReadMutex;
1272   Mutex::ScopedLock  lock(gReadMutex);
1273   gt::SetRefReaderObject(document);
1274   Gltf2Util::ReadDocument(jsonObject, document);
1275 }
1276
1277 bool GenerateDocument(json::unique_ptr& root, gt::Document& document, bool& isMRendererModel)
1278 {
1279   auto& rootObj = js::Cast<json_object_s>(*root);
1280   auto  jsAsset = js::FindObjectChild("asset", rootObj);
1281
1282   auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1283   if(jsAssetVersion)
1284   {
1285     document.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1286   }
1287
1288   auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1289   if(jsAssetGenerator)
1290   {
1291     document.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1292     isMRendererModel           = (document.mAsset.mGenerator.find(Gltf2Util::GetRendererModelIdentification().data()) != std::string_view::npos);
1293   }
1294
1295   Gltf2Util::InitializeGltfLoader();
1296   Gltf2Util::ReadDocumentFromParsedData(rootObj, document);
1297
1298   return true;
1299 }
1300
1301 void ConvertGltfToContext(gt::Document& document, Gltf2Util::ConversionContext& context, bool isMRendererModel)
1302 {
1303   Dali::Scene3D::Loader::ShaderDefinitionFactory shaderFactory;
1304   shaderFactory.SetResources(context.mOutput.mResources);
1305
1306   Gltf2Util::ConvertBuffers(document, context);
1307   Gltf2Util::ConvertMaterials(document, context);
1308   Gltf2Util::ConvertMeshes(document, context);
1309   Gltf2Util::ConvertNodes(document, context, isMRendererModel);
1310   Gltf2Util::ConvertAnimations(document, context);
1311   Gltf2Util::ProcessSkins(document, context);
1312   Gltf2Util::ProduceShaders(shaderFactory, context.mOutput.mScene);
1313   context.mOutput.mScene.EnsureUniqueSkinningShaderInstances(context.mOutput.mResources);
1314
1315   // Set Default Environment map
1316   Gltf2Util::SetDefaultEnvironmentMap(document, context);
1317 }
1318
1319 } // namespace Gltf2Util
1320
1321 } // namespace Dali::Scene3D::Loader::Internal