Parse gltf mesh extra and extensions + Get BlendShape index by name
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / scene-definition.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-scene3d/public-api/loader/scene-definition.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/common/map-wrapper.h>
23 #include <dali/public-api/animation/constraints.h>
24
25 // INTERNAL
26 #include <dali-scene3d/internal/graphics/builtin-shader-extern-gen.h>
27 #include <dali-scene3d/internal/model-components/model-node-impl.h>
28 #include <dali-scene3d/public-api/loader/blend-shape-details.h>
29 #include <dali-scene3d/public-api/loader/skinning-details.h>
30 #include <dali-scene3d/public-api/loader/utils.h>
31
32 // #define DEBUG_SCENE_DEFINITION
33 // #define DEBUG_JOINTS
34
35 #if defined(DEBUG_SCENE_DEFINITION) || defined(DEBUG_JOINTS)
36 #define DEBUG_ONLY(x) x
37 #else
38 #define DEBUG_ONLY(x)
39 #endif
40
41 #define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout))
42
43 namespace Dali::Scene3D::Loader
44 {
45 namespace
46 {
47 const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)>& GetConstraintFactory()
48 {
49   static const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)> sConstraintFactory = {
50     {Property::Type::BOOLEAN,
51      [](Actor& a, Property::Index i) {
52        return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) { current = inputs[0]->GetBoolean(); });
53      }},
54     {Property::Type::INTEGER,
55      [](Actor& a, Property::Index i) {
56        return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) { current = inputs[0]->GetInteger(); });
57      }},
58     {Property::Type::FLOAT,
59      [](Actor& a, Property::Index i) {
60        return Constraint::New<float>(a, i, EqualToConstraint());
61      }},
62     {Property::Type::VECTOR2,
63      [](Actor& a, Property::Index i) {
64        return Constraint::New<Vector2>(a, i, EqualToConstraint());
65      }},
66     {Property::Type::VECTOR3,
67      [](Actor& a, Property::Index i) {
68        return Constraint::New<Vector3>(a, i, EqualToConstraint());
69      }},
70     {Property::Type::VECTOR4,
71      [](Actor& a, Property::Index i) {
72        return Constraint::New<Vector4>(a, i, EqualToConstraint());
73      }},
74     {Property::Type::MATRIX,
75      [](Actor& a, Property::Index i) {
76        return Constraint::New<Matrix>(a, i, EqualToConstraint());
77      }},
78     {Property::Type::MATRIX3,
79      [](Actor& a, Property::Index i) {
80        return Constraint::New<Matrix3>(a, i, EqualToConstraint());
81      }},
82     {Property::Type::ROTATION,
83      [](Actor& a, Property::Index i) {
84        return Constraint::New<Quaternion>(a, i, EqualToConstraint());
85      }},
86   };
87   return sConstraintFactory;
88 }
89
90 struct ResourceReflector : IResourceReflector
91 {
92   Index* iMesh   = nullptr;
93   Index* iShader = nullptr;
94
95   void Reflect(ResourceType::Value type, Index& id)
96   {
97     switch(type)
98     {
99       case ResourceType::Shader:
100         DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
101         iShader = &id;
102         break;
103
104       case ResourceType::Mesh:
105         DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
106         iMesh = &id;
107         break;
108
109       default: // Other resource types are not relevant to the problem at hand.
110         break;
111     }
112   }
113 };
114
115 #ifdef DEBUG_JOINTS
116
117 Shader sJointDebugShader;
118 int    sNumScenes = 0;
119
120 void EnsureJointDebugShaderCreated()
121 {
122   if(0 == sNumScenes)
123   {
124     sJointDebugShader = Shader::New(SHADER_SCENE3D_JOINT_DEBUG_VERT, SHADER_SCENE3D_JOINT_DEBUG_FRAG);
125   }
126   ++sNumScenes;
127 }
128
129 void AddJointDebugVisual(Actor aJoint)
130 {
131   Property::Map attribs;
132   attribs["aPosition"] = Property::Type::VECTOR3;
133   attribs["aColor"]    = Property::Type::FLOAT;
134
135   PropertyBuffer vbo = PropertyBuffer::New(attribs);
136
137   struct Vertex
138   {
139     Vector3 pos;
140     float   color;
141   } vertices[] = {
142     {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f},
143     {Vector3::XAXIS, .999f},
144     {Vector3::YAXIS, .999f * 256.f},
145     {Vector3::ZAXIS, .999f * 256.f * 256.f},
146   };
147
148   vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
149
150   uint16_t indices[] = {0, 1, 0, 2, 0, 3};
151
152   Geometry geo = Geometry::New();
153   geo.AddVertexBuffer(vbo);
154   geo.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
155   geo.SetType(Geometry::LINES);
156
157   Renderer r = Renderer::New(geo, sJointDebugShader);
158   aJoint.AddRenderer(r);
159
160   aJoint.SetVisible(true);
161 }
162 #endif //DEBUG_JOINTS
163
164 class ActorCreatorVisitor : public NodeDefinition::IVisitor
165 {
166 public:
167   ActorCreatorVisitor(NodeDefinition::CreateParams& params)
168   : mCreationContext(params)
169   {
170   }
171
172   void Start(NodeDefinition& n)
173   {
174     mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
175
176     ModelNode a = n.CreateModelNode(mCreationContext);
177     if(!mActorStack.empty())
178     {
179       mActorStack.back().Add(a);
180     }
181     else
182     {
183       mRoot = a;
184     }
185     mActorStack.push_back(a);
186   }
187
188   void Finish(NodeDefinition& n)
189   {
190     mActorStack.pop_back();
191     mCreationContext.mXforms.modelStack.Pop();
192   }
193
194   ModelNode GetRoot() const
195   {
196     return mRoot;
197   }
198
199 private:
200   NodeDefinition::CreateParams& mCreationContext;
201   std::vector<ModelNode>        mActorStack;
202   ModelNode                     mRoot;
203 };
204
205 template<typename RequestType>
206 void SortAndDeduplicateRequests(std::vector<RequestType>& requests)
207 {
208   // Sort requests by shaders and primitives.
209   std::sort(requests.begin(), requests.end());
210
211   // Remove duplicates.
212   auto iter    = requests.begin();
213   auto iterEnd = requests.end();
214
215   Shader         shader         = iter->mShader;
216   ModelPrimitive modelPrimitive = iter->mPrimitive;
217   ++iter;
218   do
219   {
220     // Multiple identical shader and primitive instances are removed.
221     while(iter != iterEnd && iter->mShader == shader && iter->mPrimitive == modelPrimitive)
222     {
223       // Mark as removed
224       iter->mShader = Shader();
225       ++iter;
226     }
227
228     if(iter == iterEnd)
229     {
230       break;
231     }
232     shader         = iter->mShader;
233     modelPrimitive = iter->mPrimitive;
234     ++iter;
235   } while(true);
236
237   requests.erase(std::remove_if(requests.begin(), requests.end(), [](const RequestType& sscr) { return !sscr.mShader; }),
238                  requests.end());
239 }
240
241 void ConfigureBoneMatrix(const Matrix& ibm, ModelNode joint, ModelPrimitive primitive, Index& boneIdx)
242 {
243   // Register bone transform on shader.
244   Internal::GetImplementation(joint).SetBoneMatrix(ibm, primitive, boneIdx);
245   ++boneIdx;
246 }
247
248 template<class Visitor, class SceneDefinition>
249 void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
250 {
251   auto& node = *sd.GetNode(iNode);
252   v.Start(node);
253
254   if(node.mCustomization)
255   {
256     if(!node.mChildren.empty())
257     {
258       auto  choice = choices.Get(node.mCustomization->mTag);
259       Index i      = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
260       sd.Visit(node.mChildren[i], choices, v);
261     }
262   }
263   else
264   {
265     for(auto i : node.mChildren)
266     {
267       sd.Visit(i, choices, v);
268     }
269   }
270
271   v.Finish(node);
272 }
273
274 } // namespace
275
276 SceneDefinition::SceneDefinition()
277 {
278   mNodes.reserve(128);
279
280 #ifdef DEBUG_JOINTS
281   EnsureJointDebugShaderCreated();
282 #endif
283 }
284
285 SceneDefinition::SceneDefinition(SceneDefinition&& other)
286 : mNodes(std::move(other.mNodes)),
287   mRootNodeIds(std::move(other.mRootNodeIds))
288 {
289 #ifdef DEBUG_JOINTS
290   EnsureJointDebugShaderCreated();
291 #endif
292 }
293
294 SceneDefinition::~SceneDefinition()
295 {
296 #ifdef DEBUG_JOINTS
297   --sNumScenes;
298   if(sNumScenes == 0)
299   {
300     sJointDebugShader = Shader();
301   }
302 #endif
303 }
304
305 uint32_t Dali::Scene3D::Loader::SceneDefinition::AddRootNode(Index iNode)
306 {
307   if(iNode < mNodes.size())
308   {
309     uint32_t result = mRootNodeIds.size();
310     mRootNodeIds.push_back(iNode);
311     return result;
312   }
313   else
314   {
315     ExceptionFlinger(ASSERT_LOCATION) << "Failed to add new root with node " << iNode << " -- index out of bounds.";
316     return -1;
317   }
318 }
319
320 const std::vector<Index>& SceneDefinition::GetRoots() const
321 {
322   return mRootNodeIds;
323 }
324
325 void SceneDefinition::RemoveRootNode(Index iRoot)
326 {
327   if(iRoot < mRootNodeIds.size())
328   {
329     mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
330   }
331   else
332   {
333     ExceptionFlinger(ASSERT_LOCATION) << "Failed to remove root " << iRoot << " -- index out of bounds.";
334   }
335 }
336
337 uint32_t SceneDefinition::GetNodeCount() const
338 {
339   return mNodes.size();
340 }
341
342 const NodeDefinition* SceneDefinition::GetNode(Index iNode) const
343 {
344   return mNodes[iNode].get();
345 }
346
347 NodeDefinition* SceneDefinition::GetNode(Index iNode)
348 {
349   if(iNode != Scene3D::Loader::INVALID_INDEX && iNode < mNodes.size())
350   {
351     return mNodes[iNode].get();
352   }
353   return nullptr;
354 }
355
356 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IVisitor& v)
357 {
358   VisitInternal(iNode, choices, v, *this);
359 }
360
361 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IConstVisitor& v) const
362 {
363   VisitInternal(iNode, choices, v, *this);
364 }
365
366 void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choices& choices, ResourceRefCounts& refCounts) const
367 {
368   struct RefCounter : IResourceReceiver
369   {
370     ResourceRefCounts* refCounts;
371
372     void Register(ResourceType::Value type, Index id)
373     {
374       ++(*refCounts)[type][id];
375     }
376   };
377
378   struct : NodeDefinition::IConstVisitor
379   {
380     RefCounter counter;
381
382     void Start(const NodeDefinition& n)
383     {
384       for(auto& renderable : n.mRenderables)
385       {
386         renderable->RegisterResources(counter);
387       }
388     }
389
390     void Finish(const NodeDefinition& n)
391     {
392     }
393
394   } refCounterVisitor;
395   refCounterVisitor.counter.refCounts = &refCounts;
396
397   Visit(iNode, choices, refCounterVisitor);
398 }
399
400 ModelNode SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params)
401 {
402   ActorCreatorVisitor actorCreatorVisitor(params);
403
404   Visit(iNode, choices, actorCreatorVisitor);
405
406   return actorCreatorVisitor.GetRoot();
407 }
408
409 void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
410                                               Customization::Map&           outCustomizationOptions,
411                                               Customization::Choices*       outMissingChoices) const
412 {
413   struct : NodeDefinition::IConstVisitor
414   {
415     const Customization::Choices* choices;        // choices that we know about.
416     Customization::Map*           options;        // tags are registered here. NO OWNERSHIP.
417     Customization::Choices*       missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
418
419     void Start(const NodeDefinition& n)
420     {
421       if(n.mCustomization)
422       {
423         const std::string& tag = n.mCustomization->mTag;
424         if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
425         {
426           missingChoices->Set(tag, 0);
427         }
428
429         auto customization = options->Get(tag);
430         if(!customization)
431         {
432           customization = options->Set(tag, {});
433         }
434         customization->nodes.push_back(n.mName);
435         customization->numOptions = std::max(customization->numOptions,
436                                              static_cast<uint32_t>(n.mChildren.size()));
437       }
438     }
439
440     void Finish(const NodeDefinition& n)
441     {
442     }
443
444   } customizationRegistrationVisitor;
445   customizationRegistrationVisitor.choices        = &choices;
446   customizationRegistrationVisitor.options        = &outCustomizationOptions;
447   customizationRegistrationVisitor.missingChoices = outMissingChoices;
448
449   for(auto i : mRootNodeIds)
450   {
451     Visit(i, choices, customizationRegistrationVisitor);
452   }
453 }
454
455 NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
456 {
457   // add next index (to which we're about to push) as a child to the designated parent, if any.
458   if(nodeDef->mParentIdx != INVALID_INDEX)
459   {
460     mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
461   }
462
463   mNodes.push_back(std::move(nodeDef));
464
465   return mNodes.back().get();
466 }
467
468 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
469 {
470   LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
471
472   std::unique_ptr<NodeDefinition>* nodePtr      = nullptr;
473   std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
474   if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
475   {
476     return false;
477   }
478
479   auto& node  = *nodePtr;
480   auto  iNode = std::distance(mNodes.data(), nodePtr);
481
482   DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
483     std::ostringstream stream;
484     stream << n.mName << " (" << n.mParentIdx << "):";
485     for(auto i : n.mChildren)
486     {
487       stream << i << ", ";
488     }
489     LOGD(("%s", stream.str().c_str()));
490   };)
491
492   // Remove node from children of previous parent (if any).
493   if(node->mParentIdx != INVALID_INDEX)
494   {
495     LOGD(("old parent:"));
496     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
497
498     auto& children = mNodes[node->mParentIdx]->mChildren;
499     children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
500
501     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
502   }
503
504   // Register node to new parent.
505   LOGD(("new parent:"));
506   DEBUG_ONLY(dumpNode(**newParentPtr);)
507   auto& children = (*newParentPtr)->mChildren;
508   if(siblingOrder > children.size())
509   {
510     siblingOrder = children.size();
511   }
512   children.insert(children.begin() + siblingOrder, 1, iNode);
513   DEBUG_ONLY(dumpNode(**newParentPtr);)
514
515   // Update parent index.
516   LOGD(("node:"));
517   DEBUG_ONLY(dumpNode(*node);)
518   auto iParent     = std::distance(mNodes.data(), newParentPtr);
519   node->mParentIdx = iParent;
520   DEBUG_ONLY(dumpNode(*node);)
521   return true;
522 }
523
524 bool SceneDefinition::RemoveNode(const std::string& name)
525 {
526   std::unique_ptr<NodeDefinition>* node = nullptr;
527   if(!FindNode(name, &node))
528   {
529     return false;
530   }
531
532   // Reset node def pointers recursively.
533   auto&                                                 thisNodes = mNodes;
534   unsigned int                                          numReset  = 0;
535   std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
536     [&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
537       LOGD(("resetting %d", &nd - thisNodes.data()));
538       for(auto i : nd->mChildren)
539       {
540         resetFn(thisNodes[i]);
541       }
542       nd.reset();
543       ++numReset;
544     };
545
546   resetFn(*node);
547
548   // Gather indices of dead nodes into a vector which we sort on insertion.
549   std::vector<Index> offsets;
550   offsets.reserve(numReset);
551   for(auto& n : mNodes)
552   {
553     if(!n)
554     {
555       offsets.push_back(std::distance(mNodes.data(), &n));
556     }
557   }
558
559   // Erase dead nodes as they don't have to be processed anymore.
560   mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
561
562   // Offset all indices (parent and child) by the index they'd sort into in offsets.
563   enum
564   {
565     INDEX_FOR_REMOVAL = INVALID_INDEX
566   };
567   auto offsetter = [&offsets](Index& i) {
568     auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
569     if(iFind != offsets.end() && *iFind == i)
570     {
571       LOGD(("marking %d for removal.", i));
572       i = INDEX_FOR_REMOVAL;
573       return false;
574     }
575     else
576     {
577       auto distance = std::distance(offsets.begin(), iFind);
578       if(distance > 0)
579       {
580         LOGD(("offsetting %d by %d.", i, distance));
581         i -= distance;
582       }
583       return true;
584     }
585   };
586
587   for(auto& nd : mNodes)
588   {
589     bool parentOffsetResult = offsetter(nd->mParentIdx);
590     DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
591
592     auto& children = nd->mChildren;
593     for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
594     {
595       offsetter(*i0);
596     }
597
598     children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
599   }
600
601   return true;
602 }
603
604 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
605 {
606   auto&                    thisNodes  = mNodes;
607   std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
608     auto node = thisNodes[i].get();
609     if(node->mParentIdx != INVALID_INDEX)
610     {
611       buildStack(node->mParentIdx);
612     }
613     model.Push(node->GetLocalSpace());
614   };
615   buildStack(index);
616 }
617
618 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
619 {
620   auto iBegin = mNodes.begin();
621   auto iEnd   = mNodes.end();
622   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) { return nd->mName == name; });
623
624   auto result = iFind != iEnd ? iFind->get() : nullptr;
625   if(result && outIndex)
626   {
627     *outIndex = std::distance(iBegin, iFind);
628   }
629   return result;
630 }
631
632 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
633 {
634   auto iBegin = mNodes.begin();
635   auto iEnd   = mNodes.end();
636   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) { return nd->mName == name; });
637
638   auto result = iFind != iEnd ? iFind->get() : nullptr;
639   if(result && outIndex)
640   {
641     *outIndex = std::distance(iBegin, iFind);
642   }
643   return result;
644 }
645
646 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
647 {
648   auto iBegin = mNodes.begin();
649   auto iEnd   = mNodes.end();
650   auto iFind  = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) { return n.get() == &node; });
651   return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
652 }
653
654 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
655 {
656   unsigned int n = 0;
657   for(auto& defp : mNodes)
658   {
659     if(predicate(*defp))
660     {
661       consumer(*defp);
662       ++n;
663       if(n == limit)
664       {
665         break;
666       }
667     }
668   }
669 }
670
671 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
672 {
673   unsigned int n = 0;
674   for(auto& defp : mNodes)
675   {
676     if(predicate(*defp))
677     {
678       consumer(*defp);
679       ++n;
680       if(n == limit)
681       {
682         break;
683       }
684     }
685   }
686 }
687
688 void SceneDefinition::ApplyConstraints(Actor&                           root,
689                                        std::vector<ConstraintRequest>&& constrainables,
690                                        StringCallback                   onError) const
691 {
692   for(auto& cr : constrainables)
693   {
694     auto&           nodeDef    = mNodes[cr.mConstraint->mSourceIdx];
695     auto            sourceName = nodeDef->mName.c_str();
696     Property::Index iTarget    = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
697     if(iTarget != Property::INVALID_INDEX)
698     {
699       auto propertyType = cr.mTarget.GetPropertyType(iTarget);
700       auto iFind        = GetConstraintFactory().find(propertyType);
701       if(iFind == GetConstraintFactory().end())
702       {
703         onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
704                              sourceName,
705                              cr.mConstraint->mProperty.c_str(),
706                              PropertyTypes::GetName(propertyType)));
707         continue;
708       }
709
710       Constraint constraint = iFind->second(cr.mTarget, iTarget);
711
712       Actor source = root.FindChildByName(nodeDef->mName);
713       if(!source)
714       {
715         auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
716         onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
717                              sourceName,
718                              cr.mConstraint->mProperty.c_str(),
719                              targetName.c_str()));
720         continue;
721       }
722       else if(source == cr.mTarget)
723       {
724         onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
725                              sourceName,
726                              cr.mConstraint->mProperty.c_str()));
727         continue;
728       }
729
730       Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
731       constraint.AddSource(Source{source, iSource});
732       constraint.Apply();
733     }
734     else
735     {
736       auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
737       onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
738                            sourceName,
739                            cr.mConstraint->mProperty.c_str(),
740                            targetName.c_str()));
741     }
742   }
743 }
744
745 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
746 {
747   std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
748   for(auto& node : mNodes)
749   {
750     for(auto& renderable : node->mRenderables)
751     {
752       ResourceReflector reflector;
753       renderable->ReflectResources(reflector);
754
755       if(reflector.iMesh)
756       {
757         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
758         if(mesh.IsSkinned())
759         {
760           skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
761         }
762       }
763     }
764   }
765
766   // For each shader, and each skeleton using the same shader as the first skeleton,
767   // update the shader references (from nodes with skinned meshes) with a new copy of
768   // the shader definition from the node using the first skeleton.
769   for(auto& users : skinningShaderUsers)
770   {
771     auto& skeletons    = users.second;
772     auto  iterSkeleton = skeletons.begin();
773     // skipping the first skeleton.
774     ++iterSkeleton;
775
776     resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
777     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
778
779     while(iterSkeleton != skeletons.end())
780     {
781       Index iShader = resources.mShaders.size();
782       resources.mShaders.push_back({shaderDef, Shader()});
783
784       for(auto& i : iterSkeleton->second)
785       {
786         *i = iShader;
787       }
788       ++iterSkeleton;
789     }
790   }
791 }
792
793 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle&                             resources,
794                                                Actor                                             rootActor,
795                                                std::vector<SkinningShaderConfigurationRequest>&& requests) const
796 {
797   if(requests.empty())
798   {
799     return;
800   }
801
802   SortAndDeduplicateRequests(requests);
803
804   for(auto& request : requests)
805   {
806     auto& skeleton = resources.mSkeletons[request.mSkeletonIdx];
807     if(skeleton.mJoints.empty())
808     {
809       LOGD(("Skeleton %d has no joints.", request.mSkeletonIdx));
810       continue;
811     }
812
813     Index boneIdx = 0;
814     for(auto& joint : skeleton.mJoints)
815     {
816       auto      node      = GetNode(joint.mNodeIdx);
817       ModelNode modelNode = ModelNode::DownCast(rootActor.FindChildByName(node->mName));
818       if(!modelNode)
819       {
820         continue;
821       }
822       ConfigureBoneMatrix(joint.mInverseBindMatrix, modelNode, request.mPrimitive, boneIdx);
823     }
824   }
825 }
826
827 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle&                               resources,
828                                                  Actor                                               rootActor,
829                                                  std::vector<BlendshapeShaderConfigurationRequest>&& requests,
830                                                  StringCallback                                      onError) const
831 {
832   if(requests.empty())
833   {
834     return true;
835   }
836
837   SortAndDeduplicateRequests(requests);
838
839   // Configure the rest.
840   bool ok = true;
841
842   for(auto& request : requests)
843   {
844     Index iNode;
845     if(FindNode(request.mNodeName, &iNode))
846     {
847       const auto& node = GetNode(iNode);
848
849       const auto& mesh = resources.mMeshes[request.mMeshIdx];
850
851       if(mesh.first.HasBlendShapes())
852       {
853         Actor              actor = rootActor.FindChildByName(node->mName);
854         Scene3D::ModelNode node  = Scene3D::ModelNode::DownCast(actor);
855         if(!node)
856         {
857           continue;
858         }
859         BlendShapes::BlendShapeData data;
860         data.components = 0x0;
861         for(auto&& blendShape : mesh.first.mBlendShapes)
862         {
863           data.names.push_back(blendShape.name);
864           data.weights.push_back(blendShape.weight);
865           data.components |= (blendShape.deltas.IsDefined() * BlendShapes::Component::POSITIONS) |
866                              (blendShape.normals.IsDefined() * BlendShapes::Component::NORMALS) | (blendShape.tangents.IsDefined() * BlendShapes::Component::TANGENTS);
867         }
868         for(auto&& factor : mesh.second.blendShapeUnnormalizeFactor)
869         {
870           data.unnormalizeFactors.push_back(factor);
871         }
872         data.version      = mesh.first.mBlendShapeVersion;
873         data.bufferOffset = mesh.second.blendShapeBufferOffset;
874         data.mActor       = actor;
875         Internal::GetImplementation(node).SetBlendShapeData(data, request.mPrimitive);
876       }
877     }
878   }
879
880   return ok;
881 }
882
883 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
884 {
885   std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
886   for(auto& node : mNodes)
887   {
888     for(auto& renderable : node->mRenderables)
889     {
890       ResourceReflector reflector;
891       renderable->ReflectResources(reflector);
892
893       if(reflector.iMesh)
894       {
895         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
896         if(mesh.HasBlendShapes())
897         {
898           blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
899         }
900       }
901     }
902   }
903
904   for(auto& users : blendShapeShaderUsers)
905   {
906     resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
907     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
908
909     auto nodesIt    = users.second.begin();
910     auto nodesEndIt = users.second.end();
911     // skipping the first node.
912     ++nodesIt;
913     while(nodesIt != nodesEndIt)
914     {
915       Index iShader = resources.mShaders.size();
916       resources.mShaders.push_back({shaderDef, Shader()});
917
918       auto& nodes = *nodesIt;
919       for(auto& shader : nodes.second)
920       {
921         *shader = iShader;
922       }
923       ++nodesIt;
924     }
925   }
926 }
927
928 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
929 {
930   SceneDefinition temp(std::move(other));
931   std::swap(mNodes, temp.mNodes);
932   std::swap(mRootNodeIds, temp.mRootNodeIds);
933   return *this;
934 }
935
936 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
937 {
938   // We're searching from the end assuming a higher probability of operations targeting
939   // recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
940   // the first to be added, is index 0.)
941   auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) { return nd->mName == name; })
942                  .base();
943
944   const bool success = iFind != mNodes.begin();
945   if(success && result)
946   {
947     --iFind;
948     *result = &*iFind;
949   }
950
951   return success;
952 }
953
954 } // namespace Dali::Scene3D::Loader