Fix webp&gif issue
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-scene-loader / utc-Dali-Gltf2Loader.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 // Enable debug log for test coverage
19 #define DEBUG_ENABLED 1
20
21 #include <dali-test-suite-utils.h>
22 #include <string_view>
23 #include "dali-scene-loader/public-api/gltf2-loader.h"
24 #include "dali-scene-loader/public-api/load-result.h"
25 #include "dali-scene-loader/public-api/resource-bundle.h"
26 #include "dali-scene-loader/public-api/scene-definition.h"
27 #include "dali-scene-loader/public-api/shader-definition-factory.h"
28
29 using namespace Dali;
30 using namespace Dali::SceneLoader;
31
32 #define DALI_TEST_THROW(expression, exception, predicate) \
33   {                                                       \
34     bool daliTestThrowSuccess__ = false;                  \
35     try                                                   \
36     {                                                     \
37       do                                                  \
38       {                                                   \
39         expression;                                       \
40       } while(0);                                         \
41       printf("No exception was thrown.\n");               \
42     }                                                     \
43     catch(std::decay<exception>::type & ex)               \
44     {                                                     \
45       daliTestThrowSuccess__ = predicate(ex);             \
46     }                                                     \
47     catch(...)                                            \
48     {                                                     \
49       printf("Wrong type of exception thrown.\n");        \
50     }                                                     \
51     DALI_TEST_CHECK(daliTestThrowSuccess__);              \
52   }
53
54 namespace
55 {
56 struct Context
57 {
58   ResourceBundle::PathProvider pathProvider = [](ResourceType::Value type) {
59     return TEST_RESOURCE_DIR "/";
60   };
61
62   ResourceBundle  resources;
63   SceneDefinition scene;
64
65   std::vector<AnimationDefinition>      animations;
66   std::vector<AnimationGroupDefinition> animationGroups;
67   std::vector<CameraParameters>         cameras;
68   std::vector<LightParameters>          lights;
69
70   LoadResult loadResult{
71     resources,
72     scene,
73     animations,
74     animationGroups,
75     cameras,
76     lights};
77 };
78
79 struct ExceptionMessageStartsWith
80 {
81   const std::string_view expected;
82
83   bool operator()(const std::runtime_error& e)
84   {
85     const bool success = (0 == strncmp(e.what(), expected.data(), expected.size()));
86     if(!success)
87     {
88       printf("Expected: %s, got: %s.\n", expected.data(), e.what());
89     }
90     return success;
91   }
92 };
93
94 } // namespace
95
96 int UtcDaliGltfLoaderFailedToLoad(void)
97 {
98   Context ctx;
99
100   ShaderDefinitionFactory sdf;
101   sdf.SetResources(ctx.resources);
102
103   DALI_TEST_THROW(LoadGltfScene("non-existent.gltf", sdf, ctx.loadResult),
104                   std::runtime_error,
105                   ExceptionMessageStartsWith{"Failed to load"});
106
107   DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
108   DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
109
110   DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
111   DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
112   DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
113   DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
114   DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
115
116   DALI_TEST_EQUAL(0, ctx.cameras.size());
117   DALI_TEST_EQUAL(0, ctx.lights.size());
118   DALI_TEST_EQUAL(0, ctx.animations.size());
119   DALI_TEST_EQUAL(0, ctx.animationGroups.size());
120
121   END_TEST;
122 }
123
124 int UtcDaliGltfLoaderFailedToParse(void)
125 {
126   Context ctx;
127
128   ShaderDefinitionFactory sdf;
129   sdf.SetResources(ctx.resources);
130
131   DALI_TEST_THROW(LoadGltfScene(TEST_RESOURCE_DIR "/invalid.gltf", sdf, ctx.loadResult),
132                   std::runtime_error,
133                   ExceptionMessageStartsWith{"Failed to parse"});
134
135   DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
136   DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
137
138   DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
139   DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
140   DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
141   DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
142   DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
143
144   DALI_TEST_EQUAL(0, ctx.cameras.size());
145   DALI_TEST_EQUAL(0, ctx.lights.size());
146   DALI_TEST_EQUAL(0, ctx.animations.size());
147   DALI_TEST_EQUAL(0, ctx.animationGroups.size());
148
149   END_TEST;
150 }
151
152 int UtcDaliGltfLoaderSuccess1(void)
153 {
154   Context ctx;
155
156   ShaderDefinitionFactory sdf;
157   sdf.SetResources(ctx.resources);
158
159   LoadGltfScene(TEST_RESOURCE_DIR "/AnimatedCube.gltf", sdf, ctx.loadResult);
160
161   DALI_TEST_EQUAL(1u, ctx.scene.GetRoots().size());
162   DALI_TEST_EQUAL(6u, ctx.scene.GetNodeCount());
163
164   DALI_TEST_EQUAL(0u, ctx.resources.mEnvironmentMaps.size());
165
166   auto& materials = ctx.resources.mMaterials;
167   DALI_TEST_EQUAL(2u, materials.size());
168   const MaterialDefinition materialGroundTruth[]{
169     {MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
170        MaterialDefinition::NORMAL | MaterialDefinition::TRANSPARENCY | MaterialDefinition::GLTF_CHANNELS |
171        (0x80 << MaterialDefinition::ALPHA_CUTOFF_SHIFT),
172      0,
173      Vector4(1.f, .766f, .336f, 1.f),
174      1.f,
175      0.f,
176      {
177        {MaterialDefinition::ALBEDO,
178         {"AnimatedCube_BaseColor.png",
179          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
180        {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | MaterialDefinition::GLTF_CHANNELS,
181         {"AnimatedCube_MetallicRoughness.png",
182          SamplerFlags::Encode(FilterMode::NEAREST_MIPMAP_LINEAR, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::MIRRORED_REPEAT)}},
183        {MaterialDefinition::NORMAL,
184         {"AnimatedCube_BaseColor.png",
185          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
186      }},
187     {MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
188        MaterialDefinition::NORMAL | MaterialDefinition::GLTF_CHANNELS,
189      0,
190      Vector4(1.f, .766f, .336f, 1.f),
191      1.f,
192      0.f,
193      {
194        {MaterialDefinition::ALBEDO,
195         {"AnimatedCube_BaseColor.png",
196          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
197        {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | MaterialDefinition::GLTF_CHANNELS,
198         {"AnimatedCube_MetallicRoughness.png",
199          SamplerFlags::Encode(FilterMode::NEAREST_MIPMAP_LINEAR, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::MIRRORED_REPEAT)}},
200        {MaterialDefinition::NORMAL,
201         {"AnimatedCube_BaseColor.png",
202          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
203      }},
204   };
205
206   auto iMaterial = materials.begin();
207   for(auto& m : materialGroundTruth)
208   {
209     printf("material %ld\n", iMaterial - materials.begin());
210     auto& md = iMaterial->first;
211     DALI_TEST_EQUAL(md.mFlags, m.mFlags);
212     DALI_TEST_EQUAL(md.mEnvironmentIdx, m.mEnvironmentIdx);
213     DALI_TEST_EQUAL(md.mColor, m.mColor);
214     DALI_TEST_EQUAL(md.mMetallic, m.mMetallic);
215     DALI_TEST_EQUAL(md.mRoughness, m.mRoughness);
216
217     DALI_TEST_EQUAL(md.mTextureStages.size(), m.mTextureStages.size());
218     auto iTexture = md.mTextureStages.begin();
219     for(auto& ts : m.mTextureStages)
220     {
221       printf("texture %ld\n", iTexture - md.mTextureStages.begin());
222       DALI_TEST_EQUAL(iTexture->mSemantic, ts.mSemantic);
223       DALI_TEST_EQUAL(iTexture->mTexture.mImageUri, ts.mTexture.mImageUri);
224       DALI_TEST_EQUAL(uint32_t(iTexture->mTexture.mSamplerFlags), uint32_t(ts.mTexture.mSamplerFlags)); // don't interpret it as a character
225       ++iTexture;
226     }
227     ++iMaterial;
228   }
229
230   auto& meshes = ctx.resources.mMeshes;
231   DALI_TEST_EQUAL(2u, meshes.size());
232
233   using Blob     = MeshDefinition::Blob;
234   using Accessor = MeshDefinition::Accessor;
235   const MeshDefinition meshGroundTruth[]{
236     {
237       0,
238       Geometry::TRIANGLES,
239       "AnimatedCube.bin",
240       Accessor{Blob{0, 0}, {}},
241       Accessor{Blob{0, 0}, {}},
242       Accessor{Blob{0, 0}, {}},
243       Accessor{Blob{0, 0}, {}},
244       Accessor{Blob{0, 0}, {}},
245     },
246     {
247       0,
248       Geometry::TRIANGLES,
249       "AnimatedCube.bin",
250       Accessor{Blob{0, 0}, {}},
251       Accessor{Blob{0, 0}, {}},
252       Accessor{Blob{0, 0}, {}},
253       Accessor{Blob{0, 0}, {}},
254       Accessor{Blob{0, 0}, {}},
255     },
256   };
257
258   auto iMesh = meshes.begin();
259   for(auto& m : meshGroundTruth)
260   {
261     printf("mesh %ld\n", iMesh - meshes.begin());
262
263     auto& md = iMesh->first;
264     DALI_TEST_EQUAL(md.mFlags, m.mFlags);
265     DALI_TEST_EQUAL(md.mPrimitiveType, m.mPrimitiveType);
266     for(auto mp : {
267           &MeshDefinition::mIndices,
268           &MeshDefinition::mPositions,
269           &MeshDefinition::mNormals,
270           &MeshDefinition::mTexCoords,
271           &MeshDefinition::mTangents,
272           &MeshDefinition::mJoints0,
273           &MeshDefinition::mWeights0})
274     {
275       DALI_TEST_EQUAL((md.*mp).IsDefined(), (m.*mp).IsDefined());
276       DALI_TEST_EQUAL((md.*mp).mBlob.IsDefined(), (m.*mp).mBlob.IsDefined());
277     }
278
279     DALI_TEST_EQUAL(md.mBlendShapeHeader.IsDefined(), m.mBlendShapeHeader.IsDefined());
280
281     ++iMesh;
282   }
283
284   DALI_TEST_EQUAL(2u, ctx.resources.mShaders.size());
285   DALI_TEST_EQUAL(0u, ctx.resources.mSkeletons.size());
286
287   DALI_TEST_EQUAL(3u, ctx.cameras.size());
288   DALI_TEST_EQUAL(0u, ctx.lights.size());
289   DALI_TEST_EQUAL(1u, ctx.animations.size());
290   DALI_TEST_EQUAL(0u, ctx.animationGroups.size());
291
292   END_TEST;
293 }
294
295 int UtcDaliGltfLoaderSuccessShort(void)
296 {
297   TestApplication app;
298
299   const std::string resourcePath = TEST_RESOURCE_DIR "/";
300   auto              pathProvider = [resourcePath](ResourceType::Value) {
301     return resourcePath;
302   };
303
304   Customization::Choices choices;
305   for(auto modelName : {
306         "2CylinderEngine",
307         "AnimatedMorphCube",
308         "AnimatedMorphSphere",
309         "AnimatedTriangle",
310         "BoxAnimated",
311         "CesiumMan",
312         "CesiumMilkTruck",
313         "EnvironmentTest",
314         "MetalRoughSpheres",
315         "MorphPrimitivesTest",
316         "MRendererTest",
317         "SimpleSparseAccessor",
318       })
319   {
320     Context ctx;
321
322     ShaderDefinitionFactory sdf;
323
324     auto& resources = ctx.resources;
325     resources.mEnvironmentMaps.push_back({});
326
327     sdf.SetResources(resources);
328
329     printf("%s\n", modelName);
330     LoadGltfScene(resourcePath + modelName + ".gltf", sdf, ctx.loadResult);
331     DALI_TEST_CHECK(ctx.scene.GetNodeCount() > 0);
332
333     auto& scene = ctx.scene;
334     for(auto iRoot : scene.GetRoots())
335     {
336       struct Visitor : NodeDefinition::IVisitor
337       {
338         struct ResourceReceiver : IResourceReceiver
339         {
340           std::vector<bool> mCounts;
341
342           void Register(ResourceType::Value type, Index id) override
343           {
344             if(type == ResourceType::Mesh)
345             {
346               mCounts[id] = true;
347             }
348           }
349         } receiver;
350
351         void Start(NodeDefinition& n) override
352         {
353           if(n.mRenderable)
354           {
355             n.mRenderable->RegisterResources(receiver);
356           }
357         }
358
359         void Finish(NodeDefinition& n) override
360         {
361         }
362       } visitor;
363       visitor.receiver.mCounts.resize(resources.mMeshes.size(), false);
364
365       scene.Visit(iRoot, choices, visitor);
366       for(uint32_t i0 = 0, i1 = resources.mMeshes.size(); i0 < i1; ++i0)
367       {
368         if(visitor.receiver.mCounts[i0])
369         {
370           auto raw = resources.mMeshes[i0].first.LoadRaw(resourcePath);
371           DALI_TEST_CHECK(!raw.mAttribs.empty());
372
373           resources.mMeshes[i0].second = resources.mMeshes[i0].first.Load(std::move(raw));
374           DALI_TEST_CHECK(resources.mMeshes[i0].second.geometry);
375         }
376       }
377     }
378   }
379
380   END_TEST;
381 }
382
383 int UtcDaliGltfLoaderMRendererTest(void)
384 {
385   Context ctx;
386
387   ShaderDefinitionFactory sdf;
388   sdf.SetResources(ctx.resources);
389   auto& resources = ctx.resources;
390   resources.mEnvironmentMaps.push_back({});
391
392   LoadGltfScene(TEST_RESOURCE_DIR "/MRendererTest.gltf", sdf, ctx.loadResult);
393
394   auto& scene = ctx.scene;
395   auto& roots = scene.GetRoots();
396   DALI_TEST_EQUAL(roots.size(), 1u);
397   DALI_TEST_EQUAL(scene.GetNode(roots[0])->mName, "RootNode");
398   DALI_TEST_EQUAL(scene.GetNode(roots[0])->mScale, Vector3(1.0f, 1.0f, 1.0f));
399
400   DALI_TEST_EQUAL(scene.GetNodeCount(), 1u);
401
402   ViewProjection viewProjection;
403   Transforms     xforms{
404     MatrixStack{},
405     viewProjection};
406   NodeDefinition::CreateParams nodeParams{
407     resources,
408     xforms,
409   };
410
411   Customization::Choices choices;
412
413   TestApplication app;
414
415   Actor root = Actor::New();
416   SetActorCentered(root);
417   for(auto iRoot : roots)
418   {
419     auto resourceRefs = resources.CreateRefCounter();
420     scene.CountResourceRefs(iRoot, choices, resourceRefs);
421     resources.CountEnvironmentReferences(resourceRefs);
422     resources.LoadResources(resourceRefs, ctx.pathProvider);
423     if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
424     {
425       scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
426       scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
427       scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
428       root.Add(actor);
429     }
430   }
431
432   DALI_TEST_EQUAL(root.GetChildCount(), 1u);
433   DALI_TEST_EQUAL(root.GetChildAt(0).GetProperty(Actor::Property::NAME).Get<std::string>(), "RootNode");
434   DALI_TEST_EQUAL(root.GetChildAt(0).GetProperty(Actor::Property::SCALE).Get<Vector3>(), Vector3(1.0f, 1.0f, 1.0f));
435
436   END_TEST;
437 }