2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-scene3d/internal/loader/gltf2-util.h>
22 #include <dali/integration-api/debug.h>
24 using namespace Dali::Scene3D::Loader;
26 namespace Dali::Scene3D::Loader::Internal
30 static constexpr std::string_view MRENDERER_MODEL_IDENTIFICATION = "M-Renderer";
31 static constexpr std::string_view POSITION_PROPERTY = "position";
32 static constexpr std::string_view ORIENTATION_PROPERTY = "orientation";
33 static constexpr std::string_view SCALE_PROPERTY = "scale";
34 static constexpr std::string_view BLEND_SHAPE_WEIGHTS_UNIFORM = "uBlendShapeWeight";
35 static constexpr std::string_view ROOT_NODE_NAME = "RootNode";
36 static const Vector3 SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
38 static const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
44 Geometry::TRIANGLE_STRIP,
45 Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
47 static struct AttributeMapping
49 gltf2::Attribute::Type mType;
50 MeshDefinition::Accessor MeshDefinition::*mAccessor;
51 uint16_t mElementSizeRequired;
52 } ATTRIBUTE_MAPPINGS[]{
53 {gltf2::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
54 {gltf2::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
55 {gltf2::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
56 {gltf2::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
57 {gltf2::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
58 {gltf2::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
61 std::vector<gltf2::Animation> ReadAnimationArray(const json_value_s& j)
63 auto results = json::Read::Array<gltf2::Animation, json::ObjectReader<gltf2::Animation>::Read>(j);
65 for(auto& animation : results)
67 for(auto& channel : animation.mChannels)
69 channel.mSampler.UpdateVector(animation.mSamplers);
76 void ApplyAccessorMinMax(const gltf2::Accessor& accessor, float* values)
78 DALI_ASSERT_ALWAYS(accessor.mMax.empty() || gltf2::AccessorType::ElementCount(accessor.mType) == accessor.mMax.size());
79 DALI_ASSERT_ALWAYS(accessor.mMin.empty() || gltf2::AccessorType::ElementCount(accessor.mType) == accessor.mMin.size());
80 MeshDefinition::Blob::ApplyMinMax(accessor.mMin, accessor.mMax, accessor.mCount, values);
83 const json::Reader<gltf2::Buffer>& GetBufferReader()
85 static const auto BUFFER_READER = std::move(json::Reader<gltf2::Buffer>()
86 .Register(*json::MakeProperty("byteLength", json::Read::Number<uint32_t>, &gltf2::Buffer::mByteLength))
87 .Register(*json::MakeProperty("uri", json::Read::StringView, &gltf2::Buffer::mUri)));
91 const json::Reader<gltf2::BufferView>& GetBufferViewReader()
93 static const auto BUFFER_VIEW_READER = std::move(json::Reader<gltf2::BufferView>()
94 .Register(*json::MakeProperty("buffer", gltf2::RefReader<gltf2::Document>::Read<gltf2::Buffer, &gltf2::Document::mBuffers>, &gltf2::BufferView::mBuffer))
95 .Register(*json::MakeProperty("byteOffset", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteOffset))
96 .Register(*json::MakeProperty("byteLength", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteLength))
97 .Register(*json::MakeProperty("byteStride", json::Read::Number<uint32_t>, &gltf2::BufferView::mByteStride))
98 .Register(*json::MakeProperty("target", json::Read::Number<uint32_t>, &gltf2::BufferView::mTarget)));
99 return BUFFER_VIEW_READER;
102 const json::Reader<gltf2::BufferViewClient>& GetBufferViewClientReader()
104 static const auto BUFFER_VIEW_CLIENT_READER = std::move(json::Reader<gltf2::BufferViewClient>()
105 .Register(*json::MakeProperty("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::BufferViewClient::mBufferView))
106 .Register(*json::MakeProperty("byteOffset", json::Read::Number<uint32_t>, &gltf2::BufferViewClient::mByteOffset)));
107 return BUFFER_VIEW_CLIENT_READER;
110 const json::Reader<gltf2::ComponentTypedBufferViewClient>& GetComponentTypedBufferViewClientReader()
112 static const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(json::Reader<gltf2::ComponentTypedBufferViewClient>()
113 .Register(*new json::Property<gltf2::ComponentTypedBufferViewClient, gltf2::Ref<gltf2::BufferView>>("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::ComponentTypedBufferViewClient::mBufferView))
114 .Register(*new json::Property<gltf2::ComponentTypedBufferViewClient, uint32_t>("byteOffset", json::Read::Number<uint32_t>, &gltf2::ComponentTypedBufferViewClient::mByteOffset))
115 .Register(*json::MakeProperty("componentType", json::Read::Enum<gltf2::Component::Type>, &gltf2::ComponentTypedBufferViewClient::mComponentType)));
116 return COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER;
119 const json::Reader<gltf2::Accessor::Sparse>& GetAccessorSparseReader()
121 static const auto ACCESSOR_SPARSE_READER = std::move(json::Reader<gltf2::Accessor::Sparse>()
122 .Register(*json::MakeProperty("count", json::Read::Number<uint32_t>, &gltf2::Accessor::Sparse::mCount))
123 .Register(*json::MakeProperty("indices", json::ObjectReader<gltf2::ComponentTypedBufferViewClient>::Read, &gltf2::Accessor::Sparse::mIndices))
124 .Register(*json::MakeProperty("values", json::ObjectReader<gltf2::BufferViewClient>::Read, &gltf2::Accessor::Sparse::mValues)));
125 return ACCESSOR_SPARSE_READER;
128 const json::Reader<gltf2::Accessor>& GetAccessorReader()
130 static const auto ACCESSOR_READER = std::move(json::Reader<gltf2::Accessor>()
131 .Register(*new json::Property<gltf2::Accessor, gltf2::Ref<gltf2::BufferView>>("bufferView",
132 gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>,
133 &gltf2::Accessor::mBufferView))
134 .Register(*new json::Property<gltf2::Accessor, uint32_t>("byteOffset",
135 json::Read::Number<uint32_t>,
136 &gltf2::Accessor::mByteOffset))
137 .Register(*new json::Property<gltf2::Accessor, gltf2::Component::Type>("componentType",
138 json::Read::Enum<gltf2::Component::Type>,
139 &gltf2::Accessor::mComponentType))
140 .Register(*new json::Property<gltf2::Accessor, std::string_view>("name", json::Read::StringView, &gltf2::Accessor::mName))
141 .Register(*json::MakeProperty("count", json::Read::Number<uint32_t>, &gltf2::Accessor::mCount))
142 .Register(*json::MakeProperty("normalized", json::Read::Boolean, &gltf2::Accessor::mNormalized))
143 .Register(*json::MakeProperty("type", gltf2::ReadStringEnum<gltf2::AccessorType>, &gltf2::Accessor::mType))
144 .Register(*json::MakeProperty("min", json::Read::Array<float, json::Read::Number>, &gltf2::Accessor::mMin))
145 .Register(*json::MakeProperty("max", json::Read::Array<float, json::Read::Number>, &gltf2::Accessor::mMax))
146 .Register(*new json::Property<gltf2::Accessor, gltf2::Accessor::Sparse>("sparse", json::ObjectReader<gltf2::Accessor::Sparse>::Read, &gltf2::Accessor::SetSparse)));
147 return ACCESSOR_READER;
150 const json::Reader<gltf2::Image>& GetImageReader()
152 static const auto IMAGE_READER = std::move(json::Reader<gltf2::Image>()
153 .Register(*new json::Property<gltf2::Image, std::string_view>("name", json::Read::StringView, &gltf2::Material::mName))
154 .Register(*json::MakeProperty("uri", json::Read::StringView, &gltf2::Image::mUri))
155 .Register(*json::MakeProperty("mimeType", json::Read::StringView, &gltf2::Image::mMimeType))
156 .Register(*json::MakeProperty("bufferView", gltf2::RefReader<gltf2::Document>::Read<gltf2::BufferView, &gltf2::Document::mBufferViews>, &gltf2::Image::mBufferView)));
160 const json::Reader<gltf2::Sampler>& GetSamplerReader()
162 static const auto SAMPLER_READER = std::move(json::Reader<gltf2::Sampler>()
163 .Register(*json::MakeProperty("minFilter", json::Read::Enum<gltf2::Filter::Type>, &gltf2::Sampler::mMinFilter))
164 .Register(*json::MakeProperty("magFilter", json::Read::Enum<gltf2::Filter::Type>, &gltf2::Sampler::mMagFilter))
165 .Register(*json::MakeProperty("wrapS", json::Read::Enum<gltf2::Wrap::Type>, &gltf2::Sampler::mWrapS))
166 .Register(*json::MakeProperty("wrapT", json::Read::Enum<gltf2::Wrap::Type>, &gltf2::Sampler::mWrapT)));
167 return SAMPLER_READER;
170 const json::Reader<gltf2::Texture>& GetTextureReader()
172 static const auto TEXURE_READER = std::move(json::Reader<gltf2::Texture>()
173 .Register(*json::MakeProperty("source", gltf2::RefReader<gltf2::Document>::Read<gltf2::Image, &gltf2::Document::mImages>, &gltf2::Texture::mSource))
174 .Register(*json::MakeProperty("sampler", gltf2::RefReader<gltf2::Document>::Read<gltf2::Sampler, &gltf2::Document::mSamplers>, &gltf2::Texture::mSampler)));
175 return TEXURE_READER;
178 const json::Reader<gltf2::TextureInfo>& GetTextureInfoReader()
180 static const auto TEXURE_INFO_READER = std::move(json::Reader<gltf2::TextureInfo>()
181 .Register(*json::MakeProperty("index", gltf2::RefReader<gltf2::Document>::Read<gltf2::Texture, &gltf2::Document::mTextures>, &gltf2::TextureInfo::mTexture))
182 .Register(*json::MakeProperty("texCoord", json::Read::Number<uint32_t>, &gltf2::TextureInfo::mTexCoord))
183 .Register(*json::MakeProperty("scale", json::Read::Number<float>, &gltf2::TextureInfo::mScale))
184 .Register(*json::MakeProperty("strength", json::Read::Number<float>, &gltf2::TextureInfo::mStrength)));
185 return TEXURE_INFO_READER;
188 const json::Reader<gltf2::Material::Pbr>& GetMaterialPbrReader()
190 static const auto MATERIAL_PBR_READER = std::move(json::Reader<gltf2::Material::Pbr>()
191 .Register(*json::MakeProperty("baseColorFactor", gltf2::ReadDaliVector<Vector4>, &gltf2::Material::Pbr::mBaseColorFactor))
192 .Register(*json::MakeProperty("baseColorTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::Pbr::mBaseColorTexture))
193 .Register(*json::MakeProperty("metallicFactor", json::Read::Number<float>, &gltf2::Material::Pbr::mMetallicFactor))
194 .Register(*json::MakeProperty("roughnessFactor", json::Read::Number<float>, &gltf2::Material::Pbr::mRoughnessFactor))
195 .Register(*json::MakeProperty("metallicRoughnessTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::Pbr::mMetallicRoughnessTexture)));
196 return MATERIAL_PBR_READER;
199 const json::Reader<gltf2::MaterialSpecular>& GetMaterialSpecularReader()
201 static const auto MATERIAL_SPECULAR_READER = std::move(json::Reader<gltf2::MaterialSpecular>()
202 .Register(*json::MakeProperty("specularFactor", json::Read::Number<float>, &gltf2::MaterialSpecular::mSpecularFactor))
203 .Register(*json::MakeProperty("specularTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::MaterialSpecular::mSpecularTexture))
204 .Register(*json::MakeProperty("specularColorFactor", gltf2::ReadDaliVector<Vector3>, &gltf2::MaterialSpecular::mSpecularColorFactor))
205 .Register(*json::MakeProperty("specularColorTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::MaterialSpecular::mSpecularColorTexture)));
206 return MATERIAL_SPECULAR_READER;
209 const json::Reader<gltf2::MaterialIor>& GetMaterialIorReader()
211 static const auto MATERIAL_IOR_READER = std::move(json::Reader<gltf2::MaterialIor>()
212 .Register(*json::MakeProperty("ior", json::Read::Number<float>, &gltf2::MaterialIor::mIor)));
213 return MATERIAL_IOR_READER;
216 const json::Reader<gltf2::MaterialExtensions>& GetMaterialExtensionsReader()
218 static const auto MATERIAL_EXTENSION_READER = std::move(json::Reader<gltf2::MaterialExtensions>()
219 .Register(*json::MakeProperty("KHR_materials_ior", json::ObjectReader<gltf2::MaterialIor>::Read, &gltf2::MaterialExtensions::mMaterialIor))
220 .Register(*json::MakeProperty("KHR_materials_specular", json::ObjectReader<gltf2::MaterialSpecular>::Read, &gltf2::MaterialExtensions::mMaterialSpecular)));
221 return MATERIAL_EXTENSION_READER;
224 const json::Reader<gltf2::Material>& GetMaterialReader()
226 static const auto MATERIAL_READER = std::move(json::Reader<gltf2::Material>()
227 .Register(*new json::Property<gltf2::Material, std::string_view>("name", json::Read::StringView, &gltf2::Material::mName))
228 .Register(*json::MakeProperty("pbrMetallicRoughness", json::ObjectReader<gltf2::Material::Pbr>::Read, &gltf2::Material::mPbrMetallicRoughness))
229 .Register(*json::MakeProperty("normalTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mNormalTexture))
230 .Register(*json::MakeProperty("occlusionTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mOcclusionTexture))
231 .Register(*json::MakeProperty("emissiveTexture", json::ObjectReader<gltf2::TextureInfo>::Read, &gltf2::Material::mEmissiveTexture))
232 .Register(*json::MakeProperty("emissiveFactor", gltf2::ReadDaliVector<Vector3>, &gltf2::Material::mEmissiveFactor))
233 .Register(*json::MakeProperty("alphaMode", gltf2::ReadStringEnum<gltf2::AlphaMode>, &gltf2::Material::mAlphaMode))
234 .Register(*json::MakeProperty("alphaCutoff", json::Read::Number<float>, &gltf2::Material::mAlphaCutoff))
235 .Register(*json::MakeProperty("doubleSided", json::Read::Boolean, &gltf2::Material::mDoubleSided))
236 .Register(*json::MakeProperty("extensions", json::ObjectReader<gltf2::MaterialExtensions>::Read, &gltf2::Material::mMaterialExtensions)));
237 return MATERIAL_READER;
240 std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
242 auto& jsonObject = json::Cast<json_object_s>(j);
243 std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>> result;
245 auto element = jsonObject.start;
248 auto jsonString = *element->name;
249 result[gltf2::Attribute::FromString(jsonString.string, jsonString.string_size)] = gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>(*element->value);
250 element = element->next;
255 std::vector<std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
257 auto& jsonObject = json::Cast<json_array_s>(j);
258 std::vector<std::map<gltf2::Attribute::Type, gltf2::Ref<gltf2::Accessor>>> result;
260 result.reserve(jsonObject.length);
262 auto element = jsonObject.start;
265 result.push_back(std::move(ReadMeshPrimitiveAttributes(*element->value)));
266 element = element->next;
272 const json::Reader<gltf2::Mesh::Primitive>& GetMeshPrimitiveReader()
274 static const auto MESH_PRIMITIVE_READER = std::move(json::Reader<gltf2::Mesh::Primitive>()
275 .Register(*json::MakeProperty("attributes", ReadMeshPrimitiveAttributes, &gltf2::Mesh::Primitive::mAttributes))
276 .Register(*json::MakeProperty("indices", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Mesh::Primitive::mIndices))
277 .Register(*json::MakeProperty("material", gltf2::RefReader<gltf2::Document>::Read<gltf2::Material, &gltf2::Document::mMaterials>, &gltf2::Mesh::Primitive::mMaterial))
278 .Register(*json::MakeProperty("mode", json::Read::Enum<gltf2::Mesh::Primitive::Mode>, &gltf2::Mesh::Primitive::mMode))
279 .Register(*json::MakeProperty("targets", ReadMeshPrimitiveTargets, &gltf2::Mesh::Primitive::mTargets)));
280 return MESH_PRIMITIVE_READER;
283 const json::Reader<gltf2::Mesh>& GetMeshReader()
285 static const auto MESH_READER = std::move(json::Reader<gltf2::Mesh>()
286 .Register(*new json::Property<gltf2::Mesh, std::string_view>("name", json::Read::StringView, &gltf2::Mesh::mName))
287 .Register(*json::MakeProperty("primitives",
288 json::Read::Array<gltf2::Mesh::Primitive, json::ObjectReader<gltf2::Mesh::Primitive>::Read>,
289 &gltf2::Mesh::mPrimitives))
290 .Register(*json::MakeProperty("weights", json::Read::Array<float, json::Read::Number>, &gltf2::Mesh::mWeights)));
294 const json::Reader<gltf2::Skin>& GetSkinReader()
296 static const auto SKIN_READER = std::move(json::Reader<gltf2::Skin>()
297 .Register(*new json::Property<gltf2::Skin, std::string_view>("name", json::Read::StringView, &gltf2::Skin::mName))
298 .Register(*json::MakeProperty("inverseBindMatrices",
299 gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>,
300 &gltf2::Skin::mInverseBindMatrices))
301 .Register(*json::MakeProperty("skeleton",
302 gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>,
303 &gltf2::Skin::mSkeleton))
304 .Register(*json::MakeProperty("joints",
305 json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>,
306 &gltf2::Skin::mJoints)));
310 const json::Reader<gltf2::Camera::Perspective>& GetCameraPerspectiveReader()
312 static const auto CAMERA_PERSPECTIVE_READER = std::move(json::Reader<gltf2::Camera::Perspective>()
313 .Register(*json::MakeProperty("aspectRatio", json::Read::Number<float>, &gltf2::Camera::Perspective::mAspectRatio))
314 .Register(*json::MakeProperty("yfov", json::Read::Number<float>, &gltf2::Camera::Perspective::mYFov))
315 .Register(*json::MakeProperty("zfar", json::Read::Number<float>, &gltf2::Camera::Perspective::mZFar))
316 .Register(*json::MakeProperty("znear", json::Read::Number<float>, &gltf2::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
317 return CAMERA_PERSPECTIVE_READER;
320 const json::Reader<gltf2::Camera::Orthographic>& GetCameraOrthographicReader()
322 static const auto CAMERA_ORTHOGRAPHIC_READER = std::move(json::Reader<gltf2::Camera::Orthographic>()
323 .Register(*json::MakeProperty("xmag", json::Read::Number<float>, &gltf2::Camera::Orthographic::mXMag))
324 .Register(*json::MakeProperty("ymag", json::Read::Number<float>, &gltf2::Camera::Orthographic::mYMag))
325 .Register(*json::MakeProperty("zfar", json::Read::Number<float>, &gltf2::Camera::Orthographic::mZFar))
326 .Register(*json::MakeProperty("znear", json::Read::Number<float>, &gltf2::Camera::Orthographic::mZNear)));
327 return CAMERA_ORTHOGRAPHIC_READER;
330 const json::Reader<gltf2::Camera>& GetCameraReader()
332 static const auto CAMERA_READER = std::move(json::Reader<gltf2::Camera>()
333 .Register(*new json::Property<gltf2::Camera, std::string_view>("name", json::Read::StringView, &gltf2::Camera::mName))
334 .Register(*json::MakeProperty("type", json::Read::StringView, &gltf2::Camera::mType))
335 .Register(*json::MakeProperty("perspective", json::ObjectReader<gltf2::Camera::Perspective>::Read, &gltf2::Camera::mPerspective))
336 .Register(*json::MakeProperty("orthographic", json::ObjectReader<gltf2::Camera::Orthographic>::Read, &gltf2::Camera::mOrthographic)));
337 return CAMERA_READER;
340 const json::Reader<gltf2::Node>& GetNodeReader()
342 static const auto NODE_READER = std::move(json::Reader<gltf2::Node>()
343 .Register(*new json::Property<gltf2::Node, std::string_view>("name", json::Read::StringView, &gltf2::Node::mName))
344 .Register(*json::MakeProperty("translation", gltf2::ReadDaliVector<Vector3>, &gltf2::Node::mTranslation))
345 .Register(*json::MakeProperty("rotation", gltf2::ReadQuaternion, &gltf2::Node::mRotation))
346 .Register(*json::MakeProperty("scale", gltf2::ReadDaliVector<Vector3>, &gltf2::Node::mScale))
347 .Register(*new json::Property<gltf2::Node, Matrix>("matrix", gltf2::ReadDaliVector<Matrix>, &gltf2::Node::SetMatrix))
348 .Register(*json::MakeProperty("camera", gltf2::RefReader<gltf2::Document>::Read<gltf2::Camera, &gltf2::Document::mCameras>, &gltf2::Node::mCamera))
349 .Register(*json::MakeProperty("children", json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>, &gltf2::Node::mChildren))
350 .Register(*json::MakeProperty("mesh", gltf2::RefReader<gltf2::Document>::Read<gltf2::Mesh, &gltf2::Document::mMeshes>, &gltf2::Node::mMesh))
351 .Register(*json::MakeProperty("skin", gltf2::RefReader<gltf2::Document>::Read<gltf2::Skin, &gltf2::Document::mSkins>, &gltf2::Node::mSkin)));
355 const json::Reader<gltf2::Animation::Sampler>& GetAnimationSamplerReader()
357 static const auto ANIMATION_SAMPLER_READER = std::move(json::Reader<gltf2::Animation::Sampler>()
358 .Register(*json::MakeProperty("input", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Animation::Sampler::mInput))
359 .Register(*json::MakeProperty("output", gltf2::RefReader<gltf2::Document>::Read<gltf2::Accessor, &gltf2::Document::mAccessors>, &gltf2::Animation::Sampler::mOutput))
360 .Register(*json::MakeProperty("interpolation", gltf2::ReadStringEnum<gltf2::Animation::Sampler::Interpolation>, &gltf2::Animation::Sampler::mInterpolation)));
361 return ANIMATION_SAMPLER_READER;
364 const json::Reader<gltf2::Animation::Channel::Target>& GetAnimationChannelTargetReader()
366 static const auto ANIMATION_TARGET_READER = std::move(json::Reader<gltf2::Animation::Channel::Target>()
367 .Register(*json::MakeProperty("node", gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>, &gltf2::Animation::Channel::Target::mNode))
368 .Register(*json::MakeProperty("path", gltf2::ReadStringEnum<gltf2::Animation::Channel::Target>, &gltf2::Animation::Channel::Target::mPath)));
369 return ANIMATION_TARGET_READER;
372 const json::Reader<gltf2::Animation::Channel>& GetAnimationChannelReader()
374 static const auto ANIMATION_CHANNEL_READER = std::move(json::Reader<gltf2::Animation::Channel>()
375 .Register(*json::MakeProperty("target", json::ObjectReader<gltf2::Animation::Channel::Target>::Read, &gltf2::Animation::Channel::mTarget))
376 .Register(*json::MakeProperty("sampler", gltf2::RefReader<gltf2::Animation>::Read<gltf2::Animation::Sampler, &gltf2::Animation::mSamplers>, &gltf2::Animation::Channel::mSampler)));
377 return ANIMATION_CHANNEL_READER;
380 const json::Reader<gltf2::Animation>& GetAnimationReader()
382 static const auto ANIMATION_READER = std::move(json::Reader<gltf2::Animation>()
383 .Register(*new json::Property<gltf2::Animation, std::string_view>("name", json::Read::StringView, &gltf2::Animation::mName))
384 .Register(*json::MakeProperty("samplers",
385 json::Read::Array<gltf2::Animation::Sampler, json::ObjectReader<gltf2::Animation::Sampler>::Read>,
386 &gltf2::Animation::mSamplers))
387 .Register(*json::MakeProperty("channels",
388 json::Read::Array<gltf2::Animation::Channel, json::ObjectReader<gltf2::Animation::Channel>::Read>,
389 &gltf2::Animation::mChannels)));
390 return ANIMATION_READER;
393 const json::Reader<gltf2::Scene>& GetSceneReader()
395 static const auto SCENE_READER = std::move(json::Reader<gltf2::Scene>()
396 .Register(*new json::Property<gltf2::Scene, std::string_view>("name", json::Read::StringView, &gltf2::Scene::mName))
397 .Register(*json::MakeProperty("nodes",
398 json::Read::Array<gltf2::Ref<gltf2::Node>, gltf2::RefReader<gltf2::Document>::Read<gltf2::Node, &gltf2::Document::mNodes>>,
399 &gltf2::Scene::mNodes)));
403 const json::Reader<gltf2::Document>& GetDocumentReader()
405 static const auto DOCUMENT_READER = std::move(json::Reader<gltf2::Document>()
406 .Register(*json::MakeProperty("buffers",
407 json::Read::Array<gltf2::Buffer, json::ObjectReader<gltf2::Buffer>::Read>,
408 &gltf2::Document::mBuffers))
409 .Register(*json::MakeProperty("bufferViews",
410 json::Read::Array<gltf2::BufferView, json::ObjectReader<gltf2::BufferView>::Read>,
411 &gltf2::Document::mBufferViews))
412 .Register(*json::MakeProperty("accessors",
413 json::Read::Array<gltf2::Accessor, json::ObjectReader<gltf2::Accessor>::Read>,
414 &gltf2::Document::mAccessors))
415 .Register(*json::MakeProperty("images",
416 json::Read::Array<gltf2::Image, json::ObjectReader<gltf2::Image>::Read>,
417 &gltf2::Document::mImages))
418 .Register(*json::MakeProperty("samplers",
419 json::Read::Array<gltf2::Sampler, json::ObjectReader<gltf2::Sampler>::Read>,
420 &gltf2::Document::mSamplers))
421 .Register(*json::MakeProperty("textures",
422 json::Read::Array<gltf2::Texture, json::ObjectReader<gltf2::Texture>::Read>,
423 &gltf2::Document::mTextures))
424 .Register(*json::MakeProperty("materials",
425 json::Read::Array<gltf2::Material, json::ObjectReader<gltf2::Material>::Read>,
426 &gltf2::Document::mMaterials))
427 .Register(*json::MakeProperty("meshes",
428 json::Read::Array<gltf2::Mesh, json::ObjectReader<gltf2::Mesh>::Read>,
429 &gltf2::Document::mMeshes))
430 .Register(*json::MakeProperty("skins",
431 json::Read::Array<gltf2::Skin, json::ObjectReader<gltf2::Skin>::Read>,
432 &gltf2::Document::mSkins))
433 .Register(*json::MakeProperty("cameras",
434 json::Read::Array<gltf2::Camera, json::ObjectReader<gltf2::Camera>::Read>,
435 &gltf2::Document::mCameras))
436 .Register(*json::MakeProperty("nodes",
437 json::Read::Array<gltf2::Node, json::ObjectReader<gltf2::Node>::Read>,
438 &gltf2::Document::mNodes))
439 .Register(*json::MakeProperty("animations",
441 &gltf2::Document::mAnimations))
442 .Register(*json::MakeProperty("scenes",
443 json::Read::Array<gltf2::Scene, json::ObjectReader<gltf2::Scene>::Read>,
444 &gltf2::Document::mScenes))
445 .Register(*json::MakeProperty("scene", gltf2::RefReader<gltf2::Document>::Read<gltf2::Scene, &gltf2::Document::mScenes>, &gltf2::Document::mScene)));
446 return DOCUMENT_READER;
449 void ConvertBuffer(const gltf2::Buffer& buffer, decltype(ResourceBundle::mBuffers)& outBuffers, const std::string& resourcePath)
451 BufferDefinition bufferDefinition;
453 bufferDefinition.mResourcePath = resourcePath;
454 bufferDefinition.mUri = buffer.mUri;
455 bufferDefinition.mByteLength = buffer.mByteLength;
457 outBuffers.emplace_back(std::move(bufferDefinition));
460 void ConvertBuffers(const gltf2::Document& document, ConversionContext& context)
462 auto& outBuffers = context.mOutput.mResources.mBuffers;
463 outBuffers.reserve(document.mBuffers.size());
465 for(auto& buffer : document.mBuffers)
467 if(buffer.mUri.empty())
471 ConvertBuffer(buffer, outBuffers, context.mPath);
475 SamplerFlags::Type ConvertWrapMode(gltf2::Wrap::Type wrapMode)
479 case gltf2::Wrap::REPEAT:
480 return SamplerFlags::WRAP_REPEAT;
481 case gltf2::Wrap::CLAMP_TO_EDGE:
482 return SamplerFlags::WRAP_CLAMP;
483 case gltf2::Wrap::MIRRORED_REPEAT:
484 return SamplerFlags::WRAP_MIRROR;
486 throw std::runtime_error("Invalid wrap type.");
490 SamplerFlags::Type ConvertSampler(const gltf2::Ref<gltf2::Sampler>& sampler)
494 return ((sampler->mMinFilter < gltf2::Filter::NEAREST_MIPMAP_NEAREST) ? (sampler->mMinFilter - gltf2::Filter::NEAREST) : ((sampler->mMinFilter - gltf2::Filter::NEAREST_MIPMAP_NEAREST) + 2)) |
495 ((sampler->mMagFilter - gltf2::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) |
496 (ConvertWrapMode(sampler->mWrapS) << SamplerFlags::WRAP_S_SHIFT) |
497 (ConvertWrapMode(sampler->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
501 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
502 // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
503 // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
504 // properties, if not in some extension -, we will simply assume linear filtering.
505 return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
506 (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
510 TextureDefinition ConvertTextureInfo(const gltf2::TextureInfo& textureInfo, ConversionContext& context, const ImageMetadata& metaData = ImageMetadata())
512 TextureDefinition textureDefinition;
513 std::string uri = std::string(textureInfo.mTexture->mSource->mUri);
516 uint32_t bufferIndex = textureInfo.mTexture->mSource->mBufferView->mBuffer.GetIndex();
517 if(bufferIndex != INVALID_INDEX && context.mOutput.mResources.mBuffers[bufferIndex].IsAvailable())
519 auto& stream = context.mOutput.mResources.mBuffers[bufferIndex].GetBufferStream();
521 stream.seekg(textureInfo.mTexture->mSource->mBufferView->mByteOffset, stream.beg);
522 std::vector<uint8_t> dataBuffer;
523 dataBuffer.resize(textureInfo.mTexture->mSource->mBufferView->mByteLength);
524 stream.read(reinterpret_cast<char*>(dataBuffer.data()), static_cast<std::streamsize>(static_cast<size_t>(textureInfo.mTexture->mSource->mBufferView->mByteLength)));
525 return TextureDefinition{std::move(dataBuffer), ConvertSampler(textureInfo.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
527 return TextureDefinition();
531 return TextureDefinition{uri, ConvertSampler(textureInfo.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
535 void AddTextureStage(uint32_t semantic, MaterialDefinition& materialDefinition, gltf2::TextureInfo textureInfo, const Dali::Scene3D::Loader::ImageMetadata& metaData, ConversionContext& context)
537 materialDefinition.mTextureStages.push_back({semantic, ConvertTextureInfo(textureInfo, context, metaData)});
538 materialDefinition.mFlags |= semantic;
541 void ConvertMaterial(const gltf2::Material& material, const std::unordered_map<std::string, ImageMetadata>& imageMetaData, decltype(ResourceBundle::mMaterials)& outMaterials, ConversionContext& context)
543 auto getTextureMetaData = [](const std::unordered_map<std::string, ImageMetadata>& metaData, const gltf2::TextureInfo& info) {
544 if(!info.mTexture->mSource->mUri.empty())
546 if(auto search = metaData.find(info.mTexture->mSource->mUri.data()); search != metaData.end())
548 return search->second;
551 return ImageMetadata();
554 MaterialDefinition materialDefinition;
556 auto& pbr = material.mPbrMetallicRoughness;
557 if(material.mAlphaMode == gltf2::AlphaMode::BLEND)
559 materialDefinition.mIsOpaque = false;
560 materialDefinition.mFlags |= MaterialDefinition::TRANSPARENCY;
562 else if(material.mAlphaMode == gltf2::AlphaMode::MASK)
564 materialDefinition.mIsMask = true;
565 materialDefinition.SetAlphaCutoff(std::min(1.f, std::max(0.f, material.mAlphaCutoff)));
568 materialDefinition.mBaseColorFactor = pbr.mBaseColorFactor;
570 materialDefinition.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!material.mNormalTexture + !!material.mOcclusionTexture + !!material.mEmissiveTexture);
571 if(pbr.mBaseColorTexture)
573 AddTextureStage(MaterialDefinition::ALBEDO, materialDefinition, pbr.mBaseColorTexture, getTextureMetaData(imageMetaData, pbr.mBaseColorTexture), context);
577 materialDefinition.mNeedAlbedoTexture = false;
580 materialDefinition.mMetallic = pbr.mMetallicFactor;
581 materialDefinition.mRoughness = pbr.mRoughnessFactor;
583 if(pbr.mMetallicRoughnessTexture)
585 AddTextureStage(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | MaterialDefinition::GLTF_CHANNELS,
587 pbr.mMetallicRoughnessTexture,
588 getTextureMetaData(imageMetaData, pbr.mMetallicRoughnessTexture),
593 materialDefinition.mNeedMetallicRoughnessTexture = false;
596 materialDefinition.mNormalScale = material.mNormalTexture.mScale;
597 if(material.mNormalTexture)
599 AddTextureStage(MaterialDefinition::NORMAL, materialDefinition, material.mNormalTexture, getTextureMetaData(imageMetaData, material.mNormalTexture), context);
603 materialDefinition.mNeedNormalTexture = false;
606 if(material.mOcclusionTexture)
608 AddTextureStage(MaterialDefinition::OCCLUSION, materialDefinition, material.mOcclusionTexture, getTextureMetaData(imageMetaData, material.mOcclusionTexture), context);
609 materialDefinition.mOcclusionStrength = material.mOcclusionTexture.mStrength;
612 materialDefinition.mEmissiveFactor = material.mEmissiveFactor;
613 if(material.mEmissiveTexture)
615 AddTextureStage(MaterialDefinition::EMISSIVE, materialDefinition, material.mEmissiveTexture, getTextureMetaData(imageMetaData, material.mEmissiveTexture), context);
618 if(!Dali::Equals(material.mMaterialExtensions.mMaterialIor.mIor, gltf2::UNDEFINED_FLOAT_VALUE))
620 float ior = material.mMaterialExtensions.mMaterialIor.mIor;
621 materialDefinition.mDielectricSpecular = powf((ior - 1.0f) / (ior + 1.0f), 2.0f);
623 materialDefinition.mSpecularFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularFactor;
624 materialDefinition.mSpecularColorFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularColorFactor;
626 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)
628 AddTextureStage(MaterialDefinition::SPECULAR, materialDefinition, material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture), context);
631 if(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)
633 AddTextureStage(MaterialDefinition::SPECULAR_COLOR, materialDefinition, material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture), context);
636 materialDefinition.mDoubleSided = material.mDoubleSided;
638 outMaterials.emplace_back(std::move(materialDefinition), TextureSet());
641 void ConvertMaterials(const gltf2::Document& document, ConversionContext& context)
643 auto& imageMetaData = context.mOutput.mSceneMetadata.mImageMetadata;
645 auto& outMaterials = context.mOutput.mResources.mMaterials;
646 outMaterials.reserve(document.mMaterials.size());
648 for(auto& material : document.mMaterials)
650 ConvertMaterial(material, imageMetaData, outMaterials, context);
654 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gltf2::Accessor& accessor)
656 DALI_ASSERT_ALWAYS((accessor.mBufferView &&
657 (accessor.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
658 (accessor.mSparse && !accessor.mBufferView));
660 DALI_ASSERT_ALWAYS(!accessor.mSparse ||
661 ((accessor.mSparse->mIndices.mBufferView && (accessor.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
662 (accessor.mSparse->mValues.mBufferView && (accessor.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
664 MeshDefinition::SparseBlob sparseBlob;
667 const gltf2::Accessor::Sparse& sparse = *accessor.mSparse;
668 const gltf2::ComponentTypedBufferViewClient& indices = sparse.mIndices;
669 const gltf2::BufferViewClient& values = sparse.mValues;
671 MeshDefinition::Blob indicesBlob(
672 indices.mBufferView->mByteOffset + indices.mByteOffset,
673 sparse.mCount * indices.GetBytesPerComponent(),
674 static_cast<uint16_t>(indices.mBufferView->mByteStride),
675 static_cast<uint16_t>(indices.GetBytesPerComponent()),
678 MeshDefinition::Blob valuesBlob(
679 values.mBufferView->mByteOffset + values.mByteOffset,
680 sparse.mCount * accessor.GetElementSizeBytes(),
681 static_cast<uint16_t>(values.mBufferView->mByteStride),
682 static_cast<uint16_t>(accessor.GetElementSizeBytes()),
686 sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), accessor.mSparse->mCount));
689 uint32_t bufferViewOffset = 0u;
690 uint32_t bufferViewStride = 0u;
691 if(accessor.mBufferView)
693 bufferViewOffset = accessor.mBufferView->mByteOffset;
694 bufferViewStride = accessor.mBufferView->mByteStride;
697 return MeshDefinition::Accessor{
698 std::move(MeshDefinition::Blob{bufferViewOffset + accessor.mByteOffset,
699 accessor.GetBytesLength(),
700 static_cast<uint16_t>(bufferViewStride),
701 static_cast<uint16_t>(accessor.GetElementSizeBytes()),
704 std::move(sparseBlob),
705 accessor.mBufferView ? accessor.mBufferView->mBuffer.GetIndex() : 0};
708 void ConvertMeshes(const gltf2::Document& document, ConversionContext& context)
710 uint32_t meshCount = 0;
711 context.mMeshIds.reserve(document.mMeshes.size());
712 for(auto& mesh : document.mMeshes)
714 context.mMeshIds.push_back(meshCount);
715 meshCount += mesh.mPrimitives.size();
718 auto& outMeshes = context.mOutput.mResources.mMeshes;
719 outMeshes.reserve(meshCount);
720 for(auto& mesh : document.mMeshes)
722 for(auto& primitive : mesh.mPrimitives)
724 MeshDefinition meshDefinition;
726 auto& attribs = primitive.mAttributes;
727 meshDefinition.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[primitive.mMode];
729 auto& accPositions = *attribs.find(gltf2::Attribute::POSITION)->second;
730 meshDefinition.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
731 // glTF2 support vector4 tangent for mesh.
732 // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
733 meshDefinition.mTangentType = Property::VECTOR4;
735 const bool needNormalsTangents = accPositions.mType == gltf2::AccessorType::VEC3;
736 for(auto& attributeMapping : ATTRIBUTE_MAPPINGS)
738 auto iFind = attribs.find(attributeMapping.mType);
739 if(iFind != attribs.end())
741 auto& accessor = meshDefinition.*(attributeMapping.mAccessor);
742 accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
744 if(iFind->first == gltf2::Attribute::JOINTS_0)
746 meshDefinition.mFlags |= (iFind->second->mComponentType == gltf2::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
747 meshDefinition.mFlags |= (iFind->second->mComponentType == gltf2::Component::UNSIGNED_BYTE) * MeshDefinition::U8_JOINT_IDS;
748 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U16_JOINT_IDS) || MaskMatch(meshDefinition.mFlags, MeshDefinition::U8_JOINT_IDS) || iFind->second->mComponentType == gltf2::Component::FLOAT);
751 else if(needNormalsTangents)
753 switch(attributeMapping.mType)
755 case gltf2::Attribute::NORMAL:
756 meshDefinition.RequestNormals();
759 case gltf2::Attribute::TANGENT:
760 meshDefinition.RequestTangents();
769 if(primitive.mIndices)
771 meshDefinition.mIndices = ConvertMeshPrimitiveAccessor(*primitive.mIndices);
772 meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
773 meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_BYTE) * MeshDefinition::U8_INDICES;
774 DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U32_INDICES) || MaskMatch(meshDefinition.mFlags, MeshDefinition::U8_INDICES) || primitive.mIndices->mComponentType == gltf2::Component::UNSIGNED_SHORT);
777 if(!primitive.mTargets.empty())
779 meshDefinition.mBlendShapes.reserve(primitive.mTargets.size());
780 meshDefinition.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
781 for(const auto& target : primitive.mTargets)
783 MeshDefinition::BlendShape blendShape;
785 auto endIt = target.end();
786 auto it = target.find(gltf2::Attribute::POSITION);
789 blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
791 it = target.find(gltf2::Attribute::NORMAL);
794 blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
796 it = target.find(gltf2::Attribute::TANGENT);
799 blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
802 if(!mesh.mWeights.empty())
804 blendShape.weight = mesh.mWeights[meshDefinition.mBlendShapes.size()];
807 meshDefinition.mBlendShapes.push_back(std::move(blendShape));
811 outMeshes.push_back({std::move(meshDefinition), MeshGeometry{}});
816 ModelRenderable* MakeModelRenderable(const gltf2::Mesh::Primitive& primitive, ConversionContext& context)
818 auto modelRenderable = new ModelRenderable();
820 modelRenderable->mShaderIdx = 0; // TODO: further thought
822 auto materialIdx = primitive.mMaterial.GetIndex();
823 if(INVALID_INDEX == materialIdx)
825 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
826 if(INVALID_INDEX == context.mDefaultMaterial)
828 auto& outMaterials = context.mOutput.mResources.mMaterials;
829 context.mDefaultMaterial = outMaterials.size();
831 ConvertMaterial(gltf2::Material{}, context.mOutput.mSceneMetadata.mImageMetadata, outMaterials, context);
834 materialIdx = context.mDefaultMaterial;
837 modelRenderable->mMaterialIdx = materialIdx;
839 return modelRenderable;
842 void ConvertCamera(const gltf2::Camera& camera, CameraParameters& cameraParameters)
844 cameraParameters.isPerspective = camera.mType.compare("perspective") == 0;
845 if(cameraParameters.isPerspective)
847 auto& perspective = camera.mPerspective;
848 if(!Dali::Equals(perspective.mYFov, gltf2::UNDEFINED_FLOAT_VALUE))
850 cameraParameters.yFovDegree = Degree(Radian(perspective.mYFov));
854 cameraParameters.yFovDegree = Degree(gltf2::UNDEFINED_FLOAT_VALUE);
856 cameraParameters.zNear = perspective.mZNear;
857 cameraParameters.zFar = perspective.mZFar;
858 // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
862 auto& ortho = camera.mOrthographic;
863 if(!Dali::Equals(ortho.mYMag, gltf2::UNDEFINED_FLOAT_VALUE) && !Dali::Equals(ortho.mXMag, gltf2::UNDEFINED_FLOAT_VALUE))
865 cameraParameters.orthographicSize = ortho.mYMag * .5f;
866 cameraParameters.aspectRatio = ortho.mXMag / ortho.mYMag;
870 cameraParameters.orthographicSize = gltf2::UNDEFINED_FLOAT_VALUE;
871 cameraParameters.aspectRatio = gltf2::UNDEFINED_FLOAT_VALUE;
873 cameraParameters.zNear = ortho.mZNear;
874 cameraParameters.zFar = ortho.mZFar;
878 void ConvertNode(gltf2::Node const& node, const Index gltfIndex, Index parentIndex, ConversionContext& context, bool isMRendererModel)
880 auto& output = context.mOutput;
881 auto& scene = output.mScene;
882 auto& resources = output.mResources;
884 const auto index = scene.GetNodeCount();
885 auto weakNode = scene.AddNode([&]() {
886 std::unique_ptr<NodeDefinition> nodeDefinition{new NodeDefinition()};
888 nodeDefinition->mParentIdx = parentIndex;
889 nodeDefinition->mName = node.mName;
890 if(nodeDefinition->mName.empty())
892 // TODO: Production quality generation of unique names.
893 nodeDefinition->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDefinition.get()));
896 if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
898 nodeDefinition->mPosition = node.mTranslation;
899 nodeDefinition->mOrientation = node.mRotation;
900 nodeDefinition->mScale = node.mScale;
902 if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
904 nodeDefinition->mScale *= 0.01f;
908 return nodeDefinition; }());
911 ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
914 context.mNodeIndices.RegisterMapping(gltfIndex, index);
916 Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
919 auto& mesh = *node.mMesh;
920 uint32_t primitiveCount = mesh.mPrimitives.size();
921 auto meshIndex = context.mMeshIds[node.mMesh.GetIndex()];
922 weakNode->mRenderables.reserve(primitiveCount);
923 for(uint32_t i = 0; i < primitiveCount; ++i)
925 std::unique_ptr<NodeDefinition::Renderable> renderable;
926 auto modelRenderable = MakeModelRenderable(mesh.mPrimitives[i], context);
927 modelRenderable->mMeshIdx = meshIndex + i;
929 DALI_ASSERT_DEBUG(resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == INVALID_INDEX ||
930 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == skeletonIdx);
931 resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx = skeletonIdx;
933 renderable.reset(modelRenderable);
934 weakNode->mRenderables.push_back(std::move(renderable));
940 CameraParameters cameraParameters;
941 ConvertCamera(*node.mCamera, cameraParameters);
943 cameraParameters.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
944 output.mCameraParameters.push_back(cameraParameters);
947 for(auto& child : node.mChildren)
949 ConvertNode(*child, child.GetIndex(), index, context, isMRendererModel);
953 void ConvertSceneNodes(const gltf2::Scene& scene, ConversionContext& context, bool isMRendererModel)
955 auto& outScene = context.mOutput.mScene;
956 Index rootIndex = outScene.GetNodeCount();
957 switch(scene.mNodes.size())
963 ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, context, isMRendererModel);
964 outScene.AddRootNode(rootIndex);
969 std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
970 sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
972 outScene.AddNode(std::move(sceneRoot));
973 outScene.AddRootNode(rootIndex);
975 for(auto& node : scene.mNodes)
977 ConvertNode(*node, node.GetIndex(), rootIndex, context, isMRendererModel);
984 void ConvertNodes(const gltf2::Document& document, ConversionContext& context, bool isMRendererModel)
986 if(!document.mScenes.empty())
988 uint32_t rootSceneIndex = 0u;
991 rootSceneIndex = document.mScene.GetIndex();
993 ConvertSceneNodes(document.mScenes[rootSceneIndex], context, isMRendererModel);
995 for(uint32_t i = 0; i < rootSceneIndex; ++i)
997 ConvertSceneNodes(document.mScenes[i], context, isMRendererModel);
1000 for(uint32_t i = rootSceneIndex + 1; i < document.mScenes.size(); ++i)
1002 ConvertSceneNodes(document.mScenes[i], context, isMRendererModel);
1007 template<typename T>
1008 void LoadDataFromAccessor(ConversionContext& context, uint32_t bufferIndex, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
1010 if(bufferIndex >= context.mOutput.mResources.mBuffers.size())
1012 DALI_LOG_ERROR("Invailid buffer index\n");
1016 auto& buffer = context.mOutput.mResources.mBuffers[bufferIndex];
1017 if(!buffer.IsAvailable())
1019 DALI_LOG_ERROR("Failed to load from buffer stream.\n");
1021 auto& stream = buffer.GetBufferStream();
1023 stream.seekg(offset, stream.beg);
1024 stream.read(reinterpret_cast<char*>(dataBuffer.Begin()), static_cast<std::streamsize>(static_cast<size_t>(size)));
1027 template<typename T>
1028 float LoadDataFromAccessors(ConversionContext& context, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
1030 inputDataBuffer.Resize(input.mCount);
1031 outputDataBuffer.Resize(output.mCount);
1033 const uint32_t inputDataBufferSize = input.GetBytesLength();
1034 const uint32_t outputDataBufferSize = output.GetBytesLength();
1036 LoadDataFromAccessor<float>(context, output.mBufferView->mBuffer.GetIndex(), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
1037 LoadDataFromAccessor<T>(context, output.mBufferView->mBuffer.GetIndex(), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
1038 ApplyAccessorMinMax(input, reinterpret_cast<float*>(inputDataBuffer.begin()));
1039 ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
1041 return inputDataBuffer[input.mCount - 1u];
1044 template<typename T>
1045 float LoadKeyFrames(ConversionContext& context, const gltf2::Animation::Channel& channel, KeyFrames& keyFrames, gltf2::Animation::Channel::Target::Type type)
1047 const gltf2::Accessor& input = *channel.mSampler->mInput;
1048 const gltf2::Accessor& output = *channel.mSampler->mOutput;
1050 Vector<float> inputDataBuffer;
1051 Vector<T> outputDataBuffer;
1053 const float duration = std::max(LoadDataFromAccessors<T>(context, input, output, inputDataBuffer, outputDataBuffer), AnimationDefinition::MIN_DURATION_SECONDS);
1055 // Set first frame value as first keyframe (gltf animation spec)
1056 if(input.mCount > 0 && !Dali::EqualsZero(inputDataBuffer[0]))
1058 keyFrames.Add(0.0f, outputDataBuffer[0]);
1061 for(uint32_t i = 0; i < input.mCount; ++i)
1063 keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
1069 float LoadBlendShapeKeyFrames(ConversionContext& context, const gltf2::Animation::Channel& channel, Index nodeIndex, uint32_t& propertyIndex, std::vector<Dali::Scene3D::Loader::AnimatedProperty>& properties)
1071 const gltf2::Accessor& input = *channel.mSampler->mInput;
1072 const gltf2::Accessor& output = *channel.mSampler->mOutput;
1074 Vector<float> inputDataBuffer;
1075 Vector<float> outputDataBuffer;
1077 const float duration = std::max(LoadDataFromAccessors<float>(context, input, output, inputDataBuffer, outputDataBuffer), AnimationDefinition::MIN_DURATION_SECONDS);
1079 char weightNameBuffer[32];
1080 auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.data());
1081 char* const pWeightName = weightNameBuffer + prefixSize;
1082 const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
1083 for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
1085 AnimatedProperty& animatedProperty = properties[propertyIndex++];
1087 animatedProperty.mNodeIndex = nodeIndex;
1088 snprintf(pWeightName, remainingSize, "%d]", weightIndex);
1089 animatedProperty.mPropertyName = std::string(weightNameBuffer);
1091 animatedProperty.mKeyFrames = KeyFrames::New();
1093 // Set first frame value as first keyframe (gltf animation spec)
1094 if(input.mCount > 0 && !Dali::EqualsZero(inputDataBuffer[0]))
1096 animatedProperty.mKeyFrames.Add(0.0f, outputDataBuffer[weightIndex]);
1099 for(uint32_t i = 0; i < input.mCount; ++i)
1101 animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
1104 animatedProperty.mTimePeriod = {0.f, duration};
1110 template<typename T>
1111 float LoadAnimation(AnimationDefinition& animationDefinition, Index nodeIndex, Index propertyIndex, const std::string& propertyName, const gltf2::Animation::Channel& channel, ConversionContext& context)
1113 AnimatedProperty& animatedProperty = animationDefinition.mProperties[propertyIndex];
1115 animatedProperty.mNodeIndex = nodeIndex;
1116 animatedProperty.mPropertyName = propertyName;
1118 animatedProperty.mKeyFrames = KeyFrames::New();
1119 float duration = LoadKeyFrames<T>(context, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1120 animatedProperty.mTimePeriod = {0.f, duration};
1125 void ConvertAnimations(const gltf2::Document& document, ConversionContext& context)
1127 auto& output = context.mOutput;
1129 output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + document.mAnimations.size());
1131 for(const auto& animation : document.mAnimations)
1133 AnimationDefinition animationDefinition;
1135 if(!animation.mName.empty())
1137 animationDefinition.mName = animation.mName;
1140 uint32_t numberOfProperties = 0u;
1141 for(const auto& channel : animation.mChannels)
1143 if(channel.mTarget.mPath == gltf2::Animation::Channel::Target::WEIGHTS)
1145 numberOfProperties += channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount;
1149 numberOfProperties++;
1152 animationDefinition.mProperties.resize(numberOfProperties);
1154 Index propertyIndex = 0u;
1155 for(const auto& channel : animation.mChannels)
1157 Index nodeIndex = context.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
1158 float duration = 0.f;
1160 switch(channel.mTarget.mPath)
1162 case gltf2::Animation::Channel::Target::TRANSLATION:
1164 duration = LoadAnimation<Vector3>(animationDefinition, nodeIndex, propertyIndex, POSITION_PROPERTY.data(), channel, context);
1167 case gltf2::Animation::Channel::Target::ROTATION:
1169 duration = LoadAnimation<Quaternion>(animationDefinition, nodeIndex, propertyIndex, ORIENTATION_PROPERTY.data(), channel, context);
1172 case gltf2::Animation::Channel::Target::SCALE:
1174 duration = LoadAnimation<Vector3>(animationDefinition, nodeIndex, propertyIndex, SCALE_PROPERTY.data(), channel, context);
1177 case gltf2::Animation::Channel::Target::WEIGHTS:
1179 duration = LoadBlendShapeKeyFrames(context, channel, nodeIndex, propertyIndex, animationDefinition.mProperties);
1185 // nothing to animate.
1190 animationDefinition.mDuration = std::max(duration, animationDefinition.mDuration);
1195 output.mAnimationDefinitions.push_back(std::move(animationDefinition));
1199 void ProcessSkins(const gltf2::Document& document, ConversionContext& context)
1201 // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1202 // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1203 // otherwise we'll set identity matrices for inverse bind pose.
1204 struct IInverseBindMatrixProvider
1206 virtual ~IInverseBindMatrixProvider()
1209 virtual void Provide(Matrix& inverseBindMatrix) = 0;
1212 struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1214 std::istream& mStream;
1215 const uint32_t mElementSizeBytes;
1217 InverseBindMatrixAccessor(const gltf2::Accessor& accessor, ConversionContext& context)
1218 : mStream(context.mOutput.mResources.mBuffers[accessor.mBufferView->mBuffer.GetIndex()].GetBufferStream()),
1219 mElementSizeBytes(accessor.GetElementSizeBytes())
1221 DALI_ASSERT_DEBUG(accessor.mType == gltf2::AccessorType::MAT4 && accessor.mComponentType == gltf2::Component::FLOAT);
1223 if(!mStream.rdbuf()->in_avail())
1225 DALI_LOG_ERROR("Failed to load from stream\n");
1228 mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset, mStream.beg);
1231 virtual void Provide(Matrix& inverseBindMatrix) override
1233 DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(inverseBindMatrix.AsFloat()), static_cast<std::streamsize>(static_cast<size_t>(mElementSizeBytes))));
1237 struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1239 virtual void Provide(Matrix& inverseBindMatrix) override
1241 inverseBindMatrix = Matrix::IDENTITY;
1245 auto& resources = context.mOutput.mResources;
1246 resources.mSkeletons.reserve(document.mSkins.size());
1248 for(auto& skin : document.mSkins)
1250 std::unique_ptr<IInverseBindMatrixProvider> inverseBindMatrixProvider;
1251 if(skin.mInverseBindMatrices)
1253 inverseBindMatrixProvider.reset(new InverseBindMatrixAccessor(*skin.mInverseBindMatrices, context));
1257 inverseBindMatrixProvider.reset(new DefaultInverseBindMatrixProvider());
1260 SkeletonDefinition skeleton;
1261 if(skin.mSkeleton.GetIndex() != INVALID_INDEX)
1263 skeleton.mRootNodeIdx = context.mNodeIndices.GetRuntimeId(skin.mSkeleton.GetIndex());
1266 skeleton.mJoints.resize(skin.mJoints.size());
1267 auto iJoint = skeleton.mJoints.begin();
1268 for(auto& joint : skin.mJoints)
1270 iJoint->mNodeIdx = context.mNodeIndices.GetRuntimeId(joint.GetIndex());
1272 inverseBindMatrixProvider->Provide(iJoint->mInverseBindMatrix);
1277 resources.mSkeletons.push_back(std::move(skeleton));
1281 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, Dali::Scene3D::Loader::SceneDefinition& scene)
1283 uint32_t nodeCount = scene.GetNodeCount();
1284 for(uint32_t i = 0; i < nodeCount; ++i)
1286 auto nodeDefinition = scene.GetNode(i);
1287 for(auto& renderable : nodeDefinition->mRenderables)
1289 if(shaderFactory.ProduceShader(*renderable) == INVALID_INDEX)
1291 DALI_LOG_ERROR("Fail to produce shader\n");
1297 void SetObjectReaders()
1299 json::SetObjectReader(GetBufferReader());
1300 json::SetObjectReader(GetBufferViewReader());
1301 json::SetObjectReader(GetBufferViewClientReader());
1302 json::SetObjectReader(GetComponentTypedBufferViewClientReader());
1303 json::SetObjectReader(GetAccessorSparseReader());
1304 json::SetObjectReader(GetAccessorReader());
1305 json::SetObjectReader(GetImageReader());
1306 json::SetObjectReader(GetSamplerReader());
1307 json::SetObjectReader(GetTextureReader());
1308 json::SetObjectReader(GetTextureInfoReader());
1309 json::SetObjectReader(GetMaterialPbrReader());
1310 json::SetObjectReader(GetMaterialSpecularReader());
1311 json::SetObjectReader(GetMaterialIorReader());
1312 json::SetObjectReader(GetMaterialExtensionsReader());
1313 json::SetObjectReader(GetMaterialReader());
1314 json::SetObjectReader(GetMeshPrimitiveReader());
1315 json::SetObjectReader(GetMeshReader());
1316 json::SetObjectReader(GetSkinReader());
1317 json::SetObjectReader(GetCameraPerspectiveReader());
1318 json::SetObjectReader(GetCameraOrthographicReader());
1319 json::SetObjectReader(GetCameraReader());
1320 json::SetObjectReader(GetNodeReader());
1321 json::SetObjectReader(GetAnimationSamplerReader());
1322 json::SetObjectReader(GetAnimationChannelTargetReader());
1323 json::SetObjectReader(GetAnimationChannelReader());
1324 json::SetObjectReader(GetAnimationReader());
1325 json::SetObjectReader(GetSceneReader());
1328 void SetDefaultEnvironmentMap(const gltf2::Document& document, ConversionContext& context)
1330 EnvironmentDefinition environmentDefinition;
1331 environmentDefinition.mUseBrdfTexture = true;
1332 environmentDefinition.mIblIntensity = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
1333 context.mOutput.mResources.mEnvironmentMaps.push_back({std::move(environmentDefinition), EnvironmentDefinition::Textures()});
1336 void InitializeGltfLoader()
1338 static Dali::Mutex initializeMutex;
1339 // Set ObjectReader only once (for all gltf loading).
1340 static bool setObjectReadersRequired = true;
1342 Mutex::ScopedLock lock(initializeMutex);
1343 if(setObjectReadersRequired)
1345 // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1347 setObjectReadersRequired = false;
1352 const std::string_view GetRendererModelIdentification()
1354 return MRENDERER_MODEL_IDENTIFICATION;
1357 void ReadDocument(const json_object_s& jsonObject, gltf2::Document& document)
1359 GetDocumentReader().Read(jsonObject, document);
1362 void ReadDocumentFromParsedData(const json_object_s& jsonObject, gltf2::Document& document)
1364 static Dali::Mutex readMutex;
1365 Mutex::ScopedLock lock(readMutex);
1366 gt::SetRefReaderObject(document);
1367 Gltf2Util::ReadDocument(jsonObject, document);
1370 bool GenerateDocument(json::unique_ptr& root, gt::Document& document, bool& isMRendererModel)
1372 auto& rootObject = js::Cast<json_object_s>(*root);
1373 auto jsonAsset = js::FindObjectChild("asset", rootObject);
1375 auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsonAsset));
1378 document.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1381 auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsonAsset));
1382 if(jsAssetGenerator)
1384 document.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1385 isMRendererModel = (document.mAsset.mGenerator.find(Gltf2Util::GetRendererModelIdentification().data()) != std::string_view::npos);
1388 Gltf2Util::InitializeGltfLoader();
1389 Gltf2Util::ReadDocumentFromParsedData(rootObject, document);
1394 void ConvertGltfToContext(gt::Document& document, Gltf2Util::ConversionContext& context, bool isMRendererModel)
1396 Dali::Scene3D::Loader::ShaderDefinitionFactory shaderFactory;
1397 shaderFactory.SetResources(context.mOutput.mResources);
1399 Gltf2Util::ConvertBuffers(document, context);
1400 Gltf2Util::ConvertMaterials(document, context);
1401 Gltf2Util::ConvertMeshes(document, context);
1402 Gltf2Util::ConvertNodes(document, context, isMRendererModel);
1403 Gltf2Util::ConvertAnimations(document, context);
1404 Gltf2Util::ProcessSkins(document, context);
1405 Gltf2Util::ProduceShaders(shaderFactory, context.mOutput.mScene);
1406 context.mOutput.mScene.EnsureUniqueSkinningShaderInstances(context.mOutput.mResources);
1408 // Set Default Environment map
1409 Gltf2Util::SetDefaultEnvironmentMap(document, context);
1412 } // namespace Gltf2Util
1414 } // namespace Dali::Scene3D::Loader::Internal