0032107: Data Exchange, RWGltf_CafReader - reading glTF document back loses sharing
[occt.git] / src / RWGltf / RWGltf_GltfJsonParser.hxx
1 // Author: Kirill Gavrilov
2 // Copyright (c) 2016-2019 OPEN CASCADE SAS
3 //
4 // This file is part of Open CASCADE Technology software library.
5 //
6 // This library is free software; you can redistribute it and/or modify it under
7 // the terms of the GNU Lesser General Public License version 2.1 as published
8 // by the Free Software Foundation, with special exception defined in the file
9 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
10 // distribution for complete text of the license and disclaimer of any warranty.
11 //
12 // Alternatively, this file may be used under the terms of Open CASCADE
13 // commercial license or contractual agreement.
14
15 #ifndef _RWGltf_GltfJsonParser_HeaderFile
16 #define _RWGltf_GltfJsonParser_HeaderFile
17
18 #include <Graphic3d_Vec.hxx>
19 #include <Message_Gravity.hxx>
20 #include <Message_ProgressScope.hxx>
21 #include <NCollection_DataMap.hxx>
22 #include <NCollection_IndexedMap.hxx>
23 #include <RWGltf_GltfAccessor.hxx>
24 #include <RWGltf_GltfPrimArrayData.hxx>
25 #include <RWGltf_GltfLatePrimitiveArray.hxx>
26 #include <RWGltf_GltfBufferView.hxx>
27 #include <RWGltf_GltfRootElement.hxx>
28 #include <RWGltf_MaterialCommon.hxx>
29 #include <RWGltf_MaterialMetallicRoughness.hxx>
30 #include <RWMesh_CoordinateSystemConverter.hxx>
31 #include <RWMesh_NodeAttributes.hxx>
32 #include <TColStd_IndexedDataMapOfStringString.hxx>
33 #include <TopoDS_Face.hxx>
34 #include <TopTools_SequenceOfShape.hxx>
35
36 // workaround name collisions with XLib
37 #ifdef None
38   #undef None
39 #endif
40 #ifdef Bool
41   #undef Bool
42 #endif
43
44 #ifdef HAVE_RAPIDJSON
45   //#define RAPIDJSON_ASSERT
46   #include <rapidjson/document.h>
47   #include <rapidjson/prettywriter.h>
48   #include <rapidjson/stringbuffer.h>
49   #include <rapidjson/istreamwrapper.h>
50   #include <rapidjson/ostreamwrapper.h>
51
52   typedef rapidjson::Document::ValueType RWGltf_JsonValue;
53 #endif
54
55 class Message_ProgressIndicator;
56
57 //! INTERNAL tool for parsing glTF document (JSON structure).
58 class RWGltf_GltfJsonParser
59 #ifdef HAVE_RAPIDJSON
60 : public rapidjson::Document
61 #endif
62 {
63 public:
64
65 #ifdef HAVE_RAPIDJSON
66   //! Auxiliary method for formatting error code.
67   Standard_EXPORT static const char* FormatParseError (rapidjson::ParseErrorCode theCode);
68 #endif
69
70 public:
71
72   //! Empty constructor.
73   Standard_EXPORT RWGltf_GltfJsonParser (TopTools_SequenceOfShape& theRootShapes);
74
75   //! Set file path.
76   Standard_EXPORT void SetFilePath (const TCollection_AsciiString& theFilePath);
77
78   //! Set flag for probing file without complete reading.
79   void SetProbeHeader (bool theToProbe) { myToProbeHeader = theToProbe; }
80
81   //! Return prefix for reporting issues.
82   const TCollection_AsciiString& ErrorPrefix() const { return myErrorPrefix; }
83
84   //! Set prefix for reporting issues.
85   void SetErrorPrefix (const TCollection_AsciiString& theErrPrefix) { myErrorPrefix = theErrPrefix; }
86
87   //! Set map for storing node attributes.
88   void SetAttributeMap (RWMesh_NodeAttributeMap& theAttribMap) { myAttribMap = &theAttribMap; }
89
90   //! Set list for storing external files.
91   void SetExternalFiles (NCollection_IndexedMap<TCollection_AsciiString>& theExternalFiles) { myExternalFiles = &theExternalFiles; }
92
93   //! Set metadata map.
94   void SetMetadata (TColStd_IndexedDataMapOfStringString& theMetadata) { myMetadata = &theMetadata; }
95
96   //! Return transformation from glTF to OCCT coordinate system.
97   const RWMesh_CoordinateSystemConverter& CoordinateSystemConverter() const { return myCSTrsf; }
98
99   //! Set transformation from glTF to OCCT coordinate system.
100   void SetCoordinateSystemConverter (const RWMesh_CoordinateSystemConverter& theConverter) { myCSTrsf = theConverter; }
101
102   //! Initialize binary format.
103   void SetBinaryFormat (int64_t theBinBodyOffset,
104                         int64_t theBinBodyLen)
105   {
106     myIsBinary      = true;
107     myBinBodyOffset = theBinBodyOffset;
108     myBinBodyLen    = theBinBodyLen;
109   }
110
111   //! Set flag to ignore nodes without Geometry, TRUE by default.
112   void SetSkipEmptyNodes (bool theToSkip) { myToSkipEmptyNodes = theToSkip; }
113
114   //! Set flag to use Mesh name in case if Node name is empty, TRUE by default.
115   void SetMeshNameAsFallback (bool theToFallback) { myUseMeshNameAsFallback = theToFallback; }
116
117   //! Parse glTF document.
118   Standard_EXPORT bool Parse (const Message_ProgressRange& theProgress);
119
120   //! Return face list for loading triangulation.
121   NCollection_Vector<TopoDS_Face>& FaceList() { return myFaceList; }
122
123 protected:
124 #ifdef HAVE_RAPIDJSON
125   //! Search mandatory root elements in the document.
126   //! Return FALSE if some mandatory element is missing.
127   Standard_EXPORT bool gltfParseRoots();
128
129   //! Parse default scene.
130   Standard_EXPORT bool gltfParseScene (const Message_ProgressRange& theProgress);
131
132   //! Parse document metadata.
133   Standard_EXPORT void gltfParseAsset();
134
135 protected:
136
137   //! Parse materials defined in the document.
138   Standard_EXPORT void gltfParseMaterials();
139
140   //! Parse standard material.
141   Standard_EXPORT bool gltfParseStdMaterial (Handle(RWGltf_MaterialCommon)& theMat,
142                                              const RWGltf_JsonValue& theMatNode);
143
144   //! Parse pbrMetallicRoughness material.
145   Standard_EXPORT bool gltfParsePbrMaterial (Handle(RWGltf_MaterialMetallicRoughness)& theMat,
146                                              const RWGltf_JsonValue& theMatNode);
147
148   //! Parse common material (KHR_materials_common extension).
149   Standard_EXPORT bool gltfParseCommonMaterial (Handle(RWGltf_MaterialCommon)& theMat,
150                                                 const RWGltf_JsonValue& theMatNode);
151
152   //! Parse texture definition.
153   Standard_EXPORT bool gltfParseTexture (Handle(Image_Texture)& theTexture,
154                                          const RWGltf_JsonValue* theTextureId);
155
156   //! Parse texture definition in binary buffer of GLB file.
157   Standard_EXPORT bool gltfParseTexturInGlbBuffer (Handle(Image_Texture)& theTexture,
158                                                    const RWGltf_JsonValue& theBinVal,
159                                                    const TCollection_AsciiString& theBufferViewId,
160                                                    const RWGltf_JsonValue& theBufferViewName);
161
162   //! Parse texture definition in binary buffer of glTF file.
163   Standard_EXPORT bool gltfParseTextureInBufferView (Handle(Image_Texture)& theTexture,
164                                                      const TCollection_AsciiString& theSourceId,
165                                                      const TCollection_AsciiString& theBufferViewhId,
166                                                      const RWGltf_JsonValue& theBufferView);
167
168   //! Bind material definition to the map.
169   Standard_EXPORT void gltfBindMaterial (const Handle(RWGltf_MaterialMetallicRoughness)& theMatPbr,
170                                          const Handle(RWGltf_MaterialCommon)& theMatCommon);
171
172 protected:
173
174   //! Parse scene array of nodes recursively.
175   Standard_EXPORT bool gltfParseSceneNodes (TopTools_SequenceOfShape& theShapeSeq,
176                                             const RWGltf_JsonValue& theSceneNodes,
177                                             const Message_ProgressRange& theProgress);
178
179   //! Parse scene node recursively.
180   Standard_EXPORT bool gltfParseSceneNode (TopoDS_Shape& theNodeShape,
181                                            const TCollection_AsciiString& theSceneNodeId,
182                                            const RWGltf_JsonValue& theSceneNode,
183                                            const Message_ProgressRange& theProgress);
184
185   //! Parse mesh element.
186   Standard_EXPORT bool gltfParseMesh (TopoDS_Shape& theMeshShape,
187                                       const TCollection_AsciiString& theMeshId,
188                                       const RWGltf_JsonValue& theMesh);
189
190   //! Parse primitive array.
191   Standard_EXPORT bool gltfParsePrimArray (TopoDS_Shape& thePrimArrayShape,
192                                            const TCollection_AsciiString& theMeshId,
193                                            const TCollection_AsciiString& theMeshName,
194                                            const RWGltf_JsonValue& thePrimArray);
195
196   //! Parse accessor.
197   Standard_EXPORT bool gltfParseAccessor (const Handle(RWGltf_GltfLatePrimitiveArray)& theMeshData,
198                                           const TCollection_AsciiString& theName,
199                                           const RWGltf_JsonValue& theAccessor,
200                                           const RWGltf_GltfArrayType theType,
201                                           const RWGltf_JsonValue* theCompBuffView);
202
203   //! Parse buffer view.
204   Standard_EXPORT bool gltfParseBufferView (const Handle(RWGltf_GltfLatePrimitiveArray)& theMeshData,
205                                             const TCollection_AsciiString& theName,
206                                             const RWGltf_JsonValue& theBufferView,
207                                             const RWGltf_GltfAccessor& theAccessor,
208                                             const RWGltf_GltfArrayType theType);
209
210   //! Parse buffer.
211   Standard_EXPORT bool gltfParseBuffer (const Handle(RWGltf_GltfLatePrimitiveArray)& theMeshData,
212                                         const TCollection_AsciiString& theName,
213                                         const RWGltf_JsonValue& theBuffer,
214                                         const RWGltf_GltfAccessor&   theAccessor,
215                                         const RWGltf_GltfBufferView& theView,
216                                         const RWGltf_GltfArrayType   theType);
217
218 protected:
219
220   //! Read vec4 from specified item.
221   static bool gltfReadVec4 (Graphic3d_Vec4d& theVec4,
222                             const RWGltf_JsonValue* theVal)
223   {
224     if (theVal == NULL
225     || !theVal->IsArray()
226     ||  theVal->Size() != 4)
227     {
228       return false;
229     }
230
231     for (int aCompIter = 0; aCompIter < 4; ++aCompIter)
232     {
233       const RWGltf_JsonValue& aGenVal = (*theVal)[aCompIter];
234       if (!aGenVal.IsNumber())
235       {
236         return false;
237       }
238       theVec4[aCompIter] = aGenVal.GetDouble();
239     }
240     return true;
241   }
242
243   //! Validate color
244   static bool validateColor4 (const Graphic3d_Vec4d& theVec)
245   {
246     return theVec.r() >= 0.0 && theVec.r() <= 1.0
247         && theVec.g() >= 0.0 && theVec.g() <= 1.0
248         && theVec.b() >= 0.0 && theVec.b() <= 1.0
249         && theVec.a() >= 0.0 && theVec.a() <= 1.0;
250   }
251
252   //! Read vec3 from specified item.
253   static bool gltfReadVec3 (Graphic3d_Vec3d& theVec3,
254                             const RWGltf_JsonValue* theVal)
255   {
256     if (theVal == NULL
257     || !theVal->IsArray()
258     ||  theVal->Size() != 3)
259     {
260       return false;
261     }
262
263     for (int aCompIter = 0; aCompIter < 3; ++aCompIter)
264     {
265       const RWGltf_JsonValue& aGenVal = (*theVal)[aCompIter];
266       if (!aGenVal.IsNumber())
267       {
268         return false;
269       }
270       theVec3[aCompIter] = aGenVal.GetDouble();
271     }
272     return true;
273   }
274
275   //! Validate color
276   static bool validateColor3 (const Graphic3d_Vec3d& theVec)
277   {
278     return theVec.r() >= 0.0 && theVec.r() <= 1.0
279         && theVec.g() >= 0.0 && theVec.g() <= 1.0
280         && theVec.b() >= 0.0 && theVec.b() <= 1.0;
281   }
282
283 protected:
284
285   //! Groups for re-using shapes.
286   enum ShapeMapGroup
287   {
288     ShapeMapGroup_Nodes,     //!< nodes
289     ShapeMapGroup_Meshes,    //!< meshes
290     ShapeMapGroup_PrimArray, //!< primitive array
291   };
292
293   //! Bind name attribute.
294   void bindNodeShape (TopoDS_Shape& theShape,
295                       const TopLoc_Location& theLoc,
296                       const TCollection_AsciiString& theNodeId,
297                       const RWGltf_JsonValue* theUserName)
298   {
299     bindNamedShape (theShape, ShapeMapGroup_Nodes, theLoc, theNodeId, theUserName);
300   }
301
302   //! Bind name attribute.
303   void bindMeshShape (TopoDS_Shape& theShape,
304                       const TCollection_AsciiString& theMeshId,
305                       const RWGltf_JsonValue* theUserName)
306   {
307     bindNamedShape (theShape, ShapeMapGroup_Meshes, TopLoc_Location(), theMeshId, theUserName);
308   }
309
310   //! Find named shape.
311   bool findNodeShape (TopoDS_Shape& theShape,
312                       const TCollection_AsciiString& theNodeId) const
313   {
314     return findNamedShape (theShape, ShapeMapGroup_Nodes, theNodeId);
315   }
316
317   //! Find named shape.
318   bool findMeshShape (TopoDS_Shape& theShape,
319                       const TCollection_AsciiString& theMeshId) const
320   {
321     return findNamedShape (theShape, ShapeMapGroup_Meshes, theMeshId);
322   }
323
324   //! Bind name attribute.
325   Standard_EXPORT void bindNamedShape (TopoDS_Shape& theShape,
326                                        ShapeMapGroup theGroup,
327                                        const TopLoc_Location& theLoc,
328                                        const TCollection_AsciiString& theId,
329                                        const RWGltf_JsonValue* theUserName);
330
331   //! Find named shape.
332   bool findNamedShape (TopoDS_Shape& theShape,
333                        ShapeMapGroup theGroup,
334                        const TCollection_AsciiString& theId) const
335   {
336     return myShapeMap[theGroup].Find (theId, theShape);
337   }
338
339   //! Return the string representation of the key.
340   static TCollection_AsciiString getKeyString (const RWGltf_JsonValue& theValue)
341   {
342     if (theValue.IsString())
343     {
344       return TCollection_AsciiString (theValue.GetString());
345     }
346     else if (theValue.IsInt())
347     {
348       return TCollection_AsciiString (theValue.GetInt());
349     }
350     return TCollection_AsciiString();
351   }
352
353 protected:
354
355   //! Auxiliary structure for fast look-up of document sub-nodes of specified node.
356   class GltfElementMap
357   {
358   public:
359
360     //! Empty constructor.
361     GltfElementMap() : myRoot (NULL) {}
362
363     //! Return TRUE if this element is NULL.
364     bool IsNull() const { return myRoot == NULL; }
365
366     //! Access this node.
367     const RWGltf_JsonValue* Root() const { return myRoot; }
368
369     //! Find the child node with specified key.
370     const RWGltf_JsonValue* FindChild (const TCollection_AsciiString& theKey)
371     {
372       const RWGltf_JsonValue* aNode = NULL;
373       return myChildren.Find (theKey, aNode)
374            ? aNode
375            : NULL;
376     }
377
378     //! Find the child node with specified key.
379     const RWGltf_JsonValue* FindChild (const RWGltf_JsonValue& theKey)
380     {
381       const TCollection_AsciiString aKey = getKeyString (theKey);
382       if (aKey.IsEmpty())
383       {
384         return NULL;
385       }
386
387       const RWGltf_JsonValue* aNode = NULL;
388       return myChildren.Find (aKey, aNode)
389            ? aNode
390            : NULL;
391     }
392
393     //! Initialize the element.
394     void Init (const TCollection_AsciiString& theRootName,
395                const RWGltf_JsonValue* theRoot);
396
397   private:
398
399     NCollection_DataMap<TCollection_AsciiString, const RWGltf_JsonValue*, TCollection_AsciiString> myChildren;
400     const RWGltf_JsonValue* myRoot;
401
402   };
403 #endif
404 protected:
405
406   //! Print message about invalid glTF syntax.
407   void reportGltfSyntaxProblem (const TCollection_AsciiString& theMsg, Message_Gravity theGravity);
408
409 protected:
410
411   TopTools_SequenceOfShape*        myRootShapes;    //!< sequence of result root shapes
412   RWMesh_NodeAttributeMap*         myAttribMap;     //!< shape attributes
413   NCollection_IndexedMap<TCollection_AsciiString>*
414                                    myExternalFiles; //!< list of external file references
415   RWMesh_CoordinateSystemConverter myCSTrsf;        //!< transformation from glTF to OCCT coordinate system
416   TColStd_IndexedDataMapOfStringString* myMetadata; //!< file metadata
417
418   NCollection_DataMap<TCollection_AsciiString, Handle(RWGltf_MaterialMetallicRoughness)> myMaterialsPbr;
419   NCollection_DataMap<TCollection_AsciiString, Handle(RWGltf_MaterialCommon)> myMaterialsCommon;
420   NCollection_DataMap<TCollection_AsciiString, Handle(XCAFDoc_VisMaterial)> myMaterials;
421   NCollection_DataMap<TCollection_AsciiString, TopoDS_Shape> myShapeMap[3];
422
423   NCollection_DataMap<TCollection_AsciiString, bool> myProbedFiles;
424   NCollection_DataMap<TCollection_AsciiString, Handle(NCollection_Buffer)> myDecodedBuffers;
425   NCollection_Vector<TopoDS_Face> myFaceList; //!< face list for loading triangulation
426
427   TCollection_AsciiString   myFilePath;       //!< file path
428   TCollection_AsciiString   myFolder;         //!< folder
429   TCollection_AsciiString   myErrorPrefix;    //!< invalid syntax error prefix
430   int64_t                   myBinBodyOffset;  //!< offset to binary body
431   int64_t                   myBinBodyLen;     //!< binary body length
432   bool                      myIsBinary;       //!< binary document
433   bool                      myIsGltf1;        //!< obsolete glTF 1.0 version format
434   bool                      myToSkipEmptyNodes; //!< ignore nodes without Geometry
435   bool                      myUseMeshNameAsFallback; //!< flag to use Mesh name in case if Node name is empty, TRUE by default
436   bool                      myToProbeHeader;  //!< flag to probe header without full reading, FALSE by default
437
438 #ifdef HAVE_RAPIDJSON
439   GltfElementMap myGltfRoots[RWGltf_GltfRootElement_NB]; //!< glTF format root elements
440 #endif
441
442 };
443
444 #endif // _RWGltf_GltfJsonParser_HeaderFile