[dali_2.1.32] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / scene-definition.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 // EXTERNAL
19 #include "dali/devel-api/common/map-wrapper.h"
20 #include "dali/public-api/animation/constraints.h"
21
22 // INTERNAL
23 #include "dali-scene3d/internal/graphics/builtin-shader-extern-gen.h"
24 #include "dali-scene3d/public-api/loader/blend-shape-details.h"
25 #include "dali-scene3d/public-api/loader/scene-definition.h"
26 #include "dali-scene3d/public-api/loader/skinning-details.h"
27 #include "dali-scene3d/public-api/loader/utils.h"
28
29 //#define DEBUG_SCENE_DEFINITION
30 //#define DEBUG_JOINTS
31
32 #if defined(DEBUG_SCENE_DEFINITION) || defined(DEBUG_JOINTS)
33 #define DEBUG_ONLY(x) x
34 #else
35 #define DEBUG_ONLY(x)
36 #endif
37
38 #define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout))
39
40 namespace Dali
41 {
42 namespace Scene3D
43 {
44 namespace Loader
45 {
46 namespace
47 {
48 const std::string JOINT_MATRIX{"jointMatrix"};
49
50 const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)> sConstraintFactory = {
51   {Property::Type::BOOLEAN,
52    [](Actor& a, Property::Index i) {
53      return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) {
54        current = inputs[0]->GetBoolean();
55      });
56    }},
57   {Property::Type::INTEGER,
58    [](Actor& a, Property::Index i) {
59      return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) {
60        current = inputs[0]->GetInteger();
61      });
62    }},
63   {Property::Type::FLOAT,
64    [](Actor& a, Property::Index i) {
65      return Constraint::New<float>(a, i, EqualToConstraint());
66    }},
67   {Property::Type::VECTOR2,
68    [](Actor& a, Property::Index i) {
69      return Constraint::New<Vector2>(a, i, EqualToConstraint());
70    }},
71   {Property::Type::VECTOR3,
72    [](Actor& a, Property::Index i) {
73      return Constraint::New<Vector3>(a, i, EqualToConstraint());
74    }},
75   {Property::Type::VECTOR4,
76    [](Actor& a, Property::Index i) {
77      return Constraint::New<Vector4>(a, i, EqualToConstraint());
78    }},
79   {Property::Type::MATRIX,
80    [](Actor& a, Property::Index i) {
81      return Constraint::New<Matrix>(a, i, EqualToConstraint());
82    }},
83   {Property::Type::MATRIX3,
84    [](Actor& a, Property::Index i) {
85      return Constraint::New<Matrix3>(a, i, EqualToConstraint());
86    }},
87   {Property::Type::ROTATION,
88    [](Actor& a, Property::Index i) {
89      return Constraint::New<Quaternion>(a, i, EqualToConstraint());
90    }},
91 };
92
93 struct ResourceReflector : IResourceReflector
94 {
95   Index* iMesh   = nullptr;
96   Index* iShader = nullptr;
97
98   void Reflect(ResourceType::Value type, Index& id)
99   {
100     switch(type)
101     {
102       case ResourceType::Shader:
103         DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
104         iShader = &id;
105         break;
106
107       case ResourceType::Mesh:
108         DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
109         iMesh = &id;
110         break;
111
112       default: // Other resource types are not relevant to the problem at hand.
113         break;
114     }
115   }
116 };
117
118 #ifdef DEBUG_JOINTS
119
120 Shader sJointDebugShader;
121 int    sNumScenes = 0;
122
123 void EnsureJointDebugShaderCreated()
124 {
125   if(0 == sNumScenes)
126   {
127     sJointDebugShader = Shader::New(SHADER_SCENE3D_JOINT_DEBUG_VERT, SHADER_SCENE3D_JOINT_DEBUG_FRAG);
128   }
129   ++sNumScenes;
130 }
131
132 void AddJointDebugVisual(Actor aJoint)
133 {
134   Property::Map attribs;
135   attribs["aPosition"] = Property::Type::VECTOR3;
136   attribs["aColor"]    = Property::Type::FLOAT;
137
138   PropertyBuffer vbo = PropertyBuffer::New(attribs);
139
140   struct Vertex
141   {
142     Vector3 pos;
143     float   color;
144   } vertices[] = {
145     {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f},
146     {Vector3::XAXIS, .999f},
147     {Vector3::YAXIS, .999f * 256.f},
148     {Vector3::ZAXIS, .999f * 256.f * 256.f},
149   };
150
151   vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
152
153   uint16_t indices[] = {0, 1, 0, 2, 0, 3};
154
155   Geometry geo = Geometry::New();
156   geo.AddVertexBuffer(vbo);
157   geo.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
158   geo.SetType(Geometry::LINES);
159
160   Renderer r = Renderer::New(geo, sJointDebugShader);
161   aJoint.AddRenderer(r);
162
163   aJoint.SetVisible(true);
164 }
165 #endif //DEBUG_JOINTS
166
167 class ActorCreatorVisitor : public NodeDefinition::IConstVisitor
168 {
169 public:
170   ActorCreatorVisitor(NodeDefinition::CreateParams& params)
171   : mCreationContext(params)
172   {
173   }
174
175   void Start(const NodeDefinition& n)
176   {
177     mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
178
179     Actor a = n.CreateActor(mCreationContext);
180     if(!mActorStack.empty())
181     {
182       mActorStack.back().Add(a);
183     }
184     else
185     {
186       mRoot = a;
187     }
188     mActorStack.push_back(a);
189   }
190
191   void Finish(const NodeDefinition& n)
192   {
193     mActorStack.pop_back();
194     mCreationContext.mXforms.modelStack.Pop();
195   }
196
197   Actor GetRoot() const
198   {
199     return mRoot;
200   }
201
202 private:
203   NodeDefinition::CreateParams& mCreationContext;
204   std::vector<Actor>            mActorStack;
205   Actor                         mRoot;
206 };
207
208 bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX)
209 {
210   bool isAncestor = false;
211   while(node != rootHint && !isAncestor)
212   {
213     node       = scene.GetNode(node)->mParentIdx;
214     isAncestor = ancestor == node;
215   }
216   return isAncestor;
217 }
218
219 void InsertUniqueSorted(std::vector<Index>& data, Index value)
220 {
221   auto iInsert = std::lower_bound(data.begin(), data.end(), value);
222   if(iInsert == data.end() || *iInsert != value)
223   {
224     data.insert(iInsert, value);
225   }
226 }
227
228 void RemoveFromSorted(std::vector<Index>& data, Index value)
229 {
230   auto iRemove = std::lower_bound(data.begin(), data.end(), value);
231   if(iRemove != data.end() && *iRemove == value)
232   {
233     data.erase(iRemove);
234   }
235 }
236
237 Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix)
238 {
239   Actor parent = actor.GetParent();
240   if(parent != ancestor)
241   {
242     propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix);
243   }
244
245   auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX);
246   if(myPropJointMatrix == Property::INVALID_INDEX)
247   {
248     myPropJointMatrix     = actor.RegisterProperty(JOINT_MATRIX, Matrix{false});
249     Constraint constraint = Constraint::New<Matrix>(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
250       Matrix jointMatrix{false};
251       jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
252
253       Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
254     });
255     constraint.AddSource(Source{actor, Actor::Property::ORIENTATION});
256     constraint.AddSource(Source{actor, Actor::Property::POSITION});
257     constraint.AddSource(Source{parent, propJointMatrix});
258     constraint.Apply();
259   }
260
261   return myPropJointMatrix;
262 }
263
264 void SortAndDeduplicateSkinningRequests(std::vector<SkinningShaderConfigurationRequest>& requests)
265 {
266   // Sort requests by shaders.
267   std::sort(requests.begin(), requests.end());
268
269   // Remove duplicates.
270   auto   i           = requests.begin();
271   auto   iEnd        = requests.end();
272   Shader s           = i->mShader;
273   Index  skeletonIdx = i->mSkeletonIdx;
274   ++i;
275   do
276   {
277     // Multiple identical shader instances are removed.
278     while(i != iEnd && i->mShader == s)
279     {
280       // Cannot have multiple skeletons input to the same shader.
281       // NOTE: DliModel now makes sure this doesn't happen.
282       DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx &&
283                          "Skinning shader must not be shared between different skeletons.");
284
285       i->mShader = Shader();
286       ++i;
287     }
288
289     if(i == iEnd)
290     {
291       break;
292     }
293     s           = i->mShader;
294     skeletonIdx = i->mSkeletonIdx;
295     ++i;
296   } while(true);
297
298   requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) {
299                    return !sscr.mShader;
300                  }),
301                  requests.end());
302 }
303
304 void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx)
305 {
306   // Register bone transform on shader.
307   char propertyNameBuffer[32];
308   snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx);
309   DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX);
310   auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false});
311
312   // Constrain bone matrix to joint transform.
313   Constraint constraint = Constraint::New<Matrix>(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) {
314     Matrix::Multiply(output, ibm, inputs[0]->GetMatrix());
315   });
316
317   auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX);
318   constraint.AddSource(Source{joint, propJointMatrix});
319   constraint.Apply();
320
321   ++boneIdx;
322 }
323
324 template<class Visitor, class SceneDefinition>
325 void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
326 {
327   auto& node = *sd.GetNode(iNode);
328   v.Start(node);
329
330   if(node.mCustomization)
331   {
332     if(!node.mChildren.empty())
333     {
334       auto  choice = choices.Get(node.mCustomization->mTag);
335       Index i      = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
336       sd.Visit(node.mChildren[i], choices, v);
337     }
338   }
339   else
340   {
341     for(auto i : node.mChildren)
342     {
343       sd.Visit(i, choices, v);
344     }
345   }
346
347   v.Finish(node);
348 }
349
350 } // namespace
351
352 SceneDefinition::SceneDefinition()
353 {
354   mNodes.reserve(128);
355
356 #ifdef DEBUG_JOINTS
357   EnsureJointDebugShaderCreated();
358 #endif
359 }
360
361 SceneDefinition::SceneDefinition(SceneDefinition&& other)
362 : mNodes(std::move(other.mNodes)),
363   mRootNodeIds(std::move(other.mRootNodeIds))
364 {
365 #ifdef DEBUG_JOINTS
366   EnsureJointDebugShaderCreated();
367 #endif
368 }
369
370 SceneDefinition::~SceneDefinition()
371 {
372 #ifdef DEBUG_JOINTS
373   --sNumScenes;
374   if(sNumScenes == 0)
375   {
376     sJointDebugShader = Shader();
377   }
378 #endif
379 }
380
381 uint32_t Dali::Scene3D::Loader::SceneDefinition::AddRootNode(Index iNode)
382 {
383   if(iNode < mNodes.size())
384   {
385     uint32_t result = mRootNodeIds.size();
386     mRootNodeIds.push_back(iNode);
387     return result;
388   }
389   else
390   {
391     ExceptionFlinger(ASSERT_LOCATION) << "Failed to add new root with node " << iNode << " -- index out of bounds.";
392     return -1;
393   }
394 }
395
396 const std::vector<Index>& SceneDefinition::GetRoots() const
397 {
398   return mRootNodeIds;
399 }
400
401 void SceneDefinition::RemoveRootNode(Index iRoot)
402 {
403   if(iRoot < mRootNodeIds.size())
404   {
405     mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
406   }
407   else
408   {
409     ExceptionFlinger(ASSERT_LOCATION) << "Failed to remove root " << iRoot << " -- index out of bounds.";
410   }
411 }
412
413 uint32_t SceneDefinition::GetNodeCount() const
414 {
415   return mNodes.size();
416 }
417
418 const NodeDefinition* SceneDefinition::GetNode(Index iNode) const
419 {
420   return mNodes[iNode].get();
421 }
422
423 NodeDefinition* SceneDefinition::GetNode(Index iNode)
424 {
425   return mNodes[iNode].get();
426 }
427
428 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IVisitor& v)
429 {
430   VisitInternal(iNode, choices, v, *this);
431 }
432
433 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IConstVisitor& v) const
434 {
435   VisitInternal(iNode, choices, v, *this);
436 }
437
438 void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choices& choices, ResourceRefCounts& refCounts) const
439 {
440   struct RefCounter : IResourceReceiver
441   {
442     ResourceRefCounts* refCounts;
443
444     void Register(ResourceType::Value type, Index id)
445     {
446       ++(*refCounts)[type][id];
447     }
448   };
449
450   struct : NodeDefinition::IConstVisitor
451   {
452     RefCounter counter;
453
454     void Start(const NodeDefinition& n)
455     {
456       if(n.mRenderable)
457       {
458         n.mRenderable->RegisterResources(counter);
459       }
460     }
461
462     void Finish(const NodeDefinition& n)
463     {
464     }
465
466   } refCounterVisitor;
467   refCounterVisitor.counter.refCounts = &refCounts;
468
469   Visit(iNode, choices, refCounterVisitor);
470 }
471
472 Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const
473 {
474   ActorCreatorVisitor actorCreatorVisitor(params);
475
476   Visit(iNode, choices, actorCreatorVisitor);
477
478   return actorCreatorVisitor.GetRoot();
479 }
480
481 void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
482                                               Customization::Map&           outCustomizationOptions,
483                                               Customization::Choices*       outMissingChoices) const
484 {
485   struct : NodeDefinition::IConstVisitor
486   {
487     const Customization::Choices* choices;        // choices that we know about.
488     Customization::Map*           options;        // tags are registered here. NO OWNERSHIP.
489     Customization::Choices*       missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
490
491     void Start(const NodeDefinition& n)
492     {
493       if(n.mCustomization)
494       {
495         const std::string& tag = n.mCustomization->mTag;
496         if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
497         {
498           missingChoices->Set(tag, 0);
499         }
500
501         auto customization = options->Get(tag);
502         if(!customization)
503         {
504           customization = options->Set(tag, {});
505         }
506         customization->nodes.push_back(n.mName);
507         customization->numOptions = std::max(customization->numOptions,
508                                              static_cast<uint32_t>(n.mChildren.size()));
509       }
510     }
511
512     void Finish(const NodeDefinition& n)
513     {
514     }
515
516   } customizationRegistrationVisitor;
517   customizationRegistrationVisitor.choices        = &choices;
518   customizationRegistrationVisitor.options        = &outCustomizationOptions;
519   customizationRegistrationVisitor.missingChoices = outMissingChoices;
520
521   for(auto i : mRootNodeIds)
522   {
523     Visit(i, choices, customizationRegistrationVisitor);
524   }
525 }
526
527 NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
528 {
529   if(FindNode(nodeDef->mName))
530   {
531     return nullptr;
532   }
533
534   // add next index (to which we're about to push) as a child to the designated parent, if any.
535   if(nodeDef->mParentIdx != INVALID_INDEX)
536   {
537     mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
538   }
539
540   mNodes.push_back(std::move(nodeDef));
541
542   return mNodes.back().get();
543 }
544
545 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
546 {
547   LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
548
549   std::unique_ptr<NodeDefinition>* nodePtr      = nullptr;
550   std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
551   if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
552   {
553     return false;
554   }
555
556   auto& node  = *nodePtr;
557   auto  iNode = std::distance(mNodes.data(), nodePtr);
558
559   DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
560     std::ostringstream stream;
561     stream << n.mName << " (" << n.mParentIdx << "):";
562     for(auto i : n.mChildren)
563     {
564       stream << i << ", ";
565     }
566     LOGD(("%s", stream.str().c_str()));
567   };)
568
569   // Remove node from children of previous parent (if any).
570   if(node->mParentIdx != INVALID_INDEX)
571   {
572     LOGD(("old parent:"));
573     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
574
575     auto& children = mNodes[node->mParentIdx]->mChildren;
576     children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
577
578     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
579   }
580
581   // Register node to new parent.
582   LOGD(("new parent:"));
583   DEBUG_ONLY(dumpNode(**newParentPtr);)
584   auto& children = (*newParentPtr)->mChildren;
585   if(siblingOrder > children.size())
586   {
587     siblingOrder = children.size();
588   }
589   children.insert(children.begin() + siblingOrder, 1, iNode);
590   DEBUG_ONLY(dumpNode(**newParentPtr);)
591
592   // Update parent index.
593   LOGD(("node:"));
594   DEBUG_ONLY(dumpNode(*node);)
595   auto iParent     = std::distance(mNodes.data(), newParentPtr);
596   node->mParentIdx = iParent;
597   DEBUG_ONLY(dumpNode(*node);)
598   return true;
599 }
600
601 bool SceneDefinition::RemoveNode(const std::string& name)
602 {
603   std::unique_ptr<NodeDefinition>* node = nullptr;
604   if(!FindNode(name, &node))
605   {
606     return false;
607   }
608
609   // Reset node def pointers recursively.
610   auto&                                                 thisNodes = mNodes;
611   unsigned int                                          numReset  = 0;
612   std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
613     [&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
614       LOGD(("resetting %d", &nd - thisNodes.data()));
615       for(auto i : nd->mChildren)
616       {
617         resetFn(thisNodes[i]);
618       }
619       nd.reset();
620       ++numReset;
621     };
622
623   resetFn(*node);
624
625   // Gather indices of dead nodes into a vector which we sort on insertion.
626   std::vector<Index> offsets;
627   offsets.reserve(numReset);
628   for(auto& n : mNodes)
629   {
630     if(!n)
631     {
632       offsets.push_back(std::distance(mNodes.data(), &n));
633     }
634   }
635
636   // Erase dead nodes as they don't have to be processed anymore.
637   mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
638
639   // Offset all indices (parent and child) by the index they'd sort into in offsets.
640   enum
641   {
642     INDEX_FOR_REMOVAL = INVALID_INDEX
643   };
644   auto offsetter = [&offsets](Index& i) {
645     auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
646     if(iFind != offsets.end() && *iFind == i)
647     {
648       LOGD(("marking %d for removal.", i));
649       i = INDEX_FOR_REMOVAL;
650       return false;
651     }
652     else
653     {
654       auto distance = std::distance(offsets.begin(), iFind);
655       if(distance > 0)
656       {
657         LOGD(("offsetting %d by %d.", i, distance));
658         i -= distance;
659       }
660       return true;
661     }
662   };
663
664   for(auto& nd : mNodes)
665   {
666     bool parentOffsetResult = offsetter(nd->mParentIdx);
667     DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
668
669     auto& children = nd->mChildren;
670     for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
671     {
672       offsetter(*i0);
673     }
674
675     children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
676   }
677
678   return true;
679 }
680
681 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
682 {
683   auto&                    thisNodes  = mNodes;
684   std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
685     auto node = thisNodes[i].get();
686     if(node->mParentIdx != INVALID_INDEX)
687     {
688       buildStack(node->mParentIdx);
689     }
690     model.Push(node->GetLocalSpace());
691   };
692   buildStack(index);
693 }
694
695 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
696 {
697   auto iBegin = mNodes.begin();
698   auto iEnd   = mNodes.end();
699   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
700     return nd->mName == name;
701   });
702
703   auto result = iFind != iEnd ? iFind->get() : nullptr;
704   if(result && outIndex)
705   {
706     *outIndex = std::distance(iBegin, iFind);
707   }
708   return result;
709 }
710
711 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
712 {
713   auto iBegin = mNodes.begin();
714   auto iEnd   = mNodes.end();
715   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
716     return nd->mName == name;
717   });
718
719   auto result = iFind != iEnd ? iFind->get() : nullptr;
720   if(result && outIndex)
721   {
722     *outIndex = std::distance(iBegin, iFind);
723   }
724   return result;
725 }
726
727 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
728 {
729   auto iBegin = mNodes.begin();
730   auto iEnd   = mNodes.end();
731   auto iFind  = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
732     return n.get() == &node;
733   });
734   return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
735 }
736
737 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
738 {
739   unsigned int n = 0;
740   for(auto& defp : mNodes)
741   {
742     if(predicate(*defp))
743     {
744       consumer(*defp);
745       ++n;
746       if(n == limit)
747       {
748         break;
749       }
750     }
751   }
752 }
753
754 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
755 {
756   unsigned int n = 0;
757   for(auto& defp : mNodes)
758   {
759     if(predicate(*defp))
760     {
761       consumer(*defp);
762       ++n;
763       if(n == limit)
764       {
765         break;
766       }
767     }
768   }
769 }
770
771 void SceneDefinition::ApplyConstraints(Actor&                           root,
772                                        std::vector<ConstraintRequest>&& constrainables,
773                                        StringCallback                   onError) const
774 {
775   for(auto& cr : constrainables)
776   {
777     auto&           nodeDef    = mNodes[cr.mConstraint->mSourceIdx];
778     auto            sourceName = nodeDef->mName.c_str();
779     Property::Index iTarget    = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
780     if(iTarget != Property::INVALID_INDEX)
781     {
782       auto propertyType = cr.mTarget.GetPropertyType(iTarget);
783       auto iFind        = sConstraintFactory.find(propertyType);
784       if(iFind == sConstraintFactory.end())
785       {
786         onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
787                              sourceName,
788                              cr.mConstraint->mProperty.c_str(),
789                              PropertyTypes::GetName(propertyType)));
790         continue;
791       }
792
793       Constraint constraint = iFind->second(cr.mTarget, iTarget);
794
795       Actor source = root.FindChildByName(nodeDef->mName);
796       if(!source)
797       {
798         auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
799         onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
800                              sourceName,
801                              cr.mConstraint->mProperty.c_str(),
802                              targetName.c_str()));
803         continue;
804       }
805       else if(source == cr.mTarget)
806       {
807         onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
808                              sourceName,
809                              cr.mConstraint->mProperty.c_str()));
810         continue;
811       }
812
813       Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
814       constraint.AddSource(Source{source, iSource});
815       constraint.Apply();
816     }
817     else
818     {
819       auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
820       onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
821                            sourceName,
822                            cr.mConstraint->mProperty.c_str(),
823                            targetName.c_str()));
824     }
825   }
826 }
827
828 void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefinition::Vector& skeletons, Actor root) const
829 {
830   // 1, For each skeleton, for each joint, walk upwards until we reach mNodes[iRoot]. If we do, record +1
831   // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1
832   // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton.
833   std::map<Index, std::vector<Index>> rootsJoints;
834   std::vector<Index>                  path;
835   path.reserve(16);
836   for(auto& s : skeletons)
837   {
838     std::map<uint32_t, uint32_t> jointRefs;
839     for(auto& j : s.mJoints)
840     {
841       auto nodeIdx = j.mNodeIdx;
842       do // Traverse upwards and record each node we have visited until we reach the scene root.
843       {
844         path.push_back(nodeIdx);
845         if(nodeIdx == iRoot)
846         {
847           break;
848         }
849         auto node = GetNode(nodeIdx);
850         nodeIdx   = node->mParentIdx;
851       } while(nodeIdx != INVALID_INDEX);
852
853       if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
854       {
855         for(auto i : path)
856         {
857           ++jointRefs[i];
858         }
859       }
860
861       path.clear();
862     }
863
864     // Only record the skeleton if we have encountered the root of the current scene.
865     if(jointRefs.empty())
866     {
867       continue;
868     }
869
870     Index    root   = s.mRootNodeIdx;
871     uint32_t maxRef = 0;
872     auto     iFind  = jointRefs.find(root);
873     if(iFind != jointRefs.end())
874     {
875       maxRef = iFind->second;
876     }
877
878     std::vector<Index> joints;
879     for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
880     {
881       // The most descendant node with the highest ref count is the root of the skeleton.
882       if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
883       {
884         maxRef = j.second;
885
886         RemoveFromSorted(joints, root);
887         root = j.first;
888       }
889       else if(j.second == 1) // This one's a leaf.
890       {
891         InsertUniqueSorted(joints, j.first);
892       }
893     }
894
895     // Merge skeletons that share the same root.
896     auto& finalJoints = rootsJoints[root];
897     for(auto j : joints)
898     {
899       if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
900            return IsAncestor(*this, j, jj, root);
901          }) != finalJoints.end())
902       {
903         continue; // if the joint is found to be an ancestor of another joint already registered, move on.
904       }
905
906       auto i = j;
907       while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
908       {
909         auto node = GetNode(i);
910         i         = node->mParentIdx;
911
912         RemoveFromSorted(finalJoints, i);
913       }
914
915       InsertUniqueSorted(finalJoints, j);
916     }
917   }
918
919   // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous
920   // leaf nodes that now have descendants, and add new ones.
921   auto iRoots    = rootsJoints.begin();
922   auto iRootsEnd = rootsJoints.end();
923   while(iRoots != iRootsEnd)
924   {
925     auto i      = iRoots->first;
926     bool merged = false;
927     while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
928     {
929       auto node = GetNode(i);
930       i         = node->mParentIdx;
931
932       auto iFind = rootsJoints.find(i);
933       if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
934       {
935         // Now find out which leaf of iFind is an ancestor, if any.
936         auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) {
937           return IsAncestor(*this, j, iRoots->first, iFind->first);
938         });
939         if(iFindLeaf != iFind->second.end())
940         {
941           iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
942         }
943
944         // Merge iRoots with iFind
945         auto& targetJoints = iFind->second;
946         if(iRoots->second.empty()) // The root is a leaf.
947         {
948           InsertUniqueSorted(targetJoints, iRoots->first);
949         }
950         else
951           for(auto j : iRoots->second)
952           {
953             InsertUniqueSorted(targetJoints, j);
954           }
955
956         merged = true;
957         break; // Traverse no more
958       }
959     }
960
961     iRoots = merged ? rootsJoints.erase(iRoots) : std::next(iRoots);
962   }
963
964   // 3, For each root, register joint matrices and constraints
965   for(auto r : rootsJoints)
966   {
967     auto node      = GetNode(r.first);
968     auto rootJoint = root.FindChildByName(node->mName);
969     DALI_ASSERT_ALWAYS(!!rootJoint);
970
971     DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX);
972     auto       propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false});
973     Constraint constraint      = Constraint::New<Matrix>(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
974       output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
975     });
976     constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
977     constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
978     constraint.Apply();
979
980     for(auto j : r.second)
981     {
982       node       = GetNode(j);
983       auto joint = rootJoint.FindChildByName(node->mName);
984       ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
985     }
986   }
987 }
988
989 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
990 {
991   std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
992   for(auto& node : mNodes)
993   {
994     if(node->mRenderable)
995     {
996       ResourceReflector reflector;
997       node->mRenderable->ReflectResources(reflector);
998
999       if(reflector.iMesh)
1000       {
1001         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1002         if(mesh.IsSkinned())
1003         {
1004           skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
1005         }
1006       }
1007     }
1008   }
1009
1010   // For each shader, and each skeleton using the same shader as the first skeleton,
1011   // update the shader references (from nodes with skinned meshes) with a new copy of
1012   // the shader definition from the node using the first skeleton.
1013   for(auto& users : skinningShaderUsers)
1014   {
1015     auto& skeletons    = users.second;
1016     auto  iterSkeleton = skeletons.begin();
1017     // skipping the first skeleton.
1018     ++iterSkeleton;
1019
1020     resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
1021     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1022
1023     while(iterSkeleton != skeletons.end())
1024     {
1025       Index iShader = resources.mShaders.size();
1026       resources.mShaders.push_back({shaderDef, Shader()});
1027
1028       for(auto& i : iterSkeleton->second)
1029       {
1030         *i = iShader;
1031       }
1032       ++iterSkeleton;
1033     }
1034   }
1035 }
1036
1037 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle&                             resources,
1038                                                Actor                                             rootActor,
1039                                                std::vector<SkinningShaderConfigurationRequest>&& requests) const
1040 {
1041   if(requests.empty())
1042   {
1043     return;
1044   }
1045
1046   SortAndDeduplicateSkinningRequests(requests);
1047
1048   for(auto& i : requests)
1049   {
1050     auto& skeleton = resources.mSkeletons[i.mSkeletonIdx];
1051     if(skeleton.mJoints.empty())
1052     {
1053       LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx));
1054       continue;
1055     }
1056
1057     Index boneIdx = 0;
1058     for(auto& j : skeleton.mJoints)
1059     {
1060       auto  node  = GetNode(j.mNodeIdx);
1061       Actor actor = rootActor.FindChildByName(node->mName);
1062       ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx);
1063     }
1064   }
1065 }
1066
1067 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle&                               resources,
1068                                                  Actor                                               rootActor,
1069                                                  std::vector<BlendshapeShaderConfigurationRequest>&& requests,
1070                                                  StringCallback                                      onError) const
1071 {
1072   if(requests.empty())
1073   {
1074     return true;
1075   }
1076
1077   // Sort requests by shaders.
1078   std::sort(requests.begin(), requests.end());
1079
1080   // Remove duplicates.
1081   auto   i    = requests.begin();
1082   auto   iEnd = requests.end();
1083   Shader s    = i->mShader;
1084   ++i;
1085   do
1086   {
1087     // Multiple identical shader instances are removed.
1088     while(i != iEnd && i->mShader == s)
1089     {
1090       i->mShader = Shader();
1091       ++i;
1092     }
1093
1094     if(i == iEnd)
1095     {
1096       break;
1097     }
1098     s = i->mShader;
1099     ++i;
1100   } while(true);
1101
1102   // Configure the rest.
1103   bool ok = true;
1104
1105   for(auto& i : requests)
1106   {
1107     Index iNode;
1108     if(FindNode(i.mNodeName, &iNode))
1109     {
1110       const auto& node = GetNode(iNode);
1111
1112       const auto& mesh = resources.mMeshes[i.mMeshIdx];
1113
1114       if(mesh.first.HasBlendShapes())
1115       {
1116         Actor actor = rootActor.FindChildByName(node->mName);
1117
1118         // Sets the property to be animated.
1119         BlendShapes::ConfigureProperties(mesh, i.mShader, actor);
1120       }
1121     }
1122   }
1123
1124   return ok;
1125 }
1126
1127 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
1128 {
1129   std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
1130   for(auto& node : mNodes)
1131   {
1132     if(node->mRenderable)
1133     {
1134       ResourceReflector reflector;
1135       node->mRenderable->ReflectResources(reflector);
1136
1137       if(reflector.iMesh)
1138       {
1139         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1140         if(mesh.HasBlendShapes())
1141         {
1142           blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
1143         }
1144       }
1145     }
1146   }
1147
1148   for(auto& users : blendShapeShaderUsers)
1149   {
1150     resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
1151     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1152
1153     auto nodesIt    = users.second.begin();
1154     auto nodesEndIt = users.second.end();
1155     // skipping the first node.
1156     ++nodesIt;
1157     while(nodesIt != nodesEndIt)
1158     {
1159       Index iShader = resources.mShaders.size();
1160       resources.mShaders.push_back({shaderDef, Shader()});
1161
1162       auto& nodes = *nodesIt;
1163       for(auto& shader : nodes.second)
1164       {
1165         *shader = iShader;
1166       }
1167       ++nodesIt;
1168     }
1169   }
1170 }
1171
1172 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
1173 {
1174   SceneDefinition temp(std::move(other));
1175   std::swap(mNodes, temp.mNodes);
1176   std::swap(mRootNodeIds, temp.mRootNodeIds);
1177   return *this;
1178 }
1179
1180 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
1181 {
1182   // We're searching from the end assuming a higher probability of operations targeting
1183   // recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
1184   // the first to be added, is index 0.)
1185   auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) {
1186                  return nd->mName == name;
1187                }).base();
1188
1189   const bool success = iFind != mNodes.begin();
1190   if(success && result)
1191   {
1192     --iFind;
1193     *result = &*iFind;
1194   }
1195
1196   return success;
1197 }
1198
1199 } // namespace Loader
1200 } // namespace Scene3D
1201 } // namespace Dali