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