2 * Copyright (c) 2022 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-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"
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))
48 const std::string JOINT_MATRIX{"jointMatrix"};
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();
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();
63 {Property::Type::FLOAT,
64 [](Actor& a, Property::Index i) {
65 return Constraint::New<float>(a, i, EqualToConstraint());
67 {Property::Type::VECTOR2,
68 [](Actor& a, Property::Index i) {
69 return Constraint::New<Vector2>(a, i, EqualToConstraint());
71 {Property::Type::VECTOR3,
72 [](Actor& a, Property::Index i) {
73 return Constraint::New<Vector3>(a, i, EqualToConstraint());
75 {Property::Type::VECTOR4,
76 [](Actor& a, Property::Index i) {
77 return Constraint::New<Vector4>(a, i, EqualToConstraint());
79 {Property::Type::MATRIX,
80 [](Actor& a, Property::Index i) {
81 return Constraint::New<Matrix>(a, i, EqualToConstraint());
83 {Property::Type::MATRIX3,
84 [](Actor& a, Property::Index i) {
85 return Constraint::New<Matrix3>(a, i, EqualToConstraint());
87 {Property::Type::ROTATION,
88 [](Actor& a, Property::Index i) {
89 return Constraint::New<Quaternion>(a, i, EqualToConstraint());
93 struct ResourceReflector : IResourceReflector
95 Index* iMesh = nullptr;
96 Index* iShader = nullptr;
98 void Reflect(ResourceType::Value type, Index& id)
102 case ResourceType::Shader:
103 DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
107 case ResourceType::Mesh:
108 DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
112 default: // Other resource types are not relevant to the problem at hand.
120 Shader sJointDebugShader;
123 void EnsureJointDebugShaderCreated()
127 sJointDebugShader = Shader::New(SHADER_SCENE3D_JOINT_DEBUG_VERT, SHADER_SCENE3D_JOINT_DEBUG_FRAG);
132 void AddJointDebugVisual(Actor aJoint)
134 Property::Map attribs;
135 attribs["aPosition"] = Property::Type::VECTOR3;
136 attribs["aColor"] = Property::Type::FLOAT;
138 PropertyBuffer vbo = PropertyBuffer::New(attribs);
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},
151 vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
153 uint16_t indices[] = {0, 1, 0, 2, 0, 3};
155 Geometry geo = Geometry::New();
156 geo.AddVertexBuffer(vbo);
157 geo.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
158 geo.SetType(Geometry::LINES);
160 Renderer r = Renderer::New(geo, sJointDebugShader);
161 aJoint.AddRenderer(r);
163 aJoint.SetVisible(true);
165 #endif //DEBUG_JOINTS
167 class ActorCreatorVisitor : public NodeDefinition::IConstVisitor
170 ActorCreatorVisitor(NodeDefinition::CreateParams& params)
171 : mCreationContext(params)
175 void Start(const NodeDefinition& n)
177 mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
179 Actor a = n.CreateActor(mCreationContext);
180 if(!mActorStack.empty())
182 mActorStack.back().Add(a);
188 mActorStack.push_back(a);
191 void Finish(const NodeDefinition& n)
193 mActorStack.pop_back();
194 mCreationContext.mXforms.modelStack.Pop();
197 Actor GetRoot() const
203 NodeDefinition::CreateParams& mCreationContext;
204 std::vector<Actor> mActorStack;
208 bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX)
210 bool isAncestor = false;
211 while(node != rootHint && !isAncestor)
213 node = scene.GetNode(node)->mParentIdx;
214 isAncestor = ancestor == node;
219 void InsertUniqueSorted(std::vector<Index>& data, Index value)
221 auto iInsert = std::lower_bound(data.begin(), data.end(), value);
222 if(iInsert == data.end() || *iInsert != value)
224 data.insert(iInsert, value);
228 void RemoveFromSorted(std::vector<Index>& data, Index value)
230 auto iRemove = std::lower_bound(data.begin(), data.end(), value);
231 if(iRemove != data.end() && *iRemove == value)
237 Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix)
239 Actor parent = actor.GetParent();
240 if(parent != ancestor)
242 propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix);
245 auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX);
246 if(myPropJointMatrix == Property::INVALID_INDEX)
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());
253 Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
255 constraint.AddSource(Source{actor, Actor::Property::ORIENTATION});
256 constraint.AddSource(Source{actor, Actor::Property::POSITION});
257 constraint.AddSource(Source{parent, propJointMatrix});
261 return myPropJointMatrix;
264 void SortAndDeduplicateSkinningRequests(std::vector<SkinningShaderConfigurationRequest>& requests)
266 // Sort requests by shaders.
267 std::sort(requests.begin(), requests.end());
269 // Remove duplicates.
270 auto i = requests.begin();
271 auto iEnd = requests.end();
272 Shader s = i->mShader;
273 Index skeletonIdx = i->mSkeletonIdx;
277 // Multiple identical shader instances are removed.
278 while(i != iEnd && i->mShader == s)
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.");
285 i->mShader = Shader();
294 skeletonIdx = i->mSkeletonIdx;
298 requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) {
299 return !sscr.mShader;
304 void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx)
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});
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());
317 auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX);
318 constraint.AddSource(Source{joint, propJointMatrix});
324 template<class Visitor, class SceneDefinition>
325 void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
327 auto& node = *sd.GetNode(iNode);
330 if(node.mCustomization)
332 if(!node.mChildren.empty())
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);
341 for(auto i : node.mChildren)
343 sd.Visit(i, choices, v);
352 SceneDefinition::SceneDefinition()
357 EnsureJointDebugShaderCreated();
361 SceneDefinition::SceneDefinition(SceneDefinition&& other)
362 : mNodes(std::move(other.mNodes)),
363 mRootNodeIds(std::move(other.mRootNodeIds))
366 EnsureJointDebugShaderCreated();
370 SceneDefinition::~SceneDefinition()
376 sJointDebugShader = Shader();
381 uint32_t Dali::Scene3D::Loader::SceneDefinition::AddRootNode(Index iNode)
383 if(iNode < mNodes.size())
385 uint32_t result = mRootNodeIds.size();
386 mRootNodeIds.push_back(iNode);
391 ExceptionFlinger(ASSERT_LOCATION) << "Failed to add new root with node " << iNode << " -- index out of bounds.";
396 const std::vector<Index>& SceneDefinition::GetRoots() const
401 void SceneDefinition::RemoveRootNode(Index iRoot)
403 if(iRoot < mRootNodeIds.size())
405 mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
409 ExceptionFlinger(ASSERT_LOCATION) << "Failed to remove root " << iRoot << " -- index out of bounds.";
413 uint32_t SceneDefinition::GetNodeCount() const
415 return mNodes.size();
418 const NodeDefinition* SceneDefinition::GetNode(Index iNode) const
420 return mNodes[iNode].get();
423 NodeDefinition* SceneDefinition::GetNode(Index iNode)
425 return mNodes[iNode].get();
428 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IVisitor& v)
430 VisitInternal(iNode, choices, v, *this);
433 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IConstVisitor& v) const
435 VisitInternal(iNode, choices, v, *this);
438 void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choices& choices, ResourceRefCounts& refCounts) const
440 struct RefCounter : IResourceReceiver
442 ResourceRefCounts* refCounts;
444 void Register(ResourceType::Value type, Index id)
446 ++(*refCounts)[type][id];
450 struct : NodeDefinition::IConstVisitor
454 void Start(const NodeDefinition& n)
458 n.mRenderable->RegisterResources(counter);
462 void Finish(const NodeDefinition& n)
467 refCounterVisitor.counter.refCounts = &refCounts;
469 Visit(iNode, choices, refCounterVisitor);
472 Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const
474 ActorCreatorVisitor actorCreatorVisitor(params);
476 Visit(iNode, choices, actorCreatorVisitor);
478 return actorCreatorVisitor.GetRoot();
481 void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
482 Customization::Map& outCustomizationOptions,
483 Customization::Choices* outMissingChoices) const
485 struct : NodeDefinition::IConstVisitor
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.
491 void Start(const NodeDefinition& n)
495 const std::string& tag = n.mCustomization->mTag;
496 if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
498 missingChoices->Set(tag, 0);
501 auto customization = options->Get(tag);
504 customization = options->Set(tag, {});
506 customization->nodes.push_back(n.mName);
507 customization->numOptions = std::max(customization->numOptions,
508 static_cast<uint32_t>(n.mChildren.size()));
512 void Finish(const NodeDefinition& n)
516 } customizationRegistrationVisitor;
517 customizationRegistrationVisitor.choices = &choices;
518 customizationRegistrationVisitor.options = &outCustomizationOptions;
519 customizationRegistrationVisitor.missingChoices = outMissingChoices;
521 for(auto i : mRootNodeIds)
523 Visit(i, choices, customizationRegistrationVisitor);
527 NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
529 if(FindNode(nodeDef->mName))
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)
537 mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
540 mNodes.push_back(std::move(nodeDef));
542 return mNodes.back().get();
545 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
547 LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
549 std::unique_ptr<NodeDefinition>* nodePtr = nullptr;
550 std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
551 if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
556 auto& node = *nodePtr;
557 auto iNode = std::distance(mNodes.data(), nodePtr);
559 DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
560 std::ostringstream stream;
561 stream << n.mName << " (" << n.mParentIdx << "):";
562 for(auto i : n.mChildren)
566 LOGD(("%s", stream.str().c_str()));
569 // Remove node from children of previous parent (if any).
570 if(node->mParentIdx != INVALID_INDEX)
572 LOGD(("old parent:"));
573 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
575 auto& children = mNodes[node->mParentIdx]->mChildren;
576 children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
578 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
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())
587 siblingOrder = children.size();
589 children.insert(children.begin() + siblingOrder, 1, iNode);
590 DEBUG_ONLY(dumpNode(**newParentPtr);)
592 // Update parent index.
594 DEBUG_ONLY(dumpNode(*node);)
595 auto iParent = std::distance(mNodes.data(), newParentPtr);
596 node->mParentIdx = iParent;
597 DEBUG_ONLY(dumpNode(*node);)
601 bool SceneDefinition::RemoveNode(const std::string& name)
603 std::unique_ptr<NodeDefinition>* node = nullptr;
604 if(!FindNode(name, &node))
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)
617 resetFn(thisNodes[i]);
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)
632 offsets.push_back(std::distance(mNodes.data(), &n));
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());
639 // Offset all indices (parent and child) by the index they'd sort into in offsets.
642 INDEX_FOR_REMOVAL = INVALID_INDEX
644 auto offsetter = [&offsets](Index& i) {
645 auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
646 if(iFind != offsets.end() && *iFind == i)
648 LOGD(("marking %d for removal.", i));
649 i = INDEX_FOR_REMOVAL;
654 auto distance = std::distance(offsets.begin(), iFind);
657 LOGD(("offsetting %d by %d.", i, distance));
664 for(auto& nd : mNodes)
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.
669 auto& children = nd->mChildren;
670 for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
675 children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
681 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
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)
688 buildStack(node->mParentIdx);
690 model.Push(node->GetLocalSpace());
695 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
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;
703 auto result = iFind != iEnd ? iFind->get() : nullptr;
704 if(result && outIndex)
706 *outIndex = std::distance(iBegin, iFind);
711 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
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;
719 auto result = iFind != iEnd ? iFind->get() : nullptr;
720 if(result && outIndex)
722 *outIndex = std::distance(iBegin, iFind);
727 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
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;
734 return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
737 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
740 for(auto& defp : mNodes)
754 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
757 for(auto& defp : mNodes)
771 void SceneDefinition::ApplyConstraints(Actor& root,
772 std::vector<ConstraintRequest>&& constrainables,
773 StringCallback onError) const
775 for(auto& cr : constrainables)
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)
782 auto propertyType = cr.mTarget.GetPropertyType(iTarget);
783 auto iFind = sConstraintFactory.find(propertyType);
784 if(iFind == sConstraintFactory.end())
786 onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
788 cr.mConstraint->mProperty.c_str(),
789 PropertyTypes::GetName(propertyType)));
793 Constraint constraint = iFind->second(cr.mTarget, iTarget);
795 Actor source = root.FindChildByName(nodeDef->mName);
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.",
801 cr.mConstraint->mProperty.c_str(),
802 targetName.c_str()));
805 else if(source == cr.mTarget)
807 onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
809 cr.mConstraint->mProperty.c_str()));
813 Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
814 constraint.AddSource(Source{source, iSource});
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.",
822 cr.mConstraint->mProperty.c_str(),
823 targetName.c_str()));
828 void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefinition::Vector& skeletons, Actor root) const
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;
836 for(auto& s : skeletons)
838 std::map<uint32_t, uint32_t> jointRefs;
839 for(auto& j : s.mJoints)
841 auto nodeIdx = j.mNodeIdx;
842 do // Traverse upwards and record each node we have visited until we reach the scene root.
844 path.push_back(nodeIdx);
849 auto node = GetNode(nodeIdx);
850 nodeIdx = node->mParentIdx;
851 } while(nodeIdx != INVALID_INDEX);
853 if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
864 // Only record the skeleton if we have encountered the root of the current scene.
865 if(jointRefs.empty())
870 Index root = s.mRootNodeIdx;
872 auto iFind = jointRefs.find(root);
873 if(iFind != jointRefs.end())
875 maxRef = iFind->second;
878 std::vector<Index> joints;
879 for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
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)))
886 RemoveFromSorted(joints, root);
889 else if(j.second == 1) // This one's a leaf.
891 InsertUniqueSorted(joints, j.first);
895 // Merge skeletons that share the same root.
896 auto& finalJoints = rootsJoints[root];
899 if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
900 return IsAncestor(*this, j, jj, root);
901 }) != finalJoints.end())
903 continue; // if the joint is found to be an ancestor of another joint already registered, move on.
907 while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
909 auto node = GetNode(i);
910 i = node->mParentIdx;
912 RemoveFromSorted(finalJoints, i);
915 InsertUniqueSorted(finalJoints, j);
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)
925 auto i = iRoots->first;
927 while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
929 auto node = GetNode(i);
930 i = node->mParentIdx;
932 auto iFind = rootsJoints.find(i);
933 if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
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);
939 if(iFindLeaf != iFind->second.end())
941 iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
944 // Merge iRoots with iFind
945 auto& targetJoints = iFind->second;
946 if(iRoots->second.empty()) // The root is a leaf.
948 InsertUniqueSorted(targetJoints, iRoots->first);
951 for(auto j : iRoots->second)
953 InsertUniqueSorted(targetJoints, j);
957 break; // Traverse no more
961 iRoots = merged ? rootsJoints.erase(iRoots) : std::next(iRoots);
964 // 3, For each root, register joint matrices and constraints
965 for(auto r : rootsJoints)
967 auto node = GetNode(r.first);
968 auto rootJoint = root.FindChildByName(node->mName);
969 DALI_ASSERT_ALWAYS(!!rootJoint);
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());
976 constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
977 constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
980 for(auto j : r.second)
983 auto joint = rootJoint.FindChildByName(node->mName);
984 ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
989 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
991 std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
992 for(auto& node : mNodes)
994 if(node->mRenderable)
996 ResourceReflector reflector;
997 node->mRenderable->ReflectResources(reflector);
1001 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1002 if(mesh.IsSkinned())
1004 skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
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)
1015 auto& skeletons = users.second;
1016 auto iterSkeleton = skeletons.begin();
1017 // skipping the first skeleton.
1020 resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
1021 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1023 while(iterSkeleton != skeletons.end())
1025 Index iShader = resources.mShaders.size();
1026 resources.mShaders.push_back({shaderDef, Shader()});
1028 for(auto& i : iterSkeleton->second)
1037 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources,
1039 std::vector<SkinningShaderConfigurationRequest>&& requests) const
1041 if(requests.empty())
1046 SortAndDeduplicateSkinningRequests(requests);
1048 for(auto& i : requests)
1050 auto& skeleton = resources.mSkeletons[i.mSkeletonIdx];
1051 if(skeleton.mJoints.empty())
1053 LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx));
1058 for(auto& j : skeleton.mJoints)
1060 auto node = GetNode(j.mNodeIdx);
1061 Actor actor = rootActor.FindChildByName(node->mName);
1062 ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx);
1067 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources,
1069 std::vector<BlendshapeShaderConfigurationRequest>&& requests,
1070 StringCallback onError) const
1072 if(requests.empty())
1077 // Sort requests by shaders.
1078 std::sort(requests.begin(), requests.end());
1080 // Remove duplicates.
1081 auto i = requests.begin();
1082 auto iEnd = requests.end();
1083 Shader s = i->mShader;
1087 // Multiple identical shader instances are removed.
1088 while(i != iEnd && i->mShader == s)
1090 i->mShader = Shader();
1102 // Configure the rest.
1105 for(auto& i : requests)
1108 if(FindNode(i.mNodeName, &iNode))
1110 const auto& node = GetNode(iNode);
1112 const auto& mesh = resources.mMeshes[i.mMeshIdx];
1114 if(mesh.first.HasBlendShapes())
1116 Actor actor = rootActor.FindChildByName(node->mName);
1118 // Sets the property to be animated.
1119 BlendShapes::ConfigureProperties(mesh, i.mShader, actor);
1127 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
1129 std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
1130 for(auto& node : mNodes)
1132 if(node->mRenderable)
1134 ResourceReflector reflector;
1135 node->mRenderable->ReflectResources(reflector);
1139 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1140 if(mesh.HasBlendShapes())
1142 blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
1148 for(auto& users : blendShapeShaderUsers)
1150 resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
1151 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1153 auto nodesIt = users.second.begin();
1154 auto nodesEndIt = users.second.end();
1155 // skipping the first node.
1157 while(nodesIt != nodesEndIt)
1159 Index iShader = resources.mShaders.size();
1160 resources.mShaders.push_back({shaderDef, Shader()});
1162 auto& nodes = *nodesIt;
1163 for(auto& shader : nodes.second)
1172 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
1174 SceneDefinition temp(std::move(other));
1175 std::swap(mNodes, temp.mNodes);
1176 std::swap(mRootNodeIds, temp.mRootNodeIds);
1180 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
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;
1189 const bool success = iFind != mNodes.begin();
1190 if(success && result)
1199 } // namespace Loader
1200 } // namespace Scene3D