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/loader/dli-loader-impl.h>
22 #include <dali-toolkit/devel-api/builder/json-parser.h>
23 #include <dali/devel-api/common/map-wrapper.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/public-api/object/property-array.h>
35 #include <dali-scene3d/internal/loader/json-util.h>
36 #include <dali-scene3d/public-api/loader/alpha-function-helper.h>
37 #include <dali-scene3d/public-api/loader/animation-definition.h>
38 #include <dali-scene3d/public-api/loader/blend-shape-details.h>
39 #include <dali-scene3d/public-api/loader/camera-parameters.h>
40 #include <dali-scene3d/public-api/loader/ktx-loader.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/parse-renderer-state.h>
44 #include <dali-scene3d/public-api/loader/scene-definition.h>
45 #include <dali-scene3d/public-api/loader/skinning-details.h>
46 #include <dali-scene3d/public-api/loader/utils.h>
48 #define DLI_0_1_COMPATIBILITY
52 using namespace Toolkit;
60 namespace rs = RendererState;
64 const std::string NODES = "nodes";
65 const std::string SCENES = "scenes";
66 const std::string NODE = "node";
67 const std::string URI = "uri";
68 const std::string URL = "url";
69 const std::string CUSTOMIZATION = "customization";
70 const std::string HINTS = "hints";
71 const std::string NAME("name");
72 const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
73 const std::string BLEND_SHAPES("blendShapes");
74 const std::string BLEND_SHAPE_VERSION_1_0("1.0");
75 const std::string BLEND_SHAPE_VERSION_2_0("2.0");
76 const std::string VERSION("version");
78 const char* const SHADOW_MAP_SIZE = "shadowMapSize";
79 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
80 const char* const PIXEL_UNITS = "px";
82 const char SLASH = '/';
84 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
86 float num[16u] = {.0f};
88 if(ReadVector(node->GetChild("matrix"), num, 16u))
91 mat.GetTransformComponents(translation, orientation, scale);
95 if(ReadVector(node->GetChild("angle"), num, 3u))
97 orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
100 if(ReadVector(node->GetChild("position"), num, 3u))
102 translation = Vector3(num);
107 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
109 return ReadBlob(node, buffer.mOffset, buffer.mLength);
112 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
114 return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
117 bool ReadColorCode(const TreeNode* node, Vector4& color, DliInputParameter::ConvertColorCode convertColorCode)
119 if(!node || !convertColorCode)
124 color = convertColorCode(node->GetString());
129 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliInputParameter::ConvertColorCode convertColorCode)
131 return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
132 ReadColor(node->GetChild("color"), color);
135 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
137 if(tnRendererState.GetType() == TreeNode::INTEGER)
139 return static_cast<RendererState::Type>(tnRendererState.GetInteger());
141 else if(tnRendererState.GetType() == TreeNode::STRING)
143 return RendererState::Parse(tnRendererState.GetString());
151 ///@brief Reads arc properties.
152 void ReadArcField(const TreeNode* eArc, ArcRenderable& arc)
154 ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
155 ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
156 ReadFloat(eArc->GetChild("radius"), arc.mRadius);
158 arc.mStartAngleDegrees = .0f;
159 ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
161 arc.mEndAngleDegrees = .0f;
162 ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
165 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
168 for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
172 return &((*it).second);
178 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
180 auto child = node->GetChild(childName);
183 ExceptionFlinger flinger(ASSERT_LOCATION);
184 flinger << "Failed to find child node '" << childName << "'";
185 if(auto nodeName = node->GetName())
187 flinger << " on '" << nodeName << "'";
194 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
196 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
198 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
199 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
202 switch(kv.second.GetType())
204 case TreeNode::ARRAY:
206 Property::Array array;
207 ParseProperties(kv.second, array);
208 map.Insert(kv.first, array);
212 case TreeNode::OBJECT:
214 Property::Map innerMap;
215 ParseProperties(kv.second, innerMap);
216 map.Insert(kv.first, innerMap);
220 case TreeNode::STRING:
222 map.Insert(kv.first, kv.second.GetString());
226 case TreeNode::INTEGER:
228 map.Insert(kv.first, kv.second.GetInteger());
232 case TreeNode::BOOLEAN:
234 map.Insert(kv.first, kv.second.GetBoolean());
238 case TreeNode::FLOAT:
240 map.Insert(kv.first, kv.second.GetFloat());
244 case TreeNode::IS_NULL:
252 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
254 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
255 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
258 switch(kv.second.GetType())
260 case TreeNode::ARRAY:
262 Property::Array innerArray;
263 ParseProperties(kv.second, innerArray);
264 array.PushBack(innerArray);
268 case TreeNode::OBJECT:
271 ParseProperties(kv.second, map);
276 case TreeNode::STRING:
278 array.PushBack(kv.second.GetString());
282 case TreeNode::INTEGER:
284 array.PushBack(kv.second.GetInteger());
288 case TreeNode::BOOLEAN:
290 array.PushBack(kv.second.GetBoolean());
294 case TreeNode::FLOAT:
296 array.PushBack(kv.second.GetFloat());
300 case TreeNode::IS_NULL:
310 struct DliLoaderImpl::Impl
312 StringCallback mOnError = DefaultErrorCallback;
313 Toolkit::JsonParser mParser;
315 void ParseScene(LoadParams& params);
318 std::map<Index, Matrix> mInverseBindMatrices;
321 * @brief Due to .dli nodes being processed in depth-first traversal with orphans being
322 * ignored, features that rely on node indices (which is more compact and closer to
323 * glTF) require a mapping from .dli node indices to those in the resulting SceneDefinition.
324 * The index mapper is responsible for maintaing this mapping, and resolving node IDs
325 * once the processing of the nodes has finished.
326 * @note The resolution requires the whole scene graph to finish parsing, therefore any
327 * node extensions relying on node IDs will see the dli ID in their processor.
332 * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
334 * @return Whether the operation was successful.
336 virtual bool Map(Index iDli, Index iScene) = 0;
339 * @return The scene index for the node's @a dli index.
341 virtual Index Resolve(Index iDli) = 0;
345 * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
346 * an intermediate representation of resources and nodes.
348 void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
350 void ParseSkeletons(const Toolkit::TreeNode* skeletons, Dali::Scene3D::Loader::SceneDefinition& scene, Dali::Scene3D::Loader::ResourceBundle& resources);
351 void ParseEnvironments(const Toolkit::TreeNode* environments, Dali::Scene3D::Loader::ResourceBundle& resources);
352 void ParseMaterials(const Toolkit::TreeNode* materials, DliInputParameter::ConvertColorCode convertColorCode, Dali::Scene3D::Loader::ResourceBundle& resources);
354 void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
355 void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
357 void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
358 void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
360 void ParseShaders(const Toolkit::TreeNode* shaders, Dali::Scene3D::Loader::ResourceBundle& resources);
361 void ParseMeshes(const Toolkit::TreeNode* meshes, Dali::Scene3D::Loader::ResourceBundle& resources);
363 void GetCameraParameters(std::vector<Dali::Scene3D::Loader::CameraParameters>& cameras) const;
364 void GetLightParameters(std::vector<Dali::Scene3D::Loader::LightParameters>& lights) const;
367 DliLoaderImpl::DliLoaderImpl()
372 DliLoaderImpl::~DliLoaderImpl() = default;
374 void DliLoaderImpl::SetErrorCallback(StringCallback onError)
376 mImpl->mOnError = onError;
379 bool DliLoaderImpl::LoadModel(const std::string& uri, Dali::Scene3D::Loader::LoadResult& result)
381 std::string daliBuffer = LoadTextFile(uri.c_str());
383 auto& parser = mImpl->mParser;
384 parser = JsonParser::New();
385 if(!parser.Parse(daliBuffer))
390 std::filesystem::path modelPath(uri);
391 Dali::Scene3D::Loader::DliInputParameter input;
392 LoadParams loadParams;
395 loadParams.input = static_cast<DliInputParameter*>(mInputParameter);
399 input.mAnimationsPath = std::string(modelPath.parent_path()) + "/";
400 loadParams.input = &input;
402 loadParams.output = &result;
404 mImpl->ParseScene(loadParams);
408 std::string DliLoaderImpl::GetParseError() const
410 std::stringstream stream;
412 auto& parser = mImpl->mParser;
413 if(parser.ParseError())
415 stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
421 void DliLoaderImpl::Impl::ParseScene(LoadParams& params)
423 auto& input = *params.input;
424 auto& output = *params.output;
426 // get index of root node.
427 auto docRoot = mParser.GetRoot();
430 // Process resources first - these are shared
431 if(auto environments = docRoot->GetChild("environment"))
433 ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
436 if(auto meshes = docRoot->GetChild("meshes"))
438 ParseMeshes(meshes, output.mResources);
441 if(auto shaders = docRoot->GetChild("shaders"))
443 ParseShaders(shaders, output.mResources);
446 if(auto materials = docRoot->GetChild("materials"))
448 ParseMaterials(materials, input.mConvertColorCode, output.mResources);
451 for(auto& c : input.mPreNodeCategoryProcessors)
453 if(auto node = docRoot->GetChild(c.first))
455 Property::Array array;
456 ParseProperties(*node, array);
457 c.second(std::move(array), mOnError);
462 Index iScene = 0; // default scene
463 ReadIndex(docRoot->GetChild("scene"), iScene);
465 auto tnScenes = RequireChild(docRoot, "scenes");
466 auto tnNodes = RequireChild(docRoot, "nodes");
467 ParseSceneInternal(iScene, tnScenes, tnNodes, params);
469 ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
471 output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
472 output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
474 // Ger cameras and lights
475 GetCameraParameters(output.mCameraParameters);
476 GetLightParameters(output.mLightParameters);
478 // Post-node processors and animations last
479 for(auto& c : input.mPostNodeCategoryProcessors)
481 if(auto node = docRoot->GetChild(c.first))
483 Property::Array array;
484 ParseProperties(*node, array);
485 c.second(std::move(array), mOnError);
489 if(auto animations = docRoot->GetChild("animations"))
491 ParseAnimations(animations, params);
494 if(!output.mAnimationDefinitions.empty())
496 if(auto animationGroups = docRoot->GetChild("animationGroups"))
498 ParseAnimationGroups(animationGroups, params);
504 void DliLoaderImpl::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
506 auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
507 auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
510 ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
513 tn = RequireChild(tn, NODES); // now a "nodes" array
514 if(tn->GetType() != TreeNode::ARRAY)
516 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
521 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
524 tn = GetNthChild(tn, 0); // now the first element of the array
526 if(!ReadIndex(tn, iRootNode))
528 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
531 if(iRootNode >= tnNodes->Size())
533 ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
536 tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
537 if(tn->GetType() != TreeNode::OBJECT)
539 ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
545 Index iRootNode = getSceneRootIdx(iScene);
546 ParseNodes(tnNodes, iRootNode, params);
548 auto& scene = params.output->mScene;
549 scene.AddRootNode(0);
551 for(Index i = 0; i < iScene; ++i)
553 Index iRootNode = getSceneRootIdx(i);
554 const Index iRoot = scene.GetNodeCount();
555 ParseNodes(tnNodes, iRootNode, params);
556 scene.AddRootNode(iRoot);
559 auto numScenes = tnScenes->Size();
560 for(Index i = iScene + 1; i < numScenes; ++i)
562 Index iRootNode = getSceneRootIdx(i);
563 const Index iRoot = scene.GetNodeCount();
564 ParseNodes(tnNodes, iRootNode, params);
565 scene.AddRootNode(iRoot);
569 void DliLoaderImpl::Impl::ParseSkeletons(const TreeNode* skeletons, Dali::Scene3D::Loader::SceneDefinition& scene, Dali::Scene3D::Loader::ResourceBundle& resources)
573 auto iStart = skeletons->CBegin();
574 for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
576 auto& node = (*i0).second;
577 std::string skeletonRootName;
578 if(ReadString(node.GetChild(NODE), skeletonRootName))
580 SkeletonDefinition skeleton;
581 if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
583 ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
586 uint32_t jointCount = 0;
587 std::function<void(Index)> visitFn;
588 auto& ibms = mInverseBindMatrices;
589 visitFn = [&](Index id) {
590 auto node = scene.GetNode(id);
591 jointCount += ibms.find(id) != ibms.end();
593 for(auto i : node->mChildren)
598 visitFn(skeleton.mRootNodeIdx);
600 if(jointCount > Skinning::MAX_JOINTS)
602 mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
603 jointCount = Skinning::MAX_JOINTS;
606 skeleton.mJoints.reserve(jointCount);
608 visitFn = [&](Index id) {
609 auto iFind = ibms.find(id);
610 if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
612 skeleton.mJoints.push_back({id, iFind->second});
615 auto node = scene.GetNode(id);
616 for(auto i : node->mChildren)
621 visitFn(skeleton.mRootNodeIdx);
623 resources.mSkeletons.push_back(std::move(skeleton));
627 ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
633 void DliLoaderImpl::Impl::ParseEnvironments(const TreeNode* environments, Dali::Scene3D::Loader::ResourceBundle& resources)
635 Matrix cubeOrientation(Matrix::IDENTITY);
637 for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
639 auto& node = (*i0).second;
641 EnvironmentDefinition envDef;
642 ReadString(node.GetChild("cubeSpecular"), envDef.mSpecularMapPath);
643 ReadString(node.GetChild("cubeDiffuse"), envDef.mDiffuseMapPath);
644 ToUnixFileSeparators(envDef.mSpecularMapPath);
645 ToUnixFileSeparators(envDef.mDiffuseMapPath);
646 envDef.mIblIntensity = 1.0f;
647 ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
648 if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
650 envDef.mCubeOrientation = Quaternion(cubeOrientation);
653 resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
656 // NOTE: guarantees environmentMaps to have an empty environment.
657 if(resources.mEnvironmentMaps.empty())
659 resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
663 void DliLoaderImpl::Impl::ParseShaders(const TreeNode* shaders, Dali::Scene3D::Loader::ResourceBundle& resources)
665 uint32_t iShader = 0;
666 for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
668 auto& node = (*i0).second;
669 ShaderDefinition shaderDef;
670 ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
672 // Read shader hints. Possible values are:
673 // Don't define for No hints.
674 // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
675 // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
677 ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
679 if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
680 ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
682 ToUnixFileSeparators(shaderDef.mVertexShaderPath);
683 ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
685 for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
687 const TreeNode::KeyNodePair& keyValue = *j0;
688 const std::string& key = keyValue.first;
689 const TreeNode& value = keyValue.second;
691 Property::Value uniformValue;
692 if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
696 else if(key.compare("rendererState") == 0)
698 shaderDef.mRendererState = ReadRendererState(keyValue.second);
700 else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
703 ReadFloat(&value, f);
706 else if(value.GetType() == TreeNode::BOOLEAN)
708 DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
710 if(ReadBool(&keyValue.second, value))
712 uniformValue = value ? 1.0f : 0.0f;
716 switch(auto size = GetNumericalArraySize(&value))
721 ReadVector(&value, m.AsFloat(), size);
729 ReadVector(&value, m.AsFloat(), size);
737 ReadVector(&value, v.AsFloat(), size);
745 ReadVector(&value, v.AsFloat(), size);
753 ReadVector(&value, v.AsFloat(), size);
759 mOnError(FormatString(
760 "shader %u: Ignoring uniform '%s': failed to infer type from %zu elements.",
767 if(Property::NONE != uniformValue.GetType())
769 shaderDef.mUniforms.Insert(key, uniformValue);
773 resources.mShaders.emplace_back(std::move(shaderDef), Shader());
777 ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
782 void DliLoaderImpl::Impl::ParseMeshes(const TreeNode* meshes, Dali::Scene3D::Loader::ResourceBundle& resources)
784 for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
786 auto& node = (*i0).second;
788 MeshDefinition meshDef;
789 if(!ReadString(node.GetChild(URI), meshDef.mUri))
791 ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
794 ToUnixFileSeparators(meshDef.mUri);
796 std::string primitive;
797 if(ReadString(node.GetChild("primitive"), primitive))
799 if(primitive == "LINES")
801 meshDef.mPrimitiveType = Geometry::LINES;
803 else if(primitive == "POINTS")
805 meshDef.mPrimitiveType = Geometry::POINTS;
807 else if(primitive != "TRIANGLES")
809 mOnError(FormatString(
810 "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
811 resources.mMeshes.size(),
817 if(ReadInt(node.GetChild("attributes"), attributes))
819 if(MaskMatch(attributes, MeshDefinition::INDICES) &&
820 !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
822 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
823 resources.mMeshes.size(),
827 if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
828 !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
830 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
831 resources.mMeshes.size(),
835 if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
836 !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
838 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
841 if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
842 !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
844 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
847 if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
848 !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
850 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
853 // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
854 if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
856 if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
857 !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
859 mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
860 resources.mMeshes.size()));
862 else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
863 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
865 mOnError(FormatString("mesh %d: Failed to read skinning information.",
866 resources.mMeshes.size()));
870 if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
872 std::string blendShapeVersion;
873 ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
875 if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
877 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
879 else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
881 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
884 switch(meshDef.mBlendShapeVersion)
886 case BlendShapes::Version::VERSION_1_0:
887 case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
889 ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
900 if(auto blendShapes = node.GetChild(BLEND_SHAPES))
902 meshDef.mBlendShapes.resize(blendShapes->Size());
905 for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
907 // Each blend shape is stored as the difference with the original mesh.
909 auto& blendShapeNode = (*it).second;
911 auto& blendShape = meshDef.mBlendShapes[index];
912 ReadString(blendShapeNode.GetChild("name"), blendShape.name);
913 if(auto position = blendShapeNode.GetChild("positions"))
915 ReadAttribAccessor(position, blendShape.deltas);
917 if(auto normals = blendShapeNode.GetChild("normals"))
919 ReadAttribAccessor(normals, blendShape.normals);
921 if(auto tangents = blendShapeNode.GetChild("tangents"))
923 ReadAttribAccessor(tangents, blendShape.tangents);
925 ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
930 if(ReadBool(node.GetChild("flipV"), flipV))
932 meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
935 resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
940 void DliLoaderImpl::Impl::ParseMaterials(const TreeNode* materials, DliInputParameter::ConvertColorCode convertColorCode, Dali::Scene3D::Loader::ResourceBundle& resources)
942 for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
944 auto& node = (*i0).second;
946 MaterialDefinition materialDef;
947 if(auto eEnvironment = node.GetChild("environment"))
949 ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
950 if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
952 ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
956 // TODO : need to consider AGIF
957 std::vector<std::string> texturePaths;
958 std::string texturePath;
959 if(ReadString(node.GetChild("albedoMap"), texturePath))
961 ToUnixFileSeparators(texturePath);
962 const auto semantic = MaterialDefinition::ALBEDO;
963 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
964 materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
966 if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
968 ToUnixFileSeparators(texturePath);
970 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
972 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
975 const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
976 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
977 materialDef.mFlags |= semantic;
980 if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
982 ToUnixFileSeparators(texturePath);
984 if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
986 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
989 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
990 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
991 materialDef.mFlags |= semantic |
992 // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
993 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
996 if(ReadString(node.GetChild("normalMap"), texturePath))
998 ToUnixFileSeparators(texturePath);
1000 const auto semantic = MaterialDefinition::NORMAL;
1001 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1002 materialDef.mFlags |= semantic |
1003 // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
1004 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
1007 if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
1009 ToUnixFileSeparators(texturePath);
1011 if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
1013 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
1016 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
1018 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
1021 if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1023 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1026 const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1027 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1028 materialDef.mFlags |= semantic;
1031 if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1033 ToUnixFileSeparators(texturePath);
1035 const auto semantic = MaterialDefinition::SUBSURFACE;
1036 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1037 materialDef.mFlags |= semantic;
1040 if(ReadString(node.GetChild("occlusionMap"), texturePath))
1042 ToUnixFileSeparators(texturePath);
1043 const auto semantic = MaterialDefinition::OCCLUSION;
1044 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1045 materialDef.mFlags |= semantic;
1048 if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1049 materialDef.mColor.a < 1.0f)
1051 materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1054 ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1055 ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1058 if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1060 for(auto& ts : materialDef.mTextureStages)
1062 ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1066 resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1070 void DliLoaderImpl::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1072 std::vector<Index> parents;
1075 struct IndexMapper : IIndexMapper
1077 IndexMapper(size_t numNodes)
1079 mIndices.reserve(numNodes);
1082 virtual bool Map(Index iDli, Index iScene) override
1084 Entry idx{iDli, iScene};
1085 auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1086 if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1088 mIndices.insert(iInsert, idx);
1090 else if(iInsert->iScene != iScene)
1097 virtual unsigned int Resolve(Index iDli) override
1099 auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) { return idx.iDli < iDli; });
1100 DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1101 return iFind->iScene;
1108 unsigned int iScene;
1110 bool operator<(const Entry& other) const
1112 return iDli < other.iDli;
1115 std::vector<Entry> mIndices;
1116 } mapper(nodes->Size());
1117 ParseNodesInternal(nodes, index, parents, params, mapper);
1119 auto& scene = params.output->mScene;
1120 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1122 for(auto& c : scene.GetNode(i0)->mConstraints)
1124 c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1129 void DliLoaderImpl::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1131 // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1132 struct IndexProperty
1134 ResourceType::Value type;
1135 const TreeNode* source;
1138 std::vector<IndexProperty> resourceIds;
1139 resourceIds.reserve(4);
1141 if(auto node = GetNthChild(nodes, index))
1143 Dali::Scene3D::Loader::NodeDefinition nodeDef;
1144 nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1147 ReadString(node->GetChild(NAME), nodeDef.mName);
1150 ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1152 // Reads the size of the node.
1154 // * It can be given as 'size' or 'bounds'.
1155 // * The sdk saves the 'size' as a vector2 in some cases.
1156 // * To avoid size related issues the following code attemps
1157 // to read the 'size/bounds' as a vector3 first, if it's
1158 // not successful then reads it as a vector2.
1159 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1160 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1161 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1162 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1165 ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1167 // type classification
1168 if(auto eCustomization = node->GetChild("customization")) // customization
1171 if(ReadString(eCustomization->GetChild("tag"), tag))
1173 nodeDef.mCustomization.reset(new Dali::Scene3D::Loader::NodeDefinition::CustomizationDefinition{tag});
1176 else // something renderable maybe
1178 std::unique_ptr<Dali::Scene3D::Loader::NodeDefinition::Renderable> renderable;
1179 ModelRenderable* modelRenderable = nullptr; // no ownership, aliasing renderable for the right type.
1181 const TreeNode* eRenderable = nullptr;
1182 if((eRenderable = node->GetChild("model")))
1184 // check for mesh before allocating - this can't be missing.
1185 auto eMesh = eRenderable->GetChild("mesh");
1188 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1191 modelRenderable = new ModelRenderable();
1192 renderable.reset(modelRenderable);
1194 resourceIds.push_back({ResourceType::Mesh, eMesh, modelRenderable->mMeshIdx});
1196 else if((eRenderable = node->GetChild("arc")))
1198 // check for mesh before allocating - this can't be missing.
1199 auto eMesh = eRenderable->GetChild("mesh");
1202 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1205 auto arcRenderable = new ArcRenderable;
1206 renderable.reset(arcRenderable);
1207 modelRenderable = arcRenderable;
1209 resourceIds.push_back({ResourceType::Mesh, eMesh, arcRenderable->mMeshIdx});
1211 ReadArcField(eRenderable, *arcRenderable);
1214 if(renderable && eRenderable != nullptr) // process common properties of all renderables + register payload
1217 renderable->mShaderIdx = 0;
1218 auto eShader = eRenderable->GetChild("shader");
1221 resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1227 modelRenderable->mMaterialIdx = 0; // must offer default of 0
1228 auto eMaterial = eRenderable->GetChild("material");
1231 resourceIds.push_back({ResourceType::Material, eMaterial, modelRenderable->mMaterialIdx});
1234 if(!ReadColorCodeOrColor(eRenderable, modelRenderable->mColor, params.input->mConvertColorCode))
1236 ReadColorCodeOrColor(node, modelRenderable->mColor, params.input->mConvertColorCode);
1240 nodeDef.mRenderables.push_back(std::move(renderable));
1244 // Resolve ints - default to 0 if undefined
1245 auto& output = params.output;
1246 for(auto& idRes : resourceIds)
1251 case ResourceType::Shader:
1252 iCheck = output->mResources.mShaders.size();
1255 case ResourceType::Mesh:
1256 iCheck = output->mResources.mMeshes.size();
1259 case ResourceType::Material:
1260 iCheck = output->mResources.mMaterials.size();
1264 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1271 else if(idRes.source->GetType() != TreeNode::INTEGER)
1273 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1277 idRes.target = idRes.source->GetInteger();
1280 if(idRes.target >= iCheck)
1282 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1285 resourceIds.clear();
1288 if(auto eExtras = node->GetChild("extras"))
1290 auto& extras = nodeDef.mExtras;
1291 extras.reserve(eExtras->Size());
1293 for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1295 Dali::Scene3D::Loader::NodeDefinition::Extra e;
1298 e.mKey = eExtra.first;
1301 mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1307 e.mValue = ReadPropertyValue(eExtra.second);
1308 if(e.mValue.GetType() == Property::Type::NONE)
1310 mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1313 eExtra.second.GetString()));
1317 auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1318 if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1320 mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1323 eExtra.second.GetString()));
1324 *iInsert = std::move(e);
1328 extras.insert(iInsert, e);
1335 if(auto eConstraints = node->GetChild("constraints"))
1337 auto& constraints = nodeDef.mConstraints;
1338 constraints.reserve(eConstraints->Size());
1340 ConstraintDefinition cDef;
1341 for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1343 auto eConstraint = *i0;
1344 if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1346 mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1348 eConstraint.second.GetString(),
1349 constraints.size()));
1353 cDef.mProperty = eConstraint.first;
1355 auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1356 if(iInsert != constraints.end() && *iInsert == cDef)
1358 mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1360 cDef.mProperty.c_str(),
1365 constraints.insert(iInsert, cDef);
1371 // Determine index for mapping
1372 const unsigned int myIndex = output->mScene.GetNodeCount();
1373 if(!mapper.Map(index, myIndex))
1375 mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree.", index, myIndex));
1379 // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1380 Matrix invBindMatrix{false};
1381 if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1383 mInverseBindMatrices[myIndex] = invBindMatrix;
1387 auto rawDef = output->mScene.AddNode(std::make_unique<Dali::Scene3D::Loader::NodeDefinition>(std::move(nodeDef)));
1388 if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1390 // ...And only then parse children.
1391 if(auto children = node->GetChild("children"))
1393 inOutParentStack.push_back(myIndex);
1395 rawDef->mChildren.reserve(children->Size());
1397 uint32_t iChild = 0;
1398 for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1400 auto& child = (*j0).second;
1401 if(child.GetType() == TreeNode::INTEGER)
1403 ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1407 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1411 inOutParentStack.pop_back();
1413 else if(rawDef->mCustomization)
1415 mOnError(FormatString("node %d: not an actual customization without children.", index));
1418 if(auto proc = params.input->mNodePropertyProcessor) // optional processing
1420 // WARNING: constraint IDs are not resolved at this point.
1421 Property::Map nodeData;
1422 ParseProperties(*node, nodeData);
1423 proc(*rawDef, std::move(nodeData), mOnError);
1428 ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1433 void DliLoaderImpl::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1435 auto& definitions = params.output->mAnimationDefinitions;
1436 definitions.reserve(definitions.size() + tnAnimations->Size());
1438 for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1442 const TreeNode& tnAnim = (*iAnim).second;
1443 AnimationDefinition animDef;
1444 ReadString(tnAnim.GetChild(NAME), animDef.mName);
1446 auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { return ad0.mName < ad1.mName; });
1447 const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1450 mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1453 // Duration -- We need something that animated properties' delay / duration can
1454 // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1455 // than our frame delay) to not be restrictive WRT replaying. If anything needs
1456 // to occur more frequently, then Animations are likely not your solution anyway.
1457 animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1458 if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1460 mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1461 animDef.mName.c_str(),
1463 animDef.mDuration));
1466 // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1467 animDef.mLoopCount = 1;
1468 if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1469 animDef.mLoopCount < 0)
1471 animDef.mLoopCount = 0;
1474 std::string endAction;
1475 if(ReadString(tnAnim.GetChild("endAction"), endAction))
1477 if("BAKE" == endAction)
1479 animDef.mEndAction = Animation::BAKE;
1481 else if("DISCARD" == endAction)
1483 animDef.mEndAction = Animation::DISCARD;
1485 else if("BAKE_FINAL" == endAction)
1487 animDef.mEndAction = Animation::BAKE_FINAL;
1491 if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1493 if("BAKE" == endAction)
1495 animDef.mDisconnectAction = Animation::BAKE;
1497 else if("DISCARD" == endAction)
1499 animDef.mDisconnectAction = Animation::DISCARD;
1501 else if("BAKE_FINAL" == endAction)
1503 animDef.mDisconnectAction = Animation::BAKE_FINAL;
1507 if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1509 animDef.mProperties.reserve(tnProperties->Size());
1510 for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1511 iProperty != iPropertyEnd;
1514 const TreeNode& tnProperty = (*iProperty).second;
1516 AnimatedProperty animProp;
1517 if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1519 mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1523 if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1525 mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1529 // these are the defaults
1530 animProp.mTimePeriod.delaySeconds = 0.f;
1531 animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1532 if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1534 mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1535 animDef.mName.c_str(),
1536 animDef.mProperties.size(),
1537 animProp.mTimePeriod.durationSeconds));
1540 std::string alphaFunctionValue;
1541 if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1543 animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1546 if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1548 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1550 std::ifstream binAniFile;
1551 std::string animationFilename;
1552 if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1554 std::string animationFullPath = params.input->mAnimationsPath + animationFilename;
1555 binAniFile.open(animationFullPath, std::ios::binary);
1556 if(binAniFile.fail())
1558 ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1563 ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1564 DALI_ASSERT_ALWAYS(byteOffset >= 0);
1566 binAniFile.seekg(byteOffset, std::ios::beg);
1569 ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1570 DALI_ASSERT_ALWAYS(numKeys >= 0);
1572 animProp.mKeyFrames = KeyFrames::New();
1574 // In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1575 // so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1576 // otherwise are blend shape weight keys.
1577 // TODO support for binary header with size information
1578 Property::Type propType = Property::FLOAT; // assume blend shape weights
1579 if(animProp.mPropertyName == "orientation")
1581 propType = Property::VECTOR4;
1583 else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1585 propType = Property::VECTOR3;
1588 // alphafunction is reserved for future implementation
1589 // NOTE: right now we're just using AlphaFunction::LINEAR.
1590 unsigned char dummyAlphaFunction;
1593 Property::Value propValue;
1594 for(int key = 0; key < numKeys; key++)
1596 binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1597 if(propType == Property::VECTOR3)
1600 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1601 propValue = Property::Value(value);
1603 else if(propType == Property::VECTOR4)
1606 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1607 propValue = Property::Value(Quaternion(value));
1612 binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1613 propValue = Property::Value(value);
1616 binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1618 animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1621 else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1623 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1624 animProp.mKeyFrames = KeyFrames::New();
1626 float progress = 0.0f;
1627 for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1629 const TreeNode::KeyNodePair& kfKeyChild = *i0;
1630 bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1631 DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1633 const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1634 DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1636 // For the "orientation" property, convert from Vector4 -> Rotation value
1637 // This work-around is preferable to a null-pointer exception in the DALi update thread
1638 Property::Value propValue(ReadPropertyValue(*tnValue));
1639 if(propValue.GetType() == Property::VECTOR4 &&
1640 animProp.mPropertyName == "orientation")
1644 propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1647 AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1648 std::string alphaFuncStr;
1649 if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1651 kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1654 animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1659 const TreeNode* tnValue = tnProperty.GetChild("value");
1662 animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1663 ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1667 mOnError(FormatString("Property '%s' fails to define target value.",
1668 animProp.mPropertyName.c_str()));
1672 animDef.mProperties.push_back(std::move(animProp));
1678 *iFind = std::move(animDef);
1682 iFind = definitions.insert(iFind, std::move(animDef));
1685 if(auto proc = params.input->mAnimationPropertyProcessor) // optional processing
1688 ParseProperties(tnAnim, map);
1689 proc(animDef, std::move(map), mOnError);
1694 void DliLoaderImpl::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1696 auto& animGroups = params.output->mAnimationGroupDefinitions;
1699 for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1700 iGroups != iGroupsEnd;
1701 ++iGroups, ++numGroups)
1703 const auto& tnGroup = *iGroups;
1704 auto tnName = tnGroup.second.GetChild(NAME);
1705 std::string groupName;
1706 if(!tnName || !ReadString(tnName, groupName))
1708 mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1712 auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) { return group.mName < name; });
1713 if(iFind != animGroups.end() && iFind->mName == groupName)
1715 mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1719 iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1722 iFind->mName = groupName;
1724 auto tnAnims = tnGroup.second.GetChild("animations");
1725 if(tnAnims && tnAnims->Size() > 0)
1727 auto& anims = iFind->mAnimations;
1728 anims.reserve(anims.size() + tnAnims->Size());
1729 for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1731 anims.push_back((*iAnims).second.GetString());
1737 void DliLoaderImpl::Impl::GetCameraParameters(std::vector<Dali::Scene3D::Loader::CameraParameters>& cameras) const
1739 if(mParser.GetRoot())
1741 if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1743 float dummyFloatArray[4];
1745 cameras.resize(jsonCameras->Size());
1746 auto iCamera = cameras.begin();
1747 for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1749 auto& jsonCamera = (*i0).second;
1751 ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFovDegree.degree);
1752 ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1753 ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1754 if(ReadVector(jsonCamera.GetChild("orthographic"), dummyFloatArray, 4u))
1756 iCamera->isPerspective = false;
1758 iCamera->orthographicSize = dummyFloatArray[2] * 0.5f;
1759 iCamera->aspectRatio = dummyFloatArray[1] / dummyFloatArray[2];
1762 if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1764 ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1773 void DliLoaderImpl::Impl::GetLightParameters(std::vector<Dali::Scene3D::Loader::LightParameters>& lights) const
1775 if(mParser.GetRoot())
1777 if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1779 lights.resize(jsonLights->Size());
1780 auto iLight = lights.begin();
1781 for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1783 auto& jsonLight = (*i0).second;
1784 if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1787 FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1788 std::distance(jsonLights->CBegin(), i0)));
1792 int shadowMapSize = 0;
1793 if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1796 FormatString("Failed to parse light %d - %s has an invalid value.",
1797 std::distance(jsonLights->CBegin(), i0),
1801 iLight->shadowMapSize = shadowMapSize;
1803 float orthoSize = 0.f;
1804 if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1805 (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1808 FormatString("Failed to parse light %d - %s has an invalid value.",
1809 std::distance(jsonLights->CBegin(), i0),
1810 ORTHOGRAPHIC_SIZE));
1813 iLight->orthographicSize = orthoSize;
1815 if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1817 mOnError(FormatString(
1818 "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1819 std::distance(jsonLights->CBegin(), i0)));
1822 if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1824 iLight->color = Vector3::ONE; // default to white
1827 if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1829 iLight->intensity = 1.0f; // default to 1.0
1832 if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1834 iLight->shadowIntensity = 1.0f; // default to 1.0
1843 } // namespace Internal
1844 } // namespace Loader
1845 } // namespace Scene3D