OBJWriter.cc 10.5 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
4
 *      Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen      *
Jan Möbius's avatar
Jan Möbius committed
5
6
 *                           www.openmesh.org                                *
 *                                                                           *
7
 *---------------------------------------------------------------------------*
8
 *  This file is part of OpenMesh.                                           *
Jan Möbius's avatar
Jan Möbius committed
9
 *                                                                           *
10
 *  OpenMesh is free software: you can redistribute it and/or modify         *
11
12
13
14
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
Jan Möbius's avatar
Jan Möbius committed
15
 *                                                                           *
16
17
18
19
20
21
22
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
Jan Möbius's avatar
Jan Möbius committed
23
 *                                                                           *
24
25
26
27
 *  OpenMesh is distributed in the hope that it will be useful,              *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
Jan Möbius's avatar
Jan Möbius committed
28
 *                                                                           *
29
30
31
32
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
33
\*===========================================================================*/
34
35

/*===========================================================================*\
36
 *                                                                           *
37
38
 *   $Revision$                                                         *
 *   $Date$                   *
Jan Möbius's avatar
Jan Möbius committed
39
40
41
42
43
44
45
46
47
 *                                                                           *
\*===========================================================================*/


//== INCLUDES =================================================================


//STL
#include <fstream>
Jan Möbius's avatar
Jan Möbius committed
48
#include <limits>
Jan Möbius's avatar
Jan Möbius committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Utils/color_cast.hh>

//=== NAMESPACES ==============================================================


namespace OpenMesh {
namespace IO {


//=== INSTANCIATE =============================================================


// register the OBJLoader singleton with MeshLoader
_OBJWriter_  __OBJWriterinstance;
_OBJWriter_& OBJWriter() { return __OBJWriterinstance; }


//=== IMPLEMENTATION ==========================================================


_OBJWriter_::_OBJWriter_() { IOManager().register_module(this); }


//-----------------------------------------------------------------------------


bool
_OBJWriter_::
84
write(const std::string& _filename, BaseExporter& _be, Options _opt, std::streamsize _precision) const
Jan Möbius's avatar
Jan Möbius committed
85
86
87
88
89
90
91
92
93
94
{
  std::fstream out(_filename.c_str(), std::ios_base::out );

  if (!out)
  {
    omerr() << "[OBJWriter] : cannot open file "
	  << _filename << std::endl;
    return false;
  }

95
96
  out.precision(_precision);

Jan Möbius's avatar
Jan Möbius committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
  {
#if defined(WIN32)
    std::string::size_type dot = _filename.find_last_of("\\/");
#else
    std::string::size_type dot = _filename.rfind("/");
#endif

    if (dot == std::string::npos){
      path_ = "./";
      objName_ = _filename;
    }else{
      path_ = _filename.substr(0,dot+1);
      objName_ = _filename.substr(dot+1);
    }

    //remove the file extension
    dot = _filename.find_last_of(".");

    if(dot != std::string::npos)
      objName_ = objName_.substr(0,dot-1);
  }

119
  bool result = write(out, _be, _opt, _precision);
Jan Möbius's avatar
Jan Möbius committed
120
121
122
123
124
125
126

  out.close();
  return result;
}

//-----------------------------------------------------------------------------

Jan Möbius's avatar
Jan Möbius committed
127
size_t _OBJWriter_::getMaterial(OpenMesh::Vec3f _color) const
Jan Möbius's avatar
Jan Möbius committed
128
{
Jan Möbius's avatar
Jan Möbius committed
129
  for (size_t i=0; i < material_.size(); i++)
Jan Möbius's avatar
Jan Möbius committed
130
131
132
133
134
135
136
137
138
139
    if(material_[i] == _color)
      return i;

  //not found add new material
  material_.push_back( _color );
  return material_.size()-1;
}

//-----------------------------------------------------------------------------

Jan Möbius's avatar
Jan Möbius committed
140
size_t _OBJWriter_::getMaterial(OpenMesh::Vec4f _color) const
Jan Möbius's avatar
Jan Möbius committed
141
{
Jan Möbius's avatar
Jan Möbius committed
142
  for (size_t i=0; i < materialA_.size(); i++)
Jan Möbius's avatar
Jan Möbius committed
143
144
145
146
147
148
149
150
151
152
153
154
    if(materialA_[i] == _color)
      return i;

  //not found add new material
  materialA_.push_back( _color );
  return materialA_.size()-1;
}

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
155
writeMaterial(std::ostream& _out, BaseExporter& _be, Options _opt) const
Jan Möbius's avatar
Jan Möbius committed
156
157
158
159
160
161
162
163
{
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  material_.clear();
  materialA_.clear();

  //iterate over faces
Jan Möbius's avatar
Jan Möbius committed
164
  for (size_t i=0, nF=_be.n_faces(); i<nF; ++i)
Jan Möbius's avatar
Jan Möbius committed
165
166
167
  {
    //color with alpha
    if ( _opt.color_has_alpha() ){
Jan Möbius's avatar
Jan Möbius committed
168
      cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(int(i)) ));
Jan Möbius's avatar
Jan Möbius committed
169
170
171
      getMaterial(cA);
    }else{
    //and without alpha
Jan Möbius's avatar
Jan Möbius committed
172
      c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(int(i)) ));
Jan Möbius's avatar
Jan Möbius committed
173
174
175
176
177
178
      getMaterial(c);
    }
  }

  //write the materials
  if ( _opt.color_has_alpha() )
Jan Möbius's avatar
Jan Möbius committed
179
    for (size_t i=0; i < materialA_.size(); i++){
Jan Möbius's avatar
Jan Möbius committed
180
181
182
183
184
185
186
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << materialA_[i][0] << materialA_[i][1] << materialA_[i][2] << std::endl;;
      _out << "Tr " << materialA_[i][3] << std::endl;
      _out << "illum 1" << std::endl;
    }
  else
Jan Möbius's avatar
Jan Möbius committed
187
    for (size_t i=0; i < material_.size(); i++){
Jan Möbius's avatar
Jan Möbius committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << material_[i][0] << material_[i][1] << material_[i][2] << std::endl;;
      _out << "illum 1" << std::endl;
    }

  return true;
}

//-----------------------------------------------------------------------------


bool
_OBJWriter_::
202
write(std::ostream& _out, BaseExporter& _be, Options _opt, std::streamsize _precision) const
Jan Möbius's avatar
Jan Möbius committed
203
{
Jan Möbius's avatar
Jan Möbius committed
204
205
  unsigned int idx;
  size_t i, j,nV, nF;
Jan Möbius's avatar
Jan Möbius committed
206
207
208
209
210
211
212
213
214
215
  Vec3f v, n;
  Vec2f t;
  VertexHandle vh;
  std::vector<VertexHandle> vhandles;
  bool useMatrial = false;
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  omlog() << "[OBJWriter] : write file\n";

216
  _out.precision(_precision);
Jan Möbius's avatar
Jan Möbius committed
217
218
219
220
221
222
223
224

  // check exporter features
  if (!check( _be, _opt))
     return false;


  // check writer features
  if ( _opt.check(Options::Binary)     || // not supported by format
Matthias Möller's avatar
Matthias Möller committed
225
       _opt.check(Options::FaceNormal))
Jan Möbius's avatar
Jan Möbius committed
226
227
228
229
230
231
232
233
234
235
     return false;


  //create material file if needed
  if ( _opt.check(Options::FaceColor) ){

    std::string matFile = path_ + objName_ + ".mat";

    std::fstream matStream(matFile.c_str(), std::ios_base::out );

236
    if (!matStream)
Jan Möbius's avatar
Jan Möbius committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    {
      omerr() << "[OBJWriter] : cannot write material file " << matFile << std::endl;

    }else{
      useMatrial = writeMaterial(matStream, _be, _opt);

      matStream.close();
    }
  }

  // header
  _out << "# " << _be.n_vertices() << " vertices, ";
  _out << _be.n_faces() << " faces" << std::endl;

  // material file
  if (useMatrial &&  _opt.check(Options::FaceColor) )
    _out << "mtllib " << objName_ << ".mat" << std::endl;

  // vertex data (point, normals, texcoords)
  for (i=0, nV=_be.n_vertices(); i<nV; ++i)
  {
Jan Möbius's avatar
Jan Möbius committed
258
    vh = VertexHandle(int(i));
Jan Möbius's avatar
Jan Möbius committed
259
260
261
262
263
264
265
    v  = _be.point(vh);
    n  = _be.normal(vh);
    t  = _be.texcoord(vh);

    _out << "v " << v[0] <<" "<< v[1] <<" "<< v[2] << std::endl;

    if (_opt.check(Options::VertexNormal))
Jan Möbius's avatar
Jan Möbius committed
266
      _out << "vn " << n[0] <<" "<< n[1] <<" "<< n[2] << std::endl;
Jan Möbius's avatar
Jan Möbius committed
267
268
269
270
271

    if (_opt.check(Options::VertexTexCoord))
      _out << "vt " << t[0] <<" "<< t[1] << std::endl;
  }

Jan Möbius's avatar
Jan Möbius committed
272
  size_t lastMat = std::numeric_limits<std::size_t>::max();
Jan Möbius's avatar
Jan Möbius committed
273

274
275
276
277
  // we do not want to write seperators if we only write vertex indices
  bool onlyVertices =    !_opt.check(Options::VertexTexCoord)
                      && !_opt.check(Options::VertexNormal);

Jan Möbius's avatar
Jan Möbius committed
278
279
280
281
282
  // faces (indices starting at 1 not 0)
  for (i=0, nF=_be.n_faces(); i<nF; ++i)
  {

    if (useMatrial &&  _opt.check(Options::FaceColor) ){
Jan Möbius's avatar
Jan Möbius committed
283
      size_t material = std::numeric_limits<std::size_t>::max();
284

Jan Möbius's avatar
Jan Möbius committed
285
286
      //color with alpha
      if ( _opt.color_has_alpha() ){
Jan Möbius's avatar
Jan Möbius committed
287
        cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(int(i)) ));
288
289
        material = getMaterial(cA);
      } else{
Jan Möbius's avatar
Jan Möbius committed
290
      //and without alpha
Jan Möbius's avatar
Jan Möbius committed
291
        c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(int(i)) ));
292
        material = getMaterial(c);
Jan Möbius's avatar
Jan Möbius committed
293
294
      }

295
      // if we are ina a new material block, specify in the file which material to use
296
297
      if(lastMat != material) {
        _out << "usemtl mat" << material << std::endl;
Jan Möbius's avatar
Jan Möbius committed
298
        lastMat = material;
299
      }
Jan Möbius's avatar
Jan Möbius committed
300
301
302
303
    }

    _out << "f";

Jan Möbius's avatar
Jan Möbius committed
304
    _be.get_vhandles(FaceHandle(int(i)), vhandles);
Jan Möbius's avatar
Jan Möbius committed
305
306
307

    for (j=0; j< vhandles.size(); ++j)
    {
308

309
      // Write vertex index
Jan Möbius's avatar
Jan Möbius committed
310
311
312
      idx = vhandles[j].idx() + 1;
      _out << " " << idx;

313
314
315
      if (!onlyVertices) {
        // write separator
        _out << "/" ;
316

317
318
319
        // write vertex texture coordinate index
        if (_opt.check(Options::VertexTexCoord))
          _out  << idx;
Jan Möbius's avatar
Jan Möbius committed
320

321
322
323
324
325
326
327
        // write vertex normal index
        if ( _opt.check(Options::VertexNormal) ) {
          // write separator
          _out << "/" ;
          _out << idx;
        }
      }
Jan Möbius's avatar
Jan Möbius committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    }

    _out << std::endl;
  }

  material_.clear();
  materialA_.clear();

  return true;
}


//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================