Salome HOME
Prepare version 1.2.1: quick fix for iteration 2 release
[modules/shaper.git] / src / SketcherPrs / SketcherPrs_SymbolPrs.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        SketcherPrs_SymbolPrs.cpp
4 // Created:     12 March 2015
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "SketcherPrs_SymbolPrs.h"
8 #include "SketcherPrs_Tools.h"
9 #include "SketcherPrs_PositionMgr.h"
10
11 #include <GeomAPI_Edge.h>
12 #include <GeomAPI_Vertex.h>
13 #include <GeomAPI_Curve.h>
14
15 #include <Events_Error.h>
16
17 #include <Graphic3d_ArrayOfSegments.hxx>
18 #include <Graphic3d_BndBox4f.hxx>
19
20 #include <SelectMgr_Selection.hxx>
21 #include <SelectMgr_SelectionManager.hxx>
22 #include <Select3D_SensitivePoint.hxx>
23 #include <TopLoc_Location.hxx>
24 #include <AIS_InteractiveContext.hxx>
25 #include <V3d_Viewer.hxx>
26 #include <Prs3d_Root.hxx>
27 #include <Geom_CartesianPoint.hxx>
28 #include <GeomAdaptor_Curve.hxx>
29 #include <StdPrs_DeflectionCurve.hxx>
30 #include <StdPrs_Point.hxx>
31 #include <StdPrs_Curve.hxx>
32
33 #include <OpenGl_Element.hxx>
34 #include <OpenGl_GraphicDriver.hxx>
35 #include <OpenGl_Context.hxx>
36 #include <OpenGl_View.hxx>
37 #include <OpenGl_PointSprite.hxx>
38 #include <OpenGl_VertexBuffer.hxx>
39 #include <OpenGl_ShaderManager.hxx>
40 #include <OpenGl_VertexBufferCompat.hxx>
41 #include <OpenGl_GraphicDriver.hxx>
42
43 #ifdef WIN32
44 # define FSEP "\\"
45 #else
46 # define FSEP "/"
47 #endif
48
49 /// Step between icons
50 static const double MyDist = 0.02;
51
52 /// Function to convert opengl data type
53 GLenum toGlDataType (const Graphic3d_TypeOfData theType, GLint& theNbComp)
54 {
55   switch (theType) {
56     case Graphic3d_TOD_USHORT:
57       theNbComp = 1;
58       return GL_UNSIGNED_SHORT;
59     case Graphic3d_TOD_UINT:
60       theNbComp = 1;
61       return GL_UNSIGNED_INT;
62     case Graphic3d_TOD_VEC2:
63       theNbComp = 2;
64       return GL_FLOAT;
65     case Graphic3d_TOD_VEC3:
66       theNbComp = 3;
67       return GL_FLOAT;
68     case Graphic3d_TOD_VEC4:
69       theNbComp = 4;
70       return GL_FLOAT;
71     case Graphic3d_TOD_VEC4UB:
72       theNbComp = 4;
73       return GL_UNSIGNED_BYTE;
74   }
75   theNbComp = 0;
76   return GL_NONE;
77 }
78
79
80 //*******************************************************************
81 //! Auxiliary class for Vertex buffer with interleaved attributes.
82 class SketcherPrs_VertexBuffer : public OpenGl_VertexBuffer
83 {
84
85 public:
86
87   //! Create uninitialized VBO..
88   SketcherPrs_VertexBuffer (const Graphic3d_Attribute* theAttribs,
89                         const Standard_Integer     theStride)
90   : Stride (theStride), NbAttributes(1)
91   {
92
93     memcpy (Attribs, theAttribs, sizeof(Graphic3d_Attribute) * NbAttributes);
94   }
95
96   //! Create uninitialized VBO.
97   SketcherPrs_VertexBuffer (const Graphic3d_Buffer& theAttribs)
98   : Stride (theAttribs.Stride), NbAttributes(1)
99   {
100     memcpy (Attribs, theAttribs.AttributesArray(), sizeof(Graphic3d_Attribute) * NbAttributes);
101   }
102
103   virtual bool HasColorAttribute() const
104   {
105     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
106       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
107       if (anAttrib.Id == Graphic3d_TOA_COLOR) {
108         return true;
109       }
110     }
111     return false;
112   }
113
114   virtual bool HasNormalAttribute() const
115   {
116     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
117       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
118       if (anAttrib.Id == Graphic3d_TOA_NORM) {
119         return true;
120       }
121     }
122     return false;
123   }
124
125   virtual void BindPositionAttribute (const Handle(OpenGl_Context)& theGlCtx) const
126   {
127     if (!OpenGl_VertexBuffer::IsValid()) {
128       return;
129     }
130
131     OpenGl_VertexBuffer::Bind (theGlCtx);
132     GLint aNbComp;
133     const GLubyte* anOffset = OpenGl_VertexBuffer::myOffset;
134     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
135       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
136       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
137       if (aDataType == GL_NONE) {
138         continue;
139       } else if (anAttrib.Id == Graphic3d_TOA_POS) {
140         OpenGl_VertexBuffer::bindAttribute (theGlCtx, Graphic3d_TOA_POS, aNbComp, aDataType, Stride, anOffset);
141         break;
142       }
143
144       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
145     }
146   }
147
148   virtual void BindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
149   {
150     if (!OpenGl_VertexBuffer::IsValid())
151       return;
152
153     OpenGl_VertexBuffer::Bind (theGlCtx);
154     GLint aNbComp;
155     const GLubyte* anOffset = OpenGl_VertexBuffer::myOffset;
156     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
157     {
158       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
159       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
160       if (aDataType == GL_NONE)
161         continue;
162
163       OpenGl_VertexBuffer::bindAttribute (theGlCtx, anAttrib.Id, aNbComp, aDataType, Stride, anOffset);
164       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
165     }
166   }
167
168   virtual void UnbindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
169   {
170     if (!OpenGl_VertexBuffer::IsValid())
171       return;
172     OpenGl_VertexBuffer::Unbind (theGlCtx);
173
174     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
175       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
176       OpenGl_VertexBuffer::unbindAttribute (theGlCtx, anAttrib.Id);
177     }
178   }
179
180 public:
181
182   Graphic3d_Attribute Attribs[1];
183   Standard_Integer    Stride;
184   Standard_Integer NbAttributes;
185 };
186
187 //**************************************************************
188 //! Redefinition of OpenGl_Element
189 class SketcherPrs_Element: public OpenGl_Element
190 {
191 public:
192   SketcherPrs_Element(const Handle(SketcherPrs_SymbolPrs)& theObj) : 
193   OpenGl_Element(), myObj(theObj) {}
194
195   virtual void Render (const Handle(OpenGl_Workspace)& theWorkspace) const
196   {
197     if (!myObj.IsNull())
198       myObj->Render(theWorkspace);
199   }
200
201   virtual void Release (OpenGl_Context* theContext) 
202   {
203     if (!myObj.IsNull())
204       myObj->Release(theContext);
205   }
206
207 private:
208   Handle(SketcherPrs_SymbolPrs) myObj;
209 };
210
211
212 //**************************************************************
213 //! Definition of call back
214 OpenGl_Element* SymbolPrsCallBack(const CALL_DEF_USERDRAW * theUserDraw)
215 {
216   Handle(SketcherPrs_SymbolPrs) anIObj = (SketcherPrs_SymbolPrs*)theUserDraw->Data;
217   if (anIObj.IsNull()) {
218     std::cout << "VUserDrawCallback error: null object passed, the custom scene element will not be rendered" << std::endl;
219   }
220   return new SketcherPrs_Element(anIObj);
221 }
222
223
224 //*****************************************************************************
225 IMPLEMENT_STANDARD_HANDLE(SketcherPrs_SymbolPrs, AIS_InteractiveObject);
226 IMPLEMENT_STANDARD_RTTIEXT(SketcherPrs_SymbolPrs, AIS_InteractiveObject);
227
228
229 std::map<const char*, Handle(Image_AlienPixMap)> SketcherPrs_SymbolPrs::myIconsMap;
230
231
232 SketcherPrs_SymbolPrs::SketcherPrs_SymbolPrs(ModelAPI_Feature* theConstraint, 
233                                              const std::shared_ptr<GeomAPI_Ax3>& thePlane)
234  : AIS_InteractiveObject(), myConstraint(theConstraint), myPlane(thePlane)
235 {
236   SetAutoHilight(Standard_False);
237 }
238
239 SketcherPrs_SymbolPrs::~SketcherPrs_SymbolPrs()
240 {
241   SketcherPrs_PositionMgr* aMgr = SketcherPrs_PositionMgr::get();
242   aMgr->deleteConstraint(this);
243 }
244
245
246
247 Handle(Image_AlienPixMap) SketcherPrs_SymbolPrs::icon()
248 {
249   if (myIconsMap.count(iconName()) == 1) {
250     return myIconsMap[iconName()];
251   }
252   char* aEnv = getenv("NEWGEOM_ROOT_DIR");
253   if (aEnv != NULL) {
254     TCollection_AsciiString aFile(aEnv);
255     aFile+=FSEP;
256     aFile+="resources";
257     aFile += FSEP;
258     aFile += iconName();
259     Handle(Image_AlienPixMap) aPixMap = new Image_AlienPixMap();
260     if (aPixMap->Load(aFile)) {
261       myIconsMap[iconName()] = aPixMap;
262       return aPixMap;
263     }
264   }
265   static const char aMsg[] = "Error! constraint images are not found";
266   cout<<aMsg<<endl;
267   Events_Error::send(aMsg);
268   myIconsMap[iconName()] = Handle(Image_AlienPixMap)();
269   return Handle(Image_AlienPixMap)();
270 }
271
272 void SketcherPrs_SymbolPrs::ClearSelected()
273 {
274   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( NULL );  
275   if( !aSelectionPrs.IsNull() ) {
276     aSelectionPrs->Clear(); 
277   }
278 }
279
280 void SketcherPrs_SymbolPrs::prepareAspect()
281 {
282   if (myAspect.IsNull()) {
283     Handle(Image_AlienPixMap) aIcon = icon();
284     if (aIcon.IsNull()) 
285       myAspect = new Graphic3d_AspectMarker3d();
286     else
287       myAspect = new Graphic3d_AspectMarker3d(aIcon);
288   }
289 }
290
291 void SketcherPrs_SymbolPrs::addLine(const Handle(Graphic3d_Group)& theGroup, std::string theAttrName) const
292 {
293   ObjectPtr aObj = SketcherPrs_Tools::getResult(myConstraint, theAttrName);
294   std::shared_ptr<GeomAPI_Shape> aLine = SketcherPrs_Tools::getShape(aObj);
295   if (aLine.get() == NULL)
296     return;
297   std::shared_ptr<GeomAPI_Edge> aEdge = std::shared_ptr<GeomAPI_Edge>(new GeomAPI_Edge(aLine));
298
299   std::shared_ptr<GeomAPI_Pnt> aPnt1 = aEdge->firstPoint();
300   std::shared_ptr<GeomAPI_Pnt> aPnt2 = aEdge->lastPoint();
301
302   Handle(Graphic3d_ArrayOfSegments) aLines = new Graphic3d_ArrayOfSegments(2, 1);
303   aLines->AddVertex(aPnt1->impl<gp_Pnt>());
304   aLines->AddVertex(aPnt2->impl<gp_Pnt>());
305   theGroup->AddPrimitiveArray(aLines);
306 }
307
308 void SketcherPrs_SymbolPrs::HilightSelected(const Handle(PrsMgr_PresentationManager3d)& thePM, 
309                                            const SelectMgr_SequenceOfOwner& theOwners)
310 {
311
312   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( thePM );
313   aSelectionPrs->Clear();
314   drawLines(aSelectionPrs, Quantity_NOC_WHITE);
315
316   aSelectionPrs->SetDisplayPriority(9);
317   aSelectionPrs->Display();
318   thePM->Highlight(this);
319 }
320
321 void SketcherPrs_SymbolPrs::HilightOwnerWithColor(const Handle(PrsMgr_PresentationManager3d)& thePM, 
322                                                  const Quantity_NameOfColor theColor, const Handle(SelectMgr_EntityOwner)& theOwner)
323 {
324   thePM->Color(this, theColor);
325
326   Handle( Prs3d_Presentation ) aHilightPrs = GetHilightPresentation( thePM );
327   aHilightPrs->Clear();
328   drawLines(aHilightPrs, theColor);
329
330   if (thePM->IsImmediateModeOn())
331     thePM->AddToImmediateList(aHilightPrs);
332 }
333
334 void SketcherPrs_SymbolPrs::Compute(const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
335                                    const Handle(Prs3d_Presentation)& thePresentation, 
336                                    const Standard_Integer theMode)
337 {
338   prepareAspect();
339
340   Handle(AIS_InteractiveContext) aCtx = GetContext();
341   Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast(aCtx->CurrentViewer()->Driver());
342   if (!aDriver.IsNull()) {
343     // register the custom element factory function
344     aDriver->UserDrawCallback() = SymbolPrsCallBack;
345   }
346
347   if (!updatePoints(20))
348     return;
349
350   int aNbVertex = myPntArray->VertexNumber();
351   if (myOwner.IsNull()) {
352     myOwner = new SelectMgr_EntityOwner(this);
353   }
354
355   mySPoints.Clear();
356   for (int i = 1; i <= aNbVertex; i++) {
357     Handle(SketcherPrs_SensitivePoint) aSP = new SketcherPrs_SensitivePoint(myOwner, myPntArray, i);
358     mySPoints.Append(aSP);
359   }
360
361   Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup(thePresentation);
362   aGroup->SetPrimitivesAspect(myAspect);
363
364   Graphic3d_BndBox4f& aBnd = aGroup->ChangeBoundingBox();
365   gp_Pnt aVert;
366   aBnd.Clear();
367   for (int i = 1; i <= myPntArray->ItemNumber(); i++) {
368     aVert = myPntArray->Vertice(i);
369     aBnd.Add (Graphic3d_Vec4((float)aVert.X(), (float)aVert.Y(), (float)aVert.Z(), 1.0f));
370   }
371
372   aGroup->UserDraw(this, true);
373   //aGroup->AddPrimitiveArray(myPntArray);
374 }
375
376
377
378 void SketcherPrs_SymbolPrs::ComputeSelection(const Handle(SelectMgr_Selection)& aSelection,
379                                             const Standard_Integer aMode)
380 {
381   ClearSelected();
382   if ((aMode == 0) || (aMode == SketcherPrs_Tools::Sel_Constraint)) {
383     for (int i = 1; i <= mySPoints.Length(); i++)
384       aSelection->Add(mySPoints.Value(i));
385   }
386 }
387
388
389 void SketcherPrs_SymbolPrs::Render(const Handle(OpenGl_Workspace)& theWorkspace) const
390 {
391   const OpenGl_AspectMarker* anAspectMarker = theWorkspace->AspectMarker(Standard_True);
392   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
393   Handle(OpenGl_View) aView = theWorkspace->ActiveView();
394   
395   double aScale = aView->Camera()->Scale();
396   if (!updatePoints(MyDist * aScale))
397     return;
398
399   Handle(Graphic3d_Buffer) aAttribs = myPntArray->Attributes();
400
401   if (myVboAttribs.IsNull()) {
402     myVboAttribs = new SketcherPrs_VertexBuffer(*aAttribs);
403   }
404
405   if (!myVboAttribs->init(aCtx, 0, aAttribs->NbElements, aAttribs->Data(), GL_NONE, aAttribs->Stride)) {
406     myVboAttribs->Release (aCtx.operator->());
407     myVboAttribs.Nullify();
408     return;
409   }
410     
411   Handle(OpenGl_Texture) aTextureBack = theWorkspace->DisableTexture();
412
413   const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes(aCtx);
414       
415   if (!aSpriteNorm.IsNull() && !aSpriteNorm->IsDisplayList()) {
416     const bool toHilight = (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT) != 0;
417     const Handle(OpenGl_PointSprite)& aSprite = (toHilight && anAspectMarker->SpriteHighlightRes(aCtx)->IsValid())
418                                               ? anAspectMarker->SpriteHighlightRes(aCtx)
419                                               : aSpriteNorm;
420     theWorkspace->EnableTexture (aSprite);
421     aCtx->ShaderManager()->BindProgram(anAspectMarker, aSprite, Standard_False, Standard_False, anAspectMarker->ShaderProgramRes(aCtx));
422     const TEL_COLOUR* aLineColor  =  &anAspectMarker->Color();
423     if (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT)
424       aLineColor = theWorkspace->HighlightColor;
425
426     aCtx->SetColor4fv(*(const OpenGl_Vec4* )(aLineColor->rgb));
427
428
429     myVboAttribs->BindAllAttributes(aCtx);
430     // Textured markers will be drawn with the point sprites
431     aCtx->SetPointSize (anAspectMarker->MarkerSize());
432     aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
433     aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
434
435     aCtx->core11fwd->glEnable (GL_BLEND);
436     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
437
438     aCtx->core11fwd->glDrawArrays (0, 0, myVboAttribs->GetElemsNb());
439
440     aCtx->core11fwd->glDisable (GL_BLEND);
441     aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
442     aCtx->SetPointSize (1.0f);
443   }
444   theWorkspace->EnableTexture (aTextureBack);
445   aCtx->BindProgram (NULL);
446
447   // Update selection position only if there is no selected object
448   // because it can corrupt selection of other objects
449   if ((GetContext()->NbCurrents() == 0) && (GetContext()->NbSelected() == 0))
450     GetContext()->RecomputeSelectionOnly(this);
451 }
452
453
454 void SketcherPrs_SymbolPrs::Release (OpenGl_Context* theContext)
455 {
456   if (!myVboAttribs.IsNull()) {
457     if (theContext) {
458       theContext->DelayedRelease (myVboAttribs);
459     }
460     myVboAttribs.Nullify();
461   }
462 }
463
464 void SketcherPrs_SymbolPrs::drawShape(const std::shared_ptr<GeomAPI_Shape>& theShape, 
465                                       const Handle(Prs3d_Presentation)& thePrs) const
466 {
467   if (theShape->isEdge()) {
468     std::shared_ptr<GeomAPI_Curve> aCurve = 
469       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(theShape));
470     if (aCurve->isLine()) {
471       GeomAdaptor_Curve aCurv(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
472       StdPrs_Curve::Add(thePrs, aCurv, myDrawer);
473     } else {
474       GeomAdaptor_Curve aAdaptor(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
475       StdPrs_DeflectionCurve::Add(thePrs,aAdaptor,myDrawer);
476     }
477   } else if (theShape->isVertex()) {
478     std::shared_ptr<GeomAPI_Vertex> aVertex = 
479       std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(theShape));
480     std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
481     Handle(Geom_CartesianPoint) aPoint = new Geom_CartesianPoint(aPnt->impl<gp_Pnt>());
482     StdPrs_Point::Add(thePrs, aPoint, myDrawer);
483   }
484 }
485
486 void SketcherPrs_SymbolPrs::drawListOfShapes(const std::shared_ptr<ModelAPI_AttributeRefList>& theListAttr, 
487                                              const Handle(Prs3d_Presentation)& thePrs) const
488 {
489   int aNb = theListAttr->size();
490   if (aNb == 0)
491     return;
492   int i;
493   ObjectPtr aObj;
494   for (i = 0; i < aNb; i++) {
495     aObj = theListAttr->object(i);
496     std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(aObj);
497     if (aShape.get() != NULL)
498       drawShape(aShape, thePrs);
499   }
500 }
501