Salome HOME
Make working possible when constraint images are not accessible
[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("NewGeomResources");
253   if (aEnv != NULL) {
254     TCollection_AsciiString aFile(aEnv);
255     aFile += FSEP;
256     aFile += iconName();
257     Handle(Image_AlienPixMap) aPixMap = new Image_AlienPixMap();
258     if (aPixMap->Load(aFile)) {
259       myIconsMap[iconName()] = aPixMap;
260       return aPixMap;
261     }
262   } else {
263     static const char aMsg[] = "Error! NewGeomResources environment variable is not defined: constraint images are not found";
264     cout<<aMsg<<endl;
265     Events_Error::send(aMsg);
266     myIconsMap[iconName()] = Handle(Image_AlienPixMap)();
267   }
268   return Handle(Image_AlienPixMap)();
269 }
270
271 void SketcherPrs_SymbolPrs::ClearSelected()
272 {
273   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( NULL );  
274   if( !aSelectionPrs.IsNull() ) {
275     aSelectionPrs->Clear(); 
276   }
277 }
278
279 void SketcherPrs_SymbolPrs::prepareAspect()
280 {
281   if (myAspect.IsNull()) {
282     Handle(Image_AlienPixMap) aIcon = icon();
283     if (aIcon.IsNull()) 
284       myAspect = new Graphic3d_AspectMarker3d();
285     else
286       myAspect = new Graphic3d_AspectMarker3d(aIcon);
287   }
288 }
289
290 void SketcherPrs_SymbolPrs::addLine(const Handle(Graphic3d_Group)& theGroup, std::string theAttrName) const
291 {
292   ObjectPtr aObj = SketcherPrs_Tools::getResult(myConstraint, theAttrName);
293   std::shared_ptr<GeomAPI_Shape> aLine = SketcherPrs_Tools::getShape(aObj);
294   if (aLine.get() == NULL)
295     return;
296   std::shared_ptr<GeomAPI_Edge> aEdge = std::shared_ptr<GeomAPI_Edge>(new GeomAPI_Edge(aLine));
297
298   std::shared_ptr<GeomAPI_Pnt> aPnt1 = aEdge->firstPoint();
299   std::shared_ptr<GeomAPI_Pnt> aPnt2 = aEdge->lastPoint();
300
301   Handle(Graphic3d_ArrayOfSegments) aLines = new Graphic3d_ArrayOfSegments(2, 1);
302   aLines->AddVertex(aPnt1->impl<gp_Pnt>());
303   aLines->AddVertex(aPnt2->impl<gp_Pnt>());
304   theGroup->AddPrimitiveArray(aLines);
305 }
306
307 void SketcherPrs_SymbolPrs::HilightSelected(const Handle(PrsMgr_PresentationManager3d)& thePM, 
308                                            const SelectMgr_SequenceOfOwner& theOwners)
309 {
310
311   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( thePM );
312   aSelectionPrs->Clear();
313   drawLines(aSelectionPrs, Quantity_NOC_WHITE);
314
315   aSelectionPrs->SetDisplayPriority(9);
316   aSelectionPrs->Display();
317   thePM->Highlight(this);
318 }
319
320 void SketcherPrs_SymbolPrs::HilightOwnerWithColor(const Handle(PrsMgr_PresentationManager3d)& thePM, 
321                                                  const Quantity_NameOfColor theColor, const Handle(SelectMgr_EntityOwner)& theOwner)
322 {
323   thePM->Color(this, theColor);
324
325   Handle( Prs3d_Presentation ) aHilightPrs = GetHilightPresentation( thePM );
326   aHilightPrs->Clear();
327   drawLines(aHilightPrs, theColor);
328
329   if (thePM->IsImmediateModeOn())
330     thePM->AddToImmediateList(aHilightPrs);
331 }
332
333 void SketcherPrs_SymbolPrs::Compute(const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
334                                    const Handle(Prs3d_Presentation)& thePresentation, 
335                                    const Standard_Integer theMode)
336 {
337   prepareAspect();
338
339   Handle(AIS_InteractiveContext) aCtx = GetContext();
340   Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast(aCtx->CurrentViewer()->Driver());
341   if (!aDriver.IsNull()) {
342     // register the custom element factory function
343     aDriver->UserDrawCallback() = SymbolPrsCallBack;
344   }
345
346   if (!updatePoints(20))
347     return;
348
349   int aNbVertex = myPntArray->VertexNumber();
350   if (myOwner.IsNull()) {
351     myOwner = new SelectMgr_EntityOwner(this);
352   }
353
354   mySPoints.Clear();
355   for (int i = 1; i <= aNbVertex; i++) {
356     Handle(SketcherPrs_SensitivePoint) aSP = new SketcherPrs_SensitivePoint(myOwner, myPntArray, i);
357     mySPoints.Append(aSP);
358   }
359
360   Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup(thePresentation);
361   aGroup->SetPrimitivesAspect(myAspect);
362
363   Graphic3d_BndBox4f& aBnd = aGroup->ChangeBoundingBox();
364   gp_Pnt aVert;
365   aBnd.Clear();
366   for (int i = 1; i <= myPntArray->ItemNumber(); i++) {
367     aVert = myPntArray->Vertice(i);
368     aBnd.Add (Graphic3d_Vec4((float)aVert.X(), (float)aVert.Y(), (float)aVert.Z(), 1.0f));
369   }
370
371   aGroup->UserDraw(this, true);
372   //aGroup->AddPrimitiveArray(myPntArray);
373 }
374
375
376
377 void SketcherPrs_SymbolPrs::ComputeSelection(const Handle(SelectMgr_Selection)& aSelection,
378                                             const Standard_Integer aMode)
379 {
380   ClearSelected();
381   if ((aMode == 0) || (aMode == SketcherPrs_Tools::Sel_Constraint)) {
382     for (int i = 1; i <= mySPoints.Length(); i++)
383       aSelection->Add(mySPoints.Value(i));
384   }
385 }
386
387
388 void SketcherPrs_SymbolPrs::Render(const Handle(OpenGl_Workspace)& theWorkspace) const
389 {
390   const OpenGl_AspectMarker* anAspectMarker = theWorkspace->AspectMarker(Standard_True);
391   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
392   Handle(OpenGl_View) aView = theWorkspace->ActiveView();
393   
394   double aScale = aView->Camera()->Scale();
395   if (!updatePoints(MyDist * aScale))
396     return;
397
398   Handle(Graphic3d_Buffer) aAttribs = myPntArray->Attributes();
399
400   if (myVboAttribs.IsNull()) {
401     myVboAttribs = new SketcherPrs_VertexBuffer(*aAttribs);
402   }
403
404   if (!myVboAttribs->init(aCtx, 0, aAttribs->NbElements, aAttribs->Data(), GL_NONE, aAttribs->Stride)) {
405     myVboAttribs->Release (aCtx.operator->());
406     myVboAttribs.Nullify();
407     return;
408   }
409     
410   Handle(OpenGl_Texture) aTextureBack = theWorkspace->DisableTexture();
411
412   const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes(aCtx);
413       
414   if (!aSpriteNorm.IsNull() && !aSpriteNorm->IsDisplayList()) {
415     const bool toHilight = (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT) != 0;
416     const Handle(OpenGl_PointSprite)& aSprite = (toHilight && anAspectMarker->SpriteHighlightRes(aCtx)->IsValid())
417                                               ? anAspectMarker->SpriteHighlightRes(aCtx)
418                                               : aSpriteNorm;
419     theWorkspace->EnableTexture (aSprite);
420     aCtx->ShaderManager()->BindProgram(anAspectMarker, aSprite, Standard_False, Standard_False, anAspectMarker->ShaderProgramRes(aCtx));
421     const TEL_COLOUR* aLineColor  =  &anAspectMarker->Color();
422     if (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT)
423       aLineColor = theWorkspace->HighlightColor;
424
425     aCtx->SetColor4fv(*(const OpenGl_Vec4* )(aLineColor->rgb));
426
427
428     myVboAttribs->BindAllAttributes(aCtx);
429     // Textured markers will be drawn with the point sprites
430     aCtx->SetPointSize (anAspectMarker->MarkerSize());
431     aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
432     aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
433
434     aCtx->core11fwd->glEnable (GL_BLEND);
435     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
436
437     aCtx->core11fwd->glDrawArrays (0, 0, myVboAttribs->GetElemsNb());
438
439     aCtx->core11fwd->glDisable (GL_BLEND);
440     aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
441     aCtx->SetPointSize (1.0f);
442   }
443   theWorkspace->EnableTexture (aTextureBack);
444   aCtx->BindProgram (NULL);
445
446   // Update selection position only if there is no selected object
447   // because it can corrupt selection of other objects
448   if ((GetContext()->NbCurrents() == 0) && (GetContext()->NbSelected() == 0))
449     GetContext()->RecomputeSelectionOnly(this);
450 }
451
452
453 void SketcherPrs_SymbolPrs::Release (OpenGl_Context* theContext)
454 {
455   if (!myVboAttribs.IsNull()) {
456     if (theContext) {
457       theContext->DelayedRelease (myVboAttribs);
458     }
459     myVboAttribs.Nullify();
460   }
461 }
462
463 void SketcherPrs_SymbolPrs::drawShape(const std::shared_ptr<GeomAPI_Shape>& theShape, 
464                                       const Handle(Prs3d_Presentation)& thePrs) const
465 {
466   if (theShape->isEdge()) {
467     std::shared_ptr<GeomAPI_Curve> aCurve = 
468       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(theShape));
469     if (aCurve->isLine()) {
470       GeomAdaptor_Curve aCurv(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
471       StdPrs_Curve::Add(thePrs, aCurv, myDrawer);
472     } else {
473       GeomAdaptor_Curve aAdaptor(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
474       StdPrs_DeflectionCurve::Add(thePrs,aAdaptor,myDrawer);
475     }
476   } else if (theShape->isVertex()) {
477     std::shared_ptr<GeomAPI_Vertex> aVertex = 
478       std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(theShape));
479     std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
480     Handle(Geom_CartesianPoint) aPoint = new Geom_CartesianPoint(aPnt->impl<gp_Pnt>());
481     StdPrs_Point::Add(thePrs, aPoint, myDrawer);
482   }
483 }
484
485 void SketcherPrs_SymbolPrs::drawListOfShapes(const std::shared_ptr<ModelAPI_AttributeRefList>& theListAttr, 
486                                              const Handle(Prs3d_Presentation)& thePrs) const
487 {
488   int aNb = theListAttr->size();
489   if (aNb == 0)
490     return;
491   int i;
492   ObjectPtr aObj;
493   for (i = 0; i < aNb; i++) {
494     aObj = theListAttr->object(i);
495     std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(aObj);
496     if (aShape.get() != NULL)
497       drawShape(aShape, thePrs);
498   }
499 }
500