VertexDeclaration.cc 17.4 KB
Newer Older
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
Jan Möbius's avatar
Jan Möbius committed
4
5
6
7
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
8
9
 *                                                                           *
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
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
 * 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.              *
39
40
41
42
43
44
45
46
47
48
49
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                       *
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

50
#include <ACG/GL/acg_glew.hh>
51
52
53
54
#include <ACG/GL/gl.hh>
#include <ACG/GL/GLState.hh>
#include <ACG/ShaderUtils/GLSLShader.hh>

Christopher Tenter's avatar
Christopher Tenter committed
55
#include <QTextStream>
56
57
58
59
60
61
62

#include "VertexDeclaration.hh"


namespace ACG
{

63
64
65
66
67
VertexElement::VertexElement()
  : type_(0), numElements_(0), usage_(VERTEX_USAGE_SHADER_INPUT), shaderInputName_(0), pointer_(0), divisor_(0), vbo_(0)
{
}

68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
void VertexElement::setByteOffset(unsigned int _offset)
{
  // union cast instead of reinterpret_cast for cross-platform compatibility
  union ptr2uint
  {
    unsigned long u;
    const void* p;
  } offset;

  offset.u = static_cast<unsigned long>(_offset);

  pointer_ = offset.p;
}

83
84
85
86
87
88
89
90
91
92
93
94
95
96
unsigned int VertexElement::getByteOffset() const
{
  // union cast instead of reinterpret_cast for cross-platform compatibility
  union ptr2uint
  {
    unsigned long u;
    const void* p;
  } offset;

  offset.p = pointer_;

  return static_cast<unsigned int>(offset.u);
}

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
VertexDeclaration::VertexDeclaration()
: vertexStride_(0), strideUserDefined_(0)
{

}


VertexDeclaration::~VertexDeclaration()
{

}


void VertexDeclaration::addElement(const VertexElement* _pElement)
{
  addElements(1, _pElement);
}

void VertexDeclaration::addElement(unsigned int _type,
                                   unsigned int _numElements,
                                   VERTEX_USAGE _usage,
118
                                   const void* _pointer,
119
120
121
                                   const char* _shaderInputName,
                                   unsigned int _divisor,
                                   unsigned int _vbo)
122
{
Jan Möbius's avatar
Jan Möbius committed
123
124
125
126
127
128
  VertexElement* ve = new VertexElement();

  ve->type_ = _type;
  ve->numElements_ = _numElements;
  ve->usage_ = _usage;
  ve->shaderInputName_ = _shaderInputName;
129
  ve->pointer_ = _pointer;
130
131
  ve->divisor_ = _divisor;
  ve->vbo_ = _vbo;
132
133
134
135
136
137
138
139
  addElement(ve);

  delete ve;
}

void VertexDeclaration::addElement(unsigned int _type,
                                   unsigned int _numElements,
                                   VERTEX_USAGE _usage, 
Christopher Tenter's avatar
Christopher Tenter committed
140
                                   size_t _byteOffset,
141
142
143
                                   const char* _shaderInputName,
                                   unsigned int _divisor,
                                   unsigned int _vbo)
144
145
146
147
148
149
150
{
  VertexElement* ve = new VertexElement();

  ve->type_ = _type;
  ve->numElements_ = _numElements;
  ve->usage_ = _usage;
  ve->shaderInputName_ = _shaderInputName;
Christopher Tenter's avatar
Christopher Tenter committed
151
  ve->pointer_ = (void*)_byteOffset;
152
153
  ve->divisor_ = _divisor;
  ve->vbo_ = _vbo;
154

Jan Möbius's avatar
Jan Möbius committed
155
156
157
  addElement(ve);

  delete ve;
158
159
160
161
162
163
164
165
166
167
168
169
170
171
}


void VertexDeclaration::addElements(unsigned int _numElements, const VertexElement* _pElements)
{
  elements_.reserve(elements_.size() + _numElements);

  for (unsigned int i = 0; i < _numElements; ++i)
  {
    VertexElement tmp = _pElements[i];
    updateShaderInputName(&tmp);
    elements_.push_back(tmp);
  }

Christopher Tenter's avatar
Christopher Tenter committed
172
173
  updateOffsets();

174
  if (!strideUserDefined_)
Christopher Tenter's avatar
Christopher Tenter committed
175
176
177
178
179
180
181
  {
    // recompute vertex stride from declaration (based on last element)

    unsigned int n = getNumElements();

    if (n)
    {
182
183
184
185
186
187
188
189
190
      // stride = offset of last element + sizeof last element - offset of first element

      // union instead of reinterpret_cast for cross-platform compatibility
      union ptr2uint
      {
        unsigned long u;
        const void* p;
      } lastOffset, firstOffset;

Christopher Tenter's avatar
Christopher Tenter committed
191

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

      std::map<unsigned int, VertexElement*> vboFirstElements;
      std::map<unsigned int, VertexElement*> vboLastElements;

      for (unsigned int i = 0; i < n; ++i)
      {
        if (vboFirstElements.find(elements_[i].vbo_) == vboFirstElements.end())
          vboFirstElements[elements_[i].vbo_] = &elements_[i];

        vboLastElements[elements_[i].vbo_] = &elements_[i];
      }


      for (std::map<unsigned int, VertexElement*>::iterator it = vboFirstElements.begin(); it != vboFirstElements.end(); ++it)
      {
        VertexElement* lastElement = vboLastElements[it->first];
        firstOffset.p = it->second->pointer_;
        lastOffset.p = lastElement->pointer_;

        vertexStridesVBO_[it->first] = static_cast<unsigned int>(lastOffset.u + getElementSize( lastElement ) - firstOffset.u);
      }

      vertexStride_ = vertexStridesVBO_.begin()->second;
Christopher Tenter's avatar
Christopher Tenter committed
215
216
    }
  }
217
218
219
220

}


221
222
223
224
225
226
// union instead of reinterpret_cast for cross-platform compatibility, must be global for use in std::map
union VertexDeclaration_ptr2uint
{
  unsigned long u;
  const void* p;
};
227
228
229
230
231
232
233

void VertexDeclaration::updateOffsets()
{
  unsigned int numElements = getNumElements();

  if (!numElements) return;

234

235
236
237
238
  // separate offsets for each vbo

  std::map<unsigned int, VertexDeclaration_ptr2uint> vboOffsets;
  std::map<unsigned int, VertexElement*> vboPrevElements;
239

240
241
242
243
244
245
246
247
  for (unsigned int i = 0; i < numElements; ++i)
  {
    if (vboOffsets.find(elements_[i].vbo_) == vboOffsets.end())
    {
      vboOffsets[elements_[i].vbo_].p = elements_[i].pointer_;
      vboPrevElements[elements_[i].vbo_] = &elements_[i];
    }
  }
248

249
  for (unsigned int i = 0; i < numElements; ++i)
250
  {
251
    VertexElement* el = &elements_[i];
252

253
254
255
256
257
258
259
    bool updateOffset = false;

    if (el->pointer_)
    {
      vboOffsets[el->vbo_].p = el->pointer_;
      vboPrevElements[el->vbo_] = el;
    }
260
    else
261
262
263
264
265
266
267
268
269
    {
      VertexElement* prevEl = vboPrevElements[el->vbo_];
      if (prevEl != el)
      {
        updateOffset = true;
        vboOffsets[el->vbo_].u += getElementSize(prevEl);
      }
      vboPrevElements[el->vbo_] = el;
    }
270

271
272
    if (updateOffset)
      el->pointer_ = vboOffsets[el->vbo_].p;
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
  }
}


void VertexDeclaration::updateShaderInputName(VertexElement* _pElem)
{
  if (!_pElem->shaderInputName_)
  {
    assert(_pElem->usage_ != VERTEX_USAGE_SHADER_INPUT);

    const char* sz = "";

    switch (_pElem->usage_)
    {
    case VERTEX_USAGE_POSITION:     sz = "inPosition"; break;
    case VERTEX_USAGE_NORMAL:       sz = "inNormal"; break;
    case VERTEX_USAGE_TEXCOORD:     sz = "inTexCoord"; break;
    case VERTEX_USAGE_COLOR:        sz = "inColor"; break;
    case VERTEX_USAGE_BLENDWEIGHTS: sz = "inBlendWeights"; break;
    case VERTEX_USAGE_BLENDINDICES: sz = "inBlendIndices"; break;

    default:
      std::cerr << "VertexDeclaration::updateShaderInputName - unknown vertex usage - " << _pElem->usage_ << std::endl;
Jan Möbius's avatar
Jan Möbius committed
296
      break;
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
    }

    _pElem->shaderInputName_ = sz;
  }
}


unsigned int VertexDeclaration::getNumElements() const
{
  return elements_.size();
}


unsigned int VertexDeclaration::getGLTypeSize(unsigned int _type)
{
  unsigned int size = 0;

  switch (_type)
  {
  case GL_DOUBLE:
    size = 8; break;

  case GL_FLOAT:
  case GL_UNSIGNED_INT:
  case GL_INT:
    size = 4; break;

//  case GL_HALF_FLOAT_ARB:
  case 0x140B: // = GL_HALF_FLOAT_ARB
  case GL_SHORT:
  case GL_UNSIGNED_SHORT:
    size = 2; break;

  case GL_BYTE:
  case GL_UNSIGNED_BYTE:
    size = 1; break;

  default:
    std::cerr << "VertexDeclaration::getElementSize - unknown type - " << _type << std::endl;
Jan Möbius's avatar
Jan Möbius committed
336
    break;
337
338
339
340
341
342
343
344
345
  }

  return size;
}



unsigned int VertexDeclaration::getElementSize(const VertexElement* _pElement)
{
346
  return _pElement ? getGLTypeSize(_pElement->type_) * _pElement->numElements_ : 0;
347
348
349
350
351
352
353
354
355
}








356
void VertexDeclaration::activateFixedFunction() const
357
358
359
360
361
362
363
364
365
366
367
368
{
  unsigned int numElements = getNumElements();
  unsigned int vertexStride = getVertexStride();

  for (unsigned int i = 0; i < numElements; ++i)
  {
    const VertexElement* pElem = getElement(i);

    switch (pElem->usage_)
    {
    case VERTEX_USAGE_POSITION:
      {
369
        ACG::GLState::vertexPointer(pElem->numElements_, pElem->type_, vertexStride, pElem->pointer_);
370
371
372
373
374
        ACG::GLState::enableClientState(GL_VERTEX_ARRAY);
      } break;

    case VERTEX_USAGE_COLOR:
      {
375
        ACG::GLState::colorPointer(pElem->numElements_, pElem->type_, vertexStride, pElem->pointer_);
376
377
378
379
380
381
        ACG::GLState::enableClientState(GL_COLOR_ARRAY);
      } break;

    case VERTEX_USAGE_TEXCOORD:
      {
        glClientActiveTexture(GL_TEXTURE0);
382
        ACG::GLState::texcoordPointer(pElem->numElements_, pElem->type_, vertexStride, pElem->pointer_);
383
384
385
386
387
388
389
        ACG::GLState::enableClientState(GL_TEXTURE_COORD_ARRAY);
      } break;

    case VERTEX_USAGE_NORMAL:
      {
        assert(pElem->numElements_ == 3);

390
        ACG::GLState::normalPointer(pElem->type_, vertexStride, pElem->pointer_);
391
392
        ACG::GLState::enableClientState(GL_NORMAL_ARRAY);
      } break;
393
394

    default: break;
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
void VertexDeclaration::deactivateFixedFunction() const
{
  unsigned int numElements = getNumElements();

  for (unsigned int i = 0; i < numElements; ++i)
  {
    const VertexElement* pElem = getElement(i);

    switch (pElem->usage_)
    {
    case VERTEX_USAGE_POSITION: ACG::GLState::disableClientState(GL_VERTEX_ARRAY); break;
    case VERTEX_USAGE_COLOR: ACG::GLState::disableClientState(GL_COLOR_ARRAY); break;
    case VERTEX_USAGE_TEXCOORD: ACG::GLState::disableClientState(GL_TEXTURE_COORD_ARRAY); break;
    case VERTEX_USAGE_NORMAL: ACG::GLState::disableClientState(GL_NORMAL_ARRAY); break;

    default: break;
    }
  }
}


423

Christopher Tenter's avatar
Christopher Tenter committed
424
void VertexDeclaration::activateShaderPipeline(GLSL::Program* _prog) const
425
{
Jan Möbius's avatar
Jan Möbius committed
426
427
  assert(_prog);

428
429
430
431
  // setup correct attribute locations as specified

  unsigned int numElements = getNumElements();

Jan Möbius's avatar
Jan Möbius committed
432
  for (unsigned int i = 0; i < numElements; ++i)
433
  {
434
435
    unsigned int vertexStride = getVertexStride(i);

436
437
438
439
440
441
442
443
444
445
446
447
448
    const VertexElement* pElem = &elements_[i];

    int loc = _prog->getAttributeLocation(pElem->shaderInputName_);

    if (loc != -1)
    {
      // default: map integers to [-1, 1] or [0, 1] range
      // exception: blend indices for gpu skinning eventually
      GLboolean normalizeElem = GL_TRUE;

      if (pElem->usage_ == VERTEX_USAGE_BLENDINDICES)
        normalizeElem = GL_FALSE;

449
450
451
452
453
454
455
      GLint curVBO = 0;
      if (pElem->vbo_)
      {
        glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &curVBO);
        glBindBuffer(GL_ARRAY_BUFFER, pElem->vbo_);
      }

456
      glVertexAttribPointer(loc, pElem->numElements_,  pElem->type_, normalizeElem, vertexStride, pElem->pointer_);
457
458
459
460
461
462
463
464
465
466

      if (supportsInstancedArrays())
      {
#ifdef GL_ARB_instanced_arrays
        glVertexAttribDivisor(loc, pElem->divisor_);
#endif
      }
      else if (pElem->divisor_)
        std::cerr << "error: VertexDeclaration::activateShaderPipeline - instanced arrays not supported by gpu!" << std::endl;

467
468
      glEnableVertexAttribArray(loc);

469
470
      if (curVBO)
        glBindBuffer(GL_ARRAY_BUFFER, curVBO);
471
472
473
474
475
476
477
    }
  }
}


void VertexDeclaration::deactivateShaderPipeline( GLSL::Program* _prog ) const
{
Jan Möbius's avatar
Jan Möbius committed
478
479
  assert(_prog);

480
481
482
483
484
485
486
487
488
  unsigned int numElements = getNumElements();

  for (unsigned int i = 0; i < numElements; ++i)
  {
    const VertexElement* pElem = &elements_[i];

    int loc = _prog->getAttributeLocation(pElem->shaderInputName_);

    if (loc != -1)
489
    {
490
491
      glDisableVertexAttribArray(loc);

492
493
494
495
496
497
498
      if (supportsInstancedArrays() && pElem->divisor_)
      {
#ifdef GL_ARB_instanced_arrays
        glVertexAttribDivisor(loc, 0);
#endif
      }
    }
499
500
501
502
503
  }
}



Christopher Tenter's avatar
Christopher Tenter committed
504
const VertexElement* VertexDeclaration::getElement(unsigned int i) const
505
506
507
508
509
{
  return &elements_[i];
}


510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
int VertexDeclaration::findElementIdByUsage(VERTEX_USAGE _usage) const
{
  for (size_t i = 0; i < elements_.size(); ++i)
    if (elements_[i].usage_ == _usage)
      return int(i);
  
  return -1;
}

const VertexElement* VertexDeclaration::findElementByUsage(VERTEX_USAGE _usage) const
{
  int eid = findElementIdByUsage(_usage);

  if (eid >= 0)
    return getElement((unsigned int)eid);

  return 0;
}


530
unsigned int VertexDeclaration::getVertexStride(unsigned int i) const
531
{
532
533
534
  if (strideUserDefined_)
    return vertexStride_;

535
536
537
538
539
  unsigned int vbo = getElement(i)->vbo_;
  std::map<unsigned int, unsigned int>::const_iterator it = vertexStridesVBO_.find(vbo);

  return (it != vertexStridesVBO_.end()) ? it->second : vertexStride_;
//  return vertexStride_;
540
541
542
543
544
545
546
547
548
}


void VertexDeclaration::setVertexStride(unsigned int _stride)
{
  strideUserDefined_ = 1;
  vertexStride_ = _stride;
}

549
550
551
552
553
554
void VertexDeclaration::clear()
{
  strideUserDefined_ = 0;
  vertexStride_ = 0;

  elements_.clear();
555
  vertexStridesVBO_.clear();
556
557
}

Christopher Tenter's avatar
Christopher Tenter committed
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

QString VertexDeclaration::toString() const
{
  // maps VERTEX_USAGE -> string
  const char* usageStrings[] = 
  {
    "POSITION",
    "NORMAL",
    "TEXCOORD",
    "COLOR",
    "BLENDWEIGHTS",
    "BLENDINDICES"
  };

  QString result;

  QTextStream resultStrm(&result);
  resultStrm << "stride = " << getVertexStride() << "\n";


  for (unsigned int i = 0; i < getNumElements(); ++i)
  {
    const VertexElement* el = getElement(i);

    // convert element-type GLEnum to string
    const char* typeString = "";

    switch (el->type_)
    {
    case GL_FLOAT: typeString = "GL_FLOAT"; break;
    case GL_DOUBLE: typeString = "GL_DOUBLE"; break;

    case GL_INT: typeString = "GL_INT"; break;
    case GL_UNSIGNED_INT: typeString = "GL_UNSIGNED_INT"; break;

    case GL_SHORT: typeString = "GL_SHORT"; break;
    case GL_UNSIGNED_SHORT: typeString = "GL_UNSIGNED_SHORT"; break;

    case GL_BYTE: typeString = "GL_BYTE"; break;
    case GL_UNSIGNED_BYTE: typeString = "GL_UNSIGNED_BYTE"; break;
    default: typeString = "unknown"; break;
    }

    // get usage in string form
    const char* usage = (el->usage_ < VERTEX_USAGE_SHADER_INPUT) ? usageStrings[el->usage_] : el->shaderInputName_;

    resultStrm << "element " << i
605
               << " - [type: " << typeString
Christopher Tenter's avatar
Christopher Tenter committed
606
607
               << ", count: " << el->numElements_
               << ", usage: " << usage
608
               << ", shader-input: " << el->shaderInputName_
609
610
611
612
613
               << ", offset: " << el->pointer_ 
               << ", divisor: " << el->divisor_ 
               << ", vbo: " << el->vbo_
               << ", stride: " << getVertexStride(i)
               << "]\n";
Christopher Tenter's avatar
Christopher Tenter committed
614
615
616
617
618
  }

  return result;
}

619
620
621
622
623
624
625
626
627
628
629
630
bool VertexDeclaration::supportsInstancedArrays()
{
  static int status_ = -1;

#ifdef GL_ARB_instanced_arrays
  if (status_ < 0) // core in 3.3
    status_ = (checkExtensionSupported("GL_ARB_instanced_arrays") || openGLVersion(3,3)) ? 1 : 0;
#endif

  return status_ > 0;
}

631
632
633
//=============================================================================
} // namespace ACG
//=============================================================================