2 * Copyright (c) 2021 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-scene-loader/public-api/dli-loader.h"
27 #include "dali-toolkit/devel-api/builder/json-parser.h"
28 #include "dali/devel-api/common/map-wrapper.h"
29 #include "dali/integration-api/debug.h"
30 #include "dali/public-api/object/property-array.h"
33 #include "dali-scene-loader/internal/json-util.h"
34 #include "dali-scene-loader/public-api/alpha-function-helper.h"
35 #include "dali-scene-loader/public-api/animation-definition.h"
36 #include "dali-scene-loader/public-api/blend-shape-details.h"
37 #include "dali-scene-loader/public-api/camera-parameters.h"
38 #include "dali-scene-loader/public-api/ktx-loader.h"
39 #include "dali-scene-loader/public-api/light-parameters.h"
40 #include "dali-scene-loader/public-api/load-result.h"
41 #include "dali-scene-loader/public-api/parse-renderer-state.h"
42 #include "dali-scene-loader/public-api/scene-definition.h"
43 #include "dali-scene-loader/public-api/skinning-details.h"
44 #include "dali-scene-loader/public-api/utils.h"
46 #define DLI_0_1_COMPATIBILITY
50 using namespace Toolkit;
54 namespace rs = RendererState;
58 const std::string NODES = "nodes";
59 const std::string SCENES = "scenes";
60 const std::string NODE = "node";
61 const std::string URI = "uri";
62 const std::string URL = "url";
63 const std::string CUSTOMIZATION = "customization";
64 const std::string HINTS = "hints";
65 const std::string NAME("name");
66 const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
67 const std::string BLEND_SHAPES("blendShapes");
68 const std::string BLEND_SHAPE_VERSION_1_0("1.0");
69 const std::string BLEND_SHAPE_VERSION_2_0("2.0");
70 const std::string VERSION("version");
72 const char* const SHADOW_MAP_SIZE = "shadowMapSize";
73 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
74 const char* const PIXEL_UNITS = "px";
76 const char SLASH = '/';
78 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
80 float num[16u] = {.0f};
82 if(ReadVector(node->GetChild("matrix"), num, 16u))
85 mat.GetTransformComponents(translation, orientation, scale);
89 if(ReadVector(node->GetChild("angle"), num, 3u))
91 orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
94 if(ReadVector(node->GetChild("position"), num, 3u))
96 translation = Vector3(num);
101 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
103 return ReadBlob(node, buffer.mOffset, buffer.mLength);
106 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
108 return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
111 bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
113 if(!node || !convertColorCode)
118 color = convertColorCode(node->GetString());
123 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
125 return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
126 ReadColor(node->GetChild("color"), color);
129 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
131 if(tnRendererState.GetType() == TreeNode::INTEGER)
133 return static_cast<RendererState::Type>(tnRendererState.GetInteger());
135 else if(tnRendererState.GetType() == TreeNode::STRING)
137 return RendererState::Parse(tnRendererState.GetString());
145 ///@brief Reads arc properties.
146 void ReadArcField(const TreeNode* eArc, ArcNode& arc)
148 ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
149 ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
150 ReadFloat(eArc->GetChild("radius"), arc.mRadius);
152 arc.mStartAngleDegrees = .0f;
153 ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
155 arc.mEndAngleDegrees = .0f;
156 ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
159 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
162 for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
166 return &((*it).second);
172 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
174 auto child = node->GetChild(childName);
177 ExceptionFlinger flinger(ASSERT_LOCATION);
178 flinger << "Failed to find child node '" << childName << "'";
179 if(auto nodeName = node->GetName())
181 flinger << " on '" << nodeName << "'";
188 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
190 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
192 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
193 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
196 switch(kv.second.GetType())
198 case TreeNode::ARRAY:
200 Property::Array array;
201 ParseProperties(kv.second, array);
202 map.Insert(kv.first, array);
206 case TreeNode::OBJECT:
208 Property::Map innerMap;
209 ParseProperties(kv.second, innerMap);
210 map.Insert(kv.first, innerMap);
214 case TreeNode::STRING:
216 map.Insert(kv.first, kv.second.GetString());
220 case TreeNode::INTEGER:
222 map.Insert(kv.first, kv.second.GetInteger());
226 case TreeNode::BOOLEAN:
228 map.Insert(kv.first, kv.second.GetBoolean());
232 case TreeNode::FLOAT:
234 map.Insert(kv.first, kv.second.GetFloat());
238 case TreeNode::IS_NULL:
246 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
248 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
249 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
252 switch(kv.second.GetType())
254 case TreeNode::ARRAY:
256 Property::Array innerArray;
257 ParseProperties(kv.second, innerArray);
258 array.PushBack(innerArray);
262 case TreeNode::OBJECT:
265 ParseProperties(kv.second, map);
270 case TreeNode::STRING:
272 array.PushBack(kv.second.GetString());
276 case TreeNode::INTEGER:
278 array.PushBack(kv.second.GetInteger());
282 case TreeNode::BOOLEAN:
284 array.PushBack(kv.second.GetBoolean());
288 case TreeNode::FLOAT:
290 array.PushBack(kv.second.GetFloat());
294 case TreeNode::IS_NULL:
304 struct DliLoader::Impl
306 StringCallback mOnError = DefaultErrorCallback;
307 Toolkit::JsonParser mParser;
309 void ParseScene(LoadParams& params);
312 std::map<Index, Matrix> mInverseBindMatrices;
315 * @brief Due to .dli nodes being processed in depth-first traversal with orphans being
316 * ignored, features that rely on node indices (which is more compact and closer to
317 * glTF) require a mapping from .dli node indices to those in the resulting SceneDefinition.
318 * The index mapper is responsible for maintaing this mapping, and resolving node IDs
319 * once the processing of the nodes has finished.
320 * @note The resolution requires the whole scene graph to finish parsing, therefore any
321 * node extensions relying on node IDs will see the dli ID in their processor.
326 * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
328 * @return Whether the operation was successful.
330 virtual bool Map(Index iDli, Index iScene) = 0;
333 * @return The scene index for the node's @a dli index.
335 virtual Index Resolve(Index iDli) = 0;
339 * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
340 * an intermediate representation of resources and nodes.
342 void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
344 void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
345 void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
346 void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
348 void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
349 void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
351 void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
352 void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
354 void ParseShaders(const Toolkit::TreeNode* shaders, ResourceBundle& resources);
355 void ParseMeshes(const Toolkit::TreeNode* meshes, ResourceBundle& resources);
357 void GetCameraParameters(std::vector<CameraParameters>& cameras) const;
358 void GetLightParameters(std::vector<LightParameters>& lights) const;
361 DliLoader::DliLoader()
366 DliLoader::~DliLoader() = default;
368 void DliLoader::SetErrorCallback(StringCallback onError)
370 mImpl->mOnError = onError;
373 bool DliLoader::LoadScene(const std::string& uri, LoadParams& params)
375 std::string daliBuffer = LoadTextFile(uri.c_str());
377 auto& parser = mImpl->mParser;
378 parser = JsonParser::New();
379 if(!parser.Parse(daliBuffer))
384 mImpl->ParseScene(params);
388 std::string DliLoader::GetParseError() const
390 std::stringstream stream;
392 auto& parser = mImpl->mParser;
393 if(parser.ParseError())
395 stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
401 void DliLoader::Impl::ParseScene(LoadParams& params)
403 auto& input = params.input;
404 auto& output = params.output;
406 // get index of root node.
407 auto docRoot = mParser.GetRoot();
409 // Process resources first - these are shared
410 if(auto environments = docRoot->GetChild("environment"))
412 ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
415 if(auto meshes = docRoot->GetChild("meshes"))
417 ParseMeshes(meshes, output.mResources);
420 if(auto shaders = docRoot->GetChild("shaders"))
422 ParseShaders(shaders, output.mResources);
425 if(auto materials = docRoot->GetChild("materials"))
427 ParseMaterials(materials, input.mConvertColorCode, output.mResources);
430 for(auto& c : input.mPreNodeCategoryProcessors)
432 if(auto node = docRoot->GetChild(c.first))
434 Property::Array array;
435 ParseProperties(*node, array);
436 c.second(std::move(array), mOnError);
441 Index iScene = 0; // default scene
442 ReadIndex(docRoot->GetChild("scene"), iScene);
444 auto tnScenes = RequireChild(docRoot, "scenes");
445 auto tnNodes = RequireChild(docRoot, "nodes");
446 ParseSceneInternal(iScene, tnScenes, tnNodes, params);
448 ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
450 output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
451 output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
453 // Ger cameras and lights
454 GetCameraParameters(output.mCameraParameters);
455 GetLightParameters(output.mLightParameters);
457 // Post-node processors and animations last
458 for(auto& c : input.mPostNodeCategoryProcessors)
460 if(auto node = docRoot->GetChild(c.first))
462 Property::Array array;
463 ParseProperties(*node, array);
464 c.second(std::move(array), mOnError);
468 if(auto animations = docRoot->GetChild("animations"))
470 ParseAnimations(animations, params);
473 if(!output.mAnimationDefinitions.empty())
475 if(auto animationGroups = docRoot->GetChild("animationGroups"))
477 ParseAnimationGroups(animationGroups, params);
482 void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
484 auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
485 auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
488 ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
491 tn = RequireChild(tn, NODES); // now a "nodes" array
492 if(tn->GetType() != TreeNode::ARRAY)
494 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
499 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
502 tn = GetNthChild(tn, 0); // now the first element of the array
504 if(!ReadIndex(tn, iRootNode))
506 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
509 if(iRootNode >= tnNodes->Size())
511 ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
514 tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
515 if(tn->GetType() != TreeNode::OBJECT)
517 ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
523 Index iRootNode = getSceneRootIdx(iScene);
524 ParseNodes(tnNodes, iRootNode, params);
526 auto& scene = params.output.mScene;
527 scene.AddRootNode(0);
529 for(Index i = 0; i < iScene; ++i)
531 Index iRootNode = getSceneRootIdx(i);
532 const Index iRoot = scene.GetNodeCount();
533 ParseNodes(tnNodes, iRootNode, params);
534 scene.AddRootNode(iRoot);
537 auto numScenes = tnScenes->Size();
538 for(Index i = iScene + 1; i < numScenes; ++i)
540 Index iRootNode = getSceneRootIdx(i);
541 const Index iRoot = scene.GetNodeCount();
542 ParseNodes(tnNodes, iRootNode, params);
543 scene.AddRootNode(iRoot);
547 void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
551 auto iStart = skeletons->CBegin();
552 for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
554 auto& node = (*i0).second;
555 std::string skeletonRootName;
556 if(ReadString(node.GetChild(NODE), skeletonRootName))
558 SkeletonDefinition skeleton;
559 if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
561 ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
564 uint32_t jointCount = 0;
565 std::function<void(Index)> visitFn;
566 auto& ibms = mInverseBindMatrices;
567 visitFn = [&](Index id) {
568 auto node = scene.GetNode(id);
569 jointCount += ibms.find(id) != ibms.end();
571 for(auto i : node->mChildren)
576 visitFn(skeleton.mRootNodeIdx);
578 if(jointCount > Skinning::MAX_JOINTS)
580 mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
581 jointCount = Skinning::MAX_JOINTS;
584 skeleton.mJoints.reserve(jointCount);
586 visitFn = [&](Index id) {
587 auto iFind = ibms.find(id);
588 if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
590 skeleton.mJoints.push_back({id, iFind->second});
593 auto node = scene.GetNode(id);
594 for(auto i : node->mChildren)
599 visitFn(skeleton.mRootNodeIdx);
601 resources.mSkeletons.push_back(std::move(skeleton));
605 ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
611 void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBundle& resources)
613 Matrix cubeOrientation(Matrix::IDENTITY);
615 for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
617 auto& node = (*i0).second;
619 EnvironmentDefinition envDef;
620 ReadString(node.GetChild("cubeSpecular"), envDef.mSpecularMapPath);
621 ReadString(node.GetChild("cubeDiffuse"), envDef.mDiffuseMapPath);
622 ToUnixFileSeparators(envDef.mSpecularMapPath);
623 ToUnixFileSeparators(envDef.mDiffuseMapPath);
624 envDef.mIblIntensity = 1.0f;
625 ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
626 if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
628 envDef.mCubeOrientation = Quaternion(cubeOrientation);
631 resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
634 // NOTE: guarantees environmentMaps to have an empty environment.
635 if(resources.mEnvironmentMaps.empty())
637 resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
641 void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
643 uint32_t iShader = 0;
644 for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
646 auto& node = (*i0).second;
647 ShaderDefinition shaderDef;
648 ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
650 // Read shader hints. Possible values are:
651 // Don't define for No hints.
652 // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
653 // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
655 ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
657 if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
658 ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
660 ToUnixFileSeparators(shaderDef.mVertexShaderPath);
661 ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
663 for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
665 const TreeNode::KeyNodePair& keyValue = *j0;
666 const std::string& key = keyValue.first;
667 const TreeNode& value = keyValue.second;
669 Property::Value uniformValue;
670 if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
674 else if(key.compare("rendererState") == 0)
676 shaderDef.mRendererState = ReadRendererState(keyValue.second);
678 else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
681 ReadFloat(&value, f);
684 else if(value.GetType() == TreeNode::BOOLEAN)
686 DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
688 if(ReadBool(&keyValue.second, value))
690 uniformValue = value ? 1.0f : 0.0f;
694 switch(auto size = GetNumericalArraySize(&value))
699 ReadVector(&value, m.AsFloat(), size);
707 ReadVector(&value, m.AsFloat(), size);
715 ReadVector(&value, v.AsFloat(), size);
723 ReadVector(&value, v.AsFloat(), size);
731 ReadVector(&value, v.AsFloat(), size);
737 mOnError(FormatString(
738 "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
744 if(Property::NONE != uniformValue.GetType())
746 shaderDef.mUniforms.Insert(key, uniformValue);
750 resources.mShaders.emplace_back(std::move(shaderDef), Shader());
754 ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
759 void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
761 for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
763 auto& node = (*i0).second;
765 MeshDefinition meshDef;
766 if(!ReadString(node.GetChild(URI), meshDef.mUri))
768 ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
771 ToUnixFileSeparators(meshDef.mUri);
773 std::string primitive;
774 if(ReadString(node.GetChild("primitive"), primitive))
776 if(primitive == "LINES")
778 meshDef.mPrimitiveType = Geometry::LINES;
780 else if(primitive == "POINTS")
782 meshDef.mPrimitiveType = Geometry::POINTS;
784 else if(primitive != "TRIANGLES")
786 mOnError(FormatString(
787 "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
788 resources.mMeshes.size(),
794 if(ReadInt(node.GetChild("attributes"), attributes))
796 if(MaskMatch(attributes, MeshDefinition::INDICES) &&
797 !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
799 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
800 resources.mMeshes.size(),
804 if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
805 !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
807 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
808 resources.mMeshes.size(),
812 if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
813 !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
815 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
818 if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
819 !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
821 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
824 if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
825 !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
827 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
830 // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
831 if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
833 if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
834 !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
836 mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
837 resources.mMeshes.size()));
839 else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
840 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
842 mOnError(FormatString("mesh %d: Failed to read skinning information.",
843 resources.mMeshes.size()));
847 if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
849 std::string blendShapeVersion;
850 ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
852 if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
854 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
856 else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
858 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
861 switch(meshDef.mBlendShapeVersion)
863 case BlendShapes::Version::VERSION_1_0:
864 case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
866 ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
877 if(auto blendShapes = node.GetChild(BLEND_SHAPES))
879 meshDef.mBlendShapes.resize(blendShapes->Size());
882 for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
884 // Each blend shape is stored as the difference with the original mesh.
886 auto& blendShapeNode = (*it).second;
888 auto& blendShape = meshDef.mBlendShapes[index];
889 ReadString(blendShapeNode.GetChild("name"), blendShape.name);
890 if(auto position = blendShapeNode.GetChild("positions"))
892 ReadAttribAccessor(position, blendShape.deltas);
894 if(auto normals = blendShapeNode.GetChild("normals"))
896 ReadAttribAccessor(normals, blendShape.normals);
898 if(auto tangents = blendShapeNode.GetChild("tangents"))
900 ReadAttribAccessor(tangents, blendShape.tangents);
902 ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
907 if(ReadBool(node.GetChild("flipV"), flipV))
909 meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
912 resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
917 void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
919 for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
921 auto& node = (*i0).second;
923 MaterialDefinition materialDef;
924 if(auto eEnvironment = node.GetChild("environment"))
926 ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
927 if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
929 ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
933 //TODO : need to consider AGIF
934 std::vector<std::string> texturePaths;
935 std::string texturePath;
936 if(ReadString(node.GetChild("albedoMap"), texturePath))
938 ToUnixFileSeparators(texturePath);
939 const auto semantic = MaterialDefinition::ALBEDO;
940 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
941 materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
943 if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
945 ToUnixFileSeparators(texturePath);
947 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
949 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
952 const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
953 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
954 materialDef.mFlags |= semantic;
957 if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
959 ToUnixFileSeparators(texturePath);
961 if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
963 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
966 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
967 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
968 materialDef.mFlags |= semantic |
969 // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
970 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
973 if(ReadString(node.GetChild("normalMap"), texturePath))
975 ToUnixFileSeparators(texturePath);
977 const auto semantic = MaterialDefinition::NORMAL;
978 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
979 materialDef.mFlags |= semantic |
980 // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
981 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
984 if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
986 ToUnixFileSeparators(texturePath);
988 if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
990 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
993 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
995 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
998 if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1000 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1003 const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1004 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1005 materialDef.mFlags |= semantic;
1008 if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1010 ToUnixFileSeparators(texturePath);
1012 const auto semantic = MaterialDefinition::SUBSURFACE;
1013 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1014 materialDef.mFlags |= semantic;
1017 if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1018 materialDef.mColor.a < 1.0f)
1020 materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1023 ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1024 ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1027 if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1029 for(auto& ts : materialDef.mTextureStages)
1031 ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1035 resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1039 void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1041 std::vector<Index> parents;
1044 struct IndexMapper : IIndexMapper
1046 IndexMapper(size_t numNodes)
1048 mIndices.reserve(numNodes);
1051 virtual bool Map(Index iDli, Index iScene) override
1053 Entry idx{iDli, iScene};
1054 auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1055 if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1057 mIndices.insert(iInsert, idx);
1059 else if(iInsert->iScene != iScene)
1066 virtual unsigned int Resolve(Index iDli) override
1068 auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) {
1069 return idx.iDli < iDli;
1071 DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1072 return iFind->iScene;
1079 unsigned int iScene;
1081 bool operator<(const Entry& other) const
1083 return iDli < other.iDli;
1086 std::vector<Entry> mIndices;
1087 } mapper(nodes->Size());
1088 ParseNodesInternal(nodes, index, parents, params, mapper);
1090 auto& scene = params.output.mScene;
1091 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1093 for(auto& c : scene.GetNode(i0)->mConstraints)
1095 c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1100 void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1102 // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1103 struct IndexProperty
1105 ResourceType::Value type;
1106 const TreeNode* source;
1109 std::vector<IndexProperty> resourceIds;
1110 resourceIds.reserve(4);
1112 if(auto node = GetNthChild(nodes, index))
1114 NodeDefinition nodeDef;
1115 nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1118 ReadString(node->GetChild(NAME), nodeDef.mName);
1121 ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1123 // Reads the size of the node.
1125 // * It can be given as 'size' or 'bounds'.
1126 // * The sdk saves the 'size' as a vector2 in some cases.
1127 // * To avoid size related issues the following code attemps
1128 // to read the 'size/bounds' as a vector3 first, if it's
1129 // not successful then reads it as a vector2.
1130 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1131 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1132 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1133 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1136 ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1138 // type classification
1139 if(auto eCustomization = node->GetChild("customization")) // customization
1142 if(ReadString(eCustomization->GetChild("tag"), tag))
1144 nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
1147 else // something renderable maybe
1149 std::unique_ptr<NodeDefinition::Renderable> renderable;
1150 ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
1152 const TreeNode* eRenderable = nullptr;
1153 if((eRenderable = node->GetChild("model")))
1155 // check for mesh before allocating - this can't be missing.
1156 auto eMesh = eRenderable->GetChild("mesh");
1159 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1162 modelNode = new ModelNode();
1163 renderable.reset(modelNode);
1165 resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx});
1167 else if((eRenderable = node->GetChild("arc")))
1169 // check for mesh before allocating - this can't be missing.
1170 auto eMesh = eRenderable->GetChild("mesh");
1173 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1176 auto arcNode = new ArcNode;
1177 renderable.reset(arcNode);
1178 modelNode = arcNode;
1180 resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx});
1182 ReadArcField(eRenderable, *arcNode);
1185 if(renderable) // process common properties of all renderables + register payload
1188 renderable->mShaderIdx = 0;
1189 auto eShader = eRenderable->GetChild("shader");
1190 resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1195 modelNode->mMaterialIdx = 0; // must offer default of 0
1196 auto eMaterial = eRenderable->GetChild("material");
1197 resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx});
1199 if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
1201 ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode);
1205 nodeDef.mRenderable = std::move(renderable);
1209 // Resolve ints - default to 0 if undefined
1210 auto& output = params.output;
1211 for(auto& idRes : resourceIds)
1216 case ResourceType::Shader:
1217 iCheck = output.mResources.mShaders.size();
1220 case ResourceType::Mesh:
1221 iCheck = output.mResources.mMeshes.size();
1224 case ResourceType::Material:
1225 iCheck = output.mResources.mMaterials.size();
1229 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1236 else if(idRes.source->GetType() != TreeNode::INTEGER)
1238 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1242 idRes.target = idRes.source->GetInteger();
1245 if(idRes.target >= iCheck)
1247 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1250 resourceIds.clear();
1253 if(auto eExtras = node->GetChild("extras"))
1255 auto& extras = nodeDef.mExtras;
1256 extras.reserve(eExtras->Size());
1258 NodeDefinition::Extra e;
1259 for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1262 e.mKey = eExtra.first;
1265 mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1271 e.mValue = ReadPropertyValue(eExtra.second);
1272 if(e.mValue.GetType() == Property::Type::NONE)
1274 mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1277 eExtra.second.GetString()));
1281 auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1282 if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1284 mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1287 eExtra.second.GetString()));
1288 *iInsert = std::move(e);
1292 extras.insert(iInsert, e);
1299 if(auto eConstraints = node->GetChild("constraints"))
1301 auto& constraints = nodeDef.mConstraints;
1302 constraints.reserve(eConstraints->Size());
1304 ConstraintDefinition cDef;
1305 for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1307 auto eConstraint = *i0;
1308 if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1310 mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1312 eConstraint.second.GetString(),
1313 constraints.size()));
1317 cDef.mProperty = eConstraint.first;
1319 auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1320 if(iInsert != constraints.end() && *iInsert == cDef)
1322 mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1324 cDef.mProperty.c_str(),
1329 constraints.insert(iInsert, cDef);
1335 // Determine index for mapping
1336 const unsigned int myIndex = output.mScene.GetNodeCount();
1337 if(!mapper.Map(index, myIndex))
1339 mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree."));
1343 // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1344 Matrix invBindMatrix{false};
1345 if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1347 mInverseBindMatrices[myIndex] = invBindMatrix;
1351 auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
1352 if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1354 // ...And only then parse children.
1355 if(auto children = node->GetChild("children"))
1357 inOutParentStack.push_back(myIndex);
1359 rawDef->mChildren.reserve(children->Size());
1361 uint32_t iChild = 0;
1362 for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1364 auto& child = (*j0).second;
1365 if(child.GetType() == TreeNode::INTEGER)
1367 ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1371 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1375 inOutParentStack.pop_back();
1377 else if(rawDef->mCustomization)
1379 mOnError(FormatString("node %d: not an actual customization without children.", index));
1382 if(auto proc = params.input.mNodePropertyProcessor) // optional processing
1384 // WARNING: constraint IDs are not resolved at this point.
1385 Property::Map nodeData;
1386 ParseProperties(*node, nodeData);
1387 proc(*rawDef, std::move(nodeData), mOnError);
1392 ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1397 void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1399 auto& definitions = params.output.mAnimationDefinitions;
1400 definitions.reserve(definitions.size() + tnAnimations->Size());
1402 for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1406 const TreeNode& tnAnim = (*iAnim).second;
1407 AnimationDefinition animDef;
1408 ReadString(tnAnim.GetChild(NAME), animDef.mName);
1410 auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
1411 return ad0.mName < ad1.mName;
1413 const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1416 mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1419 // Duration -- We need something that animated properties' delay / duration can
1420 // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1421 // than our frame delay) to not be restrictive WRT replaying. If anything needs
1422 // to occur more frequently, then Animations are likely not your solution anyway.
1423 animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1424 if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1426 mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1427 animDef.mName.c_str(),
1429 animDef.mDuration));
1432 // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1433 animDef.mLoopCount = 1;
1434 if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1435 animDef.mLoopCount < 0)
1437 animDef.mLoopCount = 0;
1440 std::string endAction;
1441 if(ReadString(tnAnim.GetChild("endAction"), endAction))
1443 if("BAKE" == endAction)
1445 animDef.mEndAction = Animation::BAKE;
1447 else if("DISCARD" == endAction)
1449 animDef.mEndAction = Animation::DISCARD;
1451 else if("BAKE_FINAL" == endAction)
1453 animDef.mEndAction = Animation::BAKE_FINAL;
1457 if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1459 if("BAKE" == endAction)
1461 animDef.mDisconnectAction = Animation::BAKE;
1463 else if("DISCARD" == endAction)
1465 animDef.mDisconnectAction = Animation::DISCARD;
1467 else if("BAKE_FINAL" == endAction)
1469 animDef.mDisconnectAction = Animation::BAKE_FINAL;
1473 if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1475 animDef.mProperties.reserve(tnProperties->Size());
1476 for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1477 iProperty != iPropertyEnd;
1480 const TreeNode& tnProperty = (*iProperty).second;
1482 AnimatedProperty animProp;
1483 if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1485 mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1489 if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1491 mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1495 // these are the defaults
1496 animProp.mTimePeriod.delaySeconds = 0.f;
1497 animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1498 if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1500 mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1501 animDef.mName.c_str(),
1502 animDef.mProperties.size(),
1503 animProp.mTimePeriod.durationSeconds));
1506 std::string alphaFunctionValue;
1507 if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1509 animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1512 if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1514 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1516 std::ifstream binAniFile;
1517 std::string animationFilename;
1518 if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1520 std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
1521 binAniFile.open(animationFullPath, std::ios::binary);
1522 if(binAniFile.fail())
1524 ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1529 ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1530 DALI_ASSERT_ALWAYS(byteOffset >= 0);
1532 binAniFile.seekg(byteOffset, std::ios::beg);
1535 ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1536 DALI_ASSERT_ALWAYS(numKeys >= 0);
1538 animProp.mKeyFrames = KeyFrames::New();
1540 //In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1541 //so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1542 // otherwise are blend shape weight keys.
1543 // TODO support for binary header with size information
1544 Property::Type propType = Property::FLOAT; // assume blend shape weights
1545 if(animProp.mPropertyName == "orientation")
1547 propType = Property::VECTOR4;
1549 else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1551 propType = Property::VECTOR3;
1554 //alphafunction is reserved for future implementation
1555 // NOTE: right now we're just using AlphaFunction::LINEAR.
1556 unsigned char dummyAlphaFunction;
1559 Property::Value propValue;
1560 for(int key = 0; key < numKeys; key++)
1562 binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1563 if(propType == Property::VECTOR3)
1566 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1567 propValue = Property::Value(value);
1569 else if(propType == Property::VECTOR4)
1572 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1573 propValue = Property::Value(Quaternion(value));
1578 binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1579 propValue = Property::Value(value);
1582 binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1584 animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1587 else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1589 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1590 animProp.mKeyFrames = KeyFrames::New();
1592 float progress = 0.0f;
1593 for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1595 const TreeNode::KeyNodePair& kfKeyChild = *i0;
1596 bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1597 DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1599 const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1600 DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1602 // For the "orientation" property, convert from Vector4 -> Rotation value
1603 // This work-around is preferable to a null-pointer exception in the DALi update thread
1604 Property::Value propValue(ReadPropertyValue(*tnValue));
1605 if(propValue.GetType() == Property::VECTOR4 &&
1606 animProp.mPropertyName == "orientation")
1610 propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1613 AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1614 std::string alphaFuncStr;
1615 if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1617 kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1620 animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1625 const TreeNode* tnValue = tnProperty.GetChild("value");
1628 animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1632 mOnError(FormatString("Property '%s' fails to define target value.",
1633 animProp.mPropertyName.c_str()));
1636 ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1639 animDef.mProperties.push_back(std::move(animProp));
1645 *iFind = std::move(animDef);
1649 iFind = definitions.insert(iFind, std::move(animDef));
1652 if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
1655 ParseProperties(tnAnim, map);
1656 proc(animDef, std::move(map), mOnError);
1661 void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1663 auto& animGroups = params.output.mAnimationGroupDefinitions;
1666 for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1667 iGroups != iGroupsEnd;
1668 ++iGroups, ++numGroups)
1670 const auto& tnGroup = *iGroups;
1671 auto tnName = tnGroup.second.GetChild(NAME);
1672 std::string groupName;
1673 if(!tnName || !ReadString(tnName, groupName))
1675 mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1679 auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) {
1680 return group.mName < name;
1682 if(iFind != animGroups.end() && iFind->mName == groupName)
1684 mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1688 iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1691 iFind->mName = groupName;
1693 auto tnAnims = tnGroup.second.GetChild("animations");
1694 if(tnAnims && tnAnims->Size() > 0)
1696 auto& anims = iFind->mAnimations;
1697 anims.reserve(anims.size() + tnAnims->Size());
1698 for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1700 anims.push_back((*iAnims).second.GetString());
1706 void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
1708 if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1710 cameras.resize(jsonCameras->Size());
1711 auto iCamera = cameras.begin();
1712 for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1714 auto& jsonCamera = (*i0).second;
1716 ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
1717 ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1718 ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1719 if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
1721 iCamera->isPerspective = false;
1724 if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1726 ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1734 void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
1736 if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1738 lights.resize(jsonLights->Size());
1739 auto iLight = lights.begin();
1740 for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1742 auto& jsonLight = (*i0).second;
1743 if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1746 FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1747 std::distance(jsonLights->CBegin(), i0)));
1751 int shadowMapSize = 0;
1752 if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1755 FormatString("Failed to parse light %d - %s has an invalid value.",
1756 std::distance(jsonLights->CBegin(), i0),
1760 iLight->shadowMapSize = shadowMapSize;
1762 float orthoSize = 0.f;
1763 if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1764 (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1767 FormatString("Failed to parse light %d - %s has an invalid value.",
1768 std::distance(jsonLights->CBegin(), i0),
1769 ORTHOGRAPHIC_SIZE));
1772 iLight->orthographicSize = orthoSize;
1774 if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1776 mOnError(FormatString(
1777 "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1778 std::distance(jsonLights->CBegin(), i0)));
1781 if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1783 iLight->color = Vector3::ONE; // default to white
1786 if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1788 iLight->intensity = 1.0f; // default to 1.0
1791 if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1793 iLight->shadowIntensity = 1.0f; // default to 1.0
1801 } // namespace SceneLoader