]> Creatis software - creaVtk.git/blob - bbtk_creaVtk_PKG/src/bbcreaVtkCreateMeshFromPoints.cxx
58448a4fe7a84f819c63dcf8d215c3dbcbf3212a
[creaVtk.git] / bbtk_creaVtk_PKG / src / bbcreaVtkCreateMeshFromPoints.cxx
1 //===== 
2 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
3 //===== 
4 #include "bbcreaVtkCreateMeshFromPoints.h"
5 #include "bbcreaVtkPackage.h"
6
7 #include "vtkTriangleStrip.h"
8 #include "vtkTriangle.h"
9 #include <vtkMath.h>
10
11 namespace bbcreaVtk
12 {
13
14 BBTK_ADD_BLACK_BOX_TO_PACKAGE(creaVtk,CreateMeshFromPoints)
15 BBTK_BLACK_BOX_IMPLEMENTATION(CreateMeshFromPoints,bbtk::AtomicBlackBox);
16 //===== 
17 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
18 //===== 
19 void CreateMeshFromPoints::Process()
20 {
21
22 // THE MAIN PROCESSING METHOD BODY
23 //   Here we simply set the input 'In' value to the output 'Out'
24 //   And print out the output value
25 // INPUT/OUTPUT ACCESSORS ARE OF THE FORM :
26 //    void bbSet{Input|Output}NAME(const TYPE&)
27 //    const TYPE& bbGet{Input|Output}NAME() const 
28 //    Where :
29 //    * NAME is the name of the input/output
30 //      (the one provided in the attribute 'name' of the tag 'input')
31 //    * TYPE is the C++ type of the input/output
32 //      (the one provided in the attribute 'type' of the tag 'input')
33
34 //    bbSetOutputOut( bbGetInputIn() );
35 //    std::cout << "Output value = " <<bbGetOutputOut() << std::endl;
36
37                 std::vector<double> lstX                = bbGetInputLstX();
38                 std::vector<double> lstY                = bbGetInputLstY();
39                 std::vector<double> lstZ                = bbGetInputLstZ();
40                 std::vector<int> lstIndexs              = bbGetInputLstIndexs();
41                 if ( (lstIndexs.size()<1) || (lstX.size()==0) || (lstX.size()!=lstY.size()) || (lstY.size()!=lstZ.size()) )
42                 {
43                         printf("Warning! CreateMeshFromPoints::Process: List of points X Y Z  and LstIndexes is not correct\n");
44                         bbSetOutputOut(NULL);
45                 } else  {
46                         int ii,sizeSegment1,sizeSegment2;
47                         int endSegment;
48 //                      vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
49                         if (points!=NULL) points->Delete();
50                         points = vtkPoints::New();
51                         int i,sizeLstX  =       lstX.size();
52                         for (i=0;i<sizeLstX;i++)
53                         {
54                                 points->InsertNextPoint(lstX[i],lstY[i],lstZ[i]);
55                         } // for i
56 //                      vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
57                         if (cells!=NULL) cells->Delete();
58                         cells = vtkCellArray::New();
59                         int maxElements;
60                         int maxSegment1,maxSegment2;
61                         int iSeg1,iSeg2;
62                         int iGeneral    =       0;
63                         int     sizeLstIdexes=lstIndexs.size();
64                         for (i=0; i<sizeLstIdexes-1; i++ )
65                         {
66                                 sizeSegment1 = lstIndexs[i];
67                                 sizeSegment2 = lstIndexs[i+1];
68                                 vtkSmartPointer<vtkTriangleStrip> triangleStrip = vtkSmartPointer<vtkTriangleStrip>::New();
69                                 triangleStrip->GetPointIds()->SetNumberOfIds(sizeSegment1+sizeSegment2);
70                                 maxElements=sizeSegment1;
71                                 if (maxElements<sizeSegment2) maxElements=sizeSegment2;
72                                 maxSegment1     = iGeneral+sizeSegment1;
73                                 maxSegment2     = iGeneral+sizeSegment1+sizeSegment2;
74                                 iSeg1           = iGeneral;
75                                 iSeg2           = iGeneral+sizeSegment1;
76                                 for (ii=0; ii<maxElements; ii++)
77                                 {
78                                         triangleStrip->GetPointIds()->SetId(ii*2  ,iSeg1);
79                                         triangleStrip->GetPointIds()->SetId(ii*2+1,iSeg2);
80                                         iSeg1++;
81                                         iSeg2++;
82                         if (iSeg1>=maxSegment1) { iSeg1=maxSegment1-1; }
83                         if (iSeg2>=maxSegment2) { iSeg2=maxSegment2-1; }
84                                 } // for ii 
85                                 iGeneral=iGeneral+sizeSegment1;
86                                 cells->InsertNextCell(triangleStrip);
87                         } //for  LstIndexs
88
89                         if(bbGetInputCloseSurface())
90                         {
91                                 int lastId1 = lstIndexs[0]-1;
92                                 int lastId2 = sizeLstX - 1;
93                                 int firstId2 = sizeLstX - lstIndexs[sizeLstIdexes - 1];
94                                 bool face1open = std::fabs(lstX[0] - lstX[lastId1]) > 0.0001 && std::fabs(lstY[0] - lstY[lastId1]) > 0.0001 && std::fabs(lstZ[0] - lstZ[lastId1]) > 0.0001;
95                                 bool face2open = std::fabs(lstX[firstId2] - lstX[lastId2]) > 0.0001 && std::fabs(lstY[firstId2] - lstY[lastId2]) > 0.0001 && std::fabs(lstZ[firstId2] - lstZ[lastId2]) > 0.0001;
96                                 
97                                 bool altFace1open = std::fabs(lstX[0] - lstX[firstId2]) > 0.0001 && std::fabs(lstY[0] - lstY[firstId2]) > 0.0001 && std::fabs(lstZ[0] - lstZ[firstId2]) > 0.0001;
98                                 bool altFace2open = std::fabs(lstX[lastId1] - lstX[lastId2]) > 0.0001 && std::fabs(lstY[lastId1] - lstY[lastId2]) > 0.0001 && std::fabs(lstZ[lastId1] - lstZ[lastId2]) > 0.0001;
99
100                                 //false = Open Contour
101                                 //true = Closed Contour
102                                 if(!face1open && !face2open)
103                                 {
104 //                                      isClosedCont = true;
105                                         CloseContourSides(lstIndexs, true, true);
106                                 }
107                                 else if(!altFace1open && !altFace2open)
108                                 {
109 //                                      isClosedCont = true;
110                                         CloseContourSides(lstIndexs, false, true);
111                                 }
112                                 else{
113                                         CloseOpenContourSurface(lstIndexs);
114                                 }
115                         }
116                     
117 //                      vtkPolyData *polydata = vtkPolyData::New();
118                         if (polydata!=NULL) polydata->Delete();
119                         polydata = vtkPolyData::New();
120                         polydata->SetPoints(points);
121                         polydata->SetStrips(cells);
122 //                      vtkCleanPolyData *clean=vtkCleanPolyData::New();
123                         if (clean!=NULL) clean->Delete();
124                         clean = vtkCleanPolyData::New();
125                         clean->SetInputData(polydata);
126                         clean->Update();
127 //                      vtkTriangleFilter *triangle = vtkTriangleFilter::New();
128                         if (triangle!=NULL) triangle->Delete();
129                         triangle = vtkTriangleFilter::New();
130                         triangle->SetInputData( clean->GetOutput() );
131                         triangle->Update();
132             bbSetOutputOut( triangle->GetOutput() );
133             //            bbSetOutputOut( clean->GetOutput() );
134                 }// if listXYZ size
135                 //printf("PG CreateMeshFromPoints::Process: End\n");
136 }
137 /**
138 * Closes the sides of the contour
139 * iterates in one way or the other, depending on the order of the points and calculated vectors.
140 * uPointOrder: Points are order in a U shape
141 * lstIndexs: number of points on each spline
142 */
143 void CreateMeshFromPoints::CloseContourSides(std::vector<int> lstIndexs, bool uPointOrder, bool isClosedCont){
144         int     sizeLstIdexes = lstIndexs.size();
145         int sizePoints = bbGetInputLstX().size();
146
147         int firstIndex, end, centroidId, numPointsFace, contraryId;
148         int increment = uPointOrder?1:sizeLstIdexes;
149         double centroid[3];
150         int numProcessFaces = sizeLstIdexes > 1?2:1;
151         for(int facesIdx = 0; facesIdx < numProcessFaces; facesIdx++){
152                 std::fill(std::begin(centroid), std::end(centroid), 0);
153                 if(facesIdx == 0)
154                 {
155                         firstIndex = 0;
156                         numPointsFace = uPointOrder?lstIndexs[0]: sizeLstIdexes;
157                         end = uPointOrder?firstIndex + numPointsFace:sizePoints - lstIndexs[sizeLstIdexes - 1] + 1;
158                         contraryId = sizePoints-1;
159                 }else{
160                         firstIndex = uPointOrder?sizePoints - lstIndexs[sizeLstIdexes-1]:lstIndexs[0]-1;
161                         numPointsFace = uPointOrder?lstIndexs[sizeLstIdexes-1]:sizeLstIdexes;
162                         end = uPointOrder?firstIndex + numPointsFace:sizePoints;
163                         contraryId = 0;
164                 }
165                 if(numPointsFace > 1)
166                 {
167                         bool validCentroid = CalcValidCentroid(centroid, firstIndex, end, increment, numPointsFace);
168                         if(validCentroid)
169                         {
170                                 bool normalOrder    = isPointingCorrectly(firstIndex, firstIndex+increment, centroid, contraryId);
171                                 centroidId          = points->InsertNextPoint(centroid[0], centroid[1], centroid[2]);
172                                 //vtkSmartPointer<vtkTriangleStrip> triangleStrip = vtkSmartPointer<vtkTriangleStrip>::New();
173                                 //triangleStrip->GetPointIds()->SetNumberOfIds(numPointsFace*2 + (!isClosedCont?2:0));
174                                 //int triangleIndex = 0;
175                                 if( normalOrder )
176                 {
177                         int initial = firstIndex;
178                         for(int index = initial; index < end; index+=increment){
179                                                 if(index+increment >= end && !isClosedCont){
180                                                         vtkNew<vtkTriangle> triangle;
181                                                         triangle->GetPointIds()->SetId(0, index);
182                                                         triangle->GetPointIds()->SetId(1, initial);
183                                                         triangle->GetPointIds()->SetId(2, centroidId);
184                                                         cells->InsertNextCell(triangle);
185                                                 }else if(index+increment < end){
186                                                         vtkNew<vtkTriangle> triangle;
187                                                         triangle->GetPointIds()->SetId(0, index);
188                                                         triangle->GetPointIds()->SetId(1, index+increment);
189                                                         triangle->GetPointIds()->SetId(2, centroidId);
190                                                         cells->InsertNextCell(triangle);
191                                                 }
192                                                 /*
193                                                 triangleStrip->GetPointIds()->SetId(triangleIndex,index);
194                                                 triangleStrip->GetPointIds()->SetId(triangleIndex+1,centroidId);//1
195                                                 if(index+increment >= end && !isClosedCont){
196                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+2,initial);//2
197                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+3,centroidId);//3
198                                                 }
199                                                 triangleIndex+=2;
200                                                 */
201                                         }
202                                         //cells->InsertNextCell(triangleStrip);
203                                 } else {
204                                         int initial = firstIndex-1;
205                                         int triangleStripStart = end-1;
206                                         for(int index = triangleStripStart; index > initial; index-=increment){ 
207                                                 if(index-increment <= initial && !isClosedCont){
208                                                         vtkNew<vtkTriangle> triangle;
209                                                         triangle->GetPointIds()->SetId(0, index);
210                                                         triangle->GetPointIds()->SetId(1, triangleStripStart);
211                                                         triangle->GetPointIds()->SetId(2, centroidId);
212                                                         cells->InsertNextCell(triangle);
213                                                 }else if(index-increment > initial){
214                                                         vtkNew<vtkTriangle> triangle;
215                                                         triangle->GetPointIds()->SetId(0, index);
216                                                         triangle->GetPointIds()->SetId(1, index-increment);
217                                                         triangle->GetPointIds()->SetId(2, centroidId);
218                                                         cells->InsertNextCell(triangle);
219                                                 }
220                                                 /**triangleStrip->GetPointIds()->SetId(triangleIndex,index);
221                                                 triangleStrip->GetPointIds()->SetId(triangleIndex+1,centroidId);
222                                                 if(index-increment <= initial && !isClosedCont){
223                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+2,triangleStripStart);
224                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+3,centroidId);
225                                                 }
226                                                 triangleIndex+=2;
227                                                 */
228                                         }
229                                         //cells->InsertNextCell(triangleStrip);
230                                 }//if normalOrder
231                         }//if validCentroid
232                 }//if numPointsFace
233         }//for facesIdx
234
235 }
236
237 /**
238 * Checks if the normal from firstPointId, secPointId and centroid points away 
239 * from the vector centroid to contrPointId.
240 * Used to check that the order used to create the new polygons is correct.
241 */
242 bool CreateMeshFromPoints::isPointingCorrectly( int firstPointId, int secPointId, double(&centroid)[3], int contrPointId) {
243
244         double firstPoint[3], secPoint[3], contrPoint[3];
245         points->GetPoint(firstPointId, firstPoint);
246         points->GetPoint(secPointId, secPoint);
247         
248         double firstVect[3], secVect[3], normal[3], contrVect[3];
249         
250         vtkMath::Subtract(firstPoint, centroid, firstVect);
251         vtkMath::Subtract(secPoint, centroid, secVect);
252         
253         points->GetPoint(contrPointId, contrPoint);
254         vtkMath::Subtract(contrPoint, centroid, contrVect);
255         
256         vtkMath::Cross(firstVect, secVect, normal);
257         double dotCalc;
258         dotCalc = vtkMath::Dot(normal, contrVect);
259         
260         return dotCalc<0;
261 }
262
263 /**
264 * Checks if the order of the points represent a curved spline (U shape) or the points resemble a straight spline.
265 * Now it checks the angle between each point and the vector that goes from the last point to the first.
266 *
267 * Previous version checked the curvature between 3 points in the spline, but this created problems when the straight lines
268 * had curves in the middle, increasing the curvature although they are not in the U shape.
269 */
270 bool CreateMeshFromPoints::CheckLinePointOrder(){
271         int sizePoints = bbGetInputLstX().size();
272         std::vector<int> lstIndexs = bbGetInputLstIndexs();
273         double point1[3], point2[3], point3[3];
274         double center[3];
275         double firstAngleSum = 0;
276         double secondAngleSum = 0;
277
278         points->GetPoint(0, point1);
279         points->GetPoint((lstIndexs[0]-1), point3);
280         double firstVect[3];
281         double secVect[3];
282         vtkMath::Subtract(point3, point1, firstVect);
283         for(int i = 0; i < lstIndexs[0]; i++){
284                 points->GetPoint(i, point2);
285                 vtkMath::Subtract(point2, point1, secVect);
286                 firstAngleSum += vtkMath::SignedAngleBetweenVectors(firstVect, secVect, firstVect);
287         }
288         points->GetPoint((sizePoints-lstIndexs[0]), point3);
289         vtkMath::Subtract(point3, point1, firstVect);
290         for(int i = 0; i < sizePoints; i+=lstIndexs.size()){
291                 points->GetPoint(i, point2);
292                 vtkMath::Subtract(point2, point1, secVect);
293                 secondAngleSum += vtkMath::SignedAngleBetweenVectors(firstVect, secVect, firstVect);
294         }
295
296         return firstAngleSum < secondAngleSum;
297 }
298
299 /**
300 * Closes an open contour
301 * lstIndexs: number of points on each spline
302 */
303 void CreateMeshFromPoints::CloseOpenContourSurface(std::vector<int> lstIndexs){
304         bool linePointOrder = CheckLinePointOrder();
305         CloseContourSides(lstIndexs, !linePointOrder, false);
306         CloseContourBottom(!linePointOrder);
307 }
308
309 /**
310 * Calculates centroid and checks if points are collinear.
311 * centroid: array to store calculation
312 * start: start index of points to use
313 * end: end index of points to use
314 * increment: increment to be used in point iteration
315 * numPoints: number of points used to calculate the centroid.
316 * Returns a bool indicating the validity of the centroid calculated.
317 * False = invalid centroid = all points are the same.
318 */
319 bool CreateMeshFromPoints::CalcValidCentroid(double(&centroid)[3], int start, int end, int increment, int numPoints){
320         double currPoint[3] = {}, prevPoint[3] = {}, middlePoint[3] = {}, firstPoint[3] = {};
321         double vector1[3], vector2[3];
322         bool samePoint = true;
323         int splineMidPoint = numPoints/2;
324         bool collinear = true;
325
326         points->GetPoint(start, firstPoint);
327         points->GetPoint(splineMidPoint, middlePoint);
328         vtkMath::Subtract(middlePoint, firstPoint, vector1);
329
330         for(int i = start; i < end; i+=increment){
331                 points->GetPoint(i, currPoint);
332                 if(samePoint && i > start && (currPoint[0] != prevPoint[0] || currPoint[1] != prevPoint[1] || currPoint[2] != prevPoint[2])){
333                         samePoint = false;
334                 }
335
336                 vtkMath::Subtract(currPoint, firstPoint, vector2);
337                 double angle = vtkMath::AngleBetweenVectors(vector1, vector2);
338                 if(angle > 0.0001 && collinear){
339                         collinear = false;
340                 }
341                 
342                 centroid[0] += currPoint[0];
343                 centroid[1] += currPoint[1];
344                 centroid[2] += currPoint[2];
345                 std::copy(std::begin(currPoint), std::end(currPoint), prevPoint);
346         }
347         
348         centroid[0] /= numPoints;
349         centroid[1] /= numPoints;
350         centroid[2] /= numPoints;
351         
352         return !samePoint && !collinear;
353 }
354
355 /**
356 * Closes the bottom of the given countour.
357 * Should only be used when its an open contour.
358 * uPointOrder: points are ordered in U shape
359 */
360 void CreateMeshFromPoints::CloseContourBottom(bool uPointOrder){
361         std::vector<int> lstIndexs = bbGetInputLstIndexs();
362         int sizeLstIdexes = lstIndexs.size();
363         int sizeLstX = bbGetInputLstX().size();
364         
365         vtkSmartPointer<vtkTriangleStrip> triangleStripBottom = vtkSmartPointer<vtkTriangleStrip>::New();
366         triangleStripBottom->GetPointIds()->SetNumberOfIds(sizeLstIdexes*2);
367         int triangleIndex = 0, currentId = 0, nextId = 0;
368         for(int splineIndex = 0; splineIndex < sizeLstIdexes;splineIndex++){
369                 triangleStripBottom->GetPointIds()->SetId(triangleIndex, currentId);
370                 nextId = uPointOrder?currentId + lstIndexs[splineIndex] - 1:sizeLstX - sizeLstIdexes + splineIndex;
371                 triangleStripBottom->GetPointIds()->SetId(triangleIndex+1, nextId);
372                 triangleIndex+=2;
373                 currentId = uPointOrder?nextId + 1: splineIndex+1;
374         }
375         cells->InsertNextCell(triangleStripBottom);
376 }
377
378 //===== 
379 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
380 //===== 
381 void CreateMeshFromPoints::bbUserSetDefaultValues()
382 {
383
384 //  SET HERE THE DEFAULT INPUT/OUTPUT VALUES OF YOUR BOX 
385 //    Here we initialize the input 'In' to 0
386 //   bbSetInputIn(0);
387         bbSetInputCloseSurface(false);
388         points          = NULL;
389         cells           = NULL;
390         polydata        = NULL;
391         clean           = NULL;
392         triangle        = NULL;
393 }
394 //===== 
395 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
396 //===== 
397 void CreateMeshFromPoints::bbUserInitializeProcessing()
398 {
399
400 //  THE INITIALIZATION METHOD BODY :
401 //    Here does nothing 
402 //    but this is where you should allocate the internal/output pointers 
403 //    if any 
404
405   
406 }
407 //===== 
408 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
409 //===== 
410 void CreateMeshFromPoints::bbUserFinalizeProcessing()
411 {
412
413 //  THE FINALIZATION METHOD BODY :
414 //    Here does nothing 
415 //    but this is where you should desallocate the internal/output pointers 
416 //    if any
417   
418 }
419 }
420 // EO namespace bbcreaVtk
421
422