Salome HOME
Update copyrights 2014.
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_Attractor.cxx
1 // Copyright (C) 2007-2014  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
42 BLSURFPlugin_Attractor::BLSURFPlugin_Attractor ()
43   : _face(),
44   _attractorShape(),
45   _attEntry(),
46   _gridU(0),
47   _gridV(0),
48   _vectU(),
49   _vectV(),
50   _DMap(),
51   _known(),
52   _trial(),
53   _u1 (0.),
54   _u2 (0.),
55   _v1 (0.),
56   _v2 (0.),
57   _startSize(-1),
58   _endSize(-1),
59   _actionRadius(-1),
60   _constantRadius(-1),
61   _type(-1),
62   _isMapBuilt(false),
63   _isEmpty(true){ MESSAGE("construction of a void attractor"); }
64
65 BLSURFPlugin_Attractor::BLSURFPlugin_Attractor (const TopoDS_Face& Face, const TopoDS_Shape& Attractor, const std::string& attEntry) 
66   : _face(),
67   _attractorShape(),
68   _attEntry(attEntry),
69   _gridU(),
70   _gridV(),
71   _vectU(),
72   _vectV(),
73   _DMap(),
74   _known(),
75   _trial(),
76   _u1 (0.),
77   _u2 (0.),
78   _v1 (0.),
79   _v2 (0.),
80   _startSize(-1),
81   _endSize(-1),
82   _actionRadius(-1),
83   _constantRadius(-1),
84   _type(0),
85   _isMapBuilt(false),
86   _isEmpty(false)
87 {
88   _face = Face;
89   _attractorShape = Attractor;
90   
91   init();
92 }
93
94 bool BLSURFPlugin_Attractor::init(){ 
95   Standard_Real u0,v0;
96   int i,j,i0,j0 ;
97   _known.clear();
98   _trial.clear();
99   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(_face);
100   
101   // Calculation of the bounds of the face
102   ShapeAnalysis::GetFaceUVBounds(_face,_u1,_u2,_v1,_v2);
103
104   _gridU = 300;
105   _gridV = 300;
106
107   for (i=0; i<=_gridU; i++){
108     _vectU.push_back(_u1+i*(_u2-_u1)/_gridU) ;
109   }
110   for (j=0; j<=_gridV; j++){
111     _vectV.push_back(_v1+j*(_v2-_v1)/_gridV) ;
112   }
113   
114   // Initialization of _DMap and _known
115   std::vector<double> temp(_gridV+1,std::numeric_limits<double>::infinity());  // Set distance of all "far" points to Infinity 
116   for (i=0; i<=_gridU; i++){
117     _DMap.push_back(temp);
118   }
119   std::vector<bool> temp2(_gridV+1,false);
120   for (i=0; i<=_gridU; i++){
121     _known.push_back(temp2);
122   }
123   
124   
125   // Determination of the starting points
126   TopExp_Explorer anEdgeExp(_attractorShape, TopAbs_EDGE, TopAbs_FACE);
127   TopExp_Explorer aVertExp(_attractorShape, TopAbs_VERTEX, TopAbs_EDGE);
128   
129   for(; anEdgeExp.More(); anEdgeExp.Next()){
130     const TopoDS_Edge& anEdge = TopoDS::Edge(anEdgeExp.Current());
131     edgeInit(aSurf, anEdge);
132   }
133   
134   for(; aVertExp.More(); aVertExp.Next()){
135     const TopoDS_Vertex& aVertex = TopoDS::Vertex(aVertExp.Current());
136     Trial_Pnt TPnt(3,0); 
137     gp_Pnt P = BRep_Tool::Pnt(aVertex);
138     GeomAPI_ProjectPointOnSurf projector( P, aSurf );
139     projector.LowerDistanceParameters(u0,v0);
140     i0 = floor ( (u0 - _u1) * _gridU / (_u2 - _u1) + 0.5 );
141     j0 = floor ( (v0 - _v1) * _gridV / (_v2 - _v1) + 0.5 );
142     TPnt[0]=0.;                                                                // Set the distance of the starting point to 0.
143     TPnt[1]=i0;
144     TPnt[2]=j0;
145     _DMap[i0][j0] = 0.;
146     _trial.insert(TPnt);                                                       // Move starting point to _trial
147   }
148
149   return true;
150 }
151
152 void BLSURFPlugin_Attractor::edgeInit(Handle(Geom_Surface) theSurf, const TopoDS_Edge& anEdge){
153   gp_Pnt2d P2;
154   double first;
155   double last;
156   int i,j,i0,j0;
157   Trial_Pnt TPnt(3,0);
158   Handle(Geom2d_Curve) aCurve2d; 
159   Handle(Geom_Curve) aCurve3d = BRep_Tool::Curve (anEdge, first, last);
160   ShapeConstruct_ProjectCurveOnSurface curveProjector;
161   curveProjector.Init(theSurf, Precision::Confusion());
162   curveProjector.PerformAdvanced (aCurve3d, first, last, aCurve2d);
163   
164   int N = 1200;
165   for (i=0; i<=N; i++){
166     P2 = aCurve2d->Value(first + i * (last-first) / N);
167     i0 = floor( (P2.X() - _u1) * _gridU / (_u2 - _u1) + 0.5 );
168     j0 = floor( (P2.Y() - _v1) * _gridV / (_v2 - _v1) + 0.5 );
169     TPnt[0] = 0.;
170     TPnt[1] = i0;
171     TPnt[2] = j0;
172     _DMap[i0][j0] = 0.;
173     _trial.insert(TPnt);
174   }
175 }  
176
177
178 void BLSURFPlugin_Attractor::SetParameters(double Start_Size, double End_Size, double Action_Radius, double Constant_Radius){
179   _startSize = Start_Size;
180   _endSize = End_Size;
181   _actionRadius = Action_Radius;
182   _constantRadius = Constant_Radius;
183 }
184
185 double BLSURFPlugin_Attractor::_distance(double u, double v){
186   
187   //   BLSURF seems to perform a linear interpolation so it's sufficient to give it a non-continuous distance map
188   int i = floor ( (u - _u1) * _gridU / (_u2 - _u1) + 0.5 );
189   int j = floor ( (v - _v1) * _gridV / (_v2 - _v1) + 0.5 );
190   
191   return _DMap[i][j];
192 }
193
194
195 double BLSURFPlugin_Attractor::GetSize(double u, double v){   
196   double myDist = 0.5 * (_distance(u,v) - _constantRadius + fabs(_distance(u,v) - _constantRadius));
197   switch(_type)
198   {
199     case TYPE_EXP:
200       if (fabs(_actionRadius) <= std::numeric_limits<double>::epsilon()){ 
201         if (myDist <= std::numeric_limits<double>::epsilon()){
202           return _startSize;
203         }
204         else {
205           return _endSize;
206         }
207       }
208       else{
209         return _endSize - (_endSize - _startSize) * exp(- myDist * myDist / (_actionRadius * _actionRadius) );
210       }
211       break;
212     case TYPE_LIN:
213         return _startSize + ( 0.5 * (_distance(u,v) - _constantRadius + abs(_distance(u,v) - _constantRadius)) ) ;
214       break;
215   }
216 }
217
218
219 void BLSURFPlugin_Attractor::BuildMap(){ 
220   
221   MESSAGE("building the map");
222   int i, j, k, n;  
223   int count = 0;
224   int ip, jp, kp, np;
225   int i0, j0;
226   gp_Pnt P;
227   gp_Vec D1U,D1V;
228   double Guu, Gvv, Guv;         // Components of the local metric tensor
229   double du, dv;
230   double D_Ref = 0.;
231   double Dist = 0.;
232   bool Dist_changed;
233   IJ_Pnt Current_Pnt(2,0);
234   Trial_Pnt TPnt(3,0);
235   TTrialSet::iterator min;
236   TTrialSet::iterator found;
237   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(_face);
238   
239   // While there are points in "Trial" (representing a kind of advancing front), loop on them -----------------------------------------------------------
240   while (_trial.size() > 0 ){
241     min = _trial.begin();                        // Get trial point with min distance from start
242     i0 = (*min)[1];
243     j0 = (*min)[2];
244     _known[i0][j0] = true;                       // Move it to "Known"
245     _trial.erase(min);                           // Remove it from "Trial"
246     
247     // Loop on neighbours of the trial min --------------------------------------------------------------------------------------------------------------
248     for (i=i0 - 1 ; i <= i0 + 1 ; i++){ 
249       if (!aSurf->IsUPeriodic()){                          // Periodic conditions in U  
250         if (i > _gridU ){
251           break; }
252         else if (i < 0){
253           i++; }
254       }
255       ip = (i + _gridU + 1) % (_gridU+1);                  // We get a periodic index :
256       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;  
257         if (!aSurf->IsVPeriodic()){                        // Periodic conditions in V . 
258           if (j > _gridV ){
259             break; }
260           else if (j < 0){
261             j++;
262           }
263         }
264         jp = (j + _gridV + 1) % (_gridV+1);
265       
266         if (!_known[ip][jp]){                              // If the distance is not known yet
267           aSurf->D1(_vectU[ip],_vectV[jp],P,D1U,D1V);      // Calculate the metric tensor at (i,j)
268           // G(i,j)  =  | ||dS/du||**2          *     | 
269           //            | <dS/du,dS/dv>  ||dS/dv||**2 |
270           Guu = D1U.X()*D1U.X() +  D1U.Y()*D1U.Y() + D1U.Z()*D1U.Z();    // Guu = ||dS/du||**2    
271           Gvv = D1V.X()*D1V.X() +  D1V.Y()*D1V.Y() + D1V.Z()*D1V.Z();    // Gvv = ||dS/dv||**2           
272           Guv = D1U.X()*D1V.X() +  D1U.Y()*D1V.Y() + D1U.Z()*D1V.Z();    // Guv = Gvu = < dS/du,dS/dv > 
273           D_Ref = _DMap[ip][jp];                           // Set a ref. distance of the point to its value in _DMap 
274           TPnt[0] = D_Ref;                                 // (may be infinite or uncertain)
275           TPnt[1] = ip;
276           TPnt[2] = jp;
277           Dist_changed = false;
278           
279           // Loop on neighbours to calculate the min distance from them ---------------------------------------------------------------------------------
280           for (k=i - 1 ; k <= i + 1 ; k++){
281             if (!aSurf->IsUPeriodic()){                              // Periodic conditions in U  
282               if(k > _gridU ){
283                 break;
284               }
285               else if (k < 0){
286                 k++; }
287             }
288             kp = (k + _gridU + 1) % (_gridU+1);                      // periodic index
289             for (n=j - 1 ; n <= j + 1 ; n++){ 
290               if (!aSurf->IsVPeriodic()){                            // Periodic conditions in V 
291                 if(n > _gridV){   
292                   break;
293                 }
294                 else if (n < 0){
295                   n++; }
296               }
297               np = (n + _gridV + 1) % (_gridV+1);                    
298               if (_known[kp][np]){                                   // If the distance of the neighbour is known
299                                                                      // Calculate the distance from (k,n)
300                 du = (k-i) * (_u2 - _u1) / _gridU;
301                 dv = (n-j) * (_v2 - _v1) / _gridV;
302                 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)
303                 if (Dist < D_Ref) {                                  // If smaller than ref. distance  ->  update ref. distance
304                   D_Ref = Dist;
305                   Dist_changed = true;
306                 }
307               }
308             }
309           } // End of the loop on neighbours --------------------------------------------------------------------------------------------------------------
310           
311           if (Dist_changed) {                              // If distance has been updated, update _trial 
312             found=_trial.find(TPnt);
313             if (found != _trial.end()){
314               _trial.erase(found);                         // Erase the point if it was already in _trial
315             }
316             TPnt[0] = D_Ref;
317             TPnt[1] = ip;
318             TPnt[2] = jp;
319             _DMap[ip][jp] = D_Ref;                         // Set it distance to the minimum distance found during the loop above
320             _trial.insert(TPnt);                           // Insert it (or reinsert it) in _trial
321           }
322         } // end if (!_known[ip][jp])
323       } // for
324     } // for
325   } // while (_trial)
326   _known.clear();
327   _trial.clear();
328   _isMapBuilt = true;
329 } // end of BuildMap()
330
331
332