Make shader version be top of the code
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / internal / gltf2-asset.h
1 #ifndef DALI_SCENE_LOADER_GLTF2_ASSET_H_
2 #define DALI_SCENE_LOADER_GLTF2_ASSET_H_
3 /*
4  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 // INTERNAL INCLUDES
21 #include "dali-scene-loader/internal/json-reader.h"
22 #include "dali-scene-loader/public-api/index.h"
23
24 // EXTERNAL INCLUDES
25 #include <cstdint>
26 #include <memory>
27 #include "dali/devel-api/common/map-wrapper.h"
28 #include "dali/public-api/common/vector-wrapper.h"
29 #include "dali/public-api/math/quaternion.h"
30 #include "dali/public-api/math/vector4.h"
31
32 namespace gltf2
33 {
34 using Index = Dali::SceneLoader::Index;
35
36 template<typename T>
37 class Ref
38 {
39 public:
40   Ref() = default;
41   Ref(std::vector<T>& v, Index i)
42   : mVector(&v),
43     mIndex(i)
44   {
45   }
46
47   /**
48    * @return The index of the object into the vector.
49    * @note It is client code responsibility to ensure that the vector is unambiguous. It should be in
50    *  a glTF document, since there's one vector for each type.
51    */
52   Index GetIndex() const
53   {
54     return mIndex;
55   }
56
57   /**
58    * @brief There may be scenarios in which the object, whose vector we're populating, changes, e.g.
59    *  when we don't have a final one at the time of reading the references.
60    */
61   void UpdateVector(std::vector<T>& v)
62   {
63     mVector = &v;
64   }
65
66   operator bool() const
67   {
68     return mVector != nullptr;
69   }
70   T* operator->() const
71   {
72     return &(*mVector)[mIndex];
73   }
74   T& operator*() const
75   {
76     return (*mVector)[mIndex];
77   }
78
79   bool operator==(const Ref<T>& other) const
80   {
81     return mVector == other.mVector && mIndex == other.mIndex;
82   }
83
84   bool operator!=(const Ref<T>& other) const
85   {
86     return !operator==(other);
87   }
88
89 private:
90   std::vector<T>* mVector = nullptr;
91   Index           mIndex  = Dali::SceneLoader::INVALID_INDEX;
92 };
93
94 struct Asset
95 {
96   std::string_view mGenerator;
97   std::string_view mVersion;
98 };
99
100 struct Component
101 {
102   enum Type
103   {
104     BYTE           = 5120,
105     UNSIGNED_BYTE  = 5121,
106     SHORT          = 5122,
107     UNSIGNED_SHORT = 5123,
108     UNSIGNED_INT   = 5125,
109     FLOAT          = 5126,
110     INVALID        = -1
111   };
112
113   static bool     IsUnsigned(Type t);
114   static uint32_t Size(Type t);
115
116   Component() = delete;
117 };
118
119 struct AccessorType
120 {
121   enum Type
122   {
123     SCALAR,
124     VEC2,
125     VEC3,
126     VEC4,
127     MAT2,
128     MAT3,
129     MAT4,
130     INVALID
131   };
132
133   static uint32_t ElementCount(Type t);
134
135   static Type FromString(const char* s, size_t len);
136
137   AccessorType() = delete;
138 };
139
140 struct AlphaMode
141 {
142   enum Type
143   {
144     OPAQUE,
145     MASK,
146     BLEND,
147     INVALID
148   };
149
150   static Type FromString(const char* s, size_t len);
151
152   AlphaMode() = delete;
153 };
154
155 struct Attribute
156 {
157   enum Type
158   {
159     POSITION,
160     NORMAL,
161     TANGENT,
162     TEXCOORD_0,
163     TEXCOORD_1,
164     COLOR_0,
165     JOINTS_0,
166     WEIGHTS_0,
167     INVALID
168   };
169
170   static Type FromString(const char* s, size_t len);
171
172   Attribute() = delete;
173 };
174
175 struct Buffer
176 {
177   uint32_t         mByteLength;
178   std::string_view mUri;
179   //TODO: extensions
180   //TODO: extras
181 };
182
183 struct BufferView
184 {
185   struct Target
186   {
187     enum Type
188     {
189       NONE,
190       ARRAY_BUFFER         = 34962,
191       ELEMENT_ARRAY_BUFFER = 34963
192     };
193
194     Target() = delete;
195   };
196
197   Ref<Buffer> mBuffer;
198   uint32_t    mByteOffset = 0;
199   uint32_t    mByteLength;
200   uint32_t    mByteStride = 0; // if 0 after reading, it needs to be calculated
201   uint32_t    mTarget;
202   //TODO: extensions
203   //TODO: extras
204 };
205
206 struct BufferViewClient
207 {
208   Ref<BufferView> mBufferView;
209   uint32_t        mByteOffset = 0;
210 };
211
212 struct ComponentTypedBufferViewClient : BufferViewClient
213 {
214   Component::Type mComponentType = Component::INVALID;
215
216   uint32_t GetBytesPerComponent() const;
217 };
218
219 struct Named
220 {
221   std::string_view mName;
222
223 protected:
224   Named() = default;
225 };
226
227 struct Accessor : ComponentTypedBufferViewClient, Named
228 {
229   struct Sparse
230   {
231     uint32_t                       mCount;
232     ComponentTypedBufferViewClient mIndices;
233     BufferViewClient               mValues;
234     //TODO: extensions
235     //TODO: extras
236   };
237
238   uint32_t                mCount;
239   bool                    mNormalized = false;
240   AccessorType::Type      mType       = AccessorType::INVALID;
241   std::vector<float>      mMin;
242   std::vector<float>      mMax;
243   std::unique_ptr<Sparse> mSparse;
244   //TODO: extensions
245   //TODO: extras
246
247   uint32_t GetElementSizeBytes() const
248   {
249     return GetBytesPerComponent() * AccessorType::ElementCount(mType);
250   }
251
252   uint32_t GetBytesLength() const
253   {
254     return GetElementSizeBytes() * mCount;
255   }
256
257   void SetSparse(const Sparse& s)
258   {
259     mSparse.reset(new Sparse(s));
260   }
261 };
262
263 struct Image : Named
264 {
265   std::string_view mUri;
266   std::string_view mMimeType;
267   Ref<BufferView>  mBufferView;
268   //TODO: extensions
269   //TODO: extras
270 };
271
272 struct Filter
273 {
274   enum Type
275   {
276     NEAREST                = 9728,
277     LINEAR                 = 9729,
278     NEAREST_MIPMAP_NEAREST = 9984,
279     NEAREST_MIPMAP_LINEAR  = 9985,
280     LINEAR_MIPMAP_NEAREST  = 9986,
281     LINEAR_MIPMAP_LINEAR   = 9987,
282   };
283
284   Filter() = delete;
285 };
286
287 struct Wrap
288 {
289   enum Type
290   {
291     REPEAT          = 10497,
292     CLAMP_TO_EDGE   = 33071,
293     MIRRORED_REPEAT = 33648,
294   };
295
296   Wrap() = delete;
297 };
298
299 struct Sampler
300 {
301   Filter::Type mMinFilter = Filter::LINEAR;
302   Filter::Type mMagFilter = Filter::LINEAR;
303   Wrap::Type   mWrapS     = Wrap::CLAMP_TO_EDGE;
304   Wrap::Type   mWrapT     = Wrap::CLAMP_TO_EDGE;
305   //TODO: extensions
306   //TODO: extras
307 };
308
309 struct Texture
310 {
311   Ref<Image>   mSource;
312   Ref<Sampler> mSampler;
313 };
314
315 struct TextureInfo
316 {
317   Ref<gltf2::Texture> mTexture;
318   uint32_t            mTexCoord = 0;
319   float               mScale    = 1.f;
320   float               mStrength = 1.f;
321
322   operator bool() const
323   {
324     return !!mTexture;
325   }
326 };
327
328 struct Material : Named
329 {
330   struct Pbr //MetallicRoughness
331   {
332     Dali::Vector4 mBaseColorFactor = Dali::Vector4::ONE;
333     TextureInfo   mBaseColorTexture;
334     float         mMetallicFactor  = 1.f;
335     float         mRoughnessFactor = 1.f;
336     TextureInfo   mMetallicRoughnessTexture;
337     //TODO: extensions
338     //TODO: extras
339   };
340
341   Pbr             mPbrMetallicRoughness;
342   TextureInfo     mNormalTexture;
343   TextureInfo     mOcclusionTexture;
344   TextureInfo     mEmissiveTexture;
345   Dali::Vector3   mEmissiveFactor;
346   AlphaMode::Type mAlphaMode   = AlphaMode::OPAQUE;
347   float           mAlphaCutoff = .5f;
348   bool            mDoubleSided = false;
349   //TODO: extensions
350   //TODO: extras
351 };
352
353 struct Mesh : Named
354 {
355   struct Primitive
356   {
357     enum Mode
358     {
359       POINTS,
360       LINES,
361       LINE_LOOP,
362       LINE_STRIP,
363       TRIANGLES,
364       TRIANGLE_STRIP,
365       TRIANGLE_FAN,
366       INVALID
367     };
368
369     std::map<Attribute::Type, Ref<Accessor>>              mAttributes;
370     std::vector<std::map<Attribute::Type, Ref<Accessor>>> mTargets;
371     Ref<Accessor>                                         mIndices;
372     Ref<Material>                                         mMaterial;
373     Mode                                                  mMode = TRIANGLES;
374
375     //TODO: [morph] targets
376     //TODO: extras
377     //TODO: extensions
378   };
379
380   std::vector<Primitive> mPrimitives;
381   std::vector<float>     mWeights;
382   //TODO: extras
383   //TODO: extensions
384 };
385
386 struct Node;
387
388 struct Skin : Named
389 {
390   Ref<Accessor>          mInverseBindMatrices;
391   Ref<Node>              mSkeleton;
392   std::vector<Ref<Node>> mJoints;
393   //TODO: extras
394   //TODO: extensions
395 };
396
397 struct Camera : Named
398 {
399   struct Perspective
400   {
401     float mAspectRatio;
402     float mYFov;
403     float mZFar;
404     float mZNear;
405     //TODO: extras
406     //TODO: extensions
407   };
408
409   struct Orthographic
410   {
411     float mXMag;
412     float mYMag;
413     float mZFar;
414     float mZNear;
415     //TODO: extras
416     //TODO: extensions
417   };
418
419   std::string_view mType;
420   Perspective      mPerspective;
421   Orthographic     mOrthographic;
422   //TODO: extras
423   //TODO: extensions
424 };
425
426 struct Node : Named
427 {
428   Dali::Vector3    mTranslation = Dali::Vector3::ZERO;
429   Dali::Quaternion mRotation    = Dali::Quaternion::IDENTITY;
430   Dali::Vector3    mScale       = Dali::Vector3::ONE;
431
432   Ref<Camera>            mCamera;
433   std::vector<Ref<Node>> mChildren;
434   Ref<Mesh>              mMesh;
435
436   Ref<Skin> mSkin;
437   //TODO: [morph] weights
438   //TODO: extras
439   //TODO: extensions
440
441   void SetMatrix(const Dali::Matrix& m);
442 };
443
444 struct Animation : Named
445 {
446   struct Sampler
447   {
448     struct Interpolation
449     {
450       enum Type
451       {
452         STEP,
453         LINEAR,
454         CUBICSPLINE,
455         INVALID
456       };
457       static Type FromString(const char* s, size_t len);
458     };
459
460     Ref<Accessor>       mInput;
461     Ref<Accessor>       mOutput;
462     Interpolation::Type mInterpolation;
463
464     //TODO: extras
465     //TODO: extensions
466   };
467
468   struct Channel
469   {
470     struct Target
471     {
472       enum Type
473       {
474         TRANSLATION,
475         ROTATION,
476         SCALE,
477         WEIGHTS,
478         INVALID
479       };
480
481       static Type FromString(const char* s, size_t len);
482
483       Ref<Node> mNode;
484       Type      mPath;
485     };
486
487     Ref<Sampler> mSampler;
488     Target       mTarget;
489     //TODO: extras
490     //TODO: extensions
491   };
492
493   std::vector<Sampler> mSamplers;
494   std::vector<Channel> mChannels;
495 };
496
497 struct Scene : Named
498 {
499   std::vector<Ref<Node>> mNodes;
500 };
501
502 struct Document
503 {
504   Asset mAsset;
505
506   std::vector<Buffer>     mBuffers;
507   std::vector<BufferView> mBufferViews;
508   std::vector<Accessor>   mAccessors;
509
510   std::vector<Image>    mImages;
511   std::vector<Sampler>  mSamplers;
512   std::vector<Texture>  mTextures;
513   std::vector<Material> mMaterials;
514
515   std::vector<Mesh> mMeshes;
516   std::vector<Skin> mSkins;
517
518   std::vector<Camera> mCameras;
519   std::vector<Node>   mNodes;
520
521   std::vector<Animation> mAnimations;
522
523   std::vector<Scene> mScenes;
524   Ref<Scene>         mScene;
525
526   Document()                = default;
527   Document(const Document&) = delete;
528   Document(Document&&)      = default;
529
530   Document& operator=(const Document&) = delete;
531   Document& operator=(Document&&) = default;
532 };
533
534 /**
535  * @brief Provides a json::Property<T>::ReadFn for interpreting unsigned integers
536  *  as a Ref<U> into a std::vector<U> data member of a type T.
537  */
538 template<typename T>
539 struct RefReader
540 {
541   static T* sObject;
542
543   template<typename U, std::vector<U> T::*V>
544   static Ref<U> Read(const json_value_s& j)
545   {
546     uint32_t index = json::Read::Number<uint32_t>(j);
547     return Ref<U>(sObject->*V, index);
548   }
549 };
550
551 template<typename T>
552 T* RefReader<T>::sObject = nullptr;
553
554 /**
555  * @brief Convenience method to set the object for RefReader.
556  */
557 template<typename T>
558 void SetRefReaderObject(T& object)
559 {
560   RefReader<T>::sObject = &object;
561 }
562
563 /**
564  * @brief Reads a string and attempts to convert it to an enum.
565  * @note The enum must: 1, be called Type, nested to T, 2, provide a FromString static method taking a const char*
566  *  (string data) and a size_t (string length) and returning T::Type.
567  */
568 template<typename T> // T must have a nested enum called Type and a static Type FromString(const char*) method.
569 typename T::Type ReadStringEnum(const json_value_s& j)
570 {
571   auto str = json::Read::StringView(j);
572
573   return T::FromString(str.data(), str.size());
574 }
575
576 /**
577  * @brief Convenience method to attempt to create a Dali vector type T from an array of floats.
578  * @note T must provide an AsFloat() member method returning the non-const array of its
579  *  float components.
580  */
581 template<typename T>
582 inline T ReadDaliVector(const json_value_s& j)
583 {
584   std::vector<float> floats = json::Read::Array<float, json::Read::Number<float>>(j);
585   T                  result;
586   std::copy(floats.begin(), std::min(floats.end(), floats.begin() + sizeof(T) / sizeof(float)), result.AsFloat());
587   return result;
588 }
589
590 /**
591  * @brief Convenience method to attemt to read a Quaternion, which implicitly converts
592  *  to Vector4 but fails to provide an AsFloat() method.
593  */
594 Dali::Quaternion ReadQuaternion(const json_value_s& j);
595
596 } // namespace gltf2
597
598 #endif //DALI_SCENE_LOADER_GLTF2_ASSET_H_