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/integration-api/debug.h>
26 #include <dali/public-api/object/type-registry-helper.h>
27 #include <dali/public-api/object/type-registry.h>
31 #include <dali-scene3d/public-api/controls/model/model.h>
32 #include <dali-scene3d/internal/controls/scene-view/scene-view-impl.h>
33 #include <dali-scene3d/public-api/loader/animation-definition.h>
34 #include <dali-scene3d/public-api/loader/camera-parameters.h>
35 #include <dali-scene3d/public-api/loader/cube-map-loader.h>
36 #include <dali-scene3d/public-api/loader/dli-loader.h>
37 #include <dali-scene3d/public-api/loader/gltf2-loader.h>
38 #include <dali-scene3d/public-api/loader/light-parameters.h>
39 #include <dali-scene3d/public-api/loader/load-result.h>
40 #include <dali-scene3d/public-api/loader/node-definition.h>
41 #include <dali-scene3d/public-api/loader/scene-definition.h>
42 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
56 return Scene3D::Model::New(std::string());
59 // Setup properties, signals and actions using the type-registry.
60 DALI_TYPE_REGISTRATION_BEGIN(Scene3D::Model, Toolkit::Control, Create);
61 DALI_TYPE_REGISTRATION_END()
63 static constexpr uint32_t OFFSET_FOR_DIFFUSE_CUBE_TEXTURE = 2u;
64 static constexpr uint32_t OFFSET_FOR_SPECULAR_CUBE_TEXTURE = 1u;
66 static constexpr Vector3 Y_DIRECTION(1.0f, -1.0f, 1.0f);
68 static constexpr std::string_view KTX_EXTENSION = ".ktx";
69 static constexpr std::string_view OBJ_EXTENSION = ".obj";
70 static constexpr std::string_view GLTF_EXTENSION = ".gltf";
71 static constexpr std::string_view DLI_EXTENSION = ".dli";
77 pointMin = Vector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
78 pointMax = Vector3(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
81 void ConsiderNewPointInVolume(const Vector3& position)
83 pointMin.x = std::min(position.x, pointMin.x);
84 pointMin.y = std::min(position.y, pointMin.y);
85 pointMin.z = std::min(position.z, pointMin.z);
87 pointMax.x = std::max(position.x, pointMax.x);
88 pointMax.y = std::max(position.y, pointMax.y);
89 pointMax.z = std::max(position.z, pointMax.z);
92 Vector3 CalculateSize()
94 return pointMax - pointMin;
97 Vector3 CalculatePivot()
99 Vector3 pivot = pointMin / (pointMin - pointMax);
100 for(uint32_t i = 0; i < 3; ++i)
102 // To avoid divid by zero
103 if(pointMin[i] == pointMax[i])
115 void ConfigureBlendShapeShaders(
116 Dali::Scene3D::Loader::ResourceBundle& resources, const Dali::Scene3D::Loader::SceneDefinition& scene, Actor root, std::vector<Dali::Scene3D::Loader::BlendshapeShaderConfigurationRequest>&& requests)
118 std::vector<std::string> errors;
119 auto onError = [&errors](const std::string& msg) { errors.push_back(msg); };
120 if(!scene.ConfigureBlendshapeShaders(resources, root, std::move(requests), onError))
122 Dali::Scene3D::Loader::ExceptionFlinger flinger(ASSERT_LOCATION);
123 for(auto& msg : errors)
125 flinger << msg << '\n';
130 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)
132 static constexpr uint32_t BOX_POINT_COUNT = 8;
133 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}};
136 const Dali::Scene3D::Loader::NodeDefinition* node = scene.GetNode(iNode);
137 Matrix localMatrix = node->GetLocalSpace();
138 Matrix::Multiply(nodeMatrix, localMatrix, parentMatrix);
141 if(node->GetExtents(nodeParams.mResources, volume[0], volume[1]))
143 for(uint32_t i = 0; i < BOX_POINT_COUNT; ++i)
145 Vector4 position = Vector4(volume[BBIndex[i][0]].x, volume[BBIndex[i][1]].y, volume[BBIndex[i][2]].z, 1.0f);
146 Vector4 objectPosition = nodeMatrix * position;
147 objectPosition /= objectPosition.w;
149 AABB.ConsiderNewPointInVolume(Vector3(objectPosition));
153 if(node->mCustomization)
155 if(!node->mChildren.empty())
157 auto choice = choices.Get(node->mCustomization->mTag);
158 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));
160 AddModelTreeToAABB(AABB, scene, choices, node->mChildren[i], nodeParams, nodeMatrix);
165 for(auto i : node->mChildren)
167 AddModelTreeToAABB(AABB, scene, choices, i, nodeParams, nodeMatrix);
172 } // anonymous namespace
174 Model::Model(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
175 : Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
177 mResourceDirectoryUrl(resourceDirectoryUrl),
179 mNaturalSize(Vector3::ZERO),
180 mModelPivot(AnchorPoint::CENTER),
181 mIblScaleFactor(1.0f),
182 mModelResourceReady(false),
183 mIBLResourceReady(true)
191 Dali::Scene3D::Model Model::New(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
193 Model* impl = new Model(modelUrl, resourceDirectoryUrl);
195 Dali::Scene3D::Model handle = Dali::Scene3D::Model(*impl);
197 // Second-phase init of the implementation
198 // This can only be done after the CustomActor connection has been made...
204 const Actor Model::GetModelRoot() const
209 void Model::SetImageBasedLightSource(const std::string& diffuseUrl, const std::string& specularUrl, float scaleFactor)
211 mIBLResourceReady = false;
212 Texture diffuseTexture = Dali::Scene3D::Loader::LoadCubeMap(diffuseUrl);
213 Texture specularTexture = Dali::Scene3D::Loader::LoadCubeMap(specularUrl);
214 SetImageBasedLightTexture(diffuseTexture, specularTexture, scaleFactor);
215 mIBLResourceReady = true;
217 // If Model resource is already ready, then set resource ready.
218 // If Model resource is still not ready, wait for model resource ready.
219 if(IsResourceReady())
221 SetResourceReady(false);
225 void Model::SetImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
227 if(diffuseTexture && specularTexture)
229 if(mDiffuseTexture != diffuseTexture || mSpecularTexture != specularTexture)
231 mDiffuseTexture = diffuseTexture;
232 mSpecularTexture = specularTexture;
233 UpdateImageBasedLightTexture();
235 if(mIblScaleFactor != scaleFactor)
237 mIblScaleFactor = scaleFactor;
238 UpdateImageBasedLightScaleFactor();
244 void Model::SetImageBasedLightScaleFactor(float scaleFactor)
246 mIblScaleFactor = scaleFactor;
247 if(mDiffuseTexture && mSpecularTexture)
249 UpdateImageBasedLightScaleFactor();
253 float Model::GetImageBasedLightScaleFactor() const
255 return mIblScaleFactor;
258 uint32_t Model::GetAnimationCount() const
260 return mAnimations.size();
263 Dali::Animation Model::GetAnimation(uint32_t index) const
265 Dali::Animation animation;
266 if(mAnimations.size() > index)
268 animation = mAnimations[index].second;
273 Dali::Animation Model::GetAnimation(const std::string& name) const
275 Dali::Animation animation;
278 for(auto&& animationData : mAnimations)
280 if(animationData.first == name)
282 animation = animationData.second;
290 ///////////////////////////////////////////////////////////
295 void Model::OnSceneConnection(int depth)
302 Actor parent = Self().GetParent();
305 Scene3D::SceneView sceneView = Scene3D::SceneView::DownCast(parent);
308 GetImpl(sceneView).RegisterModel(Scene3D::Model::DownCast(Self()));
309 mParentSceneView = sceneView;
312 parent = parent.GetParent();
315 Control::OnSceneConnection(depth);
318 void Model::OnSceneDisconnection()
320 Scene3D::SceneView sceneView = mParentSceneView.GetHandle();
323 GetImpl(sceneView).UnregisterModel(Scene3D::Model::DownCast(Self()));
324 mParentSceneView.Reset();
326 Control::OnSceneDisconnection();
329 Vector3 Model::GetNaturalSize()
339 float Model::GetHeightForWidth(float width)
342 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
343 return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
346 float Model::GetWidthForHeight(float height)
349 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
350 return Control::GetWidthForHeight(height) + padding.start + padding.end;
353 void Model::OnRelayout(const Vector2& size, RelayoutContainer& container)
355 Control::OnRelayout(size, container);
359 bool Model::IsResourceReady() const
361 return mModelResourceReady && mIBLResourceReady;
364 void Model::LoadModel()
366 std::filesystem::path modelUrl(mModelUrl);
367 if(mResourceDirectoryUrl.empty())
369 mResourceDirectoryUrl = std::string(modelUrl.parent_path()) + "/";
371 std::string extension = modelUrl.extension();
372 std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
374 Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type) {
375 return mResourceDirectoryUrl;
378 Dali::Scene3D::Loader::ResourceBundle resources;
379 Dali::Scene3D::Loader::SceneDefinition scene;
380 std::vector<Dali::Scene3D::Loader::AnimationGroupDefinition> animGroups;
381 std::vector<Dali::Scene3D::Loader::CameraParameters> cameraParameters;
382 std::vector<Dali::Scene3D::Loader::LightParameters> lights;
384 std::vector<Dali::Scene3D::Loader::AnimationDefinition> animations;
387 Dali::Scene3D::Loader::LoadResult output{resources, scene, animations, animGroups, cameraParameters, lights};
389 if(extension == DLI_EXTENSION)
391 Dali::Scene3D::Loader::DliLoader loader;
392 Dali::Scene3D::Loader::DliLoader::InputParams input{
393 pathProvider(Dali::Scene3D::Loader::ResourceType::Mesh),
399 Dali::Scene3D::Loader::DliLoader::LoadParams loadParams{input, output};
400 if(!loader.LoadScene(mModelUrl, loadParams))
402 Dali::Scene3D::Loader::ExceptionFlinger(ASSERT_LOCATION) << "Failed to load scene from '" << mModelUrl << "': " << loader.GetParseError();
405 else if(extension == GLTF_EXTENSION)
407 Dali::Scene3D::Loader::ShaderDefinitionFactory sdf;
408 sdf.SetResources(resources);
409 Dali::Scene3D::Loader::LoadGltfScene(mModelUrl, sdf, output);
411 resources.mEnvironmentMaps.push_back({});
415 DALI_LOG_ERROR("Unsupported model type.\n");
418 Dali::Scene3D::Loader::Transforms xforms{Dali::Scene3D::Loader::MatrixStack{}, Dali::Scene3D::Loader::ViewProjection{}};
419 Dali::Scene3D::Loader::NodeDefinition::CreateParams nodeParams{resources, xforms, {}, {}, {}};
420 Dali::Scene3D::Loader::Customization::Choices choices;
422 mModelRoot = Actor::New();
425 for(auto iRoot : scene.GetRoots())
427 auto resourceRefs = resources.CreateRefCounter();
428 scene.CountResourceRefs(iRoot, choices, resourceRefs);
429 resources.CountEnvironmentReferences(resourceRefs);
431 resources.LoadResources(resourceRefs, pathProvider);
433 // glTF Mesh is defined in right hand coordinate system, with positive Y for Up direction.
434 // Because DALi uses left hand system, Y direciton will be flipped for environment map sampling.
435 for(auto&& env : resources.mEnvironmentMaps)
437 env.first.mYDirection = Y_DIRECTION;
440 if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
442 scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
443 scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
444 ConfigureBlendShapeShaders(resources, scene, actor, std::move(nodeParams.mBlendshapeRequests));
446 scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
448 mModelRoot.Add(actor);
451 AddModelTreeToAABB(AABB, scene, choices, iRoot, nodeParams, Matrix::IDENTITY);
454 if(!animations.empty())
456 auto getActor = [&](const std::string& name) {
457 return mModelRoot.FindChildByName(name);
461 for(auto&& animation : animations)
463 Dali::Animation anim = animation.ReAnimate(getActor);
465 mAnimations.push_back({animation.mName, anim});
469 mRenderableActors.clear();
470 CollectRenderableActor(mModelRoot);
471 UpdateImageBasedLightTexture();
472 UpdateImageBasedLightScaleFactor();
474 mNaturalSize = AABB.CalculateSize();
475 mModelPivot = AABB.CalculatePivot();
476 mModelRoot.SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
477 Vector3 controlSize = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
478 if(controlSize.x == 0.0f || controlSize.y == 0.0f)
480 Self().SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
486 Self().Add(mModelRoot);
488 Self().SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
489 Self().SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3(mModelPivot.x, 1.0f - mModelPivot.y, mModelPivot.z));
491 mModelResourceReady = true;
493 Control::SetResourceReady(false);
496 void Model::ScaleModel()
501 Vector3 size = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
502 if(size.x > 0.0f && size.y > 0.0f)
505 scale = std::min(size.x / mNaturalSize.x, scale);
506 scale = std::min(size.y / mNaturalSize.y, scale);
508 // Models in glTF and dli are defined as right hand coordinate system.
509 // DALi uses left hand coordinate system. Scaling negative is for change winding order.
510 mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION * scale);
514 void Model::FitModelPosition()
518 // Loaded model pivot is not the model center.
519 mModelRoot.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
520 mModelRoot.SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3::ONE - mModelPivot);
524 void Model::CollectRenderableActor(Actor actor)
526 uint32_t rendererCount = actor.GetRendererCount();
529 mRenderableActors.push_back(actor);
532 uint32_t childrenCount = actor.GetChildCount();
533 for(uint32_t i = 0; i < childrenCount; ++i)
535 CollectRenderableActor(actor.GetChildAt(i));
539 void Model::UpdateImageBasedLightTexture()
541 if(!mDiffuseTexture || !mSpecularTexture)
546 for(auto&& actor : mRenderableActors)
548 Actor renderableActor = actor.GetHandle();
551 uint32_t rendererCount = renderableActor.GetRendererCount();
552 for(uint32_t i = 0; i < rendererCount; ++i)
554 Dali::Renderer renderer = renderableActor.GetRendererAt(i);
557 Dali::TextureSet textures = renderer.GetTextures();
560 uint32_t textureCount = textures.GetTextureCount();
561 // EnvMap requires at least 2 texture, diffuse and specular
562 if(textureCount > 2u)
564 textures.SetTexture(textureCount - OFFSET_FOR_DIFFUSE_CUBE_TEXTURE, mDiffuseTexture);
565 textures.SetTexture(textureCount - OFFSET_FOR_SPECULAR_CUBE_TEXTURE, mSpecularTexture);
574 void Model::UpdateImageBasedLightScaleFactor()
576 if(!mDiffuseTexture || !mSpecularTexture)
580 for(auto&& actor : mRenderableActors)
582 Actor renderableActor = actor.GetHandle();
585 renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), mIblScaleFactor);
590 } // namespace Internal
591 } // namespace Scene3D