DrawMesh.cc 50.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
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
39
40
41
42
43
44
45
46
47
48
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  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:                                                    *
 *                                                                           *
 *  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.                        *
 *                                                                           *
 *  OpenFlipper 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.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
\*===========================================================================*/

#define ACG_DRAW_MESH_C

//=============================================================================

#include "DrawMesh.hh"
#include <ACG/Geometry/GPUCacheOptimizer.hh>
49
#include <ACG/GL/VertexDeclaration.hh>
50
51
#include <cassert>
#include <cmath>
52
53
#include <vector>
#include <map>
54
#include <cstring>
55
56
#include <fstream>

57
58
59
#ifdef USE_OPENMP
#include <omp.h>
#endif
60

61
62
63
64
//=============================================================================

#define DRAW_MESH_VERTEX_CMP_EPSILON 1e-4f

65
66
67
// print a memory usage report each draw call
//#define DEBUG_MEM_USAGE

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

namespace ACG
{

template <class Mesh>
DrawMeshT<Mesh>::Vertex::Vertex()
{
  for (int i = 0; i < 3; ++i)
  {
    pos[i] = 0.0f;
    n[i] = 0.0f;
//    tan[i] = 0.0f;

    if (i < 2)
      tex[i] = 0.0f;
  }

//  tan[3] = 0.0f;

  fcol = vcol = 0xFFFFFFFF;
}

template <class Mesh>
int DrawMeshT<Mesh>::Vertex::equals(const Vertex& r)
{
  float f = 0.0f; // difference
  for (int i = 0; i < 3; ++i)
  {
    f += fabsf(r.pos[i] - pos[i]);
    f += fabsf(r.n[i] - n[i]);
//    f += fabsf(r.tan[i] - tan[i]);

    if (i < 2)
      f += fabsf(r.tex[i] - tex[i]);
  }

//  f += fabsf(r.tan[3] - tan[3]);

  return (vcol == r.vcol && fcol == r.fcol) && (f < DRAW_MESH_VERTEX_CMP_EPSILON);
}

template <class Mesh>
DrawMeshT<Mesh>::DrawMeshT(Mesh& _mesh)
:  mesh_(_mesh),
112
   meshComp_(0),
113
114
115
116
117
118
119
120
121
122
   numTris_(0), numVerts_(0),
   vertices_(0),
   rebuild_(REBUILD_NONE),
   prevNumFaces_(0), prevNumVerts_(0),
   vbo_(0), ibo_(0),
   lineIBO_(0),
   indexType_(0),
   colorMode_(1),
   flatMode_(0), bVBOinFlatMode_(0),
   textureMode_(1), bVBOinHalfedgeTexMode_(1),
123
   halfedgeNormalMode_(0), bVBOinHalfedgeNormalMode_(0),
124
125
126
127
128
129
130
   invVertexMap_(0),
   verticesTmp_(0),
   textureIndexPropertyName_("Not Set"),
   perFaceTextureCoordinatePropertyName_("Not Set"),
   updatePerEdgeBuffers_(1),
  updatePerHalfedgeBuffers_(1)
{
131
132
133
  vertexDeclVCol_ = new VertexDeclaration;
  vertexDeclFCol_ = new VertexDeclaration;

134
135
136
  vertexDeclEdgeCol_ = new VertexDeclaration;
  vertexDeclHalfedgeCol_ = new VertexDeclaration;
  vertexDeclHalfedgePos_ = new VertexDeclaration;
137

138
  createVertexDeclarations();
139
140
141
}


142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187

template<class Mesh>
template<class Prop>
void DrawMeshT<Mesh>::getMeshPropertyType( Prop _propData, GLuint* _outType, int* _outSize, int* _outStride )
{
  std::string tid = typeid( _propData ).name();

  GLuint fmt = 0;
  int size = 0;

  if (sscanf(tid.c_str(), "class OpenMesh::VectorT<float,%i> const *", &size) == 1)
    fmt = GL_FLOAT;
  else if (sscanf(tid.c_str(), "class OpenMesh::VectorT<double,%i> const *", &size) == 1)
    fmt = GL_DOUBLE;
  else if (sscanf(tid.c_str(), "class OpenMesh::VectorT<int,%i> const *", &size) == 1)
    fmt = GL_INT;
  else if (sscanf(tid.c_str(), "class OpenMesh::VectorT<unsigned int,%i> const *", &size) == 1)
    fmt = GL_UNSIGNED_INT;
  else if (!strcmp(tid.c_str(), "int const *"))
  {
    fmt = GL_INT;
    size = 1;
  }
  else
  {
    std::cerr << "DrawMesh: unknown typeid of property: " << tid << std::endl;

    // random guess
    fmt = GL_DOUBLE;
    size = 3;
  }

  if (_outType)
    *_outType = fmt;

  if (_outSize)
    *_outSize = size;

  if (_outStride)
    *_outStride = (fmt == GL_DOUBLE ? 8 : 4) * size;
}


template<class Mesh>
class DrawMeshFaceInput : public MeshCompilerFaceInput
{
188

189
public:
190
191
192
193
194

  DrawMeshFaceInput(Mesh& _mesh) :
  mesh_(_mesh)
  {
  };
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

  // map[attrID] -> use per halfedge/vertex attribute (true/false)
  std::vector<int> attributeStoredPerHalfedge_;


  int getNumFaces() const { return mesh_.n_faces(); }

  // compute number of indices later automatically
  int getNumIndices() const { return 0; };

  /** Get number of vertices per face.
   * @param _faceID face index
  */
  int getFaceSize(const int _faceID) const
  {
    return mesh_.valence( mesh_.face_handle(_faceID) );
  }

  /** Get a single vertex-index entry of a face.
   *
   * @param _faceID face index
   * @param _faceCorner vertex corner of the face
   * @param _attrID attribute channel 
   * @return index-data if successful, -1 otherwise
  */
  int getSingleFaceAttr(const int _faceID, const int _faceCorner, const int _attrID) const
  {
    const typename Mesh::FaceHandle fh =  mesh_.face_handle(_faceID);

    typename Mesh::ConstFaceHalfedgeIter fh_it = mesh_.cfh_iter(fh);

    // ========================================================================================
    // Optimization for triangular meshes (use previous halfedge to skip part of the iteration)
    // ========================================================================================
    if ( mesh_.is_trimesh()) {
      if ( attributeStoredPerHalfedge_[_attrID] != 0 ) {
        switch (_faceCorner) {
          case 0 : return fh_it->idx();
          break;
          case 1 : return (mesh_.next_halfedge_handle(*fh_it)).idx();
          break;
          case 2 : return (mesh_.prev_halfedge_handle(*fh_it)).idx();
          break;
          default :   std::cerr << " Index error!" << _faceCorner << std::endl; return -1;
          break;
        }
      } else {
        switch (_faceCorner) {
          case 0 : return mesh_.to_vertex_handle(*fh_it).idx();
          break;
          case 1 : return (mesh_.to_vertex_handle(mesh_.next_halfedge_handle(*fh_it))).idx();
          break;
          case 2 : return (mesh_.to_vertex_handle(mesh_.prev_halfedge_handle(*fh_it))).idx();
          break;
          default :   std::cerr << " Index error!" << _faceCorner << std::endl; return -1;
          break;
        }
      }
    }

    // ========================================================================================
    // Poly Meshes
    // ========================================================================================
    if ( attributeStoredPerHalfedge_[_attrID] != 0 ) {

      for (int i = 0; fh_it.is_valid() && i <= _faceCorner; ++fh_it, ++i )
        if (i == _faceCorner)
          return fh_it->idx();

    } else {

      for (int i = 0; fh_it.is_valid() && i <= _faceCorner; ++fh_it, ++i )
        if (i == _faceCorner)
          return mesh_.to_vertex_handle(*fh_it).idx();

    }

    // Not found -> return -1 as error
    return -1;
  }

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @param _out pointer to output buffer, use getFaceSize(_faceID) to get the size needed to store face data
   * @return true if successful, false otherwise
  */
  bool getFaceAttr(const int _faceID, const int _attrID, int* _out) const
  {
    const typename Mesh::FaceHandle fh =  mesh_.face_handle(_faceID);

    const bool usePerHalfedge = (attributeStoredPerHalfedge_[_attrID] != 0);

    // read all vertex indices of this face
    typename Mesh::ConstFaceHalfedgeIter hh_it = mesh_.cfh_iter(fh);
    for (int i = 0; hh_it.is_valid(); ++hh_it, ++i )
    {
      _out[i] = usePerHalfedge ? hh_it->idx() : mesh_.to_vertex_handle(*hh_it).idx();
    }

    return true;
  }

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @return array data of size "getFaceSize(_faceID)", allowed to return 0 when array data not permanently available in memory
  */
  int* getFaceAttr(const int _faceID, const int _attrID) const
  {
    // cannot be implemented with OpenMesh data structure
    return 0;
  }



  int getVertexAdjCount(const int _vertexID) const
  {
    const typename Mesh::VertexHandle vh =  mesh_.vertex_handle(_vertexID);

    int counter = 0;

    // read all vertex indices of this face
    typename Mesh::ConstVertexFaceIter adj_it = mesh_.cvf_iter(vh);
    for (;adj_it.is_valid(); ++adj_it)
      ++counter;

    return counter;
  }

  int getVertexAdjFace(const int _vertexID, const int _k) const
  {
    const typename Mesh::VertexHandle vh =  mesh_.vertex_handle(_vertexID);

    // read all vertex indices of this face
    typename Mesh::ConstVertexFaceIter adj_it = mesh_.cvf_iter(vh);
    for (int i = 0; adj_it.is_valid() && i < _k; ++adj_it, ++i);

    return adj_it->idx();
  }

336
337
private:
  Mesh& mesh_;
338
339
340
341
};



342
343
344
345
346
347
template <class Mesh>
void
DrawMeshT<Mesh>::rebuild()
{
  if (rebuild_ == REBUILD_NONE) return;

348
349
350
351
352
353
  if (!mesh_.n_vertices())
  {
    numVerts_ = 0;
    numTris_ = 0;
    return;
  }
Christopher Tenter's avatar
Christopher Tenter committed
354

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
  // support for point clouds:
  if (mesh_.n_vertices() && mesh_.n_faces() == 0)
  {
    if (mesh_.n_vertices() > numVerts_)
    {
      delete [] invVertexMap_; invVertexMap_ = 0;
      delete [] vertices_; vertices_ = 0;
      delete [] verticesTmp_; verticesTmp_ = 0;

      numVerts_ = mesh_.n_vertices();
      vertices_ = new Vertex[numVerts_];
      verticesTmp_ = new Vertex[numVerts_];
    }
    numVerts_ = mesh_.n_vertices();

    // read all vertices
371
    for (size_t i = 0; i < numVerts_; ++i)
372
373
374
375
376
377
      readVertex(vertices_ + i,
                 mesh_.vertex_handle(i), 
                 (typename Mesh::HalfedgeHandle)(-1), 
                 (typename Mesh::FaceHandle)(-1));

    createVBO();
378
    rebuild_ = REBUILD_NONE;
379
380
381
382
383
384
    return;
  }



  unsigned int maxFaceVertCount = 0;
385
386
  unsigned int numIndices = 0;
  unsigned int newTriCount = countTris(&maxFaceVertCount, &numIndices);
387
388
389
390
391
392
  
  int bTriangleRebuild = 0; // what should be rebuild?
  int bVertexRebuild = 0;

  if (newTriCount > numTris_)
  {
393
    // index buffer too small
394
    if (ibo_) glDeleteBuffers(1, &ibo_);
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    ibo_ = 0;

    numTris_ = newTriCount;

    bTriangleRebuild = 1;
  }

  if (prevNumFaces_ != mesh_.n_faces())
  {
    bTriangleRebuild = 1;
    prevNumFaces_ = mesh_.n_faces();
  }

  if (prevNumVerts_ != mesh_.n_vertices())
  {
    if (prevNumVerts_ < mesh_.n_vertices())
    {
      // resize inverse vertex map
      delete [] invVertexMap_;
      invVertexMap_ = new unsigned int[mesh_.n_vertices()];
    }

    bVertexRebuild = 1;
    bTriangleRebuild = 1; // this may have caused changes in the topology!
    prevNumVerts_ = mesh_.n_vertices();
  }

422
423
  // support faster update by only updating vertices (do a complete update if the textures have to be rebuild)
  if (!bTriangleRebuild && !bVertexRebuild && (rebuild_ & REBUILD_GEOMETRY) && !(rebuild_ & REBUILD_TEXTURES))
424
425
  {
    // only update vertices, i.e. update values of vertices
426

427
428
429
430
    #ifndef WIN32
      #ifdef USE_OPENMP
        #pragma omp parallel for
      #endif
431
    #endif
432
433
434
    for (unsigned int i = 0; i < numVerts_; ++i)
    {
      // just pick one face, srews up face colors here so color updates need a full rebuild
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
      const typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);
      typename Mesh::VertexHandle   vh(-1);
      typename Mesh::FaceHandle     fh(-1);

      if (hh.is_valid())
      {
        vh = mesh_.to_vertex_handle(hh);
        fh = mesh_.face_handle(hh);
      }
      else
      {
        int f_id, c_id;
        int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
        vh = mesh_.vertex_handle(posID);
      }
450
451
452
453
454
455
456
457
458
459

      readVertex(vertices_ + i, vh, hh, fh);
    }

    createVBO();

    rebuild_ = REBUILD_NONE;
    return;
  }

460
461
462
  // full rebuild:
  delete meshComp_;
  meshComp_ = new MeshCompiler(*vertexDeclFCol_);
463
464


465
466
  // search for convenient attribute indices
  int attrIDNorm = -1, attrIDPos = -1, attrIDTexC = -1;
467

468
469
470
  for (int i = 0; i < (int)meshComp_->getVertexDeclaration()->getNumElements(); ++i)
  {
    const VertexElement* e = meshComp_->getVertexDeclaration()->getElement(i);
471

472
473
474
475
476
477
478
479
    switch (e->usage_)
    {
    case VERTEX_USAGE_POSITION: attrIDPos = i; break;
    case VERTEX_USAGE_NORMAL: attrIDNorm = i; break;
    case VERTEX_USAGE_TEXCOORD: attrIDTexC = i; break;
    default: break;
    }
  }
480
481


482
  // pass face data to mesh compiler
483
484
485
486
487
  DrawMeshFaceInput<Mesh>* faceInput = new DrawMeshFaceInput<Mesh>(mesh_);
  faceInput->attributeStoredPerHalfedge_.resize(meshComp_->getVertexDeclaration()->getNumElements(), 0);
  faceInput->attributeStoredPerHalfedge_[attrIDPos]  = 0;
  faceInput->attributeStoredPerHalfedge_[attrIDNorm] = ( (halfedgeNormalMode_ && mesh_.has_halfedge_normals()) ? 1 : 0 );
  faceInput->attributeStoredPerHalfedge_[attrIDTexC] = ( mesh_.has_halfedge_texcoords2D() ? 1 : 0);
488

489
  meshComp_->setFaceInput(faceInput);
490

491
492
493
  // set textures
  for (int i = 0; i < mesh_.n_faces(); ++i)
    meshComp_->setFaceGroup(i, getTextureIDofFace(i));
494

495
  // pass vertex data to mesh compiler
496
497


498
499
500
501
502
503
504
505
  // points
  meshComp_->setVertices(mesh_.n_vertices(), mesh_.points(), 24, false, GL_DOUBLE, 3);
  
  // normals
  if (halfedgeNormalMode_ == 0 && mesh_.has_vertex_normals())
    meshComp_->setNormals(mesh_.n_vertices(), mesh_.vertex_normals(), 24, false, GL_DOUBLE, 3);
  else if (halfedgeNormalMode_ &&  mesh_.has_halfedge_normals())
    meshComp_->setNormals(mesh_.n_halfedges(), mesh_.property(mesh_.halfedge_normals_pph()).data(), 24, false, GL_DOUBLE, 3);
506

507
508
  if (mesh_.has_halfedge_texcoords2D())
    meshComp_->setTexCoords(mesh_.n_halfedges(), mesh_.htexcoords2D(), 8, false, GL_FLOAT, 2);
509
510


511
512
513
514
515
516
517
518
/*
  setMeshCompilerInput(attrIDPos, mesh_.points(), mesh_.n_vertices());
  
  // normals
  if (halfedgeNormalMode_ == 0 && mesh_.has_vertex_normals())
    setMeshCompilerInput(attrIDNorm, mesh_.vertex_normals(), mesh_.n_vertices());
  else if (halfedgeNormalMode_ &&  mesh_.has_halfedge_normals())
    setMeshCompilerInput(attrIDNorm, mesh_.property(mesh_.halfedge_normals_pph()).data(), mesh_.n_halfedges());
519

520
521
522
523
524
525
526
527
528
  if (mesh_.has_halfedge_texcoords2D())
  {
    setMeshCompilerInput(attrIDTexC, mesh_.htexcoords2D(), mesh_.n_halfedges());
// 
//     GLuint fmtN = 0;
//     int sizeN = 0, strideN = 0;
//     getMeshPropertyType(mesh_.htexcoords2D(), &fmtN, &sizeN, &strideN);
// 
//     meshComp_->setTexCoords(mesh_.n_halfedges(), mesh_.htexcoords2D(), strideN, false, fmtN, sizeN);
529
  }
530
*/
531

532
  meshComp_->build(true, true, true, true);
533
534


535
536
537
538
  // create inverse vertex map
  for (int i = 0; i < (int)mesh_.n_faces(); ++i)
  {
    typename Mesh::FaceHandle fh =  mesh_.face_handle(i);
539

540
    int corner = 0;
541

542
543
544
545
546
547
    for (typename Mesh::FaceHalfedgeIter hh_it = mesh_.fh_iter(fh); hh_it.is_valid(); ++hh_it )
    {
      int vertexId = mesh_.to_vertex_handle(*hh_it).idx();
      invVertexMap_[vertexId] = meshComp_->mapToDrawVertexID(i, corner++);
    }
  }
548
549


550
551
  // get vertex buffer
  numVerts_ = meshComp_->getNumVertices();
552

553
554
555
  delete [] vertices_;
  vertices_ = new Vertex[numVerts_];
  meshComp_->getVertexBuffer(vertices_);
556

557
558
  // copy colors
  for (int i = 0; i < (int)numVerts_; ++i)
559
  {
560
    typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);
561

562
563
564
565
566
567
568
569
570
571
572
573
574
    if (hh.is_valid())
    {
      vertices_[i].vcol = getVertexColor(mesh_.to_vertex_handle(hh));
      vertices_[i].fcol = getFaceColor(mesh_.face_handle(hh));
    }
    else
    {
      // isolated vertex
      int f_id, c_id;
      int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
      vertices_[i].vcol = getVertexColor( mesh_.vertex_handle(posID) );
      vertices_[i].fcol = 0;
    }
575
576
577
578
579
580
581
582
  }

  //////////////////////////////////////////////////////////////////////////
  // copy to GPU

  createVBO();
  createIBO();

583
  bVBOinHalfedgeNormalMode_ = halfedgeNormalMode_;
584
585
586
587
588
589
590
591
592
593

  rebuild_ = REBUILD_NONE;

  // picking buffers update
}


template <class Mesh>
void
DrawMeshT<Mesh>::readVertex(Vertex* _pV,
594
595
596
                            const typename Mesh::VertexHandle _vh,
                            const typename Mesh::HalfedgeHandle _hh,
                            const typename Mesh::FaceHandle _fh)
597
{
598
599
600
  static const typename Mesh::HalfedgeHandle invalidHEH(-1);
  static const typename Mesh::FaceHandle     invalidFH(-1);

601
602
603
604
  for (int m = 0; m < 3; ++m)
  {
    _pV->pos[m] = mesh_.point(_vh)[m];

605
    if (halfedgeNormalMode_ == 0 && mesh_.has_vertex_normals())
606
      _pV->n[m] = mesh_.normal(_vh)[m];
607
    else if (halfedgeNormalMode_ && 
608
      mesh_.has_halfedge_normals() && _hh != invalidHEH)
609
      _pV->n[m] = mesh_.normal(_hh)[m];
610
611
612
613
614
615
    else _pV->n[m] = 0.0f;

    if (m < 2)
    {
      if (mesh_.has_halfedge_texcoords2D())
      {
616
        if (_hh != invalidHEH)
617
618
619
620
621
622
623
624
625
626
          _pV->tex[m] = mesh_.texcoord2D(_hh)[m];
      }
      else _pV->tex[m] = 0.0f;
    }
  }
  
  // per face & per vertex color
  unsigned int byteCol[2];
  for (int col = 0; col < 2; ++col)
  {
627
    Vec4uc vecCol(255, 255, 255, 255);
628

629
    if (col == 0 && mesh_.has_vertex_colors()) vecCol = OpenMesh::color_cast<Vec4uc, typename Mesh::Color>(mesh_.color(_vh));
630
    if (_fh != invalidFH)
631
632
    {
      if (col == 1 && mesh_.has_face_colors() && _fh.idx() >= 0) 
633
        vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_fh));
634
635
636
637
638
639
    }

    // OpenGL color format: A8B8G8R8
    byteCol[col] = (unsigned char)(vecCol[0]);
    byteCol[col] |= ((unsigned char)(vecCol[1])) << 8;
    byteCol[col] |= ((unsigned char)(vecCol[2])) << 16;
640
641
    byteCol[col] |= ((unsigned char)(vecCol[3])) << 24;
    //byteCol[col] |= 0xFF << 24; // if no alpha channel
642
643
644
645
646
647
648
649
650
  }

 _pV->vcol = byteCol[0];
//  _pV->vcol = 0xFFFF0000; // blue,  debug
 _pV->fcol = byteCol[1];
//  pV->fcol = 0xFF00FF00; // green, debug
}

template <class Mesh>
651
652
unsigned int
DrawMeshT<Mesh>::getVertexColor(const typename Mesh::VertexHandle _vh)
653
{
654
  static const typename Mesh::VertexHandle     invalidVH(-1);
655

656
657
658
  unsigned int byteCol;
  
  Vec4uc vecCol(255, 255, 255, 255);
659

660
661
  if ( _vh != invalidVH && mesh_.has_vertex_colors() )
    vecCol = OpenMesh::color_cast<Vec4uc, typename Mesh::Color>(mesh_.color(_vh));
662

663
664
665
666
667
  // OpenGL color format: A8B8G8R8
  byteCol  = (unsigned char)(vecCol[0]);
  byteCol |= ((unsigned char)(vecCol[1])) << 8;
  byteCol |= ((unsigned char)(vecCol[2])) << 16;
  byteCol |= ((unsigned char)(vecCol[3])) << 24;
668

669
  return byteCol;
670
671
672
}

template <class Mesh>
673
674
unsigned int
DrawMeshT<Mesh>::getFaceColor(const typename Mesh::FaceHandle _fh)
675
{
676
  static const typename Mesh::FaceHandle     invalidFH(-1);
677

678
679
  unsigned int byteCol;
  Vec4uc vecCol(255, 255, 255, 255);
680

681
682
  if ( _fh != invalidFH && mesh_.has_face_colors() && _fh.idx() >= 0 ) 
    vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_fh));
683

684
685
686
687
688
  // OpenGL color format: A8B8G8R8
  byteCol  = (unsigned char)(vecCol[0]);
  byteCol |= ((unsigned char)(vecCol[1])) << 8;
  byteCol |= ((unsigned char)(vecCol[2])) << 16;
  byteCol |= ((unsigned char)(vecCol[3])) << 24;
689

690
  return byteCol;
691
692
693
694
695
}


template <class Mesh>
int
696
DrawMeshT<Mesh>::getTextureIDofFace(unsigned int _face)
697
698
699
{
  OpenMesh::FPropHandleT< int > textureIndexProperty;
  if (mesh_.get_property_handle(textureIndexProperty, textureIndexPropertyName_))
700
    return mesh_.property(textureIndexProperty, mesh_.face_handle(_face));
701

702
703
  if (mesh_.has_face_texture_index())
    return mesh_.texture_index(mesh_.face_handle(_face));
704

705
  return 0;
706
707
708
}

template <class Mesh>
709
710
int
DrawMeshT<Mesh>::getTextureIDofTri(unsigned int _tri)
711
{
712
  return getTextureIDofFace(meshComp_->mapToOriginalFaceID(_tri));
713
714
715
716
717
718
719
720
721
722
723
}


template <class Mesh>
void
DrawMeshT<Mesh>::createVBO()
{
  // data read from vertices_
  if (!vbo_)
    glGenBuffersARB(1, &vbo_);

724
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, vbo_);
725
726
727
728
729
730
731
732
733

  if (!flatMode_ && textureMode_)
  {
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVerts_ * sizeof(Vertex), vertices_, GL_STATIC_DRAW_ARB);
    bVBOinFlatMode_ = 0;
  }
  else
  {
    // use per face normals
734
735
736
737

    if (!verticesTmp_)
      verticesTmp_ = new Vertex[numVerts_];

738
739
740
741
742
743
    memcpy(verticesTmp_, vertices_, sizeof(Vertex) * numVerts_);

    if (flatMode_)
    {
      for (unsigned int i = 0; i < numTris_; ++i)
      {
744
745
        int faceId = meshComp_->mapToOriginalFaceID(i);

746
        // get face normal
747
        ACG::Vec3d n = mesh_.normal(mesh_.face_handle(faceId));
748
749
750
751

        // store face normal in last tri vertex
        for (unsigned int k = 0; k < 3; ++k)
        {
752
753
          int idx = meshComp_->getIndex(i*3 + 2);
          verticesTmp_[idx].n[k] = n[k];
754
755
756
757
758
759
760
761
        }
      }
      bVBOinFlatMode_ = 1;
    }
    if (!textureMode_)
    {
      for (unsigned int i = 0; i < numVerts_; ++i)
      {
762
763
764
765
766
767
768
769
770
        typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

        if (hh.is_valid())
        {
          // copy texcoord
          for (int k = 0; k < 2; ++k)
            verticesTmp_[i].tex[k] = mesh_.texcoord2D( mesh_.to_vertex_handle(hh) )[k];
        }
        else
771
        {
772
773
774
775
776
777
          // isolated vertex
          int f_id, c_id;
          int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);

          for (int k = 0; k < 2; ++k)
            verticesTmp_[i].tex[k] = mesh_.texcoord2D( mesh_.vertex_handle(posID) )[k];
778
779
780
781
782
783
784
785
786
        }
      }
      bVBOinHalfedgeTexMode_ = 0;
    }

    glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVerts_ * sizeof(Vertex), verticesTmp_, GL_STATIC_DRAW_ARB);

  }

787
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
788
789
790
791
792
793
794
795
796
797
798
799
800
}

template <class Mesh>
void
DrawMeshT<Mesh>::createIBO()
{
  // data read from indices_

  // create triangle index buffer

  if (!ibo_)
    glGenBuffersARB(1, &ibo_);

801
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, ibo_);
802
803

  indexType_ = GL_UNSIGNED_INT;
804
805
806
807
808
809
810
811
812
813
814
815
816
//   if (numVerts_ <= 0xFFFF)
//   {
//     // use 2 byte indices
//     unsigned short* pwIndices = (unsigned short*)indicesTmp_;
//     indexType_ = GL_UNSIGNED_SHORT;
// 
//     for (unsigned int i = 0; i < numTris_ * 3; ++i)
//       pwIndices[i] = (unsigned short)indices_[i];
// 
//     glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numTris_ * 3 * sizeof(unsigned short), pwIndices, GL_STATIC_DRAW_ARB);
//   }
//   else
  glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numTris_ * 3 * sizeof(unsigned int), meshComp_->getIndexBuffer(), GL_STATIC_DRAW_ARB);
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842


  // line index buffer:
  if (mesh_.n_edges())
  {
    unsigned int* pLineBuffer = new unsigned int[mesh_.n_edges() * 2];

    if (!lineIBO_)
      glGenBuffersARB(1, &lineIBO_);

    for (unsigned int i = 0; i < mesh_.n_edges(); ++i)
    {
      OpenMesh::HalfedgeHandle hh = mesh_.halfedge_handle(mesh_.edge_handle(i), 0);

      if (indexType_ == GL_UNSIGNED_SHORT)
      {
        ((unsigned short*)pLineBuffer)[2*i] = (unsigned short)invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        ((unsigned short*)pLineBuffer)[2*i+1] = (unsigned short)invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
      }
      else
      {
        pLineBuffer[2*i] = invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        pLineBuffer[2*i+1] = invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
      }
    }

843
    ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER, lineIBO_);
844
845
846
847
848
849
850
851
852
853
854
855
856
857

    // 2 or 4 byte indices:
    if (indexType_ == GL_UNSIGNED_SHORT)
      glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 
                   mesh_.n_edges() * 2 * sizeof(unsigned short), 
                   pLineBuffer, GL_STATIC_DRAW_ARB);
    else
      glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 
                   mesh_.n_edges() * 2 * sizeof(unsigned int),
                   pLineBuffer, GL_STATIC_DRAW_ARB);

    delete [] pLineBuffer;
  }

858
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
859
860
861
862
863
864
865
866
867
868
869
}

template <class Mesh>
DrawMeshT<Mesh>::~DrawMeshT(void)
{
  delete [] vertices_;
  delete [] verticesTmp_;
//  delete [] m_pVerticesC;

  delete [] invVertexMap_;

870
871
  delete vertexDeclFCol_;
  delete vertexDeclVCol_;
872
873
874
  delete vertexDeclEdgeCol_;
  delete vertexDeclHalfedgeCol_;
  delete vertexDeclHalfedgePos_;
875

876
877
878
879
880
  if (vbo_) glDeleteBuffersARB(1, &vbo_);
  if (ibo_) glDeleteBuffersARB(1, &ibo_);
  if (lineIBO_) glDeleteBuffersARB(1, &lineIBO_);
}

881
882
883
884
885
886
887
888


template <class Mesh>
unsigned int DrawMeshT<Mesh>::getMemoryUsage(bool _printReport)
{
  unsigned int res = 0;
  unsigned int sysBufSize = 0;

889
  sysBufSize += meshComp_->getMemoryUsage();
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965

  // vertex buffer
  if (vertices_)
    sysBufSize += sizeof(Vertex) * numVerts_;

  if (verticesTmp_)
    sysBufSize += sizeof(Vertex) * numVerts_;

  
  
  res += sysBufSize;

  // mappings
  unsigned int mapsSize = 0;
 
  if (invVertexMap_)
    res += mesh_.n_vertices() * 4;

  res += mapsSize;


  // picking buffers
  unsigned int pickBufSize = 0;

  pickBufSize += pickVertBuf_.capacity() * sizeof(ACG::Vec3f);
  pickBufSize += pickVertColBuf_.capacity() * sizeof(ACG::Vec4uc);

  pickBufSize += pickEdgeBuf_.capacity() * sizeof(ACG::Vec4uc);

  pickBufSize += pickFaceVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  pickBufSize += pickFaceColBuf_.capacity() * sizeof(ACG::Vec4uc);


  pickBufSize += pickAnyFaceColBuf_.capacity() * sizeof(ACG::Vec4uc);
  pickBufSize += pickAnyEdgeColBuf_.capacity() * sizeof(ACG::Vec4uc);
  pickBufSize += pickAnyVertexColBuf_.capacity() * sizeof(ACG::Vec4uc);

  res += pickBufSize;


  // edge and halfedge vertex buffers (glDraw from sysmem)
  unsigned int edgeBufSize = 0;

  edgeBufSize += perEdgeVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  edgeBufSize += perEdgeColorBuf_.capacity() * sizeof(ACG::Vec4uc);

  edgeBufSize += perHalfedgeVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  edgeBufSize += perHalfedgeColorBuf_.capacity() * sizeof(ACG::Vec4uc);


  res += edgeBufSize;


  unsigned int gpuBufSize = 0;

  if (ibo_)
    gpuBufSize += numTris_ * 3 * (indexType_ == GL_UNSIGNED_INT ? 4 : 2);

  if (vbo_)
    gpuBufSize += numVerts_ * sizeof(Vertex);

  if (_printReport)
  {
    std::cout << "\nDrawMesh memory usage in MB:\n";
    std::cout << "Vertex+IndexBuffer (SYSMEM only): " << float(sysBufSize) / (1024 * 1024);
    std::cout << "\nMappings: " << float(mapsSize) / (1024 * 1024);
    std::cout << "\nPicking Buffers: " << float(pickBufSize) / (1024 * 1024);
    std::cout << "\nEdge Buffers: " << float(edgeBufSize) / (1024 * 1024);
    std::cout << "\nTotal SYSMEM: " << float(res) / (1024 * 1024);
    std::cout << "\nTotal GPU: " << float(gpuBufSize) / (1024 * 1024) << std::endl;
  }
  
  return res;
}


966
template <class Mesh>
967
void DrawMeshT<Mesh>::updateGPUBuffers()
968
969
{
  // rebuild if necessary
970
  if ((!numTris_ && mesh_.n_faces())|| ! numVerts_ || (!meshComp_ && mesh_.n_faces()))
971
972
973
  {
    rebuild_ = REBUILD_FULL;
  }
974

975
976
  if (bVBOinHalfedgeNormalMode_ != halfedgeNormalMode_) rebuild_ = REBUILD_FULL;

977
978
979
980
981
982
983
984
  // if no rebuild necessary, check for smooth / flat shading switch 
  // to update normals
  if (rebuild_ == REBUILD_NONE)
  {
    if (bVBOinFlatMode_ != flatMode_ || bVBOinHalfedgeTexMode_ != textureMode_)
      createVBO();
  }
  else
985
  {
986
    rebuild();
987
  }
988
989
990
991
992
993
994
995
996
997
998
999
1000
}


template <class Mesh>
GLuint DrawMeshT<Mesh>::getVBO()
{
  updateGPUBuffers();
  return vbo_;
}

template <class Mesh>
GLuint DrawMeshT<Mesh>::getIBO()
{