MeshNode2T_impl.hh 50.4 KB
Newer Older
1
#pragma once
Jan Möbius's avatar
Jan Möbius committed
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
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * 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
43

Jan Möbius's avatar
Jan Möbius committed
44
45
46
47
48
49
50
51
52
53
54
55




//=============================================================================
//
//  CLASS MeshNodeT - IMPLEMENTATION
//
//=============================================================================

#define ACG_MESHNODE_C

56
57
#include "MeshNode2T.hh"

Jan Möbius's avatar
Jan Möbius committed
58
59
60
#include <ACG/Geometry/GPUCacheOptimizer.hh>
#include <ACG/GL/DrawMesh.hh>
#include <ACG/GL/GLError.hh>
61
#include <ACG/GL/GLState.hh>
Jan Möbius's avatar
Jan Möbius committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

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


namespace ACG {
namespace SceneGraph {
    

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



template<class Mesh>
MeshNodeT<Mesh>::
MeshNodeT(Mesh& _mesh,
          BaseNode* _parent,
78
          const std::string& _name ):
Jan Möbius's avatar
Jan Möbius committed
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  MeshNodeBase(_parent, _name),
  mesh_(_mesh),
  drawMesh_(0),
  enableNormals_(true),
  enableColors_(true),
  enabled_arrays_(0),
  updateVertexPicking_(true),
  vertexPickingBaseIndex_(0),
  updateEdgePicking_(true),
  edgePickingBaseIndex_(0),
  updateFacePicking_(true),
  facePickingBaseIndex_(0),
  updateAnyPicking_(true),
  anyPickingBaseIndex_(0),
  perFaceTextureIndexAvailable_(false),
  textureMap_(0),
  draw_with_offset_(false)
{
 
  /// \todo : Handle vbo not supported
  
  drawMesh_ = new DrawMeshT<Mesh>(mesh_);

  // Hand draw mesh down to super class.
  MeshNodeBase::supplyDrawMesh(drawMesh_);
}  

template<class Mesh>
MeshNodeT<Mesh>::
~MeshNodeT()
{
  // Delete all allocated buffers
  delete drawMesh_;
}

template<class Mesh>
DrawModes::DrawMode
MeshNodeT<Mesh>::
availableDrawModes() const {
  DrawModes::DrawMode drawModes(DrawModes::NONE);
  
  // We can always render points and a wireframe.
  drawModes |= DrawModes::POINTS;
  drawModes |= DrawModes::HIDDENLINE;
  drawModes |= DrawModes::WIREFRAME;
  drawModes |= DrawModes::HALFEDGES;
  
  if (mesh_.has_vertex_normals())
  {
    drawModes |= DrawModes::POINTS_SHADED;  
    drawModes |= DrawModes::SOLID_SMOOTH_SHADED;
    drawModes |= DrawModes::SOLID_PHONG_SHADED;
  }
  
  if (mesh_.has_face_normals())
    drawModes |= DrawModes::SOLID_FLAT_SHADED;

  if (mesh_.has_halfedge_normals())
    drawModes |= DrawModes::SOLID_SMOOTH_SHADED_FEATURES;
  
  if (mesh_.has_vertex_colors())
  {
    drawModes |= DrawModes::POINTS_COLORED;
    drawModes |= DrawModes::SOLID_POINTS_COLORED;

    if (mesh_.has_vertex_normals())
      drawModes |= DrawModes::SOLID_POINTS_COLORED_SHADED;
  }

  if(mesh_.has_edge_colors())
  {
    drawModes |= DrawModes::EDGES_COLORED;
  }

  if(mesh_.has_halfedge_colors())
  {
    drawModes |= DrawModes::HALFEDGES_COLORED;
  }
  
158
159
  bool enableTexturedFaces = drawMesh_->perFaceTextureCoordinateAvailable() != 0;

Jan Möbius's avatar
Jan Möbius committed
160
161
162
163
164
165
166
167
168
  if (mesh_.has_face_colors()) {
    drawModes |= DrawModes::SOLID_FACES_COLORED;
    
    if( mesh_.has_face_normals() )
      drawModes |= DrawModes::SOLID_FACES_COLORED_FLAT_SHADED;

    if (mesh().has_vertex_normals()) {
      drawModes |= DrawModes::SOLID_FACES_COLORED_SMOOTH_SHADED;

169
      if (enableTexturedFaces)
Jan Möbius's avatar
Jan Möbius committed
170
171
172
173
174
175
176
177
178
179
180
        drawModes |= DrawModes::SOLID_FACES_COLORED_2DTEXTURED_FACE_SMOOTH_SHADED;
    }
  }
  
  if ( mesh_.has_vertex_texcoords2D() ) {
    drawModes |= DrawModes::SOLID_TEXTURED;
    
    if (mesh_.has_vertex_normals())
      drawModes |= DrawModes::SOLID_TEXTURED_SHADED; 
  }
  
181
  if ( enableTexturedFaces ) {
Jan Möbius's avatar
Jan Möbius committed
182
183
184
185
186
187
188
189
190
191
192
193
194
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
    drawModes |= DrawModes::SOLID_2DTEXTURED_FACE;
    
    if (mesh_.has_face_normals())
      drawModes |= DrawModes::SOLID_2DTEXTURED_FACE_SHADED;
  }
  
  return drawModes;
}

template<class Mesh>
void
MeshNodeT<Mesh>::
boundingBox(Vec3d& _bbMin, Vec3d& _bbMax) {
  _bbMin.minimize(bbMin_);
  _bbMax.maximize(bbMax_);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
draw(GLState& _state, const DrawModes::DrawMode& _drawMode) {
    
/*  
  if ( ( _drawMode & DrawModes::SOLID_FLAT_SHADED ) ||
    ( _drawMode & DrawModes::SOLID_FACES_COLORED_FLAT_SHADED) ||
    ( _drawMode & DrawModes::SOLID_TEXTURED) ||
    ( _drawMode & DrawModes::SOLID_2DTEXTURED_FACE))
  {
    drawMesh_->setFlatShading();
  }
  else
    drawMesh_->setSmoothShading();


  if ( (_drawMode & DrawModes::SOLID_FACES_COLORED ||
    _drawMode & DrawModes::SOLID_FACES_COLORED_FLAT_SHADED))
  {
    drawMesh_->usePerFaceColors();
  }
  else
    drawMesh_->usePerVertexColors();
*/
    
  
  glPushAttrib(GL_ENABLE_BIT);
  
  GLenum prev_depth_offset = _state.depthFunc();
  if(draw_with_offset_)
  {
    ACG::GLState::enable(GL_POLYGON_OFFSET_FILL);
    glPolygonOffset(-1.0f, -10.0f);
    ACG::GLState::depthFunc(GL_LEQUAL);
  }
  
  GLenum prev_depth = _state.depthFunc();

  /// get bound texture buffer and target
  GLuint lastBuffer = ACG::GLState::getBoundTextureBuffer();
  GLenum lastTarget = ACG::GLState::getBoundTextureTarget();

  // Unbind to avoid painting textures on non textured primitives
  ACG::GLState::bindTexture(lastTarget,0);


  if ( (_drawMode & DrawModes::POINTS) || (_drawMode & DrawModes::POINTS_COLORED) || (_drawMode & DrawModes::POINTS_SHADED )  ) {
    
    _state.set_color( _state.specular_color() );

    ACG::GLState::shadeModel(GL_FLAT);
    
    if ( _drawMode & DrawModes::POINTS_SHADED  ) {
      ACG::GLState::enable(GL_LIGHTING);
    } else
      ACG::GLState::disable(GL_LIGHTING);
  
    // Use Colors in this mode if allowed
    if ( enableColors_ && (_drawMode & DrawModes::POINTS_COLORED) )
    {
      drawMesh_->usePerVertexColors();

      // If we have colors and lighting with normals, we have to use colormaterial
      if ( enableNormals_ && (_drawMode & DrawModes::POINTS_SHADED ) )
        ACG::GLState::enable(GL_COLOR_MATERIAL);
      else
        ACG::GLState::disable(GL_COLOR_MATERIAL);
    }
    else
      drawMesh_->disableColors();
    
    // Bring the arrays online
//    enable_arrays(arrays);
    
    // Draw vertices
    draw_vertices();
  }
  
  
  /// \todo We can render also wireframe shaded and with vertex colors
  if (_drawMode & DrawModes::WIREFRAME)
  {

    const Vec4f oldColor = _state.color();

    // If the mode is atomic, we use the specular, otherwise we take the overlay color
    if (_drawMode.isAtomic() )
      _state.set_color( _state.specular_color() );
    else
      _state.set_color( _state.overlay_color() );

    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);

    drawMesh_->disableColors();

    draw_lines();

    _state.set_color(oldColor);
  }  
  
  if (_drawMode & DrawModes::HIDDENLINE)
  {
//    enable_arrays(VERTEX_ARRAY);
    
    // First:
    // Render all faces in background color to initialize z-buffer
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

//    drawMesh_->SetFlatShading();
    drawMesh_->disableColors();

    Vec4f  clear_color  = _state.clear_color();
    clear_color[3] = 1.0;
    _state.set_color( clear_color );

    ACG::GLState::depthRange(0.01, 1.0);
    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    // Second
    // Render the lines. All lines not on the front will be skipped in z-test
//    enable_arrays(VERTEX_ARRAY|LINE_INDEX_ARRAY);
    ACG::GLState::depthFunc(GL_LEQUAL);

    _state.set_color( _state.specular_color() );

    draw_lines();
    
    //restore depth buffer comparison function for the next draw calls inside this function
    ACG::GLState::depthFunc(prev_depth);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  }


  if (_drawMode & DrawModes::EDGES_COLORED)
  {
    enable_arrays( PER_EDGE_VERTEX_ARRAY | PER_EDGE_COLOR_ARRAY );
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    draw_lines();
  }  

  if (_drawMode & DrawModes::HALFEDGES)
  {
    _state.set_color( _state.specular_color() );

    enable_arrays( PER_HALFEDGE_VERTEX_ARRAY);
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    draw_halfedges();
  }  

  if (_drawMode & DrawModes::HALFEDGES_COLORED)
  {
    enable_arrays( PER_HALFEDGE_VERTEX_ARRAY | PER_HALFEDGE_COLOR_ARRAY );
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    draw_halfedges();
  }  

  if ( ( _drawMode & DrawModes::SOLID_POINTS_COLORED ) && mesh_.has_vertex_colors() )
  {
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->usePerVertexColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
  }

  if ( ( _drawMode & DrawModes::SOLID_POINTS_COLORED_SHADED ) && mesh_.has_vertex_colors() && mesh_.has_vertex_normals() )
  {
    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);
    if ( enableNormals_ ) {
       ACG::GLState::enable(GL_COLOR_MATERIAL);
    } else {
      ACG::GLState::disable(GL_COLOR_MATERIAL);
    }

    drawMesh_->usePerVertexColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
  }

  if ( ( _drawMode & DrawModes::SOLID_FLAT_SHADED ) && mesh_.has_face_normals() && mesh_.n_faces() > 0)
  {
    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->setFlatShading();
    drawMesh_->disableColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
  }
  
  if ( ( _drawMode & DrawModes::SOLID_SMOOTH_SHADED ) && mesh_.has_vertex_normals() )
  {
    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->usePerVertexNormals();
    drawMesh_->setSmoothShading();
    drawMesh_->disableColors();
    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
  }
  
  if ( ( _drawMode & DrawModes::SOLID_PHONG_SHADED ) && mesh_.has_vertex_normals() )
  {
    ///\todo Integrate shader here! 
    //     if ( parent() != 0 ) {
    //       if ( parent()->className() == "ShaderNode" ) {
    //
    //         ShaderNode* node = dynamic_cast< ShaderNode* > ( parent() );
    //
    //         GLSL::PtrProgram program = node->getShader( DrawModes::SOLID_PHONG_SHADED );
    //
    //         // Enable own Phong shader
    //         program->use();
//    enable_arrays(VERTEX_ARRAY | NORMAL_VERTEX_ARRAY );
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->usePerVertexNormals();
    drawMesh_->setSmoothShading();
    drawMesh_->disableColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    //disable own Phong shader
    //         program->disable();
    //       }
    //     }
  }
  
  
  if ( ( _drawMode & DrawModes::SOLID_FACES_COLORED ) && mesh_.has_face_colors()  && mesh_.n_faces() > 0)
  {
    Vec4f base_color_backup = _state.base_color();
    
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);
//    enable_arrays(PER_FACE_VERTEX_ARRAY | PER_FACE_COLOR_ARRAY);    

    drawMesh_->usePerFaceColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    _state.set_base_color(base_color_backup);
  }


  if ( ( _drawMode & DrawModes::SOLID_SMOOTH_SHADED_FEATURES ) && mesh_.has_halfedge_normals()  && mesh_.n_faces() > 0)
  {
    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->disableColors();
    drawMesh_->setSmoothShading();
    drawMesh_->usePerHalfedgeNormals();

    draw_faces();

    ACG::GLState::depthRange(0.0, 1.0);
  }
  
  if ( ( _drawMode & DrawModes::SOLID_FACES_COLORED_FLAT_SHADED ) && mesh_.has_face_colors() && mesh_.has_face_normals()  && mesh_.n_faces() > 0 )
  {
    Vec4f base_color_backup = _state.base_color();
    ACG::GLState::enable(GL_LIGHTING);
    
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);
//    enable_arrays(PER_FACE_VERTEX_ARRAY | PER_FACE_COLOR_ARRAY | PER_FACE_NORMAL_ARRAY );

    drawMesh_->setFlatShading();
    drawMesh_->usePerFaceColors();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    _state.set_base_color(base_color_backup);
  }

  
  if ( ( _drawMode & DrawModes::SOLID_FACES_COLORED_SMOOTH_SHADED ) && mesh_.has_face_colors() && mesh_.has_vertex_normals() && mesh_.n_faces() > 0)
  {
    Vec4f base_color_backup = _state.base_color();

    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->setSmoothShading();
    drawMesh_->usePerVertexNormals();
    drawMesh_->usePerFaceColors();


    drawMesh_->draw(textureMap_, true);
    ACG::GLState::depthRange(0.0, 1.0);

    _state.set_base_color(base_color_backup);
  }

  // Rebind the previous texture
  ACG::GLState::bindTexture(lastTarget,lastBuffer);
  

  if ((_drawMode & DrawModes::SOLID_FACES_COLORED_2DTEXTURED_FACE_SMOOTH_SHADED) && mesh_.has_face_colors() && mesh_.has_vertex_normals() && mesh_.n_faces() > 0)
  {
    // face colors, texturing via halfedge texcoords, smooth shading of lighting color

    Vec4f base_color_backup = _state.base_color();

    ACG::GLState::enable(GL_TEXTURE_2D);

    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->setSmoothShading();
    drawMesh_->usePerVertexNormals();
    drawMesh_->usePerFaceColors();
    drawMesh_->usePerHalfedgeTexcoords();

    drawMesh_->draw(textureMap_, true);
    ACG::GLState::depthRange(0.0, 1.0);

    ACG::GLState::disable(GL_TEXTURE_2D);

    _state.set_base_color(base_color_backup);
  }

  if ( ( _drawMode & DrawModes::SOLID_TEXTURED )  && mesh_.has_vertex_texcoords2D())
  {
    ACG::GLState::enable(GL_TEXTURE_2D);
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->disableColors();
    drawMesh_->usePerVertexTexcoords();


    // texture environment: fragment color = texture sample
    GLint prevTexEnvMode = 0;
    glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &prevTexEnvMode);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    ACG::GLState::disable(GL_TEXTURE_2D);

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, prevTexEnvMode);
  }

  if ((_drawMode & DrawModes::SOLID_ENV_MAPPED) && mesh_.has_vertex_normals())
  {
    ACG::GLState::enable(GL_TEXTURE_2D);
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->disableColors();
    drawMesh_->usePerVertexTexcoords();


    // texture environment: fragment color = texture sample
    GLint prevTexEnvMode = 0;
    glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &prevTexEnvMode);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    ACG::GLState::disable(GL_TEXTURE_2D);

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, prevTexEnvMode);
  }
  
  if ( ( _drawMode & DrawModes::SOLID_TEXTURED_SHADED ) && mesh_.has_vertex_texcoords2D() && mesh_.has_vertex_normals())
  {
//    enable_arrays(VERTEX_ARRAY | NORMAL_VERTEX_ARRAY | TEXCOORD_VERTEX_ARRAY);
    ACG::GLState::enable(GL_TEXTURE_2D);
    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_SMOOTH);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->setSmoothShading();
    drawMesh_->disableColors();
    drawMesh_->usePerVertexTexcoords();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    ACG::GLState::disable(GL_TEXTURE_2D);
  }
  
    
  // Textured by using coordinates stored in halfedges ... arrays generated by stripprocessor
  if ( (_drawMode & DrawModes::SOLID_2DTEXTURED_FACE)  && mesh_.n_faces() > 0 )
  {
    ACG::GLState::enable(GL_TEXTURE_2D);
    
//    enable_arrays( PER_FACE_VERTEX_ARRAY | PER_FACE_TEXCOORD_ARRAY );
    
    ACG::GLState::disable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->disableColors();
    drawMesh_->usePerHalfedgeTexcoords();

    glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    ACG::GLState::disable(GL_TEXTURE_2D);
  }
  

  // Textured by using coordinates stored in halfedges
  if ( ( _drawMode & DrawModes::SOLID_2DTEXTURED_FACE_SHADED ) && mesh_.has_face_normals()  && mesh_.n_faces() > 0)
  {
    ACG::GLState::enable(GL_TEXTURE_2D);

    //    enable_arrays( PER_FACE_VERTEX_ARRAY | PER_FACE_TEXCOORD_ARRAY | PER_FACE_PER_VERTEX_NORMAL_ARRAY );

    ACG::GLState::enable(GL_LIGHTING);
    ACG::GLState::shadeModel(GL_FLAT);
    ACG::GLState::depthRange(0.01, 1.0);

    drawMesh_->setFlatShading();
    drawMesh_->disableColors();
    drawMesh_->usePerHalfedgeTexcoords();

    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    ACG::GLState::disable(GL_TEXTURE_2D);

  }

  enable_arrays(0);
  
  // Unbind all remaining buffers
  ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB , 0 );
  
  if(draw_with_offset_)
  {
    ACG::GLState::depthFunc(prev_depth_offset); 
  }
  
  glPopAttrib();
}


template <class Mesh>
void ACG::SceneGraph::MeshNodeT<Mesh>::getRenderObjects( IRenderer* _renderer, GLState& _state, const DrawModes::DrawMode& _drawMode, const Material* _mat )
{
  RenderObject ro;

  ro.debugName = "MeshNode";
   
  // shader gen setup (lighting, shademode, vertex-colors..)
  
  for (unsigned int i = 0; i < _drawMode.getNumLayers(); ++i)
  {
    const DrawModes::DrawModeProperties* props = _drawMode.getLayer(i);

    // reset renderobject
    ro.initFromState(&_state);
    ro.priority = 0;
    ro.depthRange = Vec2f(0.0f, 1.0f);
    ro.depthTest = true; // some previous node disabled depth testing
    ro.depthWrite = true;
    ro.depthFunc = GL_LESS;
    ro.setMaterial(_mat);


    ro.shaderDesc.vertexTemplateFile.clear(); //QString(props->vertexShader().c_str());
    ro.shaderDesc.geometryTemplateFile.clear(); //QString(props->geometryShader().c_str());
    ro.shaderDesc.fragmentTemplateFile.clear(); //QString(props->fragmentShader().c_str());

    ro.shaderDesc.vertexColorsInterpolator.clear();

    // ------------------------
    // 1. setup drawMesh based on property source


    ro.shaderDesc.vertexColors = true;

    switch (props->colorSource())
    {
    case DrawModes::COLOR_PER_VERTEX: drawMesh_->usePerVertexColors(); break;
    case DrawModes::COLOR_PER_FACE: drawMesh_->usePerFaceColors(); break;
    default:
      {
        drawMesh_->disableColors(); 
        ro.shaderDesc.vertexColors = false;
      } break;
    }

    // only the polygon primitives can set the normal source
    if (props->primitive() == DrawModes::PRIMITIVE_POLYGON)
    {
      switch (props->normalSource())
      {
      case DrawModes::NORMAL_PER_VERTEX: drawMesh_->usePerVertexNormals(); break;
      case DrawModes::NORMAL_PER_HALFEDGE: drawMesh_->usePerHalfedgeNormals(); break;
      default: break;
      }

      if (props->flatShaded())
        drawMesh_->setFlatShading();
      else
        drawMesh_->setSmoothShading();
    }


    ro.shaderDesc.addTextureType(GL_TEXTURE_2D,false,0);

    switch (props->texcoordSource())
    {
    case DrawModes::TEXCOORD_PER_VERTEX: drawMesh_->usePerVertexTexcoords(); break;
    case DrawModes::TEXCOORD_PER_HALFEDGE: drawMesh_->usePerHalfedgeTexcoords(); break;
    default:
      {
        ro.shaderDesc.clearTextures();
      }break;
    }

    // ------------------------
    // 2. prepare renderobject


    // enable / disable lighting
    ro.shaderDesc.numLights = props->lighting() ? 0 : -1;

753
754
755
    // Enable/Disable twoSided Lighting
    ro.shaderDesc.twoSidedLighting = _state.twosided_lighting();

Jan Möbius's avatar
Jan Möbius committed
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    // TODO: better handling of attribute sources in shader gen
    switch (props->lightStage())
    {
      case DrawModes::LIGHTSTAGE_SMOOTH:
        ro.shaderDesc.shadeMode = SG_SHADE_GOURAUD;
        break;
      case DrawModes::LIGHTSTAGE_PHONG:
        ro.shaderDesc.shadeMode = SG_SHADE_PHONG;
        break;
      case DrawModes::LIGHTSTAGE_UNLIT:
        ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;
        break;
    }

    if (props->flatShaded())
      ro.shaderDesc.shadeMode = SG_SHADE_FLAT;

773
774
    if (props->normalSource() == DrawModes::NORMAL_PER_FACE)
      ro.shaderDesc.vertexNormalInterpolator = "flat";
775
776
    else
      ro.shaderDesc.vertexNormalInterpolator.clear();
777

Jan Möbius's avatar
Jan Möbius committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
    // handle 'special' primitives (wireframe, hiddenline, primitives in sysmem buffers)..

    if (props->primitive() == DrawModes::PRIMITIVE_WIREFRAME)
    {
      ro.debugName = "MeshNode.Wireframe";

      ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;
      drawMesh_->disableColors();

      // use specular color for lines
      if (_drawMode.isAtomic() )
        ro.emissive = ro.specular;
      else
        ro.emissive = OpenMesh::color_cast<ACG::Vec3f>(_state.overlay_color());

      // allow wireframe + solid mode
      ro.depthFunc = GL_LEQUAL;
      ro.priority = -1; // render before polygon

      ro.setupLineRendering(_state.line_width(), Vec2f((float)_state.viewport_width(), (float)_state.viewport_height()));

      applyRenderObjectSettings(props->primitive(), &ro);
      add_line_RenderObjects(_renderer, &ro);
    }

    if (props->primitive()  == DrawModes::PRIMITIVE_HIDDENLINE)
    {
      ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;
      drawMesh_->disableColors();

      // use specular color for lines
      if (_drawMode.isAtomic() )
        ro.emissive = ro.specular;
      else
        ro.emissive = OpenMesh::color_cast<ACG::Vec3f>(_state.overlay_color());

      // eventually prepare depthbuffer first
      int polyLayer = _drawMode.getLayerIndexByPrimitive(DrawModes::PRIMITIVE_POLYGON);
      if ( (polyLayer > int(i) || polyLayer < 0) && ( mesh_.n_faces() != 0 ))
      {
        ro.priority = 0;

        applyRenderObjectSettings(DrawModes::PRIMITIVE_POLYGON, &ro);

        // disable color write
        ro.glColorMask(0,0,0,0);

        ro.debugName = "MeshNode.HiddenLine.faces";
        add_face_RenderObjects(_renderer, &ro);
      }


      // draw lines after depth image
      ro.priority = 1;
      ro.glColorMask(1,1,1,1);
      ro.depthFunc = GL_LEQUAL;

      ro.setupLineRendering(_state.line_width(), Vec2f((float)_state.viewport_width(), (float)_state.viewport_height()));

      applyRenderObjectSettings(DrawModes::PRIMITIVE_HIDDENLINE, &ro);

      ro.debugName = "MeshNode.HiddenLine.lines";
      add_line_RenderObjects(_renderer, &ro);
    }

    if (props->colored() && props->primitive()  == DrawModes::PRIMITIVE_EDGE)
    {
      ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;
      ro.shaderDesc.vertexColors = true;

      // note: colored edges are in sysmem, so they are directly bound to the VertexDeclaration
      drawMesh_->updateEdgeHalfedgeVertexDeclarations();
      ro.vertexDecl = drawMesh_->getEdgeColoredVertexDeclaration();
      ro.glDrawArrays(GL_LINES, 0, int(mesh_.n_edges() * 2));

      // use specular color for lines
      ro.emissive = ro.specular;

      // line thickness
      ro.setupLineRendering(_state.line_width(), Vec2f((float)_state.viewport_width(), (float)_state.viewport_height()));

      applyRenderObjectSettings(props->primitive(), &ro);
      ro.debugName = "MeshNode.Edges";
861
      add_line_RenderObjects(_renderer, &ro);
Jan Möbius's avatar
Jan Möbius committed
862
863
864
865
866
867
868
869
870
871
872

       // skip other edge primitives for this drawmode layer
      continue;
    }  

    if (props->primitive()  == DrawModes::PRIMITIVE_HALFEDGE)
    {
      ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;

      // buffers in system memory
      drawMesh_->updateEdgeHalfedgeVertexDeclarations();
873
874
      halfedgeDecl.clear();
      halfedgeDecl.addElement(GL_FLOAT, 3, VERTEX_USAGE_POSITION, (void *)0); 
Jan Möbius's avatar
Jan Möbius committed
875

876
      ro.vertexDecl = &halfedgeDecl;
Jan Möbius's avatar
Jan Möbius committed
877
878
      // use specular color for lines
      ro.emissive = ro.specular;
879
880
      ro.vertexBuffer = drawMesh_->getHEVBO();
      ro.indexBuffer = 0;
Jan Möbius's avatar
Jan Möbius committed
881
882
883
884
885
886
887
888
889
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
      ro.glDrawArrays(GL_LINES, 0, int(mesh_.n_halfedges() * 2));

      ro.debugName = "MeshNode.HalfEdges";
      _renderer->addRenderObject(&ro);
    }  


    // -----------------------------------------------------
    // take care of all the other primitives

    ro.depthRange = Vec2f(0.01f, 1.0f);

    switch (props->primitive())
    {
    case DrawModes::PRIMITIVE_POINT:
      {
        if (ro.shaderDesc.shadeMode == SG_SHADE_UNLIT)
        {
          // use specular color for points
          if (_drawMode.isAtomic() )
            ro.emissive = ro.specular;
          else
            ro.emissive = OpenMesh::color_cast<ACG::Vec3f>(_state.overlay_color());
        }

        // use shaders to simulate point size
        ro.setupPointRendering(_mat->pointSize(), Vec2f((float)_state.viewport_width(), (float)_state.viewport_height()));

        applyRenderObjectSettings(props->primitive(), &ro);
        ro.debugName = "MeshNode.Points";
        add_point_RenderObjects(_renderer, &ro);
      } break;
    case DrawModes::PRIMITIVE_EDGE:
      {
        // use specular color for lines
        ro.emissive = ro.specular;

        // use shaders to simulate line width
        ro.setupLineRendering(_state.line_width(), Vec2f((float)_state.viewport_width(), (float)_state.viewport_height()));

        applyRenderObjectSettings(props->primitive(), &ro);
        ro.debugName = "MeshNode.Edges";
        add_line_RenderObjects(_renderer, &ro);
      } break;
    case DrawModes::PRIMITIVE_POLYGON: 
      {
        applyRenderObjectSettings(props->primitive(), &ro);

        if (!ro.shaderDesc.vertexTemplateFile.isEmpty())
          drawMesh_->scanVertexShaderForInput(ro.shaderDesc.vertexTemplateFile.toStdString());

        bool useNonIndexed = (props->colorSource() == DrawModes::COLOR_PER_FACE) && (props->lightStage() == DrawModes::LIGHTSTAGE_SMOOTH) && !props->flatShaded();
        if (!useNonIndexed && props->colorSource() == DrawModes::COLOR_PER_FACE)
          ro.shaderDesc.vertexColorsInterpolator = "flat";

        ro.debugName = "MeshNode.Faces";
        add_face_RenderObjects(_renderer, &ro, useNonIndexed);

        ro.shaderDesc.vertexColorsInterpolator.clear();
      } break;
    default: break;
    }
  }

}


template<class Mesh>
void
MeshNodeT<Mesh>::
add_point_RenderObjects(IRenderer* _renderer, const RenderObject* _baseObj) {
  drawMesh_->addPointRenderObjects(_renderer, _baseObj);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
draw_vertices() {
  drawMesh_->drawVertices();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
draw_lines() {

  if ((enabled_arrays_ & PER_EDGE_COLOR_ARRAY) && (enabled_arrays_ & PER_EDGE_VERTEX_ARRAY))
  {
    // colored edges still slow
    glDrawArrays(GL_LINES, 0, int(mesh_.n_edges() * 2));
  }
  else
    drawMesh_->drawLines();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
add_line_RenderObjects(IRenderer* _renderer, const RenderObject* _baseObj) {

  if ((enabled_arrays_ & PER_EDGE_COLOR_ARRAY) && (enabled_arrays_ & PER_EDGE_VERTEX_ARRAY))
  {
    // colored edges still slow
    glDrawArrays(GL_LINES, 0, int(mesh_.n_edges() * 2));
  }
  else
    drawMesh_->addLineRenderObjects(_renderer, _baseObj);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
draw_halfedges() {
  // If we are rendering per edge per vertex attributes, we need to use a seperated vertex buffer!
  if ( enabled_arrays_ & PER_HALFEDGE_VERTEX_ARRAY )
    glDrawArrays(GL_LINES, 0, int(mesh_.n_halfedges() * 2));
  // Something went wrong here!
  else
    std::cerr << "Unable to Draw! halfedge array configuration is invalid!!" << std::endl;
}

template<class Mesh>
void
MeshNodeT<Mesh>::
draw_faces() {
  drawMesh_->draw(textureMap_);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
add_face_RenderObjects(IRenderer* _renderer, const RenderObject* _baseObj, bool _nonindexed) {
  drawMesh_->addTriRenderObjects(_renderer, _baseObj, textureMap_, _nonindexed);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
enable_arrays(unsigned int _arrays) {

  // Unbind everything to ensure sane settings
  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
  ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);

  //===================================================================
  // per Edge Vertex Array
  //===================================================================  
  
  // Check if we should enable the per face vertex array
  if (_arrays & PER_EDGE_VERTEX_ARRAY)  {
    
    // Check if its already enabled
    if (!(enabled_arrays_ & PER_EDGE_VERTEX_ARRAY)) {
      enabled_arrays_ |= PER_EDGE_VERTEX_ARRAY;
      
      // For this version we load the colors directly not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
      ACG::GLState::vertexPointer( drawMesh_->perEdgeVertexBuffer() );   
      
      ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
      
    }
  } else if (enabled_arrays_ & PER_EDGE_VERTEX_ARRAY) {
    // Disable Vertex array
    enabled_arrays_ &= ~PER_EDGE_VERTEX_ARRAY;
    ACG::GLState::disableClientState(GL_VERTEX_ARRAY);
  } 
  
  //===================================================================
  // per Edge Color Array
  //===================================================================  
  
  // Check if we should enable the per face vertex array
  if ( mesh_.has_edge_colors()  && ( _arrays & PER_EDGE_COLOR_ARRAY) )  {
    
    // Check if its already enabled
    if (!(enabled_arrays_ & PER_EDGE_COLOR_ARRAY)) {
      enabled_arrays_ |= PER_EDGE_COLOR_ARRAY;
      
      // For this version we load the colors directly not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
      ACG::GLState::colorPointer( drawMesh_->perEdgeColorBuffer() );
      
      ACG::GLState::enableClientState(GL_COLOR_ARRAY);
      
    }
  } else if (enabled_arrays_ & PER_EDGE_COLOR_ARRAY) {
    // Disable Vertex array
    enabled_arrays_ &= ~PER_EDGE_COLOR_ARRAY;
    ACG::GLState::disableClientState(GL_COLOR_ARRAY);
  }   


  //===================================================================
  // per Halfedge Vertex Array
  //===================================================================  
  
  // Check if we should enable the per face vertex array
  if (_arrays & PER_HALFEDGE_VERTEX_ARRAY)  {
    
    // Check if its already enabled
    if (!(enabled_arrays_ & PER_HALFEDGE_VERTEX_ARRAY)) {
      enabled_arrays_ |= PER_HALFEDGE_VERTEX_ARRAY;
      
      // For this version we load the colors directly not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
      ACG::GLState::vertexPointer( drawMesh_->perHalfedgeVertexBuffer() );   
      
      ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
      
    }
  } else if (enabled_arrays_ & PER_HALFEDGE_VERTEX_ARRAY) {
    // Disable Vertex array
    enabled_arrays_ &= ~PER_HALFEDGE_VERTEX_ARRAY;
    ACG::GLState::disableClientState(GL_VERTEX_ARRAY);
  } 
  
  //===================================================================
  // per Halfedge Color Array
  //===================================================================  
  
  // Check if we should enable the per face vertex array
  if ( mesh_.has_halfedge_colors()  && ( _arrays & PER_HALFEDGE_COLOR_ARRAY) )  {
    
    // Check if its already enabled
    if (!(enabled_arrays_ & PER_HALFEDGE_COLOR_ARRAY)) {
      enabled_arrays_ |= PER_HALFEDGE_COLOR_ARRAY;
      
      // For this version we load the colors directly not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
      ACG::GLState::colorPointer( drawMesh_->perHalfedgeColorBuffer() );
      
      ACG::GLState::enableClientState(GL_COLOR_ARRAY);
      
    }
  } else if (enabled_arrays_ & PER_HALFEDGE_COLOR_ARRAY) {
    // Disable Vertex array
    enabled_arrays_ &= ~PER_HALFEDGE_COLOR_ARRAY;
    ACG::GLState::disableClientState(GL_COLOR_ARRAY);
  }   

  //===================================================================
  // Check for OpenGL Errors
  //===================================================================    
  glCheckErrors();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
pick(GLState& _state, PickTarget _target) {

  switch (_target)
  {
    case PICK_VERTEX:
    {
      pick_vertices(_state);
      break;
    }
    case PICK_FRONT_VERTEX:
    {
      pick_vertices(_state, true);
      break;
    }
    
    case PICK_ANYTHING:
    {
      pick_any(_state);
      break;
    }
    case PICK_FACE:
    {
      pick_faces(_state);
      break;
    }
    
    case PICK_EDGE:
    {
      pick_edges(_state);
      break;
    }
    
    case PICK_FRONT_EDGE:
    {
      pick_edges(_state, true);
      break;
    }
    
    default:
      break;
  }

}

template<class Mesh>
void
MeshNodeT<Mesh>::
pick_vertices(GLState& _state, bool _front)
{  
  GLenum prev_depth = _state.depthFunc();
  
  if (!_state.pick_set_maximum (static_cast<unsigned int>(mesh_.n_vertices()))) {
    omerr() << "MeshNode::pick_vertices: color range too small, " << "picking failed\n";
    return;
  }
  
  if ( mesh_.n_vertices() == 0 ) {
    std::cerr << "pick_vertices: No vertices in Mesh!" << std::endl;
    return;
  }
  
  if (_front && ( mesh_.n_faces() != 0 ) ) {
    
    Vec4f  clear_color = _state.clear_color();
    Vec4f  base_color  = _state.base_color();
    clear_color[3] = 1.0;

    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glColor(clear_color);
    
    ACG::GLState::depthRange(0.01, 1.0);
    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    ACG::GLState::depthFunc(GL_LEQUAL);
    glColor(base_color);
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  }

  // picking implementations:
  //  0 -> render mesh with picking color buffer (compatibility mode, add. mem alloc: 16 bytes per openmesh vertex)
  //  1 -> render mesh with picking shader (optimized, add. mem alloc: none for point-clouds, otherwise 4 bytes per openmesh vertex on gpu)
  int pickImplementationMethod = 0;

1217
1218
  // use optimized picking if supported (the function actually checks whether the shader was linked and bound)
  // which shader should be used only depends on the available OpenGL version
Jan Möbius's avatar
Jan Möbius committed
1219
  if (drawMesh_->supportsPickingVertices_opt())
1220
    pickImplementationMethod = openGLVersionTest(3,2) ? 1 : 0;
Jan Möbius's avatar
Jan Möbius committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322

  if (_state.color_picking () ) {
    
    if ( updateVertexPicking_ || _state.pick_current_index () != vertexPickingBaseIndex_) {
      if (pickImplementationMethod == 0)
        drawMesh_->updatePickingVertices(_state);
      else
        drawMesh_->updatePickingVertices_opt(_state);
      vertexPickingBaseIndex_ = _state.pick_current_index ();
      updateVertexPicking_    = false;
    }

    if (mesh_.n_vertices()) {
      
      if (pickImplementationMethod == 0) {
        // For this version we load the colors directly not from vbo
        ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
        ACG::GLState::colorPointer( drawMesh_->pickVertexColorBuffer() );   
        ACG::GLState::enableClientState(GL_COLOR_ARRAY);    

        // vertex positions
        ACG::GLState::vertexPointer( drawMesh_->pickVertexBuffer() );
        ACG::GLState::enableClientState(GL_VERTEX_ARRAY);

        // Draw color picking
        glDrawArrays(GL_POINTS, 0, int(mesh_.n_vertices()));

        // Disable color array
        ACG::GLState::disableClientState(GL_COLOR_ARRAY);

        // disable vertex array
        ACG::GLState::disableClientState(GL_VERTEX_ARRAY);
      }
      else if (pickImplementationMethod == 1){

        // optimized rendering of picking ids with shaders
        drawMesh_->drawPickingVertices_opt(_state.projection() * _state.modelview(), vertexPickingBaseIndex_);

      }
      
      
    } else {
     std::cerr << "pick_vertices: No vertices in Mesh!" << std::endl; 
    }
    
  } else {
    std::cerr << "No fallback pick_vertices!" << std::endl;
  }
  
  ACG::GLState::depthFunc(prev_depth);
  
}

template<class Mesh>
void
MeshNodeT<Mesh>::
pick_edges(GLState& _state, bool _front)
{  
  GLenum prev_depth = _state.depthFunc();
  
  if (!_state.pick_set_maximum (static_cast<unsigned int>(mesh_.n_edges()))) {
    omerr() << "MeshNode::pick_edges: color range too small, " << "picking failed\n";
    return;
  }
  
  if ( mesh_.n_vertices() == 0 ) {
    std::cerr << "pick_edges: No vertices in Mesh!" << std::endl;
    return;
  }
  
  if ( _front && ( mesh_.n_faces() != 0 ) ) {
    
    Vec4f  clear_color = _state.clear_color();
    Vec4f  base_color  = _state.base_color();
    clear_color[3] = 1.0;
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glColor(clear_color);
    
    ACG::GLState::depthRange(0.01, 1.0);
    draw_faces();
    ACG::GLState::depthRange(0.0, 1.0);
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    ACG::GLState::depthFunc(GL_LEQUAL);
    glColor(base_color);
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    
    // disable all other arrays
    enable_arrays(0);
  }
  
  if (_state.color_picking () && drawMesh_ ) {

    // picking implementations:
    //  0 -> render mesh with picking color buffer (compatibility mode, add. mem alloc: 32 bytes per openmesh edge)
    //  1 -> render mesh with picking shader (add. mem alloc: none)
    int pickImplementationMethod = 0;

    // use optimized picking if supported
    if (drawMesh_->supportsPickingEdges_opt())
1323
      pickImplementationMethod = openGLVersionTest(3,2) ? 1 : 0;
Jan Möbius's avatar
Jan Möbius committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
    
    if ( updateEdgePicking_ || _state.pick_current_index () != edgePickingBaseIndex_) {
      if (pickImplementationMethod == 0)
        drawMesh_->updatePickingEdges(_state);
      else
        drawMesh_->updatePickingEdges_opt(_state);
      edgePickingBaseIndex_ = _state.pick_current_index ();
      updateEdgePicking_    = false;
    }
    
    if ( mesh_.n_edges() != 0 && drawMesh_) {
      
      if (pickImplementationMethod == 0){
        // For this version we load the colors directly not from vbo
        ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);

        ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
        ACG::GLState::enableClientState(GL_COLOR_ARRAY);

        ACG::GLState::vertexPointer(drawMesh_->perEdgeVertexBuffer());
        ACG::GLState::colorPointer(drawMesh_->pickEdgeColorBuffer());

        glDrawArrays(GL_LINES, 0, int(mesh_.n_edges() * 2));

        ACG::GLState::disableClientState(GL_COLOR_ARRAY);
        ACG::GLState::disableClientState(GL_VERTEX_ARRAY);

        // disable all other arrays
        enable_arrays(0); 
      }
      else if (pickImplementationMethod == 1){
        // optimized rendering of edge ids
        drawMesh_->drawPickingEdges_opt(_state.projection() * _state.modelview(), edgePickingBaseIndex_);
      }

      
    }
    
  } else {
    std::cerr << "No fallback pick_edges!" << std::endl;
  }
  
  ACG::GLState::depthFunc(prev_depth);
  
}

template<class Mesh>
void
MeshNodeT<Mesh>::
pick_faces(GLState& _state)
{
  
  if ( mesh_.n_vertices() == 0 ) {
    std::cerr << "pick_faces: No vertices in Mesh!" << std::endl;
    return;
  }
  
  if ( mesh_.n_faces() > 0 ) {
    if (!_state.pick_set_maximum (static_cast<unsigned int>(mesh_.n_faces()))) {
      omerr() << "MeshNode::pick_faces: color range too small, " << "picking failed\n";
      return;
    }
  } else {
    if (!_state.pick_set_maximum (1)) {
      omerr() << "Strange pickSetMAximum failed for index 1 in MeshNode\n";
      return;
    }
  }

  // picking implementations:
  //  0 -> render mesh with picking color buffer (compatibility mode, add. mem alloc: 48 bytes per triangle)
  //  1 -> render mesh with picking shader (optimized, add. mem alloc: 4 bytes per triangle on gpu)
  int pickImplementationMethod = 0;

  
  // use optimized picking if supported
  if (drawMesh_->supportsPickingFaces_opt())
1401
    pickImplementationMethod = openGLVersionTest(3,2) ? 1 : 0;
Jan Möbius's avatar
Jan Möbius committed
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495

//  pickImplementationMethod = 0;

  if (_state.color_picking ()) {

    if (pickImplementationMethod == 0) {
      // compatibility mode (unoptimized)

      if ( updateFacePicking_ || _state.pick_current_index () != facePickingBaseIndex_) {
        drawMesh_->updatePickingFaces(_state);
        facePickingBaseIndex_ = _state.pick_current_index ();
        updateFacePicking_    = false;
      }

      if ( mesh_.n_faces() != 0 ) {

        // For this version we load the colors directly not from vbo
        ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);

        ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
        ACG::GLState::enableClientState(GL_COLOR_ARRAY);

        ACG::GLState::vertexPointer(drawMesh_->pickFaceVertexBuffer());
        ACG::GLState::colorPointer(drawMesh_->pickFaceColorBuffer());

        glDrawArrays(GL_TRIANGLES, 0, int(3 * drawMesh_->getNumTris()));

        ACG::GLState::disableClientState(GL_COLOR_ARRAY);
        ACG::GLState::disableClientState(GL_VERTEX_ARRAY);

        // disable all other arrays
        enable_arrays(0);

      }

    }
    else if (pickImplementationMethod == 1) {
      
      //  render mesh with face picking shader (optimized)

      if ( updateFacePicking_ || _state.pick_current_index () != facePickingBaseIndex_) {
        drawMesh_->updatePickingFaces_opt(_state);
        facePickingBaseIndex_ = _state.pick_current_index ();
        updateFacePicking_    = false;
      }

      if ( mesh_.n_faces() != 0 ) {

        drawMesh_->drawPickingFaces_opt(_state.projection() * _state.modelview(), facePickingBaseIndex_);

        /* debug:  print color id of first face
        Vec4uc facePickingOffsetColor = _state.pick_get_name_color(0);
        
        std::cout << "base_color: " << int(facePickingOffsetColor[0]) << " " <<
          int(facePickingOffsetColor[1]) << " " <<
          int(facePickingOffsetColor[2]) << " " <<
          int(facePickingOffsetColor[3]) << " " << std::endl;
                Vec4uc facePickingOffsetColor = _state.pick_get_name_color(0);
        */
      }
    }
    else
      std::cerr << "Unknown picking method in pick_faces!" << std::endl;
    
    
  } else
    std::cerr << "No fallback pick_faces!" << std::endl;
  
}

template<class Mesh>
void
MeshNodeT<Mesh>::
pick_any(GLState& _state)
{    
  GLenum prev_depth = _state.depthFunc();
  size_t numElements = mesh_.n_faces() + mesh_.n_edges() + mesh_.n_vertices();
  
  if ( mesh_.n_vertices() == 0 ) {
    std::cerr << "pick_any: No vertices in Mesh!" << std::endl;
    return;
  }
  
  // nothing to pick ?
  if (numElements == 0) {
    std::cerr << "pick_any: Number of elements : 0 " << std::endl;
    return;
  }
  
  if (!_state.pick_set_maximum (static_cast<unsigned int>(numElements)))
  {
    omerr() << "MeshNode::pick_any: color range too small, " << "picking failed\n";
    return;
  }
1496

Jan Möbius's avatar
Jan Möbius committed
1497
1498
1499
1500
1501
1502
1503
1504
1505
  if (_state.color_picking() && drawMesh_) {

    // picking implementations:
    //  0 -> render mesh with picking color buffer (compatibility mode, add. mem alloc: 48 bytes per triangle + 32 bytes per edge + 16 bytes per vertex)
    //  1 -> render mesh with picking shader (optimized, add. mem alloc: none [ shared memory with optimized vertex,edge,face picking ])
    int pickImplementationMethod = 0;

    // use optimized picking if supported
    if (drawMesh_->supportsPickingAny_opt())
1506
      pickImplementationMethod = openGLVersionTest(3,2) ? 1 : 0;
Jan Möbius's avatar
Jan Möbius committed
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516


    if ( updateAnyPicking_ || _state.pick_current_index () != anyPickingBaseIndex_) {
      if (pickImplementationMethod == 0)
        drawMesh_->updatePickingAny(_state);
      else
        drawMesh_->updatePickingAny_opt(_state);
      anyPickingBaseIndex_ = _state.pick_current_index ();
      updateAnyPicking_    = false;
    }
1517

Jan Möbius's avatar
Jan Möbius committed
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
    if (pickImplementationMethod == 0){
      // For this version we load the colors directly, not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);

      ACG::GLState::disableClientState(GL_NORMAL_ARRAY);
      ACG::GLState::disableClientState(GL_TEXTURE_COORD_ARRAY);

      ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
      ACG::GLState::enableClientState(GL_COLOR_ARRAY);

      // If we do not have any faces, we generate an empty list here.  
      if ( mesh_.n_faces() != 0 && drawMesh_) {

        ACG::GLState::vertexPointer(drawMesh_->pickFaceVertexBuffer());
        ACG::GLState::colorPointer(drawMesh_->pickAnyFaceColorBuffer());

        glDrawArrays(GL_TRIANGLES, 0, int(3 * drawMesh_->getNumTris()));
      }

      ACG::GLState::depthFunc(GL_LEQUAL);

      // If we do not have any edges, we generate an empty list here.  
      if ( mesh_.n_edges() != 0 && drawMesh_) {

        ACG::GLState::vertexPointer(drawMesh_->perEdgeVertexBuffer());
        ACG::GLState::colorPointer(drawMesh_->pickAnyEdgeColorBuffer());

        glDrawArrays(GL_LINES, 0, int(mesh_.n_edges() * 2));
      }

      // For this version we load the colors directly not from vbo
      ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
      ACG::GLState::vertexPointer( drawMesh_->pickVertexBuffer() );
      ACG::GLState::colorPointer(drawMesh_->pickAnyVertexColorBuffer());

      // Draw color picking
      glDrawArrays(GL_POINTS, 0, int(mesh_.n_vertices()));

      ACG::GLState::disableClientState(GL_COLOR_ARRAY);
      ACG::GLState::disableClientState(GL_VERTEX_ARRAY);

      // disable all other arrays
      enable_arrays(0);
    } else {
      // optimized version of any picking with shaders
      drawMesh_->drawPickingAny_opt(_state.projection() * _state.modelview(), anyPickingBaseIndex_);
    }
    
  } else
    std::cerr << "No fallback pick_any!" << std::endl;

  //restore depth buffer comparison function for the active display list
  ACG::GLState::depthFunc(prev_depth);
  
  glCheckErrors();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
update_geometry() {
  /// \todo check the following statements. If only geometry changed, the normals,vertices have to be updated nothing else!
  /*
  updateFaceList_ = true;
  updateAnyList_ = true;
  */
  
  updateVertexPicking_ = true;
  updateEdgePicking_   = true;
  updateFacePicking_   = true;
  updateAnyPicking_    = true;
  
  // Set per edge arrays to invalid as they have to be regenerated
  drawMesh_->invalidatePerEdgeBuffers();

  // Set per halfedge arrays to invalid as they have to be regenerated
  drawMesh_->invalidatePerHalfedgeBuffers();
  
  drawMesh_->updateGeometry();

  drawMesh_->invalidateFullVBO();

  // First of all, we update the bounding box:
  bbMin_ = Vec3d(FLT_MAX,  FLT_MAX,  FLT_MAX);
  bbMax_ = Vec3d(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  typename Mesh::ConstVertexIter  v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end());
  
  for (; v_it!=v_end; ++v_it)
  {
    bbMin_.minimize(mesh_.point(*v_it));
    bbMax_.maximize(mesh_.point(*v_it));
  }
}

template<class Mesh>
void
MeshNodeT<Mesh>::
update_topology() {

  drawMesh_->invalidatePerEdgeBuffers();
  drawMesh_->invalidatePerHalfedgeBuffers();


  drawMesh_->updateTopology();

  // Unbind the buffer after the work has been done
  ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}

template<class Mesh>
void
MeshNodeT<Mesh>::
update_textures() {
  drawMesh_->updateTextures();

  updateVertexPicking_ = true;
  updateFacePicking_ = true;
  updateAnyPicking_ = true;
}



template<class Mesh>
void
MeshNodeT<Mesh>::
update_color() {
  
  drawMesh_->invalidatePerEdgeBuffers();
  drawMesh_->invalidatePerHalfedgeBuffers();
  
  // TODO: optimize update strategy:
  // if only vertex colors have changed, then call UpdateGeometry() (faster)
  // for face colors we have to use UpdateFull()
  drawMesh_->updateFull();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
setIndexPropertyName( std::string _indexPropertyName ) { 

  drawMesh_->setTextureIndexPropertyName(_indexPropertyName);
  perFaceTextureIndexAvailable_ =  drawMesh_->perFaceTextureIndexAvailable() != 0;
}

template<class Mesh>
const std::string&
MeshNodeT<Mesh>::
indexPropertyName() const {

  return drawMesh_->getTextureIndexPropertyName();
}

template<class Mesh>
void
MeshNodeT<Mesh>::
setHalfedgeTextcoordPropertyName( std::string _halfedgeTextcoordPropertyName ){ 
  drawMesh_->setPerFaceTextureCoordinatePropertyName(_halfedgeTextcoordPropertyName);
}




template<class Mesh>
unsigned int
MeshNodeT<Mesh>::getMemoryUsage()
{
  unsigned int res = 0;

  if (drawMesh_)
    res += drawMesh_->getMemoryUsage();

  return res;
}


template<class Mesh>
DrawMeshT<Mesh>*
MeshNodeT<Mesh>::getDrawMesh()
{
  return drawMesh_;
}




//=============================================================================
} // namespace SceneGraph
} // namespace ACG
//=============================================================================