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-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/debug.h>
27 #include <dali/public-api/object/type-registry-helper.h>
28 #include <dali/public-api/object/type-registry.h>
32 #include <dali-scene3d/internal/controls/scene-view/scene-view-impl.h>
33 #include <dali-scene3d/public-api/controls/model/model.h>
34 #include <dali-scene3d/public-api/loader/animation-definition.h>
35 #include <dali-scene3d/public-api/loader/camera-parameters.h>
36 #include <dali-scene3d/public-api/loader/cube-map-loader.h>
37 #include <dali-scene3d/public-api/loader/dli-loader.h>
38 #include <dali-scene3d/public-api/loader/gltf2-loader.h>
39 #include <dali-scene3d/public-api/loader/light-parameters.h>
40 #include <dali-scene3d/public-api/loader/load-result.h>
41 #include <dali-scene3d/public-api/loader/node-definition.h>
42 #include <dali-scene3d/public-api/loader/scene-definition.h>
43 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
57 return Scene3D::Model::New(std::string());
60 // Setup properties, signals and actions using the type-registry.
61 DALI_TYPE_REGISTRATION_BEGIN(Scene3D::Model, Toolkit::Control, Create);
62 DALI_TYPE_REGISTRATION_END()
64 static constexpr uint32_t OFFSET_FOR_DIFFUSE_CUBE_TEXTURE = 2u;
65 static constexpr uint32_t OFFSET_FOR_SPECULAR_CUBE_TEXTURE = 1u;
67 static constexpr Vector3 Y_DIRECTION(1.0f, -1.0f, 1.0f);
69 static constexpr bool DEFAULT_MODEL_CHILDREN_SENSITIVE = false;
70 static constexpr bool DEFAULT_MODEL_CHILDREN_FOCUSABLE = false;
72 static constexpr std::string_view KTX_EXTENSION = ".ktx";
73 static constexpr std::string_view OBJ_EXTENSION = ".obj";
74 static constexpr std::string_view GLTF_EXTENSION = ".gltf";
75 static constexpr std::string_view DLI_EXTENSION = ".dli";
81 pointMin = Vector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
82 pointMax = Vector3(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
85 void ConsiderNewPointInVolume(const Vector3& position)
87 pointMin.x = std::min(position.x, pointMin.x);
88 pointMin.y = std::min(position.y, pointMin.y);
89 pointMin.z = std::min(position.z, pointMin.z);
91 pointMax.x = std::max(position.x, pointMax.x);
92 pointMax.y = std::max(position.y, pointMax.y);
93 pointMax.z = std::max(position.z, pointMax.z);
96 Vector3 CalculateSize()
98 return pointMax - pointMin;
101 Vector3 CalculatePivot()
103 Vector3 pivot = pointMin / (pointMin - pointMax);
104 for(uint32_t i = 0; i < 3; ++i)
106 // To avoid divid by zero
107 if(pointMin[i] == pointMax[i])
119 void ConfigureBlendShapeShaders(
120 Dali::Scene3D::Loader::ResourceBundle& resources, const Dali::Scene3D::Loader::SceneDefinition& scene, Actor root, std::vector<Dali::Scene3D::Loader::BlendshapeShaderConfigurationRequest>&& requests)
122 std::vector<std::string> errors;
123 auto onError = [&errors](const std::string& msg) { errors.push_back(msg); };
124 if(!scene.ConfigureBlendshapeShaders(resources, root, std::move(requests), onError))
126 Dali::Scene3D::Loader::ExceptionFlinger flinger(ASSERT_LOCATION);
127 for(auto& msg : errors)
129 flinger << msg << '\n';
134 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)
136 static constexpr uint32_t BOX_POINT_COUNT = 8;
137 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}};
140 const Dali::Scene3D::Loader::NodeDefinition* node = scene.GetNode(iNode);
141 Matrix localMatrix = node->GetLocalSpace();
142 Matrix::Multiply(nodeMatrix, localMatrix, parentMatrix);
145 if(node->GetExtents(nodeParams.mResources, volume[0], volume[1]))
147 for(uint32_t i = 0; i < BOX_POINT_COUNT; ++i)
149 Vector4 position = Vector4(volume[BBIndex[i][0]].x, volume[BBIndex[i][1]].y, volume[BBIndex[i][2]].z, 1.0f);
150 Vector4 objectPosition = nodeMatrix * position;
151 objectPosition /= objectPosition.w;
153 AABB.ConsiderNewPointInVolume(Vector3(objectPosition));
157 if(node->mCustomization)
159 if(!node->mChildren.empty())
161 auto choice = choices.Get(node->mCustomization->mTag);
162 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));
164 AddModelTreeToAABB(AABB, scene, choices, node->mChildren[i], nodeParams, nodeMatrix);
169 for(auto i : node->mChildren)
171 AddModelTreeToAABB(AABB, scene, choices, i, nodeParams, nodeMatrix);
176 } // anonymous namespace
178 Model::Model(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
179 : Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
181 mResourceDirectoryUrl(resourceDirectoryUrl),
183 mNaturalSize(Vector3::ZERO),
184 mModelPivot(AnchorPoint::CENTER),
185 mSceneIblScaleFactor(1.0f),
186 mIblScaleFactor(1.0f),
187 mModelChildrenSensitive(DEFAULT_MODEL_CHILDREN_SENSITIVE),
188 mModelChildrenFocusable(DEFAULT_MODEL_CHILDREN_FOCUSABLE),
189 mModelResourceReady(false),
190 mIBLResourceReady(true)
198 Dali::Scene3D::Model Model::New(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
200 Model* impl = new Model(modelUrl, resourceDirectoryUrl);
202 Dali::Scene3D::Model handle = Dali::Scene3D::Model(*impl);
204 // Second-phase init of the implementation
205 // This can only be done after the CustomActor connection has been made...
211 const Actor Model::GetModelRoot() const
216 void Model::SetChildrenSensitive(bool enable)
218 if(mModelChildrenSensitive != enable)
220 mModelChildrenSensitive = enable;
223 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
228 bool Model::GetChildrenSensitive() const
230 return mModelChildrenSensitive;
233 void Model::SetChildrenFocusable(bool enable)
235 if(mModelChildrenFocusable != enable)
237 mModelChildrenFocusable = enable;
240 mModelRoot.SetProperty(Dali::Actor::Property::KEYBOARD_FOCUSABLE, mModelChildrenFocusable);
241 mModelRoot.SetProperty(Dali::DevelActor::Property::KEYBOARD_FOCUSABLE_CHILDREN, mModelChildrenFocusable);
246 bool Model::GetChildrenFocusable() const
248 return mModelChildrenFocusable;
251 void Model::SetImageBasedLightSource(const std::string& diffuseUrl, const std::string& specularUrl, float scaleFactor)
253 mIBLResourceReady = false;
254 Texture diffuseTexture = (!diffuseUrl.empty()) ? Dali::Scene3D::Loader::LoadCubeMap(diffuseUrl) : Texture();
255 Texture specularTexture = (!specularUrl.empty()) ? Dali::Scene3D::Loader::LoadCubeMap(specularUrl) : Texture();
256 SetImageBasedLightTexture(diffuseTexture, specularTexture, scaleFactor);
257 mIBLResourceReady = true;
259 // If Model resource is already ready, then set resource ready.
260 // If Model resource is still not ready, wait for model resource ready.
261 if(IsResourceReady())
263 SetResourceReady(false);
267 void Model::SetImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
269 // If input texture is wrong, Model is rendered with SceneView's IBL.
270 if(mDiffuseTexture != diffuseTexture || mSpecularTexture != specularTexture)
272 mDiffuseTexture = diffuseTexture;
273 mSpecularTexture = specularTexture;
274 mIblScaleFactor = scaleFactor;
275 UpdateImageBasedLightTexture();
279 void Model::SetImageBasedLightScaleFactor(float scaleFactor)
281 mIblScaleFactor = scaleFactor;
282 if(mDiffuseTexture && mSpecularTexture)
284 UpdateImageBasedLightScaleFactor();
288 float Model::GetImageBasedLightScaleFactor() const
290 return mIblScaleFactor;
293 uint32_t Model::GetAnimationCount() const
295 return mAnimations.size();
298 Dali::Animation Model::GetAnimation(uint32_t index) const
300 Dali::Animation animation;
301 if(mAnimations.size() > index)
303 animation = mAnimations[index].second;
308 Dali::Animation Model::GetAnimation(const std::string& name) const
310 Dali::Animation animation;
313 for(auto&& animationData : mAnimations)
315 if(animationData.first == name)
317 animation = animationData.second;
325 ///////////////////////////////////////////////////////////
330 void Model::OnInitialize()
332 // Make ParentOrigin as Center.
333 Self().SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
336 void Model::OnSceneConnection(int depth)
343 Actor parent = Self().GetParent();
346 Scene3D::SceneView sceneView = Scene3D::SceneView::DownCast(parent);
349 GetImpl(sceneView).RegisterSceneItem(this);
350 mParentSceneView = sceneView;
353 parent = parent.GetParent();
356 Control::OnSceneConnection(depth);
359 void Model::OnSceneDisconnection()
361 Scene3D::SceneView sceneView = mParentSceneView.GetHandle();
364 GetImpl(sceneView).UnregisterSceneItem(this);
365 mParentSceneView.Reset();
367 Control::OnSceneDisconnection();
370 Vector3 Model::GetNaturalSize()
380 float Model::GetHeightForWidth(float width)
383 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
384 return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
387 float Model::GetWidthForHeight(float height)
390 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
391 return Control::GetWidthForHeight(height) + padding.start + padding.end;
394 void Model::OnRelayout(const Vector2& size, RelayoutContainer& container)
396 Control::OnRelayout(size, container);
400 bool Model::IsResourceReady() const
402 return mModelResourceReady && mIBLResourceReady;
405 void Model::LoadModel()
407 std::filesystem::path modelUrl(mModelUrl);
408 if(mResourceDirectoryUrl.empty())
410 mResourceDirectoryUrl = std::string(modelUrl.parent_path()) + "/";
412 std::string extension = modelUrl.extension();
413 std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
415 Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type) {
416 return mResourceDirectoryUrl;
419 Dali::Scene3D::Loader::ResourceBundle resources;
420 Dali::Scene3D::Loader::SceneDefinition scene;
421 std::vector<Dali::Scene3D::Loader::AnimationGroupDefinition> animGroups;
422 std::vector<Dali::Scene3D::Loader::CameraParameters> cameraParameters;
423 std::vector<Dali::Scene3D::Loader::LightParameters> lights;
425 std::vector<Dali::Scene3D::Loader::AnimationDefinition> animations;
428 Dali::Scene3D::Loader::SceneMetadata metaData;
430 std::filesystem::path metaDataUrl = modelUrl;
431 metaDataUrl.replace_extension("metadata");
433 Dali::Scene3D::Loader::LoadSceneMetadata(metaDataUrl.c_str(), metaData);
435 Dali::Scene3D::Loader::LoadResult output{resources, scene, metaData, animations, animGroups, cameraParameters, lights};
437 if(extension == DLI_EXTENSION)
439 Dali::Scene3D::Loader::DliLoader loader;
440 Dali::Scene3D::Loader::DliLoader::InputParams input{
441 pathProvider(Dali::Scene3D::Loader::ResourceType::Mesh),
447 Dali::Scene3D::Loader::DliLoader::LoadParams loadParams{input, output};
448 if(!loader.LoadScene(mModelUrl, loadParams))
450 Dali::Scene3D::Loader::ExceptionFlinger(ASSERT_LOCATION) << "Failed to load scene from '" << mModelUrl << "': " << loader.GetParseError();
453 else if(extension == GLTF_EXTENSION)
455 Dali::Scene3D::Loader::ShaderDefinitionFactory sdf;
456 sdf.SetResources(resources);
457 Dali::Scene3D::Loader::LoadGltfScene(mModelUrl, sdf, output);
459 resources.mEnvironmentMaps.push_back({});
463 DALI_LOG_ERROR("Unsupported model type.\n");
466 Dali::Scene3D::Loader::Transforms xforms{Dali::Scene3D::Loader::MatrixStack{}, Dali::Scene3D::Loader::ViewProjection{}};
467 Dali::Scene3D::Loader::NodeDefinition::CreateParams nodeParams{resources, xforms, {}, {}, {}};
468 Dali::Scene3D::Loader::Customization::Choices choices;
470 mModelRoot = Actor::New();
473 for(auto iRoot : scene.GetRoots())
475 auto resourceRefs = resources.CreateRefCounter();
476 scene.CountResourceRefs(iRoot, choices, resourceRefs);
477 resources.CountEnvironmentReferences(resourceRefs);
479 resources.LoadResources(resourceRefs, pathProvider);
481 // glTF Mesh is defined in right hand coordinate system, with positive Y for Up direction.
482 // Because DALi uses left hand system, Y direciton will be flipped for environment map sampling.
483 for(auto&& env : resources.mEnvironmentMaps)
485 env.first.mYDirection = Y_DIRECTION;
488 if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
490 scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
491 scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
492 ConfigureBlendShapeShaders(resources, scene, actor, std::move(nodeParams.mBlendshapeRequests));
494 scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
496 mModelRoot.Add(actor);
499 AddModelTreeToAABB(AABB, scene, choices, iRoot, nodeParams, Matrix::IDENTITY);
502 if(!resources.mEnvironmentMaps.empty())
504 mDefaultDiffuseTexture = resources.mEnvironmentMaps.front().second.mDiffuse;
505 mDefaultSpecularTexture = resources.mEnvironmentMaps.front().second.mSpecular;
508 if(!animations.empty())
510 auto getActor = [&](const Scene3D::Loader::AnimatedProperty& property) {
511 return mModelRoot.FindChildById(scene.GetNode(property.mNodeIndex)->mNodeId);
515 for(auto&& animation : animations)
517 Dali::Animation anim = animation.ReAnimate(getActor);
519 mAnimations.push_back({animation.mName, anim});
523 mRenderableActors.clear();
524 CollectRenderableActor(mModelRoot);
525 UpdateImageBasedLightTexture();
526 UpdateImageBasedLightScaleFactor();
528 mNaturalSize = AABB.CalculateSize();
529 mModelPivot = AABB.CalculatePivot();
530 mModelRoot.SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
531 Vector3 controlSize = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
532 if(controlSize.x == 0.0f || controlSize.y == 0.0f)
534 Self().SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
540 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
541 mModelRoot.SetProperty(Dali::Actor::Property::KEYBOARD_FOCUSABLE, mModelChildrenFocusable);
542 mModelRoot.SetProperty(Dali::DevelActor::Property::KEYBOARD_FOCUSABLE_CHILDREN, mModelChildrenFocusable);
544 Self().Add(mModelRoot);
546 Self().SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3(mModelPivot.x, 1.0f - mModelPivot.y, mModelPivot.z));
548 mModelResourceReady = true;
550 Control::SetResourceReady(false);
553 void Model::ScaleModel()
558 Vector3 size = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
559 if(size.x > 0.0f && size.y > 0.0f)
562 scale = std::min(size.x / mNaturalSize.x, scale);
563 scale = std::min(size.y / mNaturalSize.y, scale);
565 // Models in glTF and dli are defined as right hand coordinate system.
566 // DALi uses left hand coordinate system. Scaling negative is for change winding order.
567 mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION * scale);
571 void Model::FitModelPosition()
575 // Loaded model pivot is not the model center.
576 mModelRoot.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
577 mModelRoot.SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3::ONE - mModelPivot);
581 void Model::CollectRenderableActor(Actor actor)
583 uint32_t rendererCount = actor.GetRendererCount();
586 mRenderableActors.push_back(actor);
589 uint32_t childrenCount = actor.GetChildCount();
590 for(uint32_t i = 0; i < childrenCount; ++i)
592 CollectRenderableActor(actor.GetChildAt(i));
596 void Model::UpdateImageBasedLightTexture()
598 Dali::Texture currentDiffuseTexture = (mDiffuseTexture) ? mDiffuseTexture : mSceneDiffuseTexture;
599 Dali::Texture currentSpecularTexture = (mSpecularTexture) ? mSpecularTexture : mSceneSpecularTexture;
600 float currentIBLScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
601 if(!currentDiffuseTexture || !currentSpecularTexture)
603 currentDiffuseTexture = mDefaultDiffuseTexture;
604 currentSpecularTexture = mDefaultSpecularTexture;
605 currentIBLScaleFactor = Dali::Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
608 for(auto&& actor : mRenderableActors)
610 Actor renderableActor = actor.GetHandle();
613 uint32_t rendererCount = renderableActor.GetRendererCount();
614 for(uint32_t i = 0; i < rendererCount; ++i)
616 Dali::Renderer renderer = renderableActor.GetRendererAt(i);
619 Dali::TextureSet textures = renderer.GetTextures();
622 uint32_t textureCount = textures.GetTextureCount();
623 // EnvMap requires at least 2 texture, diffuse and specular
624 if(textureCount > 2u)
626 textures.SetTexture(textureCount - OFFSET_FOR_DIFFUSE_CUBE_TEXTURE, currentDiffuseTexture);
627 textures.SetTexture(textureCount - OFFSET_FOR_SPECULAR_CUBE_TEXTURE, currentSpecularTexture);
632 renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), currentIBLScaleFactor);
637 void Model::UpdateImageBasedLightScaleFactor()
639 if((!mDiffuseTexture || !mSpecularTexture) &&
640 (!mSceneDiffuseTexture || !mSceneSpecularTexture))
645 float currentIBLScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
646 for(auto&& actor : mRenderableActors)
648 Actor renderableActor = actor.GetHandle();
651 renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), currentIBLScaleFactor);
656 void Model::NotifyImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
658 if(mSceneDiffuseTexture != diffuseTexture || mSceneSpecularTexture != specularTexture)
660 mSceneDiffuseTexture = diffuseTexture;
661 mSceneSpecularTexture = specularTexture;
662 mSceneIblScaleFactor = scaleFactor;
663 UpdateImageBasedLightTexture();
667 void Model::NotifyImageBasedLightScaleFactor(float scaleFactor)
669 mSceneIblScaleFactor = scaleFactor;
670 if(mSceneDiffuseTexture && mSceneSpecularTexture)
672 UpdateImageBasedLightScaleFactor();
676 } // namespace Internal
677 } // namespace Scene3D