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