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_ProgressScope.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 Message_ProgressRange& 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::SendFail (TCollection_AsciiString ("Error: file '") + theFile + "' is not found");
148 return Standard_False;
151 // determine length of file
152 const int64_t aFileLen = aFile.FileLen;
155 Message::SendFail (TCollection_AsciiString ("Error: file '") + theFile + "' is empty");
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_ProgressScope aPS (theProgress, "Reading text OBJ file", aNbMiBTotal);
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)
189 const Standard_Integer aNbMiBRead = Standard_Integer(aPosition / (1024 * 1024));
190 aPS.Next (aNbMiBRead - aNbMiBPassed);
191 aNbMiBPassed = aNbMiBRead;
200 TCollection_AsciiString aComment (aLine + 1);
201 aComment.LeftAdjust();
202 aComment.RightAdjust();
203 if (!aComment.IsEmpty())
205 if (!myFileComments.IsEmpty())
207 myFileComments += "\n";
209 myFileComments += aComment;
214 else if (*aLine == '\n'
224 if (::strncmp (aLine, "mtllib", 6) == 0)
226 readMaterialLib (IsSpace (aLine[6]) ? aLine + 7 : "");
228 else if (aLine[0] == 'v' && RWObj_Tools::isSpaceChar (aLine[1]))
232 else if (aLine[0] == 'f' && RWObj_Tools::isSpaceChar (aLine[1]))
239 if (aLine[0] == 'v' && RWObj_Tools::isSpaceChar (aLine[1]))
242 pushVertex (aLine + 2);
244 else if (aLine[0] == 'v'
246 && RWObj_Tools::isSpaceChar (aLine[2]))
248 pushNormal (aLine + 3);
250 else if (aLine[0] == 'v'
252 && RWObj_Tools::isSpaceChar (aLine[2]))
254 pushTexel (aLine + 3);
256 else if (aLine[0] == 'f' && RWObj_Tools::isSpaceChar (aLine[1]))
259 pushIndices (aLine + 2);
261 else if (aLine[0] == 'g' && IsSpace (aLine[1]))
263 pushGroup (aLine + 2);
265 else if (aLine[0] == 's' && IsSpace (aLine[1]))
267 pushSmoothGroup (aLine + 2);
269 else if (aLine[0] == 'o' && IsSpace (aLine[1]))
271 pushObject (aLine + 2);
273 else if (::strncmp (aLine, "mtllib", 6) == 0)
275 readMaterialLib (IsSpace (aLine[6]) ? aLine + 7 : "");
277 else if (::strncmp (aLine, "usemtl", 6) == 0)
279 pushMaterial (IsSpace (aLine[6]) ? aLine + 7 : "");
284 addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject);
289 // collect external references
290 for (NCollection_DataMap<TCollection_AsciiString, RWObj_Material>::Iterator aMatIter (myMaterials); aMatIter.More(); aMatIter.Next())
292 const RWObj_Material& aMat = aMatIter.Value();
293 if (!aMat.DiffuseTexture.IsEmpty())
295 myExternalFiles.Add (aMat.DiffuseTexture);
297 if (!aMat.SpecularTexture.IsEmpty())
299 myExternalFiles.Add (aMat.SpecularTexture);
301 if (!aMat.BumpTexture.IsEmpty())
303 myExternalFiles.Add (aMat.BumpTexture);
307 // flush the last group
310 addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject);
312 if (myNbElemsBig != 0)
314 Message::SendWarning (TCollection_AsciiString("Warning: OBJ reader, ") + myNbElemsBig + " polygon(s) have been split into triangles");
320 // =======================================================================
321 // function : pushIndices
323 // =======================================================================
324 void RWObj_Reader::pushIndices (const char* thePos)
328 Standard_Integer aNbElemNodes = 0;
329 for (Standard_Integer aNode = 0;; ++aNode)
331 Graphic3d_Vec3i a3Indices (-1, -1, -1);
332 a3Indices[0] = strtol (thePos, &aNext, 10) - 1;
343 a3Indices[1] = strtol (thePos, &aNext, 10) - 1;
346 // parse Normal index
350 a3Indices[2] = strtol (thePos, &aNext, 10) - 1;
355 // handle negative indices
356 if (a3Indices[0] < -1)
358 a3Indices[0] += myObjVerts.Upper() + 2;
360 if (a3Indices[1] < -1)
362 a3Indices[1] += myObjVertsUV.Upper() + 2;
364 if (a3Indices[2] < -1)
366 a3Indices[2] += myObjNorms.Upper() + 2;
369 Standard_Integer anIndex = -1;
370 if (!myPackedIndices.Find (a3Indices, anIndex))
372 if (a3Indices[0] >= 0)
374 myMemEstim += sizeof(Graphic3d_Vec3);
376 if (a3Indices[1] >= 0)
378 myMemEstim += sizeof(Graphic3d_Vec2);
380 if (a3Indices[2] >= 0)
382 myMemEstim += sizeof(Graphic3d_Vec3);
384 myMemEstim += sizeof(Graphic3d_Vec4i) + sizeof(Standard_Integer); // naive map
385 if (a3Indices[0] < myObjVerts.Lower() || a3Indices[0] > myObjVerts.Upper())
388 Message::SendFail (TCollection_AsciiString("Error: invalid OBJ syntax at line ") + myNbLines + ": vertex index is out of range");
392 anIndex = addNode (myObjVerts.Value (a3Indices[0]));
393 myPackedIndices.Bind (a3Indices, anIndex);
394 if (a3Indices[1] >= 0)
396 if (myObjVertsUV.IsEmpty())
398 Message::SendWarning (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
399 + ": UV index is specified but no UV nodes are defined");
401 else if (a3Indices[1] < myObjVertsUV.Lower() || a3Indices[1] > myObjVertsUV.Upper())
403 Message::SendWarning (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
404 + ": UV index is out of range");
405 setNodeUV (anIndex,Graphic3d_Vec2 (0.0f, 0.0f));
409 setNodeUV (anIndex, myObjVertsUV.Value (a3Indices[1]));
412 if (a3Indices[2] >= 0)
414 if (myObjNorms.IsEmpty())
416 Message::SendWarning (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
417 + ": Normal index is specified but no Normals nodes are defined");
419 else if (a3Indices[2] < myObjNorms.Lower() || a3Indices[2] > myObjNorms.Upper())
421 Message::SendWarning (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines
422 + ": Normal index is out of range");
423 setNodeNormal (anIndex, Graphic3d_Vec3 (0.0f, 0.0f, 1.0f));
427 setNodeNormal (anIndex, myObjNorms.Value (a3Indices[2]));
432 if (myCurrElem.size() < size_t(aNode))
434 myCurrElem.resize (aNode * 2, -1);
436 myCurrElem[aNode] = anIndex;
437 aNbElemNodes = aNode + 1;
451 if (myCurrElem[0] < 0
459 if (aNbElemNodes == 3)
461 myMemEstim += sizeof(Graphic3d_Vec4i);
462 addElement (myCurrElem[0], myCurrElem[1], myCurrElem[2], -1);
464 else if (aNbElemNodes == 4)
466 myMemEstim += sizeof(Graphic3d_Vec4i);
467 addElement (myCurrElem[0], myCurrElem[1], myCurrElem[2], myCurrElem[3]);
471 const NCollection_Array1<Standard_Integer> aCurrElemArray1 (myCurrElem[0], 1, aNbElemNodes);
472 const Standard_Integer aNbAdded = triangulatePolygon (aCurrElemArray1);
478 myMemEstim += sizeof(Graphic3d_Vec4i) * aNbAdded;
482 //================================================================
483 // Function : triangulatePolygonFan
485 //================================================================
486 Standard_Integer RWObj_Reader::triangulatePolygonFan (const NCollection_Array1<Standard_Integer>& theIndices)
488 const Standard_Integer aNbElemNodes = theIndices.Size();
489 for (Standard_Integer aNodeIter = 0; aNodeIter < aNbElemNodes - 2; ++aNodeIter)
491 Graphic3d_Vec4i aTriNodes (-1, -1, -1, -1);
492 for (Standard_Integer aNodeInSubTriIter = 0; aNodeInSubTriIter < 3; ++aNodeInSubTriIter)
494 const Standard_Integer aCurrNodeIndex = (aNodeInSubTriIter == 0) ? 0 : (aNodeIter + aNodeInSubTriIter);
495 aTriNodes[aNodeInSubTriIter] = theIndices.Value (theIndices.Lower() + aCurrNodeIndex);
497 addElement (aTriNodes[0], aTriNodes[1], aTriNodes[2], -1);
499 return aNbElemNodes - 2;
502 //================================================================
503 // Function : polygonCenter
505 //================================================================
506 gp_XYZ RWObj_Reader::polygonCenter (const NCollection_Array1<Standard_Integer>& theIndices)
508 if (theIndices.Size() < 3)
510 return gp_XYZ (0.0, 0.0, 0.0);
512 else if (theIndices.Size() == 4)
514 gp_XYZ aCenter = getNode (theIndices.Value (theIndices.Lower() + 0)).XYZ()
515 + getNode (theIndices.Value (theIndices.Lower() + 2)).XYZ();
520 gp_XYZ aCenter (0, 0, 0);
521 for (NCollection_Array1<Standard_Integer>::Iterator aPntIter (theIndices); aPntIter.More(); aPntIter.Next())
523 aCenter += getNode (aPntIter.Value()).XYZ();
526 aCenter /= (Standard_Real )theIndices.Size();
530 //================================================================
531 // Function : polygonNormal
533 //================================================================
534 gp_XYZ RWObj_Reader::polygonNormal (const NCollection_Array1<Standard_Integer>& theIndices)
536 const gp_XYZ aCenter = polygonCenter (theIndices);
537 gp_XYZ aMaxDir = getNode (theIndices.First()).XYZ() - aCenter;
538 gp_XYZ aNormal = (getNode (theIndices.Last()).XYZ() - aCenter).Crossed (aMaxDir);
539 for (int aPntIter = theIndices.Lower(); aPntIter < theIndices.Upper(); ++aPntIter)
541 const gp_XYZ aTmpDir2 = getNode (theIndices.Value (aPntIter + 1)).XYZ() - aCenter;
542 if (aTmpDir2.SquareModulus() > aMaxDir.SquareModulus())
547 const gp_XYZ aTmpDir1 = getNode (theIndices.Value (aPntIter)).XYZ() - aCenter;
548 gp_XYZ aDelta = aTmpDir1.Crossed (aTmpDir2);
549 if (aNormal.Dot (aDelta) < 0.0)
556 const Standard_Real aMod = aNormal.Modulus();
557 if (aMod > gp::Resolution())
564 //================================================================
565 // Function : triangulatePolygon
567 //================================================================
568 Standard_Integer RWObj_Reader::triangulatePolygon (const NCollection_Array1<Standard_Integer>& theIndices)
570 const Standard_Integer aNbElemNodes = theIndices.Size();
571 if (aNbElemNodes < 3)
576 const gp_XYZ aPolygonNorm = polygonNormal (theIndices);
578 // map polygon onto plane
581 const double aAbsXYZ[] = { Abs(aPolygonNorm.X()), Abs(aPolygonNorm.Y()), Abs(aPolygonNorm.Z()) };
582 Standard_Integer aMinI = (aAbsXYZ[0] < aAbsXYZ[1]) ? 0 : 1;
583 aMinI = (aAbsXYZ[aMinI] < aAbsXYZ[2]) ? aMinI : 2;
584 const Standard_Integer aI1 = (aMinI + 1) % 3 + 1;
585 const Standard_Integer aI2 = (aMinI + 2) % 3 + 1;
586 aXDir.ChangeCoord (aMinI + 1) = 0;
587 aXDir.ChangeCoord (aI1) = aPolygonNorm.Coord (aI2);
588 aXDir.ChangeCoord (aI2) = -aPolygonNorm.Coord (aI1);
590 const gp_XYZ aYDir = aPolygonNorm ^ aXDir;
592 Handle(NCollection_IncAllocator) anAllocator = new NCollection_IncAllocator();
593 Handle(BRepMesh_DataStructureOfDelaun) aMeshStructure = new BRepMesh_DataStructureOfDelaun (anAllocator);
594 IMeshData::VectorOfInteger anIndexes (aNbElemNodes, anAllocator);
595 for (Standard_Integer aNodeIter = 0; aNodeIter < aNbElemNodes; ++aNodeIter)
597 const Standard_Integer aNodeIndex = theIndices.Value (theIndices.Lower() + aNodeIter);
598 const gp_XYZ aPnt3d = getNode (aNodeIndex).XYZ();
599 gp_XY aPnt2d (aXDir * aPnt3d, aYDir * aPnt3d);
600 BRepMesh_Vertex aVertex (aPnt2d, aNodeIndex, BRepMesh_Frontier);
601 anIndexes.Append (aMeshStructure->AddNode (aVertex));
604 const bool isClockwiseOrdered = isClockwisePolygon (aMeshStructure, anIndexes);
605 for (Standard_Integer aIdx = anIndexes.Lower(); aIdx <= anIndexes.Upper(); ++aIdx)
607 const Standard_Integer aPtIdx = isClockwiseOrdered ? aIdx : (aIdx + 1) % anIndexes.Length();
608 const Standard_Integer aNextPtIdx = isClockwiseOrdered ? (aIdx + 1) % anIndexes.Length() : aIdx;
609 BRepMesh_Edge anEdge (anIndexes.Value (aPtIdx),
610 anIndexes.Value (aNextPtIdx),
612 aMeshStructure->AddLink (anEdge);
617 BRepMesh_Delaun aTriangulation (aMeshStructure, anIndexes);
618 const IMeshData::MapOfInteger& aTriangles = aMeshStructure->ElementsOfDomain();
619 if (aTriangles.Extent() < 1)
621 return triangulatePolygonFan (theIndices);
624 Standard_Integer aNbTrisAdded = 0;
625 for (IMeshData::MapOfInteger::Iterator aTriIter (aTriangles); aTriIter.More(); aTriIter.Next())
627 const Standard_Integer aTriangleId = aTriIter.Key();
628 const BRepMesh_Triangle& aTriangle = aMeshStructure->GetElement (aTriangleId);
629 if (aTriangle.Movability() == BRepMesh_Deleted)
635 aMeshStructure->ElementNodes (aTriangle, aTri2d);
636 if (!isClockwiseOrdered)
638 std::swap (aTri2d[1], aTri2d[2]);
640 const BRepMesh_Vertex& aVertex1 = aMeshStructure->GetNode (aTri2d[0]);
641 const BRepMesh_Vertex& aVertex2 = aMeshStructure->GetNode (aTri2d[1]);
642 const BRepMesh_Vertex& aVertex3 = aMeshStructure->GetNode (aTri2d[2]);
643 addElement (aVertex1.Location3d(), aVertex2.Location3d(), aVertex3.Location3d(), -1);
648 catch (Standard_Failure const& theFailure)
650 Message::SendWarning (TCollection_AsciiString ("Error: exception raised during polygon split\n[") + theFailure.GetMessageString() + "]");
652 return triangulatePolygonFan (theIndices);
655 // =======================================================================
656 // function : pushObject
658 // =======================================================================
659 void RWObj_Reader::pushObject (const char* theObjectName)
661 TCollection_AsciiString aNewObject;
662 if (!RWObj_Tools::ReadName (theObjectName, aNewObject))
664 // empty group name is OK
666 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewObject))
668 myPackedIndices.Clear(); // vertices might be duplicated after this point...
670 myActiveSubMesh.Object = aNewObject;
673 // =======================================================================
674 // function : pushGroup
676 // =======================================================================
677 void RWObj_Reader::pushGroup (const char* theGroupName)
679 TCollection_AsciiString aNewGroup;
680 if (!RWObj_Tools::ReadName (theGroupName, aNewGroup))
682 // empty group name is OK
684 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewGroup))
686 myPackedIndices.Clear(); // vertices might be duplicated after this point...
688 myActiveSubMesh.Group = aNewGroup;
691 // =======================================================================
692 // function : pushSmoothGroup
694 // =======================================================================
695 void RWObj_Reader::pushSmoothGroup (const char* theSmoothGroupIndex)
697 TCollection_AsciiString aNewSmoothGroup;
698 RWObj_Tools::ReadName (theSmoothGroupIndex, aNewSmoothGroup);
699 if (aNewSmoothGroup == "off"
700 || aNewSmoothGroup == "0")
702 aNewSmoothGroup.Clear();
704 if (myActiveSubMesh.SmoothGroup.IsEqual (aNewSmoothGroup))
706 // Ignore duplicated statements to workaround some weird OBJ files.
707 // Note that smooth groups are handled in different manner than groups and objects,
708 // which always flushed even with equal names.
712 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewSmoothGroup))
714 myPackedIndices.Clear(); // vertices might be duplicated after this point...
716 myActiveSubMesh.SmoothGroup = aNewSmoothGroup;
719 // =======================================================================
720 // function : pushMaterial
722 // =======================================================================
723 void RWObj_Reader::pushMaterial (const char* theMaterialName)
725 TCollection_AsciiString aNewMat;
726 if (!RWObj_Tools::ReadName (theMaterialName, aNewMat))
728 // empty material name is allowed by specs
730 else if (!myMaterials.IsBound (aNewMat))
732 Message::SendWarning (TCollection_AsciiString("Warning: use of undefined OBJ material at line ") + myNbLines);
735 if (myActiveSubMesh.Material.IsEqual (aNewMat))
740 // implicitly create a new group to split materials
741 if (addMesh (myActiveSubMesh, RWObj_SubMeshReason_NewMaterial))
743 myPackedIndices.Clear(); // vertices might be duplicated after this point...
745 myActiveSubMesh.Material = aNewMat;
748 // =======================================================================
749 // function : readMaterialLib
751 // =======================================================================
752 void RWObj_Reader::readMaterialLib (const char* theFileName)
754 TCollection_AsciiString aMatPath;
755 if (!RWObj_Tools::ReadName (theFileName, aMatPath))
757 Message::SendWarning (TCollection_AsciiString("Warning: invalid OBJ syntax at line ") + myNbLines);
761 RWObj_MtlReader aMatReader (myMaterials);
762 if (aMatReader.Read (myFolder, aMatPath))
764 myExternalFiles.Add (myFolder + aMatPath);
768 // =======================================================================
769 // function : checkMemory
771 // =======================================================================
772 bool RWObj_Reader::checkMemory()
774 if (myMemEstim < myMemLimitBytes
780 Message::SendFail (TCollection_AsciiString("Error: OBJ file content does not fit into ")
781 + Standard_Integer(myMemLimitBytes / (1024 * 1024)) + " MiB limit."
782 + "\nMesh data will be truncated.");