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::IVisitor
170 ActorCreatorVisitor(NodeDefinition::CreateParams& params)
171 : mCreationContext(params)
175 void Start(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(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)
456 for(auto& renderable : n.mRenderables)
458 renderable->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)
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 // add next index (to which we're about to push) as a child to the designated parent, if any.
530 if(nodeDef->mParentIdx != INVALID_INDEX)
532 mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
535 mNodes.push_back(std::move(nodeDef));
537 return mNodes.back().get();
540 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
542 LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
544 std::unique_ptr<NodeDefinition>* nodePtr = nullptr;
545 std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
546 if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
551 auto& node = *nodePtr;
552 auto iNode = std::distance(mNodes.data(), nodePtr);
554 DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
555 std::ostringstream stream;
556 stream << n.mName << " (" << n.mParentIdx << "):";
557 for(auto i : n.mChildren)
561 LOGD(("%s", stream.str().c_str()));
564 // Remove node from children of previous parent (if any).
565 if(node->mParentIdx != INVALID_INDEX)
567 LOGD(("old parent:"));
568 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
570 auto& children = mNodes[node->mParentIdx]->mChildren;
571 children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
573 DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
576 // Register node to new parent.
577 LOGD(("new parent:"));
578 DEBUG_ONLY(dumpNode(**newParentPtr);)
579 auto& children = (*newParentPtr)->mChildren;
580 if(siblingOrder > children.size())
582 siblingOrder = children.size();
584 children.insert(children.begin() + siblingOrder, 1, iNode);
585 DEBUG_ONLY(dumpNode(**newParentPtr);)
587 // Update parent index.
589 DEBUG_ONLY(dumpNode(*node);)
590 auto iParent = std::distance(mNodes.data(), newParentPtr);
591 node->mParentIdx = iParent;
592 DEBUG_ONLY(dumpNode(*node);)
596 bool SceneDefinition::RemoveNode(const std::string& name)
598 std::unique_ptr<NodeDefinition>* node = nullptr;
599 if(!FindNode(name, &node))
604 // Reset node def pointers recursively.
605 auto& thisNodes = mNodes;
606 unsigned int numReset = 0;
607 std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
608 [&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
609 LOGD(("resetting %d", &nd - thisNodes.data()));
610 for(auto i : nd->mChildren)
612 resetFn(thisNodes[i]);
620 // Gather indices of dead nodes into a vector which we sort on insertion.
621 std::vector<Index> offsets;
622 offsets.reserve(numReset);
623 for(auto& n : mNodes)
627 offsets.push_back(std::distance(mNodes.data(), &n));
631 // Erase dead nodes as they don't have to be processed anymore.
632 mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
634 // Offset all indices (parent and child) by the index they'd sort into in offsets.
637 INDEX_FOR_REMOVAL = INVALID_INDEX
639 auto offsetter = [&offsets](Index& i) {
640 auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
641 if(iFind != offsets.end() && *iFind == i)
643 LOGD(("marking %d for removal.", i));
644 i = INDEX_FOR_REMOVAL;
649 auto distance = std::distance(offsets.begin(), iFind);
652 LOGD(("offsetting %d by %d.", i, distance));
659 for(auto& nd : mNodes)
661 bool parentOffsetResult = offsetter(nd->mParentIdx);
662 DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
664 auto& children = nd->mChildren;
665 for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
670 children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
676 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
678 auto& thisNodes = mNodes;
679 std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
680 auto node = thisNodes[i].get();
681 if(node->mParentIdx != INVALID_INDEX)
683 buildStack(node->mParentIdx);
685 model.Push(node->GetLocalSpace());
690 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
692 auto iBegin = mNodes.begin();
693 auto iEnd = mNodes.end();
694 auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
695 return nd->mName == name;
698 auto result = iFind != iEnd ? iFind->get() : nullptr;
699 if(result && outIndex)
701 *outIndex = std::distance(iBegin, iFind);
706 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
708 auto iBegin = mNodes.begin();
709 auto iEnd = mNodes.end();
710 auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
711 return nd->mName == name;
714 auto result = iFind != iEnd ? iFind->get() : nullptr;
715 if(result && outIndex)
717 *outIndex = std::distance(iBegin, iFind);
722 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
724 auto iBegin = mNodes.begin();
725 auto iEnd = mNodes.end();
726 auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
727 return n.get() == &node;
729 return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
732 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
735 for(auto& defp : mNodes)
749 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
752 for(auto& defp : mNodes)
766 void SceneDefinition::ApplyConstraints(Actor& root,
767 std::vector<ConstraintRequest>&& constrainables,
768 StringCallback onError) const
770 for(auto& cr : constrainables)
772 auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx];
773 auto sourceName = nodeDef->mName.c_str();
774 Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
775 if(iTarget != Property::INVALID_INDEX)
777 auto propertyType = cr.mTarget.GetPropertyType(iTarget);
778 auto iFind = sConstraintFactory.find(propertyType);
779 if(iFind == sConstraintFactory.end())
781 onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
783 cr.mConstraint->mProperty.c_str(),
784 PropertyTypes::GetName(propertyType)));
788 Constraint constraint = iFind->second(cr.mTarget, iTarget);
790 Actor source = root.FindChildByName(nodeDef->mName);
793 auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
794 onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
796 cr.mConstraint->mProperty.c_str(),
797 targetName.c_str()));
800 else if(source == cr.mTarget)
802 onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
804 cr.mConstraint->mProperty.c_str()));
808 Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
809 constraint.AddSource(Source{source, iSource});
814 auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
815 onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
817 cr.mConstraint->mProperty.c_str(),
818 targetName.c_str()));
823 void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefinition::Vector& skeletons, Actor root) const
825 // 1, For each skeleton, for each joint, walk upwards until we reach mNodes[iRoot]. If we do, record +1
826 // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1
827 // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton.
828 std::map<Index, std::vector<Index>> rootsJoints;
829 std::vector<Index> path;
831 for(auto& s : skeletons)
833 std::map<uint32_t, uint32_t> jointRefs;
834 for(auto& j : s.mJoints)
836 auto nodeIdx = j.mNodeIdx;
837 do // Traverse upwards and record each node we have visited until we reach the scene root.
839 path.push_back(nodeIdx);
844 auto node = GetNode(nodeIdx);
845 nodeIdx = node->mParentIdx;
846 } while(nodeIdx != INVALID_INDEX);
848 if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
859 // Only record the skeleton if we have encountered the root of the current scene.
860 if(jointRefs.empty())
865 Index root = s.mRootNodeIdx;
867 auto iFind = jointRefs.find(root);
868 if(iFind != jointRefs.end())
870 maxRef = iFind->second;
873 std::vector<Index> joints;
874 for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
876 // The most descendant node with the highest ref count is the root of the skeleton.
877 if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
881 RemoveFromSorted(joints, root);
884 else if(j.second == 1) // This one's a leaf.
886 InsertUniqueSorted(joints, j.first);
890 // Merge skeletons that share the same root.
891 auto& finalJoints = rootsJoints[root];
894 if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
895 return IsAncestor(*this, j, jj, root);
896 }) != finalJoints.end())
898 continue; // if the joint is found to be an ancestor of another joint already registered, move on.
902 while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
904 auto node = GetNode(i);
905 i = node->mParentIdx;
907 RemoveFromSorted(finalJoints, i);
910 InsertUniqueSorted(finalJoints, j);
914 // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous
915 // leaf nodes that now have descendants, and add new ones.
916 auto iRoots = rootsJoints.begin();
917 auto iRootsEnd = rootsJoints.end();
918 while(iRoots != iRootsEnd)
920 auto i = iRoots->first;
922 while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
924 auto node = GetNode(i);
925 i = node->mParentIdx;
927 auto iFind = rootsJoints.find(i);
928 if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
930 // Now find out which leaf of iFind is an ancestor, if any.
931 auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) {
932 return IsAncestor(*this, j, iRoots->first, iFind->first);
934 if(iFindLeaf != iFind->second.end())
936 iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
939 // Merge iRoots with iFind
940 auto& targetJoints = iFind->second;
941 if(iRoots->second.empty()) // The root is a leaf.
943 InsertUniqueSorted(targetJoints, iRoots->first);
946 for(auto j : iRoots->second)
948 InsertUniqueSorted(targetJoints, j);
952 break; // Traverse no more
956 iRoots = merged ? rootsJoints.erase(iRoots) : std::next(iRoots);
959 // 3, For each root, register joint matrices and constraints
960 for(const auto& r : rootsJoints)
962 auto node = GetNode(r.first);
963 auto rootJoint = root.FindChildByName(node->mName);
964 DALI_ASSERT_ALWAYS(!!rootJoint);
966 DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX);
967 auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false});
968 Constraint constraint = Constraint::New<Matrix>(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
969 output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
971 constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
972 constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
975 for(const auto j : r.second)
978 auto joint = rootJoint.FindChildByName(node->mName);
979 ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
984 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
986 std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
987 for(auto& node : mNodes)
989 for(auto& renderable : node->mRenderables)
991 ResourceReflector reflector;
992 renderable->ReflectResources(reflector);
996 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
999 skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
1005 // For each shader, and each skeleton using the same shader as the first skeleton,
1006 // update the shader references (from nodes with skinned meshes) with a new copy of
1007 // the shader definition from the node using the first skeleton.
1008 for(auto& users : skinningShaderUsers)
1010 auto& skeletons = users.second;
1011 auto iterSkeleton = skeletons.begin();
1012 // skipping the first skeleton.
1015 resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
1016 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1018 while(iterSkeleton != skeletons.end())
1020 Index iShader = resources.mShaders.size();
1021 resources.mShaders.push_back({shaderDef, Shader()});
1023 for(auto& i : iterSkeleton->second)
1032 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources,
1034 std::vector<SkinningShaderConfigurationRequest>&& requests) const
1036 if(requests.empty())
1041 SortAndDeduplicateSkinningRequests(requests);
1043 for(auto& request : requests)
1045 auto& skeleton = resources.mSkeletons[request.mSkeletonIdx];
1046 if(skeleton.mJoints.empty())
1048 LOGD(("Skeleton %d has no joints.", request.mSkeletonIdx));
1053 for(auto& joint : skeleton.mJoints)
1055 auto node = GetNode(joint.mNodeIdx);
1056 Actor actor = rootActor.FindChildByName(node->mName);
1057 ConfigureBoneMatrix(joint.mInverseBindMatrix, actor, request.mShader, boneIdx);
1062 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources,
1064 std::vector<BlendshapeShaderConfigurationRequest>&& requests,
1065 StringCallback onError) const
1067 if(requests.empty())
1072 // Sort requests by shaders.
1073 std::sort(requests.begin(), requests.end());
1075 // Remove duplicates.
1076 auto i = requests.begin();
1077 auto iEnd = requests.end();
1078 Shader s = i->mShader;
1082 // Multiple identical shader instances are removed.
1083 while(i != iEnd && i->mShader == s)
1085 i->mShader = Shader();
1097 // Configure the rest.
1100 for(auto& i : requests)
1103 if(FindNode(i.mNodeName, &iNode))
1105 const auto& node = GetNode(iNode);
1107 const auto& mesh = resources.mMeshes[i.mMeshIdx];
1109 if(mesh.first.HasBlendShapes())
1111 Actor actor = rootActor.FindChildByName(node->mName);
1113 // Sets the property to be animated.
1114 BlendShapes::ConfigureProperties(mesh, i.mShader, actor);
1122 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
1124 std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
1125 for(auto& node : mNodes)
1127 for(auto& renderable : node->mRenderables)
1129 ResourceReflector reflector;
1130 renderable->ReflectResources(reflector);
1134 const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1135 if(mesh.HasBlendShapes())
1137 blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
1143 for(auto& users : blendShapeShaderUsers)
1145 resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
1146 const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1148 auto nodesIt = users.second.begin();
1149 auto nodesEndIt = users.second.end();
1150 // skipping the first node.
1152 while(nodesIt != nodesEndIt)
1154 Index iShader = resources.mShaders.size();
1155 resources.mShaders.push_back({shaderDef, Shader()});
1157 auto& nodes = *nodesIt;
1158 for(auto& shader : nodes.second)
1167 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
1169 SceneDefinition temp(std::move(other));
1170 std::swap(mNodes, temp.mNodes);
1171 std::swap(mRootNodeIds, temp.mRootNodeIds);
1175 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
1177 // We're searching from the end assuming a higher probability of operations targeting
1178 // recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
1179 // the first to be added, is index 0.)
1180 auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) {
1181 return nd->mName == name;
1184 const bool success = iFind != mNodes.begin();
1185 if(success && result)
1194 } // namespace Loader
1195 } // namespace Scene3D