1 // Author: Kirill Gavrilov
2 // Copyright (c) 2017-2019 OPEN CASCADE SAS
4 // This file is part of Open CASCADE Technology software library.
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.
12 // Alternatively, this file may be used under the terms of Open CASCADE
13 // commercial license or contractual agreement.
15 #include <RWObj_Reader.hxx>
17 #include <RWObj_MtlReader.hxx>
19 #include <BRepMesh_DataStructureOfDelaun.hxx>
20 #include <BRepMesh_Delaun.hxx>
22 #include <Message.hxx>
23 #include <Message_Messenger.hxx>
24 #include <Message_ProgressSentry.hxx>
25 #include <NCollection_IncAllocator.hxx>
26 #include <OSD_OpenFile.hxx>
27 #include <OSD_Path.hxx>
28 #include <OSD_Timer.hxx>
29 #include <Precision.hxx>
30 #include <Standard_CLocaleSentry.hxx>
31 #include <Standard_ReadLineBuffer.hxx>
37 #define ftell64(a) _ftelli64(a)
38 #define fseek64(a,b,c) _fseeki64(a,b,c)
40 #define ftell64(a) ftello(a)
41 #define fseek64(a,b,c) fseeko(a,b,c)
44 IMPLEMENT_STANDARD_RTTIEXT(RWObj_Reader, Standard_Transient)
48 // The length of buffer to read (in bytes)
49 static const size_t THE_BUFFER_SIZE = 4 * 1024;
52 struct RWObj_ReaderFile
57 //! Constructor opening the file.
58 RWObj_ReaderFile (const TCollection_AsciiString& theFile)
59 : File (OSD_OpenFile (theFile.ToCString(), "rb")),
62 if (this->File != NULL)
64 // determine length of file
65 ::fseek64 (this->File, 0, SEEK_END);
66 FileLen = ::ftell64 (this->File);
67 ::fseek64 (this->File, 0, SEEK_SET);
71 //! Destructor closing the file.
81 //! Return TRUE if given polygon has clockwise node order.
82 static bool isClockwisePolygon (const Handle(BRepMesh_DataStructureOfDelaun)& theMesh,
83 const IMeshData::VectorOfInteger& theIndexes)
86 const int aNbElemNodes = theIndexes.Size();
87 for (int aNodeIter = theIndexes.Lower(); aNodeIter <= theIndexes.Upper(); ++aNodeIter)
89 int aNodeNext = theIndexes.Lower() + ((aNodeIter + 1) % aNbElemNodes);
90 const BRepMesh_Vertex& aVert1 = theMesh->GetNode (theIndexes.Value (aNodeIter));
91 const BRepMesh_Vertex& aVert2 = theMesh->GetNode (theIndexes.Value (aNodeNext));
92 aPtSum += (aVert2.Coord().X() - aVert1.Coord().X())
93 * (aVert2.Coord().Y() + aVert1.Coord().Y());
99 // ================================================================
102 // ================================================================
103 RWObj_Reader::RWObj_Reader()
104 : myMemLimitBytes (Standard_Size(-1)),
115 // ================================================================
118 // ================================================================
119 Standard_Boolean RWObj_Reader::read (const TCollection_AsciiString& theFile,
120 const Handle(Message_ProgressIndicator)& theProgress,
121 const Standard_Boolean theToProbe)
130 myObjVertsUV.Clear();
132 myPackedIndices.Clear();
134 myFileComments.Clear();
135 myExternalFiles.Clear();
136 myActiveSubMesh = RWObj_SubMesh();
138 // determine file location to load associated files
139 TCollection_AsciiString aFileName;
140 OSD_Path::FolderAndFileFromPath (theFile, myFolder, aFileName);
141 myCurrElem.resize (1024, -1);
143 Standard_CLocaleSentry aLocaleSentry;
144 RWObj_ReaderFile aFile (theFile);
145 if (aFile.File == NULL)
147 Message::DefaultMessenger()->Send (TCollection_AsciiString ("Error: file '") + theFile + "' is not found!", Message_Fail);
148 return Standard_False;
151 // determine length of file
152 const int64_t aFileLen = aFile.FileLen;
155 Message::DefaultMessenger()->Send (TCollection_AsciiString ("Error: file '") + theFile + "' is empty!", Message_Fail);
156 return Standard_False;
159 Standard_ReadLineBuffer aBuffer (THE_BUFFER_SIZE);
160 aBuffer.SetMultilineMode (true);
162 const Standard_Integer aNbMiBTotal = Standard_Integer(aFileLen / (1024 * 1024));
163 Standard_Integer aNbMiBPassed = 0;
164 Message_ProgressSentry aPSentry (theProgress, "Reading text OBJ file", 0, aNbMiBTotal, 1);
169 int64_t aPosition = 0;
171 int64_t aReadBytes = 0;
172 const char* aLine = NULL;
175 aLine = aBuffer.ReadLine (aFile.File, aLineLen, aReadBytes);
181 aPosition += aReadBytes;
182 if (aTimer.ElapsedTime() > 1.0)
184 if (!aPSentry.More())
189 const Standard_Integer aNbMiBRead = Standard_Integer(aPosition / (1024 * 1024));
190 for (; aNbMiBPassed < aNbMiBRead; ++aNbMiBPassed) { aPSentry.Next(); }
199 TCollection_AsciiString aComment (aLine + 1);
200 aComment.LeftAdjust();
201 aComment.RightAdjust();
202 if (!aComment.IsEmpty())
204 if (!myFileComments.IsEmpty())
206 myFileComments += "\n";
208 myFileComments += aComment;
213 else if (*aLine == '\n'
223 if (::memcmp (aLine, "mtllib", 6) == 0)
225 readMaterialLib (aLine + 7);
227 else if (aLine[0] == 'v' && RWObj_Tools::isSpaceChar (aLine[1]))
231 else if (aLine[0] == 'f' && RWObj_Tools::isSpaceChar (aLine[1]))
238 if (aLine[0] == 'v' && RWObj_Tools::isSpaceChar (aLine[1]))
241 pushVertex (aLine + 2);
243 else if (aLine[0] == 'v'
245 && RWObj_Tools::isSpaceChar (aLine[2]))
247 pushNormal (aLine + 3);
249 else if (aLine[0] == 'v'
251 && RWObj_Tools::isSpaceChar (aLine[2]))
253 pushTexel (aLine + 3);
255 else if (aLine[0] == 'f' && RWObj_Tools::isSpaceChar (aLine[1]))
258 pushIndices (aLine + 2);
260 else if (aLine[0] == 'g' && IsSpace (aLine[1]))
262 pushGroup (aLine + 2);
264 else if (aLine[0] == 's' && IsSpace (aLine[1]))
266 pushSmoothGroup (aLine + 2);
268 else if (aLine[0] == 'o' && IsSpace (aLine[1]))
270 pushObject (aLine + 2);
272 else if (::memcmp (aLine, "mtllib", 6) == 0)
274 readMaterialLib (aLine + 7);
276 else if (::memcmp (aLine, "usemtl", 6) == 0)
278 pushMaterial (aLine + 7);
283 addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject);
288 // collect external references
289 for (NCollection_DataMap<TCollection_AsciiString, RWObj_Material>::Iterator aMatIter (myMaterials); aMatIter.More(); aMatIter.Next())
291 const RWObj_Material& aMat = aMatIter.Value();
292 if (!aMat.DiffuseTexture.IsEmpty())
294 myExternalFiles.Add (aMat.DiffuseTexture);
296 if (!aMat.SpecularTexture.IsEmpty())
298 myExternalFiles.Add (aMat.SpecularTexture);
300 if (!aMat.BumpTexture.IsEmpty())
302 myExternalFiles.Add (aMat.BumpTexture);
306 // flush the last group
309 addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject);
311 if (myNbElemsBig != 0)
313 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: OBJ reader, ") + myNbElemsBig
314 + " polygon(s) have been split into triangles.", Message_Warning);
317 for (; aNbMiBPassed < aNbMiBTotal; ++aNbMiBPassed) { aPSentry.Next(); }
321 // =======================================================================
322 // function : pushIndices
324 // =======================================================================
325 void RWObj_Reader::pushIndices (const char* thePos)
329 Standard_Integer aNbElemNodes = 0;
330 for (Standard_Integer aNode = 0;; ++aNode)
332 Graphic3d_Vec3i a3Indices (-1, -1, -1);
333 a3Indices[0] = strtol (thePos, &aNext, 10) - 1;
344 a3Indices[1] = strtol (thePos, &aNext, 10) - 1;
347 // parse Normal index
351 a3Indices[2] = strtol (thePos, &aNext, 10) - 1;
356 // handle negative indices
357 if (a3Indices[0] < -1)
359 a3Indices[0] += myObjVerts.Upper() + 2;
361 if (a3Indices[1] < -1)
363 a3Indices[1] += myObjVertsUV.Upper() + 2;
365 if (a3Indices[2] < -1)
367 a3Indices[2] += myObjNorms.Upper() + 2;
370 Standard_Integer anIndex = -1;
371 if (!myPackedIndices.Find (a3Indices, anIndex))
373 if (a3Indices[0] >= 0)
375 myMemEstim += sizeof(Graphic3d_Vec3);
377 if (a3Indices[1] >= 0)
379 myMemEstim += sizeof(Graphic3d_Vec2);
381 if (a3Indices[2] >= 0)
383 myMemEstim += sizeof(Graphic3d_Vec3);
385 myMemEstim += sizeof(Graphic3d_Vec4i) + sizeof(Standard_Integer); // naive map
386 if (a3Indices[0] < myObjVerts.Lower() || a3Indices[0] > myObjVerts.Upper())
389 Message::DefaultMessenger()->Send (TCollection_AsciiString("Error: invalid OBJ syntax at line ") + myNbLines
390 + ": vertex index is out of range.", Message_Fail);
394 anIndex = addNode (myObjVerts.Value (a3Indices[0]));
395 myPackedIndices.Bind (a3Indices, anIndex);
396 if (a3Indices[1] >= 0)
398 if (myObjVertsUV.IsEmpty())
400 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
401 + ": UV index is specified but no UV nodes are defined.", Message_Warning);
403 else if (a3Indices[1] < myObjVertsUV.Lower() || a3Indices[1] > myObjVertsUV.Upper())
405 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
406 + ": UV index is out of range.", Message_Warning);
407 setNodeUV (anIndex,Graphic3d_Vec2 (0.0f, 0.0f));
411 setNodeUV (anIndex, myObjVertsUV.Value (a3Indices[1]));
414 if (a3Indices[2] >= 0)
416 if (myObjNorms.IsEmpty())
418 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
419 + ": Normal index is specified but no Normals nodes are defined.", Message_Warning);
421 else if (a3Indices[2] < myObjNorms.Lower() || a3Indices[2] > myObjNorms.Upper())
423 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
424 + ": Normal index is out of range.", Message_Warning);
425 setNodeNormal (anIndex, Graphic3d_Vec3 (0.0f, 0.0f, 1.0f));
429 setNodeNormal (anIndex, myObjNorms.Value (a3Indices[2]));
434 if (myCurrElem.size() < size_t(aNode))
436 myCurrElem.resize (aNode * 2, -1);
438 myCurrElem[aNode] = anIndex;
439 aNbElemNodes = aNode + 1;
453 if (myCurrElem[0] < 0
461 if (aNbElemNodes == 3)
463 myMemEstim += sizeof(Graphic3d_Vec4i);
464 addElement (myCurrElem[0], myCurrElem[1], myCurrElem[2], -1);
466 else if (aNbElemNodes == 4)
468 myMemEstim += sizeof(Graphic3d_Vec4i);
469 addElement (myCurrElem[0], myCurrElem[1], myCurrElem[2], myCurrElem[3]);
473 const NCollection_Array1<Standard_Integer> aCurrElemArray1 (myCurrElem[0], 1, aNbElemNodes);
474 const Standard_Integer aNbAdded = triangulatePolygon (aCurrElemArray1);
480 myMemEstim += sizeof(Graphic3d_Vec4i) * aNbAdded;
484 //================================================================
485 // Function : triangulatePolygonFan
487 //================================================================
488 Standard_Integer RWObj_Reader::triangulatePolygonFan (const NCollection_Array1<Standard_Integer>& theIndices)
490 const Standard_Integer aNbElemNodes = theIndices.Size();
491 for (Standard_Integer aNodeIter = 0; aNodeIter < aNbElemNodes - 2; ++aNodeIter)
493 Graphic3d_Vec4i aTriNodes (-1, -1, -1, -1);
494 for (Standard_Integer aNodeInSubTriIter = 0; aNodeInSubTriIter < 3; ++aNodeInSubTriIter)
496 const Standard_Integer aCurrNodeIndex = (aNodeInSubTriIter == 0) ? 0 : (aNodeIter + aNodeInSubTriIter);
497 aTriNodes[aNodeInSubTriIter] = theIndices.Value (theIndices.Lower() + aCurrNodeIndex);
499 addElement (aTriNodes[0], aTriNodes[1], aTriNodes[2], -1);
501 return aNbElemNodes - 2;
504 //================================================================
505 // Function : polygonCenter
507 //================================================================
508 gp_XYZ RWObj_Reader::polygonCenter (const NCollection_Array1<Standard_Integer>& theIndices)
510 if (theIndices.Size() < 3)
512 return gp_XYZ (0.0, 0.0, 0.0);
514 else if (theIndices.Size() == 4)
516 gp_XYZ aCenter = getNode (theIndices.Value (theIndices.Lower() + 0)).XYZ()
517 + getNode (theIndices.Value (theIndices.Lower() + 2)).XYZ();
522 gp_XYZ aCenter (0, 0, 0);
523 for (NCollection_Array1<Standard_Integer>::Iterator aPntIter (theIndices); aPntIter.More(); aPntIter.Next())
525 aCenter += getNode (aPntIter.Value()).XYZ();
528 aCenter /= (Standard_Real )theIndices.Size();
532 //================================================================
533 // Function : polygonNormal
535 //================================================================
536 gp_XYZ RWObj_Reader::polygonNormal (const NCollection_Array1<Standard_Integer>& theIndices)
538 const gp_XYZ aCenter = polygonCenter (theIndices);
539 gp_XYZ aMaxDir = getNode (theIndices.First()).XYZ() - aCenter;
540 gp_XYZ aNormal = (getNode (theIndices.Last()).XYZ() - aCenter).Crossed (aMaxDir);
541 for (int aPntIter = theIndices.Lower(); aPntIter < theIndices.Upper(); ++aPntIter)
543 const gp_XYZ aTmpDir2 = getNode (theIndices.Value (aPntIter + 1)).XYZ() - aCenter;
544 if (aTmpDir2.SquareModulus() > aMaxDir.SquareModulus())
549 const gp_XYZ aTmpDir1 = getNode (theIndices.Value (aPntIter)).XYZ() - aCenter;
550 gp_XYZ aDelta = aTmpDir1.Crossed (aTmpDir2);
551 if (aNormal.Dot (aDelta) < 0.0)
558 const Standard_Real aMod = aNormal.Modulus();
559 if (aMod > gp::Resolution())
566 //================================================================
567 // Function : triangulatePolygon
569 //================================================================
570 Standard_Integer RWObj_Reader::triangulatePolygon (const NCollection_Array1<Standard_Integer>& theIndices)
572 const Standard_Integer aNbElemNodes = theIndices.Size();
573 if (aNbElemNodes < 3)
578 const gp_XYZ aPolygonNorm = polygonNormal (theIndices);
580 // map polygon onto plane
583 const double aAbsXYZ[] = { Abs(aPolygonNorm.X()), Abs(aPolygonNorm.Y()), Abs(aPolygonNorm.Z()) };
584 Standard_Integer aMinI = (aAbsXYZ[0] < aAbsXYZ[1]) ? 0 : 1;
585 aMinI = (aAbsXYZ[aMinI] < aAbsXYZ[2]) ? aMinI : 2;
586 const Standard_Integer aI1 = (aMinI + 1) % 3 + 1;
587 const Standard_Integer aI2 = (aMinI + 2) % 3 + 1;
588 aXDir.ChangeCoord (aMinI + 1) = 0;
589 aXDir.ChangeCoord (aI1) = aPolygonNorm.Coord (aI2);
590 aXDir.ChangeCoord (aI2) = -aPolygonNorm.Coord (aI1);
592 const gp_XYZ aYDir = aPolygonNorm ^ aXDir;
594 Handle(NCollection_IncAllocator) anAllocator = new NCollection_IncAllocator();
595 Handle(BRepMesh_DataStructureOfDelaun) aMeshStructure = new BRepMesh_DataStructureOfDelaun (anAllocator);
596 IMeshData::VectorOfInteger anIndexes (aNbElemNodes, anAllocator);
597 for (Standard_Integer aNodeIter = 0; aNodeIter < aNbElemNodes; ++aNodeIter)
599 const Standard_Integer aNodeIndex = theIndices.Value (theIndices.Lower() + aNodeIter);
600 const gp_XYZ aPnt3d = getNode (aNodeIndex).XYZ();
601 gp_XY aPnt2d (aXDir * aPnt3d, aYDir * aPnt3d);
602 BRepMesh_Vertex aVertex (aPnt2d, aNodeIndex, BRepMesh_Frontier);
603 anIndexes.Append (aMeshStructure->AddNode (aVertex));
606 const bool isClockwiseOrdered = isClockwisePolygon (aMeshStructure, anIndexes);
607 for (Standard_Integer aIdx = anIndexes.Lower(); aIdx <= anIndexes.Upper(); ++aIdx)
609 const Standard_Integer aPtIdx = isClockwiseOrdered ? aIdx : (aIdx + 1) % anIndexes.Length();
610 const Standard_Integer aNextPtIdx = isClockwiseOrdered ? (aIdx + 1) % anIndexes.Length() : aIdx;
611 BRepMesh_Edge anEdge (anIndexes.Value (aPtIdx),
612 anIndexes.Value (aNextPtIdx),
614 aMeshStructure->AddLink (anEdge);
619 BRepMesh_Delaun aTriangulation (aMeshStructure, anIndexes);
620 const IMeshData::MapOfInteger& aTriangles = aMeshStructure->ElementsOfDomain();
621 if (aTriangles.Extent() < 1)
623 return triangulatePolygonFan (theIndices);
626 Standard_Integer aNbTrisAdded = 0;
627 for (IMeshData::MapOfInteger::Iterator aTriIter (aTriangles); aTriIter.More(); aTriIter.Next())
629 const Standard_Integer aTriangleId = aTriIter.Key();
630 const BRepMesh_Triangle& aTriangle = aMeshStructure->GetElement (aTriangleId);
631 if (aTriangle.Movability() == BRepMesh_Deleted)
637 aMeshStructure->ElementNodes (aTriangle, aTri2d);
638 if (!isClockwiseOrdered)
640 std::swap (aTri2d[1], aTri2d[2]);
642 const BRepMesh_Vertex& aVertex1 = aMeshStructure->GetNode (aTri2d[0]);
643 const BRepMesh_Vertex& aVertex2 = aMeshStructure->GetNode (aTri2d[1]);
644 const BRepMesh_Vertex& aVertex3 = aMeshStructure->GetNode (aTri2d[2]);
645 addElement (aVertex1.Location3d(), aVertex2.Location3d(), aVertex3.Location3d(), -1);
650 catch (Standard_Failure const& theFailure)
652 Message::DefaultMessenger()->Send (TCollection_AsciiString ("Error: exception raised during polygon split\n[")
653 + theFailure.GetMessageString() + "]", Message_Warning);
655 return triangulatePolygonFan (theIndices);
658 // =======================================================================
659 // function : pushObject
661 // =======================================================================
662 void RWObj_Reader::pushObject (const char* theObjectName)
664 TCollection_AsciiString aNewObject;
665 if (!RWObj_Tools::ReadName (theObjectName, aNewObject))
667 // empty group name is OK
669 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject))
671 myPackedIndices.Clear(); // vertices might be duplicated after this point...
673 myActiveSubMesh.Object = aNewObject;
676 // =======================================================================
677 // function : pushGroup
679 // =======================================================================
680 void RWObj_Reader::pushGroup (const char* theGroupName)
682 TCollection_AsciiString aNewGroup;
683 if (!RWObj_Tools::ReadName (theGroupName, aNewGroup))
685 // empty group name is OK
687 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewGroup))
689 myPackedIndices.Clear(); // vertices might be duplicated after this point...
691 myActiveSubMesh.Group = aNewGroup;
694 // =======================================================================
695 // function : pushSmoothGroup
697 // =======================================================================
698 void RWObj_Reader::pushSmoothGroup (const char* theSmoothGroupIndex)
700 TCollection_AsciiString aNewSmoothGroup;
701 RWObj_Tools::ReadName (theSmoothGroupIndex, aNewSmoothGroup);
702 if (aNewSmoothGroup == "off"
703 || aNewSmoothGroup == "0")
705 aNewSmoothGroup.Clear();
707 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewSmoothGroup))
709 myPackedIndices.Clear(); // vertices might be duplicated after this point...
711 myActiveSubMesh.SmoothGroup = aNewSmoothGroup;
714 // =======================================================================
715 // function : pushMaterial
717 // =======================================================================
718 void RWObj_Reader::pushMaterial (const char* theMaterialName)
720 TCollection_AsciiString aNewMat;
721 if (!RWObj_Tools::ReadName (theMaterialName, aNewMat))
723 // empty material name is allowed by specs
725 else if (!myMaterials.IsBound (aNewMat))
727 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: use of undefined OBJ material at line ")
728 + myNbLines, Message_Warning);
731 if (myActiveSubMesh.Material.IsEqual (aNewMat))
736 // implicitly create a new group to split materials
737 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewMaterial))
739 myPackedIndices.Clear(); // vertices might be duplicated after this point...
741 myActiveSubMesh.Material = aNewMat;
744 // =======================================================================
745 // function : readMaterialLib
747 // =======================================================================
748 void RWObj_Reader::readMaterialLib (const char* theFileName)
750 TCollection_AsciiString aMatPath;
751 if (!RWObj_Tools::ReadName (theFileName, aMatPath))
753 Message::DefaultMessenger()->Send (TCollection_AsciiString("Warning: invalid OBJ syntax at line ")
754 + myNbLines, Message_Warning);
758 RWObj_MtlReader aMatReader (myMaterials);
759 if (aMatReader.Read (myFolder, aMatPath))
761 myExternalFiles.Add (myFolder + aMatPath);
765 // =======================================================================
766 // function : checkMemory
768 // =======================================================================
769 bool RWObj_Reader::checkMemory()
771 if (myMemEstim < myMemLimitBytes
777 Message::DefaultMessenger()->Send (TCollection_AsciiString("Error: OBJ file content does not fit into ")
778 + Standard_Integer(myMemLimitBytes / (1024 * 1024)) + " MiB limit."
779 + "\nMesh data will be truncated.", Message_Fail);