commit 907922fdee5544431acb36da34c5e542604fa854 Author: Leonardo Fischer Date: Sat Nov 10 10:27:37 2012 -0200 The first commit diff --git a/DCEL_Example.sln b/DCEL_Example.sln new file mode 100644 index 0000000..397a2d7 --- /dev/null +++ b/DCEL_Example.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DCEL_Example", "DCEL_Example.vcproj", "{6E4B73C0-2BD7-4E6C-B52E-F5D157D0E98A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6E4B73C0-2BD7-4E6C-B52E-F5D157D0E98A}.Debug|Win32.ActiveCfg = Debug|Win32 + {6E4B73C0-2BD7-4E6C-B52E-F5D157D0E98A}.Debug|Win32.Build.0 = Debug|Win32 + {6E4B73C0-2BD7-4E6C-B52E-F5D157D0E98A}.Release|Win32.ActiveCfg = Release|Win32 + {6E4B73C0-2BD7-4E6C-B52E-F5D157D0E98A}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/DCEL_Example.vcproj b/DCEL_Example.vcproj new file mode 100644 index 0000000..7407bd6 --- /dev/null +++ b/DCEL_Example.vcproj @@ -0,0 +1,235 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENCE.txt b/LICENCE.txt new file mode 100644 index 0000000..fb3d94a --- /dev/null +++ b/LICENCE.txt @@ -0,0 +1,23 @@ +DCEL Library by Leonardo Garcia Fischer - Licence of Use + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/source/DCEL/DCELStream.h b/source/DCEL/DCELStream.h new file mode 100644 index 0000000..5612203 --- /dev/null +++ b/source/DCEL/DCELStream.h @@ -0,0 +1,272 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCELStream_h +#define DCELStream_h + +#include +#include "Mesh.h" + +template +class DCELStream +{ +public: + + static void read(MeshT& mesh, std::istream &stream); + + /** + Format: + + version 1 + #this is a comment + vc + fc + ec + v + ... # repeat v for vc times, one for each vertex + f + ... # repeat f for fc times, one for each face + e + ... # repeat e for ec times, one for each half edge + end + */ + static void write(const MeshT& mesh, std::ostream &stream); + + template + static void copyDcelData(const MeshT& source, MeshT2& target ) + { + const MeshT::Vertex* vertex = NULL; + const unsigned int numVertices = source.getNumVertices(); + const MeshT::Face* face = NULL; + const unsigned int numFaces = source.getNumFaces(); + const MeshT::HalfEdge* edge = NULL; + const unsigned int numEdges = source.getNumHalfEdges(); + + target.clear(); + target.getVertices().reserve( numVertices ); + target.getFaces().reserve( numFaces ); + target.getHalfEdges().reserve( numEdges ); + + for( unsigned int vertexId=0; vertexIdgetOrigin() ); + ++vertexCount; + } + target.createTriangularFace( vid[0], vid[1], vid[2] ); + + // convert here the data from the source to target faces + } + + /* + for( unsigned int edgeId=0; edgeId +void DCELStream::read(MeshT& mesh, std::istream &stream) +{ + while( stream.good() ) + { + std::string str; + stream >> str; + if( str=="version" ) + { + unsigned int version; + stream >> version; + switch(version) + { + case 1: + read_v1(mesh, stream); + break; + default: + std::cerr << "Warning: unknown version " << version << std::endl; + } + } + else if( str.at(0)=='#' ) + { + consumeComment(str, stream); + } + else + { + std::cerr << "Unknown line: " << str << std::endl; + } + } +} + +template +void DCELStream::write(const MeshT& mesh, std::ostream &stream) +{ + const MeshT::Vertex* vertex = NULL; + const unsigned int numVertices = mesh.getNumVertices(); + const MeshT::Face* face = NULL; + const unsigned int numFaces = mesh.getNumFaces(); + const MeshT::HalfEdge* edge = NULL; + const unsigned int numEdges = mesh.getNumHalfEdges(); + + stream << "version 1" << std::endl; + + stream << "vc " << numVertices << std::endl; + stream << "fc " << numFaces << std::endl; + stream << "ec " << numEdges << std::endl; + + for( unsigned int vertexId=0; vertexIdgetData() << std::endl; + } + + for( unsigned int faceId=0; faceIdgetOrigin() ); + ++vertexCount; + } + stream << vertexCount; + for( unsigned int v=0; vgetData(); + stream << std::endl; + } + + for( unsigned int edgeId=0; edgeIdgetOrigin() ) + << " " << mesh.getVertexId( edge->getTwin()->getOrigin() ) + << " " << edge->getData() << std::endl; + } + + stream << "end"; +} + +template +void DCELStream::read_v1(MeshT& mesh, std::istream &stream) +{ + std::string str; + + bool reading = true; + while( reading && stream.good() ) + { + stream >> str; + + if( str=="v" ) + { + MeshT::Vertex* vertex = mesh.getVertex( mesh.createVertex() ); + stream >> (vertex->getData()); + } + else if( str=="f" ) + { + unsigned int vertexCount; + stream >> vertexCount; + unsigned int vid[3];//TODO generalize + for( unsigned int i=0; i> (vid[i]); + + unsigned int fid = mesh.createTriangularFace( vid[0], vid[1], vid[2] ); + MeshT::Face* face = mesh.getFace( fid ); + stream >> face->getData(); + } + else if( str=="e" ) + { + unsigned int from, to; + stream >> from >> to; + MeshT::HalfEdge* edge = mesh.getHalfEdge( mesh.getVertex(from), mesh.getVertex(to) ); + if( edge ) + { + stream >> edge->getData(); + } + else + { + std::cerr << '?'; + } + } + + else if( str=="vc" ) + { + unsigned int vc = -1; + stream >> vc; + mesh.getVertices().reserve( vc*5 ); + } + else if( str=="fc" ) + { + unsigned int fc = -1; + stream >> fc; + mesh.getFaces().reserve( fc*5 ); + } + else if( str=="ec" ) + { + unsigned int ec = -1; + stream >> ec; + mesh.getHalfEdges().reserve( ec*5 ); + } + else if( str=="end" ) + { + reading = false; + } + else if( str.at(0)=='#' ) + { + consumeComment(str, stream); + } + else + { + std::cerr << "Unknown line: " << str; + } + } + mesh.manageUnhandledTriangles(); +} + +template +void DCELStream::consumeComment(const std::string& commentBegin, std::istream &stream) +{ + char buffer[512]; + stream.getline( buffer, sizeof(buffer) ); + std::cerr << commentBegin << " " << buffer << std::endl; +} + +#endif//DCELStream_h diff --git a/source/DCEL/EdgeIterator.h b/source/DCEL/EdgeIterator.h new file mode 100644 index 0000000..0dec165 --- /dev/null +++ b/source/DCEL/EdgeIterator.h @@ -0,0 +1,125 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCEL_EdgeIterator_h +#define DCEL_EdgeIterator_h + +#include "Vertex.h" +#include "Face.h" +#include "HalfEdge.h" +//#include + +/** + A class that helps the iteration of the edges of a vertice or face. + + In the case of a vertex, it runs over each edge that has the given + edge as origin. + + In the case of a face, it runs over each edge that forms the boundary + of that face. +*/ +template +class EdgeIteratorT +{ + typedef VertexT Vertex; + typedef HalfEdgeT HalfEdge; + typedef FaceT Face; + +public: + + /** + Creates an EdgeIterator that runs over each edge that starts on the + given vertex. + */ + inline EdgeIteratorT(const Vertex* vertex) + { + reset(vertex); + }; + + /** + Creates an EdgeIterator that runs over each edge that forms the + boundary of the given face. + */ + inline EdgeIteratorT(const Face* face) + { + reset(face); + }; + + /** + Returns the next edge in the sequence. + + Returns NULL if all the sequence of edges has ended. + */ + inline HalfEdge* getNext() + { + HalfEdge* next = nextEdge; + + if( nextEdge ) + { + if( vertexIterator ) // edges starting at a vertex iterator + { + HalfEdge* twin = nextEdge->getTwin(); + //assert(twin); + nextEdge = twin->getNext(); + } + else // edges from face iterator + { + nextEdge = nextEdge->getNext(); + } + } + + if( nextEdge==startEdge ) + { + nextEdge = NULL; + } + + return next; + }; + + /** + Check if there is any edge in the sequence of edges. + */ + inline bool hasNext() const + { + return nextEdge!=NULL; + }; + + /** + Makes the iterator start again, from the first edge + of the sequence. + */ + inline void reset() + { + nextEdge = startEdge; + }; + + inline void reset(const Vertex* vertex) + { + //assert(vertex); + vertexIterator = true; + startEdge = vertex->getIncidentEdge(); + reset(); + }; + + inline void reset(const Face* face) + { + //assert(face); + vertexIterator = false; + startEdge = face->getBoundary(); + reset(); + }; + +protected: +private: + HalfEdge* startEdge; + HalfEdge* nextEdge; + bool vertexIterator; +}; + +#endif//DCEL_EdgeIterator_h diff --git a/source/DCEL/Exception.h b/source/DCEL/Exception.h new file mode 100644 index 0000000..6bdf70a --- /dev/null +++ b/source/DCEL/Exception.h @@ -0,0 +1,58 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef Exception_h +#define Exception_h + +#include +#include + +namespace cpp +{ + class Exception: public std::exception + { + public: + Exception(const char* m) + :msg(m) + {}; + + Exception(const std::string& msg) + : msg(msg) + {}; + + Exception(const std::exception& e) + : msg(e.what()) + { + } + + ~Exception() throw() + {} + + Exception& operator=(const std::exception& e) throw() + { + this->msg = e.what(); + return *this; + } + + virtual const char* what() const throw() + { + return msg.c_str(); + } + + virtual const std::string& message() const + { + return this->msg; + } + + private: + std::string msg; + }; +}; + +#endif//Exception_h diff --git a/source/DCEL/Face.h b/source/DCEL/Face.h new file mode 100644 index 0000000..0800f82 --- /dev/null +++ b/source/DCEL/Face.h @@ -0,0 +1,58 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCEL_Face_h +#define DCEL_Face_h + +//#include + +template +class HalfEdgeT; + +template +class FaceT +{ + typedef HalfEdgeT HalfEdge; + typedef FaceT Face; + +public: + + FaceT(): + boundary( NULL ) + { + }; + + inline HalfEdge* getBoundary() const + { + return this->boundary; + }; + + inline void setBoundary(HalfEdge* bound) + { + //assert( this ); + this->boundary = bound; + }; + + inline FaceDataT& getData() + { + return data; + }; + + inline const FaceDataT& getData() const + { + return data; + }; + +protected: +private: + HalfEdge* boundary; + FaceDataT data; +}; + +#endif//DCEL_Face_h diff --git a/source/DCEL/HalfEdge.h b/source/DCEL/HalfEdge.h new file mode 100644 index 0000000..1bf0ab2 --- /dev/null +++ b/source/DCEL/HalfEdge.h @@ -0,0 +1,123 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCEL_HalfEdge_h +#define DCEL_HalfEdge_h + +//#include + +template +class VertexT; + +template +class FaceT; + +template +class HalfEdgeT +{ + typedef VertexT Vertex; + typedef HalfEdgeT HalfEdge; + typedef FaceT Face; + +public: + + HalfEdgeT( ): + data(), + twin(NULL), + next(NULL), + prev(NULL), + origin(NULL), + face(NULL) + { + }; + + inline HalfEdge* getTwin() const + { + //assert(this); + return this->twin; + }; + + inline void setTwin(HalfEdge* newTwin) + { + //assert(this); + this->twin = newTwin; + newTwin->twin = this; + }; + + inline HalfEdge* getNext() const + { + //assert(this); + return this->next; + }; + + inline void setNext(HalfEdge* newNext) + { + //assert(this); + this->next = newNext; + newNext->prev = this; + }; + + inline HalfEdge* getPrev() const + { + //assert(this); + return this->prev; + }; + + inline void setPrev(HalfEdge* newPrev) + { + //assert(this); + this->prev = newPrev; + newPrev->next = this; + }; + + inline Vertex* getOrigin() const + { + //assert(this); + return this->origin; + }; + + inline void setOrigin(Vertex* newOrigin) + { + //assert(this); + this->origin = newOrigin; + }; + + inline Face* getFace() const + { + //assert(this); + return this->face; + }; + + inline void setFace(Face* newFace) + { + //assert(this); + this->face = newFace; + }; + + inline HalfEdgeDataT& getData() + { + return data; + }; + + inline const HalfEdgeDataT& getData() const + { + return data; + }; + +protected: +private: + HalfEdge* twin; + HalfEdge* next; + HalfEdge* prev; + Vertex* origin; + Face* face; + HalfEdgeDataT data; +}; + +#endif//DCEL_HalfEdge_h diff --git a/source/DCEL/Mesh.h b/source/DCEL/Mesh.h new file mode 100644 index 0000000..75410a2 --- /dev/null +++ b/source/DCEL/Mesh.h @@ -0,0 +1,1035 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCEL_Mesh_h +#define DCEL_Mesh_h + +#include +#include + +#include "Vertex.h" +#include "Face.h" +#include "HalfEdge.h" +#include "EdgeIterator.h" + +#include "Exception.h" + +/** + A class that stores the mesh structure. It the list of the vertices, edges and faces. + Also, it has some methods for simplify the mesh manipulation. +*/ +template +class Mesh +{ + typedef Mesh MeshT; +public: + + typedef VertexT Vertex; + typedef HalfEdgeT HalfEdge; + typedef FaceT Face; + typedef EdgeIteratorT EdgeIterator; + + typedef VertexDataT VertexData; + typedef HalfEdgeDataT HalfEdgeData; + typedef FaceDataT FaceData; + + Mesh( ); + + ~Mesh( ); + + /** + Creates a new, unused vertex on the mesh. + + Returns the id of the created vertex. + */ + unsigned int createVertex( ); + + /** + Creates a new, unused vertex on the mesh. + + Returns the pointer to the vertex itself. + */ + Vertex* createGetVertex(); + + /** + Create a face, that has its boundary pointing to bound. + */ + unsigned int createFace( HalfEdge* bound ); + + /** + Create an edge between the vertex origin and twinOrigin. Return the + ID of the half-edge that has origin as its origin vertex. + + Actually, this method will create two half edges, and will set their + origin, set their face pointers and each one will have the other as + their. + + The two half-edges will be placed in the edge's list sequentially. + */ + unsigned int createEdge( Vertex* origin, Face* face, Vertex* twinOrigin, Face* twinFace ); + + /** + Adds a new face to the mesh. The face is bounded by previously + added vertices, that are identified by the given IDs. + + The IDs must be given in a CCW order. No checking is done about this. + If the vertices are not in a CCW order, the structure may become corrupted. + + Returns the id of the created face. + */ + unsigned int createTriangularFace(unsigned int vId1, unsigned int vId2, unsigned int vId3); + + /** + Returns a pointer to the given vertex ID. + */ + inline Vertex* getVertex( unsigned int id ) const; + + /** + Return the list of vertices. + */ + inline std::vector& getVertices(); + + /** + Returns the list of vertices, for const operations. + */ + inline const std::vector& getVertices() const; + + /** + Returns the current number of vertices stored on the mesh. + + The first vertex has ID=0 and the last one has ID=-1 + */ + inline unsigned int getNumVertices() const; + + /** + Computes the ID of a given vertex. + */ + inline unsigned int getVertexId( const Vertex* vertex ) const; + + /** + Returns the list of faces. + */ + inline std::vector& getFaces( ); + + /** + Returns the number of faces that this mesh has. + + The first face has ID=0 and the last one has ID=-1 + */ + inline unsigned int getNumFaces() const; + + /** + Returns the list of faces, for const operations + */ + inline const std::vector& getFaces( ) const; + + /** + Returns the face with the given ID. + */ + inline Face* getFace( unsigned int faceId ) const; + + /** + Returns the ID of a given pointer face. The + ID can be used in the method getFace(id) to + retrieve the same pointer. + */ + inline unsigned int getFaceId( const Face* face) const; + + /** + Return the list of half-edges. + + Note that this list contains the two half-edges of each edge of the + mesh. When this mesh is created using the create*Face methods, + each half edge and its twin is adjacent in the list. + + In other words, in a normal case, to iterate over the edges only once + you must iterate over the even or odd items of this list. + */ + inline std::vector& getHalfEdges( ); + + /** + Return a list of edges. Note that in this list the twins of the edges + does not appear. In other words, this list represents the connections + between two unordered vertices. Used for const operations. + */ + inline const std::vector& getHalfEdges( ) const; + + /** + Returns the Half edge with the given ID. + */ + HalfEdge* getHalfEdge(unsigned int id); + + /** + Returns the Half edge with the given ID. + */ + const HalfEdge* getHalfEdge(unsigned int id) const; + + /** + Returns a pointer to the edge that has vertexA as origin and + has vertexB as 'target' (edge->twin->origin). + + Returns NULL if this edge doesn't exist. + */ + HalfEdge* getHalfEdge( Vertex* vertexA, Vertex* vertexB ) const; + HalfEdge* getHalfEdge( unsigned int vertexIdA, unsigned int vertexIdB) const; + + /** + Returns the ID of a given halfEdge. + */ + unsigned int getHalfEdgeId( HalfEdge* halfEdge) const; + + /** + Returns the number of half-edges of the mesh. + + Note that the actual number of edges is / 2. + */ + unsigned int getNumHalfEdges() const; + + /** + Iterate through all faces, calling the checkFace() method + to check if that face is consistent. + */ + void checkAllFaces() const; + + /** + A helper method used to test some assumed conditions about the DCEL. + + It should be used after each face "add*Face" method. + + It checkFace for the following conditions on the last added face: + - Every face must have a boundary (1) + - The sequence of vertices pointed by face->boundary must point to the same face (2) + - Every edge must have an origin vertex (3) + - Every vertex must have a incident pointer (4) + - Every edge must have an twin edge (5) + - Every edge must have a next pointer (6) + - The pointer edge->next->origin must be equal to edge->twin->origin (7) + - Every edge must have a prev pointer (8) + - The pointer edge->prev->twin->origin must be equal to edge->origin (9) + */ + void checkFace( unsigned int faceId ) const; + + /** + During the insertion of triangular faces, some times it can be + ambiguous how to insert the triangle into the structure, due to + how the pointers connects the vertices, edges and faces. + In these cases, these triangles are not inserted into the mesh, + but are delayed to be inserted when there is no ambiguity in its + insertion. This method tries to insert these triangles. + */ + void manageUnhandledTriangles(); + + int getNumUnhandledTriangles() const; + + /** + Finds the half edge that does not have an associated face yet, and its twin + starts at the given vertex. + */ + HalfEdge* findIncidentHalfEdge(Vertex* vertex); + + /** + Clear the entire mesh, releasing the vertices, faces and half-edges. + */ + void clear(); + + const std::list& getUnhandledTriangles() const + { + return this->unhandledTriangles; + } + +protected: +private: + std::vector vertices; + std::vector faces; + std::vector edges; + + std::list unhandledTriangles; + int unhandledTrianglesCount; +}; + + +////////////////////////////////////////////////////////////////////////// +// IMPLEMENTATION // +////////////////////////////////////////////////////////////////////////// + + +template +Mesh::Mesh(): + unhandledTrianglesCount(0) +{ +}; + +template +Mesh::~Mesh() +{ + this->clear(); +}; + +template +unsigned int Mesh::createVertex( ) +{ + this->vertices.push_back( Vertex() ); + return this->vertices.size()-1; +}; + +template +VertexT* Mesh::createGetVertex( ) +{ + this->vertices.push_back( Vertex() ); + return &this->vertices.back(); +}; + +template +unsigned int Mesh::createFace( HalfEdge* bound ) +{ + unsigned int faceId = this->faces.size(); + this->faces.push_back( Face() ); + Face* face = &(faces[faceId]); + face->setBoundary( bound ); + return faceId; +}; + +template +unsigned int Mesh::createEdge( Vertex* origin, Face* face, Vertex* twinOrigin, Face* twinFace ) +{ + unsigned int edgeId = this->edges.size(); + this->edges.push_back( HalfEdge() ); + HalfEdge* e1 = &this->edges[edgeId]; + e1->setOrigin( origin ); + e1->setFace( face ); + + this->edges.push_back( HalfEdge() ); + HalfEdge* e2 = &this->edges[edgeId+1]; + e2->setOrigin( twinOrigin ); + e2->setFace( twinFace ); + + e1->setTwin(e2); + + return edgeId; +}; + +template +unsigned int Mesh::createTriangularFace(unsigned int vId1, unsigned int vId2, unsigned int vId3) +{ + Vertex* v1 = this->getVertex(vId1); + Vertex* v2 = this->getVertex(vId2); + Vertex* v3 = this->getVertex(vId3); + HalfEdge* e1 = this->getHalfEdge(v1, v2); + HalfEdge* e2 = this->getHalfEdge(v2, v3); + HalfEdge* e3 = this->getHalfEdge(v3, v1); + + int unusedVertices = 0; + if (v1->getIncidentEdge()==NULL) unusedVertices++; + if (v2->getIncidentEdge()==NULL) unusedVertices++; + if (v3->getIncidentEdge()==NULL) unusedVertices++; + + int readyEdges = 0; + if (e1!=NULL) readyEdges++; + if (e2!=NULL) readyEdges++; + if (e3!=NULL) readyEdges++; + + unsigned int nullFaceId = (unsigned int)-1; + unsigned int faceId = nullFaceId; + Face* face = NULL; + + //the most simple case, all vertices has degree 0 + //create 3 edges, and link then + if ( unusedVertices==3 && readyEdges==0 ) + { + faceId = createFace( NULL ); + face = getFace( faceId ); + + e1 = getHalfEdge( createEdge( v1, face, v2, NULL ) ); + v1->setIncidentEdge( e1 ); + face->setBoundary( e1 ); + + e2 = getHalfEdge( createEdge( v2, face, v3, NULL ) ); + v2->setIncidentEdge( e2 ); + + e3 = getHalfEdge(createEdge( v3, face, v1, NULL ) ); + v3->setIncidentEdge( e3 ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + e1->getTwin()->setNext( e3->getTwin() ); + e3->getTwin()->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1->getTwin() ); + } + + //there are one vertex that has been used by another triangle. + //Create the 3 edges, and link to the old triangle. + else if( unusedVertices==2 && readyEdges==0 ) + { + if( v2->getIncidentEdge()!=NULL ) + { + Vertex* vt = v1; + v1 = v2; + v2 = v3; + v3 = vt; + } + else if( v3->getIncidentEdge()!=NULL ) + { + Vertex* vt = v1; + v1 = v3; + v3 = v2; + v2 = vt; + } + HalfEdge* ei1 = findIncidentHalfEdge( v1 ); + if( ei1!=NULL ) + { + HalfEdge* ei1n = ei1->getNext(); + + faceId = createFace( NULL ); + face = getFace( faceId ); + + e1 = getHalfEdge( createEdge( v1, face, v2, ei1->getFace() ) ); + face->setBoundary( e1 ); + + e2 = getHalfEdge( createEdge( v2, face, v3, ei1->getFace() ) ); + v2->setIncidentEdge( e2 ); + + e3 = getHalfEdge(createEdge( v3, face, v1, ei1->getFace() ) ); + v3->setIncidentEdge( e3 ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + ei1->setNext( e3->getTwin() ); + e3->getTwin()->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1->getTwin() ); + e1->getTwin()->setNext( ei1n ); + } + } + + //2 vertices are already in use by 2 distinct triangles, and + //one vertex doesn't have been used yet. + else if( unusedVertices==1 && readyEdges==0 ) + { + if( v3->getIncidentEdge()==NULL ) + { + Vertex* vt = v1; + v1 = v2; + v2 = v3; + v3 = vt; + } + else if( v1->getIncidentEdge()==NULL ) + { + Vertex* vt = v1; + v1 = v3; + v3 = v2; + v2 = vt; + } + + HalfEdge* ei1 = findIncidentHalfEdge( v1 ); + HalfEdge* ei3 = findIncidentHalfEdge( v3 ); + if( ei1!=NULL && ei3!=NULL ) + { + HalfEdge* ei1n = ei1->getNext(); + HalfEdge* ei3n = ei3->getNext(); + + faceId = createFace( NULL ); + face = getFace( faceId ); + + e1 = getHalfEdge( createEdge( v1, face, v2, ei1n->getFace() ) ); + e2 = getHalfEdge( createEdge( v2, face, v3, ei3->getFace() ) ); + e3 = getHalfEdge(createEdge( v3, face, v1, ei1->getFace() ) ); + + face->setBoundary( e1 ); + v2->setIncidentEdge( e2 ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + ei1->setNext( e3->getTwin() ); + e3->getTwin()->setNext( ei3n ); + + ei3->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1->getTwin() ); + e1->getTwin()->setNext( ei1n ); + } + } + + //two of the vertices already have one edge connected between then, + //and one vertex has not been used yet. + else if (unusedVertices==1 && readyEdges==1) + { + //rotate pointers, so the v1 and v2 are connected, and v3 is unused + if (e2!=NULL) + { + Vertex* vt = v1; + v1 = v2; + v2 = v3; + v3 = vt; + HalfEdge *et = e1; + e1 = e2; + e2 = e3; + e3 = et; + } + else if (e3!=NULL) + { + Vertex* vt = v1; + v1 = v3; + v3 = v2; + v2 = vt; + HalfEdge* et = e1; + e1 = e3; + e3 = e2; + e2 = et; + } + + if (e1->getFace()==NULL) + { + HalfEdge* e1n = e1->getNext(); + HalfEdge* e1p = e1->getPrev(); + + faceId = createFace( e1 ); + face = getFace( faceId ); + + e2 = getHalfEdge(createEdge( v2, face, v3, e1n->getFace() ) ); + e3 = getHalfEdge(createEdge( v3, face, v1, e1p->getFace() ) ); + + e1->setFace( face ); + v3->setIncidentEdge( e3 ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + e1p->setNext( e3->getTwin() ); + e3->getTwin()->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1n ); + } + } + + //all the tree vertices are used by different triangles, no + //ready edge available. + else if ( unusedVertices==0 && readyEdges==0 ) + { + HalfEdge* ei1 = findIncidentHalfEdge( v1 ); + HalfEdge* ei2 = findIncidentHalfEdge( v2 ); + HalfEdge* ei3 = findIncidentHalfEdge( v3 ); + + if( ei1!=NULL && ei2!=NULL && ei3!=NULL ) + { + + HalfEdge* ei1n = ei1->getNext(); + HalfEdge* ei2n = ei2->getNext(); + HalfEdge* ei3n = ei3->getNext(); + + faceId = createFace( NULL ); + face = getFace( faceId ); + + e1 = getHalfEdge( createEdge( v1, face, v2, ei2->getFace() ) ); + e2 = getHalfEdge( createEdge( v2, face, v3, ei3->getFace() ) ); + e3 = getHalfEdge( createEdge( v3, face, v1, ei1->getFace() ) ); + + face->setBoundary( e1 ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + ei1->setNext( e3->getTwin() ); + e3->getTwin()->setNext( ei3n ); + + ei3->setNext( e2->getTwin() ); + e2->getTwin()->setNext( ei2n ); + + ei2->setNext( e1->getTwin() ); + e1->getTwin()->setNext( ei1n ); + } + } + + //all vertices are used, and two of then are used by the + //same triangle. In this case, one edge will be shared with + //other triangle. + else if (unusedVertices==0 && readyEdges==1) + { + if( e2!=NULL ) + { + Vertex* vt = v1; + v1 = v2; + v2 = v3; + v3 = vt; + HalfEdge *et = e1; + e1 = e2; + e2 = e3; + e3 = et; + } + else if( e3!=NULL ) + { + Vertex* vt = v1; + v1 = v3; + v3 = v2; + v2 = vt; + HalfEdge* et = e1; + e1 = e3; + e3 = e2; + e2 = et; + } + + HalfEdge* ei3 = findIncidentHalfEdge( v3 ); + if( ei3 && e1->getFace()==NULL ) + { + HalfEdge* e1p = e1->getPrev(); + HalfEdge* e1n = e1->getNext(); + HalfEdge* ei3n = ei3->getNext(); + + faceId = createFace( e1 ); + face = getFace( faceId ); + + e2 = getHalfEdge( createEdge( v2, face, v3, ei3->getFace() ) ); + e3 = getHalfEdge( createEdge( v3, face, v1, e1p->getFace() ) ); + + e1->setFace( face ); + e2->setFace( face ); + e3->setFace( face ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + e1p->setNext( e3->getTwin() ); + e3->getTwin()->setNext( ei3n ); + + ei3->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1n ); + } + } + + //The three vertices are used, but there is an edge missing. + //will create one edge to 'fill' the hole and expand the mesh + else if( unusedVertices==0 && readyEdges==2 ) + { + if (e1==NULL) + { + Vertex* vt = v1; + v1 = v3; + v3 = v2; + v2 = vt; + HalfEdge* et = e1; + e1 = e3; + e3 = e2; + e2 = et; + } + else if (e3==NULL) + { + Vertex* vt = v1; + v1 = v2; + v2 = v3; + v3 = vt; + HalfEdge *et = e1; + e1 = e2; + e2 = e3; + e3 = et; + } + + if (e1->getFace()==NULL && e3->getFace()==NULL) + { + HalfEdge* e1n = e1->getNext(); + HalfEdge* e3p = e3->getPrev(); + + if (e3->getNext()==e1 && e1->getPrev()==e3) + { + faceId = createFace( e1 ); + face = getFace( faceId ); + + e2 = getHalfEdge( createEdge( v2, face, v3, e1n->getFace() ) ); + + e1->setFace( face ); + e3->setFace( face ); + + e1->setNext( e2 ); + e2->setNext( e3 ); + e3->setNext( e1 ); + + e3p->setNext( e2->getTwin() ); + e2->getTwin()->setNext( e1n ); + } + else + { + std::cerr << "outro erro" << std::endl; + } + } + } + + //A practically closed face, need only that the internal edges + //point to a new face. A easy case =) + else if ( unusedVertices==0 && readyEdges==3 ) + { + if(e1->getFace()==NULL && e2->getFace()==NULL && e3->getFace()==NULL) + { + if (e1->getNext()==e2 && e2->getNext()==e3 && e3->getNext()==e1) + { + faceId = createFace( e1 ); + face = getFace( faceId ); + e1->setFace( face ); + e2->setFace( face ); + e3->setFace( face ); + } + else + { + std::cerr << "mais outro erro" << std::endl; + } + } + } + + // if there is no face pointer, then a triangle should be inserted in + // a difficult case to handle. For now, the most simple solution is + // handle this triangle latter, after other triangles have been added + // and there is no ambiguity + if( face==NULL ) + { + this->unhandledTriangles.push_back( vId1 ); + this->unhandledTriangles.push_back( vId2 ); + this->unhandledTriangles.push_back( vId3 ); + unhandledTrianglesCount++; + } + + return faceId; +}; + +template +VertexT* Mesh::getVertex( unsigned int id ) const +{ + const MeshT::Vertex* v = &(this->vertices[id]); + return const_cast(v); +}; + +template +std::vector>& Mesh::getVertices() +{ + return this->vertices; +}; + +template +const std::vector>& Mesh::getVertices() const +{ + return this->vertices; +}; + +template +unsigned int Mesh::getNumVertices() const +{ + return this->vertices.size(); +}; + +template +unsigned int Mesh::getVertexId(const Vertex* vertex) const +{ + const Vertex* firstVertex = &(this->vertices[0]); + unsigned int id = vertex - firstVertex; + if( id>=0 && id < this->vertices.size() ) + { + if( &(this->vertices[id]) == vertex ) + return id; + } + return -1; +} + +template +std::vector>& Mesh::getFaces( ) +{ + return this->faces; +}; + +template +const std::vector>& Mesh::getFaces( ) const +{ + return this->faces; +}; + +template +unsigned int Mesh::getNumFaces( ) const +{ + return this->faces.size(); +} + +template +FaceT* Mesh::getFace(unsigned int faceId) const +{ + const Face* f = &(this->faces[faceId]); + return const_cast(f); +}; + +template +unsigned int Mesh::getFaceId(const Face* face) const +{ + const Face* firstFace = &(this->faces[0]); + unsigned int id = face - firstFace; + if( id>=0 && id < this->faces.size() ) + { + if( &(this->faces[id]) == face ) + return id; + } + return -1; +}; + +template +inline std::vector>& Mesh::getHalfEdges( ) +{ + return this->edges; +}; + +template +inline const std::vector>& Mesh::getHalfEdges( ) const +{ + return this->edges; +}; + +template +HalfEdgeT* Mesh::getHalfEdge(unsigned int id) +{ + HalfEdge* e = &(this->edges[id]); + return e; +} + +template +const HalfEdgeT* Mesh::getHalfEdge(unsigned int id) const +{ + const HalfEdge* e = &(this->edges[id]); + return e; +} + +template +HalfEdgeT* Mesh::getHalfEdge(Vertex* vertexA, Vertex* vertexB) const +{ + EdgeIterator it( vertexA ); + while( it.hasNext() ) + { + HalfEdge* e = it.getNext(); + if( e->getTwin()->getOrigin()==vertexB ) + { + return e; + } + } + return NULL; +}; + +template +HalfEdgeT* Mesh::getHalfEdge( unsigned int vertexIdA, unsigned int vertexIdB) const +{ + return getHalfEdge( getVertex(vertexIdA), getVertex(vertexIdB) ); +}; + +template +unsigned int Mesh::getHalfEdgeId( HalfEdge* halfEdge) const +{ + const HalfEdge* firstEdge = &(this->edges[0]); + unsigned int id = halfEdge - firstEdge; + if( id>=0 && id < this->edges.size() ) + { + if( &(this->edges[id]) == halfEdge ) + return id; + } + return -1; +} + +template +unsigned int Mesh::getNumHalfEdges() const +{ + return this->edges.size(); +} + +template +void Mesh::checkAllFaces() const +{ + const unsigned int numFaces = this->getNumFaces(); + for( unsigned int f=0; fcheckFace(f); + } +} + +template +void Mesh::checkFace(unsigned int faceId) const +{ + Face* face = this->getFace(faceId); + + if( face->getBoundary()==NULL ) + { + throw cpp::Exception("Every face must have a boundary (1)"); + } + + HalfEdge* edge = NULL; + EdgeIterator it(face); + while( it.hasNext() ) + { + edge = it.getNext(); + + if( edge->getFace()!=face ) + { + throw cpp::Exception("The sequence of half-edges pointed by face->boundary must point to the same face (2)"); + } + + if( edge->getOrigin()==NULL ) + { + throw cpp::Exception("Every edge must have an origin vertex (3)"); + } + + if( edge->getOrigin()->getIncidentEdge()==NULL ) + { + throw cpp::Exception("Every vertex must have a incident pointer (4)"); + } + + if( edge->getTwin()==NULL ) + { + throw cpp::Exception("Every edge must have an twin edge (5)"); + } + + if( edge->getNext()==NULL ) + { + throw cpp::Exception("Every edge must have a next half-edge pointer (6)"); + } + else if( edge->getNext()->getOrigin()!=edge->getTwin()->getOrigin() ) + { + throw cpp::Exception("The pointer edge->next->origin must be equal to edge->twin->origin (7)"); + } + + if( edge->getPrev()==NULL ) + { + throw cpp::Exception("Every edge must have a prev pointer (8)"); + } + else if( edge->getPrev()->getTwin()->getOrigin()!=edge->getOrigin() ) + { + throw cpp::Exception("The pointer edge->prev->twin->origin must be equal to edge->origin (9)"); + } + + bool edgeFound = false; + unsigned int count = 0; + EdgeIterator vit( edge->getOrigin() ); + while(vit.hasNext()) + { + if (vit.getNext() == edge) + { + edgeFound = true; + break; + } + else + { + // if a "infinite" loop happens here, also there is an undetectable error! + // lets say that a vertex will not have more than 1000 incident edges. + count++; + if( count>1000 ) + { + throw cpp::Exception("There is an error iterating through the edges of a vertex - possible infinite loop - (10)"); + } + } + } + if ( !edgeFound ) + { + throw cpp::Exception("The edge cannot be reachable iterating thought its origin (11)"); + } + + if (edge->getTwin()->getFace()==NULL) + { + const HalfEdge* initialBorder = edge->getTwin(); + const HalfEdge* cEdge = initialBorder->getNext(); + while( cEdge!=initialBorder ) + { + if (cEdge->getFace()!=NULL) + { + throw cpp::Exception("The sequence of half edges on the border does not points to a null face (12)"); + } + cEdge = cEdge->getNext(); + } + } + } + + if( edge->getNext()!=face->getBoundary() ) + { + throw cpp::Exception("The pointer edge->next of the last edge in a face border must be equals to the face->boundary (12)"); + } +}; + +template +void Mesh::manageUnhandledTriangles() +{ + if( unhandledTrianglesCount*3 != unhandledTriangles.size() ) + { + throw cpp::Exception("The number of unhandled triangles should be equal to the number of unhandled vertices*3!"); + } + + int curTriangle = 0; + while( !this->unhandledTriangles.empty() ) + { + if( curTriangle==unhandledTrianglesCount ) + { + int remainingTriangles = this->unhandledTriangles.size() / 3; + if( remainingTrianglescreateTriangularFace(v1,v2,v3); + if( fid==-1 ) //ajust the number of triangles in case of the triangle was not added to the mesh + { + unhandledTrianglesCount--; + } + + curTriangle++; + } +} + +template +int Mesh::getNumUnhandledTriangles() const +{ + return this->unhandledTrianglesCount; +} + +template +HalfEdgeT* Mesh::findIncidentHalfEdge(Vertex* vertex) +{ + HalfEdge* edgeTmp = NULL; + HalfEdge* result = NULL; + int nullFacesCount=0; + EdgeIterator it(vertex); + while( it.hasNext() ) + { + edgeTmp = it.getNext(); + if( edgeTmp->getTwin()->getFace()==NULL ) + { + result = edgeTmp->getTwin(); + nullFacesCount++; + } + } + if( nullFacesCount!=1 ) + { + result = NULL; + } + return result; +} + +template +void Mesh::clear() +{ + this->vertices.clear(); + this->edges.clear(); + this->faces.clear(); + this->unhandledTriangles.clear(); + this->unhandledTrianglesCount = 0; +} + +#endif//DCEL_Mesh_h diff --git a/source/DCEL/PlyImporter.cpp b/source/DCEL/PlyImporter.cpp new file mode 100644 index 0000000..d0e7734 --- /dev/null +++ b/source/DCEL/PlyImporter.cpp @@ -0,0 +1,102 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#include "PlyImporter.h" +#include "../rply/rply.h" + +/* + This code uses the RPly 1.01 library, from + http://w3.impa.br/~diego/software/rply/. + + The code for this lib can be downloaded from + http://w3.impa.br/~diego/software/rply/rply-1.01.tar.gz. There is a copy of + the RPly 1.01 available with this file. +*/ + +int vertex_cb(p_ply_argument argument) +{ + PlyLoader* loader; + long coordinate; + + ply_get_argument_user_data(argument, (void**)&loader, &coordinate); + float position = (float)ply_get_argument_value(argument); + switch(coordinate) + { + case 0: + loader->vertices.push_back( Vector3f(position,0,0) ); + break; + case 1: + loader->vertices.back().y = position; + break; + case 2: + loader->vertices.back().z = position; + } + return 1; +} + +int face_cb(p_ply_argument argument) +{ + long length, value_index; + ply_get_argument_property(argument, NULL, &length, &value_index); + + if( length!=3 ) //ensures only triangles are read + { + throw cpp::Exception("This file contains other things than triangles (1)!'"); + } + unsigned int val = (unsigned int)ply_get_argument_value(argument); + if( value_index<0 ) + { + if( val!=3 ) //ensures only triangles are read + { + throw cpp::Exception("This file contains other things than triangles (2)!'"); + } + return 1; // just returns, this is not usefull data (its the size of the list that will follow) + } + + PlyLoader* loader; + ply_get_argument_user_data(argument, (void**)&loader, NULL); + loader->faces.push_back( val ); + + return 1; +} + +void error_cb(const char *message) +{ + std::cerr << message << std::endl; +} + +void PlyLoader::load( const std::string& plyFilename ) +{ + this->vertices.clear(); + this->verticeCount = 0; + this->faces.clear(); + this->faceCount = 0; + + p_ply ply = ply_open(plyFilename.c_str(), error_cb); + if( !ply ) + { + throw cpp::Exception(std::string("Cannot open the file '")+plyFilename+"'"); + } + + if(!ply_read_header(ply) ) + { + throw cpp::Exception(std::string("Error loading the header of the file '")+plyFilename+"'"); + } + + this->verticeCount = ply_set_read_cb(ply, "vertex", "x", vertex_cb, this, 0); + ply_set_read_cb(ply, "vertex", "y", vertex_cb, this, 1); + ply_set_read_cb(ply, "vertex", "z", vertex_cb, this, 2); + + this->faceCount = ply_set_read_cb(ply, "face", "vertex_indices", face_cb, this, 0); + if (!ply_read(ply)) + { + throw cpp::Exception(std::string("Error loading the the whole file '")+plyFilename+"'"); + } + ply_close(ply); +} diff --git a/source/DCEL/PlyImporter.h b/source/DCEL/PlyImporter.h new file mode 100644 index 0000000..a9c7d80 --- /dev/null +++ b/source/DCEL/PlyImporter.h @@ -0,0 +1,105 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef PlyImporter_h +#define PlyImporter_h + +#include "DCELStream.h" +#include "Vector3.h" + +/** + This class is used internally by the PlyImporter, and should not be used externally. + + It loads a set of vertices into the "vertices" list and the set of faces into the + "faces" list. Each 3 values into the "faces" lists stores one triangular face, + composed by the vertices referenced by the 3 unsigned int values. +*/ +class PlyLoader +{ +public: + void load(const std::string& plyFilename); + + std::list vertices; + unsigned int verticeCount; + std::list faces; + unsigned int faceCount; +}; + +/** + Class that imports a PLY file into a DCEL mesh. + + It assumes that the mesh is totally triangulated. +*/ +template +class PlyImporter +{ +public: + + /** + Loads from the given filename. + + It just calls the 'import' method with the opened stream. + */ + void import( const std::string& plyFilename, MeshT& mesh ); + +private: +}; + + +template +void PlyImporter::import( const std::string& plyFilename, MeshT& mesh ) +{ + std::cerr << "Starting importing the file '" << plyFilename << "'" << std::endl; + + std::cerr << "- loading the PLY file" << std::endl; + //loads the ply file + PlyLoader loader; + loader.load( plyFilename ); + + // put it into the mesh + std::cerr << "- loading the DCEL mesh: " << std::endl; + std::cerr << " + " << loader.verticeCount << " vertices" << std::endl; + mesh.clear(); + mesh.getVertices().reserve(loader.verticeCount); + mesh.getFaces().reserve(loader.faceCount); + mesh.getHalfEdges().reserve( 2*(loader.verticeCount+loader.faceCount-2) ); // Euler: V – A + F = 2 --> A = V + F - 2 + std::list::iterator vit = loader.vertices.begin(); + while( vit!=loader.vertices.end() ) + { + unsigned int id = mesh.createVertex(); + mesh.getVertex(id)->getData().position = *vit; + vit++; + } + + std::cerr << " + " << loader.faceCount << " faces" << std::endl; + + std::list::iterator fit = loader.faces.begin(); + unsigned int count=0; + while( fit!=loader.faces.end() ) + { + count++; + unsigned int a = *fit; ++fit; + unsigned int b = *fit; ++fit; + unsigned int c = *fit; ++fit; + unsigned int fid = mesh.createTriangularFace( a, b, c ); + if (fid!=-1) + { + mesh.checkFace(fid); + mesh.checkAllFaces(); + } + } + + std::cerr << " + " << mesh.getNumUnhandledTriangles() << " bad triangles" << std::endl; + + mesh.manageUnhandledTriangles(); + mesh.checkAllFaces(); + std::cerr << "Done!" << std::endl; +} + +#endif//PlyImporter_h diff --git a/source/DCEL/Vector3.h b/source/DCEL/Vector3.h new file mode 100644 index 0000000..44711ce --- /dev/null +++ b/source/DCEL/Vector3.h @@ -0,0 +1,313 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef VECTOR_3_H +#define VECTOR_3_H + +#include + +template +class Vector3 +{ +public: + Vector3() + {} + + Vector3(T x, T y, T z) + :x(x) + ,y(y) + ,z(z) + {} + + Vector3(const Vector3& v) + :x(v.x) + ,y(v.y) + ,z(v.z) + {} + + Vector3(const Vector3* v) + :x(v->x) + ,y(v->y) + ,z(v->z) + {} + + inline void set(T x, T y, T z) + { + this->x = x; + this->y = y; + this->z = z; + } + + inline void set(const Vector3& other) + { + this->x = other.x; + this->y = other.y; + this->z = other.z; + } + + inline Vector3 operator=(const Vector3& other) + { + this->x = other.x; + this->y = other.y; + this->z = other.z; + return *this; + } + + /** + Explicitly, but easily, converts this Vector instance to one of the given type. + + Vector3 u(0,0,0); + Vector3 v = u.cast(); + */ + template + Vector3 cast() const + { + return Vector3( (U)x, (U)y, (U)z ); + } + + inline bool operator==(const Vector3& other) const + { + return this->x == other.x && this->y == other.y && this->z==other.z; + } + + inline bool operator!=(const Vector3& other) const + { + return this->x!=other.x || this->y!=other.y || this->z!=other.z; + } + + inline Vector3 operator+(const Vector3& other) const + { + return Vector3(this->x + other.x, this->y + other.y, this->z + other.z); + } + + inline void operator+=(const Vector3& other) + { + this->x+=other.x; + this->y+=other.y; + this->z+=other.z; + } + + inline Vector3 operator-() const + { + return Vector3(-this->x, -this->y, -this->z); + } + + inline Vector3 operator-(const Vector3& other) const + { + return Vector3(this->x - other.x, this->y - other.y, this->z - other.z); + } + + inline void operator-=(const Vector3& other) + { + this->x-=other.x; + this->y-=other.y; + this->z-=other.z; + } + + inline Vector3 operator*(T s) const + { + return Vector3(this->x*s, this->y*s, this->z*s); + } + + inline void operator*=(T s) + { + this->x*=s; + this->y*=s; + this->z*=s; + } + + inline Vector3 operator/(T s) const + { + return Vector3(this->x/s, this->y/s, this->z/s); + } + + inline void operator/=(T s) + { + this->x/=s; + this->y/=s; + this->z/=s; + } + + inline Vector3 cross( const Vector3& other ) const + { + return Vector3( + this->y*other.z - this->z*other.y, + this->z*other.x - this->x*other.z, + this->x*other.y - this->y*other.x ); + } + + inline T dot( const Vector3& other ) const + { + return this->x*other.x + this->y*other.y + this->z*other.z; + } + + inline T length() const + { + return( sqrt( this->x*this->x + this->y*this->y + this->z*this->z ) ); + } + + /** + Returns the square of the length of the vector. + + Use this if you just want to compare legths of vectors, as this is faster to + compute than lenght() + */ + inline T length2() const + { + return this->x*this->x + this->y*this->y + this->z*this->z; + } + + /** + Resizes the vector. + */ + inline void setLength(const T newLenght) + { + const T scale = ( newLenght / this->length() ); + this->x *= scale; + this->y *= scale; + this->z *= scale; + } + + inline T distance(const Vector3& other) const + { + const T xDelta = this->x-other.x; + const T yDelta = this->y-other.y; + const T zDelta = this->z-other.z; + return sqrt( xDelta*xDelta + yDelta*yDelta + zDelta*zDelta); + } + + /** + Returns the square of the distance to the other vector + + Use this if you just want to compare distances, as the square of + the distance is faster to compute than the distance itself. + */ + inline T distance2(const Vector3& other) const + { + const T xDelta = this->x-other.x; + const T yDelta = this->y-other.y; + const T zDelta = this->z-other.z; + return xDelta*xDelta + yDelta*yDelta + zDelta*zDelta; + } + + inline void normalize() + { + const T len = this->length(); + this->x /= len; + this->y /= len; + this->z /= len; + } + + /** + Returns a normalized copy of the vector. + + Use if you need a normalized version of the vector AND + the vector itself. + */ + inline Vector3 normalizedCopy() + { + Vector3 v = this; + const T len = v.length(); //inline normalize + v.x /= len; + v.y /= len; + v.z /= len; + return v; + } + + inline void rotateAroundY(T radians) + { + const double cs = cos(radians); + const double sn = sin(radians); + set((T)(x*cs - z*sn), y, (T)(x*sn + z*cs)); + } + + /** + This method will rotate the point represented by this vector + arround a given axis. + + This is the most general form for the methods rotateAroundX, + Y and Z, but is more expensive. + + \note the axis MUST be normalized + + \note that the axis passes through the point (0,0,0). + + Math from http://local.wasp.uwa.edu.au/~pbourke/geometry/rotate/ + */ + inline void rotateAround(const Vector3& axis, T radians) + { + T costheta = cos(radians); + T sintheta = sin(radians); + + Vector3 q; + q.x = (costheta + (1 - costheta) * axis.x * axis.x) * this->x; + q.x += ((1 - costheta) * axis.x * axis.y - axis.z * sintheta) * this->y; + q.x += ((1 - costheta) * axis.x * axis.z + axis.y * sintheta) * this->z; + + q.y = ((1 - costheta) * axis.x * axis.y + axis.z * sintheta) * this->x; + q.y += (costheta + (1 - costheta) * axis.y * axis.y) * this->y; + q.y += ((1 - costheta) * axis.y * axis.z - axis.x * sintheta) * this->z; + + q.z = ((1 - costheta) * axis.x * axis.z - axis.y * sintheta) * this->x; + q.z += ((1 - costheta) * axis.y * axis.z + axis.x * sintheta) * this->y; + q.z += (costheta + (1 - costheta) * axis.z * axis.z) * this->z; + + this->set(q); + } + + inline void rotateAround(const Vector3& p1, const Vector3& p2, T radians) + { + Vector3 r; + r.x = p2.x - p1.x; + r.y = p2.y - p1.y; + r.z = p2.z - p1.z; + this->x -= p1.x; + this->y -= p1.y; + this->z -= p1.z; + r.normalize(); + + T costheta, sintheta; + costheta = cos(radians); + sintheta = sin(radians); + + Vector3 q; + q.x = (costheta + (1 - costheta) * r.x * r.x) * this->x; + q.x += ((1 - costheta) * r.x * r.y - r.z * sintheta) * this->y; + q.x += ((1 - costheta) * r.x * r.z + r.y * sintheta) * this->z; + + q.y = ((1 - costheta) * r.x * r.y + r.z * sintheta) * this->x; + q.y += (costheta + (1 - costheta) * r.y * r.y) * this->y; + q.y += ((1 - costheta) * r.y * r.z - r.x * sintheta) * this->z; + + q.z = ((1 - costheta) * r.x * r.z - r.y * sintheta) * this->x; + q.z += ((1 - costheta) * r.y * r.z + r.x * sintheta) * this->y; + q.z += (costheta + (1 - costheta) * r.z * r.z) * this->z; + + q.x += p1.x; + q.y += p1.y; + q.z += p1.z; + + this->set(q); + } + + bool isNaN() const + { + return x!=x || y!=y || z!=z; + } + + T x; + T y; + T z; +}; + +typedef Vector3 Vector3i; +typedef Vector3 Vector3f; +typedef Vector3 Vector3d; + +#endif//VECTOR_3_H diff --git a/source/DCEL/Vertex.h b/source/DCEL/Vertex.h new file mode 100644 index 0000000..d8885d4 --- /dev/null +++ b/source/DCEL/Vertex.h @@ -0,0 +1,60 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef DCEL_Vertex_h +#define DCEL_Vertex_h + +//#include + +template +class HalfEdgeT; + +template +class VertexT +{ + typedef VertexT Vertex; + typedef HalfEdgeT HalfEdge; + +public: + + VertexT(): + data(), + incidentEdge(NULL) + { + }; + + inline HalfEdge* getIncidentEdge() const + { + //assert(this); + return this->incidentEdge; + }; + + inline void setIncidentEdge(HalfEdge* edge) + { + //assert(this); + this->incidentEdge = edge; + }; + + inline VertexDataT& getData() + { + return data; + }; + + inline const VertexDataT& getData() const + { + return data; + }; + +protected: +private: + HalfEdge* incidentEdge; + VertexDataT data; +}; + +#endif//DCEL_Vertex_h diff --git a/source/DCEL/WavefrontObjImporter.cpp b/source/DCEL/WavefrontObjImporter.cpp new file mode 100644 index 0000000..d3a8a08 --- /dev/null +++ b/source/DCEL/WavefrontObjImporter.cpp @@ -0,0 +1,66 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#include "WavefrontObjImporter.h" +#include +#include + +void WavefrontObjLoader::load( const std::string& objFile ) +{ + vertices.clear(); + verticeCount=0; + faces.clear(); + faceCount=0; + + std::ifstream stream; + try + { + stream.open( objFile.c_str(), std::ios::in ); + if( stream ) + { + // load the obj + while( stream.good() ) + { + char buffer[512]; + stream.getline(buffer, sizeof(buffer)); + std::stringstream str(buffer); + std::string name; + str >> name; + if( name=="v" ) + { + Vector3f position; + str >> position.x >> position.y >> position.z; + vertices.push_back( position ); + verticeCount++; + } + else if( name=="f" ) + { + unsigned int a, b, c; + str >> a >> b >> c; + faces.push_back(a-1); + faces.push_back(b-1); + faces.push_back(c-1); + faceCount++; + } + } + stream.close(); + } + else + { + throw cpp::Exception("Can't open the file '"+objFile+"'"); + } + } + catch( const std::exception& e ) + { + if( stream.is_open() ) + stream.close(); + std::cerr << e.what(); + throw; + } +} diff --git a/source/DCEL/WavefrontObjImporter.h b/source/DCEL/WavefrontObjImporter.h new file mode 100644 index 0000000..4f97456 --- /dev/null +++ b/source/DCEL/WavefrontObjImporter.h @@ -0,0 +1,107 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef WavefrontObjImporter_h +#define WavefrontObjImporter_h + +#include "DCELStream.h" +#include "Vector3.h" + +class WavefrontObjLoader +{ +public: + + void load( const std::string& objFile ); + + std::list vertices; + unsigned int verticeCount; + std::list faces; + unsigned int faceCount; +protected: +private: +}; + +/** + Class that imports a Wavefront OBJ file into a DCEL mesh. + + It assumes that the mesh is totally triangulated. +*/ +template +class WavefrontObjImporter +{ +public: + + /** + Loads from the given filename. + + It just calls the 'import' method with the opened stream. + */ + void import( const std::string& objFile, MeshT& mesh); + + void import( std::list& vertices, unsigned int verticeCount, std::list& faces, unsigned int faceCount, MeshT& mesh); +}; + +template +void WavefrontObjImporter::import( const std::string& objFilename, MeshT& mesh ) +{ + std::cerr << "Starting importing the file '" << objFilename << "'" << std::endl; + + std::cerr << "- loading the OBJ file" << std::endl; + WavefrontObjLoader loader; + loader.load(objFilename); + + import(loader.vertices, loader.verticeCount, loader.faces, loader.faceCount, mesh); + +} + +template +void WavefrontObjImporter::import( std::list& vertices, unsigned int verticeCount, std::list& faces, unsigned int faceCount, MeshT& mesh) +{ + // put it into the mesh + std::cerr << "- loading the DCEL mesh: " << std::endl; + std::cerr << " + " << verticeCount << " vertices" << std::endl; + mesh.clear(); + mesh.getVertices().reserve(verticeCount); + mesh.getFaces().reserve(faceCount); + //mesh.getEdges().reserve( 2*(verticeCount+faceCount) ); // Euler: V – A + F = 2 --> A = V + F - 2 + mesh.getHalfEdges().reserve( 2*(3*faceCount) ); // just a good expensive number of edges =) + std::list::iterator vit = vertices.begin(); + while( vit!=vertices.end() ) + { + unsigned int id = mesh.createVertex(); + mesh.getVertex(id)->getData().position = *vit; + vit++; + } + + std::cerr << " + " << faceCount << " faces" << std::endl; + std::list::iterator fit = faces.begin(); + unsigned int count=0; + while( fit!=faces.end() ) + { + count++; + unsigned int a = *fit; ++fit; + unsigned int b = *fit; ++fit; + unsigned int c = *fit; ++fit; + unsigned int fid = mesh.createTriangularFace( a, b, c ); + if (fid!=-1) + { + //std::cout << a << ' ' << b << ' ' << c << std::endl; + mesh.checkFace(fid); + mesh.checkAllFaces(); + } + } + + std::cerr << " + " << mesh.getNumUnhandledTriangles() << " bad triangles" << std::endl; + mesh.manageUnhandledTriangles(); + mesh.checkAllFaces(); + + std::cerr << "Done!" << std::endl; +} + +#endif//WavefrontObjImporter_h diff --git a/source/main.cpp b/source/main.cpp new file mode 100644 index 0000000..27a16a6 --- /dev/null +++ b/source/main.cpp @@ -0,0 +1,423 @@ +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright Leonardo Fischer 2011 - http://coderender.blogspot.com +// +// Distributed under the licence available in the accompanying file +// LICENCE.txt. Please read it before use this code. +// +/////////////////////////////////////////////////////////////////////////////// + +#include "DCEL/Mesh.h" +#include "DCEL/DCELStream.h" +#include "DCEL/WavefrontObjImporter.h" +#include "DCEL/Vector3.h" +#include + +/** + Here I'll define the three data structures that will be + associated with Vertices, half-edges and faces. Put anything you want + inside of it. +*/ +class VertexData +{ +public: + VertexData() + { + this->x = 0; + this->y = 0; + this->z = 0; + } + + float x, y, z; + void setVerticeCoordinates(float x, float y) + { + this->x = x; + this->y = y; + } + + /** + If you need to save the stream to a file, rewrite the << operator for the + ostream class. The DCELStream class will use it to write to a file. More latter. + */ + friend std::ostream& operator <<(std::ostream &os, const VertexData& vertexData) + { + os << vertexData.x << " " << vertexData.y; + return os; + } + + /** + If you save the mesh to a file, rewrite the operator >> to be able to load + the mesh latter using the DCELStream class. + */ + friend std::istream& operator >>(std::istream &is, VertexData& vertexData) + { + is >> vertexData.x >> vertexData.y; + return is; + } +}; + +/** + Another possible class to use within a vertex. In the current implementation of + the WavefrontObjImporter, I need the Vector3f class to load the vertices positions. + + Of course, there should be another way to do this, but I didn't figured out. + If you have a suggestion, let me know =) +*/ +class VertexDataWithPosition +{ +public: + Vector3f position; +protected: +private: +}; + +class HalfEdgeData +{ +public: + HalfEdgeData() { + modified = false; + } + + void modify() { + modified = true; + } + + bool isModified() const { + return modified; + } + + friend std::ostream& operator <<(std::ostream &os, const HalfEdgeData& halfEdgeData) + { + std::string modified = halfEdgeData.isModified()? "true" : "false"; + os << modified; + return os; + } + + friend std::istream& operator >>(std::istream &is, HalfEdgeData& halfEdgeData) + { + std::string modified; + is >> modified; + + if (modified.compare("true")==0) + { + halfEdgeData.modify(); + } + + return is; + } + +private: + bool modified; +}; + +class FaceData +{ +public: + std::string colorName; + + friend std::ostream& operator <<(std::ostream &os, const FaceData& faceData) + { + os << faceData.colorName; + return os; + } + + friend std::istream& operator >>(std::istream &is, FaceData& faceData) + { + is >> faceData.colorName; + return is; + } +}; + + +/** + Now I will define the type MyMesh, which is a Mesh that each vertex, face and half-edge + has one object given as parameter here. +*/ +typedef Mesh MyMesh; + +/** + Another type of Mesh. In this type, each vertex will have an instance of + VertexDataWithPosition. + + Although MyMesh and MyMeshUsingVector have the same structure, they are not + interchangeable. They are different objects! But you can use + the DCELStream::copyDcelData() method to convert between different mesh types. +*/ +typedef Mesh MyMeshUsingVector; + + +/** + This method will create and initialize an hard-coded mesh. +*/ +void createHardCodedMesh(MyMesh* mesh) { + + // reserve the needed space for the mesh. These numbers came from the hardcoded structure :) + mesh->getVertices().reserve( 5 ); // we will put 5 vertices into the mesh + mesh->getHalfEdges().reserve( 16 ); //there are 8 edges on the figure. Each edge has 2 half-edges. So, 16 + mesh->getFaces().reserve( 4 ); //4 faces + + /** + Now, create the vertices. Each time I call createGetVertex here, a new vertex is created + and a pointer to it is returned. The first vertex has its ID equals to 0, the second equals + to 1, and so on. + + If you call getData() on that pointer, you get a reference for the VertexData + object that is inside this vertex. The getData() works in the same way for + Half-Edge and Face pointers, returning a HalfEdgeData and FaceData object, + respectively. + */ + mesh->createGetVertex()->getData().setVerticeCoordinates( 10, 5 ); //vertex 0 + mesh->createGetVertex()->getData().setVerticeCoordinates( 6, 10 ); //vertex 1 + mesh->createGetVertex()->getData().setVerticeCoordinates( 15, 9 ); //vertex 2 + mesh->createGetVertex()->getData().setVerticeCoordinates( 14, 1 ); //vertex 3 + mesh->createGetVertex()->getData().setVerticeCoordinates( 2, 4 ); //vertex 4 + + /** + Now we will create the faces using the IDs from the vertices created before. I'll + give the three vertices's IDs that represents each face. Again, the faces receive + an incremental ID starting from 0. + + I must ensure that all faces are described in the same orientation (clock-wise or + counter-clock-wise). If I fail in this, I will receive very strange runtime errors. + */ + mesh->createTriangularFace( 0, 1, 2 ); + mesh->createTriangularFace( 0, 2, 3 ); + mesh->createTriangularFace( 0, 3, 4 ); + mesh->createTriangularFace( 0, 4, 1 ); + + /** + This is just a helper method that checks that all pointers are + set correctly. If I did anything wrong before, an exception will + be thrown. + */ + mesh->checkAllFaces(); + + /** + Now I'll use the ID of each face to set a color on it. + */ + mesh->getFace(0)->getData().colorName = "red"; + mesh->getFace(1)->getData().colorName = "green"; + mesh->getFace(2)->getData().colorName = "blue"; + mesh->getFace(3)->getData().colorName = "white"; + + /** + Now I'll modify some half edges using a iterator. This will iterate over + all half-edges that starts on the vertex 1. The iterator can run over all + the edges that starts on the given vertex or face. + */ + MyMesh::EdgeIterator iterator( mesh->getVertex(1) ); + while(iterator.hasNext()) { + MyMesh::HalfEdge* halfEdge = iterator.getNext(); + halfEdge->getData().modify(); + } + + /** + And also, I'll modify the half-edge that starts on the vertex 0 and ends on + the vertex 3. The method getHalfEdge(unsigned int a, unsigned int b) returns the + half-edge that starts at 'a' and ends at 'b', or null if such connection does + not exists. + */ + MyMesh::HalfEdge* edge = mesh->getHalfEdge(3, 0); + if (edge!=NULL) + { + edge->getData().modify(); + } +} + +void saveMesh(MyMesh* mesh, const char* filename) +{ + if (mesh!=NULL) + { + std::ofstream outputFile; + outputFile.open(filename); + if (outputFile) + { + /** + This is where I will write the mesh to a file. + + Note that the operator "<<" need to be rewrited on the VertexData, + HalfEdgeData and FaceData classes. + */ + DCELStream::write(*mesh, outputFile); + + outputFile.close(); + } + } +} + +void loadMesh(MyMesh* mesh, const char* filename) +{ + if (mesh!=NULL) + { + std::ifstream inputFile; + inputFile.open(filename); + if (inputFile) + { + /** + This is where I load the mesh from a DCEL file, saved with the + DCELStream::write() method. + + As for the DCELStream::write(), here you need to rewrite the + ">>" operator on the VertexData, HalfEdgeData and FaceData classes. + */ + DCELStream::read(*mesh, inputFile); + + inputFile.close(); + } + } +} + +void doSomeStuffWithMesh(MyMesh* mesh) +{ + /** + Print some basic information about the mesh. + */ + std::cout << "The mesh contain " << mesh->getNumFaces() << " faces." << std::endl; + std::cout << "The mesh contain " << mesh->getNumVertices() << " vertices." << std::endl; + std::cout << "The mesh contain " << mesh->getNumHalfEdges() << " half-edges. " << + "This number is 2 times the number of edges." << std::endl; + std::cout << std::endl; + + /** + Show the ID of the neighbor vertices of the vertex 4. It will get each half-edge + that starts at the vertex 4, get its twin half-edge, and get the origin of the twin + half-edge. + + The method getVertexId() returns the id of a given vertex. There are similar vertices + for half-edges and faces + */ + std::cout << "The neighbors of the vertex 4 are: "; + MyMesh::Vertex * vertex = mesh->getVertex(4); + MyMesh::EdgeIterator iterator(vertex); + while(iterator.hasNext()) { + MyMesh::Vertex* neighborVertex = iterator.getNext()->getTwin()->getOrigin(); + std::cout << mesh->getVertexId(neighborVertex) << ", "; + } + std::cout << std::endl << std::endl; + + /** + Iterate over the edges that composes the face 1 (the one composed by + the vertices 0, 2, 3). For each edge, will show its start vertex ID, + its ending vertex ID (which is the origin of its twin), and show if + it was modified (remember that I called modify() on the half-edge that + starts on vertex 3 and ends on vertex 0, see createHardCodedMesh() ). + */ + std::cout << "The half-edges of the face 1 are: "; + MyMesh::Face* face = mesh->getFace(1); + iterator.reset(face); //now the iterator will run over the edges of the face + while ( iterator.hasNext() ) + { + MyMesh::HalfEdge* halfEdge = iterator.getNext(); + std::cout << "[id="<< mesh->getHalfEdgeId(halfEdge) << + " origin=" << mesh->getVertexId( halfEdge->getOrigin() ) << + " end=" << mesh->getVertexId( halfEdge->getTwin()->getOrigin() ) << + " modified=" << (halfEdge->getData().isModified()?"true":"false") << "], "; + } + std::cout << std::endl << std::endl; + + /** + Iterate over all faces that the mesh have, showing its color. It is possible + to iterate over the half-edges and faces in the same way. + */ + std::cout << "The faces are: "; + for (unsigned int i=0; igetNumFaces(); ++i) + { + MyMesh::Face* face = mesh->getFace(i); + std::cout << "[id=" << mesh->getFaceId(face) << " color=" << face->getData().colorName << "], "; + } + std::cout << std::endl << std::endl; +} + +void importWavefrontObjFile(MyMeshUsingVector* mesh, const char* filename) +{ + WavefrontObjImporter importer; + importer.import(filename, *mesh); +} + +void convertBetweenMeshes(MyMeshUsingVector* meshUsingVector, MyMesh* mesh) +{ + /** + This will create on the 'mesh' the same structure of 'meshUsingVector'. + Note that only the DCEL connectivity is copied. + */ + DCELStream::copyDcelData(*meshUsingVector, *mesh); + + /** + As the IDs of faces, half-edges and vertices are the same in both meshes, + it is possible to use this fact to convert internal data from one structure + to the other. + + Of course, there should be a better way to do this automatically in the + copyDcelData() method, but I had no time to implement it =( + */ + for (unsigned int i=0;igetNumVertices(); ++i) + { + MyMeshUsingVector::Vertex* originVertex = meshUsingVector->getVertex(i); + MyMesh::Vertex* targetVertex = mesh->getVertex(i); + targetVertex->getData().x = originVertex->getData().position.x; + targetVertex->getData().y = originVertex->getData().position.y; + targetVertex->getData().z = originVertex->getData().position.z; + } + for (unsigned int i=0;igetNumHalfEdges(); ++i) + { + MyMeshUsingVector::HalfEdge* originHalfEdge = meshUsingVector->getHalfEdge(i); + MyMesh::HalfEdge* targetHalfEdge = mesh->getHalfEdge(i); + if (originHalfEdge->getData().isModified()) + { + targetHalfEdge->getData().modify(); + } + } + for (unsigned int i=0;igetNumFaces(); ++i) + { + MyMesh::Face* targetFace = mesh->getFace(i); + targetFace->getData().colorName = "yellow"; + } +} + +int main(int argc, char* argv[]) +{ + try + { + /** + Creates a new, hard coded mesh, and save it to a file. + */ + MyMesh* mesh = new MyMesh(); + createHardCodedMesh(mesh); + saveMesh(mesh, "hard-coded-mesh.dcel"); + delete mesh; + + /** + Creates a new, empty mesh, and fill it with the data from + the file saved before. Also, print some stuff about it + on the console. + */ + mesh = new MyMesh(); //create a new, empty mesh + loadMesh(mesh, "hard-coded-mesh.dcel"); + doSomeStuffWithMesh(mesh); + delete mesh; + + /** + Creates another type of mesh (using my Vector3 class). Then, import a .OBJ + file into it. Finally, convert that mesh to the MyMesh data structure. + + The method checkAllFaces() just ensures that everything is ok =) + */ + MyMeshUsingVector* meshUsingVect = new MyMeshUsingVector(); + mesh = new MyMesh(); + importWavefrontObjFile(meshUsingVect, "sphere.obj"); + convertBetweenMeshes(meshUsingVect, mesh); + mesh->checkAllFaces(); + meshUsingVect->checkAllFaces(); + delete meshUsingVect; + delete mesh; + + system("pause"); + return 0; + } + catch (std::exception& e) + { + std::cerr << "An exception occurred: " << e.what() << std::endl; + system("pause"); + return 1; + } +} diff --git a/source/rply/LICENSE b/source/rply/LICENSE new file mode 100644 index 0000000..02e7c5f --- /dev/null +++ b/source/rply/LICENSE @@ -0,0 +1,20 @@ +RPly 1.01 license +Copyright © 2003-2005 Diego Nehab. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/source/rply/etc/convert.c b/source/rply/etc/convert.c new file mode 100644 index 0000000..89ce93a --- /dev/null +++ b/source/rply/etc/convert.c @@ -0,0 +1,136 @@ +#include +#include +#include +#include +#include "rply.h" + +/* internal function prototypes */ +static void error(const char *fmt, ...); +static void help(void); +static void parse_arguments(int argc, char **argv, + e_ply_storage_mode *storage_mode, + const char **iname, const char **oname); +static void setup_callbacks(p_ply iply, p_ply oply); + +/* given a format mode, an input file name and an output file name, + * convert input file to output in given format mode */ +int main(int argc, char **argv) +{ + const char *value = NULL; + e_ply_storage_mode storage_mode = PLY_LITTLE_ENDIAN; + const char *iname = NULL, *oname = NULL; + p_ply iply = NULL, oply = NULL; + /* parse command line arguments */ + parse_arguments(argc, argv, &storage_mode, &iname, &oname); + /* open input file and make sure we parsed its header */ + iply = ply_open(iname, NULL); + if (!iply) error("Unable to open file '%s'", iname); + if (!ply_read_header(iply)) error("Failed reading '%s' header", iname); + /* create output file */ + oply = ply_create(oname, storage_mode, NULL); + if (!oply) error("Unable to create file '%s'", oname); + /* create elements and properties in output file and + * setup callbacks for them in input file */ + setup_callbacks(iply, oply); + /* pass comments and obj_infos from input to output */ + value = NULL; + while ((value = ply_get_next_comment(iply, value))) + if (!ply_add_comment(oply, value)) + error("Failed adding comments"); + value = NULL; + while ((value = ply_get_next_obj_info(iply, value))) + if (!ply_add_obj_info(oply, value)) + error("Failed adding comments"); + /* write output header */ + if (!ply_write_header(oply)) error("Failed writing '%s' header", oname); + /* read input file generating callbacks that pass data to output file */ + if (!ply_read(iply)) error("Conversion failed"); + /* close up, we are done */ + if (!ply_close(iply)) error("Error closing file '%s'", iname); + if (!ply_close(oply)) error("Error closing file '%s'", oname); + return 0; +} + +/* prints an error message and exits */ +static void error(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fprintf(stderr, "\n"); + exit(1); +} + +/* prints the help message and exits */ +static void help(void) +{ + error("Usage:\n" + " convert