Salome HOME
Fix crash with some attractors
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_Attractor.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // ---
21 // File    : BLSURFPlugin_Attractor.cxx
22 // Authors : Renaud Nédélec (OCC)
23 // ---
24 // 
25 // The idea of the algorithm used to calculate the distance on a 
26 // non-euclidian parametric surface has been found in the ref. below:
27 //
28 // Ref:"Accurate Anisotropic Fast Marching for Diffusion-Based Geodesic Tractography"
29 // S. Jbabdi, P. Bellec, R. Toro, Daunizeau, M. Pélégrini-Issac, and H. Benali1
30 //
31
32 #include "BLSURFPlugin_Attractor.hxx"
33 #include <utilities.h>
34 #include <algorithm>
35 #include <cmath>
36
37 // cascade include
38 #include <ShapeAnalysis.hxx>
39 #include <ShapeConstruct_ProjectCurveOnSurface.hxx>
40 #include <Precision.hxx>
41 #include <GeomLib_IsPlanarSurface.hxx>
42
43 // kernel includes
44 #include <Basics_OCCTVersion.hxx>
45
46 BLSURFPlugin_Attractor::BLSURFPlugin_Attractor ()
47   : _face(),
48   _attractorShape(),
49   _attEntry(),
50   _vectU(),
51   _vectV(),
52   _DMap(),
53   _known(),
54   _trial(),
55   _type(-1),
56   _gridU(0),
57   _gridV(0),
58   _u1 (0.),
59   _u2 (0.),
60   _v1 (0.),
61   _v2 (0.),
62   _startSize(-1),
63   _endSize(-1),
64   _actionRadius(-1),
65   _constantRadius(-1),
66   _isMapBuilt(false),
67   _isEmpty(true){ MESSAGE("construction of a void attractor"); }
68
69 BLSURFPlugin_Attractor::BLSURFPlugin_Attractor (const TopoDS_Face& Face, const TopoDS_Shape& Attractor, const std::string& attEntry) 
70   : _face(),
71   _attractorShape(),
72   _attEntry(attEntry),
73   _vectU(),
74   _vectV(),
75   _DMap(),
76   _known(),
77   _trial(),
78   _type(0),
79   _gridU(),
80   _gridV(),
81   _u1 (0.),
82   _u2 (0.),
83   _v1 (0.),
84   _v2 (0.),
85   _startSize(-1),
86   _endSize(-1),
87   _actionRadius(-1),
88   _constantRadius(-1),
89   _isMapBuilt(false),
90   _isEmpty(false)
91 {
92   _face = Face;
93   _attractorShape = Attractor;
94   
95   init();
96 }
97
98 bool BLSURFPlugin_Attractor::init(){ 
99   Standard_Real u0,v0;
100   int i,j,i0,j0 ;
101   _known.clear();
102   _trial.clear();
103   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(_face);
104
105   _distance = &BLSURFPlugin_Attractor::_distanceFromMap;
106
107   if ( GeomLib_IsPlanarSurface( aSurf ).IsPlanar() &&
108        _attractorShape.ShapeType() == TopAbs_VERTEX )
109   {
110     // a specific case, the map is not needed
111     gp_Pnt P = BRep_Tool::Pnt( TopoDS::Vertex( _attractorShape ));
112     GeomAPI_ProjectPointOnSurf projector( P, aSurf );
113     if ( projector.IsDone() && projector.NbPoints() == 1 )
114     {
115       projector.LowerDistanceParameters(u0,v0);
116
117       _attractorPnt = aSurf->Value( u0,v0 );
118       _plane        = aSurf;
119       _distance     = &BLSURFPlugin_Attractor::_distanceFromPoint;
120       _isMapBuilt   = true;
121       _isEmpty      = false;
122       return true;
123     }
124   }
125   
126   // Calculation of the bounds of the face
127   ShapeAnalysis::GetFaceUVBounds(_face,_u1,_u2,_v1,_v2);
128
129   _gridU = 300;
130   _gridV = 300;
131
132   for (i=0; i<=_gridU; i++){
133     _vectU.push_back(_u1+i*(_u2-_u1)/_gridU) ;
134   }
135   for (j=0; j<=_gridV; j++){
136     _vectV.push_back(_v1+j*(_v2-_v1)/_gridV) ;
137   }
138   
139   // Initialization of _DMap and _known
140   std::vector<double> temp(_gridV+1,std::numeric_limits<double>::infinity());  // Set distance of all "far" points to Infinity 
141   for (i=0; i<=_gridU; i++){
142     _DMap.push_back(temp);
143   }
144   std::vector<bool> temp2(_gridV+1,false);
145   for (i=0; i<=_gridU; i++){
146     _known.push_back(temp2);
147   }
148   
149   
150   // Determination of the starting points
151   TopExp_Explorer anEdgeExp(_attractorShape, TopAbs_EDGE, TopAbs_FACE);
152   TopExp_Explorer aVertExp(_attractorShape, TopAbs_VERTEX, TopAbs_EDGE);
153   
154   for(; anEdgeExp.More(); anEdgeExp.Next()){
155     const TopoDS_Edge& anEdge = TopoDS::Edge(anEdgeExp.Current());
156     edgeInit(aSurf, anEdge);
157   }
158   
159   for(; aVertExp.More(); aVertExp.Next()){
160     const TopoDS_Vertex& aVertex = TopoDS::Vertex(aVertExp.Current());
161     Trial_Pnt TPnt(3,0); 
162     gp_Pnt P = BRep_Tool::Pnt(aVertex);
163     GeomAPI_ProjectPointOnSurf projector( P, aSurf );
164     projector.LowerDistanceParameters(u0,v0);
165     i0 = floor ( (u0 - _u1) * _gridU / (_u2 - _u1) + 0.5 );
166     j0 = floor ( (v0 - _v1) * _gridV / (_v2 - _v1) + 0.5 );
167     TPnt[0]=0.;                                                                // Set the distance of the starting point to 0.
168     TPnt[1]=i0;
169     TPnt[2]=j0;
170     _DMap[i0][j0] = 0.;
171     _trial.insert(TPnt);                                                       // Move starting point to _trial
172   }
173
174   return true;
175 }
176
177 void BLSURFPlugin_Attractor::edgeInit(Handle(Geom_Surface) theSurf, const TopoDS_Edge& anEdge){
178   gp_Pnt2d P2;
179   double first;
180   double last;
181   int i,i0,j0;
182   Trial_Pnt TPnt(3,0);
183   Handle(Geom2d_Curve) aCurve2d; 
184   Handle(Geom_Curve) aCurve3d = BRep_Tool::Curve (anEdge, first, last);
185   ShapeConstruct_ProjectCurveOnSurface curveProjector;
186   curveProjector.Init(theSurf, Precision::Confusion());
187 #if OCC_VERSION_LARGE > 0x07010000
188   curveProjector.Perform (aCurve3d, first, last, aCurve2d);
189 #else
190   curveProjector.PerformAdvanced (aCurve3d, first, last, aCurve2d);
191 #endif
192   
193   int N = 1200;
194   for (i=0; i<=N; i++){
195     P2 = aCurve2d->Value(first + i * (last-first) / N);
196     i0 = floor( (P2.X() - _u1) * _gridU / (_u2 - _u1) + 0.5 );
197     j0 = floor( (P2.Y() - _v1) * _gridV / (_v2 - _v1) + 0.5 );
198     TPnt[0] = 0.;
199     TPnt[1] = i0;
200     TPnt[2] = j0;
201     _DMap[i0][j0] = 0.;
202     _trial.insert(TPnt);
203   }
204 }  
205
206
207 void BLSURFPlugin_Attractor::SetParameters(double Start_Size, double End_Size, double Action_Radius, double Constant_Radius){
208   _startSize = Start_Size;
209   _endSize = End_Size;
210   _actionRadius = Action_Radius;
211   _constantRadius = Constant_Radius;
212 }
213
214 double BLSURFPlugin_Attractor::_distanceFromPoint(double u, double v)
215 {
216   return _attractorPnt.Distance( _plane->Value( u, v ));
217 }
218
219 double BLSURFPlugin_Attractor::_distanceFromMap(double u, double v){
220   
221   //   MG-CADSurf seems to perform a linear interpolation so it's sufficient to give it a non-continuous distance map
222   int i = floor ( (u - _u1) * _gridU / (_u2 - _u1) + 0.5 );
223   int j = floor ( (v - _v1) * _gridV / (_v2 - _v1) + 0.5 );
224   
225   // avoid out of bounds of _DMap
226   if (i > _DMap.size())
227     i = _DMap.size()-1;
228
229   if (i < 0)
230     i = 0;
231
232   if (j > _DMap[i].size())
233     j = _DMap[i].size()-1;
234
235   if (j < 0)
236     j = 0;
237
238   return _DMap[i][j];
239 }
240
241 double BLSURFPlugin_Attractor::GetSize(double u, double v)
242 {
243   const double attrDist = (this->*_distance)(u,v);
244   const double myDist = 0.5 * (attrDist - _constantRadius + fabs(attrDist - _constantRadius));
245   switch(_type)
246   {
247     case TYPE_EXP:
248       if (fabs(_actionRadius) <= std::numeric_limits<double>::epsilon()){ 
249         if (myDist <= std::numeric_limits<double>::epsilon()){
250           return _startSize;
251         }
252         else {
253           return _endSize;
254         }
255       }
256       else{
257         return _endSize - (_endSize - _startSize) * exp(- myDist * myDist / (_actionRadius * _actionRadius) );
258       }
259       break;
260     case TYPE_LIN:
261         return _startSize + ( 0.5 * (attrDist - _constantRadius + fabs(attrDist - _constantRadius)) ) ;
262       break;
263   }
264   return -1;
265 }
266
267
268 void BLSURFPlugin_Attractor::BuildMap() { 
269   
270   MESSAGE("building the map");
271   int i, j, k, n;  
272   //int count = 0;
273   int ip, jp, kp, np;
274   int i0, j0;
275   gp_Pnt P;
276   gp_Vec D1U,D1V;
277   double Guu, Gvv, Guv;         // Components of the local metric tensor
278   double du, dv;
279   double D_Ref = 0.;
280   double Dist = 0.;
281   bool Dist_changed;
282   IJ_Pnt Current_Pnt(2,0);
283   Trial_Pnt TPnt(3,0);
284   TTrialSet::iterator min;
285   TTrialSet::iterator found;
286   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(_face);
287   
288   // While there are points in "Trial" (representing a kind of advancing front), loop on them -----------------------------------------------------------
289   while (_trial.size() > 0 ) {
290     min = _trial.begin();                        // Get trial point with min distance from start
291     i0 = (*min)[1];
292     j0 = (*min)[2];
293     _known[i0][j0] = true;                       // Move it to "Known"
294     _trial.erase(min);                           // Remove it from "Trial"
295     
296     // Loop on neighbours of the trial min --------------------------------------------------------------------------------------------------------------
297     for (i=i0 - 1 ; i <= i0 + 1 ; i++){ 
298       if (!aSurf->IsUPeriodic()){                          // Periodic conditions in U  
299         if (i > _gridU ){
300           break; }
301         else if (i < 0){
302           i++; }
303       }
304       ip = (i + _gridU + 1) % (_gridU+1);                  // We get a periodic index :
305       for (j=j0 - 1 ; j <= j0 + 1 ; j++){                  //    ip=modulo(i,N+2) so that  i=-1->ip=N; i=0 -> ip=0 ; ... ; i=N+1 -> ip=0;  
306         if (!aSurf->IsVPeriodic()){                        // Periodic conditions in V . 
307           if (j > _gridV ){
308             break; }
309           else if (j < 0){
310             j++;
311           }
312         }
313         jp = (j + _gridV + 1) % (_gridV+1);
314       
315         if (!_known[ip][jp]){                              // If the distance is not known yet
316           aSurf->D1(_vectU[ip],_vectV[jp],P,D1U,D1V);      // Calculate the metric tensor at (i,j)
317           // G(i,j)  =  | ||dS/du||**2          *     | 
318           //            | <dS/du,dS/dv>  ||dS/dv||**2 |
319           Guu = D1U.X()*D1U.X() +  D1U.Y()*D1U.Y() + D1U.Z()*D1U.Z();    // Guu = ||dS/du||**2    
320           Gvv = D1V.X()*D1V.X() +  D1V.Y()*D1V.Y() + D1V.Z()*D1V.Z();    // Gvv = ||dS/dv||**2           
321           Guv = D1U.X()*D1V.X() +  D1U.Y()*D1V.Y() + D1U.Z()*D1V.Z();    // Guv = Gvu = < dS/du,dS/dv > 
322           D_Ref = _DMap[ip][jp];                           // Set a ref. distance of the point to its value in _DMap 
323           TPnt[0] = D_Ref;                                 // (may be infinite or uncertain)
324           TPnt[1] = ip;
325           TPnt[2] = jp;
326           Dist_changed = false;
327           
328           // Loop on neighbours to calculate the min distance from them ---------------------------------------------------------------------------------
329           for (k=i - 1 ; k <= i + 1 ; k++){
330             if (!aSurf->IsUPeriodic()){                              // Periodic conditions in U  
331               if(k > _gridU ){
332                 break;
333               }
334               else if (k < 0){
335                 k++; }
336             }
337             kp = (k + _gridU + 1) % (_gridU+1);                      // periodic index
338             for (n=j - 1 ; n <= j + 1 ; n++){ 
339               if (!aSurf->IsVPeriodic()){                            // Periodic conditions in V 
340                 if(n > _gridV){   
341                   break;
342                 }
343                 else if (n < 0){
344                   n++; }
345               }
346               np = (n + _gridV + 1) % (_gridV+1);                    
347               if (_known[kp][np]){                                   // If the distance of the neighbour is known
348                                                                      // Calculate the distance from (k,n)
349                 du = (k-i) * (_u2 - _u1) / _gridU;
350                 dv = (n-j) * (_v2 - _v1) / _gridV;
351                 Dist = _DMap[kp][np] + sqrt( Guu * du*du + 2*Guv * du*dv + Gvv * dv*dv );   // ds**2 = du'Gdu + 2*du'Gdv + dv'Gdv  (G is always symetrical)
352                 if (Dist < D_Ref) {                                  // If smaller than ref. distance  ->  update ref. distance
353                   D_Ref = Dist;
354                   Dist_changed = true;
355                 }
356               }
357             }
358           } // End of the loop on neighbours --------------------------------------------------------------------------------------------------------------
359           
360           if (Dist_changed) {                              // If distance has been updated, update _trial 
361             found=_trial.find(TPnt);
362             if (found != _trial.end()){
363               _trial.erase(found);                         // Erase the point if it was already in _trial
364             }
365             TPnt[0] = D_Ref;
366             TPnt[1] = ip;
367             TPnt[2] = jp;
368             _DMap[ip][jp] = D_Ref;                         // Set it distance to the minimum distance found during the loop above
369             _trial.insert(TPnt);                           // Insert it (or reinsert it) in _trial
370           }
371         } // end if (!_known[ip][jp])
372       } // for
373     } // for
374   } // while (_trial)
375   _known.clear();
376   _trial.clear();
377   _isMapBuilt = true;
378 } // end of BuildMap()
379
380
381