fc31b70f61ad817f9eb788bdecbe173bcc103751
[occt.git] / src / OpenGl / OpenGl_PrimitiveArray.cxx
1 // Created on: 2011-07-13
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_AspectFace.hxx>
17 #include <OpenGl_Context.hxx>
18 #include <OpenGl_GraphicDriver.hxx>
19 #include <OpenGl_IndexBuffer.hxx>
20 #include <OpenGl_PointSprite.hxx>
21 #include <OpenGl_PrimitiveArray.hxx>
22 #include <OpenGl_ShaderManager.hxx>
23 #include <OpenGl_ShaderProgram.hxx>
24 #include <OpenGl_Structure.hxx>
25 #include <OpenGl_VertexBufferCompat.hxx>
26 #include <OpenGl_Workspace.hxx>
27 #include <Graphic3d_TextureParams.hxx>
28 #include <NCollection_AlignedAllocator.hxx>
29
30 namespace
31 {
32   //! Convert data type to GL info
33   inline GLenum toGlDataType (const Graphic3d_TypeOfData theType,
34                               GLint&                     theNbComp)
35   {
36     switch (theType)
37     {
38       case Graphic3d_TOD_USHORT:
39         theNbComp = 1;
40         return GL_UNSIGNED_SHORT;
41       case Graphic3d_TOD_UINT:
42         theNbComp = 1;
43         return GL_UNSIGNED_INT;
44       case Graphic3d_TOD_VEC2:
45         theNbComp = 2;
46         return GL_FLOAT;
47       case Graphic3d_TOD_VEC3:
48         theNbComp = 3;
49         return GL_FLOAT;
50       case Graphic3d_TOD_VEC4:
51         theNbComp = 4;
52         return GL_FLOAT;
53       case Graphic3d_TOD_VEC4UB:
54         theNbComp = 4;
55         return GL_UNSIGNED_BYTE;
56       case Graphic3d_TOD_FLOAT:
57         theNbComp = 1;
58         return GL_FLOAT;
59     }
60     theNbComp = 0;
61     return GL_NONE;
62   }
63
64 }
65
66 //! Auxiliary template for VBO with interleaved attributes.
67 template<class TheBaseClass, int NbAttributes>
68 class OpenGl_VertexBufferT : public TheBaseClass
69 {
70
71 public:
72
73   //! Create uninitialized VBO.
74   OpenGl_VertexBufferT (const Graphic3d_Attribute* theAttribs,
75                         const Standard_Integer     theStride)
76   : Stride (theStride)
77   {
78     memcpy (Attribs, theAttribs, sizeof(Graphic3d_Attribute) * NbAttributes);
79   }
80
81   //! Create uninitialized VBO.
82   OpenGl_VertexBufferT (const Graphic3d_Buffer& theAttribs)
83   : Stride (theAttribs.Stride)
84   {
85     memcpy (Attribs, theAttribs.AttributesArray(), sizeof(Graphic3d_Attribute) * NbAttributes);
86   }
87
88   virtual bool HasColorAttribute() const
89   {
90     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
91     {
92       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
93       if (anAttrib.Id == Graphic3d_TOA_COLOR)
94       {
95         return true;
96       }
97     }
98     return false;
99   }
100
101   virtual bool HasNormalAttribute() const
102   {
103     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
104     {
105       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
106       if (anAttrib.Id == Graphic3d_TOA_NORM)
107       {
108         return true;
109       }
110     }
111     return false;
112   }
113
114   virtual void BindPositionAttribute (const Handle(OpenGl_Context)& theGlCtx) const
115   {
116     if (!TheBaseClass::IsValid())
117     {
118       return;
119     }
120
121     TheBaseClass::Bind (theGlCtx);
122     GLint aNbComp;
123     const GLubyte* anOffset = TheBaseClass::myOffset;
124     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
125     {
126       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
127       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
128       if (aDataType == GL_NONE)
129       {
130         continue;
131       }
132       else if (anAttrib.Id == Graphic3d_TOA_POS)
133       {
134         TheBaseClass::bindAttribute (theGlCtx, Graphic3d_TOA_POS, aNbComp, aDataType, Stride, anOffset);
135         break;
136       }
137
138       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
139     }
140   }
141
142   virtual void BindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
143   {
144     if (!TheBaseClass::IsValid())
145     {
146       return;
147     }
148
149     TheBaseClass::Bind (theGlCtx);
150     GLint aNbComp;
151     const GLubyte* anOffset = TheBaseClass::myOffset;
152     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
153     {
154       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
155       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
156       if (aDataType == GL_NONE)
157       {
158         continue;
159       }
160
161       TheBaseClass::bindAttribute (theGlCtx, anAttrib.Id, aNbComp, aDataType, Stride, anOffset);
162       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
163     }
164   }
165
166   virtual void UnbindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
167   {
168     if (!TheBaseClass::IsValid())
169     {
170       return;
171     }
172     TheBaseClass::Unbind (theGlCtx);
173
174     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
175     {
176       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
177       TheBaseClass::unbindAttribute (theGlCtx, anAttrib.Id);
178     }
179   }
180
181 public:
182
183   Graphic3d_Attribute Attribs[NbAttributes];
184   Standard_Integer    Stride;
185
186 };
187
188 // =======================================================================
189 // function : clearMemoryGL
190 // purpose  :
191 // =======================================================================
192 void OpenGl_PrimitiveArray::clearMemoryGL (const Handle(OpenGl_Context)& theGlCtx) const
193 {
194   if (!myVboIndices.IsNull())
195   {
196     myVboIndices->Release (theGlCtx.operator->());
197     myVboIndices.Nullify();
198   }
199   if (!myVboAttribs.IsNull())
200   {
201     myVboAttribs->Release (theGlCtx.operator->());
202     myVboAttribs.Nullify();
203   }
204 }
205
206 // =======================================================================
207 // function : initNormalVbo
208 // purpose  :
209 // =======================================================================
210 Standard_Boolean OpenGl_PrimitiveArray::initNormalVbo (const Handle(OpenGl_Context)& theCtx) const
211 {
212   switch (myAttribs->NbAttributes)
213   {
214     case 1:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 1> (*myAttribs); break;
215     case 2:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 2> (*myAttribs); break;
216     case 3:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 3> (*myAttribs); break;
217     case 4:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 4> (*myAttribs); break;
218     case 5:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 5> (*myAttribs); break;
219     case 6:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 6> (*myAttribs); break;
220     case 7:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 7> (*myAttribs); break;
221     case 8:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 8> (*myAttribs); break;
222     case 9:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 9> (*myAttribs); break;
223     case 10: myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 10>(*myAttribs); break;
224   }
225
226   if (!myVboAttribs->init (theCtx, 0, myAttribs->NbElements, myAttribs->Data(), GL_NONE, myAttribs->Stride))
227   {
228     TCollection_ExtendedString aMsg;
229     aMsg += "VBO creation for Primitive Array has failed for ";
230     aMsg += myAttribs->NbElements;
231     aMsg += " vertices. Out of memory?";
232     theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PERFORMANCE, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
233
234     clearMemoryGL (theCtx);
235     return Standard_False;
236   }
237   else if (myIndices.IsNull())
238   {
239     return Standard_True;
240   }
241
242   myVboIndices = new OpenGl_IndexBuffer();
243   bool isOk = false;
244   switch (myIndices->Stride)
245   {
246     case 2:
247     {
248       isOk = myVboIndices->Init (theCtx, 1, myIndices->NbElements, reinterpret_cast<const GLushort*> (myIndices->Data()));
249       break;
250     }
251     case 4:
252     {
253       isOk = myVboIndices->Init (theCtx, 1, myIndices->NbElements, reinterpret_cast<const GLuint*> (myIndices->Data()));
254       break;
255     }
256     default:
257     {
258       clearMemoryGL (theCtx);
259       return Standard_False;
260     }
261   }
262   if (!isOk)
263   {
264     TCollection_ExtendedString aMsg;
265     aMsg += "VBO creation for Primitive Array has failed for ";
266     aMsg += myIndices->NbElements;
267     aMsg += " indices. Out of memory?";
268     theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PERFORMANCE, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
269     clearMemoryGL (theCtx);
270     return Standard_False;
271   }
272   return Standard_True;
273 }
274
275 // =======================================================================
276 // function : buildVBO
277 // purpose  :
278 // =======================================================================
279 Standard_Boolean OpenGl_PrimitiveArray::buildVBO (const Handle(OpenGl_Context)& theCtx,
280                                                   const Standard_Boolean        theToKeepData) const
281 {
282   bool isNormalMode = theCtx->ToUseVbo();
283   clearMemoryGL (theCtx);
284   if (myAttribs.IsNull()
285    || myAttribs->IsEmpty()
286    || myAttribs->NbElements < 1
287    || myAttribs->NbAttributes < 1
288    || myAttribs->NbAttributes > 10)
289   {
290     // vertices should be always defined - others are optional
291     return Standard_False;
292   }
293
294   if (isNormalMode
295    && initNormalVbo (theCtx))
296   {
297     if (!theCtx->caps->keepArrayData
298      && !theToKeepData)
299     {
300       myIndices.Nullify();
301       myAttribs.Nullify();
302     }
303     return Standard_True;
304   }
305
306   Handle(OpenGl_VertexBufferCompat) aVboAttribs;
307   switch (myAttribs->NbAttributes)
308   {
309     case 1:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 1> (*myAttribs); break;
310     case 2:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 2> (*myAttribs); break;
311     case 3:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 3> (*myAttribs); break;
312     case 4:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 4> (*myAttribs); break;
313     case 5:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 5> (*myAttribs); break;
314     case 6:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 6> (*myAttribs); break;
315     case 7:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 7> (*myAttribs); break;
316     case 8:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 8> (*myAttribs); break;
317     case 9:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 9> (*myAttribs); break;
318     case 10: aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 10>(*myAttribs); break;
319   }
320   aVboAttribs->initLink (myAttribs, 0, myAttribs->NbElements, GL_NONE);
321   if (!myIndices.IsNull())
322   {
323     Handle(OpenGl_VertexBufferCompat) aVboIndices = new OpenGl_VertexBufferCompat();
324     switch (myIndices->Stride)
325     {
326       case 2:
327       {
328         aVboIndices->initLink (myIndices, 1, myIndices->NbElements, GL_UNSIGNED_SHORT);
329         break;
330       }
331       case 4:
332       {
333         aVboIndices->initLink (myIndices, 1, myIndices->NbElements, GL_UNSIGNED_INT);
334         break;
335       }
336       default:
337       {
338         return Standard_False;
339       }
340     }
341     myVboIndices = aVboIndices;
342   }
343   myVboAttribs = aVboAttribs;
344   if (!theCtx->caps->keepArrayData
345    && !theToKeepData)
346   {
347     // does not make sense for compatibility mode
348     //myIndices.Nullify();
349     //myAttribs.Nullify();
350   }
351
352   return Standard_True;
353 }
354
355 // =======================================================================
356 // function : drawArray
357 // purpose  :
358 // =======================================================================
359 void OpenGl_PrimitiveArray::drawArray (const Handle(OpenGl_Workspace)& theWorkspace,
360                                        const Graphic3d_Vec4*           theFaceColors,
361                                        const Standard_Boolean          theHasVertColor) const
362 {
363   const Handle(OpenGl_Context)& aGlContext  = theWorkspace->GetGlContext();
364   const bool                    toHilight   = theWorkspace->ToHighlight();
365   bool                          hasVColors  = theHasVertColor && !toHilight;
366   if (myVboAttribs.IsNull())
367   {
368   #if !defined(GL_ES_VERSION_2_0)
369     if (myDrawMode == GL_POINTS)
370     {
371       // extreme compatibility mode - without sprites but with markers
372       drawMarkers (theWorkspace);
373     }
374   #endif
375     return;
376   }
377
378   myVboAttribs->BindAllAttributes (aGlContext);
379   if (theHasVertColor && toHilight)
380   {
381     // disable per-vertex color
382     OpenGl_VertexBuffer::unbindAttribute (aGlContext, Graphic3d_TOA_COLOR);
383   }
384   if (!myVboIndices.IsNull())
385   {
386     myVboIndices->Bind (aGlContext);
387     GLubyte* anOffset = myVboIndices->GetDataOffset();
388     if (!myBounds.IsNull())
389     {
390       // draw primitives by vertex count with the indices
391       const size_t aStride = myVboIndices->GetDataType() == GL_UNSIGNED_SHORT ? sizeof(unsigned short) : sizeof(unsigned int);
392       for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
393       {
394         const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
395         if (theFaceColors != NULL) aGlContext->SetColor4fv (theFaceColors[aGroupIter]);
396         glDrawElements (myDrawMode, aNbElemsInGroup, myVboIndices->GetDataType(), anOffset);
397         anOffset += aStride * aNbElemsInGroup;
398       }
399     }
400     else
401     {
402       // draw one (or sequential) primitive by the indices
403       glDrawElements (myDrawMode, myVboIndices->GetElemsNb(), myVboIndices->GetDataType(), anOffset);
404     }
405     myVboIndices->Unbind (aGlContext);
406   }
407   else if (!myBounds.IsNull())
408   {
409     GLint aFirstElem = 0;
410     for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
411     {
412       const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
413       if (theFaceColors != NULL) aGlContext->SetColor4fv (theFaceColors[aGroupIter]);
414       glDrawArrays (myDrawMode, aFirstElem, aNbElemsInGroup);
415       aFirstElem += aNbElemsInGroup;
416     }
417   }
418   else
419   {
420     if (myDrawMode == GL_POINTS)
421     {
422       drawMarkers (theWorkspace);
423     }
424     else
425     {
426       glDrawArrays (myDrawMode, 0, myVboAttribs->GetElemsNb());
427     }
428   }
429
430   // bind with 0
431   myVboAttribs->UnbindAllAttributes (aGlContext);
432
433   if (hasVColors)
434   {
435     theWorkspace->NamedStatus |= OPENGL_NS_RESMAT;
436   }
437 }
438
439 // =======================================================================
440 // function : drawEdges
441 // purpose  :
442 // =======================================================================
443 void OpenGl_PrimitiveArray::drawEdges (const TEL_COLOUR*               theEdgeColour,
444                                        const Handle(OpenGl_Workspace)& theWorkspace) const
445 {
446   const Handle(OpenGl_Context)& aGlContext = theWorkspace->GetGlContext();
447   if (myVboAttribs.IsNull())
448   {
449     return;
450   }
451
452 #if !defined(GL_ES_VERSION_2_0)
453   if (aGlContext->core11 != NULL)
454   {
455     glDisable (GL_LIGHTING);
456   }
457 #endif
458
459   const OpenGl_AspectLine* anAspectLineOld = theWorkspace->SetAspectLine (theWorkspace->AspectFace()->AspectEdge());
460   const OpenGl_AspectLine* anAspect = theWorkspace->ApplyAspectLine();
461
462 #if !defined(GL_ES_VERSION_2_0)
463   glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
464 #endif
465
466   if (aGlContext->core20fwd != NULL)
467   {
468     aGlContext->ShaderManager()->BindLineProgram (NULL, anAspect->Type() != Aspect_TOL_SOLID, Standard_False, Standard_False, anAspect->ShaderProgramRes (aGlContext));
469   }
470
471   /// OCC22236 NOTE: draw edges for all situations:
472   /// 1) draw elements with GL_LINE style as edges from myPArray->bufferVBO[VBOEdges] indices array
473   /// 2) draw elements from vertex array, when bounds defines count of primitive's vertices.
474   /// 3) draw primitive's edges by vertexes if no edges and bounds array is specified
475   myVboAttribs->BindPositionAttribute (aGlContext);
476
477   aGlContext->SetColor4fv   (*(const OpenGl_Vec4* )theEdgeColour->rgb);
478   aGlContext->SetTypeOfLine (anAspect->Type());
479   aGlContext->SetLineWidth  (anAspect->Width());
480
481   if (!myVboIndices.IsNull())
482   {
483     myVboIndices->Bind (aGlContext);
484     GLubyte* anOffset = myVboIndices->GetDataOffset();
485
486     // draw primitives by vertex count with the indices
487     if (!myBounds.IsNull())
488     {
489       const size_t aStride = myVboIndices->GetDataType() == GL_UNSIGNED_SHORT ? sizeof(unsigned short) : sizeof(unsigned int);
490       for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
491       {
492         const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
493         glDrawElements (myDrawMode, aNbElemsInGroup, myVboIndices->GetDataType(), anOffset);
494         anOffset += aStride * aNbElemsInGroup;
495       }
496     }
497     // draw one (or sequential) primitive by the indices
498     else
499     {
500       glDrawElements (myDrawMode, myVboIndices->GetElemsNb(), myVboIndices->GetDataType(), anOffset);
501     }
502     myVboIndices->Unbind (aGlContext);
503   }
504   else if (!myBounds.IsNull())
505   {
506     GLint aFirstElem = 0;
507     for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
508     {
509       const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
510       glDrawArrays (myDrawMode, aFirstElem, aNbElemsInGroup);
511       aFirstElem += aNbElemsInGroup;
512     }
513   }
514   else
515   {
516     glDrawArrays (myDrawMode, 0, myAttribs->NbElements);
517   }
518
519   // unbind buffers
520   myVboAttribs->UnbindAttribute (aGlContext, Graphic3d_TOA_POS);
521
522   // restore line context
523   theWorkspace->SetAspectLine (anAspectLineOld);
524 }
525
526 // =======================================================================
527 // function : drawMarkers
528 // purpose  :
529 // =======================================================================
530 void OpenGl_PrimitiveArray::drawMarkers (const Handle(OpenGl_Workspace)& theWorkspace) const
531 {
532   const OpenGl_AspectMarker* anAspectMarker     = theWorkspace->ApplyAspectMarker();
533   const Handle(OpenGl_Context)&     aCtx        = theWorkspace->GetGlContext();
534   const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes (aCtx);
535   if (!aSpriteNorm.IsNull()
536    && !aSpriteNorm->IsDisplayList())
537   {
538     // Textured markers will be drawn with the point sprites
539     aCtx->SetPointSize (anAspectMarker->MarkerSize());
540     aCtx->SetPointSpriteOrigin();
541   #if !defined(GL_ES_VERSION_2_0)
542     if (aCtx->core11 != NULL)
543     {
544       aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
545       aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
546     }
547   #endif
548
549     aCtx->core11fwd->glEnable (GL_BLEND);
550     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
551
552     aCtx->core11fwd->glDrawArrays (myDrawMode, 0, !myVboAttribs.IsNull() ? myVboAttribs->GetElemsNb() : myAttribs->NbElements);
553
554     aCtx->core11fwd->glDisable (GL_BLEND);
555   #if !defined(GL_ES_VERSION_2_0)
556     if (aCtx->core11 != NULL)
557     {
558       aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
559     }
560   #endif
561     aCtx->SetPointSize (1.0f);
562     return;
563   }
564   else if (anAspectMarker->Type() == Aspect_TOM_POINT)
565   {
566     aCtx->SetPointSize (anAspectMarker->MarkerSize());
567     aCtx->core11fwd->glDrawArrays (myDrawMode, 0, !myVboAttribs.IsNull() ? myVboAttribs->GetElemsNb() : myAttribs->NbElements);
568     aCtx->SetPointSize (1.0f);
569   }
570 #if !defined(GL_ES_VERSION_2_0)
571   // Textured markers will be drawn with the glBitmap
572   else if (anAspectMarker->Type() != Aspect_TOM_POINT
573        && !aSpriteNorm.IsNull())
574   {
575     /**if (!isHilight && (myPArray->vcolours != NULL))
576     {
577       for (Standard_Integer anIter = 0; anIter < myAttribs->NbElements; anIter++)
578       {
579         glColor4ubv    (myPArray->vcolours[anIter].GetData());
580         glRasterPos3fv (myAttribs->Value<Graphic3d_Vec3> (anIter).GetData());
581         aSpriteNorm->DrawBitmap (theWorkspace->GetGlContext());
582       }
583     }
584     else*/
585     {
586       for (Standard_Integer anIter = 0; anIter < myAttribs->NbElements; anIter++)
587       {
588         aCtx->core11->glRasterPos3fv (myAttribs->Value<Graphic3d_Vec3> (anIter).GetData());
589         aSpriteNorm->DrawBitmap (theWorkspace->GetGlContext());
590       }
591     }
592   }
593 #endif
594 }
595
596 // =======================================================================
597 // function : OpenGl_PrimitiveArray
598 // purpose  :
599 // =======================================================================
600 OpenGl_PrimitiveArray::OpenGl_PrimitiveArray (const OpenGl_GraphicDriver* theDriver)
601
602 : myDrawMode  (DRAW_MODE_NONE),
603   myIsVboInit (Standard_False)
604 {
605   if (theDriver != NULL)
606   {
607     myUID = theDriver->GetNextPrimitiveArrayUID();
608   }
609 }
610
611 // =======================================================================
612 // function : OpenGl_PrimitiveArray
613 // purpose  :
614 // =======================================================================
615 OpenGl_PrimitiveArray::OpenGl_PrimitiveArray (const OpenGl_GraphicDriver*          theDriver,
616                                               const Graphic3d_TypeOfPrimitiveArray theType,
617                                               const Handle(Graphic3d_IndexBuffer)& theIndices,
618                                               const Handle(Graphic3d_Buffer)&      theAttribs,
619                                               const Handle(Graphic3d_BoundBuffer)& theBounds)
620
621 : myIndices   (theIndices),
622   myAttribs   (theAttribs),
623   myBounds    (theBounds),
624   myDrawMode  (DRAW_MODE_NONE),
625   myIsVboInit (Standard_False)
626 {
627   if (!myIndices.IsNull()
628     && myIndices->NbElements < 1)
629   {
630     // dummy index buffer?
631     myIndices.Nullify();
632   }
633
634   if (theDriver != NULL)
635   {
636     myUID = theDriver->GetNextPrimitiveArrayUID();
637   #if defined (GL_ES_VERSION_2_0)
638     const Handle(OpenGl_Context)& aCtx = theDriver->GetSharedContext();
639     if (!aCtx.IsNull())
640     {
641       processIndices (aCtx);
642     }
643   #endif
644   }
645
646   setDrawMode (theType);
647 }
648
649 // =======================================================================
650 // function : ~OpenGl_PrimitiveArray
651 // purpose  :
652 // =======================================================================
653 OpenGl_PrimitiveArray::~OpenGl_PrimitiveArray()
654 {
655   //
656 }
657
658 // =======================================================================
659 // function : Release
660 // purpose  :
661 // =======================================================================
662 void OpenGl_PrimitiveArray::Release (OpenGl_Context* theContext)
663 {
664   myIsVboInit = Standard_False;
665   if (!myVboIndices.IsNull())
666   {
667     if (theContext)
668     {
669       theContext->DelayedRelease (myVboIndices);
670     }
671     myVboIndices.Nullify();
672   }
673   if (!myVboAttribs.IsNull())
674   {
675     if (theContext)
676     {
677       theContext->DelayedRelease (myVboAttribs);
678     }
679     myVboAttribs.Nullify();
680   }
681 }
682
683 // =======================================================================
684 // function : Render
685 // purpose  :
686 // =======================================================================
687 void OpenGl_PrimitiveArray::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
688 {
689   if (myDrawMode == DRAW_MODE_NONE)
690   {
691     return;
692   }
693
694   const OpenGl_AspectFace*   anAspectFace   = theWorkspace->ApplyAspectFace();
695   const OpenGl_AspectLine*   anAspectLine   = theWorkspace->ApplyAspectLine();
696   const OpenGl_AspectMarker* anAspectMarker = myDrawMode == GL_POINTS
697                                             ? theWorkspace->ApplyAspectMarker()
698                                             : theWorkspace->AspectMarker();
699
700   // create VBOs on first render call
701   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
702   if (!myIsVboInit)
703   {
704     // compatibility - keep data to draw markers using display lists
705     const Standard_Boolean toKeepData = myDrawMode == GL_POINTS
706                                     && !anAspectMarker->SpriteRes (aCtx).IsNull()
707                                     &&  anAspectMarker->SpriteRes (aCtx)->IsDisplayList();
708   #if defined (GL_ES_VERSION_2_0)
709     processIndices (aCtx);
710   #endif
711     buildVBO (aCtx, toKeepData);
712     myIsVboInit = Standard_True;
713   }
714
715   Tint aFrontLightingModel = anAspectFace->IntFront().color_mask;
716   const Standard_Boolean hasColorAttrib = !myVboAttribs.IsNull()
717                                         && myVboAttribs->HasColorAttribute();
718   const Standard_Boolean isLightOn = aFrontLightingModel != 0
719                                  && !myVboAttribs.IsNull()
720                                  &&  myVboAttribs->HasNormalAttribute();
721 #if !defined(GL_ES_VERSION_2_0)
722   // manage FFP lighting
723   if (aCtx->core11 != NULL)
724   {
725     if (!isLightOn)
726     {
727       glDisable (GL_LIGHTING);
728     }
729     else
730     {
731       glEnable (GL_LIGHTING);
732     }
733   }
734 #endif
735   // Temporarily disable environment mapping
736   Handle(OpenGl_Texture) aTextureBack;
737   if (myDrawMode <= GL_LINE_STRIP)
738   {
739     aTextureBack = theWorkspace->DisableTexture();
740   }
741
742   if ((myDrawMode >  GL_LINE_STRIP && anAspectFace->InteriorStyle() != Aspect_IS_EMPTY) ||
743       (myDrawMode <= GL_LINE_STRIP))
744   {
745     const bool             toHilight    = theWorkspace->ToHighlight();
746     const Standard_Boolean hasVertColor = hasColorAttrib && !toHilight;
747     if (aCtx->core20fwd != NULL)
748     {
749       switch (myDrawMode)
750       {
751         case GL_POINTS:
752         {
753           const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes (aCtx);
754           if (!aSpriteNorm.IsNull()
755            && !aSpriteNorm->IsDisplayList())
756           {
757             const Handle(OpenGl_PointSprite)& aSprite = (toHilight && anAspectMarker->SpriteHighlightRes (aCtx)->IsValid())
758                                                       ? anAspectMarker->SpriteHighlightRes (aCtx)
759                                                       : aSpriteNorm;
760             theWorkspace->EnableTexture (aSprite);
761             aCtx->ShaderManager()->BindMarkerProgram (aSprite, isLightOn, hasVertColor, anAspectMarker->ShaderProgramRes (aCtx));
762           }
763           else
764           {
765             aCtx->ShaderManager()->BindMarkerProgram (NULL, isLightOn, hasVertColor, anAspectMarker->ShaderProgramRes (aCtx));
766           }
767           break;
768         }
769         case GL_LINES:
770         case GL_LINE_STRIP:
771         {
772           aCtx->ShaderManager()->BindLineProgram (NULL, anAspectLine->Type() != Aspect_TOL_SOLID, isLightOn, hasVertColor, anAspectLine->ShaderProgramRes (aCtx));
773           break;
774         }
775         default:
776         {
777           const Handle(OpenGl_Texture)& aTexture = theWorkspace->ActiveTexture();
778           const Standard_Boolean isLightOnFace = isLightOn
779                                               && (aTexture.IsNull()
780                                                || aTexture->GetParams()->IsModulate());
781           const Standard_Boolean toEnableEnvMap = (!aTexture.IsNull() && (aTexture == theWorkspace->EnvironmentTexture()));
782           aCtx->ShaderManager()->BindFaceProgram (aTexture,
783                                                   isLightOnFace,
784                                                   hasVertColor,
785                                                   toEnableEnvMap,
786                                                   anAspectFace->ShaderProgramRes (aCtx));
787           break;
788         }
789       }
790     }
791
792     // All primitives should gather material properties from the AspectFace in shading mode
793     if (isLightOn)
794     {
795       aCtx->SetShadingMaterial (anAspectFace, theWorkspace->ToHighlight() ? (const OpenGl_Vec4* )theWorkspace->HighlightColor : NULL);
796     }
797
798     if (!theWorkspace->ActiveTexture().IsNull()
799      && myDrawMode != GL_POINTS) // transformation is not supported within point sprites
800     {
801       aCtx->SetTextureMatrix (theWorkspace->ActiveTexture()->GetParams());
802     }
803
804     if (myDrawMode <= GL_LINE_STRIP)
805     {
806       const TEL_COLOUR& aLineColor = myDrawMode == GL_POINTS ? theWorkspace->MarkerColor() : theWorkspace->LineColor();
807       aCtx->SetColor4fv (*(const OpenGl_Vec4* )aLineColor.rgb);
808     }
809     else
810     {
811       const TEL_COLOUR& anInteriorColor = theWorkspace->InteriorColor();
812       aCtx->SetColor4fv (*(const OpenGl_Vec4* )anInteriorColor.rgb);
813     }
814     if (myDrawMode == GL_LINES
815      || myDrawMode == GL_LINE_STRIP)
816     {
817       aCtx->SetTypeOfLine (anAspectLine->Type());
818       aCtx->SetLineWidth  (anAspectLine->Width());
819     }
820
821     const Graphic3d_Vec4* aFaceColors = !myBounds.IsNull() && !toHilight && anAspectFace->InteriorStyle() != Aspect_IS_HIDDENLINE
822                                       ?  myBounds->Colors
823                                       :  NULL;
824     drawArray (theWorkspace, aFaceColors, hasColorAttrib);
825   }
826
827   if (myDrawMode <= GL_LINE_STRIP)
828   {
829     theWorkspace->EnableTexture (aTextureBack);
830   }
831   else
832   {
833     if (anAspectFace->Edge()
834      || anAspectFace->InteriorStyle() == Aspect_IS_HIDDENLINE)
835     {
836       const TEL_COLOUR* anEdgeColor = &theWorkspace->EdgeColor();
837       drawEdges (anEdgeColor, theWorkspace);
838
839       // restore OpenGL polygon mode if needed
840     #if !defined(GL_ES_VERSION_2_0)
841       if (anAspectFace->InteriorStyle() >= Aspect_IS_HATCH)
842       {
843         glPolygonMode (GL_FRONT_AND_BACK,
844           anAspectFace->InteriorStyle() == Aspect_IS_POINT ? GL_POINT : GL_FILL);
845       }
846     #endif
847     }
848   }
849
850   aCtx->BindProgram (NULL);
851 }
852
853 // =======================================================================
854 // function : setDrawMode
855 // purpose  :
856 // =======================================================================
857 void OpenGl_PrimitiveArray::setDrawMode (const Graphic3d_TypeOfPrimitiveArray theType)
858 {
859   if (myAttribs.IsNull())
860   {
861     myDrawMode = DRAW_MODE_NONE;
862     return;
863   }
864
865   switch (theType)
866   {
867     case Graphic3d_TOPA_POINTS:
868       myDrawMode = GL_POINTS;
869       break;
870     case Graphic3d_TOPA_POLYLINES:
871       myDrawMode = GL_LINE_STRIP;
872       break;
873     case Graphic3d_TOPA_SEGMENTS:
874       myDrawMode = GL_LINES;
875       break;
876     case Graphic3d_TOPA_TRIANGLES:
877       myDrawMode = GL_TRIANGLES;
878       break;
879     case Graphic3d_TOPA_TRIANGLESTRIPS:
880       myDrawMode = GL_TRIANGLE_STRIP;
881       break;
882     case Graphic3d_TOPA_TRIANGLEFANS:
883       myDrawMode = GL_TRIANGLE_FAN;
884       break;
885   #if !defined(GL_ES_VERSION_2_0)
886     case Graphic3d_TOPA_POLYGONS:
887       myDrawMode = GL_POLYGON;
888       break;
889     case Graphic3d_TOPA_QUADRANGLES:
890       myDrawMode = GL_QUADS;
891       break;
892     case Graphic3d_TOPA_QUADRANGLESTRIPS:
893       myDrawMode = GL_QUAD_STRIP;
894       break;
895   #else
896     case Graphic3d_TOPA_POLYGONS:
897     case Graphic3d_TOPA_QUADRANGLES:
898     case Graphic3d_TOPA_QUADRANGLESTRIPS:
899   #endif
900     case Graphic3d_TOPA_UNDEFINED:
901       break;
902   }
903 }
904
905 // =======================================================================
906 // function : processIndices
907 // purpose  :
908 // =======================================================================
909 Standard_Boolean OpenGl_PrimitiveArray::processIndices (const Handle(OpenGl_Context)& theContext) const
910 {
911   if (myIndices.IsNull()
912    || theContext->hasUintIndex)
913   {
914     return Standard_True;
915   }
916
917   if (myIndices->NbElements > std::numeric_limits<GLushort>::max())
918   {
919     Handle(Graphic3d_Buffer) anAttribs = new Graphic3d_Buffer (new NCollection_AlignedAllocator (16));
920     if (!anAttribs->Init (myIndices->NbElements, myAttribs->AttributesArray(), myAttribs->NbAttributes))
921     {
922       return Standard_False; // failed to initialize attribute array
923     }
924
925     for (Standard_Integer anIdxIdx = 0; anIdxIdx < myIndices->NbElements; ++anIdxIdx)
926     {
927       const Standard_Integer anIndex = myIndices->Index (anIdxIdx);
928       memcpy (anAttribs->ChangeData() + myAttribs->Stride * anIdxIdx,
929               myAttribs->Data()       + myAttribs->Stride * anIndex,
930               myAttribs->Stride);
931     }
932
933     myIndices.Nullify();
934     myAttribs = anAttribs;
935   }
936
937   return Standard_True;
938 }
939
940 // =======================================================================
941 // function : InitBuffers
942 // purpose  :
943 // =======================================================================
944 void OpenGl_PrimitiveArray::InitBuffers (const Handle(OpenGl_Context)&        theContext,
945                                          const Graphic3d_TypeOfPrimitiveArray theType,
946                                          const Handle(Graphic3d_IndexBuffer)& theIndices,
947                                          const Handle(Graphic3d_Buffer)&      theAttribs,
948                                          const Handle(Graphic3d_BoundBuffer)& theBounds)
949 {
950   // Release old graphic resources
951   Release (theContext.operator->());
952
953   myIndices = theIndices;
954   myAttribs = theAttribs;
955   myBounds = theBounds;
956 #if defined(GL_ES_VERSION_2_0)
957   processIndices (theContext);
958 #endif
959
960   setDrawMode (theType);
961 }