0029528: Visualization, TKOpenGl - allow defining sRGB textures
[occt.git] / src / OpenGl / OpenGl_Text.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_Aspects.hxx>
17 #include <OpenGl_GlCore11.hxx>
18 #include <OpenGl_GraphicDriver.hxx>
19 #include <OpenGl_ShaderManager.hxx>
20 #include <OpenGl_ShaderProgram.hxx>
21 #include <OpenGl_ShaderStates.hxx>
22 #include <OpenGl_Text.hxx>
23 #include <OpenGl_Workspace.hxx>
24 #include <OpenGl_View.hxx>
25 #include <OpenGl_VertexBufferCompat.hxx>
26
27 #include <Font_FontMgr.hxx>
28 #include <Font_FTFont.hxx>
29 #include <Graphic3d_TransformUtils.hxx>
30 #include <TCollection_HAsciiString.hxx>
31
32 namespace
33 {
34   static const OpenGl_Mat4d THE_IDENTITY_MATRIX;
35
36   static const TCollection_AsciiString THE_DEFAULT_FONT (Font_NOF_ASCII_MONO);
37
38   //! Auxiliary tool for setting polygon offset temporarily.
39   struct BackPolygonOffsetSentry
40   {
41     BackPolygonOffsetSentry (OpenGl_Context* theCtx)
42     : myCtx (theCtx)
43     {
44       if (theCtx != NULL)
45       {
46         myOffsetBack = theCtx->PolygonOffset();
47         Graphic3d_PolygonOffset aPolyOffset = myOffsetBack;
48         aPolyOffset.Mode = Aspect_POM_Fill;
49         aPolyOffset.Units += 1.0f;
50         theCtx->SetPolygonOffset (aPolyOffset);
51       }
52     }
53
54     ~BackPolygonOffsetSentry()
55     {
56       if (myCtx != NULL)
57       {
58         myCtx->SetPolygonOffset (myOffsetBack);
59       }
60     }
61
62   private:
63     BackPolygonOffsetSentry (const BackPolygonOffsetSentry& );
64     BackPolygonOffsetSentry& operator= (const BackPolygonOffsetSentry& );
65   private:
66     OpenGl_Context* myCtx;
67     Graphic3d_PolygonOffset myOffsetBack;
68   };
69
70 } // anonymous namespace
71
72 // =======================================================================
73 // function : OpenGl_Text
74 // purpose  :
75 // =======================================================================
76 OpenGl_Text::OpenGl_Text()
77 : myScaleHeight (1.0f),
78   myIs2d        (Standard_False)
79 {
80   myText = new Graphic3d_Text (10.);
81 }
82
83
84 // =======================================================================
85 // function : OpenGl_Text
86 // purpose  :
87 // =======================================================================
88 OpenGl_Text::OpenGl_Text (const Handle(Graphic3d_Text)& theTextParams)
89 : myText        (theTextParams),
90   myScaleHeight (1.0f),
91   myIs2d        (Standard_False)
92 {
93 }
94
95 // =======================================================================
96 // function : SetPosition
97 // purpose  :
98 // =======================================================================
99 void OpenGl_Text::SetPosition (const OpenGl_Vec3& thePoint)
100 {
101   myText->SetPosition (gp_Pnt (thePoint.x(), thePoint.y(), thePoint.z()));
102 }
103
104 // =======================================================================
105 // function : SetFontSize
106 // purpose  :
107 // =======================================================================
108 void OpenGl_Text::SetFontSize (const Handle(OpenGl_Context)& theCtx,
109                                const Standard_Integer        theFontSize)
110 {
111   if (myText->Height() != theFontSize)
112   {
113     Release (theCtx.operator->());
114   }
115   myText->SetHeight ((Standard_ShortReal)theFontSize);
116 }
117
118 // =======================================================================
119 // function : Reset
120 // purpose  :
121 // =======================================================================
122 void OpenGl_Text::Reset (const Handle(OpenGl_Context)& theCtx)
123 {
124   if (!myFont.IsNull() && myFont->FTFont()->PointSize() != myText->Height())
125   {
126     Release (theCtx.operator->());
127   }
128   else
129   {
130     releaseVbos (theCtx.operator->());
131   }
132 }
133
134 // =======================================================================
135 // function : Init
136 // purpose  :
137 // =======================================================================
138 void OpenGl_Text::Init (const Handle(OpenGl_Context)& theCtx,
139                         const Standard_Utf8Char*      theText,
140                         const OpenGl_Vec3&            thePoint)
141 {
142   Reset (theCtx);
143   Set2D (Standard_False);
144
145   NCollection_String aText;
146   aText.FromUnicode (theText);
147   myText->SetText (aText);
148   myText->SetPosition (gp_Pnt (thePoint.x(), thePoint.y(), thePoint.z()));
149 }
150
151 // =======================================================================
152 // function : ~OpenGl_Text
153 // purpose  :
154 // =======================================================================
155 OpenGl_Text::~OpenGl_Text()
156 {
157   //
158 }
159
160 // =======================================================================
161 // function : releaseVbos
162 // purpose  :
163 // =======================================================================
164 void OpenGl_Text::releaseVbos (OpenGl_Context* theCtx)
165 {
166   for (Standard_Integer anIter = 0; anIter < myVertsVbo.Length(); ++anIter)
167   {
168     Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.ChangeValue (anIter);
169     Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.ChangeValue (anIter);
170
171     if (theCtx != NULL)
172     {
173       theCtx->DelayedRelease (aVerts);
174       theCtx->DelayedRelease (aTCrds);
175     }
176     aVerts.Nullify();
177     aTCrds.Nullify();
178   }
179   if (theCtx != NULL
180   && !myBndVertsVbo.IsNull())
181   {
182     theCtx->DelayedRelease (myBndVertsVbo);
183   }
184
185   myTextures.Clear();
186   myVertsVbo.Clear();
187   myTCrdsVbo.Clear();
188   myBndVertsVbo.Nullify();
189 }
190
191 // =======================================================================
192 // function : Release
193 // purpose  :
194 // =======================================================================
195 void OpenGl_Text::Release (OpenGl_Context* theCtx)
196 {
197   releaseVbos (theCtx);
198   if (!myFont.IsNull())
199   {
200     const TCollection_AsciiString aKey = myFont->ResourceKey();
201     myFont.Nullify();
202     if (theCtx != NULL)
203     {
204       theCtx->ReleaseResource (aKey, Standard_True);
205     }
206   }
207 }
208
209 // =======================================================================
210 // function : StringSize
211 // purpose  :
212 // =======================================================================
213 void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
214                               const NCollection_String&     theText,
215                               const OpenGl_Aspects&         theTextAspect,
216                               const Standard_ShortReal      theHeight,
217                               const unsigned int            theResolution,
218                               Standard_ShortReal&           theWidth,
219                               Standard_ShortReal&           theAscent,
220                               Standard_ShortReal&           theDescent)
221 {
222   theWidth   = 0.0f;
223   theAscent  = 0.0f;
224   theDescent = 0.0f;
225   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)theHeight, theResolution);
226   Handle(OpenGl_Font) aFont = FindFont (theCtx, theTextAspect, (Standard_Integer)theHeight, theResolution, aFontKey);
227   if (aFont.IsNull() || !aFont->IsValid())
228   {
229     return;
230   }
231
232   theAscent  = aFont->Ascender();
233   theDescent = aFont->Descender();
234
235   GLfloat aWidth = 0.0f;
236   for (NCollection_Utf8Iter anIter = theText.Iterator(); *anIter != 0;)
237   {
238     const Standard_Utf32Char aCharThis =   *anIter;
239     const Standard_Utf32Char aCharNext = *++anIter;
240
241     if (aCharThis == '\x0D' // CR  (carriage return)
242      || aCharThis == '\a'   // BEL (alarm)
243      || aCharThis == '\f'   // FF  (form feed) NP (new page)
244      || aCharThis == '\b'   // BS  (backspace)
245      || aCharThis == '\v')  // VT  (vertical tab)
246     {
247       continue; // skip unsupported carriage control codes
248     }
249     else if (aCharThis == '\x0A') // LF (line feed, new line)
250     {
251       theWidth = Max (theWidth, aWidth);
252       aWidth   = 0.0f;
253       continue;
254     }
255     else if (aCharThis == ' ')
256     {
257       aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
258       continue;
259     }
260     else if (aCharThis == '\t')
261     {
262       aWidth += aFont->FTFont()->AdvanceX (' ', aCharNext) * 8.0f;
263       continue;
264     }
265
266     aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
267   }
268   theWidth = Max (theWidth, aWidth);
269
270   Handle(OpenGl_Context) aCtx = theCtx;
271   aFont.Nullify();
272   aCtx->ReleaseResource (aFontKey, Standard_True);
273 }
274
275 // =======================================================================
276 // function : Render
277 // purpose  :
278 // =======================================================================
279 void OpenGl_Text::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
280 {
281   const OpenGl_Aspects* aTextAspect = theWorkspace->ApplyAspects();
282   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
283   const Handle(OpenGl_TextureSet) aPrevTexture = aCtx->BindTextures (Handle(OpenGl_TextureSet)());
284
285   // Bind custom shader program or generate default version
286   aCtx->ShaderManager()->BindFontProgram (aTextAspect->ShaderProgramRes (aCtx));
287
288   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
289   {
290     myOrientationMatrix = theWorkspace->View()->Camera()->OrientationMatrix();
291     // reset translation part
292     myOrientationMatrix.ChangeValue (0, 3) = 0.0;
293     myOrientationMatrix.ChangeValue (1, 3) = 0.0;
294     myOrientationMatrix.ChangeValue (2, 3) = 0.0;
295   }
296
297   myProjMatrix.Convert (aCtx->ProjectionState.Current());
298
299   // use highlight color or colors from aspect
300   render (aCtx,
301           *aTextAspect,
302           theWorkspace->TextColor(),
303           theWorkspace->TextSubtitleColor(),
304           aCtx->Resolution());
305
306   // restore aspects
307   if (!aPrevTexture.IsNull())
308   {
309     aCtx->BindTextures (aPrevTexture);
310   }
311
312   // restore Z buffer settings
313   if (theWorkspace->UseZBuffer())
314   {
315     glEnable (GL_DEPTH_TEST);
316   }
317 }
318
319 // =======================================================================
320 // function : Render
321 // purpose  :
322 // =======================================================================
323 void OpenGl_Text::Render (const Handle(OpenGl_Context)& theCtx,
324                           const OpenGl_Aspects& theTextAspect,
325                           unsigned int theResolution) const
326 {
327 #if !defined(GL_ES_VERSION_2_0)
328   const Standard_Integer aPrevPolygonMode  = theCtx->SetPolygonMode (GL_FILL);
329   const bool             aPrevHatchingMode = theCtx->SetPolygonHatchEnabled (false);
330 #endif
331
332   render (theCtx, theTextAspect,
333           theTextAspect.Aspect()->ColorRGBA(),
334           theTextAspect.Aspect()->ColorSubTitleRGBA(),
335           theResolution);
336
337 #if !defined(GL_ES_VERSION_2_0)
338   theCtx->SetPolygonMode         (aPrevPolygonMode);
339   theCtx->SetPolygonHatchEnabled (aPrevHatchingMode);
340 #endif
341 }
342
343 // =======================================================================
344 // function : setupMatrix
345 // purpose  :
346 // =======================================================================
347 void OpenGl_Text::setupMatrix (const Handle(OpenGl_Context)& theCtx,
348                                const OpenGl_Aspects& theTextAspect,
349                                const OpenGl_Vec3& theDVec) const
350 {
351   OpenGl_Mat4d aModViewMat, aProjectMat;
352   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
353   {
354     aProjectMat = myProjMatrix * myOrientationMatrix;
355   }
356   else
357   {
358     aProjectMat = myProjMatrix;
359   }
360
361   if (myIs2d)
362   {
363     const gp_Pnt& aPoint = myText->Position();
364     Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, aPoint.X() + theDVec.x(), aPoint.Y() + theDVec.y(), 0.f);
365     Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, 1.f, -1.f, 1.f);
366     Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.f, 0.f, 1.f);
367   }
368   else
369   {
370     OpenGl_Vec3d anObjXYZ;
371     OpenGl_Vec3d aWinXYZ = myWinXYZ + OpenGl_Vec3d (theDVec);
372     if (!myText->HasPlane() && !theTextAspect.Aspect()->IsTextZoomable())
373     {
374       // Align coordinates to the nearest integer to avoid extra interpolation issues.
375       // Note that for better readability we could also try aligning freely rotated in 3D text (myHasPlane),
376       // when camera orientation co-aligned with horizontal text orientation,
377       // but this might look awkward while rotating camera.
378       aWinXYZ.x() = Floor (aWinXYZ.x());
379       aWinXYZ.y() = Floor (aWinXYZ.y());
380     }
381     Graphic3d_TransformUtils::UnProject<Standard_Real> (aWinXYZ.x(), aWinXYZ.y(), aWinXYZ.z(),
382                                                         THE_IDENTITY_MATRIX, aProjectMat, theCtx->Viewport(),
383                                                         anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
384
385     if (myText->HasPlane())
386     {
387       const gp_Ax2& anOrientation = myText->Orientation();
388       const gp_Dir& aVectorDir   = anOrientation.XDirection();
389       const gp_Dir& aVectorUp    = anOrientation.Direction();
390       const gp_Dir& aVectorRight = anOrientation.YDirection();
391
392       aModViewMat.SetColumn (2, OpenGl_Vec3d (aVectorUp.X(), aVectorUp.Y(), aVectorUp.Z()));
393       aModViewMat.SetColumn (1, OpenGl_Vec3d (aVectorRight.X(), aVectorRight.Y(), aVectorRight.Z()));
394       aModViewMat.SetColumn (0, OpenGl_Vec3d (aVectorDir.X(), aVectorDir.Y(), aVectorDir.Z()));
395
396       if (!myText->HasOwnAnchorPoint())
397       {
398         OpenGl_Mat4d aPosMat;
399         const gp_Pnt& aPoint = myText->Position();
400         aPosMat.SetColumn (3, OpenGl_Vec3d (aPoint.X(), aPoint.Y(), aPoint.Z()));
401         aPosMat *= aModViewMat;
402         aModViewMat.SetColumn (3, aPosMat.GetColumn (3));
403       }
404       else
405       {
406         aModViewMat.SetColumn (3, anObjXYZ);
407       }
408     }
409     else
410     {
411       Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
412       Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.0, 0.0, 1.0);
413     }
414
415     if (!theTextAspect.Aspect()->IsTextZoomable())
416     {
417       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, myScaleHeight, myScaleHeight, myScaleHeight);
418     }
419     else if (theCtx->HasRenderScale())
420     {
421       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, theCtx->RenderScaleInv(), theCtx->RenderScaleInv(), theCtx->RenderScaleInv());
422     }
423   }
424
425   if (myText->HasPlane() && !myText->HasOwnAnchorPoint())
426   {
427     OpenGl_Mat4d aCurrentWorldViewMat;
428     aCurrentWorldViewMat.Convert (theCtx->WorldViewState.Current());
429     theCtx->WorldViewState.SetCurrent<Standard_Real> (aCurrentWorldViewMat * aModViewMat);
430   }
431   else
432   {
433     theCtx->WorldViewState.SetCurrent<Standard_Real> (aModViewMat);
434   }
435   theCtx->ApplyWorldViewMatrix();
436
437   if (!myIs2d)
438   {
439     theCtx->ProjectionState.SetCurrent<Standard_Real> (aProjectMat);
440     theCtx->ApplyProjectionMatrix();
441   }
442
443   // Upload updated state to shader program
444   theCtx->ShaderManager()->PushState (theCtx->ActiveProgram());
445 }
446
447 // =======================================================================
448 // function : drawText
449 // purpose  :
450 // =======================================================================
451 void OpenGl_Text::drawText (const Handle(OpenGl_Context)& theCtx,
452                             const OpenGl_Aspects& theTextAspect) const
453 {
454   (void )theTextAspect;
455   if (myVertsVbo.Length() != myTextures.Length()
456    || myTextures.IsEmpty())
457   {
458     return;
459   }
460
461   for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
462   {
463     const GLuint aTexId = myTextures.Value (anIter);
464     glBindTexture (GL_TEXTURE_2D, aTexId);
465
466     const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter);
467     const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter);
468     aVerts->BindAttribute (theCtx, Graphic3d_TOA_POS);
469     aTCrds->BindAttribute (theCtx, Graphic3d_TOA_UV);
470
471     glDrawArrays (GL_TRIANGLES, 0, GLsizei(aVerts->GetElemsNb()));
472
473     aTCrds->UnbindAttribute (theCtx, Graphic3d_TOA_UV);
474     aVerts->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
475   }
476   glBindTexture (GL_TEXTURE_2D, 0);
477 }
478
479 // =======================================================================
480 // function : FontKey
481 // purpose  :
482 // =======================================================================
483 TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_Aspects& theAspect,
484                                               Standard_Integer theHeight,
485                                               unsigned int theResolution)
486 {
487   const Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
488                                  ? theAspect.Aspect()->TextFontAspect()
489                                  : Font_FA_Regular;
490   const TCollection_AsciiString& aFont = !theAspect.Aspect()->TextFont().IsNull() ? theAspect.Aspect()->TextFont()->String() : THE_DEFAULT_FONT;
491   return aFont
492        + TCollection_AsciiString(":") + Standard_Integer(anAspect)
493        + TCollection_AsciiString(":") + Standard_Integer(theResolution)
494        + TCollection_AsciiString(":") + theHeight;
495 }
496
497 // =======================================================================
498 // function : FindFont
499 // purpose  :
500 // =======================================================================
501 Handle(OpenGl_Font) OpenGl_Text::FindFont (const Handle(OpenGl_Context)& theCtx,
502                                            const OpenGl_Aspects& theAspect,
503                                            Standard_Integer theHeight,
504                                            unsigned int theResolution,
505                                            const TCollection_AsciiString& theKey)
506 {
507   Handle(OpenGl_Font) aFont;
508   if (theHeight < 2)
509   {
510     return aFont; // invalid parameters
511   }
512
513   if (!theCtx->GetResource (theKey, aFont))
514   {
515     Handle(Font_FontMgr) aFontMgr = Font_FontMgr::GetInstance();
516     const TCollection_AsciiString& aFontName = !theAspect.Aspect()->TextFont().IsNull()
517                                              ?  theAspect.Aspect()->TextFont()->String()
518                                              :  THE_DEFAULT_FONT;
519     Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
520                              ? theAspect.Aspect()->TextFontAspect()
521                              : Font_FA_Regular;
522     Font_FTFontParams aParams;
523     aParams.PointSize  = theHeight;
524     aParams.Resolution = theResolution;
525     if (Handle(Font_FTFont) aFontFt = Font_FTFont::FindAndCreate (aFontName, anAspect, aParams, Font_StrictLevel_Any))
526     {
527       aFont = new OpenGl_Font (aFontFt, theKey);
528       if (!aFont->Init (theCtx))
529       {
530         theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
531                               TCollection_AsciiString ("Font '") + aFontName + "' - initialization of GL resources has failed!");
532         aFontFt.Nullify();
533         aFont->Release (theCtx.get());
534         aFont = new OpenGl_Font (aFontFt, theKey);
535       }
536     }
537     else
538     {
539       theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
540                            TCollection_AsciiString ("Font '") + aFontName + "' is not found in the system!");
541       aFont = new OpenGl_Font (aFontFt, theKey);
542     }
543
544     theCtx->ShareResource (theKey, aFont);
545   }
546   return aFont;
547 }
548
549 // =======================================================================
550 // function : drawRect
551 // purpose  :
552 // =======================================================================
553 void OpenGl_Text::drawRect (const Handle(OpenGl_Context)& theCtx,
554                             const OpenGl_Aspects& theTextAspect,
555                             const OpenGl_Vec4& theColorSubs) const
556 {
557   Handle(OpenGl_ShaderProgram) aPrevProgram = theCtx->ActiveProgram();
558   if (myBndVertsVbo.IsNull())
559   {
560     OpenGl_Vec2 aQuad[4] =
561     {
562       OpenGl_Vec2(myBndBox.Right, myBndBox.Bottom),
563       OpenGl_Vec2(myBndBox.Right, myBndBox.Top),
564       OpenGl_Vec2(myBndBox.Left,  myBndBox.Bottom),
565       OpenGl_Vec2(myBndBox.Left,  myBndBox.Top)
566     };
567     if (theCtx->ToUseVbo())
568     {
569       myBndVertsVbo = new OpenGl_VertexBuffer();
570     }
571     else
572     {
573       myBndVertsVbo = new OpenGl_VertexBufferCompat();
574     }
575     myBndVertsVbo->Init (theCtx, 2, 4, aQuad[0].GetData());
576   }
577
578   // bind unlit program
579   theCtx->ShaderManager()->BindFaceProgram (Handle(OpenGl_TextureSet)(), Graphic3d_TOSM_UNLIT,
580                                             Graphic3d_AlphaMode_Opaque, Standard_False, Standard_False,
581                                             Handle(OpenGl_ShaderProgram)());
582
583 #if !defined(GL_ES_VERSION_2_0)
584   if (theCtx->core11 != NULL
585    && theCtx->ActiveProgram().IsNull())
586   {
587     glBindTexture (GL_TEXTURE_2D, 0);
588   }
589 #endif
590   theCtx->SetColor4fv (theColorSubs);
591   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
592   myBndVertsVbo->BindAttribute (theCtx, Graphic3d_TOA_POS);
593
594   theCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
595
596   myBndVertsVbo->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
597   theCtx->BindProgram (aPrevProgram);
598 }
599
600 // =======================================================================
601 // function : render
602 // purpose  :
603 // =======================================================================
604 void OpenGl_Text::render (const Handle(OpenGl_Context)& theCtx,
605                           const OpenGl_Aspects& theTextAspect,
606                           const OpenGl_Vec4& theColorText,
607                           const OpenGl_Vec4& theColorSubs,
608                           unsigned int theResolution) const
609 {
610   if (myText->Text().IsEmpty())
611   {
612     return;
613   }
614
615   // Note that using difference resolution in different Views in same Viewer
616   // will lead to performance regression (for example, text will be recreated every time).
617   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)myText->Height(), theResolution);
618   if (!myFont.IsNull()
619    && !myFont->ResourceKey().IsEqual (aFontKey))
620   {
621     // font changed
622     const_cast<OpenGl_Text* > (this)->Release (theCtx.operator->());
623   }
624
625   if (myFont.IsNull())
626   {
627     myFont = FindFont (theCtx, theTextAspect, (Standard_Integer)myText->Height(), theResolution, aFontKey);
628   }
629   if (!myFont->WasInitialized())
630   {
631     return;
632   }
633
634   if (myTextures.IsEmpty())
635   {
636     Font_TextFormatter aFormatter;
637
638     aFormatter.SetupAlignment (myText->HorizontalAlignment(), myText->VerticalAlignment());
639     aFormatter.Reset();
640
641     aFormatter.Append (myText->Text(), *myFont->FTFont());
642     aFormatter.Format();
643
644     OpenGl_TextBuilder aBuilder;
645     aBuilder.Perform (aFormatter,
646                       theCtx,
647                       *myFont.operator->(),
648                       myTextures,
649                       myVertsVbo,
650                       myTCrdsVbo);
651
652     aFormatter.BndBox (myBndBox);
653     if (!myBndVertsVbo.IsNull())
654     {
655       myBndVertsVbo->Release (theCtx.get());
656       myBndVertsVbo.Nullify();
657     }
658   }
659
660   if (myTextures.IsEmpty())
661   {
662     return;
663   }
664
665   myScaleHeight  = 1.0f;
666
667   theCtx->WorldViewState.Push();
668   myModelMatrix.Convert (theCtx->WorldViewState.Current() * theCtx->ModelWorldState.Current());
669
670   const GLdouble aPointSize = (GLdouble )myFont->FTFont()->PointSize();
671   if (!myIs2d)
672   {
673     const gp_Pnt& aPoint = myText->Position();
674     Graphic3d_TransformUtils::Project<Standard_Real> (aPoint.X(), aPoint.Y(), aPoint.Z(),
675                                                       myModelMatrix, myProjMatrix, theCtx->Viewport(),
676                                                       myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z());
677
678     // compute scale factor for constant text height
679     if (!theTextAspect.Aspect()->IsTextZoomable())
680     {
681       Graphic3d_Vec3d aPnt1, aPnt2;
682       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z(),
683                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
684                                                           aPnt1.x(), aPnt1.y(), aPnt1.z());
685       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y() + aPointSize, myWinXYZ.z(),
686                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
687                                                           aPnt2.x(), aPnt2.y(), aPnt2.z());
688       myScaleHeight = (aPnt2.y() - aPnt1.y()) / aPointSize;
689     }
690   }
691
692 #if !defined(GL_ES_VERSION_2_0)
693   if (theCtx->core11 != NULL
694    && theCtx->caps->ffpEnable)
695   {
696     glDisable (GL_LIGHTING);
697   }
698 #endif
699
700   // setup depth test
701   const bool hasDepthTest = !myIs2d
702                          && theTextAspect.Aspect()->TextStyle() != Aspect_TOST_ANNOTATION;
703   if (!hasDepthTest)
704   {
705     glDisable (GL_DEPTH_TEST);
706   }
707
708   if (theCtx->core15fwd != NULL)
709   {
710     theCtx->core15fwd->glActiveTexture (GL_TEXTURE0);
711   }
712 #if !defined(GL_ES_VERSION_2_0)
713   // activate texture unit
714   GLint aTexEnvParam = GL_REPLACE;
715   if (theCtx->core11 != NULL)
716   {
717     glDisable (GL_TEXTURE_1D);
718     glEnable  (GL_TEXTURE_2D);
719     glGetTexEnviv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &aTexEnvParam);
720     if (aTexEnvParam != GL_REPLACE)
721     {
722       glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
723     }
724   }
725 #endif
726
727   // setup blending
728   glEnable (GL_BLEND);
729   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
730
731   // alpha to coverage makes text too thin
732   theCtx->SetSampleAlphaToCoverage (false);
733
734   // extra drawings
735   switch (theTextAspect.Aspect()->TextDisplayType())
736   {
737     case Aspect_TODT_BLEND:
738     {
739     #if !defined(GL_ES_VERSION_2_0)
740       glEnable  (GL_COLOR_LOGIC_OP);
741       glLogicOp (GL_XOR);
742     #endif
743       break;
744     }
745     case Aspect_TODT_SUBTITLE:
746     {
747       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
748       drawRect (theCtx, theTextAspect, theColorSubs);
749       break;
750     }
751     case Aspect_TODT_DEKALE:
752     {
753       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
754       theCtx->SetColor4fv (theColorSubs);
755       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, +1.0f, 0.0f));
756       drawText    (theCtx, theTextAspect);
757       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, -1.0f, 0.0f));
758       drawText    (theCtx, theTextAspect);
759       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, +1.0f, 0.0f));
760       drawText    (theCtx, theTextAspect);
761       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
762       drawText    (theCtx, theTextAspect);
763       break;
764     }
765     case Aspect_TODT_SHADOW:
766     {
767       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
768       theCtx->SetColor4fv (theColorSubs);
769       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
770       drawText    (theCtx, theTextAspect);
771       break;
772     }
773     case Aspect_TODT_DIMENSION:
774     case Aspect_TODT_NORMAL:
775     {
776       break;
777     }
778   }
779
780   // main draw call
781   theCtx->SetColor4fv (theColorText);
782   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
783   drawText    (theCtx, theTextAspect);
784
785   if (!myIs2d)
786   {
787     theCtx->ProjectionState.SetCurrent<Standard_Real> (myProjMatrix);
788     theCtx->ApplyProjectionMatrix();
789   }
790
791 #if !defined(GL_ES_VERSION_2_0)
792   if (theCtx->core11 != NULL)
793   {
794     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aTexEnvParam);
795   }
796 #endif
797
798   if (theTextAspect.Aspect()->TextDisplayType() == Aspect_TODT_DIMENSION)
799   {
800     glDisable (GL_BLEND);
801     if (!myIs2d)
802     {
803       glDisable (GL_DEPTH_TEST);
804     }
805   #if !defined(GL_ES_VERSION_2_0)
806     if (theCtx->core11 != NULL)
807     {
808       glDisable (GL_TEXTURE_2D);
809     }
810   #endif
811     const bool aColorMaskBack = theCtx->SetColorMask (false);
812
813     glClear (GL_STENCIL_BUFFER_BIT);
814     glEnable (GL_STENCIL_TEST);
815     glStencilFunc (GL_ALWAYS, 1, 0xFF);
816     glStencilOp (GL_KEEP, GL_KEEP, GL_REPLACE);
817
818     drawRect (theCtx, theTextAspect, OpenGl_Vec4 (1.0f, 1.0f, 1.0f, 1.0f));
819
820     glStencilFunc (GL_ALWAYS, 0, 0xFF);
821
822     theCtx->SetColorMask (aColorMaskBack);
823   }
824
825   // reset OpenGL state
826   glDisable (GL_BLEND);
827   glDisable (GL_STENCIL_TEST);
828 #if !defined(GL_ES_VERSION_2_0)
829   glDisable (GL_COLOR_LOGIC_OP);
830 #endif
831
832   // model view matrix was modified
833   theCtx->WorldViewState.Pop();
834   theCtx->ApplyModelViewMatrix();
835 }