Merge "Change dali-scene-loader to dali-scene3d" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / dli-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 // CLASS HEADER
19 #include "dali-scene3d/public-api/loader/dli-loader.h"
20
21 // EXTERNAL INCLUDES
22 #include <algorithm>
23 #include <cmath>
24 #include <fstream>
25 #include <limits>
26 #include <memory>
27 #include "dali-toolkit/devel-api/builder/json-parser.h"
28 #include "dali/devel-api/common/map-wrapper.h"
29 #include "dali/integration-api/debug.h"
30 #include "dali/public-api/object/property-array.h"
31
32 // INTERNAL INCLUDES
33 #include "dali-scene3d/internal/loader/json-util.h"
34 #include "dali-scene3d/public-api/loader/alpha-function-helper.h"
35 #include "dali-scene3d/public-api/loader/animation-definition.h"
36 #include "dali-scene3d/public-api/loader/blend-shape-details.h"
37 #include "dali-scene3d/public-api/loader/camera-parameters.h"
38 #include "dali-scene3d/public-api/loader/ktx-loader.h"
39 #include "dali-scene3d/public-api/loader/light-parameters.h"
40 #include "dali-scene3d/public-api/loader/load-result.h"
41 #include "dali-scene3d/public-api/loader/parse-renderer-state.h"
42 #include "dali-scene3d/public-api/loader/scene-definition.h"
43 #include "dali-scene3d/public-api/loader/skinning-details.h"
44 #include "dali-scene3d/public-api/loader/utils.h"
45
46 #define DLI_0_1_COMPATIBILITY
47
48 namespace Dali
49 {
50 using namespace Toolkit;
51
52 namespace Scene3D
53 {
54 namespace Loader
55 {
56 namespace rs = RendererState;
57
58 namespace
59 {
60 const std::string NODES         = "nodes";
61 const std::string SCENES        = "scenes";
62 const std::string NODE          = "node";
63 const std::string URI           = "uri";
64 const std::string URL           = "url";
65 const std::string CUSTOMIZATION = "customization";
66 const std::string HINTS         = "hints";
67 const std::string NAME("name");
68 const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
69 const std::string BLEND_SHAPES("blendShapes");
70 const std::string BLEND_SHAPE_VERSION_1_0("1.0");
71 const std::string BLEND_SHAPE_VERSION_2_0("2.0");
72 const std::string VERSION("version");
73
74 const char* const SHADOW_MAP_SIZE   = "shadowMapSize";
75 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
76 const char* const PIXEL_UNITS       = "px";
77
78 const char SLASH = '/';
79
80 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
81 {
82   float num[16u] = {.0f};
83
84   if(ReadVector(node->GetChild("matrix"), num, 16u))
85   {
86     Matrix mat(num);
87     mat.GetTransformComponents(translation, orientation, scale);
88   }
89   else
90   {
91     if(ReadVector(node->GetChild("angle"), num, 3u))
92     {
93       orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
94     }
95
96     if(ReadVector(node->GetChild("position"), num, 3u))
97     {
98       translation = Vector3(num);
99     }
100   }
101 }
102
103 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
104 {
105   return ReadBlob(node, buffer.mOffset, buffer.mLength);
106 }
107
108 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
109 {
110   return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
111 }
112
113 bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
114 {
115   if(!node || !convertColorCode)
116   {
117     return false;
118   }
119
120   color = convertColorCode(node->GetString());
121
122   return true;
123 }
124
125 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
126 {
127   return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
128          ReadColor(node->GetChild("color"), color);
129 }
130
131 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
132 {
133   if(tnRendererState.GetType() == TreeNode::INTEGER)
134   {
135     return static_cast<RendererState::Type>(tnRendererState.GetInteger());
136   }
137   else if(tnRendererState.GetType() == TreeNode::STRING)
138   {
139     return RendererState::Parse(tnRendererState.GetString());
140   }
141   else
142   {
143     return -1;
144   }
145 }
146
147 ///@brief Reads arc properties.
148 void ReadArcField(const TreeNode* eArc, ArcNode& arc)
149 {
150   ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
151   ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
152   ReadFloat(eArc->GetChild("radius"), arc.mRadius);
153
154   arc.mStartAngleDegrees = .0f;
155   ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
156
157   arc.mEndAngleDegrees = .0f;
158   ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
159 }
160
161 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
162 {
163   uint32_t i = 0;
164   for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
165   {
166     if(i == index)
167     {
168       return &((*it).second);
169     }
170   }
171   return NULL;
172 }
173
174 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
175 {
176   auto child = node->GetChild(childName);
177   if(!child)
178   {
179     ExceptionFlinger flinger(ASSERT_LOCATION);
180     flinger << "Failed to find child node '" << childName << "'";
181     if(auto nodeName = node->GetName())
182     {
183       flinger << " on '" << nodeName << "'";
184     }
185     flinger << ".";
186   }
187   return child;
188 }
189
190 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
191
192 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
193 {
194   DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
195   for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
196   {
197     auto kv = *i0;
198     switch(kv.second.GetType())
199     {
200       case TreeNode::ARRAY:
201       {
202         Property::Array array;
203         ParseProperties(kv.second, array);
204         map.Insert(kv.first, array);
205         break;
206       }
207
208       case TreeNode::OBJECT:
209       {
210         Property::Map innerMap;
211         ParseProperties(kv.second, innerMap);
212         map.Insert(kv.first, innerMap);
213         break;
214       }
215
216       case TreeNode::STRING:
217       {
218         map.Insert(kv.first, kv.second.GetString());
219         break;
220       }
221
222       case TreeNode::INTEGER:
223       {
224         map.Insert(kv.first, kv.second.GetInteger());
225         break;
226       }
227
228       case TreeNode::BOOLEAN:
229       {
230         map.Insert(kv.first, kv.second.GetBoolean());
231         break;
232       }
233
234       case TreeNode::FLOAT:
235       {
236         map.Insert(kv.first, kv.second.GetFloat());
237         break;
238       }
239
240       case TreeNode::IS_NULL:
241       {
242         break;
243       }
244     }
245   }
246 }
247
248 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
249 {
250   DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
251   for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
252   {
253     auto kv = *i0;
254     switch(kv.second.GetType())
255     {
256       case TreeNode::ARRAY:
257       {
258         Property::Array innerArray;
259         ParseProperties(kv.second, innerArray);
260         array.PushBack(innerArray);
261         break;
262       }
263
264       case TreeNode::OBJECT:
265       {
266         Property::Map map;
267         ParseProperties(kv.second, map);
268         array.PushBack(map);
269         break;
270       }
271
272       case TreeNode::STRING:
273       {
274         array.PushBack(kv.second.GetString());
275         break;
276       }
277
278       case TreeNode::INTEGER:
279       {
280         array.PushBack(kv.second.GetInteger());
281         break;
282       }
283
284       case TreeNode::BOOLEAN:
285       {
286         array.PushBack(kv.second.GetBoolean());
287         break;
288       }
289
290       case TreeNode::FLOAT:
291       {
292         array.PushBack(kv.second.GetFloat());
293         break;
294       }
295
296       case TreeNode::IS_NULL:
297       {
298         break;
299       }
300     }
301   }
302 }
303
304 } //namespace
305
306 struct DliLoader::Impl
307 {
308   StringCallback      mOnError = DefaultErrorCallback;
309   Toolkit::JsonParser mParser;
310
311   void ParseScene(LoadParams& params);
312
313 private:
314   std::map<Index, Matrix> mInverseBindMatrices;
315
316   /**
317    * @brief Due to .dli nodes being processed in depth-first traversal with orphans being
318    *  ignored, features that rely on node indices (which is more compact and closer to
319    *  glTF) require a mapping from .dli node indices to those in the resulting SceneDefinition.
320    *  The index mapper is responsible for maintaing this mapping, and resolving node IDs
321    *  once the processing of the nodes has finished.
322    * @note The resolution requires the whole scene graph to finish parsing, therefore any
323    *  node extensions relying on node IDs will see the dli ID in their processor.
324    */
325   struct IIndexMapper
326   {
327     /**
328      * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
329      *  index.
330      * @return Whether the operation was successful.
331      */
332     virtual bool Map(Index iDli, Index iScene) = 0;
333
334     /**
335      * @return The scene index for the node's @a dli index.
336      */
337     virtual Index Resolve(Index iDli) = 0;
338   };
339
340   /**
341    * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
342    *  an intermediate representation of resources and nodes.
343    */
344   void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
345
346   void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
347   void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
348   void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
349
350   void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
351   void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
352
353   void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
354   void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
355
356   void ParseShaders(const Toolkit::TreeNode* shaders, ResourceBundle& resources);
357   void ParseMeshes(const Toolkit::TreeNode* meshes, ResourceBundle& resources);
358
359   void GetCameraParameters(std::vector<CameraParameters>& cameras) const;
360   void GetLightParameters(std::vector<LightParameters>& lights) const;
361 };
362
363 DliLoader::DliLoader()
364 : mImpl{new Impl}
365 {
366 }
367
368 DliLoader::~DliLoader() = default;
369
370 void DliLoader::SetErrorCallback(StringCallback onError)
371 {
372   mImpl->mOnError = onError;
373 }
374
375 bool DliLoader::LoadScene(const std::string& uri, LoadParams& params)
376 {
377   std::string daliBuffer = LoadTextFile(uri.c_str());
378
379   auto& parser = mImpl->mParser;
380   parser       = JsonParser::New();
381   if(!parser.Parse(daliBuffer))
382   {
383     return false;
384   }
385
386   mImpl->ParseScene(params);
387   return true;
388 }
389
390 std::string DliLoader::GetParseError() const
391 {
392   std::stringstream stream;
393
394   auto& parser = mImpl->mParser;
395   if(parser.ParseError())
396   {
397     stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
398   }
399
400   return stream.str();
401 }
402
403 void DliLoader::Impl::ParseScene(LoadParams& params)
404 {
405   auto& input  = params.input;
406   auto& output = params.output;
407
408   // get index of root node.
409   auto docRoot = mParser.GetRoot();
410
411   // Process resources first - these are shared
412   if(auto environments = docRoot->GetChild("environment"))
413   {
414     ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
415   }
416
417   if(auto meshes = docRoot->GetChild("meshes"))
418   {
419     ParseMeshes(meshes, output.mResources);
420   }
421
422   if(auto shaders = docRoot->GetChild("shaders"))
423   {
424     ParseShaders(shaders, output.mResources);
425   }
426
427   if(auto materials = docRoot->GetChild("materials"))
428   {
429     ParseMaterials(materials, input.mConvertColorCode, output.mResources);
430   }
431
432   for(auto& c : input.mPreNodeCategoryProcessors)
433   {
434     if(auto node = docRoot->GetChild(c.first))
435     {
436       Property::Array array;
437       ParseProperties(*node, array);
438       c.second(std::move(array), mOnError);
439     }
440   }
441
442   // Process scenes
443   Index iScene = 0; // default scene
444   ReadIndex(docRoot->GetChild("scene"), iScene);
445
446   auto tnScenes = RequireChild(docRoot, "scenes");
447   auto tnNodes  = RequireChild(docRoot, "nodes");
448   ParseSceneInternal(iScene, tnScenes, tnNodes, params);
449
450   ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
451
452   output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
453   output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
454
455   // Ger cameras and lights
456   GetCameraParameters(output.mCameraParameters);
457   GetLightParameters(output.mLightParameters);
458
459   // Post-node processors and animations last
460   for(auto& c : input.mPostNodeCategoryProcessors)
461   {
462     if(auto node = docRoot->GetChild(c.first))
463     {
464       Property::Array array;
465       ParseProperties(*node, array);
466       c.second(std::move(array), mOnError);
467     }
468   }
469
470   if(auto animations = docRoot->GetChild("animations"))
471   {
472     ParseAnimations(animations, params);
473   }
474
475   if(!output.mAnimationDefinitions.empty())
476   {
477     if(auto animationGroups = docRoot->GetChild("animationGroups"))
478     {
479       ParseAnimationGroups(animationGroups, params);
480     }
481   }
482 }
483
484 void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
485 {
486   auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
487     auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
488     if(!tn)
489     {
490       ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
491     }
492
493     tn = RequireChild(tn, NODES); // now a "nodes" array
494     if(tn->GetType() != TreeNode::ARRAY)
495     {
496       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
497     }
498
499     if(tn->Size() < 1)
500     {
501       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
502     }
503
504     tn = GetNthChild(tn, 0); // now the first element of the array
505     Index iRootNode;
506     if(!ReadIndex(tn, iRootNode))
507     {
508       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
509     }
510
511     if(iRootNode >= tnNodes->Size())
512     {
513       ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
514     }
515
516     tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
517     if(tn->GetType() != TreeNode::OBJECT)
518     {
519       ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
520     }
521
522     return iRootNode;
523   };
524
525   Index iRootNode = getSceneRootIdx(iScene);
526   ParseNodes(tnNodes, iRootNode, params);
527
528   auto& scene = params.output.mScene;
529   scene.AddRootNode(0);
530
531   for(Index i = 0; i < iScene; ++i)
532   {
533     Index       iRootNode = getSceneRootIdx(i);
534     const Index iRoot     = scene.GetNodeCount();
535     ParseNodes(tnNodes, iRootNode, params);
536     scene.AddRootNode(iRoot);
537   }
538
539   auto numScenes = tnScenes->Size();
540   for(Index i = iScene + 1; i < numScenes; ++i)
541   {
542     Index       iRootNode = getSceneRootIdx(i);
543     const Index iRoot     = scene.GetNodeCount();
544     ParseNodes(tnNodes, iRootNode, params);
545     scene.AddRootNode(iRoot);
546   }
547 }
548
549 void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
550 {
551   if(skeletons)
552   {
553     auto iStart = skeletons->CBegin();
554     for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
555     {
556       auto&       node = (*i0).second;
557       std::string skeletonRootName;
558       if(ReadString(node.GetChild(NODE), skeletonRootName))
559       {
560         SkeletonDefinition skeleton;
561         if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
562         {
563           ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
564         }
565
566         uint32_t                   jointCount = 0;
567         std::function<void(Index)> visitFn;
568         auto&                      ibms = mInverseBindMatrices;
569         visitFn                         = [&](Index id) {
570           auto node = scene.GetNode(id);
571           jointCount += ibms.find(id) != ibms.end();
572
573           for(auto i : node->mChildren)
574           {
575             visitFn(i);
576           }
577         };
578         visitFn(skeleton.mRootNodeIdx);
579
580         if(jointCount > Skinning::MAX_JOINTS)
581         {
582           mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
583           jointCount = Skinning::MAX_JOINTS;
584         }
585
586         skeleton.mJoints.reserve(jointCount);
587
588         visitFn = [&](Index id) {
589           auto iFind = ibms.find(id);
590           if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
591           {
592             skeleton.mJoints.push_back({id, iFind->second});
593           }
594
595           auto node = scene.GetNode(id);
596           for(auto i : node->mChildren)
597           {
598             visitFn(i);
599           }
600         };
601         visitFn(skeleton.mRootNodeIdx);
602
603         resources.mSkeletons.push_back(std::move(skeleton));
604       }
605       else
606       {
607         ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
608       }
609     }
610   }
611 }
612
613 void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBundle& resources)
614 {
615   Matrix cubeOrientation(Matrix::IDENTITY);
616
617   for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
618   {
619     auto& node = (*i0).second;
620
621     EnvironmentDefinition envDef;
622     ReadString(node.GetChild("cubeSpecular"), envDef.mSpecularMapPath);
623     ReadString(node.GetChild("cubeDiffuse"), envDef.mDiffuseMapPath);
624     ToUnixFileSeparators(envDef.mSpecularMapPath);
625     ToUnixFileSeparators(envDef.mDiffuseMapPath);
626     envDef.mIblIntensity = 1.0f;
627     ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
628     if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
629     {
630       envDef.mCubeOrientation = Quaternion(cubeOrientation);
631     }
632
633     resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
634   }
635
636   // NOTE: guarantees environmentMaps to have an empty environment.
637   if(resources.mEnvironmentMaps.empty())
638   {
639     resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
640   }
641 }
642
643 void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
644 {
645   uint32_t iShader = 0;
646   for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
647   {
648     auto&            node = (*i0).second;
649     ShaderDefinition shaderDef;
650     ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
651
652     // Read shader hints. Possible values are:
653     //                         Don't define for No hints.
654     // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
655     //     "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
656
657     ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
658
659     if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
660        ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
661     {
662       ToUnixFileSeparators(shaderDef.mVertexShaderPath);
663       ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
664
665       for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
666       {
667         const TreeNode::KeyNodePair& keyValue = *j0;
668         const std::string&           key      = keyValue.first;
669         const TreeNode&              value    = keyValue.second;
670
671         Property::Value uniformValue;
672         if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
673         {
674           continue;
675         }
676         else if(key.compare("rendererState") == 0)
677         {
678           shaderDef.mRendererState = ReadRendererState(keyValue.second);
679         }
680         else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
681         {
682           float f = 0.f;
683           ReadFloat(&value, f);
684           uniformValue = f;
685         }
686         else if(value.GetType() == TreeNode::BOOLEAN)
687         {
688           DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
689           bool value = false;
690           if(ReadBool(&keyValue.second, value))
691           {
692             uniformValue = value ? 1.0f : 0.0f;
693           }
694         }
695         else
696           switch(auto size = GetNumericalArraySize(&value))
697           {
698             case 16:
699             {
700               Matrix m;
701               ReadVector(&value, m.AsFloat(), size);
702               uniformValue = m;
703               break;
704             }
705
706             case 9:
707             {
708               Matrix3 m;
709               ReadVector(&value, m.AsFloat(), size);
710               uniformValue = m;
711               break;
712             }
713
714             case 4:
715             {
716               Vector4 v;
717               ReadVector(&value, v.AsFloat(), size);
718               uniformValue = v;
719               break;
720             }
721
722             case 3:
723             {
724               Vector3 v;
725               ReadVector(&value, v.AsFloat(), size);
726               uniformValue = v;
727               break;
728             }
729
730             case 2:
731             {
732               Vector2 v;
733               ReadVector(&value, v.AsFloat(), size);
734               uniformValue = v;
735               break;
736             }
737
738             default:
739               mOnError(FormatString(
740                 "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
741                 iShader,
742                 key.c_str()));
743               break;
744           }
745
746         if(Property::NONE != uniformValue.GetType())
747         {
748           shaderDef.mUniforms.Insert(key, uniformValue);
749         }
750       }
751
752       resources.mShaders.emplace_back(std::move(shaderDef), Shader());
753     }
754     else
755     {
756       ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
757     }
758   }
759 }
760
761 void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
762 {
763   for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
764   {
765     auto& node = (*i0).second;
766
767     MeshDefinition meshDef;
768     if(!ReadString(node.GetChild(URI), meshDef.mUri))
769     {
770       ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
771     }
772
773     ToUnixFileSeparators(meshDef.mUri);
774
775     std::string primitive;
776     if(ReadString(node.GetChild("primitive"), primitive))
777     {
778       if(primitive == "LINES")
779       {
780         meshDef.mPrimitiveType = Geometry::LINES;
781       }
782       else if(primitive == "POINTS")
783       {
784         meshDef.mPrimitiveType = Geometry::POINTS;
785       }
786       else if(primitive != "TRIANGLES")
787       {
788         mOnError(FormatString(
789           "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
790           resources.mMeshes.size(),
791           primitive.c_str()));
792       }
793     }
794
795     int attributes;
796     if(ReadInt(node.GetChild("attributes"), attributes))
797     {
798       if(MaskMatch(attributes, MeshDefinition::INDICES) &&
799          !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
800       {
801         ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
802                                                           resources.mMeshes.size(),
803                                                           "indices");
804       }
805
806       if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
807          !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
808       {
809         ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
810                                                           resources.mMeshes.size(),
811                                                           "positions");
812       }
813
814       if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
815          !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
816       {
817         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
818       }
819
820       if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
821          !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
822       {
823         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
824       }
825
826       if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
827          !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
828       {
829         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
830       }
831
832       // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
833       if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
834       {
835         if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
836            !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
837         {
838           mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
839                                 resources.mMeshes.size()));
840         }
841         else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
842                 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
843         {
844           mOnError(FormatString("mesh %d: Failed to read skinning information.",
845                                 resources.mMeshes.size()));
846         }
847       }
848
849       if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
850       {
851         std::string blendShapeVersion;
852         ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
853
854         if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
855         {
856           meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
857         }
858         else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
859         {
860           meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
861         }
862
863         switch(meshDef.mBlendShapeVersion)
864         {
865           case BlendShapes::Version::VERSION_1_0:
866           case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
867           {
868             ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
869             break;
870           }
871           default:
872           {
873             // nothing to do
874             break;
875           }
876         }
877       }
878
879       if(auto blendShapes = node.GetChild(BLEND_SHAPES))
880       {
881         meshDef.mBlendShapes.resize(blendShapes->Size());
882
883         auto index = 0u;
884         for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
885         {
886           // Each blend shape is stored as the difference with the original mesh.
887
888           auto& blendShapeNode = (*it).second;
889
890           auto& blendShape = meshDef.mBlendShapes[index];
891           ReadString(blendShapeNode.GetChild("name"), blendShape.name);
892           if(auto position = blendShapeNode.GetChild("positions"))
893           {
894             ReadAttribAccessor(position, blendShape.deltas);
895           }
896           if(auto normals = blendShapeNode.GetChild("normals"))
897           {
898             ReadAttribAccessor(normals, blendShape.normals);
899           }
900           if(auto tangents = blendShapeNode.GetChild("tangents"))
901           {
902             ReadAttribAccessor(tangents, blendShape.tangents);
903           }
904           ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
905         }
906       }
907
908       bool flipV;
909       if(ReadBool(node.GetChild("flipV"), flipV))
910       {
911         meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
912       }
913
914       resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
915     }
916   }
917 }
918
919 void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
920 {
921   for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
922   {
923     auto& node = (*i0).second;
924
925     MaterialDefinition materialDef;
926     if(auto eEnvironment = node.GetChild("environment"))
927     {
928       ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
929       if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
930       {
931         ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
932       }
933     }
934
935     //TODO : need to consider AGIF
936     std::vector<std::string> texturePaths;
937     std::string              texturePath;
938     if(ReadString(node.GetChild("albedoMap"), texturePath))
939     {
940       ToUnixFileSeparators(texturePath);
941       const auto semantic = MaterialDefinition::ALBEDO;
942       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
943       materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
944     }
945     if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
946     {
947       ToUnixFileSeparators(texturePath);
948
949       if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
950       {
951         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
952       }
953
954       const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
955       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
956       materialDef.mFlags |= semantic;
957     }
958
959     if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
960     {
961       ToUnixFileSeparators(texturePath);
962
963       if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
964       {
965         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
966       }
967
968       const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
969       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
970       materialDef.mFlags |= semantic |
971                             // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
972                             (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
973     }
974
975     if(ReadString(node.GetChild("normalMap"), texturePath))
976     {
977       ToUnixFileSeparators(texturePath);
978
979       const auto semantic = MaterialDefinition::NORMAL;
980       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
981       materialDef.mFlags |= semantic |
982                             // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
983                             (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
984     }
985
986     if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
987     {
988       ToUnixFileSeparators(texturePath);
989
990       if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
991       {
992         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
993       }
994
995       if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
996       {
997         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
998       }
999
1000       if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1001       {
1002         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1003       }
1004
1005       const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1006       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1007       materialDef.mFlags |= semantic;
1008     }
1009
1010     if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1011     {
1012       ToUnixFileSeparators(texturePath);
1013
1014       const auto semantic = MaterialDefinition::SUBSURFACE;
1015       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1016       materialDef.mFlags |= semantic;
1017     }
1018
1019     if(ReadString(node.GetChild("occlusionMap"), texturePath))
1020     {
1021       ToUnixFileSeparators(texturePath);
1022       const auto semantic = MaterialDefinition::OCCLUSION;
1023       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1024       materialDef.mFlags |= semantic;
1025     }
1026
1027     if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1028        materialDef.mColor.a < 1.0f)
1029     {
1030       materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1031     }
1032
1033     ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1034     ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1035
1036     bool mipmaps;
1037     if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1038     {
1039       for(auto& ts : materialDef.mTextureStages)
1040       {
1041         ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1042       }
1043     }
1044
1045     resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1046   }
1047 }
1048
1049 void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1050 {
1051   std::vector<Index> parents;
1052   parents.reserve(8);
1053
1054   struct IndexMapper : IIndexMapper
1055   {
1056     IndexMapper(size_t numNodes)
1057     {
1058       mIndices.reserve(numNodes);
1059     }
1060
1061     virtual bool Map(Index iDli, Index iScene) override
1062     {
1063       Entry idx{iDli, iScene};
1064       auto  iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1065       if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1066       {
1067         mIndices.insert(iInsert, idx);
1068       }
1069       else if(iInsert->iScene != iScene)
1070       {
1071         return false;
1072       }
1073       return true;
1074     }
1075
1076     virtual unsigned int Resolve(Index iDli) override
1077     {
1078       auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) {
1079         return idx.iDli < iDli;
1080       });
1081       DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1082       return iFind->iScene;
1083     }
1084
1085   private:
1086     struct Entry
1087     {
1088       unsigned int iDli;
1089       unsigned int iScene;
1090
1091       bool operator<(const Entry& other) const
1092       {
1093         return iDli < other.iDli;
1094       }
1095     };
1096     std::vector<Entry> mIndices;
1097   } mapper(nodes->Size());
1098   ParseNodesInternal(nodes, index, parents, params, mapper);
1099
1100   auto& scene = params.output.mScene;
1101   for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1102   {
1103     for(auto& c : scene.GetNode(i0)->mConstraints)
1104     {
1105       c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1106     }
1107   }
1108 }
1109
1110 void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1111 {
1112   // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1113   struct IndexProperty
1114   {
1115     ResourceType::Value type;
1116     const TreeNode*     source;
1117     Index&              target;
1118   };
1119   std::vector<IndexProperty> resourceIds;
1120   resourceIds.reserve(4);
1121
1122   if(auto node = GetNthChild(nodes, index))
1123   {
1124     NodeDefinition nodeDef;
1125     nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1126
1127     // name
1128     ReadString(node->GetChild(NAME), nodeDef.mName);
1129
1130     // transform
1131     ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1132
1133     // Reads the size of the node.
1134     //
1135     // * It can be given as 'size' or 'bounds'.
1136     // * The sdk saves the 'size' as a vector2 in some cases.
1137     // * To avoid size related issues the following code attemps
1138     //   to read the 'size/bounds' as a vector3 first, if it's
1139     //   not successful then reads it as a vector2.
1140     ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1141       ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1142       ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1143       ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1144
1145     // visibility
1146     ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1147
1148     // type classification
1149     if(auto eCustomization = node->GetChild("customization")) // customization
1150     {
1151       std::string tag;
1152       if(ReadString(eCustomization->GetChild("tag"), tag))
1153       {
1154         nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
1155       }
1156     }
1157     else // something renderable maybe
1158     {
1159       std::unique_ptr<NodeDefinition::Renderable> renderable;
1160       ModelNode*                                  modelNode = nullptr; // no ownership, aliasing renderable for the right type.
1161
1162       const TreeNode* eRenderable = nullptr;
1163       if((eRenderable = node->GetChild("model")))
1164       {
1165         // check for mesh before allocating - this can't be missing.
1166         auto eMesh = eRenderable->GetChild("mesh");
1167         if(!eMesh)
1168         {
1169           ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1170         }
1171
1172         modelNode = new ModelNode();
1173         renderable.reset(modelNode);
1174
1175         resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx});
1176       }
1177       else if((eRenderable = node->GetChild("arc")))
1178       {
1179         // check for mesh before allocating - this can't be missing.
1180         auto eMesh = eRenderable->GetChild("mesh");
1181         if(!eMesh)
1182         {
1183           ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1184         }
1185
1186         auto arcNode = new ArcNode;
1187         renderable.reset(arcNode);
1188         modelNode = arcNode;
1189
1190         resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx});
1191
1192         ReadArcField(eRenderable, *arcNode);
1193       }
1194
1195       if(renderable) // process common properties of all renderables + register payload
1196       {
1197         // shader
1198         renderable->mShaderIdx = 0;
1199         auto eShader           = eRenderable->GetChild("shader");
1200         resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1201
1202         // color
1203         if(modelNode)
1204         {
1205           modelNode->mMaterialIdx = 0; // must offer default of 0
1206           auto eMaterial          = eRenderable->GetChild("material");
1207           resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx});
1208
1209           if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
1210           {
1211             ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode);
1212           }
1213         }
1214
1215         nodeDef.mRenderable = std::move(renderable);
1216       }
1217     }
1218
1219     // Resolve ints - default to 0 if undefined
1220     auto& output = params.output;
1221     for(auto& idRes : resourceIds)
1222     {
1223       Index iCheck = 0;
1224       switch(idRes.type)
1225       {
1226         case ResourceType::Shader:
1227           iCheck = output.mResources.mShaders.size();
1228           break;
1229
1230         case ResourceType::Mesh:
1231           iCheck = output.mResources.mMeshes.size();
1232           break;
1233
1234         case ResourceType::Material:
1235           iCheck = output.mResources.mMaterials.size();
1236           break;
1237
1238         default:
1239           ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1240       }
1241
1242       if(!idRes.source)
1243       {
1244         idRes.target = 0;
1245       }
1246       else if(idRes.source->GetType() != TreeNode::INTEGER)
1247       {
1248         ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1249       }
1250       else
1251       {
1252         idRes.target = idRes.source->GetInteger();
1253       }
1254
1255       if(idRes.target >= iCheck)
1256       {
1257         ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1258       }
1259     }
1260     resourceIds.clear();
1261
1262     // Extra properties
1263     if(auto eExtras = node->GetChild("extras"))
1264     {
1265       auto& extras = nodeDef.mExtras;
1266       extras.reserve(eExtras->Size());
1267
1268       for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1269       {
1270         NodeDefinition::Extra e;
1271
1272         auto eExtra = *i0;
1273         e.mKey      = eExtra.first;
1274         if(e.mKey.empty())
1275         {
1276           mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1277                                 index,
1278                                 extras.size()));
1279           continue;
1280         }
1281
1282         e.mValue = ReadPropertyValue(eExtra.second);
1283         if(e.mValue.GetType() == Property::Type::NONE)
1284         {
1285           mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1286                                 index,
1287                                 e.mKey.c_str(),
1288                                 eExtra.second.GetString()));
1289         }
1290         else
1291         {
1292           auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1293           if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1294           {
1295             mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1296                                   index,
1297                                   e.mKey.c_str(),
1298                                   eExtra.second.GetString()));
1299             *iInsert = std::move(e);
1300           }
1301           else
1302           {
1303             extras.insert(iInsert, e);
1304           }
1305         }
1306       }
1307     }
1308
1309     // Constraints
1310     if(auto eConstraints = node->GetChild("constraints"))
1311     {
1312       auto& constraints = nodeDef.mConstraints;
1313       constraints.reserve(eConstraints->Size());
1314
1315       ConstraintDefinition cDef;
1316       for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1317       {
1318         auto eConstraint = *i0;
1319         if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1320         {
1321           mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1322                                 index,
1323                                 eConstraint.second.GetString(),
1324                                 constraints.size()));
1325         }
1326         else
1327         {
1328           cDef.mProperty = eConstraint.first;
1329
1330           auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1331           if(iInsert != constraints.end() && *iInsert == cDef)
1332           {
1333             mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1334                                   index,
1335                                   cDef.mProperty.c_str(),
1336                                   cDef.mSourceIdx));
1337           }
1338           else
1339           {
1340             constraints.insert(iInsert, cDef);
1341           }
1342         }
1343       }
1344     }
1345
1346     // Determine index for mapping
1347     const unsigned int myIndex = output.mScene.GetNodeCount();
1348     if(!mapper.Map(index, myIndex))
1349     {
1350       mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree."));
1351       return;
1352     }
1353
1354     // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1355     Matrix invBindMatrix{false};
1356     if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1357     {
1358       mInverseBindMatrices[myIndex] = invBindMatrix;
1359     }
1360
1361     // Register nodeDef
1362     auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
1363     if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1364     {
1365       // ...And only then parse children.
1366       if(auto children = node->GetChild("children"))
1367       {
1368         inOutParentStack.push_back(myIndex);
1369
1370         rawDef->mChildren.reserve(children->Size());
1371
1372         uint32_t iChild = 0;
1373         for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1374         {
1375           auto& child = (*j0).second;
1376           if(child.GetType() == TreeNode::INTEGER)
1377           {
1378             ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1379           }
1380           else
1381           {
1382             ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1383           }
1384         }
1385
1386         inOutParentStack.pop_back();
1387       }
1388       else if(rawDef->mCustomization)
1389       {
1390         mOnError(FormatString("node %d: not an actual customization without children.", index));
1391       }
1392
1393       if(auto proc = params.input.mNodePropertyProcessor) // optional processing
1394       {
1395         // WARNING: constraint IDs are not resolved at this point.
1396         Property::Map nodeData;
1397         ParseProperties(*node, nodeData);
1398         proc(*rawDef, std::move(nodeData), mOnError);
1399       }
1400     }
1401     else
1402     {
1403       ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1404     }
1405   }
1406 }
1407
1408 void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1409 {
1410   auto& definitions = params.output.mAnimationDefinitions;
1411   definitions.reserve(definitions.size() + tnAnimations->Size());
1412
1413   for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1414       iAnim != iAnimEnd;
1415       ++iAnim)
1416   {
1417     const TreeNode&     tnAnim = (*iAnim).second;
1418     AnimationDefinition animDef;
1419     ReadString(tnAnim.GetChild(NAME), animDef.mName);
1420
1421     auto       iFind     = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
1422       return ad0.mName < ad1.mName;
1423     });
1424     const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1425     if(overwrite)
1426     {
1427       mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1428     }
1429
1430     // Duration -- We need something that animated properties' delay / duration can
1431     // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1432     // than our frame delay) to not be restrictive WRT replaying. If anything needs
1433     // to occur more frequently, then Animations are likely not your solution anyway.
1434     animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1435     if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1436     {
1437       mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1438                             animDef.mName.c_str(),
1439                             "duration",
1440                             animDef.mDuration));
1441     }
1442
1443     // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1444     animDef.mLoopCount = 1;
1445     if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1446        animDef.mLoopCount < 0)
1447     {
1448       animDef.mLoopCount = 0;
1449     }
1450
1451     std::string endAction;
1452     if(ReadString(tnAnim.GetChild("endAction"), endAction))
1453     {
1454       if("BAKE" == endAction)
1455       {
1456         animDef.mEndAction = Animation::BAKE;
1457       }
1458       else if("DISCARD" == endAction)
1459       {
1460         animDef.mEndAction = Animation::DISCARD;
1461       }
1462       else if("BAKE_FINAL" == endAction)
1463       {
1464         animDef.mEndAction = Animation::BAKE_FINAL;
1465       }
1466     }
1467
1468     if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1469     {
1470       if("BAKE" == endAction)
1471       {
1472         animDef.mDisconnectAction = Animation::BAKE;
1473       }
1474       else if("DISCARD" == endAction)
1475       {
1476         animDef.mDisconnectAction = Animation::DISCARD;
1477       }
1478       else if("BAKE_FINAL" == endAction)
1479       {
1480         animDef.mDisconnectAction = Animation::BAKE_FINAL;
1481       }
1482     }
1483
1484     if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1485     {
1486       animDef.mProperties.reserve(tnProperties->Size());
1487       for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1488           iProperty != iPropertyEnd;
1489           ++iProperty)
1490       {
1491         const TreeNode& tnProperty = (*iProperty).second;
1492
1493         AnimatedProperty animProp;
1494         if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1495         {
1496           mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1497           continue;
1498         }
1499
1500         if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1501         {
1502           mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1503           continue;
1504         }
1505
1506         // these are the defaults
1507         animProp.mTimePeriod.delaySeconds    = 0.f;
1508         animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1509         if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1510         {
1511           mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1512                                 animDef.mName.c_str(),
1513                                 animDef.mProperties.size(),
1514                                 animProp.mTimePeriod.durationSeconds));
1515         }
1516
1517         std::string alphaFunctionValue;
1518         if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1519         {
1520           animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1521         }
1522
1523         if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1524         {
1525           DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1526
1527           std::ifstream binAniFile;
1528           std::string   animationFilename;
1529           if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1530           {
1531             std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
1532             binAniFile.open(animationFullPath, std::ios::binary);
1533             if(binAniFile.fail())
1534             {
1535               ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1536             }
1537           }
1538
1539           int byteOffset = 0;
1540           ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1541           DALI_ASSERT_ALWAYS(byteOffset >= 0);
1542
1543           binAniFile.seekg(byteOffset, std::ios::beg);
1544
1545           int numKeys = 0;
1546           ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1547           DALI_ASSERT_ALWAYS(numKeys >= 0);
1548
1549           animProp.mKeyFrames = KeyFrames::New();
1550
1551           //In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1552           //so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1553           // otherwise are blend shape weight keys.
1554           // TODO support for binary header with size information
1555           Property::Type propType = Property::FLOAT; // assume blend shape weights
1556           if(animProp.mPropertyName == "orientation")
1557           {
1558             propType = Property::VECTOR4;
1559           }
1560           else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1561           {
1562             propType = Property::VECTOR3;
1563           }
1564
1565           //alphafunction is reserved for future implementation
1566           // NOTE: right now we're just using AlphaFunction::LINEAR.
1567           unsigned char dummyAlphaFunction;
1568
1569           float           progress;
1570           Property::Value propValue;
1571           for(int key = 0; key < numKeys; key++)
1572           {
1573             binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1574             if(propType == Property::VECTOR3)
1575             {
1576               Vector3 value;
1577               binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1578               propValue = Property::Value(value);
1579             }
1580             else if(propType == Property::VECTOR4)
1581             {
1582               Vector4 value;
1583               binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1584               propValue = Property::Value(Quaternion(value));
1585             }
1586             else
1587             {
1588               float value;
1589               binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1590               propValue = Property::Value(value);
1591             }
1592
1593             binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1594
1595             animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1596           }
1597         }
1598         else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1599         {
1600           DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1601           animProp.mKeyFrames = KeyFrames::New();
1602
1603           float progress = 0.0f;
1604           for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1605           {
1606             const TreeNode::KeyNodePair& kfKeyChild = *i0;
1607             bool                         readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1608             DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1609
1610             const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1611             DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1612
1613             // For the "orientation" property, convert from Vector4 -> Rotation value
1614             // This work-around is preferable to a null-pointer exception in the DALi update thread
1615             Property::Value propValue(ReadPropertyValue(*tnValue));
1616             if(propValue.GetType() == Property::VECTOR4 &&
1617                animProp.mPropertyName == "orientation")
1618             {
1619               Vector4 v;
1620               propValue.Get(v);
1621               propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1622             }
1623
1624             AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1625             std::string   alphaFuncStr;
1626             if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1627             {
1628               kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1629             }
1630
1631             animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1632           }
1633         }
1634         else
1635         {
1636           const TreeNode* tnValue = tnProperty.GetChild("value");
1637           if(tnValue)
1638           {
1639             animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1640             ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1641           }
1642           else
1643           {
1644             mOnError(FormatString("Property '%s' fails to define target value.",
1645                                   animProp.mPropertyName.c_str()));
1646           }
1647         }
1648
1649         animDef.mProperties.push_back(std::move(animProp));
1650       }
1651     }
1652
1653     if(overwrite)
1654     {
1655       *iFind = std::move(animDef);
1656     }
1657     else
1658     {
1659       iFind = definitions.insert(iFind, std::move(animDef));
1660     }
1661
1662     if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
1663     {
1664       Property::Map map;
1665       ParseProperties(tnAnim, map);
1666       proc(animDef, std::move(map), mOnError);
1667     }
1668   }
1669 }
1670
1671 void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1672 {
1673   auto& animGroups = params.output.mAnimationGroupDefinitions;
1674
1675   int numGroups = 0;
1676   for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1677       iGroups != iGroupsEnd;
1678       ++iGroups, ++numGroups)
1679   {
1680     const auto& tnGroup = *iGroups;
1681     auto        tnName  = tnGroup.second.GetChild(NAME);
1682     std::string groupName;
1683     if(!tnName || !ReadString(tnName, groupName))
1684     {
1685       mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1686       continue;
1687     }
1688
1689     auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) {
1690       return group.mName < name;
1691     });
1692     if(iFind != animGroups.end() && iFind->mName == groupName)
1693     {
1694       mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1695     }
1696     else
1697     {
1698       iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1699     }
1700
1701     iFind->mName = groupName;
1702
1703     auto tnAnims = tnGroup.second.GetChild("animations");
1704     if(tnAnims && tnAnims->Size() > 0)
1705     {
1706       auto& anims = iFind->mAnimations;
1707       anims.reserve(anims.size() + tnAnims->Size());
1708       for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1709       {
1710         anims.push_back((*iAnims).second.GetString());
1711       }
1712     }
1713   }
1714 }
1715
1716 void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
1717 {
1718   if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1719   {
1720     cameras.resize(jsonCameras->Size());
1721     auto iCamera = cameras.begin();
1722     for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1723     {
1724       auto& jsonCamera = (*i0).second;
1725
1726       ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
1727       ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1728       ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1729       if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
1730       {
1731         iCamera->isPerspective = false;
1732       }
1733
1734       if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1735       {
1736         ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1737       }
1738
1739       ++iCamera;
1740     }
1741   }
1742 }
1743
1744 void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
1745 {
1746   if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1747   {
1748     lights.resize(jsonLights->Size());
1749     auto iLight = lights.begin();
1750     for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1751     {
1752       auto& jsonLight = (*i0).second;
1753       if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1754       {
1755         mOnError(
1756           FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1757                        std::distance(jsonLights->CBegin(), i0)));
1758         continue;
1759       }
1760
1761       int shadowMapSize = 0;
1762       if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1763       {
1764         mOnError(
1765           FormatString("Failed to parse light %d - %s has an invalid value.",
1766                        std::distance(jsonLights->CBegin(), i0),
1767                        SHADOW_MAP_SIZE));
1768         continue;
1769       }
1770       iLight->shadowMapSize = shadowMapSize;
1771
1772       float orthoSize = 0.f;
1773       if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1774          (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1775       {
1776         mOnError(
1777           FormatString("Failed to parse light %d - %s has an invalid value.",
1778                        std::distance(jsonLights->CBegin(), i0),
1779                        ORTHOGRAPHIC_SIZE));
1780         continue;
1781       }
1782       iLight->orthographicSize = orthoSize;
1783
1784       if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1785       {
1786         mOnError(FormatString(
1787           "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1788           std::distance(jsonLights->CBegin(), i0)));
1789       }
1790
1791       if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1792       {
1793         iLight->color = Vector3::ONE; // default to white
1794       }
1795
1796       if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1797       {
1798         iLight->intensity = 1.0f; // default to 1.0
1799       }
1800
1801       if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1802       {
1803         iLight->shadowIntensity = 1.0f; // default to 1.0
1804       }
1805
1806       ++iLight;
1807     }
1808   }
1809 }
1810
1811 } // namespace Loader
1812 } // namespace Scene3D
1813 } // namespace Dali