0031193: Visualization - OpenGl_Flipping wrong text position if local transformation set
[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 : EstimatedDataSize
211 // purpose  :
212 // =======================================================================
213 Standard_Size OpenGl_Text::EstimatedDataSize() const
214 {
215   Standard_Size aSize = 0;
216   for (Standard_Integer anIter = myVertsVbo.Lower(); anIter <= myVertsVbo.Upper(); ++anIter)
217   {
218     if (const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter))
219     {
220       aSize += aVerts->EstimatedDataSize();
221     }
222     if (const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter))
223     {
224       aSize += aTCrds->EstimatedDataSize();
225     }
226   }
227   if (!myBndVertsVbo.IsNull())
228   {
229     aSize += myBndVertsVbo->EstimatedDataSize();
230   }
231   return aSize;
232 }
233
234 // =======================================================================
235 // function : UpdateDrawStats
236 // purpose  :
237 // =======================================================================
238 void OpenGl_Text::UpdateDrawStats (Graphic3d_FrameStatsDataTmp& theStats,
239                                    bool theIsDetailed) const
240 {
241   ++theStats[Graphic3d_FrameStatsCounter_NbElemsNotCulled];
242   ++theStats[Graphic3d_FrameStatsCounter_NbElemsTextNotCulled];
243   if (theIsDetailed)
244   {
245     for (Standard_Integer anIter = myVertsVbo.Lower(); anIter <= myVertsVbo.Upper(); ++anIter)
246     {
247       if (const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter))
248       {
249         theStats[Graphic3d_FrameStatsCounter_NbTrianglesNotCulled] += aVerts->GetElemsNb() / 3; // 2 non-indexed triangles per glyph
250       }
251     }
252   }
253 }
254
255 // =======================================================================
256 // function : StringSize
257 // purpose  :
258 // =======================================================================
259 void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
260                               const NCollection_String&     theText,
261                               const OpenGl_Aspects&         theTextAspect,
262                               const Standard_ShortReal      theHeight,
263                               const unsigned int            theResolution,
264                               Standard_ShortReal&           theWidth,
265                               Standard_ShortReal&           theAscent,
266                               Standard_ShortReal&           theDescent)
267 {
268   theWidth   = 0.0f;
269   theAscent  = 0.0f;
270   theDescent = 0.0f;
271   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)theHeight, theResolution);
272   Handle(OpenGl_Font) aFont = FindFont (theCtx, theTextAspect, (Standard_Integer)theHeight, theResolution, aFontKey);
273   if (aFont.IsNull() || !aFont->IsValid())
274   {
275     return;
276   }
277
278   theAscent  = aFont->Ascender();
279   theDescent = aFont->Descender();
280
281   GLfloat aWidth = 0.0f;
282   for (NCollection_Utf8Iter anIter = theText.Iterator(); *anIter != 0;)
283   {
284     const Standard_Utf32Char aCharThis =   *anIter;
285     const Standard_Utf32Char aCharNext = *++anIter;
286
287     if (aCharThis == '\x0D' // CR  (carriage return)
288      || aCharThis == '\a'   // BEL (alarm)
289      || aCharThis == '\f'   // FF  (form feed) NP (new page)
290      || aCharThis == '\b'   // BS  (backspace)
291      || aCharThis == '\v')  // VT  (vertical tab)
292     {
293       continue; // skip unsupported carriage control codes
294     }
295     else if (aCharThis == '\x0A') // LF (line feed, new line)
296     {
297       theWidth = Max (theWidth, aWidth);
298       aWidth   = 0.0f;
299       continue;
300     }
301     else if (aCharThis == ' ')
302     {
303       aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
304       continue;
305     }
306     else if (aCharThis == '\t')
307     {
308       aWidth += aFont->FTFont()->AdvanceX (' ', aCharNext) * 8.0f;
309       continue;
310     }
311
312     aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
313   }
314   theWidth = Max (theWidth, aWidth);
315
316   Handle(OpenGl_Context) aCtx = theCtx;
317   aFont.Nullify();
318   aCtx->ReleaseResource (aFontKey, Standard_True);
319 }
320
321 // =======================================================================
322 // function : Render
323 // purpose  :
324 // =======================================================================
325 void OpenGl_Text::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
326 {
327   const OpenGl_Aspects* aTextAspect = theWorkspace->ApplyAspects (false); // do not bind textures as they will be disabled anyway
328   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
329
330   // Bind custom shader program or generate default version
331   aCtx->ShaderManager()->BindFontProgram (aTextAspect->ShaderProgramRes (aCtx));
332   const Handle(OpenGl_TextureSet) aPrevTexture = aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
333
334   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
335   {
336     myOrientationMatrix = theWorkspace->View()->Camera()->OrientationMatrix();
337     // reset translation part
338     myOrientationMatrix.ChangeValue (0, 3) = 0.0;
339     myOrientationMatrix.ChangeValue (1, 3) = 0.0;
340     myOrientationMatrix.ChangeValue (2, 3) = 0.0;
341   }
342
343   myProjMatrix.Convert (aCtx->ProjectionState.Current());
344
345   // use highlight color or colors from aspect
346   render (aCtx,
347           *aTextAspect,
348           theWorkspace->TextColor(),
349           theWorkspace->TextSubtitleColor(),
350           aCtx->Resolution());
351
352   // restore aspects
353   if (!aPrevTexture.IsNull())
354   {
355     aCtx->BindTextures (aPrevTexture, Handle(OpenGl_ShaderProgram)());
356   }
357
358   // restore Z buffer settings
359   if (theWorkspace->UseZBuffer())
360   {
361     glEnable (GL_DEPTH_TEST);
362   }
363 }
364
365 // =======================================================================
366 // function : Render
367 // purpose  :
368 // =======================================================================
369 void OpenGl_Text::Render (const Handle(OpenGl_Context)& theCtx,
370                           const OpenGl_Aspects& theTextAspect,
371                           unsigned int theResolution) const
372 {
373 #if !defined(GL_ES_VERSION_2_0)
374   const Standard_Integer aPrevPolygonMode  = theCtx->SetPolygonMode (GL_FILL);
375   const bool             aPrevHatchingMode = theCtx->SetPolygonHatchEnabled (false);
376 #endif
377
378   render (theCtx, theTextAspect,
379           theTextAspect.Aspect()->ColorRGBA(),
380           theTextAspect.Aspect()->ColorSubTitleRGBA(),
381           theResolution);
382
383 #if !defined(GL_ES_VERSION_2_0)
384   theCtx->SetPolygonMode         (aPrevPolygonMode);
385   theCtx->SetPolygonHatchEnabled (aPrevHatchingMode);
386 #endif
387 }
388
389 // =======================================================================
390 // function : setupMatrix
391 // purpose  :
392 // =======================================================================
393 void OpenGl_Text::setupMatrix (const Handle(OpenGl_Context)& theCtx,
394                                const OpenGl_Aspects& theTextAspect,
395                                const OpenGl_Vec3& theDVec) const
396 {
397   OpenGl_Mat4d aModViewMat, aProjectMat;
398   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
399   {
400     aProjectMat = myProjMatrix * myOrientationMatrix;
401   }
402   else
403   {
404     aProjectMat = myProjMatrix;
405   }
406
407   if (myIs2d)
408   {
409     const gp_Pnt& aPoint = myText->Position();
410     Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, aPoint.X() + theDVec.x(), aPoint.Y() + theDVec.y(), 0.f);
411     Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, 1.f, -1.f, 1.f);
412     Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.f, 0.f, 1.f);
413   }
414   else
415   {
416     OpenGl_Vec3d anObjXYZ;
417     OpenGl_Vec3d aWinXYZ = myWinXYZ + OpenGl_Vec3d (theDVec);
418     if (!myText->HasPlane() && !theTextAspect.Aspect()->IsTextZoomable())
419     {
420       // Align coordinates to the nearest integer to avoid extra interpolation issues.
421       // Note that for better readability we could also try aligning freely rotated in 3D text (myHasPlane),
422       // when camera orientation co-aligned with horizontal text orientation,
423       // but this might look awkward while rotating camera.
424       aWinXYZ.x() = Floor (aWinXYZ.x());
425       aWinXYZ.y() = Floor (aWinXYZ.y());
426     }
427     Graphic3d_TransformUtils::UnProject<Standard_Real> (aWinXYZ.x(), aWinXYZ.y(), aWinXYZ.z(),
428                                                         THE_IDENTITY_MATRIX, aProjectMat, theCtx->Viewport(),
429                                                         anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
430
431     if (myText->HasPlane())
432     {
433       const gp_Ax2& anOrientation = myText->Orientation();
434       const gp_Dir& aVectorDir   = anOrientation.XDirection();
435       const gp_Dir& aVectorUp    = anOrientation.Direction();
436       const gp_Dir& aVectorRight = anOrientation.YDirection();
437
438       aModViewMat.SetColumn (2, OpenGl_Vec3d (aVectorUp.X(), aVectorUp.Y(), aVectorUp.Z()));
439       aModViewMat.SetColumn (1, OpenGl_Vec3d (aVectorRight.X(), aVectorRight.Y(), aVectorRight.Z()));
440       aModViewMat.SetColumn (0, OpenGl_Vec3d (aVectorDir.X(), aVectorDir.Y(), aVectorDir.Z()));
441
442       if (!myText->HasOwnAnchorPoint())
443       {
444         OpenGl_Mat4d aPosMat;
445         const gp_Pnt& aPoint = myText->Position();
446         aPosMat.SetColumn (3, OpenGl_Vec3d (aPoint.X(), aPoint.Y(), aPoint.Z()));
447         aPosMat *= aModViewMat;
448         aModViewMat.SetColumn (3, aPosMat.GetColumn (3));
449       }
450       else
451       {
452         aModViewMat.SetColumn (3, anObjXYZ);
453       }
454     }
455     else
456     {
457       Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
458       Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.0, 0.0, 1.0);
459     }
460
461     if (!theTextAspect.Aspect()->IsTextZoomable())
462     {
463       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, myScaleHeight, myScaleHeight, myScaleHeight);
464     }
465     else if (theCtx->HasRenderScale())
466     {
467       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, theCtx->RenderScaleInv(), theCtx->RenderScaleInv(), theCtx->RenderScaleInv());
468     }
469   }
470
471   if (myText->HasPlane() && !myText->HasOwnAnchorPoint())
472   {
473     OpenGl_Mat4d aCurrentWorldViewMat;
474     aCurrentWorldViewMat.Convert (theCtx->WorldViewState.Current());
475
476     // apply local transformation
477     OpenGl_Mat4d aModelWorld;
478     aModelWorld.Convert (theCtx->ModelWorldState.Current());
479     aCurrentWorldViewMat = aCurrentWorldViewMat * aModelWorld;
480
481     theCtx->WorldViewState.SetCurrent<Standard_Real> (aCurrentWorldViewMat * aModViewMat);
482   }
483   else
484   {
485     theCtx->WorldViewState.SetCurrent<Standard_Real> (aModViewMat);
486   }
487   theCtx->ApplyWorldViewMatrix();
488
489   if (!myIs2d)
490   {
491     theCtx->ProjectionState.SetCurrent<Standard_Real> (aProjectMat);
492     theCtx->ApplyProjectionMatrix();
493   }
494
495   // Upload updated state to shader program
496   theCtx->ShaderManager()->PushState (theCtx->ActiveProgram());
497 }
498
499 // =======================================================================
500 // function : drawText
501 // purpose  :
502 // =======================================================================
503 void OpenGl_Text::drawText (const Handle(OpenGl_Context)& theCtx,
504                             const OpenGl_Aspects& theTextAspect) const
505 {
506   (void )theTextAspect;
507   if (myVertsVbo.Length() != myTextures.Length()
508    || myTextures.IsEmpty())
509   {
510     return;
511   }
512
513   for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
514   {
515     const GLuint aTexId = myTextures.Value (anIter);
516     glBindTexture (GL_TEXTURE_2D, aTexId);
517
518     const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter);
519     const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter);
520     aVerts->BindAttribute (theCtx, Graphic3d_TOA_POS);
521     aTCrds->BindAttribute (theCtx, Graphic3d_TOA_UV);
522
523     glDrawArrays (GL_TRIANGLES, 0, GLsizei(aVerts->GetElemsNb()));
524
525     aTCrds->UnbindAttribute (theCtx, Graphic3d_TOA_UV);
526     aVerts->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
527   }
528   glBindTexture (GL_TEXTURE_2D, 0);
529 }
530
531 // =======================================================================
532 // function : FontKey
533 // purpose  :
534 // =======================================================================
535 TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_Aspects& theAspect,
536                                               Standard_Integer theHeight,
537                                               unsigned int theResolution)
538 {
539   const Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
540                                  ? theAspect.Aspect()->TextFontAspect()
541                                  : Font_FA_Regular;
542   const TCollection_AsciiString& aFont = !theAspect.Aspect()->TextFont().IsNull() ? theAspect.Aspect()->TextFont()->String() : THE_DEFAULT_FONT;
543   return aFont
544        + TCollection_AsciiString(":") + Standard_Integer(anAspect)
545        + TCollection_AsciiString(":") + Standard_Integer(theResolution)
546        + TCollection_AsciiString(":") + theHeight;
547 }
548
549 // =======================================================================
550 // function : FindFont
551 // purpose  :
552 // =======================================================================
553 Handle(OpenGl_Font) OpenGl_Text::FindFont (const Handle(OpenGl_Context)& theCtx,
554                                            const OpenGl_Aspects& theAspect,
555                                            Standard_Integer theHeight,
556                                            unsigned int theResolution,
557                                            const TCollection_AsciiString& theKey)
558 {
559   Handle(OpenGl_Font) aFont;
560   if (theHeight < 2)
561   {
562     return aFont; // invalid parameters
563   }
564
565   if (!theCtx->GetResource (theKey, aFont))
566   {
567     Handle(Font_FontMgr) aFontMgr = Font_FontMgr::GetInstance();
568     const TCollection_AsciiString& aFontName = !theAspect.Aspect()->TextFont().IsNull()
569                                              ?  theAspect.Aspect()->TextFont()->String()
570                                              :  THE_DEFAULT_FONT;
571     Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
572                              ? theAspect.Aspect()->TextFontAspect()
573                              : Font_FA_Regular;
574     Font_FTFontParams aParams;
575     aParams.PointSize  = theHeight;
576     aParams.Resolution = theResolution;
577     if (Handle(Font_FTFont) aFontFt = Font_FTFont::FindAndCreate (aFontName, anAspect, aParams, Font_StrictLevel_Any))
578     {
579       aFont = new OpenGl_Font (aFontFt, theKey);
580       if (!aFont->Init (theCtx))
581       {
582         theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
583                               TCollection_AsciiString ("Font '") + aFontName + "' - initialization of GL resources has failed!");
584         aFontFt.Nullify();
585         aFont->Release (theCtx.get());
586         aFont = new OpenGl_Font (aFontFt, theKey);
587       }
588     }
589     else
590     {
591       theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
592                            TCollection_AsciiString ("Font '") + aFontName + "' is not found in the system!");
593       aFont = new OpenGl_Font (aFontFt, theKey);
594     }
595
596     theCtx->ShareResource (theKey, aFont);
597   }
598   return aFont;
599 }
600
601 // =======================================================================
602 // function : drawRect
603 // purpose  :
604 // =======================================================================
605 void OpenGl_Text::drawRect (const Handle(OpenGl_Context)& theCtx,
606                             const OpenGl_Aspects& theTextAspect,
607                             const OpenGl_Vec4& theColorSubs) const
608 {
609   Handle(OpenGl_ShaderProgram) aPrevProgram = theCtx->ActiveProgram();
610   if (myBndVertsVbo.IsNull())
611   {
612     OpenGl_Vec2 aQuad[4] =
613     {
614       OpenGl_Vec2(myBndBox.Right, myBndBox.Bottom),
615       OpenGl_Vec2(myBndBox.Right, myBndBox.Top),
616       OpenGl_Vec2(myBndBox.Left,  myBndBox.Bottom),
617       OpenGl_Vec2(myBndBox.Left,  myBndBox.Top)
618     };
619     if (theCtx->ToUseVbo())
620     {
621       myBndVertsVbo = new OpenGl_VertexBuffer();
622     }
623     else
624     {
625       myBndVertsVbo = new OpenGl_VertexBufferCompat();
626     }
627     myBndVertsVbo->Init (theCtx, 2, 4, aQuad[0].GetData());
628   }
629
630   // bind unlit program
631   theCtx->ShaderManager()->BindFaceProgram (Handle(OpenGl_TextureSet)(), Graphic3d_TOSM_UNLIT,
632                                             Graphic3d_AlphaMode_Opaque, Standard_False, Standard_False,
633                                             Handle(OpenGl_ShaderProgram)());
634
635 #if !defined(GL_ES_VERSION_2_0)
636   if (theCtx->core11 != NULL
637    && theCtx->ActiveProgram().IsNull())
638   {
639     glBindTexture (GL_TEXTURE_2D, 0);
640   }
641 #endif
642   theCtx->SetColor4fv (theColorSubs);
643   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
644   myBndVertsVbo->BindAttribute (theCtx, Graphic3d_TOA_POS);
645
646   theCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
647
648   myBndVertsVbo->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
649   theCtx->BindProgram (aPrevProgram);
650 }
651
652 // =======================================================================
653 // function : render
654 // purpose  :
655 // =======================================================================
656 void OpenGl_Text::render (const Handle(OpenGl_Context)& theCtx,
657                           const OpenGl_Aspects& theTextAspect,
658                           const OpenGl_Vec4& theColorText,
659                           const OpenGl_Vec4& theColorSubs,
660                           unsigned int theResolution) const
661 {
662   if (myText->Text().IsEmpty())
663   {
664     return;
665   }
666
667   // Note that using difference resolution in different Views in same Viewer
668   // will lead to performance regression (for example, text will be recreated every time).
669   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)myText->Height(), theResolution);
670   if (!myFont.IsNull()
671    && !myFont->ResourceKey().IsEqual (aFontKey))
672   {
673     // font changed
674     const_cast<OpenGl_Text* > (this)->Release (theCtx.operator->());
675   }
676
677   if (myFont.IsNull())
678   {
679     myFont = FindFont (theCtx, theTextAspect, (Standard_Integer)myText->Height(), theResolution, aFontKey);
680   }
681   if (!myFont->WasInitialized())
682   {
683     return;
684   }
685
686   if (myTextures.IsEmpty())
687   {
688     Font_TextFormatter aFormatter;
689
690     aFormatter.SetupAlignment (myText->HorizontalAlignment(), myText->VerticalAlignment());
691     aFormatter.Reset();
692
693     aFormatter.Append (myText->Text(), *myFont->FTFont());
694     aFormatter.Format();
695
696     OpenGl_TextBuilder aBuilder;
697     aBuilder.Perform (aFormatter,
698                       theCtx,
699                       *myFont.operator->(),
700                       myTextures,
701                       myVertsVbo,
702                       myTCrdsVbo);
703
704     aFormatter.BndBox (myBndBox);
705     if (!myBndVertsVbo.IsNull())
706     {
707       myBndVertsVbo->Release (theCtx.get());
708       myBndVertsVbo.Nullify();
709     }
710   }
711
712   if (myTextures.IsEmpty())
713   {
714     return;
715   }
716
717   myScaleHeight  = 1.0f;
718
719   theCtx->WorldViewState.Push();
720   myModelMatrix.Convert (theCtx->WorldViewState.Current() * theCtx->ModelWorldState.Current());
721
722   const GLdouble aPointSize = (GLdouble )myFont->FTFont()->PointSize();
723   if (!myIs2d)
724   {
725     const gp_Pnt& aPoint = myText->Position();
726     Graphic3d_TransformUtils::Project<Standard_Real> (aPoint.X(), aPoint.Y(), aPoint.Z(),
727                                                       myModelMatrix, myProjMatrix, theCtx->Viewport(),
728                                                       myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z());
729
730     // compute scale factor for constant text height
731     if (!theTextAspect.Aspect()->IsTextZoomable())
732     {
733       Graphic3d_Vec3d aPnt1, aPnt2;
734       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z(),
735                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
736                                                           aPnt1.x(), aPnt1.y(), aPnt1.z());
737       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y() + aPointSize, myWinXYZ.z(),
738                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
739                                                           aPnt2.x(), aPnt2.y(), aPnt2.z());
740       myScaleHeight = (aPnt2.y() - aPnt1.y()) / aPointSize;
741     }
742   }
743
744 #if !defined(GL_ES_VERSION_2_0)
745   if (theCtx->core11 != NULL
746    && theCtx->caps->ffpEnable)
747   {
748     glDisable (GL_LIGHTING);
749   }
750 #endif
751
752   // setup depth test
753   const bool hasDepthTest = !myIs2d
754                          && theTextAspect.Aspect()->TextStyle() != Aspect_TOST_ANNOTATION;
755   if (!hasDepthTest)
756   {
757     glDisable (GL_DEPTH_TEST);
758   }
759
760   if (theCtx->core15fwd != NULL)
761   {
762     theCtx->core15fwd->glActiveTexture (GL_TEXTURE0);
763   }
764 #if !defined(GL_ES_VERSION_2_0)
765   // activate texture unit
766   GLint aTexEnvParam = GL_REPLACE;
767   if (theCtx->core11 != NULL)
768   {
769     glDisable (GL_TEXTURE_1D);
770     glEnable  (GL_TEXTURE_2D);
771     glGetTexEnviv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &aTexEnvParam);
772     if (aTexEnvParam != GL_REPLACE)
773     {
774       glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
775     }
776   }
777 #endif
778
779   // setup blending
780   glEnable (GL_BLEND);
781   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
782
783   // alpha to coverage makes text too thin
784   theCtx->SetSampleAlphaToCoverage (false);
785
786   // extra drawings
787   switch (theTextAspect.Aspect()->TextDisplayType())
788   {
789     case Aspect_TODT_BLEND:
790     {
791     #if !defined(GL_ES_VERSION_2_0)
792       glEnable  (GL_COLOR_LOGIC_OP);
793       glLogicOp (GL_XOR);
794     #endif
795       break;
796     }
797     case Aspect_TODT_SUBTITLE:
798     {
799       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
800       drawRect (theCtx, theTextAspect, theColorSubs);
801       break;
802     }
803     case Aspect_TODT_DEKALE:
804     {
805       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
806       theCtx->SetColor4fv (theColorSubs);
807       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, +1.0f, 0.0f));
808       drawText    (theCtx, theTextAspect);
809       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, -1.0f, 0.0f));
810       drawText    (theCtx, theTextAspect);
811       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, +1.0f, 0.0f));
812       drawText    (theCtx, theTextAspect);
813       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
814       drawText    (theCtx, theTextAspect);
815       break;
816     }
817     case Aspect_TODT_SHADOW:
818     {
819       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
820       theCtx->SetColor4fv (theColorSubs);
821       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
822       drawText    (theCtx, theTextAspect);
823       break;
824     }
825     case Aspect_TODT_DIMENSION:
826     case Aspect_TODT_NORMAL:
827     {
828       break;
829     }
830   }
831
832   // main draw call
833   theCtx->SetColor4fv (theColorText);
834   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
835   drawText    (theCtx, theTextAspect);
836
837   if (!myIs2d)
838   {
839     theCtx->ProjectionState.SetCurrent<Standard_Real> (myProjMatrix);
840     theCtx->ApplyProjectionMatrix();
841   }
842
843 #if !defined(GL_ES_VERSION_2_0)
844   if (theCtx->core11 != NULL)
845   {
846     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aTexEnvParam);
847   }
848 #endif
849
850   if (theTextAspect.Aspect()->TextDisplayType() == Aspect_TODT_DIMENSION)
851   {
852     glDisable (GL_BLEND);
853     if (!myIs2d)
854     {
855       glDisable (GL_DEPTH_TEST);
856     }
857   #if !defined(GL_ES_VERSION_2_0)
858     if (theCtx->core11 != NULL)
859     {
860       glDisable (GL_TEXTURE_2D);
861     }
862   #endif
863     const bool aColorMaskBack = theCtx->SetColorMask (false);
864
865     glClear (GL_STENCIL_BUFFER_BIT);
866     glEnable (GL_STENCIL_TEST);
867     glStencilFunc (GL_ALWAYS, 1, 0xFF);
868     glStencilOp (GL_KEEP, GL_KEEP, GL_REPLACE);
869
870     drawRect (theCtx, theTextAspect, OpenGl_Vec4 (1.0f, 1.0f, 1.0f, 1.0f));
871
872     glStencilFunc (GL_ALWAYS, 0, 0xFF);
873
874     theCtx->SetColorMask (aColorMaskBack);
875   }
876
877   // reset OpenGL state
878   glDisable (GL_BLEND);
879   glDisable (GL_STENCIL_TEST);
880 #if !defined(GL_ES_VERSION_2_0)
881   glDisable (GL_COLOR_LOGIC_OP);
882 #endif
883
884   // model view matrix was modified
885   theCtx->WorldViewState.Pop();
886   theCtx->ApplyModelViewMatrix();
887 }
888
889 // =======================================================================
890 // function : DumpJson
891 // purpose  :
892 // =======================================================================
893 void OpenGl_Text::DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth) const
894 {
895   OCCT_DUMP_CLASS_BEGIN (theOStream, OpenGl_Text)
896   OCCT_DUMP_BASE_CLASS (theOStream, theDepth, OpenGl_Element)
897
898   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myTextures.Size())
899
900   for (NCollection_Vector<Handle(OpenGl_VertexBuffer)>::Iterator aCrdsIt (myTCrdsVbo); aCrdsIt.More(); aCrdsIt.Next())
901   {
902     const Handle(OpenGl_VertexBuffer)& aVertexBuffer = aCrdsIt.Value();
903     OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, aVertexBuffer.get())
904   }
905
906   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myBndBox)
907 }