1 // Created on: 2012-04-09
2 // Created by: Sergey ANIKIN
3 // Copyright (c) 2012-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <ViewerTest.hxx>
18 #include <AIS_InteractiveContext.hxx>
19 #include <AIS_InteractiveObject.hxx>
21 #include <Draw_Interpretor.hxx>
22 #include <Graphic3d_Group.hxx>
23 #include <Graphic3d_ShaderObject.hxx>
24 #include <Graphic3d_ShaderProgram.hxx>
25 #include <OpenGl_AspectFace.hxx>
26 #include <OpenGl_AspectLine.hxx>
27 #include <OpenGl_AspectMarker.hxx>
28 #include <OpenGl_AspectText.hxx>
29 #include <OpenGl_Context.hxx>
30 #include <OpenGl_Element.hxx>
31 #include <OpenGl_GlCore20.hxx>
32 #include <OpenGl_GraphicDriver.hxx>
33 #include <OpenGl_ShaderManager.hxx>
34 #include <OpenGl_Workspace.hxx>
35 #include <OSD_Environment.hxx>
36 #include <OSD_File.hxx>
37 #include <Prs3d_Drawer.hxx>
38 #include <Prs3d_Presentation.hxx>
39 #include <Prs3d_Root.hxx>
40 #include <Prs3d_LineAspect.hxx>
41 #include <Prs3d_ShadingAspect.hxx>
42 #include <Select3D_SensitiveCurve.hxx>
43 #include <SelectMgr_EntityOwner.hxx>
44 #include <SelectMgr_Selection.hxx>
45 #include <TCollection_AsciiString.hxx>
46 #include <V3d_View.hxx>
47 #include <V3d_Viewer.hxx>
48 #include <ViewerTest_DoubleMapOfInteractiveAndName.hxx>
49 #include <ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName.hxx>
50 #include <OpenGl_Group.hxx>
52 extern Standard_Boolean VDisplayAISObject (const TCollection_AsciiString& theName,
53 const Handle(AIS_InteractiveObject)& theAISObj,
54 Standard_Boolean theReplaceIfExists = Standard_True);
55 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
59 //=======================================================================
60 //function : VUserDraw
61 //purpose : Checks availability and operation of UserDraw feature
62 //=======================================================================
64 class VUserDrawObj : public AIS_InteractiveObject
68 DEFINE_STANDARD_RTTI_INLINE(VUserDrawObj,AIS_InteractiveObject);
81 class Element : public OpenGl_Element
84 Handle(VUserDrawObj) myIObj;
87 Element (const Handle(VUserDrawObj)& theIObj) : myIObj (theIObj) {}
91 virtual void Render (const Handle(OpenGl_Workspace)& theWorkspace) const
94 myIObj->Render(theWorkspace);
97 virtual void Release (OpenGl_Context*)
103 DEFINE_STANDARD_ALLOC
107 // Virtual methods implementation
108 void Compute (const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
109 const Handle(Prs3d_Presentation)& thePresentation,
110 const Standard_Integer theMode) Standard_OVERRIDE;
112 void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
113 const Standard_Integer theMode) Standard_OVERRIDE;
115 // Called by VUserDrawElement
116 void Render(const Handle(OpenGl_Workspace)& theWorkspace) const;
120 friend class Element;
123 void VUserDrawObj::Compute(const Handle(PrsMgr_PresentationManager3d)& thePrsMgr,
124 const Handle(Prs3d_Presentation)& thePrs,
125 const Standard_Integer /*theMode*/)
129 Graphic3d_Vec4 aBndMin (myCoords[0], myCoords[1], myCoords[2], 1.0f);
130 Graphic3d_Vec4 aBndMax (myCoords[3], myCoords[4], myCoords[5], 1.0f);
131 Handle(OpenGl_Group) aGroup = Handle(OpenGl_Group)::DownCast (thePrs->NewGroup());
132 aGroup->SetMinMaxValues (aBndMin.x(), aBndMin.y(), aBndMin.z(),
133 aBndMax.x(), aBndMax.y(), aBndMax.z());
134 aGroup->SetGroupPrimitivesAspect (myDrawer->LineAspect()->Aspect());
135 VUserDrawObj::Element* anElem = new VUserDrawObj::Element (this);
136 aGroup->AddElement(anElem);
138 // invalidate bounding box of the scene
139 thePrsMgr->StructureManager()->Update();
142 void VUserDrawObj::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
143 const Standard_Integer /*theMode*/)
145 Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner(this);
146 Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 5);
147 aPnts->SetValue(1, gp_Pnt(myCoords[0], myCoords[1], myCoords[2]));
148 aPnts->SetValue(2, gp_Pnt(myCoords[3], myCoords[4], myCoords[2]));
149 aPnts->SetValue(3, gp_Pnt(myCoords[3], myCoords[4], myCoords[5]));
150 aPnts->SetValue(4, gp_Pnt(myCoords[0], myCoords[1], myCoords[5]));
151 aPnts->SetValue(5, gp_Pnt(myCoords[0], myCoords[1], myCoords[2]));
152 Handle(Select3D_SensitiveCurve) aSensitive = new Select3D_SensitiveCurve(anEntityOwner, aPnts);
153 theSelection->Add(aSensitive);
156 void VUserDrawObj::Render(const Handle(OpenGl_Workspace)& theWorkspace) const
158 // this sample does not use GLSL programs - make sure it is disabled
159 Handle(OpenGl_Context) aCtx = theWorkspace->GetGlContext();
160 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
161 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
163 // To test linking against OpenGl_Workspace and all aspect classes
164 const OpenGl_AspectMarker* aMA = theWorkspace->AspectMarker();
165 aMA->Aspect()->Type();
166 const OpenGl_AspectText* aTA = theWorkspace->AspectText();
167 aTA->Aspect()->Font();
168 OpenGl_Vec4 aColor = theWorkspace->LineColor();
170 #if !defined(GL_ES_VERSION_2_0)
171 // Finally draw something to make sure UserDraw really works
172 glPushAttrib(GL_ENABLE_BIT);
173 glDisable(GL_LIGHTING);
174 glColor4fv(aColor.GetData());
175 glBegin(GL_LINE_LOOP);
176 glVertex3f(myCoords[0], myCoords[1], myCoords[2]);
177 glVertex3f(myCoords[3], myCoords[4], myCoords[2]);
178 glVertex3f(myCoords[3], myCoords[4], myCoords[5]);
179 glVertex3f(myCoords[0], myCoords[1], myCoords[5]);
185 } // end of anonymous namespace
187 static Standard_Integer VUserDraw (Draw_Interpretor& di,
188 Standard_Integer argc,
191 Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
192 if (aContext.IsNull())
194 di << argv[0] << "Call 'vinit' before!\n";
198 Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast (aContext->CurrentViewer()->Driver());
199 if (aDriver.IsNull())
201 std::cerr << "Graphic driver not available.\n";
207 di << argv[0] << "Wrong number of arguments, only the object name expected\n";
211 TCollection_AsciiString aName (argv[1]);
212 VDisplayAISObject(aName, Handle(AIS_InteractiveObject)());
214 Handle(VUserDrawObj) anIObj = new VUserDrawObj();
215 VDisplayAISObject(aName, anIObj);
220 //==============================================================================
221 //function : VFeedback
223 //==============================================================================
225 static int VFeedback (Draw_Interpretor& theDI,
226 Standard_Integer /*theArgNb*/,
227 const char** /*theArgVec*/)
229 #if !defined(GL_ES_VERSION_2_0)
230 // get the active view
231 Handle(V3d_View) aView = ViewerTest::CurrentView();
234 std::cerr << "No active view. Please call vinit.\n";
238 unsigned int aBufferSize = 1024 * 1024;
241 size_t aBytes = (size_t )aBufferSize * sizeof(GLfloat);
242 if (aBytes / sizeof(GLfloat) != (size_t )aBufferSize)
244 // finito la commedia
245 std::cerr << "Can not allocate buffer - requested size ("
246 << (double(aBufferSize / (1024 * 1024)) * double(sizeof(GLfloat)))
247 << " MiB) is out of address space\n";
251 GLfloat* aBuffer = (GLfloat* )Standard::Allocate (aBytes);
254 // finito la commedia
255 std::cerr << "Can not allocate buffer with size ("
256 << (double(aBufferSize / (1024 * 1024)) * double(sizeof(GLfloat)))
261 glFeedbackBuffer ((GLsizei )aBufferSize, GL_2D, aBuffer);
262 glRenderMode (GL_FEEDBACK);
266 GLint aResult = glRenderMode (GL_RENDER);
271 void* aPtr = aBuffer;
272 Standard::Free (aPtr);
277 std::cout << "FeedBack result= " << aResult << "\n";
284 GLint aBitmapsNb = 0;
285 GLint aPassThrNb = 0;
286 GLint aUnknownNb = 0;
287 const GLint NODE_VALUES = 2; // GL_2D
288 for (GLint anIter = 0; anIter < aResult;)
290 const GLfloat aPos = aBuffer[anIter];
291 switch ((GLint )aPos)
297 anIter += 1 + NODE_VALUES;
300 case GL_LINE_RESET_TOKEN:
305 anIter += 1 + 2 * NODE_VALUES;
308 case GL_POLYGON_TOKEN:
310 const GLint aCount = (GLint )aBuffer[++anIter];
312 anIter += aCount * NODE_VALUES + 1;
317 else if (aCount == 4)
327 case GL_BITMAP_TOKEN:
328 case GL_DRAW_PIXEL_TOKEN:
329 case GL_COPY_PIXEL_TOKEN:
332 anIter += 1 + NODE_VALUES;
335 case GL_PASS_THROUGH_TOKEN:
338 anIter += 2; // header + value
349 void* aPtr = aBuffer;
350 Standard::Free (aPtr);
353 theDI << "Total nodes: " << aNodesNb << "\n"
354 << "Points: " << aPntNb << "\n"
355 << "Line segments: " << aLinesNb << "\n"
356 << "Triangles: " << aTriNb << "\n"
357 << "Quads: " << aQuadsNb << "\n"
358 << "Polygons: " << aPolyNb << "\n"
359 << "Bitmap tokens: " << aBitmapsNb << "\n"
360 << "Pass through: " << aPassThrNb << "\n"
361 << "UNKNOWN: " << aUnknownNb << "\n";
363 double aLen2D = double(aNodesNb * 2 + aPntNb + aLinesNb * 2 + (aTriNb + aQuadsNb + aPolyNb) * 2 + aBitmapsNb + aPassThrNb);
364 double aLen3D = double(aNodesNb * 3 + aPntNb + aLinesNb * 2 + (aTriNb + aQuadsNb + aPolyNb) * 2 + aBitmapsNb + aPassThrNb);
365 double aLen3D_rgba = double(aNodesNb * 7 + aPntNb + aLinesNb * 2 + (aTriNb + aQuadsNb + aPolyNb) * 2 + aBitmapsNb + aPassThrNb);
366 theDI << "Buffer size GL_2D: " << aLen2D * double(sizeof(GLfloat)) / double(1024 * 1024) << " MiB\n"
367 << "Buffer size GL_3D: " << aLen3D * double(sizeof(GLfloat)) / double(1024 * 1024) << " MiB\n"
368 << "Buffer size GL_3D_COLOR: " << aLen3D_rgba * double(sizeof(GLfloat)) / double(1024 * 1024) << " MiB\n";
373 std::cout << "Command is unsupported on current platform.\n";
378 //==============================================================================
379 //function : VImmediateFront
381 //==============================================================================
383 static int VImmediateFront (Draw_Interpretor& /*theDI*/,
384 Standard_Integer theArgNb,
385 const char** theArgVec)
388 Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
389 if (aContextAIS.IsNull())
391 std::cerr << "No active view. Please call vinit.\n";
395 Handle(Graphic3d_GraphicDriver) aDriver = aContextAIS->CurrentViewer()->Driver();
397 if (aDriver.IsNull())
399 std::cerr << "Graphic driver not available.\n";
405 std::cerr << "Wrong number of arguments.\n";
409 ViewerTest::CurrentView()->View()->SetImmediateModeDrawToFront (atoi(theArgVec[1]) != 0);
414 //! Search the info from the key.
415 inline TCollection_AsciiString searchInfo (const TColStd_IndexedDataMapOfStringString& theDict,
416 const TCollection_AsciiString& theKey)
418 for (TColStd_IndexedDataMapOfStringString::Iterator anIter (theDict); anIter.More(); anIter.Next())
420 if (TCollection_AsciiString::IsSameString (anIter.Key(), theKey, Standard_False))
422 return anIter.Value();
425 return TCollection_AsciiString();
428 //==============================================================================
431 //==============================================================================
433 static int VGlInfo (Draw_Interpretor& theDI,
434 Standard_Integer theArgNb,
435 const char** theArgVec)
437 // get the active view
438 Handle(V3d_View) aView = ViewerTest::CurrentView();
441 std::cerr << "No active view. Please call vinit.\n";
445 Standard_Integer anArgIter = 1;
446 Graphic3d_DiagnosticInfo anInfoLevel = Graphic3d_DiagnosticInfo_Basic;
449 TCollection_AsciiString aName (theArgVec[1]);
451 if (aName == "-short")
454 anInfoLevel = Graphic3d_DiagnosticInfo_Short;
456 else if (aName == "-basic")
459 anInfoLevel = Graphic3d_DiagnosticInfo_Basic;
461 else if (aName == "-complete"
465 anInfoLevel = Graphic3d_DiagnosticInfo_Complete;
469 TColStd_IndexedDataMapOfStringString aDict;
470 if (anArgIter >= theArgNb)
472 aView->DiagnosticInformation (aDict, anInfoLevel);
473 TCollection_AsciiString aText;
474 for (TColStd_IndexedDataMapOfStringString::Iterator aValueIter (aDict); aValueIter.More(); aValueIter.Next())
476 if (!aText.IsEmpty())
480 aText += TCollection_AsciiString(" ") + aValueIter.Key() + ": " + aValueIter.Value();
483 theDI << "OpenGL info:\n"
488 const Standard_Boolean isList = theArgNb >= 3;
489 aView->DiagnosticInformation (aDict, Graphic3d_DiagnosticInfo_Complete);
490 for (; anArgIter < theArgNb; ++anArgIter)
492 TCollection_AsciiString aName (theArgVec[anArgIter]);
494 TCollection_AsciiString aValue;
495 if (aName.Search ("VENDOR") != -1)
497 aValue = searchInfo (aDict, "GLvendor");
499 else if (aName.Search ("RENDERER") != -1)
501 aValue = searchInfo (aDict, "GLdevice");
503 else if (aName.Search ("SHADING_LANGUAGE_VERSION") != -1
504 || aName.Search ("GLSL") != -1)
506 aValue = searchInfo (aDict, "GLSLversion");
508 else if (aName.Search ("VERSION") != -1)
510 aValue = searchInfo (aDict, "GLversion");
512 else if (aName.Search ("EXTENSIONS") != -1)
514 aValue = searchInfo (aDict, "GLextensions");
518 std::cerr << "Unknown key '" << aName.ToCString() << "'\n";
524 theDI << "{" << aValue << "} ";
536 //==============================================================================
537 //function : VShaderProg
538 //purpose : Sets the pair of vertex and fragment shaders for the object
539 //==============================================================================
540 static Standard_Integer VShaderProg (Draw_Interpretor& /*theDI*/,
541 Standard_Integer theArgNb,
542 const char** theArgVec)
544 Handle(AIS_InteractiveContext) aCtx = ViewerTest::GetAISContext();
547 std::cerr << "Use 'vinit' command before " << theArgVec[0] << "\n";
550 else if (theArgNb < 2)
552 std::cerr << theArgVec[0] << " syntax error: lack of arguments\n";
556 TCollection_AsciiString aLastArg (theArgVec[theArgNb - 1]);
557 aLastArg.LowerCase();
558 const Standard_Boolean toTurnOff = aLastArg == "off";
559 Standard_Integer anArgsNb = theArgNb - 1;
560 Handle(Graphic3d_ShaderProgram) aProgram;
562 && aLastArg == "phong")
564 const TCollection_AsciiString& aShadersRoot = Graphic3d_ShaderProgram::ShadersFolder();
565 if (aShadersRoot.IsEmpty())
567 std::cerr << "Both environment variables CSF_ShadersDirectory and CASROOT are undefined!\n"
568 << "At least one should be defined to load Phong program.\n";
572 const TCollection_AsciiString aSrcVert = aShadersRoot + "/PhongShading.vs";
573 const TCollection_AsciiString aSrcFrag = aShadersRoot + "/PhongShading.fs";
575 if (!aSrcVert.IsEmpty()
576 && !OSD_File (aSrcVert).Exists())
578 std::cerr << "Error: PhongShading.vs is not found\n";
581 if (!aSrcFrag.IsEmpty()
582 && !OSD_File (aSrcFrag).Exists())
584 std::cerr << "Error: PhongShading.fs is not found\n";
588 aProgram = new Graphic3d_ShaderProgram();
589 aProgram->AttachShader (Graphic3d_ShaderObject::CreateFromFile (Graphic3d_TOS_VERTEX, aSrcVert));
590 aProgram->AttachShader (Graphic3d_ShaderObject::CreateFromFile (Graphic3d_TOS_FRAGMENT, aSrcFrag));
593 && aProgram.IsNull())
597 std::cerr << theArgVec[0] << " syntax error: lack of arguments\n";
601 const TCollection_AsciiString aSrcVert = theArgVec[theArgNb - 2];
602 const TCollection_AsciiString aSrcFrag = theArgVec[theArgNb - 1];
603 if (!aSrcVert.IsEmpty()
604 && !OSD_File (aSrcVert).Exists())
606 std::cerr << "Non-existing vertex shader source\n";
609 if (!aSrcFrag.IsEmpty()
610 && !OSD_File (aSrcFrag).Exists())
612 std::cerr << "Non-existing fragment shader source\n";
616 aProgram = new Graphic3d_ShaderProgram();
617 aProgram->AttachShader (Graphic3d_ShaderObject::CreateFromFile (Graphic3d_TOS_VERTEX, aSrcVert));
618 aProgram->AttachShader (Graphic3d_ShaderObject::CreateFromFile (Graphic3d_TOS_FRAGMENT, aSrcFrag));
619 anArgsNb = theArgNb - 2;
622 Handle(AIS_InteractiveObject) anIO;
624 || *theArgVec[1] == '*')
626 for (ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName anIter (GetMapOfAIS());
627 anIter.More(); anIter.Next())
629 anIO = Handle(AIS_InteractiveObject)::DownCast (anIter.Key1());
635 if (!anIO->Attributes()->HasOwnShadingAspect())
637 Handle(Prs3d_ShadingAspect) aNewAspect = new Prs3d_ShadingAspect();
638 *aNewAspect->Aspect() = *anIO->Attributes()->ShadingAspect()->Aspect();
639 aNewAspect->Aspect()->SetShaderProgram (aProgram);
640 anIO->Attributes()->SetShadingAspect (aNewAspect);
641 aCtx->Redisplay (anIO, Standard_False);
645 anIO->Attributes()->SetShaderProgram (aProgram, Graphic3d_ASPECT_FILL_AREA);
646 anIO->SynchronizeAspects();
649 aCtx->UpdateCurrentViewer();
653 for (Standard_Integer anArgIter = 1; anArgIter < anArgsNb; ++anArgIter)
655 const TCollection_AsciiString aName (theArgVec[anArgIter]);
656 if (!GetMapOfAIS().IsBound2 (aName))
658 std::cerr << "Warning: " << aName.ToCString() << " is not displayed\n";
661 anIO = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aName));
664 std::cerr << "Warning: " << aName.ToCString() << " is not an AIS object\n";
668 if (!anIO->Attributes()->HasOwnShadingAspect())
670 Handle(Prs3d_ShadingAspect) aNewAspect = new Prs3d_ShadingAspect();
671 *aNewAspect->Aspect() = *anIO->Attributes()->ShadingAspect()->Aspect();
672 aNewAspect->Aspect()->SetShaderProgram (aProgram);
673 anIO->Attributes()->SetShadingAspect (aNewAspect);
674 aCtx->Redisplay (anIO, Standard_False);
678 anIO->Attributes()->SetShaderProgram (aProgram, Graphic3d_ASPECT_FILL_AREA);
679 anIO->SynchronizeAspects();
683 aCtx->UpdateCurrentViewer();
687 //=======================================================================
688 //function : OpenGlCommands
690 //=======================================================================
692 void ViewerTest::OpenGlCommands(Draw_Interpretor& theCommands)
694 const char* aGroup ="Commands for low-level TKOpenGl features";
696 theCommands.Add("vuserdraw",
697 "vuserdraw : name - simulates drawing with help of UserDraw",
698 __FILE__, VUserDraw, aGroup);
699 theCommands.Add("vfeedback",
700 "vfeedback : perform test GL feedback rendering",
701 __FILE__, VFeedback, aGroup);
702 theCommands.Add("vimmediatefront",
703 "vimmediatefront : render immediate mode to front buffer or to back buffer",
704 __FILE__, VImmediateFront, aGroup);
705 theCommands.Add("vglinfo",
706 "vglinfo [-short|-basic|-complete]"
707 "\n\t\t: [GL_VENDOR] [GL_RENDERER] [GL_VERSION]"
708 "\n\t\t: [GL_SHADING_LANGUAGE_VERSION] [GL_EXTENSIONS]"
709 "\n\t\t: print OpenGL info",
710 __FILE__, VGlInfo, aGroup);
711 theCommands.Add("vshaderprog",
712 " 'vshaderprog [name] pathToVertexShader pathToFragmentShader'"
713 "\n\t\t: or 'vshaderprog [name] off' to disable GLSL program"
714 "\n\t\t: or 'vshaderprog [name] phong' to enable per-pixel lighting calculations"
715 "\n\t\t: * might be used to specify all displayed objects",
716 __FILE__, VShaderProg, aGroup);