2 * Copyright (c) 2023 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-scene3d/internal/controls/model/model-impl.h>
22 #include <dali-toolkit/dali-toolkit.h>
23 #include <dali-toolkit/internal/controls/control/control-data-impl.h>
24 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
25 #include <dali/devel-api/actors/actor-devel.h>
26 #include <dali/integration-api/adaptor-framework/adaptor.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/public-api/math/math-utils.h>
29 #include <dali/public-api/object/type-registry-helper.h>
30 #include <dali/public-api/object/type-registry.h>
34 #include <dali-scene3d/internal/common/model-cache-manager.h>
35 #include <dali-scene3d/internal/controls/scene-view/scene-view-impl.h>
36 #include <dali-scene3d/internal/light/light-impl.h>
37 #include <dali-scene3d/internal/model-components/model-node-impl.h>
38 #include <dali-scene3d/public-api/controls/model/model.h>
39 #include <dali-scene3d/public-api/loader/animation-definition.h>
40 #include <dali-scene3d/public-api/loader/camera-parameters.h>
41 #include <dali-scene3d/public-api/loader/light-parameters.h>
42 #include <dali-scene3d/public-api/loader/load-result.h>
43 #include <dali-scene3d/public-api/loader/node-definition.h>
44 #include <dali-scene3d/public-api/loader/scene-definition.h>
45 #include <dali-scene3d/public-api/loader/shader-manager.h>
46 #include <dali-scene3d/public-api/model-motion/motion-index/blend-shape-index.h>
59 * Creates control through type registry
63 return Scene3D::Model::New(std::string());
66 // Setup properties, signals and actions using the type-registry.
67 DALI_TYPE_REGISTRATION_BEGIN(Scene3D::Model, Toolkit::Control, Create);
68 DALI_TYPE_REGISTRATION_END()
70 static constexpr Vector3 Y_DIRECTION(1.0f, -1.0f, 1.0f);
71 static constexpr float SIZE_STEP_CONDITION = 0.1f;
73 static constexpr bool DEFAULT_MODEL_CHILDREN_SENSITIVE = false;
74 static constexpr bool DEFAULT_MODEL_CHILDREN_FOCUSABLE = false;
80 pointMin = Vector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
81 pointMax = Vector3(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
84 void ConsiderNewPointInVolume(const Vector3& position)
86 pointMin.x = std::min(position.x, pointMin.x);
87 pointMin.y = std::min(position.y, pointMin.y);
88 pointMin.z = std::min(position.z, pointMin.z);
90 pointMax.x = std::max(position.x, pointMax.x);
91 pointMax.y = std::max(position.y, pointMax.y);
92 pointMax.z = std::max(position.z, pointMax.z);
95 Vector3 CalculateSize()
97 return pointMax - pointMin;
100 Vector3 CalculatePivot()
102 Vector3 pivot = pointMin / (pointMin - pointMax);
103 for(uint32_t i = 0; i < 3; ++i)
105 // To avoid divid by zero
106 if(Dali::Equals(pointMin[i], pointMax[i]))
118 void ConfigureBlendShapeShaders(
119 Dali::Scene3D::Loader::ResourceBundle& resources, const Dali::Scene3D::Loader::SceneDefinition& scene, Actor root, std::vector<Dali::Scene3D::Loader::BlendshapeShaderConfigurationRequest>&& requests)
121 std::vector<std::string> errors;
122 auto onError = [&errors](const std::string& msg) { errors.push_back(msg); };
123 if(!scene.ConfigureBlendshapeShaders(resources, root, std::move(requests), onError))
125 Dali::Scene3D::Loader::ExceptionFlinger flinger(ASSERT_LOCATION);
126 for(auto& msg : errors)
128 flinger << msg << '\n';
133 void AddModelTreeToAABB(BoundingVolume& AABB, const Dali::Scene3D::Loader::SceneDefinition& scene, const Dali::Scene3D::Loader::Customization::Choices& choices, Dali::Scene3D::Loader::Index iNode, Dali::Scene3D::Loader::NodeDefinition::CreateParams& nodeParams, Matrix parentMatrix)
135 static constexpr uint32_t BOX_POINT_COUNT = 8;
136 static uint32_t BBIndex[BOX_POINT_COUNT][3] = {{0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}};
139 const Dali::Scene3D::Loader::NodeDefinition* node = scene.GetNode(iNode);
140 Matrix localMatrix = node->GetLocalSpace();
141 Matrix::Multiply(nodeMatrix, localMatrix, parentMatrix);
144 if(node->GetExtents(nodeParams.mResources, volume[0], volume[1]))
146 for(uint32_t i = 0; i < BOX_POINT_COUNT; ++i)
148 Vector4 position = Vector4(volume[BBIndex[i][0]].x, volume[BBIndex[i][1]].y, volume[BBIndex[i][2]].z, 1.0f);
149 Vector4 objectPosition = nodeMatrix * position;
150 objectPosition /= objectPosition.w;
152 AABB.ConsiderNewPointInVolume(Vector3(objectPosition));
156 if(node->mCustomization)
158 if(!node->mChildren.empty())
160 auto choice = choices.Get(node->mCustomization->mTag);
161 Dali::Scene3D::Loader::Index i = std::min(choice != Dali::Scene3D::Loader::Customization::NONE ? choice : 0, static_cast<Dali::Scene3D::Loader::Index>(node->mChildren.size() - 1));
163 AddModelTreeToAABB(AABB, scene, choices, node->mChildren[i], nodeParams, nodeMatrix);
168 for(auto i : node->mChildren)
170 AddModelTreeToAABB(AABB, scene, choices, i, nodeParams, nodeMatrix);
175 void UpdateBlendShapeNodeMapRecursively(Model::BlendShapeModelNodeMap& resultMap, const Scene3D::ModelNode& node)
181 const auto childCount = node.GetChildCount();
182 for(auto i = 0u; i < childCount; ++i)
184 UpdateBlendShapeNodeMapRecursively(resultMap, Scene3D::ModelNode::DownCast(node.GetChildAt(i)));
187 std::vector<std::string> blendShapeNames;
188 node.RetrieveBlendShapeNames(blendShapeNames);
189 for(const auto& iter : blendShapeNames)
191 // Append or create new list.
192 resultMap[iter].push_back(node);
196 void UpdateShaderRecursively(Scene3D::ModelNode node, Scene3D::Loader::ShaderManagerPtr shaderManager)
203 GetImplementation(node).UpdateShader(shaderManager);
205 uint32_t childrenCount = node.GetChildCount();
206 for(uint32_t i = 0; i < childrenCount; ++i)
208 Scene3D::ModelNode childNode = Scene3D::ModelNode::DownCast(node.GetChildAt(i));
211 UpdateShaderRecursively(childNode, shaderManager);
216 } // anonymous namespace
218 Model::Model(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
219 : Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
221 mResourceDirectoryUrl(resourceDirectoryUrl),
223 mShaderManager(new Scene3D::Loader::ShaderManager()),
224 mNaturalSize(Vector3::ZERO),
225 mModelPivot(AnchorPoint::CENTER),
226 mSceneIblScaleFactor(1.0f),
227 mIblScaleFactor(1.0f),
228 mSceneSpecularMipmapLevels(1u),
229 mSpecularMipmapLevels(1u),
230 mModelChildrenSensitive(DEFAULT_MODEL_CHILDREN_SENSITIVE),
231 mModelChildrenFocusable(DEFAULT_MODEL_CHILDREN_FOCUSABLE),
232 mModelResourceReady(false),
233 mIblDiffuseResourceReady(true),
234 mIblSpecularResourceReady(true),
235 mIblDiffuseDirty(false),
236 mIblSpecularDirty(false)
242 ResetResourceTasks();
244 if(ModelCacheManager::Get() && !mModelUrl.empty())
246 ModelCacheManager::Get().UnreferenceModelCache(mModelUrl);
250 Dali::Scene3D::Model Model::New(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
252 Model* impl = new Model(modelUrl, resourceDirectoryUrl);
254 Dali::Scene3D::Model handle = Dali::Scene3D::Model(*impl);
256 // Second-phase init of the implementation
257 // This can only be done after the CustomActor connection has been made...
263 const Scene3D::ModelNode Model::GetModelRoot() const
268 void Model::AddModelNode(Scene3D::ModelNode modelNode)
275 mModelRoot.Add(modelNode);
276 if(mModelUrl.empty())
278 mModelResourceReady = true;
281 UpdateShaderRecursively(modelNode, mShaderManager);
283 if(mIblDiffuseResourceReady && mIblSpecularResourceReady)
285 UpdateImageBasedLightTexture();
286 UpdateImageBasedLightScaleFactor();
289 if(Self().GetProperty<bool>(Dali::Actor::Property::CONNECTED_TO_SCENE))
291 NotifyResourceReady();
295 void Model::RemoveModelNode(Scene3D::ModelNode modelNode)
299 UpdateShaderRecursively(modelNode, nullptr);
300 mModelRoot.Remove(modelNode);
304 void Model::SetChildrenSensitive(bool enable)
306 if(mModelChildrenSensitive != enable)
308 mModelChildrenSensitive = enable;
311 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
316 bool Model::GetChildrenSensitive() const
318 return mModelChildrenSensitive;
321 void Model::SetChildrenFocusable(bool enable)
323 if(mModelChildrenFocusable != enable)
325 mModelChildrenFocusable = enable;
328 mModelRoot.SetProperty(Dali::Actor::Property::KEYBOARD_FOCUSABLE, mModelChildrenFocusable);
329 mModelRoot.SetProperty(Dali::DevelActor::Property::KEYBOARD_FOCUSABLE_CHILDREN, mModelChildrenFocusable);
334 bool Model::GetChildrenFocusable() const
336 return mModelChildrenFocusable;
339 void Model::SetImageBasedLightSource(const std::string& diffuseUrl, const std::string& specularUrl, float scaleFactor)
341 bool needIblReset = false;
342 bool isOnScene = Self().GetProperty<bool>(Dali::Actor::Property::CONNECTED_TO_SCENE);
343 if(mDiffuseIblUrl != diffuseUrl)
345 mDiffuseIblUrl = diffuseUrl;
346 if(mDiffuseIblUrl.empty())
352 mIblDiffuseDirty = true;
353 mIblDiffuseResourceReady = false;
357 if(mSpecularIblUrl != specularUrl)
359 mSpecularIblUrl = specularUrl;
360 if(mSpecularIblUrl.empty())
366 mIblSpecularDirty = true;
367 mIblSpecularResourceReady = false;
371 // If one or both of diffuse url and specular url are empty,
372 // we don't need to request to load texture.
375 ResetResourceTask(mIblDiffuseLoadTask);
376 ResetResourceTask(mIblSpecularLoadTask);
378 mIblDiffuseDirty = false;
379 mIblSpecularDirty = false;
380 mIblDiffuseResourceReady = true;
381 mIblSpecularResourceReady = true;
383 mDiffuseTexture.Reset();
384 mSpecularTexture.Reset();
385 UpdateImageBasedLightTexture();
389 if(isOnScene && mIblDiffuseDirty)
391 ResetResourceTask(mIblDiffuseLoadTask);
392 mIblDiffuseLoadTask = new EnvironmentMapLoadTask(mDiffuseIblUrl, Scene3D::EnvironmentMapType::CUBEMAP, MakeCallback(this, &Model::OnIblDiffuseLoadComplete));
393 Dali::AsyncTaskManager::Get().AddTask(mIblDiffuseLoadTask);
394 mIblDiffuseDirty = false;
397 if(isOnScene && mIblSpecularDirty)
399 ResetResourceTask(mIblSpecularLoadTask);
400 mIblSpecularLoadTask = new EnvironmentMapLoadTask(mSpecularIblUrl, Scene3D::EnvironmentMapType::CUBEMAP, MakeCallback(this, &Model::OnIblSpecularLoadComplete));
401 Dali::AsyncTaskManager::Get().AddTask(mIblSpecularLoadTask);
402 mIblSpecularDirty = false;
406 if(!Dali::Equals(mIblScaleFactor, scaleFactor))
408 mIblScaleFactor = scaleFactor;
409 UpdateImageBasedLightScaleFactor();
412 // If diffuse and specular textures are already loaded, emits resource ready signal here.
413 NotifyResourceReady();
416 void Model::SetImageBasedLightScaleFactor(float scaleFactor)
418 mIblScaleFactor = scaleFactor;
419 if(mDiffuseTexture && mSpecularTexture)
421 UpdateImageBasedLightScaleFactor();
425 float Model::GetImageBasedLightScaleFactor() const
427 return mIblScaleFactor;
430 uint32_t Model::GetAnimationCount() const
432 return mAnimations.size();
435 Dali::Animation Model::GetAnimation(uint32_t index) const
437 Dali::Animation animation;
438 if(mAnimations.size() > index)
440 animation = mAnimations[index].second;
445 Dali::Animation Model::GetAnimation(const std::string& name) const
447 Dali::Animation animation;
450 for(auto&& animationData : mAnimations)
452 if(animationData.first == name)
454 animation = animationData.second;
462 uint32_t Model::GetCameraCount() const
464 return mCameraParameters.size();
467 Dali::CameraActor Model::GenerateCamera(uint32_t index) const
469 Dali::CameraActor camera;
470 if(mCameraParameters.size() > index)
472 camera = Dali::CameraActor::New3DCamera();
473 if(!mCameraParameters[index].ConfigureCamera(camera, false))
475 DALI_LOG_ERROR("Fail to generate %u's camera actor : Some property was not defined. Please check model file.\n", index);
480 ApplyCameraTransform(camera);
485 bool Model::ApplyCamera(uint32_t index, Dali::CameraActor camera) const
487 if(camera && mCameraParameters.size() > index)
489 if(!mCameraParameters[index].ConfigureCamera(camera, false))
491 DALI_LOG_ERROR("Fail to apply %u's camera actor : Some property was not defined. Please check model file.\n", index);
495 ApplyCameraTransform(camera);
501 Scene3D::ModelNode Model::FindChildModelNodeByName(std::string_view nodeName)
503 Actor childActor = Self().FindChildByName(nodeName);
504 return Scene3D::ModelNode::DownCast(childActor);
507 void Model::RetrieveBlendShapeNames(std::vector<std::string>& blendShapeNames) const
509 blendShapeNames.reserve(blendShapeNames.size() + mBlendShapeModelNodeMap.size());
510 for(const auto& iter : mBlendShapeModelNodeMap)
512 blendShapeNames.push_back(iter.first);
516 void Model::RetrieveModelNodesByBlendShapeName(std::string_view blendShapeName, std::vector<Scene3D::ModelNode>& modelNodes) const
518 auto iter = mBlendShapeModelNodeMap.find(std::string(blendShapeName));
519 if(iter != mBlendShapeModelNodeMap.end())
521 const auto& modelNodeList = iter->second;
522 modelNodes.reserve(modelNodes.size() + modelNodeList.size());
523 for(const auto& nodeIter : modelNodeList)
525 modelNodes.push_back(nodeIter);
530 Dali::Animation Model::GenerateMotionDataAnimation(Scene3D::MotionData motionData)
532 Dali::Animation animation;
534 // TODO : Need to collect duplicated codes with SetMotionData()
538 const uint32_t motionCount = motionData.GetMotionCount();
539 for(uint32_t i = 0u; i < motionCount; ++i)
541 auto motionIndex = motionData.GetIndex(i);
542 auto motionValue = motionData.GetValue(i);
543 if(motionIndex && motionValue)
545 if(motionIndex.GetModelNodeId() != Property::INVALID_KEY)
547 Scene3D::ModelNode modelNode;
548 if(motionIndex.GetModelNodeId().type == Property::Key::Type::STRING)
550 modelNode = FindChildModelNodeByName(motionIndex.GetModelNodeId().stringKey);
552 else if(motionIndex.GetModelNodeId().type == Property::Key::Type::INDEX)
554 // TODO : Not implement yet.
559 KeyFrames keyFrames = motionValue.GetKeyFrames();
563 // Try to use index first. If failed, try to use name
564 Property::Index animatedPropertyIndex = motionIndex.GetPropertyIndex(modelNode);
565 if(animatedPropertyIndex != Property::INVALID_INDEX)
567 if(DALI_UNLIKELY(!animation))
569 animation = Animation::New(motionData.GetDuration());
571 animation.AnimateBetween(Dali::Property(modelNode, animatedPropertyIndex), keyFrames);
575 std::string animatedPropertyName = motionIndex.GetPropertyName(modelNode);
576 Dali::Property property(modelNode, animatedPropertyName);
577 if(property.propertyIndex != Property::INVALID_INDEX)
579 if(DALI_UNLIKELY(!animation))
581 animation = Animation::New(motionData.GetDuration());
583 animation.AnimateBetween(property, keyFrames);
591 Scene3D::BlendShapeIndex blendShapeIndex = Scene3D::BlendShapeIndex::DownCast(motionIndex);
592 if(blendShapeIndex && blendShapeIndex.GetBlendShapeId().type == Property::Key::Type::STRING)
594 // Special case : For BlendShapeIndex that doesn't have ModelNodeId and has string BlendShapeId,
595 // we need to animate all kind of blendshapes
597 KeyFrames keyFrames = motionValue.GetKeyFrames();
601 std::vector<Scene3D::ModelNode> modelNodes;
602 RetrieveModelNodesByBlendShapeName(blendShapeIndex.GetBlendShapeId().stringKey, modelNodes);
604 for(auto& modelNode : modelNodes)
606 // Try to use index first. If failed, try to use name
607 Property::Index animatedPropertyIndex = motionIndex.GetPropertyIndex(modelNode);
608 if(animatedPropertyIndex != Property::INVALID_INDEX)
610 if(DALI_UNLIKELY(!animation))
612 animation = Animation::New(motionData.GetDuration());
614 animation.AnimateBetween(Dali::Property(modelNode, animatedPropertyIndex), keyFrames);
618 std::string animatedPropertyName = motionIndex.GetPropertyName(modelNode);
619 Dali::Property property(modelNode, animatedPropertyName);
621 if(property.propertyIndex != Property::INVALID_INDEX)
623 if(DALI_UNLIKELY(!animation))
625 animation = Animation::New(motionData.GetDuration());
627 animation.AnimateBetween(property, keyFrames);
641 void Model::SetMotionData(Scene3D::MotionData motionData)
643 // TODO : Need to collect duplicated codes with GenerateMotionDataAnimation()
647 const uint32_t motionCount = motionData.GetMotionCount();
648 for(uint32_t i = 0u; i < motionCount; ++i)
650 auto motionIndex = motionData.GetIndex(i);
651 auto motionValue = motionData.GetValue(i);
652 if(motionIndex && motionValue)
654 if(motionIndex.GetModelNodeId() != Property::INVALID_KEY)
656 Scene3D::ModelNode modelNode;
657 if(motionIndex.GetModelNodeId().type == Property::Key::Type::STRING)
659 modelNode = FindChildModelNodeByName(motionIndex.GetModelNodeId().stringKey);
661 else if(motionIndex.GetModelNodeId().type == Property::Key::Type::INDEX)
663 // TODO : Not implement yet.
668 Property::Value value = motionValue.GetPropertyValue();
670 if(value.GetType() != Property::Type::NONE)
672 // Try to use index first. If failed, try to use name
673 Property::Index propertyIndex = motionIndex.GetPropertyIndex(modelNode);
674 if(propertyIndex != Property::INVALID_INDEX)
676 modelNode.SetProperty(propertyIndex, value);
680 std::string propertyName = motionIndex.GetPropertyName(modelNode);
681 Dali::Property property(modelNode, propertyName);
682 if(property.propertyIndex != Property::INVALID_INDEX)
684 modelNode.SetProperty(property.propertyIndex, value);
692 Scene3D::BlendShapeIndex blendShapeIndex = Scene3D::BlendShapeIndex::DownCast(motionIndex);
693 if(blendShapeIndex && blendShapeIndex.GetBlendShapeId().type == Property::Key::Type::STRING)
695 // Special case : For BlendShapeIndex that doesn't have ModelNodeId and has string BlendShapeId,
696 // we need to animate all kind of blendshapes
698 Property::Value value = motionValue.GetPropertyValue();
700 if(value.GetType() != Property::Type::NONE)
702 std::vector<Scene3D::ModelNode> modelNodes;
703 RetrieveModelNodesByBlendShapeName(blendShapeIndex.GetBlendShapeId().stringKey, modelNodes);
705 for(auto& modelNode : modelNodes)
707 // Try to use index first. If failed, try to use name
708 Property::Index propertyIndex = motionIndex.GetPropertyIndex(modelNode);
709 if(propertyIndex != Property::INVALID_INDEX)
711 modelNode.SetProperty(propertyIndex, value);
715 std::string propertyName = motionIndex.GetPropertyName(modelNode);
716 Dali::Property property(modelNode, propertyName);
717 if(property.propertyIndex != Property::INVALID_INDEX)
719 modelNode.SetProperty(property.propertyIndex, value);
731 ///////////////////////////////////////////////////////////
736 void Model::OnInitialize()
738 // Make ParentOrigin as Center.
739 Self().SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
742 void Model::OnSceneConnection(int depth)
744 Actor parent = Self().GetParent();
747 // If this Model has parent SceneView and the its ShaderManager is same with privious ShaderManager,
748 // this Model don't need to update shader.
749 Scene3D::SceneView sceneView = Scene3D::SceneView::DownCast(parent);
752 mParentSceneView = sceneView;
753 GetImpl(sceneView).RegisterSceneItem(this);
754 Scene3D::Loader::ShaderManagerPtr shaderManager = GetImpl(sceneView).GetShaderManager();
755 if(mShaderManager != shaderManager)
757 mShaderManager = shaderManager;
758 UpdateShaderRecursively(mModelRoot, mShaderManager);
762 parent = parent.GetParent();
765 // Model can be added on Dali::Scene directly without SceneView.
766 // So, Model's mShaderManager and shaders of child ModelNodes are needed to be reset when this Model has not parent SceneView.
767 Scene3D::SceneView parentSceneView = mParentSceneView.GetHandle();
770 mShaderManager = new Dali::Scene3D::Loader::ShaderManager();
771 UpdateShaderRecursively(mModelRoot, mShaderManager);
774 if(!mModelLoadTask && !mModelResourceReady && !mModelUrl.empty())
776 // Request model load only if we setup url.
777 if(ModelCacheManager::Get())
779 ModelCacheManager::Get().ReferenceModelCache(mModelUrl);
781 mModelLoadTask = new ModelLoadTask(mModelUrl, mResourceDirectoryUrl, MakeCallback(this, &Model::OnModelLoadComplete));
782 Dali::AsyncTaskManager::Get().AddTask(mModelLoadTask);
785 // If diffuse and specular url is not valid, IBL does not need to be loaded.
786 if(!mDiffuseIblUrl.empty() && !mSpecularIblUrl.empty())
788 SetImageBasedLightSource(mDiffuseIblUrl, mSpecularIblUrl, mIblScaleFactor);
791 NotifyResourceReady();
793 mSizeNotification = Self().AddPropertyNotification(Actor::Property::SIZE, StepCondition(SIZE_STEP_CONDITION));
794 mSizeNotification.NotifySignal().Connect(this, &Model::OnSizeNotification);
795 Control::OnSceneConnection(depth);
798 void Model::OnSceneDisconnection()
800 // If mParentSceneView is still onScene, that means this model
801 // is disconnected from mParentSceneView's sub tree.
802 // So, Unregister this Model from SceneView.
803 Scene3D::SceneView sceneView = mParentSceneView.GetHandle();
804 if(sceneView && sceneView.GetProperty<bool>(Dali::Actor::Property::CONNECTED_TO_SCENE))
806 GetImpl(sceneView).UnregisterSceneItem(this);
807 mParentSceneView.Reset();
810 mSizeNotification.NotifySignal().Disconnect(this, &Model::OnSizeNotification);
811 Self().RemovePropertyNotification(mSizeNotification);
812 mSizeNotification.Reset();
814 Control::OnSceneDisconnection();
817 void Model::OnSizeSet(const Vector3& size)
822 Vector3 Model::GetNaturalSize()
826 DALI_LOG_ERROR("Model is still not loaded.\n");
827 return Vector3::ZERO;
833 float Model::GetHeightForWidth(float width)
836 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
837 return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
840 float Model::GetWidthForHeight(float height)
843 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
844 return Control::GetWidthForHeight(height) + padding.start + padding.end;
847 void Model::OnRelayout(const Vector2& size, RelayoutContainer& container)
849 Control::OnRelayout(size, container);
853 bool Model::IsResourceReady() const
855 return mModelResourceReady && mIblDiffuseResourceReady && mIblSpecularResourceReady;
858 void Model::CreateModelRoot()
860 mModelRoot = Scene3D::ModelNode::New();
861 mModelRoot.SetProperty(Actor::Property::COLOR_MODE, ColorMode::USE_OWN_MULTIPLY_PARENT_COLOR);
862 mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION);
863 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
864 mModelRoot.SetProperty(Dali::Actor::Property::KEYBOARD_FOCUSABLE, mModelChildrenFocusable);
865 mModelRoot.SetProperty(Dali::DevelActor::Property::KEYBOARD_FOCUSABLE_CHILDREN, mModelChildrenFocusable);
866 Self().Add(mModelRoot);
869 void Model::ScaleModel(bool useCurrentSize)
877 Vector3 size = (useCurrentSize) ? Self().GetCurrentProperty<Vector3>(Dali::Actor::Property::SIZE) : Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
878 if(size.x > 0.0f && size.y > 0.0f)
881 scale = std::min(size.x / mNaturalSize.x, scale);
882 scale = std::min(size.y / mNaturalSize.y, scale);
884 // Models in glTF and dli are defined as right hand coordinate system.
885 // DALi uses left hand coordinate system. Scaling negative is for change winding order.
886 mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION * scale);
889 void Model::FitModelPosition()
895 // Loaded model pivot is not the model center.
896 mModelRoot.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
897 mModelRoot.SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3::ONE - mModelPivot);
900 void Model::UpdateImageBasedLightTextureRecursively(Scene3D::ModelNode node, Dali::Texture diffuseTexture, Dali::Texture specularTexture, float iblScaleFactor, uint32_t specularMipmapLevels)
907 GetImplementation(node).SetImageBasedLightTexture(diffuseTexture, specularTexture, iblScaleFactor, specularMipmapLevels);
908 uint32_t childrenCount = node.GetChildCount();
909 for(uint32_t i = 0; i < childrenCount; ++i)
911 Scene3D::ModelNode childNode = Scene3D::ModelNode::DownCast(node.GetChildAt(i));
916 UpdateImageBasedLightTextureRecursively(childNode, diffuseTexture, specularTexture, iblScaleFactor, specularMipmapLevels);
920 void Model::UpdateImageBasedLightScaleFactorRecursively(Scene3D::ModelNode node, float iblScaleFactor)
927 GetImplementation(node).SetImageBasedLightScaleFactor(iblScaleFactor);
929 uint32_t childrenCount = node.GetChildCount();
930 for(uint32_t i = 0; i < childrenCount; ++i)
932 Scene3D::ModelNode childNode = Scene3D::ModelNode::DownCast(node.GetChildAt(i));
937 UpdateImageBasedLightScaleFactorRecursively(childNode, iblScaleFactor);
941 void Model::UpdateImageBasedLightTexture()
943 Dali::Texture currentDiffuseTexture = (mDiffuseTexture && mSpecularTexture) ? mDiffuseTexture : mSceneDiffuseTexture;
944 Dali::Texture currentSpecularTexture = (mDiffuseTexture && mSpecularTexture) ? mSpecularTexture : mSceneSpecularTexture;
945 float currentIblScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
946 uint32_t currentIblSpecularMipmapLevels = (mDiffuseTexture && mSpecularTexture) ? mSpecularMipmapLevels : mSceneSpecularMipmapLevels;
948 if(!currentDiffuseTexture || !currentSpecularTexture)
950 currentDiffuseTexture = mDefaultDiffuseTexture;
951 currentSpecularTexture = mDefaultSpecularTexture;
952 currentIblScaleFactor = Dali::Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
953 currentIblSpecularMipmapLevels = 1u;
956 UpdateImageBasedLightTextureRecursively(mModelRoot, currentDiffuseTexture, currentSpecularTexture, currentIblScaleFactor, currentIblSpecularMipmapLevels);
959 void Model::UpdateImageBasedLightScaleFactor()
961 if((!mDiffuseTexture || !mSpecularTexture) &&
962 (!mSceneDiffuseTexture || !mSceneSpecularTexture))
967 float currentIblScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
968 UpdateImageBasedLightScaleFactorRecursively(mModelRoot, currentIblScaleFactor);
971 void Model::ApplyCameraTransform(Dali::CameraActor camera) const
973 Vector3 selfPosition = Self().GetProperty<Vector3>(Actor::Property::POSITION);
974 Quaternion selfOrientation = Self().GetProperty<Quaternion>(Actor::Property::ORIENTATION);
975 Vector3 selfScale = Self().GetProperty<Vector3>(Actor::Property::SCALE);
977 Vector3 cameraPosition = camera.GetProperty<Vector3>(Actor::Property::POSITION);
978 Quaternion cameraOrientation = camera.GetProperty<Quaternion>(Actor::Property::ORIENTATION);
979 Vector3 cameraScale = camera.GetProperty<Vector3>(Actor::Property::SCALE);
981 // Models in glTF and dli are defined as right hand coordinate system.
982 // DALi uses left hand coordinate system. Scaling negative is for change winding order.
983 if(!Dali::Equals(Y_DIRECTION.Dot(Vector3::YAXIS), 1.0f))
985 // Reflect by XZ plane
986 cameraPosition.y = -cameraPosition.y;
987 Quaternion yDirectionQuaternion;
988 yDirectionQuaternion.mVector = Vector3::YAXIS;
989 // Reflect orientation
990 cameraOrientation = yDirectionQuaternion * cameraOrientation * yDirectionQuaternion;
993 Vector3 resultPosition;
994 Quaternion resultOrientation;
997 Matrix selfMatrix(false);
998 Matrix cameraMatrix(false);
999 Matrix resultMatrix(false);
1000 selfMatrix.SetTransformComponents(selfScale, selfOrientation, selfPosition);
1001 cameraMatrix.SetTransformComponents(cameraScale, cameraOrientation, cameraPosition);
1002 Matrix::Multiply(resultMatrix, cameraMatrix, selfMatrix);
1003 resultMatrix.GetTransformComponents(resultPosition, resultOrientation, resultScale);
1005 camera.SetProperty(Actor::Property::POSITION, resultPosition);
1006 camera.SetProperty(Actor::Property::ORIENTATION, resultOrientation);
1007 camera.SetProperty(Actor::Property::SCALE, resultScale);
1010 void Model::NotifyImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor, uint32_t specularMipmapLevels)
1012 if(mSceneDiffuseTexture != diffuseTexture || mSceneSpecularTexture != specularTexture)
1014 mSceneDiffuseTexture = diffuseTexture;
1015 mSceneSpecularTexture = specularTexture;
1016 mSceneIblScaleFactor = scaleFactor;
1017 mSceneSpecularMipmapLevels = specularMipmapLevels;
1018 // If Model IBL is not set, use SceneView's IBL.
1019 if(!mDiffuseTexture || !mSpecularTexture)
1021 UpdateImageBasedLightTexture();
1026 void Model::NotifyImageBasedLightScaleFactor(float scaleFactor)
1028 mSceneIblScaleFactor = scaleFactor;
1029 if(mSceneDiffuseTexture && mSceneSpecularTexture)
1031 UpdateImageBasedLightScaleFactor();
1035 void Model::OnModelLoadComplete()
1037 if(!mModelLoadTask->HasSucceeded())
1039 ResetResourceTasks();
1041 if(ModelCacheManager::Get() && !mModelUrl.empty())
1043 ModelCacheManager::Get().UnreferenceModelCache(mModelUrl);
1055 auto& resources = mModelLoadTask->GetResources();
1056 auto& scene = mModelLoadTask->GetScene();
1057 CreateAnimations(scene);
1058 ResetCameraParameters();
1059 if(!resources.mEnvironmentMaps.empty())
1061 mDefaultDiffuseTexture = resources.mEnvironmentMaps.front().second.mDiffuse;
1062 mDefaultSpecularTexture = resources.mEnvironmentMaps.front().second.mSpecular;
1065 UpdateImageBasedLightTexture();
1066 UpdateImageBasedLightScaleFactor();
1067 Self().SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3(mModelPivot.x, 1.0f - mModelPivot.y, mModelPivot.z));
1069 mModelResourceReady = true;
1070 NotifyResourceReady();
1071 ResetResourceTask(mModelLoadTask);
1074 void Model::OnIblDiffuseLoadComplete()
1076 mDiffuseTexture = mIblDiffuseLoadTask->GetLoadedTexture();
1077 ResetResourceTask(mIblDiffuseLoadTask);
1078 mIblDiffuseResourceReady = true;
1079 if(mIblDiffuseResourceReady && mIblSpecularResourceReady)
1081 OnIblLoadComplete();
1085 void Model::OnIblSpecularLoadComplete()
1087 mSpecularTexture = mIblSpecularLoadTask->GetLoadedTexture();
1088 mSpecularMipmapLevels = mIblSpecularLoadTask->GetMipmapLevels();
1089 ResetResourceTask(mIblSpecularLoadTask);
1090 mIblSpecularResourceReady = true;
1091 if(mIblDiffuseResourceReady && mIblSpecularResourceReady)
1093 OnIblLoadComplete();
1097 void Model::OnIblLoadComplete()
1099 UpdateImageBasedLightTexture();
1100 NotifyResourceReady();
1103 void Model::OnSizeNotification(Dali::PropertyNotification& source)
1108 void Model::ResetResourceTasks()
1110 if(!Dali::Adaptor::IsAvailable())
1114 ResetResourceTask(mModelLoadTask);
1115 ResetResourceTask(mIblDiffuseLoadTask);
1116 ResetResourceTask(mIblSpecularLoadTask);
1119 void Model::ResetResourceTask(IntrusivePtr<AsyncTask> asyncTask)
1125 Dali::AsyncTaskManager::Get().RemoveTask(asyncTask);
1129 void Model::NotifyResourceReady()
1131 if(!IsResourceReady())
1135 Control::SetResourceReady();
1138 void Model::CreateModel()
1140 BoundingVolume AABB;
1141 auto& resources = mModelLoadTask->GetResources();
1142 auto& scene = mModelLoadTask->GetScene();
1143 auto& resourceChoices = mModelLoadTask->GetResourceChoices();
1144 Dali::Scene3D::Loader::Transforms xforms{Dali::Scene3D::Loader::MatrixStack{}, Dali::Scene3D::Loader::ViewProjection{}};
1146 Dali::Scene3D::Loader::NodeDefinition::CreateParams nodeParams{resources, xforms, mShaderManager, {}, {}, {}};
1148 // Generate Dali handles from resource bundle. Note that we generate all scene's resouce immediatly.
1149 resources.GenerateResources();
1150 for(auto iRoot : scene.GetRoots())
1152 if(auto modelNode = scene.CreateNodes(iRoot, resourceChoices, nodeParams))
1154 scene.ConfigureSkinningShaders(resources, modelNode, std::move(nodeParams.mSkinnables));
1155 ConfigureBlendShapeShaders(resources, scene, modelNode, std::move(nodeParams.mBlendshapeRequests));
1157 scene.ApplyConstraints(modelNode, std::move(nodeParams.mConstrainables));
1159 mModelRoot.Add(modelNode);
1162 AddModelTreeToAABB(AABB, scene, resourceChoices, iRoot, nodeParams, Matrix::IDENTITY);
1165 UpdateBlendShapeNodeMap();
1167 mNaturalSize = AABB.CalculateSize();
1168 mModelPivot = AABB.CalculatePivot();
1169 mModelRoot.SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
1170 Vector3 controlSize = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
1171 if(Dali::EqualsZero(controlSize.x) || Dali::EqualsZero(controlSize.y))
1173 Self().SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
1179 void Model::CreateAnimations(Dali::Scene3D::Loader::SceneDefinition& scene)
1181 mAnimations.clear();
1182 if(!mModelLoadTask->GetAnimations().empty())
1184 auto getActor = [&](const Scene3D::Loader::AnimatedProperty& property) {
1185 if(property.mNodeIndex == Scene3D::Loader::INVALID_INDEX)
1187 return mModelRoot.FindChildByName(property.mNodeName);
1189 auto* node = scene.GetNode(property.mNodeIndex);
1192 return Dali::Actor();
1194 return mModelRoot.FindChildById(node->mNodeId);
1197 for(auto&& animation : mModelLoadTask->GetAnimations())
1199 Dali::Animation anim = animation.ReAnimate(getActor);
1200 mAnimations.push_back({animation.GetName(), anim});
1205 void Model::ResetCameraParameters()
1207 mCameraParameters.clear();
1208 if(!mModelLoadTask->GetCameras().empty())
1210 // Copy camera parameters.
1211 std::copy(mModelLoadTask->GetCameras().begin(), mModelLoadTask->GetCameras().end(), std::back_inserter(mCameraParameters));
1215 void Model::UpdateBlendShapeNodeMap()
1217 // Remove privous node map
1218 mBlendShapeModelNodeMap.clear();
1220 UpdateBlendShapeNodeMapRecursively(mBlendShapeModelNodeMap, mModelRoot);
1223 } // namespace Internal
1224 } // namespace Scene3D