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.
17 #include "dali-scene-loader/public-api/gltf2-loader.h"
19 #include "dali-scene-loader/internal/gltf2-asset.h"
20 #include "dali-scene-loader/public-api/load-result.h"
21 #include "dali-scene-loader/public-api/resource-bundle.h"
22 #include "dali-scene-loader/public-api/scene-definition.h"
23 #include "dali-scene-loader/public-api/shader-definition-factory.h"
24 #include "dali-scene-loader/public-api/utils.h"
25 #include "dali/public-api/math/quaternion.h"
27 #define ENUM_STRING_MAPPING(t, x) \
41 const std::string POSITION_PROPERTY("position");
42 const std::string ORIENTATION_PROPERTY("orientation");
43 const std::string SCALE_PROPERTY("scale");
44 const std::string BLEND_SHAPE_WEIGHTS_UNIFORM("uBlendShapeWeight");
46 const std::string MRENDERER_MODEL_IDENTIFICATION("M-Renderer");
48 const std::string ROOT_NODE_NAME("RootNode");
49 const Vector3 SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
51 const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
57 Geometry::TRIANGLE_STRIP,
58 Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
60 struct AttributeMapping
62 gt::Attribute::Type mType;
63 MeshDefinition::Accessor MeshDefinition::*mAccessor;
64 uint16_t mElementSizeRequired;
65 } ATTRIBUTE_MAPPINGS[]{
66 {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
67 {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
68 {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
69 {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
70 {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
73 std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
76 SetRefReaderObject(proxy);
78 auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
80 for(auto& animation : results)
82 for(auto& channel : animation.mChannels)
84 channel.mSampler.UpdateVector(animation.mSamplers);
91 void ApplyAccessorMinMax(const gt::Accessor& acc, float* values)
93 DALI_ASSERT_ALWAYS(acc.mMax.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
94 DALI_ASSERT_ALWAYS(acc.mMin.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
95 MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
98 const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
99 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
100 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
102 const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
103 .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
104 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
105 .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
106 .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
107 .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
109 const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
110 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
111 .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
113 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
114 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
115 .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
116 .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
118 const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
119 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
120 .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
121 .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
123 const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
124 .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
125 gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
126 >::Accessor::mBufferView))
127 .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
128 js::Read::Number<uint32_t>,
129 >::Accessor::mByteOffset))
130 .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
131 js::Read::Enum<gt::Component::Type>,
132 >::Accessor::mComponentType))
133 .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
134 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
135 .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
136 .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
137 .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
138 .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
139 .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
141 const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
142 .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
143 .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
144 .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
145 .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
147 const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
148 .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
149 .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
150 .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
151 .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
153 const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
154 .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
155 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
157 const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
158 .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
159 .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
160 .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
161 .Register(*js::MakeProperty("strength", js::Read::Number<float>, >::TextureInfo::mStrength)));
163 const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
164 .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
165 .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
166 .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
167 .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
168 .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
170 const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
171 .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
172 .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
173 .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
174 .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
175 .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
176 .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
177 .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
178 .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff)));
180 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
182 auto& jo = js::Cast<json_object_s>(j);
183 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
188 auto jstr = *i->name;
189 result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
195 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
197 auto& jo = js::Cast<json_array_s>(j);
198 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
200 result.reserve(jo.length);
205 result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
212 const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
213 .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
214 .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
215 .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
216 .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
217 .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
219 const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
220 .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
221 .Register(*js::MakeProperty("primitives",
222 js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
223 >::Mesh::mPrimitives))
224 .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
226 const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
227 .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
228 .Register(*js::MakeProperty("inverseBindMatrices",
229 gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
230 >::Skin::mInverseBindMatrices))
231 .Register(*js::MakeProperty("skeleton",
232 gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
233 >::Skin::mSkeleton))
234 .Register(*js::MakeProperty("joints",
235 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
236 >::Skin::mJoints)));
238 const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
239 .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
240 .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
241 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
242 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
244 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
245 .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
246 .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
247 .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
248 .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
250 const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
251 .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
252 .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
253 .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
254 .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
256 const auto NODE_READER = std::move(js::Reader<gt::Node>()
257 .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
258 .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
259 .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
260 .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
261 .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
262 .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
263 .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
264 .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
265 .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
267 const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
268 .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
269 .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
270 .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
272 const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
273 .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
274 .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
276 const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
277 .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
278 .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
280 const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
281 .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
282 .Register(*js::MakeProperty("samplers",
283 js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
284 >::Animation::mSamplers))
285 .Register(*js::MakeProperty("channels",
286 js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
287 >::Animation::mChannels)));
289 const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
290 .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
291 .Register(*js::MakeProperty("nodes",
292 js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
293 >::Scene::mNodes)));
295 const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
296 .Register(*js::MakeProperty("buffers",
297 js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
298 >::Document::mBuffers))
299 .Register(*js::MakeProperty("bufferViews",
300 js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
301 >::Document::mBufferViews))
302 .Register(*js::MakeProperty("accessors",
303 js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
304 >::Document::mAccessors))
305 .Register(*js::MakeProperty("images",
306 js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
307 >::Document::mImages))
308 .Register(*js::MakeProperty("samplers",
309 js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
310 >::Document::mSamplers))
311 .Register(*js::MakeProperty("textures",
312 js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
313 >::Document::mTextures))
314 .Register(*js::MakeProperty("materials",
315 js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
316 >::Document::mMaterials))
317 .Register(*js::MakeProperty("meshes",
318 js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
319 >::Document::mMeshes))
320 .Register(*js::MakeProperty("skins",
321 js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
322 >::Document::mSkins))
323 .Register(*js::MakeProperty("cameras",
324 js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
325 >::Document::mCameras))
326 .Register(*js::MakeProperty("nodes",
327 js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
328 >::Document::mNodes))
329 .Register(*js::MakeProperty("animations",
331 >::Document::mAnimations))
332 .Register(*js::MakeProperty("scenes",
333 js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
334 >::Document::mScenes))
335 .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
343 bool operator<(const NodeMapping& mapping, Index gltfIdx)
345 return mapping.gltfIdx < gltfIdx;
348 class NodeIndexMapper
351 NodeIndexMapper() = default;
352 NodeIndexMapper(const NodeIndexMapper&) = delete;
353 NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
355 ///@brief Registers a mapping of the @a gltfIdx of a node to its @a runtimeIdx .
356 ///@note If the indices are the same, the registration is omitted, in order to
357 /// save growing a vector.
358 void RegisterMapping(Index gltfIdx, Index runtimeIdx)
360 if(gltfIdx != runtimeIdx)
362 auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
363 DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
364 mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
368 ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
369 Index GetRuntimeId(Index gltfIdx) const
371 auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
372 return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
376 std::vector<NodeMapping> mNodes;
379 struct ConversionContext
384 Index mDefaultMaterial;
386 std::vector<Index> mMeshIds;
387 NodeIndexMapper mNodeIndices;
390 SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
394 case gt::Wrap::REPEAT:
395 return SamplerFlags::WRAP_REPEAT;
396 case gt::Wrap::CLAMP_TO_EDGE:
397 return SamplerFlags::WRAP_CLAMP;
398 case gt::Wrap::MIRRORED_REPEAT:
399 return SamplerFlags::WRAP_MIRROR;
401 throw std::runtime_error("Invalid wrap type.");
405 SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
409 return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
413 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
414 // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
415 // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
416 // properties, if not in some extension -, we will simply assume linear filtering.
417 return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
418 (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
422 TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm)
424 return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)};
427 void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials)
429 MaterialDefinition matDef;
431 auto& pbr = m.mPbrMetallicRoughness;
432 if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
434 matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
437 if(m.mAlphaMode == gt::AlphaMode::MASK)
439 matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff)));
442 matDef.mColor = pbr.mBaseColorFactor;
444 matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture + !!m.mOcclusionTexture + !!m.mEmissiveTexture);
445 if(pbr.mBaseColorTexture)
447 const auto semantic = MaterialDefinition::ALBEDO;
448 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)});
449 // TODO: and there had better be one
450 matDef.mFlags |= semantic;
453 matDef.mMetallic = pbr.mMetallicFactor;
454 matDef.mRoughness = pbr.mRoughnessFactor;
456 if(pbr.mMetallicRoughnessTexture)
458 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
459 MaterialDefinition::GLTF_CHANNELS;
460 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)});
461 // TODO: and there had better be one
462 matDef.mFlags |= semantic;
467 const auto semantic = MaterialDefinition::NORMAL;
468 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)});
469 // TODO: and there had better be one
470 matDef.mFlags |= semantic;
473 // TODO: handle doubleSided
474 if(m.mOcclusionTexture)
476 const auto semantic = MaterialDefinition::OCCLUSION;
477 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mOcclusionTexture)});
478 // TODO: and there had better be one
479 matDef.mFlags |= semantic;
480 matDef.mOcclusionStrength = m.mOcclusionTexture.mStrength;
483 if(m.mEmissiveTexture)
485 const auto semantic = MaterialDefinition::EMISSIVE;
486 matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mEmissiveTexture)});
487 // TODO: and there had better be one
488 matDef.mFlags |= semantic;
489 matDef.mEmissiveFactor = m.mEmissiveFactor;
492 outMaterials.emplace_back(std::move(matDef), TextureSet());
495 void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx)
497 auto& outMaterials = cctx.mOutput.mResources.mMaterials;
498 outMaterials.reserve(doc.mMaterials.size());
500 for(auto& m : doc.mMaterials)
502 ConvertMaterial(m, outMaterials);
506 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
508 DALI_ASSERT_ALWAYS((acc.mBufferView &&
509 (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
510 (acc.mSparse && !acc.mBufferView));
512 DALI_ASSERT_ALWAYS(!acc.mSparse ||
513 ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
514 (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
516 MeshDefinition::SparseBlob sparseBlob;
519 const gt::Accessor::Sparse& sparse = *acc.mSparse;
520 const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
521 const gt::BufferViewClient& values = sparse.mValues;
523 MeshDefinition::Blob indicesBlob(
524 indices.mBufferView->mByteOffset + indices.mByteOffset,
525 sparse.mCount * indices.GetBytesPerComponent(),
526 static_cast<uint16_t>(indices.mBufferView->mByteStride),
527 static_cast<uint16_t>(indices.GetBytesPerComponent()),
530 MeshDefinition::Blob valuesBlob(
531 values.mBufferView->mByteOffset + values.mByteOffset,
532 sparse.mCount * acc.GetElementSizeBytes(),
533 static_cast<uint16_t>(values.mBufferView->mByteStride),
534 static_cast<uint16_t>(acc.GetElementSizeBytes()),
538 sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
541 uint32_t bufferViewOffset = 0u;
542 uint32_t bufferViewStride = 0u;
545 bufferViewOffset = acc.mBufferView->mByteOffset;
546 bufferViewStride = acc.mBufferView->mByteStride;
549 return MeshDefinition::Accessor{
550 std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
551 acc.GetBytesLength(),
552 static_cast<uint16_t>(bufferViewStride),
553 static_cast<uint16_t>(acc.GetElementSizeBytes()),
556 std::move(sparseBlob)};
559 void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx)
561 uint32_t meshCount = 0;
562 cctx.mMeshIds.reserve(doc.mMeshes.size());
563 for(auto& m : doc.mMeshes)
565 cctx.mMeshIds.push_back(meshCount);
566 meshCount += m.mPrimitives.size();
569 auto& outMeshes = cctx.mOutput.mResources.mMeshes;
570 outMeshes.reserve(meshCount);
571 for(auto& m : doc.mMeshes)
573 for(auto& p : m.mPrimitives)
575 MeshDefinition meshDef;
577 auto& attribs = p.mAttributes;
578 meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
579 meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode];
581 auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
582 meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
584 const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
585 for(auto& am : ATTRIBUTE_MAPPINGS)
587 auto iFind = attribs.find(am.mType);
588 if(iFind != attribs.end())
590 DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0);
591 auto& accessor = meshDef.*(am.mAccessor);
592 accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
594 // Fixing up -- a few of glTF2 sample models have VEC4 tangents; we need VEC3s.
595 if(iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired))
597 accessor.mBlob.mStride = std::max(static_cast<uint16_t>(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired),
598 accessor.mBlob.mElementSizeHint);
599 accessor.mBlob.mElementSizeHint = am.mElementSizeRequired;
602 if(iFind->first == gt::Attribute::JOINTS_0)
604 meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
605 DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
608 else if(needNormalsTangents)
612 case gt::Attribute::NORMAL:
613 meshDef.RequestNormals();
616 case gt::Attribute::TANGENT:
617 meshDef.RequestTangents();
628 meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices);
629 meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
630 DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
633 if(!p.mTargets.empty())
635 meshDef.mBlendShapes.reserve(p.mTargets.size());
636 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
637 for(const auto& target : p.mTargets)
639 MeshDefinition::BlendShape blendShape;
641 auto endIt = target.end();
642 auto it = target.find(gt::Attribute::POSITION);
645 blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
647 it = target.find(gt::Attribute::NORMAL);
650 blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
652 it = target.find(gt::Attribute::TANGENT);
655 blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
658 if(!m.mWeights.empty())
660 blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()];
663 meshDef.mBlendShapes.push_back(std::move(blendShape));
667 outMeshes.push_back({std::move(meshDef), MeshGeometry{}});
672 ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cctx)
674 auto modelNode = new ModelNode();
676 modelNode->mShaderIdx = 0; // TODO: further thought
678 auto materialIdx = prim.mMaterial.GetIndex();
679 if(INVALID_INDEX == materialIdx)
681 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
682 if(INVALID_INDEX == cctx.mDefaultMaterial)
684 auto& outMaterials = cctx.mOutput.mResources.mMaterials;
685 cctx.mDefaultMaterial = outMaterials.size();
687 ConvertMaterial(gt::Material{}, outMaterials);
690 materialIdx = cctx.mDefaultMaterial;
693 modelNode->mMaterialIdx = materialIdx;
698 void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
700 camParams.isPerspective = camera.mType.compare("perspective") == 0;
701 if(camParams.isPerspective)
703 auto& perspective = camera.mPerspective;
704 camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
705 camParams.zNear = perspective.mZNear;
706 camParams.zFar = perspective.mZFar;
707 // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
711 auto& ortho = camera.mOrthographic;
712 camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f;
713 camParams.zNear = ortho.mZNear;
714 camParams.zFar = ortho.mZFar;
718 void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx, bool isMRendererModel)
720 auto& output = cctx.mOutput;
721 auto& scene = output.mScene;
722 auto& resources = output.mResources;
724 const auto idx = scene.GetNodeCount();
725 auto weakNode = scene.AddNode([&]() {
726 std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
728 nodeDef->mParentIdx = parentIdx;
729 nodeDef->mName = node.mName;
730 if(nodeDef->mName.empty())
732 // TODO: Production quality generation of unique names.
733 nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
736 if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
738 nodeDef->mPosition = node.mTranslation;
739 nodeDef->mOrientation = node.mRotation;
740 nodeDef->mScale = node.mScale;
742 if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
744 nodeDef->mScale *= 0.01f;
752 ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
755 cctx.mNodeIndices.RegisterMapping(gltfIdx, idx);
757 Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
758 if(node.mMesh && !node.mMesh->mPrimitives.empty())
760 auto& mesh = *node.mMesh;
762 auto iPrim = mesh.mPrimitives.begin();
763 auto modelNode = MakeModelNode(*iPrim, cctx);
764 auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
765 modelNode->mMeshIdx = meshIdx;
767 weakNode->mRenderable.reset(modelNode);
769 DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
770 resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
771 resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
773 // As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es.
774 while(++iPrim != mesh.mPrimitives.end())
776 std::unique_ptr<NodeDefinition> child{new NodeDefinition};
777 child->mParentIdx = idx;
779 auto childModel = MakeModelNode(*iPrim, cctx);
782 childModel->mMeshIdx = meshIdx;
784 child->mRenderable.reset(childModel);
786 scene.AddNode(std::move(child));
788 DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
789 resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
790 resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
796 CameraParameters camParams;
797 ConvertCamera(*node.mCamera, camParams);
799 camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
800 output.mCameraParameters.push_back(camParams);
803 for(auto& n : node.mChildren)
805 ConvertNode(*n, n.GetIndex(), idx, cctx, isMRendererModel);
809 void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx, bool isMRendererModel)
811 auto& outScene = cctx.mOutput.mScene;
812 Index rootIdx = outScene.GetNodeCount();
813 switch(scene.mNodes.size())
819 ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx, isMRendererModel);
820 outScene.AddRootNode(rootIdx);
825 std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
826 sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
828 outScene.AddNode(std::move(sceneRoot));
829 outScene.AddRootNode(rootIdx);
831 for(auto& n : scene.mNodes)
833 ConvertNode(*n, n.GetIndex(), rootIdx, cctx, isMRendererModel);
840 void ConvertNodes(const gt::Document& doc, ConversionContext& cctx, bool isMRendererModel)
842 ConvertSceneNodes(*doc.mScene, cctx, isMRendererModel);
844 for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
846 ConvertSceneNodes(doc.mScenes[i], cctx, isMRendererModel);
849 for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
851 ConvertSceneNodes(doc.mScenes[i], cctx, isMRendererModel);
856 void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
858 std::ifstream animationBinaryFile(path, std::ifstream::binary);
860 if(!animationBinaryFile.is_open())
862 throw std::runtime_error("Failed to load " + path);
865 animationBinaryFile.seekg(offset);
866 animationBinaryFile.read(reinterpret_cast<char*>(dataBuffer.Begin()), size);
867 animationBinaryFile.close();
871 float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
873 inputDataBuffer.Resize(input.mCount);
874 outputDataBuffer.Resize(output.mCount);
876 const uint32_t inputDataBufferSize = input.GetBytesLength();
877 const uint32_t outputDataBufferSize = output.GetBytesLength();
879 LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
880 LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
881 ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
883 return inputDataBuffer[input.mCount - 1u];
887 float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
889 const gltf2::Accessor& input = *channel.mSampler->mInput;
890 const gltf2::Accessor& output = *channel.mSampler->mOutput;
892 Vector<float> inputDataBuffer;
893 Vector<T> outputDataBuffer;
895 const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
897 for(uint32_t i = 0; i < input.mCount; ++i)
899 keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
905 float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector<SceneLoader::AnimatedProperty>& properties)
907 const gltf2::Accessor& input = *channel.mSampler->mInput;
908 const gltf2::Accessor& output = *channel.mSampler->mOutput;
910 Vector<float> inputDataBuffer;
911 Vector<float> outputDataBuffer;
913 const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
915 char weightNameBuffer[32];
916 auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
917 char* const pWeightName = weightNameBuffer + prefixSize;
918 const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
919 for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
921 AnimatedProperty& animatedProperty = properties[propertyIndex++];
923 animatedProperty.mNodeName = nodeName;
924 snprintf(pWeightName, remainingSize, "%d]", weightIndex);
925 animatedProperty.mPropertyName = std::string(weightNameBuffer);
927 animatedProperty.mKeyFrames = KeyFrames::New();
928 for(uint32_t i = 0; i < input.mCount; ++i)
930 animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
933 animatedProperty.mTimePeriod = {0.f, duration};
939 void ConvertAnimations(const gt::Document& doc, ConversionContext& cctx)
941 auto& output = cctx.mOutput;
943 output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
945 for(const auto& animation : doc.mAnimations)
947 AnimationDefinition animationDef;
949 if(!animation.mName.empty())
951 animationDef.mName = animation.mName;
954 uint32_t numberOfProperties = 0u;
956 for(const auto& channel : animation.mChannels)
958 numberOfProperties += channel.mSampler->mOutput->mCount;
960 animationDef.mProperties.resize(numberOfProperties);
962 Index propertyIndex = 0u;
963 for(const auto& channel : animation.mChannels)
965 std::string nodeName;
966 if(!channel.mTarget.mNode->mName.empty())
968 nodeName = channel.mTarget.mNode->mName;
972 Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
973 nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
976 float duration = 0.f;
978 switch(channel.mTarget.mPath)
980 case gt::Animation::Channel::Target::TRANSLATION:
982 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
984 animatedProperty.mNodeName = nodeName;
985 animatedProperty.mPropertyName = POSITION_PROPERTY;
987 animatedProperty.mKeyFrames = KeyFrames::New();
988 duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
990 animatedProperty.mTimePeriod = {0.f, duration};
993 case gt::Animation::Channel::Target::ROTATION:
995 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
997 animatedProperty.mNodeName = nodeName;
998 animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1000 animatedProperty.mKeyFrames = KeyFrames::New();
1001 duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1003 animatedProperty.mTimePeriod = {0.f, duration};
1006 case gt::Animation::Channel::Target::SCALE:
1008 AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1010 animatedProperty.mNodeName = nodeName;
1011 animatedProperty.mPropertyName = SCALE_PROPERTY;
1013 animatedProperty.mKeyFrames = KeyFrames::New();
1014 duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1016 animatedProperty.mTimePeriod = {0.f, duration};
1019 case gt::Animation::Channel::Target::WEIGHTS:
1021 duration = LoadBlendShapeKeyFrames(cctx.mPath, channel, nodeName, propertyIndex, animationDef.mProperties);
1027 // nothing to animate.
1032 animationDef.mDuration = std::max(duration, animationDef.mDuration);
1037 output.mAnimationDefinitions.push_back(std::move(animationDef));
1041 void ProcessSkins(const gt::Document& doc, ConversionContext& cctx)
1043 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1044 // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1045 // otherwise we'll set identity matrices for inverse bind pose.
1046 struct IInverseBindMatrixProvider
1048 virtual ~IInverseBindMatrixProvider()
1051 virtual void Provide(Matrix& ibm) = 0;
1054 struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1056 std::ifstream mStream;
1057 const uint32_t mElementSizeBytes;
1059 InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
1060 : mStream(path + std::string(accessor.mBufferView->mBuffer->mUri), std::ios::binary),
1061 mElementSizeBytes(accessor.GetElementSizeBytes())
1063 DALI_ASSERT_ALWAYS(mStream);
1064 DALI_ASSERT_DEBUG(accessor.mType == gt::AccessorType::MAT4 && accessor.mComponentType == gt::Component::FLOAT);
1066 mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset);
1069 virtual void Provide(Matrix& ibm) override
1071 DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), mElementSizeBytes));
1075 struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1077 virtual void Provide(Matrix& ibm) override
1079 ibm = Matrix::IDENTITY;
1083 auto& resources = cctx.mOutput.mResources;
1084 resources.mSkeletons.reserve(doc.mSkins.size());
1086 for(auto& s : doc.mSkins)
1088 std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1089 if(s.mInverseBindMatrices)
1091 ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath));
1095 ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1098 SkeletonDefinition skeleton;
1099 if(s.mSkeleton.GetIndex() != INVALID_INDEX)
1101 skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
1104 skeleton.mJoints.resize(s.mJoints.size());
1105 auto iJoint = skeleton.mJoints.begin();
1106 for(auto& j : s.mJoints)
1108 iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex());
1110 ibmProvider->Provide(iJoint->mInverseBindMatrix);
1115 resources.mSkeletons.push_back(std::move(skeleton));
1119 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
1121 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
1123 auto nodeDef = scene.GetNode(i0);
1124 if(auto renderable = nodeDef->mRenderable.get())
1126 renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef);
1131 void SetObjectReaders()
1133 js::SetObjectReader(BUFFER_READER);
1134 js::SetObjectReader(BUFFER_VIEW_READER);
1135 js::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1136 js::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1137 js::SetObjectReader(ACCESSOR_SPARSE_READER);
1138 js::SetObjectReader(ACCESSOR_READER);
1139 js::SetObjectReader(IMAGE_READER);
1140 js::SetObjectReader(SAMPLER_READER);
1141 js::SetObjectReader(TEXURE_READER);
1142 js::SetObjectReader(TEXURE_INFO_READER);
1143 js::SetObjectReader(MATERIAL_PBR_READER);
1144 js::SetObjectReader(MATERIAL_READER);
1145 js::SetObjectReader(MESH_PRIMITIVE_READER);
1146 js::SetObjectReader(MESH_READER);
1147 js::SetObjectReader(SKIN_READER);
1148 js::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1149 js::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1150 js::SetObjectReader(CAMERA_READER);
1151 js::SetObjectReader(NODE_READER);
1152 js::SetObjectReader(ANIMATION_SAMPLER_READER);
1153 js::SetObjectReader(ANIMATION_TARGET_READER);
1154 js::SetObjectReader(ANIMATION_CHANNEL_READER);
1155 js::SetObjectReader(ANIMATION_READER);
1156 js::SetObjectReader(SCENE_READER);
1161 void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
1163 bool failed = false;
1164 auto js = LoadTextFile(url.c_str(), &failed);
1167 throw std::runtime_error("Failed to load " + url);
1170 json::unique_ptr root(json_parse(js.c_str(), js.size()));
1173 throw std::runtime_error("Failed to parse " + url);
1176 static bool setObjectReaders = true;
1177 if(setObjectReaders)
1179 // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1181 setObjectReaders = false;
1186 auto& rootObj = js::Cast<json_object_s>(*root);
1187 auto jsAsset = js::FindObjectChild("asset", rootObj);
1189 auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1192 doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1195 bool isMRendererModel(false);
1196 auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1197 if(jsAssetGenerator)
1199 doc.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1200 isMRendererModel = (doc.mAsset.mGenerator.find(MRENDERER_MODEL_IDENTIFICATION) != std::string_view::npos);
1204 gt::SetRefReaderObject(doc);
1205 DOCUMENT_READER.Read(rootObj, doc);
1207 auto path = url.substr(0, url.rfind('/') + 1);
1208 ConversionContext cctx{params, path, INVALID_INDEX};
1210 ConvertMaterials(doc, cctx);
1211 ConvertMeshes(doc, cctx);
1212 ConvertNodes(doc, cctx, isMRendererModel);
1213 ConvertAnimations(doc, cctx);
1215 ProcessSkins(doc, cctx);
1217 ProduceShaders(shaderFactory, params.mScene);
1218 params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
1221 } // namespace SceneLoader