OBJWriter.cc 12.7 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
/* ========================================================================= *
Jan Möbius's avatar
Jan Möbius committed
2 3
 *                                                                           *
 *                               OpenMesh                                    *
Jan Möbius's avatar
Jan Möbius committed
4
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
Jan Möbius's avatar
Typo  
Jan Möbius committed
5
 *           Department of Computer Graphics and Multimedia                  *
Jan Möbius's avatar
Jan Möbius committed
6 7
 *                          All rights reserved.                             *
 *                            www.openmesh.org                               *
Jan Möbius's avatar
Jan Möbius committed
8
 *                                                                           *
9
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
10 11
 * This file is part of OpenMesh.                                            *
 *---------------------------------------------------------------------------*
12
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
Jan Möbius's avatar
Jan Möbius committed
39 40
 *                                                                           *
 * ========================================================================= */
41 42

/*===========================================================================*\
43
 *                                                                           *
44 45
 *   $Revision$                                                         *
 *   $Date$                   *
Jan Möbius's avatar
Jan Möbius committed
46 47 48 49 50 51 52 53 54
 *                                                                           *
\*===========================================================================*/


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


//STL
#include <fstream>
Jan Möbius's avatar
Jan Möbius committed
55
#include <limits>
Jan Möbius's avatar
Jan Möbius committed
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 84 85 86 87 88

// OpenMesh
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <OpenMesh/Core/IO/IOManager.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_::
89
write(const std::string& _filename, BaseExporter& _be, Options _opt, std::streamsize _precision) const
Jan Möbius's avatar
Jan Möbius committed
90 91 92 93 94 95 96 97 98 99
{
  std::fstream out(_filename.c_str(), std::ios_base::out );

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

100
  // Set precision on output stream. The default is set via IOManager and passed through to all writers.
101 102
  out.precision(_precision);

103 104 105
  // Set fixed output to avoid problems with programs not reading scientific notation correctly
  out << std::fixed;

Jan Möbius's avatar
Jan Möbius committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
  {
#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
122
    dot = objName_.find_last_of(".");
Jan Möbius's avatar
Jan Möbius committed
123 124

    if(dot != std::string::npos)
125
      objName_ = objName_.substr(0,dot);
Jan Möbius's avatar
Jan Möbius committed
126 127
  }

128
  bool result = write(out, _be, _opt, _precision);
Jan Möbius's avatar
Jan Möbius committed
129 130 131 132 133 134 135

  out.close();
  return result;
}

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

Jan Möbius's avatar
Jan Möbius committed
136
size_t _OBJWriter_::getMaterial(OpenMesh::Vec3f _color) const
Jan Möbius's avatar
Jan Möbius committed
137
{
Jan Möbius's avatar
Jan Möbius committed
138
  for (size_t i=0; i < material_.size(); i++)
Jan Möbius's avatar
Jan Möbius committed
139 140 141 142 143 144 145 146 147 148
    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
149
size_t _OBJWriter_::getMaterial(OpenMesh::Vec4f _color) const
Jan Möbius's avatar
Jan Möbius committed
150
{
Jan Möbius's avatar
Jan Möbius committed
151
  for (size_t i=0; i < materialA_.size(); i++)
Jan Möbius's avatar
Jan Möbius committed
152 153 154 155 156 157 158 159 160 161 162 163
    if(materialA_[i] == _color)
      return i;

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

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

bool
_OBJWriter_::
164
writeMaterial(std::ostream& _out, BaseExporter& _be, Options _opt) const
Jan Möbius's avatar
Jan Möbius committed
165 166 167 168 169 170 171 172
{
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

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

  //iterate over faces
Jan Möbius's avatar
Jan Möbius committed
173
  for (size_t i=0, nF=_be.n_faces(); i<nF; ++i)
Jan Möbius's avatar
Jan Möbius committed
174 175 176
  {
    //color with alpha
    if ( _opt.color_has_alpha() ){
Jan Möbius's avatar
Jan Möbius committed
177
      cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(int(i)) ));
Jan Möbius's avatar
Jan Möbius committed
178 179 180
      getMaterial(cA);
    }else{
    //and without alpha
Jan Möbius's avatar
Jan Möbius committed
181
      c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(int(i)) ));
Jan Möbius's avatar
Jan Möbius committed
182 183 184 185 186 187
      getMaterial(c);
    }
  }

  //write the materials
  if ( _opt.color_has_alpha() )
Jan Möbius's avatar
Jan Möbius committed
188
    for (size_t i=0; i < materialA_.size(); i++){
189 190
      _out << "newmtl " << "mat" << i << '\n';
      _out << "Ka 0.5000 0.5000 0.5000" << '\n';
191
      _out << "Kd " << materialA_[i][0] << ' ' << materialA_[i][1] << ' ' << materialA_[i][2] << '\n';
192 193
      _out << "Tr " << materialA_[i][3] << '\n';
      _out << "illum 1" << '\n';
Jan Möbius's avatar
Jan Möbius committed
194 195
    }
  else
Jan Möbius's avatar
Jan Möbius committed
196
    for (size_t i=0; i < material_.size(); i++){
197 198
      _out << "newmtl " << "mat" << i << '\n';
      _out << "Ka 0.5000 0.5000 0.5000" << '\n';
199
      _out << "Kd " << material_[i][0] << ' ' << material_[i][1] << ' ' << material_[i][2] << '\n';
200
      _out << "illum 1" << '\n';
Jan Möbius's avatar
Jan Möbius committed
201 202 203 204 205 206 207 208 209 210
    }

  return true;
}

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


bool
_OBJWriter_::
211
write(std::ostream& _out, BaseExporter& _be, Options _opt, std::streamsize _precision) const
Jan Möbius's avatar
Jan Möbius committed
212
{
Jan Möbius's avatar
Jan Möbius committed
213 214
  unsigned int idx;
  size_t i, j,nV, nF;
Jan Möbius's avatar
Jan Möbius committed
215 216 217 218 219 220 221 222 223 224
  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";

225
  _out.precision(_precision);
Jan Möbius's avatar
Jan Möbius committed
226 227 228 229 230

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

231 232 233 234
  // No binary mode for OBJ
  if ( _opt.check(Options::Binary) ) {
    omout() << "[OBJWriter] : Warning, Binary mode requested for OBJ Writer (No support for Binary mode), falling back to standard." <<  std::endl;
  }
Jan Möbius's avatar
Jan Möbius committed
235

236 237 238 239 240
  // check for unsupported writer features
  if (_opt.check(Options::FaceNormal) ) {
    omerr() << "[OBJWriter] : FaceNormal not supported by OBJ Writer" <<  std::endl;
    return false;
  }
Jan Möbius's avatar
Jan Möbius committed
241

242 243 244 245 246
  // check for unsupported writer features
  if (_opt.check(Options::VertexColor) ) {
    omerr() << "[OBJWriter] : VertexColor not supported by OBJ Writer" <<  std::endl;
    return false;
  }
Jan Möbius's avatar
Jan Möbius committed
247 248 249 250 251 252 253 254

  //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 );

255
    if (!matStream)
Jan Möbius's avatar
Jan Möbius committed
256 257 258 259 260 261 262 263 264 265 266 267
    {
      omerr() << "[OBJWriter] : cannot write material file " << matFile << std::endl;

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

      matStream.close();
    }
  }

  // header
  _out << "# " << _be.n_vertices() << " vertices, ";
268
  _out << _be.n_faces() << " faces" << '\n';
Jan Möbius's avatar
Jan Möbius committed
269 270 271

  // material file
  if (useMatrial &&  _opt.check(Options::FaceColor) )
272
    _out << "mtllib " << objName_ << ".mat" << '\n';
Jan Möbius's avatar
Jan Möbius committed
273

274 275 276 277 278 279 280 281 282 283 284 285 286
  std::map<Vec2f,int> texMap;
  //collect Texturevertices from halfedges
  if(_opt.check(Options::FaceTexCoord))
  {
    std::vector<Vec2f> texCoords;
    //add all texCoords to map
    unsigned int num = _be.get_face_texcoords(texCoords);
    for(unsigned int i = 0; i < num ; ++i)
    {
      texMap[texCoords[i]] = i;
    }
  }

287
  //collect Texture coordinates from vertices
288 289
  if(_opt.check(Options::VertexTexCoord))
  {
290
    for (size_t i=0, nV=_be.n_vertices(); i<nV; ++i)
291
    {
Jan Möbius's avatar
Jan Möbius committed
292
      vh = VertexHandle(static_cast<int>(i));
293
      t  = _be.texcoord(vh);
Jan Möbius's avatar
Jan Möbius committed
294
      texMap[t] = static_cast<int>(i);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    }
  }

  // assign each texcoord in the map its id
  // and write the vt entries
  if(_opt.check(Options::VertexTexCoord) || _opt.check(Options::FaceTexCoord))
  {
    int texCount = 0;
    for(std::map<Vec2f,int>::iterator it = texMap.begin(); it != texMap.end() ; ++it)
    {
      _out << "vt " << it->first[0] << " " << it->first[1] << '\n';
      it->second = ++texCount;
    }
  }

Jan Möbius's avatar
Jan Möbius committed
310 311 312
  // vertex data (point, normals, texcoords)
  for (i=0, nV=_be.n_vertices(); i<nV; ++i)
  {
Jan Möbius's avatar
Jan Möbius committed
313
    vh = VertexHandle(int(i));
Jan Möbius's avatar
Jan Möbius committed
314 315 316 317
    v  = _be.point(vh);
    n  = _be.normal(vh);
    t  = _be.texcoord(vh);

318
    _out << "v " << v[0] <<" "<< v[1] <<" "<< v[2] << '\n';
Jan Möbius's avatar
Jan Möbius committed
319 320

    if (_opt.check(Options::VertexNormal))
321
      _out << "vn " << n[0] <<" "<< n[1] <<" "<< n[2] << '\n';    
Jan Möbius's avatar
Jan Möbius committed
322 323
  }

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

326 327
  // we do not want to write seperators if we only write vertex indices
  bool onlyVertices =    !_opt.check(Options::VertexTexCoord)
328 329
                      && !_opt.check(Options::VertexNormal)
                      && !_opt.check(Options::FaceTexCoord);
330

Jan Möbius's avatar
Jan Möbius committed
331 332 333 334 335
  // 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
336
      size_t material = std::numeric_limits<std::size_t>::max();
337

Jan Möbius's avatar
Jan Möbius committed
338 339
      //color with alpha
      if ( _opt.color_has_alpha() ){
Jan Möbius's avatar
Jan Möbius committed
340
        cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(int(i)) ));
341 342
        material = getMaterial(cA);
      } else{
Jan Möbius's avatar
Jan Möbius committed
343
      //and without alpha
Jan Möbius's avatar
Jan Möbius committed
344
        c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(int(i)) ));
345
        material = getMaterial(c);
Jan Möbius's avatar
Jan Möbius committed
346 347
      }

348
      // if we are ina a new material block, specify in the file which material to use
349
      if(lastMat != material) {
350
        _out << "usemtl mat" << material << '\n';
Jan Möbius's avatar
Jan Möbius committed
351
        lastMat = material;
352
      }
Jan Möbius's avatar
Jan Möbius committed
353 354 355 356
    }

    _out << "f";

Jan Möbius's avatar
Jan Möbius committed
357
    _be.get_vhandles(FaceHandle(int(i)), vhandles);
Jan Möbius's avatar
Jan Möbius committed
358 359 360

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

362
      // Write vertex index
Jan Möbius's avatar
Jan Möbius committed
363 364 365
      idx = vhandles[j].idx() + 1;
      _out << " " << idx;

366 367 368
      if (!onlyVertices) {
        // write separator
        _out << "/" ;
369

370 371 372 373 374 375 376 377 378 379
        //write texCoords index from halfedge
        if(_opt.check(Options::FaceTexCoord))
        {
          _out << texMap[_be.texcoord(_be.getHeh(FaceHandle(int(i)),vhandles[j]))];
        }

        else
        {
          // write vertex texture coordinate index
          if (_opt.check(Options::VertexTexCoord))
380
            _out  << texMap[_be.texcoord(vhandles[j])];
381
        }
Jan Möbius's avatar
Jan Möbius committed
382

383 384 385 386 387 388 389
        // write vertex normal index
        if ( _opt.check(Options::VertexNormal) ) {
          // write separator
          _out << "/" ;
          _out << idx;
        }
      }
Jan Möbius's avatar
Jan Möbius committed
390 391
    }

392
    _out << '\n';
Jan Möbius's avatar
Jan Möbius committed
393 394 395 396 397 398 399 400 401 402 403 404 405
  }

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

  return true;
}


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