2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "dali-scene3d/public-api/loader/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-scene3d/internal/loader/json-util.h"
34 #include "dali-scene3d/public-api/loader/alpha-function-helper.h"
35 #include "dali-scene3d/public-api/loader/animation-definition.h"
36 #include "dali-scene3d/public-api/loader/blend-shape-details.h"
37 #include "dali-scene3d/public-api/loader/camera-parameters.h"
38 #include "dali-scene3d/public-api/loader/ktx-loader.h"
39 #include "dali-scene3d/public-api/loader/light-parameters.h"
40 #include "dali-scene3d/public-api/loader/load-result.h"
41 #include "dali-scene3d/public-api/loader/parse-renderer-state.h"
42 #include "dali-scene3d/public-api/loader/scene-definition.h"
43 #include "dali-scene3d/public-api/loader/skinning-details.h"
44 #include "dali-scene3d/public-api/loader/utils.h"
46 #define DLI_0_1_COMPATIBILITY
50 using namespace Toolkit;
56 namespace rs = RendererState;
60 const char* NODES = "nodes";
61 const char* SCENES = "scenes";
62 const char* NODE = "node";
63 const char* URI = "uri";
64 const char* URL = "url";
65 const char* HINTS = "hints";
66 const char* NAME("name");
67 const char* BLEND_SHAPE_HEADER("blendShapeHeader");
68 const char* BLEND_SHAPES("blendShapes");
69 const char* BLEND_SHAPE_VERSION_1_0("1.0");
70 const char* BLEND_SHAPE_VERSION_2_0("2.0");
71 const char* VERSION("version");
73 const char* const SHADOW_MAP_SIZE = "shadowMapSize";
74 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
75 const char* const PIXEL_UNITS = "px";
77 const char SLASH = '/';
79 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
81 float num[16u] = {.0f};
83 if(ReadVector(node->GetChild("matrix"), num, 16u))
86 mat.GetTransformComponents(translation, orientation, scale);
90 if(ReadVector(node->GetChild("angle"), num, 3u))
92 orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
95 if(ReadVector(node->GetChild("position"), num, 3u))
97 translation = Vector3(num);
102 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
104 return ReadBlob(node, buffer.mOffset, buffer.mLength);
107 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
109 return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
112 bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
114 if(!node || !convertColorCode)
119 color = convertColorCode(node->GetString());
124 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
126 return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
127 ReadColor(node->GetChild("color"), color);
130 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
132 if(tnRendererState.GetType() == TreeNode::INTEGER)
134 return static_cast<RendererState::Type>(tnRendererState.GetInteger());
136 else if(tnRendererState.GetType() == TreeNode::STRING)
138 return RendererState::Parse(tnRendererState.GetString());
146 ///@brief Reads arc properties.
147 void ReadArcField(const TreeNode* eArc, ArcRenderable& arc)
149 ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
150 ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
151 ReadFloat(eArc->GetChild("radius"), arc.mRadius);
153 arc.mStartAngleDegrees = .0f;
154 ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
156 arc.mEndAngleDegrees = .0f;
157 ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
160 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
163 for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
167 return &((*it).second);
173 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
175 auto child = node->GetChild(childName);
178 ExceptionFlinger flinger(ASSERT_LOCATION);
179 flinger << "Failed to find child node '" << childName << "'";
180 if(auto nodeName = node->GetName())
182 flinger << " on '" << nodeName << "'";
189 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
191 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
193 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
194 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
197 switch(kv.second.GetType())
199 case TreeNode::ARRAY:
201 Property::Array array;
202 ParseProperties(kv.second, array);
203 map.Insert(kv.first, array);
207 case TreeNode::OBJECT:
209 Property::Map innerMap;
210 ParseProperties(kv.second, innerMap);
211 map.Insert(kv.first, innerMap);
215 case TreeNode::STRING:
217 map.Insert(kv.first, kv.second.GetString());
221 case TreeNode::INTEGER:
223 map.Insert(kv.first, kv.second.GetInteger());
227 case TreeNode::BOOLEAN:
229 map.Insert(kv.first, kv.second.GetBoolean());
233 case TreeNode::FLOAT:
235 map.Insert(kv.first, kv.second.GetFloat());
239 case TreeNode::IS_NULL:
247 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
249 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
250 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
253 switch(kv.second.GetType())
255 case TreeNode::ARRAY:
257 Property::Array innerArray;
258 ParseProperties(kv.second, innerArray);
259 array.PushBack(innerArray);
263 case TreeNode::OBJECT:
266 ParseProperties(kv.second, map);
271 case TreeNode::STRING:
273 array.PushBack(kv.second.GetString());
277 case TreeNode::INTEGER:
279 array.PushBack(kv.second.GetInteger());
283 case TreeNode::BOOLEAN:
285 array.PushBack(kv.second.GetBoolean());
289 case TreeNode::FLOAT:
291 array.PushBack(kv.second.GetFloat());
295 case TreeNode::IS_NULL:
305 struct DliLoader::Impl
307 StringCallback mOnError = DefaultErrorCallback;
308 Toolkit::JsonParser mParser;
310 void ParseScene(LoadParams& params);
313 std::map<Index, Matrix> mInverseBindMatrices;
316 * @brief Due to .dli nodes being processed in depth-first traversal with orphans being
317 * ignored, features that rely on node indices (which is more compact and closer to
318 * glTF) require a mapping from .dli node indices to those in the resulting SceneDefinition.
319 * The index mapper is responsible for maintaing this mapping, and resolving node IDs
320 * once the processing of the nodes has finished.
321 * @note The resolution requires the whole scene graph to finish parsing, therefore any
322 * node extensions relying on node IDs will see the dli ID in their processor.
327 * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
329 * @return Whether the operation was successful.
331 virtual bool Map(Index iDli, Index iScene) = 0;
334 * @return The scene index for the node's @a dli index.
336 virtual Index Resolve(Index iDli) = 0;
340 * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
341 * an intermediate representation of resources and nodes.
343 void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
345 void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
346 void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
347 void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
349 void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
350 void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
352 void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
353 void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
355 void ParseShaders(const Toolkit::TreeNode* shaders, ResourceBundle& resources);
356 void ParseMeshes(const Toolkit::TreeNode* meshes, ResourceBundle& resources);
358 void GetCameraParameters(std::vector<CameraParameters>& cameras) const;
359 void GetLightParameters(std::vector<LightParameters>& lights) const;
362 DliLoader::DliLoader()
367 DliLoader::~DliLoader() = default;
369 void DliLoader::SetErrorCallback(StringCallback onError)
371 mImpl->mOnError = onError;
374 bool DliLoader::LoadScene(const std::string& uri, LoadParams& params)
376 std::string daliBuffer = LoadTextFile(uri.c_str());
378 auto& parser = mImpl->mParser;
379 parser = JsonParser::New();
380 if(!parser.Parse(daliBuffer))
385 mImpl->ParseScene(params);
389 std::string DliLoader::GetParseError() const
391 std::stringstream stream;
393 auto& parser = mImpl->mParser;
394 if(parser.ParseError())
396 stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
402 void DliLoader::Impl::ParseScene(LoadParams& params)
404 auto& input = params.input;
405 auto& output = params.output;
407 // get index of root node.
408 auto docRoot = mParser.GetRoot();
411 // Process resources first - these are shared
412 if(auto environments = docRoot->GetChild("environment"))
414 ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
417 if(auto meshes = docRoot->GetChild("meshes"))
419 ParseMeshes(meshes, output.mResources);
422 if(auto shaders = docRoot->GetChild("shaders"))
424 ParseShaders(shaders, output.mResources);
427 if(auto materials = docRoot->GetChild("materials"))
429 ParseMaterials(materials, input.mConvertColorCode, output.mResources);
432 for(auto& c : input.mPreNodeCategoryProcessors)
434 if(auto node = docRoot->GetChild(c.first))
436 Property::Array array;
437 ParseProperties(*node, array);
438 c.second(std::move(array), mOnError);
443 Index iScene = 0; // default scene
444 ReadIndex(docRoot->GetChild("scene"), iScene);
446 auto tnScenes = RequireChild(docRoot, "scenes");
447 auto tnNodes = RequireChild(docRoot, "nodes");
448 ParseSceneInternal(iScene, tnScenes, tnNodes, params);
450 ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
452 output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
453 output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
455 // Ger cameras and lights
456 GetCameraParameters(output.mCameraParameters);
457 GetLightParameters(output.mLightParameters);
459 // Post-node processors and animations last
460 for(auto& c : input.mPostNodeCategoryProcessors)
462 if(auto node = docRoot->GetChild(c.first))
464 Property::Array array;
465 ParseProperties(*node, array);
466 c.second(std::move(array), mOnError);
470 if(auto animations = docRoot->GetChild("animations"))
472 ParseAnimations(animations, params);
475 if(!output.mAnimationDefinitions.empty())
477 if(auto animationGroups = docRoot->GetChild("animationGroups"))
479 ParseAnimationGroups(animationGroups, params);
485 void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
487 auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
488 auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
491 ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
494 tn = RequireChild(tn, NODES); // now a "nodes" array
495 if(tn->GetType() != TreeNode::ARRAY)
497 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
502 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
505 tn = GetNthChild(tn, 0); // now the first element of the array
507 if(!ReadIndex(tn, iRootNode))
509 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
512 if(iRootNode >= tnNodes->Size())
514 ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
517 tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
518 if(tn->GetType() != TreeNode::OBJECT)
520 ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
526 Index iRootNode = getSceneRootIdx(iScene);
527 ParseNodes(tnNodes, iRootNode, params);
529 auto& scene = params.output.mScene;
530 scene.AddRootNode(0);
532 for(Index i = 0; i < iScene; ++i)
534 Index iRootNode = getSceneRootIdx(i);
535 const Index iRoot = scene.GetNodeCount();
536 ParseNodes(tnNodes, iRootNode, params);
537 scene.AddRootNode(iRoot);
540 auto numScenes = tnScenes->Size();
541 for(Index i = iScene + 1; i < numScenes; ++i)
543 Index iRootNode = getSceneRootIdx(i);
544 const Index iRoot = scene.GetNodeCount();
545 ParseNodes(tnNodes, iRootNode, params);
546 scene.AddRootNode(iRoot);
550 void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
554 auto iStart = skeletons->CBegin();
555 for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
557 auto& node = (*i0).second;
558 std::string skeletonRootName;
559 if(ReadString(node.GetChild(NODE), skeletonRootName))
561 SkeletonDefinition skeleton;
562 if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
564 ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
567 uint32_t jointCount = 0;
568 std::function<void(Index)> visitFn;
569 auto& ibms = mInverseBindMatrices;
570 visitFn = [&](Index id) {
571 auto node = scene.GetNode(id);
572 jointCount += ibms.find(id) != ibms.end();
574 for(auto i : node->mChildren)
579 visitFn(skeleton.mRootNodeIdx);
581 if(jointCount > Skinning::MAX_JOINTS)
583 mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
584 jointCount = Skinning::MAX_JOINTS;
587 skeleton.mJoints.reserve(jointCount);
589 visitFn = [&](Index id) {
590 auto iFind = ibms.find(id);
591 if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
593 skeleton.mJoints.push_back({id, iFind->second});
596 auto node = scene.GetNode(id);
597 for(auto i : node->mChildren)
602 visitFn(skeleton.mRootNodeIdx);
604 resources.mSkeletons.push_back(std::move(skeleton));
608 ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
614 void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBundle& resources)
616 Matrix cubeOrientation(Matrix::IDENTITY);
618 for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
620 auto& node = (*i0).second;
622 EnvironmentDefinition envDef;
623 ReadString(node.GetChild("cubeSpecular"), envDef.mSpecularMapPath);
624 ReadString(node.GetChild("cubeDiffuse"), envDef.mDiffuseMapPath);
625 ToUnixFileSeparators(envDef.mSpecularMapPath);
626 ToUnixFileSeparators(envDef.mDiffuseMapPath);
627 envDef.mIblIntensity = 1.0f;
628 ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
629 if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
631 envDef.mCubeOrientation = Quaternion(cubeOrientation);
634 resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
637 // NOTE: guarantees environmentMaps to have an empty environment.
638 if(resources.mEnvironmentMaps.empty())
640 resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
644 void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
646 uint32_t iShader = 0;
647 for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
649 auto& node = (*i0).second;
650 ShaderDefinition shaderDef;
651 ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
653 // Read shader hints. Possible values are:
654 // Don't define for No hints.
655 // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
656 // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
658 ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
660 if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
661 ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
663 ToUnixFileSeparators(shaderDef.mVertexShaderPath);
664 ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
666 for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
668 const TreeNode::KeyNodePair& keyValue = *j0;
669 const std::string& key = keyValue.first;
670 const TreeNode& value = keyValue.second;
672 Property::Value uniformValue;
673 if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
677 else if(key.compare("rendererState") == 0)
679 shaderDef.mRendererState = ReadRendererState(keyValue.second);
681 else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
684 ReadFloat(&value, f);
687 else if(value.GetType() == TreeNode::BOOLEAN)
689 DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
691 if(ReadBool(&keyValue.second, value))
693 uniformValue = value ? 1.0f : 0.0f;
697 switch(auto size = GetNumericalArraySize(&value))
702 ReadVector(&value, m.AsFloat(), size);
710 ReadVector(&value, m.AsFloat(), size);
718 ReadVector(&value, v.AsFloat(), size);
726 ReadVector(&value, v.AsFloat(), size);
734 ReadVector(&value, v.AsFloat(), size);
740 mOnError(FormatString(
741 "shader %u: Ignoring uniform '%s': failed to infer type from %zu elements.",
748 if(Property::NONE != uniformValue.GetType())
750 shaderDef.mUniforms.Insert(key, uniformValue);
754 resources.mShaders.emplace_back(std::move(shaderDef), Shader());
758 ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
763 void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
765 for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
767 auto& node = (*i0).second;
769 MeshDefinition meshDef;
770 if(!ReadString(node.GetChild(URI), meshDef.mUri))
772 ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
775 ToUnixFileSeparators(meshDef.mUri);
777 std::string primitive;
778 if(ReadString(node.GetChild("primitive"), primitive))
780 if(primitive == "LINES")
782 meshDef.mPrimitiveType = Geometry::LINES;
784 else if(primitive == "POINTS")
786 meshDef.mPrimitiveType = Geometry::POINTS;
788 else if(primitive != "TRIANGLES")
790 mOnError(FormatString(
791 "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
792 resources.mMeshes.size(),
798 if(ReadInt(node.GetChild("attributes"), attributes))
800 if(MaskMatch(attributes, MeshDefinition::INDICES) &&
801 !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
803 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
804 resources.mMeshes.size(),
808 if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
809 !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
811 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
812 resources.mMeshes.size(),
816 if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
817 !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
819 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
822 if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
823 !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
825 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
828 if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
829 !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
831 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
834 // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
835 if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
837 if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
838 !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
840 mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
841 resources.mMeshes.size()));
843 else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
844 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
846 mOnError(FormatString("mesh %d: Failed to read skinning information.",
847 resources.mMeshes.size()));
851 if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
853 std::string blendShapeVersion;
854 ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
856 if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
858 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
860 else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
862 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
865 switch(meshDef.mBlendShapeVersion)
867 case BlendShapes::Version::VERSION_1_0:
868 case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
870 ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
881 if(auto blendShapes = node.GetChild(BLEND_SHAPES))
883 meshDef.mBlendShapes.resize(blendShapes->Size());
886 for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
888 // Each blend shape is stored as the difference with the original mesh.
890 auto& blendShapeNode = (*it).second;
892 auto& blendShape = meshDef.mBlendShapes[index];
893 ReadString(blendShapeNode.GetChild("name"), blendShape.name);
894 if(auto position = blendShapeNode.GetChild("positions"))
896 ReadAttribAccessor(position, blendShape.deltas);
898 if(auto normals = blendShapeNode.GetChild("normals"))
900 ReadAttribAccessor(normals, blendShape.normals);
902 if(auto tangents = blendShapeNode.GetChild("tangents"))
904 ReadAttribAccessor(tangents, blendShape.tangents);
906 ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
911 if(ReadBool(node.GetChild("flipV"), flipV))
913 meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
916 resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
921 void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
923 for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
925 auto& node = (*i0).second;
927 MaterialDefinition materialDef;
928 if(auto eEnvironment = node.GetChild("environment"))
930 ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
931 if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
933 ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
937 // TODO : need to consider AGIF
938 std::vector<std::string> texturePaths;
939 std::string texturePath;
940 if(ReadString(node.GetChild("albedoMap"), texturePath))
942 ToUnixFileSeparators(texturePath);
943 const auto semantic = MaterialDefinition::ALBEDO;
944 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
945 materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
947 if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
949 ToUnixFileSeparators(texturePath);
951 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
953 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
956 const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
957 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
958 materialDef.mFlags |= semantic;
961 if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
963 ToUnixFileSeparators(texturePath);
965 if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
967 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
970 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
971 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
972 materialDef.mFlags |= semantic |
973 // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
974 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
977 if(ReadString(node.GetChild("normalMap"), texturePath))
979 ToUnixFileSeparators(texturePath);
981 const auto semantic = MaterialDefinition::NORMAL;
982 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
983 materialDef.mFlags |= semantic |
984 // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
985 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
988 if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
990 ToUnixFileSeparators(texturePath);
992 if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
994 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
997 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
999 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
1002 if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1004 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1007 const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1008 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1009 materialDef.mFlags |= semantic;
1012 if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1014 ToUnixFileSeparators(texturePath);
1016 const auto semantic = MaterialDefinition::SUBSURFACE;
1017 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1018 materialDef.mFlags |= semantic;
1021 if(ReadString(node.GetChild("occlusionMap"), texturePath))
1023 ToUnixFileSeparators(texturePath);
1024 const auto semantic = MaterialDefinition::OCCLUSION;
1025 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1026 materialDef.mFlags |= semantic;
1029 if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1030 materialDef.mColor.a < 1.0f)
1032 materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1035 ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1036 ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1039 if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1041 for(auto& ts : materialDef.mTextureStages)
1043 ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1047 resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1051 void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1053 std::vector<Index> parents;
1056 struct IndexMapper : IIndexMapper
1058 IndexMapper(size_t numNodes)
1060 mIndices.reserve(numNodes);
1063 virtual bool Map(Index iDli, Index iScene) override
1065 Entry idx{iDli, iScene};
1066 auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1067 if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1069 mIndices.insert(iInsert, idx);
1071 else if(iInsert->iScene != iScene)
1078 virtual unsigned int Resolve(Index iDli) override
1080 auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) { return idx.iDli < iDli; });
1081 DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1082 return iFind->iScene;
1089 unsigned int iScene;
1091 bool operator<(const Entry& other) const
1093 return iDli < other.iDli;
1096 std::vector<Entry> mIndices;
1097 } mapper(nodes->Size());
1098 ParseNodesInternal(nodes, index, parents, params, mapper);
1100 auto& scene = params.output.mScene;
1101 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1103 for(auto& c : scene.GetNode(i0)->mConstraints)
1105 c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1110 void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1112 // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1113 struct IndexProperty
1115 ResourceType::Value type;
1116 const TreeNode* source;
1119 std::vector<IndexProperty> resourceIds;
1120 resourceIds.reserve(4);
1122 if(auto node = GetNthChild(nodes, index))
1124 NodeDefinition nodeDef;
1125 nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1128 ReadString(node->GetChild(NAME), nodeDef.mName);
1131 ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1133 // Reads the size of the node.
1135 // * It can be given as 'size' or 'bounds'.
1136 // * The sdk saves the 'size' as a vector2 in some cases.
1137 // * To avoid size related issues the following code attemps
1138 // to read the 'size/bounds' as a vector3 first, if it's
1139 // not successful then reads it as a vector2.
1140 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1141 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1142 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1143 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1146 ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1148 // type classification
1149 if(auto eCustomization = node->GetChild("customization")) // customization
1152 if(ReadString(eCustomization->GetChild("tag"), tag))
1154 nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
1157 else // something renderable maybe
1159 std::unique_ptr<NodeDefinition::Renderable> renderable;
1160 ModelRenderable* modelRenderable = nullptr; // no ownership, aliasing renderable for the right type.
1162 const TreeNode* eRenderable = nullptr;
1163 if((eRenderable = node->GetChild("model")))
1165 // check for mesh before allocating - this can't be missing.
1166 auto eMesh = eRenderable->GetChild("mesh");
1169 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1172 modelRenderable = new ModelRenderable();
1173 renderable.reset(modelRenderable);
1175 resourceIds.push_back({ResourceType::Mesh, eMesh, modelRenderable->mMeshIdx});
1177 else if((eRenderable = node->GetChild("arc")))
1179 // check for mesh before allocating - this can't be missing.
1180 auto eMesh = eRenderable->GetChild("mesh");
1183 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1186 auto arcRenderable = new ArcRenderable;
1187 renderable.reset(arcRenderable);
1188 modelRenderable = arcRenderable;
1190 resourceIds.push_back({ResourceType::Mesh, eMesh, arcRenderable->mMeshIdx});
1192 ReadArcField(eRenderable, *arcRenderable);
1195 if(renderable && eRenderable != nullptr) // process common properties of all renderables + register payload
1198 renderable->mShaderIdx = 0;
1199 auto eShader = eRenderable->GetChild("shader");
1202 resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1208 modelRenderable->mMaterialIdx = 0; // must offer default of 0
1209 auto eMaterial = eRenderable->GetChild("material");
1212 resourceIds.push_back({ResourceType::Material, eMaterial, modelRenderable->mMaterialIdx});
1215 if(!ReadColorCodeOrColor(eRenderable, modelRenderable->mColor, params.input.mConvertColorCode))
1217 ReadColorCodeOrColor(node, modelRenderable->mColor, params.input.mConvertColorCode);
1221 nodeDef.mRenderables.push_back(std::move(renderable));
1225 // Resolve ints - default to 0 if undefined
1226 auto& output = params.output;
1227 for(auto& idRes : resourceIds)
1232 case ResourceType::Shader:
1233 iCheck = output.mResources.mShaders.size();
1236 case ResourceType::Mesh:
1237 iCheck = output.mResources.mMeshes.size();
1240 case ResourceType::Material:
1241 iCheck = output.mResources.mMaterials.size();
1245 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1252 else if(idRes.source->GetType() != TreeNode::INTEGER)
1254 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1258 idRes.target = idRes.source->GetInteger();
1261 if(idRes.target >= iCheck)
1263 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1266 resourceIds.clear();
1269 if(auto eExtras = node->GetChild("extras"))
1271 auto& extras = nodeDef.mExtras;
1272 extras.reserve(eExtras->Size());
1274 for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1276 NodeDefinition::Extra e;
1279 e.mKey = eExtra.first;
1282 mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1288 e.mValue = ReadPropertyValue(eExtra.second);
1289 if(e.mValue.GetType() == Property::Type::NONE)
1291 mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1294 eExtra.second.GetString()));
1298 auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1299 if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1301 mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1304 eExtra.second.GetString()));
1305 *iInsert = std::move(e);
1309 extras.insert(iInsert, e);
1316 if(auto eConstraints = node->GetChild("constraints"))
1318 auto& constraints = nodeDef.mConstraints;
1319 constraints.reserve(eConstraints->Size());
1321 ConstraintDefinition cDef;
1322 for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1324 auto eConstraint = *i0;
1325 if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1327 mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1329 eConstraint.second.GetString(),
1330 constraints.size()));
1334 cDef.mProperty = eConstraint.first;
1336 auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1337 if(iInsert != constraints.end() && *iInsert == cDef)
1339 mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1341 cDef.mProperty.c_str(),
1346 constraints.insert(iInsert, cDef);
1352 // Determine index for mapping
1353 const unsigned int myIndex = output.mScene.GetNodeCount();
1354 if(!mapper.Map(index, myIndex))
1356 mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree.", index, myIndex));
1360 // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1361 Matrix invBindMatrix{false};
1362 if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1364 mInverseBindMatrices[myIndex] = invBindMatrix;
1368 auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
1369 if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1371 // ...And only then parse children.
1372 if(auto children = node->GetChild("children"))
1374 inOutParentStack.push_back(myIndex);
1376 rawDef->mChildren.reserve(children->Size());
1378 uint32_t iChild = 0;
1379 for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1381 auto& child = (*j0).second;
1382 if(child.GetType() == TreeNode::INTEGER)
1384 ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1388 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1392 inOutParentStack.pop_back();
1394 else if(rawDef->mCustomization)
1396 mOnError(FormatString("node %d: not an actual customization without children.", index));
1399 if(auto proc = params.input.mNodePropertyProcessor) // optional processing
1401 // WARNING: constraint IDs are not resolved at this point.
1402 Property::Map nodeData;
1403 ParseProperties(*node, nodeData);
1404 proc(*rawDef, std::move(nodeData), mOnError);
1409 ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1414 void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1416 auto& definitions = params.output.mAnimationDefinitions;
1417 definitions.reserve(definitions.size() + tnAnimations->Size());
1419 for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1423 const TreeNode& tnAnim = (*iAnim).second;
1424 AnimationDefinition animDef;
1425 ReadString(tnAnim.GetChild(NAME), animDef.mName);
1427 auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { return ad0.mName < ad1.mName; });
1428 const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1431 mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1434 // Duration -- We need something that animated properties' delay / duration can
1435 // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1436 // than our frame delay) to not be restrictive WRT replaying. If anything needs
1437 // to occur more frequently, then Animations are likely not your solution anyway.
1438 animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1439 if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1441 mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1442 animDef.mName.c_str(),
1444 animDef.mDuration));
1447 // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1448 animDef.mLoopCount = 1;
1449 if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1450 animDef.mLoopCount < 0)
1452 animDef.mLoopCount = 0;
1455 std::string endAction;
1456 if(ReadString(tnAnim.GetChild("endAction"), endAction))
1458 if("BAKE" == endAction)
1460 animDef.mEndAction = Animation::BAKE;
1462 else if("DISCARD" == endAction)
1464 animDef.mEndAction = Animation::DISCARD;
1466 else if("BAKE_FINAL" == endAction)
1468 animDef.mEndAction = Animation::BAKE_FINAL;
1472 if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1474 if("BAKE" == endAction)
1476 animDef.mDisconnectAction = Animation::BAKE;
1478 else if("DISCARD" == endAction)
1480 animDef.mDisconnectAction = Animation::DISCARD;
1482 else if("BAKE_FINAL" == endAction)
1484 animDef.mDisconnectAction = Animation::BAKE_FINAL;
1488 if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1490 animDef.mProperties.reserve(tnProperties->Size());
1491 for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1492 iProperty != iPropertyEnd;
1495 const TreeNode& tnProperty = (*iProperty).second;
1497 AnimatedProperty animProp;
1498 if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1500 mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1504 if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1506 mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1510 // these are the defaults
1511 animProp.mTimePeriod.delaySeconds = 0.f;
1512 animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1513 if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1515 mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1516 animDef.mName.c_str(),
1517 animDef.mProperties.size(),
1518 animProp.mTimePeriod.durationSeconds));
1521 std::string alphaFunctionValue;
1522 if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1524 animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1527 if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1529 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1531 std::ifstream binAniFile;
1532 std::string animationFilename;
1533 if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1535 std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
1536 binAniFile.open(animationFullPath, std::ios::binary);
1537 if(binAniFile.fail())
1539 ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1544 ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1545 DALI_ASSERT_ALWAYS(byteOffset >= 0);
1547 binAniFile.seekg(byteOffset, std::ios::beg);
1550 ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1551 DALI_ASSERT_ALWAYS(numKeys >= 0);
1553 animProp.mKeyFrames = KeyFrames::New();
1555 // In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1556 // so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1557 // otherwise are blend shape weight keys.
1558 // TODO support for binary header with size information
1559 Property::Type propType = Property::FLOAT; // assume blend shape weights
1560 if(animProp.mPropertyName == "orientation")
1562 propType = Property::VECTOR4;
1564 else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1566 propType = Property::VECTOR3;
1569 // alphafunction is reserved for future implementation
1570 // NOTE: right now we're just using AlphaFunction::LINEAR.
1571 unsigned char dummyAlphaFunction;
1574 Property::Value propValue;
1575 for(int key = 0; key < numKeys; key++)
1577 binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1578 if(propType == Property::VECTOR3)
1581 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1582 propValue = Property::Value(value);
1584 else if(propType == Property::VECTOR4)
1587 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1588 propValue = Property::Value(Quaternion(value));
1593 binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1594 propValue = Property::Value(value);
1597 binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1599 animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1602 else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1604 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1605 animProp.mKeyFrames = KeyFrames::New();
1607 float progress = 0.0f;
1608 for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1610 const TreeNode::KeyNodePair& kfKeyChild = *i0;
1611 bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1612 DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1614 const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1615 DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1617 // For the "orientation" property, convert from Vector4 -> Rotation value
1618 // This work-around is preferable to a null-pointer exception in the DALi update thread
1619 Property::Value propValue(ReadPropertyValue(*tnValue));
1620 if(propValue.GetType() == Property::VECTOR4 &&
1621 animProp.mPropertyName == "orientation")
1625 propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1628 AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1629 std::string alphaFuncStr;
1630 if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1632 kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1635 animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1640 const TreeNode* tnValue = tnProperty.GetChild("value");
1643 animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1644 ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1648 mOnError(FormatString("Property '%s' fails to define target value.",
1649 animProp.mPropertyName.c_str()));
1653 animDef.mProperties.push_back(std::move(animProp));
1659 *iFind = std::move(animDef);
1663 iFind = definitions.insert(iFind, std::move(animDef));
1666 if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
1669 ParseProperties(tnAnim, map);
1670 proc(animDef, std::move(map), mOnError);
1675 void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1677 auto& animGroups = params.output.mAnimationGroupDefinitions;
1680 for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1681 iGroups != iGroupsEnd;
1682 ++iGroups, ++numGroups)
1684 const auto& tnGroup = *iGroups;
1685 auto tnName = tnGroup.second.GetChild(NAME);
1686 std::string groupName;
1687 if(!tnName || !ReadString(tnName, groupName))
1689 mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1693 auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) { return group.mName < name; });
1694 if(iFind != animGroups.end() && iFind->mName == groupName)
1696 mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1700 iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1703 iFind->mName = groupName;
1705 auto tnAnims = tnGroup.second.GetChild("animations");
1706 if(tnAnims && tnAnims->Size() > 0)
1708 auto& anims = iFind->mAnimations;
1709 anims.reserve(anims.size() + tnAnims->Size());
1710 for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1712 anims.push_back((*iAnims).second.GetString());
1718 void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
1720 if(mParser.GetRoot())
1722 if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1724 float dummyFloatArray[4];
1726 cameras.resize(jsonCameras->Size());
1727 auto iCamera = cameras.begin();
1728 for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1730 auto& jsonCamera = (*i0).second;
1732 ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
1733 ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1734 ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1735 if(ReadVector(jsonCamera.GetChild("orthographic"), dummyFloatArray, 4u))
1737 iCamera->isPerspective = false;
1739 iCamera->orthographicSize = dummyFloatArray[2] * 0.5f;
1740 iCamera->aspectRatio = dummyFloatArray[1] / dummyFloatArray[2];
1743 if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1745 ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1754 void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
1756 if(mParser.GetRoot())
1758 if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1760 lights.resize(jsonLights->Size());
1761 auto iLight = lights.begin();
1762 for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1764 auto& jsonLight = (*i0).second;
1765 if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1768 FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1769 std::distance(jsonLights->CBegin(), i0)));
1773 int shadowMapSize = 0;
1774 if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1777 FormatString("Failed to parse light %d - %s has an invalid value.",
1778 std::distance(jsonLights->CBegin(), i0),
1782 iLight->shadowMapSize = shadowMapSize;
1784 float orthoSize = 0.f;
1785 if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1786 (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1789 FormatString("Failed to parse light %d - %s has an invalid value.",
1790 std::distance(jsonLights->CBegin(), i0),
1791 ORTHOGRAPHIC_SIZE));
1794 iLight->orthographicSize = orthoSize;
1796 if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1798 mOnError(FormatString(
1799 "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1800 std::distance(jsonLights->CBegin(), i0)));
1803 if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1805 iLight->color = Vector3::ONE; // default to white
1808 if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1810 iLight->intensity = 1.0f; // default to 1.0
1813 if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1815 iLight->shadowIntensity = 1.0f; // default to 1.0
1824 } // namespace Loader
1825 } // namespace Scene3D