2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "dali/devel-api/common/map-wrapper.h"
20 #include "dali/public-api/animation/constraints.h"
23 #include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h"
24 #include "dali-scene-loader/public-api/blend-shape-details.h"
25 #include "dali-scene-loader/public-api/scene-definition.h"
26 #include "dali-scene-loader/public-api/skinning-details.h"
27 #include "dali-scene-loader/public-api/utils.h"
29 //#define DEBUG_SCENE_DEFINITION
30 //#define DEBUG_JOINTS
32 #if defined(DEBUG_SCENE_DEFINITION) || defined(DEBUG_JOINTS)
33 #define DEBUG_ONLY(x) x
38 #define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout))
46 const std::string JOINT_MATRIX{"jointMatrix"};
48 const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)> sConstraintFactory = {
49 {Property::Type::BOOLEAN,
50 [](Actor& a, Property::Index i) {
51 return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) {
52 current = inputs[0]->GetBoolean();
55 {Property::Type::INTEGER,
56 [](Actor& a, Property::Index i) {
57 return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) {
58 current = inputs[0]->GetInteger();
61 {Property::Type::FLOAT,
62 [](Actor& a, Property::Index i) {
63 return Constraint::New<float>(a, i, EqualToConstraint());
65 {Property::Type::VECTOR2,
66 [](Actor& a, Property::Index i) {
67 return Constraint::New<Vector2>(a, i, EqualToConstraint());
69 {Property::Type::VECTOR3,
70 [](Actor& a, Property::Index i) {
71 return Constraint::New<Vector3>(a, i, EqualToConstraint());
73 {Property::Type::VECTOR4,
74 [](Actor& a, Property::Index i) {
75 return Constraint::New<Vector4>(a, i, EqualToConstraint());
77 {Property::Type::MATRIX,
78 [](Actor& a, Property::Index i) {
79 return Constraint::New<Matrix>(a, i, EqualToConstraint());
81 {Property::Type::MATRIX3,
82 [](Actor& a, Property::Index i) {
83 return Constraint::New<Matrix3>(a, i, EqualToConstraint());
85 {Property::Type::ROTATION,
86 [](Actor& a, Property::Index i) {
87 return Constraint::New<Quaternion>(a, i, EqualToConstraint());
91 struct ResourceReflector : IResourceReflector
93 Index* iMesh = nullptr;
94 Index* iShader = nullptr;
96 void Reflect(ResourceType::Value type, Index& id)
100 case ResourceType::Shader:
101 DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
105 case ResourceType::Mesh:
106 DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
110 default: // Other resource types are not relevant to the problem at hand.
118 Shader sJointDebugShader;
121 void EnsureJointDebugShaderCreated()
125 sJointDebugShader = Shader::New(SHADER_SCENE_LOADER_JOINT_DEBUG_VERT, SHADER_SCENE_LOADER_JOINT_DEBUG_FRAG);
130 void AddJointDebugVisual(Actor aJoint)
132 Property::Map attribs;
133 attribs["aPosition"] = Property::Type::VECTOR3;
134 attribs["aColor"] = Property::Type::FLOAT;
136 PropertyBuffer vbo = PropertyBuffer::New(attribs);
143 {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f},
144 {Vector3::XAXIS, .999f},
145 {Vector3::YAXIS, .999f * 256.f},
146 {Vector3::ZAXIS, .999f * 256.f * 256.f},
149 vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
151 uint16_t indices[] = {0, 1, 0, 2, 0, 3};
153 Geometry geo = Geometry::New();
154 geo.AddVertexBuffer(vbo);
155 geo.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
156 geo.SetType(Geometry::LINES);
158 Renderer r = Renderer::New(geo, sJointDebugShader);
159 aJoint.AddRenderer(r);
161 aJoint.SetVisible(true);
163 #endif //DEBUG_JOINTS
165 class ActorCreatorVisitor : public NodeDefinition::IConstVisitor
168 ActorCreatorVisitor(NodeDefinition::CreateParams& params)
169 : mCreationContext(params)
173 void Start(const NodeDefinition& n)
175 mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
177 Actor a = n.CreateActor(mCreationContext);
178 if(!mActorStack.empty())
180 mActorStack.back().Add(a);
186 mActorStack.push_back(a);
189 void Finish(const NodeDefinition& n)
191 mActorStack.pop_back();
192 mCreationContext.mXforms.modelStack.Pop();
195 Actor GetRoot() const
201 NodeDefinition::CreateParams& mCreationContext;
202 std::vector<Actor> mActorStack;
206 bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX)
208 bool isAncestor = false;
209 while(node != rootHint && !isAncestor)
211 node = scene.GetNode(node)->mParentIdx;
212 isAncestor = ancestor == node;
217 void InsertUniqueSorted(std::vector<Index>& data, Index value)
219 auto iInsert = std::lower_bound(data.begin(), data.end(), value);
220 if(iInsert == data.end() || *iInsert != value)
222 data.insert(iInsert, value);
226 void RemoveFromSorted(std::vector<Index>& data, Index value)
228 auto iRemove = std::lower_bound(data.begin(), data.end(), value);
229 if(iRemove != data.end() && *iRemove == value)
235 Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix)
237 Actor parent = actor.GetParent();
238 if(parent != ancestor)
240 propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix);
243 auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX);
244 if(myPropJointMatrix == Property::INVALID_INDEX)
246 myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{false});
247 Constraint constraint = Constraint::New<Matrix>(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
248 Matrix jointMatrix{false};
249 jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
251 Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
253 constraint.AddSource(Source{actor, Actor::Property::ORIENTATION});
254 constraint.AddSource(Source{actor, Actor::Property::POSITION});
255 constraint.AddSource(Source{parent, propJointMatrix});
259 return myPropJointMatrix;
262 void SortAndDeduplicateSkinningRequests(std::vector<SkinningShaderConfigurationRequest>& requests)
264 // Sort requests by shaders.
265 std::sort(requests.begin(), requests.end());
267 // Remove duplicates.
268 auto i = requests.begin();
269 auto iEnd = requests.end();
270 Shader s = i->mShader;
271 Index skeletonIdx = i->mSkeletonIdx;
275 // Multiple identical shader instances are removed.
276 while(i != iEnd && i->mShader == s)
278 // Cannot have multiple skeletons input to the same shader.
279 // NOTE: DliModel now makes sure this doesn't happen.
280 DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx &&
281 "Skinning shader must not be shared between different skeletons.");
283 i->mShader = Shader();
292 skeletonIdx = i->mSkeletonIdx;
296 requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) {
297 return !sscr.mShader;
302 void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx)
304 // Register bone transform on shader.
305 char propertyNameBuffer[32];
306 snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx);
307 DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX);
308 auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false});
310 // Constrain bone matrix to joint transform.
311 Constraint constraint = Constraint::New<Matrix>(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) {
312 Matrix::Multiply(output, ibm, inputs[0]->GetMatrix());
315 auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX);
316 constraint.AddSource(Source{joint, propJointMatrix});
322 template<class Visitor, class SceneDefinition>
323 void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
325 auto& node = *sd.GetNode(iNode);
328 if(node.mCustomization)
330 if(!node.mChildren.empty())
332 auto choice = choices.Get(node.mCustomization->mTag);
333 Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
334 sd.Visit(node.mChildren[i], choices, v);
339 for(auto i : node.mChildren)
341 sd.Visit(i, choices, v);
350 SceneDefinition::SceneDefinition()
355 EnsureJointDebugShaderCreated();
359 SceneDefinition::SceneDefinition(SceneDefinition&& other)
360 : mNodes(std::move(other.mNodes)),
361 mRootNodeIds(std::move(other.mRootNodeIds))
364 EnsureJointDebugShaderCreated();
368 SceneDefinition::~SceneDefinition()
374 sJointDebugShader = Shader();
379 uint32_t SceneLoader::SceneDefinition::AddRootNode(Index iNode)
381 if(iNode < mNodes.size())
383 uint32_t result = mRootNodeIds.size();
384 mRootNodeIds.push_back(iNode);
389 ExceptionFlinger(ASSERT_LOCATION) << "Failed to add new root with node " << iNode << " -- index out of bounds.";
394 const std::vector<Index>& SceneDefinition::GetRoots() const
399 void SceneDefinition::RemoveRootNode(Index iRoot)
401 if(iRoot < mRootNodeIds.size())
403 mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
407 ExceptionFlinger(ASSERT_LOCATION) << "Failed to remove root " << iRoot << " -- index out of bounds.";
411 uint32_t SceneDefinition::GetNodeCount() const
413 return mNodes.size();
416 const NodeDefinition* SceneDefinition::GetNode(Index iNode) const
418 return mNodes[iNode].get();
421 NodeDefinition* SceneDefinition::GetNode(Index iNode)
423 return mNodes[iNode].get();
426 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IVisitor& v)
428 VisitInternal(iNode, choices, v, *this);
431 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IConstVisitor& v) const
433 VisitInternal(iNode, choices, v, *this);
436 void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choices& choices, ResourceRefCounts& refCounts) const
438 struct RefCounter : IResourceReceiver
440 ResourceRefCounts* refCounts;
442 void Register(ResourceType::Value type, Index id)
444 ++(*refCounts)[type][id];
448 struct : NodeDefinition::IConstVisitor
452 void Start(const NodeDefinition& n)
456 n.mRenderable->RegisterResources(counter);
460 void Finish(const NodeDefinition& n)
465 refCounterVisitor.counter.refCounts = &refCounts;
467 Visit(iNode, choices, refCounterVisitor);
470 Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const
472 ActorCreatorVisitor actorCreatorVisitor(params);
474 Visit(iNode, choices, actorCreatorVisitor);
476 return actorCreatorVisitor.GetRoot();
479 void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
480 Customization::Map& outCustomizationOptions,
481 Customization::Choices* outMissingChoices) const
483 struct : NodeDefinition::IConstVisitor
485 const Customization::Choices* choices; // choices that we know about.
486 Customization::Map* options; // tags are registered here. NO OWNERSHIP.
487 Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
489 void Start(const NodeDefinition& n)
493 const std::string& tag = n.mCustomization->mTag;
494 if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
496 missingChoices->Set(tag, 0);
499 auto customization = options->Get(tag);
502 customization = options->Set(tag, {});
504 customization->nodes.push_back(n.mName);
505 customization->numOptions = std::max(customization->numOptions,
506 static_cast<uint32_t>(n.mChildren.size()));
510 void Finish(const NodeDefinition& n)
514 } customizationRegistrationVisitor;
515 customizationRegistrationVisitor.choices = &choices;
516 customizationRegistrationVisitor.options = &outCustomizationOptions;
517 customizationRegistrationVisitor.missingChoices = outMissingChoices;
519 for(auto i : mRootNodeIds)
521 Visit(i, choices, customizationRegistrationVisitor);
525 NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
527 if(FindNode(nodeDef->mName))
532 // add next index (to which we're about to push) as a child to the designated parent, if any.
533 if(nodeDef->mParentIdx != INVALID_INDEX)
535 mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
538 mNodes.push_back(std::move(nodeDef));
540 return mNodes.back().get();
543 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
545 LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
547 std::unique_ptr<NodeDefinition>* nodePtr = nullptr;
548 std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
549 if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
554 auto& node = *nodePtr;
555 auto iNode = std::distance(mNodes.data(), nodePtr);
557 DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
558 std::ostringstream stream;
559 stream << n.mName << " (" << n.mParentIdx << "):";
560 for(auto i : n.mChildren)
564 LOGD(("%s", stream.str().c_str()));
567 // Remove node from children of previous parent (if any).
568 if(node->mParentIdx != INVALID_INDEX)
570 LOGD(("old parent:"));
571 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
573 auto& children = mNodes[node->mParentIdx]->mChildren;
574 children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
576 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
579 // Register node to new parent.
580 LOGD(("new parent:"));
581 DEBUG_ONLY(dumpNode(**newParentPtr);)
582 auto& children = (*newParentPtr)->mChildren;
583 if(siblingOrder > children.size())
585 siblingOrder = children.size();
587 children.insert(children.begin() + siblingOrder, 1, iNode);
588 DEBUG_ONLY(dumpNode(**newParentPtr);)
590 // Update parent index.
592 DEBUG_ONLY(dumpNode(*node);)
593 auto iParent = std::distance(mNodes.data(), newParentPtr);
594 node->mParentIdx = iParent;
595 DEBUG_ONLY(dumpNode(*node);)
599 bool SceneDefinition::RemoveNode(const std::string& name)
601 std::unique_ptr<NodeDefinition>* node = nullptr;
602 if(!FindNode(name, &node))
607 // Reset node def pointers recursively.
608 auto& thisNodes = mNodes;
609 unsigned int numReset = 0;
610 std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
611 [&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
612 LOGD(("resetting %d", &nd - thisNodes.data()));
613 for(auto i : nd->mChildren)
615 resetFn(thisNodes[i]);
623 // Gather indices of dead nodes into a vector which we sort on insertion.
624 std::vector<Index> offsets;
625 offsets.reserve(numReset);
626 for(auto& n : mNodes)
630 offsets.push_back(std::distance(mNodes.data(), &n));
634 // Erase dead nodes as they don't have to be processed anymore.
635 mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
637 // Offset all indices (parent and child) by the index they'd sort into in offsets.
640 INDEX_FOR_REMOVAL = INVALID_INDEX
642 auto offsetter = [&offsets](Index& i) {
643 auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
644 if(iFind != offsets.end() && *iFind == i)
646 LOGD(("marking %d for removal.", i));
647 i = INDEX_FOR_REMOVAL;
652 auto distance = std::distance(offsets.begin(), iFind);
655 LOGD(("offsetting %d by %d.", i, distance));
662 for(auto& nd : mNodes)
664 bool parentOffsetResult = offsetter(nd->mParentIdx);
665 DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
667 auto& children = nd->mChildren;
668 for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
673 children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
679 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
681 auto& thisNodes = mNodes;
682 std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
683 auto node = thisNodes[i].get();
684 if(node->mParentIdx != INVALID_INDEX)
686 buildStack(node->mParentIdx);
688 model.Push(node->GetLocalSpace());
693 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
695 auto iBegin = mNodes.begin();
696 auto iEnd = mNodes.end();
697 auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
698 return nd->mName == name;
701 auto result = iFind != iEnd ? iFind->get() : nullptr;
702 if(result && outIndex)
704 *outIndex = std::distance(iBegin, iFind);
709 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
711 auto iBegin = mNodes.begin();
712 auto iEnd = mNodes.end();
713 auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
714 return nd->mName == name;
717 auto result = iFind != iEnd ? iFind->get() : nullptr;
718 if(result && outIndex)
720 *outIndex = std::distance(iBegin, iFind);
725 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
727 auto iBegin = mNodes.begin();
728 auto iEnd = mNodes.end();
729 auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
730 return n.get() == &node;
732 return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
735 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
738 for(auto& defp : mNodes)
752 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
755 for(auto& defp : mNodes)
769 void SceneDefinition::ApplyConstraints(Actor& root,
770 std::vector<ConstraintRequest>&& constrainables,
771 StringCallback onError) const
773 for(auto& cr : constrainables)
775 auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx];
776 auto sourceName = nodeDef->mName.c_str();
777 Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
778 if(iTarget != Property::INVALID_INDEX)
780 auto propertyType = cr.mTarget.GetPropertyType(iTarget);
781 auto iFind = sConstraintFactory.find(propertyType);
782 if(iFind == sConstraintFactory.end())
784 onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
786 cr.mConstraint->mProperty.c_str(),
787 PropertyTypes::GetName(propertyType)));
791 Constraint constraint = iFind->second(cr.mTarget, iTarget);
793 Actor source = root.FindChildByName(nodeDef->mName);
796 auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
797 onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
799 cr.mConstraint->mProperty.c_str(),
800 targetName.c_str()));
803 else if(source == cr.mTarget)
805 onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
807 cr.mConstraint->mProperty.c_str()));
811 Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
812 constraint.AddSource(Source{source, iSource});
817 auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
818 onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
820 cr.mConstraint->mProperty.c_str(),
821 targetName.c_str()));
826 void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefinition::Vector& skeletons, Actor root) const
828 // 1, For each skeleton, for each joint, walk upwards until we reach mNodes[iRoot]. If we do, record +1
829 // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1
830 // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton.
831 std::map<Index, std::vector<Index>> rootsJoints;
832 std::vector<Index> path;
834 for(auto& s : skeletons)
836 std::map<uint32_t, uint32_t> jointRefs;
837 for(auto& j : s.mJoints)
839 auto nodeIdx = j.mNodeIdx;
840 do // Traverse upwards and record each node we have visited until we reach the scene root.
842 path.push_back(nodeIdx);
847 auto node = GetNode(nodeIdx);
848 nodeIdx = node->mParentIdx;
849 } while(nodeIdx != INVALID_INDEX);
851 if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
862 // Only record the skeleton if we have encountered the root of the current scene.
863 if(jointRefs.empty())
868 Index root = s.mRootNodeIdx;
870 auto iFind = jointRefs.find(root);
871 if(iFind != jointRefs.end())
873 maxRef = iFind->second;
876 std::vector<Index> joints;
877 for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
879 // The most descendant node with the highest ref count is the root of the skeleton.
880 if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
884 RemoveFromSorted(joints, root);
887 else if(j.second == 1) // This one's a leaf.
889 InsertUniqueSorted(joints, j.first);
893 // Merge skeletons that share the same root.
894 auto& finalJoints = rootsJoints[root];
897 if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
898 return IsAncestor(*this, j, jj, root);
899 }) != finalJoints.end())
901 continue; // if the joint is found to be an ancestor of another joint already registered, move on.
905 while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
907 auto node = GetNode(i);
908 i = node->mParentIdx;
910 RemoveFromSorted(finalJoints, i);
913 InsertUniqueSorted(finalJoints, j);
917 // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous
918 // leaf nodes that now have descendants, and add new ones.
919 auto iRoots = rootsJoints.begin();
920 auto iRootsEnd = rootsJoints.end();
921 while(iRoots != iRootsEnd)
923 auto i = iRoots->first;
925 while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
927 auto node = GetNode(i);
928 i = node->mParentIdx;
930 auto iFind = rootsJoints.find(i);
931 if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
933 // Now find out which leaf of iFind is an ancestor, if any.
934 auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) {
935 return IsAncestor(*this, j, iRoots->first, iFind->first);
937 if(iFindLeaf != iFind->second.end())
939 iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
942 // Merge iRoots with iFind
943 auto& targetJoints = iFind->second;
944 if(iRoots->second.empty()) // The root is a leaf.
946 InsertUniqueSorted(targetJoints, iRoots->first);
949 for(auto j : iRoots->second)
951 InsertUniqueSorted(targetJoints, j);
955 break; // Traverse no more
959 iRoots = merged ? rootsJoints.erase(iRoots) : std::next(iRoots);
962 // 3, For each root, register joint matrices and constraints
963 for(auto r : rootsJoints)
965 auto node = GetNode(r.first);
966 auto rootJoint = root.FindChildByName(node->mName);
967 DALI_ASSERT_ALWAYS(!!rootJoint);
969 DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX);
970 auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false});
971 Constraint constraint = Constraint::New<Matrix>(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
972 output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
974 constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
975 constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
978 for(auto j : r.second)
981 auto joint = rootJoint.FindChildByName(node->mName);
982 ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
987 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
989 std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
990 for(auto& node : mNodes)
992 if(node->mRenderable)
994 ResourceReflector reflector;
995 node->mRenderable->ReflectResources(reflector);
999 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1000 if(mesh.IsSkinned())
1002 skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
1008 // For each shader, and each skeleton using the same shader as the first skeleton,
1009 // update the shader references (from nodes with skinned meshes) with a new copy of
1010 // the shader definition from the node using the first skeleton.
1011 for(auto& users : skinningShaderUsers)
1013 auto& skeletons = users.second;
1014 auto iterSkeleton = skeletons.begin();
1015 // skipping the first skeleton.
1018 resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
1019 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1021 while(iterSkeleton != skeletons.end())
1023 Index iShader = resources.mShaders.size();
1024 resources.mShaders.push_back({shaderDef, Shader()});
1026 for(auto& i : iterSkeleton->second)
1035 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources,
1037 std::vector<SkinningShaderConfigurationRequest>&& requests) const
1039 if(requests.empty())
1044 SortAndDeduplicateSkinningRequests(requests);
1046 for(auto& i : requests)
1048 auto& skeleton = resources.mSkeletons[i.mSkeletonIdx];
1049 if(skeleton.mJoints.empty())
1051 LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx));
1056 for(auto& j : skeleton.mJoints)
1058 auto node = GetNode(j.mNodeIdx);
1059 Actor actor = rootActor.FindChildByName(node->mName);
1060 ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx);
1065 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources,
1067 std::vector<BlendshapeShaderConfigurationRequest>&& requests,
1068 StringCallback onError) const
1070 if(requests.empty())
1075 // Sort requests by shaders.
1076 std::sort(requests.begin(), requests.end());
1078 // Remove duplicates.
1079 auto i = requests.begin();
1080 auto iEnd = requests.end();
1081 Shader s = i->mShader;
1085 // Multiple identical shader instances are removed.
1086 while(i != iEnd && i->mShader == s)
1088 i->mShader = Shader();
1100 requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) {
1101 return !bscr.mShader;
1105 // Configure the rest.
1108 for(auto& i : requests)
1111 if(FindNode(i.mNodeName, &iNode))
1113 const auto& node = GetNode(iNode);
1115 const auto& mesh = resources.mMeshes[i.mMeshIdx];
1117 if(mesh.first.HasBlendShapes())
1119 Actor actor = rootActor.FindChildByName(node->mName);
1121 // Sets the property to be animated.
1122 BlendShapes::ConfigureProperties(mesh, i.mShader, actor);
1130 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
1132 std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
1133 for(auto& node : mNodes)
1135 if(node->mRenderable)
1137 ResourceReflector reflector;
1138 node->mRenderable->ReflectResources(reflector);
1142 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1143 if(mesh.HasBlendShapes())
1145 blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
1151 for(auto& users : blendShapeShaderUsers)
1153 resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
1154 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1156 auto nodesIt = users.second.begin();
1157 auto nodesEndIt = users.second.end();
1158 // skipping the first node.
1160 while(nodesIt != nodesEndIt)
1162 Index iShader = resources.mShaders.size();
1163 resources.mShaders.push_back({shaderDef, Shader()});
1165 auto& nodes = *nodesIt;
1166 for(auto& shader : nodes.second)
1175 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
1177 SceneDefinition temp(std::move(other));
1178 std::swap(mNodes, temp.mNodes);
1179 std::swap(mRootNodeIds, temp.mRootNodeIds);
1183 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
1185 // We're searching from the end assuming a higher probability of operations targeting
1186 // recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
1187 // the first to be added, is index 0.)
1188 auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) {
1189 return nd->mName == name;
1192 const bool success = iFind != mNodes.begin();
1193 if(success && result)
1202 } // namespace SceneLoader