Salome HOME
Issue #604 Creation of an unexpected line in the Sketcher
[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, 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
372   // Disable frustum culling for this object by marking it as mutable
373   aGroup->Structure()->SetMutable(true);
374   //aGroup->AddPrimitiveArray(myPntArray);
375 }
376
377
378
379 void SketcherPrs_SymbolPrs::ComputeSelection(const Handle(SelectMgr_Selection)& aSelection,
380                                             const Standard_Integer aMode)
381 {
382   ClearSelected();
383   if ((aMode == 0) || (aMode == SketcherPrs_Tools::Sel_Constraint)) {
384     for (int i = 1; i <= mySPoints.Length(); i++)
385       aSelection->Add(mySPoints.Value(i));
386   }
387 }
388
389
390 void SketcherPrs_SymbolPrs::Render(const Handle(OpenGl_Workspace)& theWorkspace) const
391 {
392   const OpenGl_AspectMarker* anAspectMarker = theWorkspace->AspectMarker(Standard_True);
393   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
394   Handle(OpenGl_View) aView = theWorkspace->ActiveView();
395   
396   double aScale = aView->Camera()->Scale();
397   if (!updatePoints(MyDist * aScale))
398     return;
399
400   Handle(Graphic3d_Buffer) aAttribs = myPntArray->Attributes();
401
402   if (myVboAttribs.IsNull()) {
403     myVboAttribs = new SketcherPrs_VertexBuffer(*aAttribs);
404   }
405
406   if (!myVboAttribs->init(aCtx, 0, aAttribs->NbElements, aAttribs->Data(), GL_NONE, aAttribs->Stride)) {
407     myVboAttribs->Release (aCtx.operator->());
408     myVboAttribs.Nullify();
409     return;
410   }
411     
412   Handle(OpenGl_Texture) aTextureBack = theWorkspace->DisableTexture();
413
414   const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes(aCtx);
415       
416   if (!aSpriteNorm.IsNull() && !aSpriteNorm->IsDisplayList()) {
417     const bool toHilight = (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT) != 0;
418     const Handle(OpenGl_PointSprite)& aSprite = (toHilight && anAspectMarker->SpriteHighlightRes(aCtx)->IsValid())
419                                               ? anAspectMarker->SpriteHighlightRes(aCtx)
420                                               : aSpriteNorm;
421     theWorkspace->EnableTexture (aSprite);
422     aCtx->ShaderManager()->BindProgram(anAspectMarker, aSprite, Standard_False, Standard_False, anAspectMarker->ShaderProgramRes(aCtx));
423     const TEL_COLOUR* aLineColor  =  &anAspectMarker->Color();
424     if (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT)
425       aLineColor = theWorkspace->HighlightColor;
426
427     if (toHilight)
428       aCtx->core11fwd->glDisable (GL_LIGHTING);
429     else
430       aCtx->core11fwd->glEnable (GL_LIGHTING);
431
432     aCtx->SetColor4fv(*(const OpenGl_Vec4* )(aLineColor->rgb));
433
434
435     myVboAttribs->BindAllAttributes(aCtx);
436     // Textured markers will be drawn with the point sprites
437     aCtx->SetPointSize (anAspectMarker->MarkerSize());
438     aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
439     aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
440
441     aCtx->core11fwd->glEnable (GL_BLEND);
442     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
443
444     aCtx->core11fwd->glDrawArrays (0, 0, myVboAttribs->GetElemsNb());
445
446     aCtx->core11fwd->glDisable (GL_BLEND);
447     aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
448     aCtx->SetPointSize (1.0f);
449   }
450   theWorkspace->EnableTexture (aTextureBack);
451   aCtx->BindProgram (NULL);
452
453   // Update selection position only if there is no selected object
454   // because it can corrupt selection of other objects
455   if ((GetContext()->NbCurrents() == 0) && (GetContext()->NbSelected() == 0))
456   {
457     GetContext()->MainSelector()->RebuildSensitivesTree (this);
458     GetContext()->MainSelector()->RebuildObjectsTree (false);
459   }
460 }
461
462
463 void SketcherPrs_SymbolPrs::Release (OpenGl_Context* theContext)
464 {
465   if (!myVboAttribs.IsNull()) {
466     if (theContext) {
467       theContext->DelayedRelease (myVboAttribs);
468     }
469     myVboAttribs.Nullify();
470   }
471 }
472
473 void SketcherPrs_SymbolPrs::drawShape(const std::shared_ptr<GeomAPI_Shape>& theShape, 
474                                       const Handle(Prs3d_Presentation)& thePrs) const
475 {
476   if (theShape->isEdge()) {
477     std::shared_ptr<GeomAPI_Curve> aCurve = 
478       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(theShape));
479     if (aCurve->isLine()) {
480       GeomAdaptor_Curve aCurv(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
481       StdPrs_Curve::Add(thePrs, aCurv, myDrawer);
482     } else {
483       GeomAdaptor_Curve aAdaptor(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
484       StdPrs_DeflectionCurve::Add(thePrs,aAdaptor,myDrawer);
485     }
486   } else if (theShape->isVertex()) {
487     std::shared_ptr<GeomAPI_Vertex> aVertex = 
488       std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(theShape));
489     std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
490     Handle(Geom_CartesianPoint) aPoint = new Geom_CartesianPoint(aPnt->impl<gp_Pnt>());
491     StdPrs_Point::Add(thePrs, aPoint, myDrawer);
492   }
493 }
494
495 void SketcherPrs_SymbolPrs::drawListOfShapes(const std::shared_ptr<ModelAPI_AttributeRefList>& theListAttr, 
496                                              const Handle(Prs3d_Presentation)& thePrs) const
497 {
498   int aNb = theListAttr->size();
499   if (aNb == 0)
500     return;
501   int i;
502   ObjectPtr aObj;
503   for (i = 0; i < aNb; i++) {
504     aObj = theListAttr->object(i);
505     std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(aObj);
506     if (aShape.get() != NULL)
507       drawShape(aShape, thePrs);
508   }
509 }
510
511 void SketcherPrs_SymbolPrs::BoundingBox (Bnd_Box& theBndBox)
512 {
513   Select3D_BndBox3d aTmpBox;
514   for (Select3D_EntitySequenceIter aPntIter (mySPoints); aPntIter.More(); aPntIter.Next())
515   {
516     const Handle(Select3D_SensitiveEntity)& anEnt = aPntIter.Value();
517     aTmpBox.Combine (anEnt->BoundingBox());
518   }
519
520   theBndBox.Update (aTmpBox.CornerMin().x(), aTmpBox.CornerMin().y(), aTmpBox.CornerMin().z(),
521                     aTmpBox.CornerMax().x(), aTmpBox.CornerMax().y(), aTmpBox.CornerMax().z());
522 }
523