]> Creatis software - creaContours.git/blob - lib/Interface_ManagerContour_NDimensions/wxContourMainFrame.cxx
14359a9f05fffc5b8367cb7aa35c809b6bc1ccbc
[creaContours.git] / lib / Interface_ManagerContour_NDimensions / wxContourMainFrame.cxx
1 /*# ---------------------------------------------------------------------
2 #
3 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
4 #                        pour la Sant�)
5 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
6 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
7 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
8 #
9 #  This software is governed by the CeCILL-B license under French law and
10 #  abiding by the rules of distribution of free software. You can  use,
11 #  modify and/ or redistribute the software under the terms of the CeCILL-B
12 #  license as circulated by CEA, CNRS and INRIA at the following URL
13 #  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
14 #  or in the file LICENSE.txt.
15 #
16 #  As a counterpart to the access to the source code and  rights to copy,
17 #  modify and redistribute granted by the license, users are provided only
18 #  with a limited warranty  and the software's author,  the holder of the
19 #  economic rights,  and the successive licensors  have only  limited
20 #  liability.
21 #
22 #  The fact that you are presently reading this means that you have had
23 #  knowledge of the CeCILL-B license and that you accept its terms.
24 # ------------------------------------------------------------------------ */
25
26 //----------------------------------------------------------------------------------------------------------------
27 // Class definition include
28 //----------------------------------------------------------------------------------------------------------------
29 #include "wxContourMainFrame.h"
30
31
32
33 //----------------------------------------------------------------------------------------------------------------
34 // Includes
35 //----------------------------------------------------------------------------------------------------------------
36
37
38 #include "NameWrapper.h"
39 #include "wx/artprov.h"
40 #include "ConceptDataWrap.h"
41 #include <creaWx.h>
42
43 #include <string>
44 using namespace std;
45
46 //----------------------------------------------------------------------------------------------------------------
47 // Class implementation
48 //----------------------------------------------------------------------------------------------------------------
49 /** @file wxContourMainFrame.cxx */
50
51         //------------------------------------------------------------------------------------------------------------
52         // Constructors & Destructors
53         //------------------------------------------------------------------------------------------------------------
54
55 wxContourMainFrame* wxContourMainFrame:: instance = NULL;
56 char wxContourMainFrame::COPY = 'C';
57
58         wxContourMainFrame :: wxContourMainFrame(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,long style)
59                 //: wxPanel(parent, id, title, pos, size, style)
60                 //: wxWindow(parent, id, pos, size, style)
61                 : wxPanel(parent, id, pos, size, style)
62         {
63                 m_mgr.SetManagedWindow(this);
64                 _contourGroup                           = 1;
65                 _creatingContoursActive         = false;
66                 _theViewPanel                           = NULL;
67 //              _modelManager                           = NULL;
68                 _instantPanel                           = NULL;
69 //              _buttonsBar                                     = NULL;
70 //              _gridPanel                                      = NULL;
71 //              _drawToolsPanel                         = NULL;
72 //              _operationsToolsPanel           = NULL;
73                 //_autoFormsPanel                               = NULL;
74 //              _standardToolsPanel                     = NULL;
75 //              _editionToolsPanel                      = NULL;
76 //              _listViewPanel                          = NULL;
77 //              _sceneManager                           = NULL;
78                 //_actualInstant                                = NULL;
79                 _numberOfVariablesStatistics = 6+1;
80
81                 _refLineControl                         = NULL;
82                 _refLineModel                           = NULL;
83                 _refLineView                            = NULL;
84 //              _actorPresent                           = false;
85
86                 // set up default notebook style
87 //              m_notebook_style =wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
88 //              m_notebook_theme = 0;
89                 //wxContour_ActionCommandsID a;
90
91                 _contourextractdata                     = NULL;
92                 _viewMaskImage                          = NULL;
93                 _viewMaskImagePanel                     = NULL;
94                 _viewThresholdImage                     = NULL;
95                 _viewThresholdImagePanel        = NULL;
96                 _viewColorLayerImagePanel       = NULL;
97                 _frameShowResultImages          = NULL;
98         }
99
100         wxContourMainFrame :: wxContourMainFrame(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,std::vector<vtkImageData*> images, long style,std::string datadir)
101                 : wxPanel(parent, id, pos, size, style)
102         {
103                 m_mgr.SetManagedWindow(this);
104                 _contourGroup                           = 1;
105                 _creatingContoursActive         = false;
106                 _theViewPanel                           = NULL;
107                 _instantPanel                           = NULL;
108                 _refLineControl                         = NULL;
109                 _refLineModel                           = NULL;
110                 _refLineView                            = NULL;
111 //              _actorPresent                           = false;
112                 _viewMaskImage                          = NULL;
113                 _viewMaskImagePanel                     = NULL;
114                 _viewThresholdImage                     = NULL;
115                 _viewThresholdImagePanel        = NULL;
116                 _viewColorLayerImagePanel       = NULL;
117                 // set up default notebook style
118                 m_notebook_style                        = wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
119                 m_notebook_theme                        = 0;
120                 //wxContour_ActionCommandsID a;
121                 _numberOfVariablesStatistics= 7;
122                 _datadir                                        = datadir;
123                 inredo                                          = 0;
124                 inundo                                          = 0;
125                 _pannew = interfMainPanel::getInstance(this,datadir+"/data/Icons");//, eventHandler);
126                 _performingOperation = new PerformingOperation();
127                 if(images.size() > 0)
128                 {
129                         this->setVectImages(images);
130                 }
131                 _contourextractdata                     = NULL;
132 }
133
134 void wxContourMainFrame::setVectImages(std::vector<vtkImageData*> imgs)
135 {
136
137         _images = imgs;
138
139         #if defined(__GNUC__)
140                 std::string str_home(getenv("HOME"));
141         #elif defined(_WIN32)
142                         std::string str_home(getenv("USERPROFILE"));
143         #endif
144                 std::string strCreaContourDataTmp = str_home + "/.creaContourDataTemp/";
145
146         std::vector<std::string> conceptNameVect;
147         std::vector<int> conceptSizeVect;
148
149         notebook = this->createNotebook();
150
151
152         kernelManager = new KernelManagerContour( imgs , _datadir+"/data/" , strCreaContourDataTmp );
153
154
155         _instantPanel                           = new wxInstantChooserPanel( notebook, "Instant Chooser", true, false, "c" );
156         _theViewPanel                           = new wxContourViewPanel( kernelManager->getSourceImage(), notebook );
157
158 //-------------------------------------------------------------
159         kernelManager->getConceptsInformation(conceptNameVect, conceptSizeVect);
160         _instantPanel->addConcepts(conceptNameVect, conceptSizeVect);
161
162
163         double val = _theViewPanel->getCurrentDeep();
164         _instantPanel->setConceptValue( "Axe Depth", (int)val );
165         //JCP _instantPanel->setConceptValue("time", num de imagenes);
166         ConceptDataWrap * data = _instantPanel->getConceptDataOf( "Axe Depth" );
167         //*******************changeInstant();
168         _theViewPanel->setVerticalConcept( "Axe Depth", data->getMinValue(), data->getMaxValue(), data->getMinShowedValue(),  data->getMaxShowedValue(), data->getActualValue() );
169
170         this->configurePanels( );
171
172 }
173
174
175         wxContourMainFrame* wxContourMainFrame :: getInstance(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,std::vector<vtkImageData*> images, long style,std::string datadir )
176         {
177                 if(instance == NULL){
178                         instance = new wxContourMainFrame(parent, id, title, pos, size, images, style,datadir);
179                 }
180                 return instance;
181         }
182
183         std::vector<vtkImageData*> wxContourMainFrame ::getVectImages()
184         {
185                 return kernelManager->getVectImages();
186         }
187
188         wxContourMainFrame* wxContourMainFrame :: getInstance()
189         {
190                 return instance;
191         }
192
193         void wxContourMainFrame :: resetInstance()
194         {
195                 instance->Destroy();
196         }
197
198         wxContourMainFrame :: ~wxContourMainFrame()
199         {
200                 delete _contourextractdata;
201                 deleteAllContours();
202                 _pannew->Close();
203                 interfMainPanel::resetInstance();
204                 delete kernelManager;
205                 instance = NULL;
206                 //_pannew->Destroy();
207                 //delete _pannew;
208
209                 m_mgr.UnInit();
210                 //delete m_mgr;
211
212                 //El problema al cerrar la aplicacion puede estar asociado
213                 //a que  wxAUINotebook esta en la aplicacion
214                 //principal (wxContourGUIExample)tambien
215                 //EED????               delete _theViewPanel;
216                 //EED????               delete _instantPanel;
217                 //EED????               delete _buttonsBar;
218                 //EED????               delete _actualInstant;
219                 //EED????               delete _sceneManager;
220         }
221
222
223         //------------------------------------------------------------------------------------------------------------
224         // Creational and initialization methods using WxAui
225         //------------------------------------------------------------------------------------------------------------
226         //
227         wxAuiNotebook * wxContourMainFrame :: createNotebook()
228         {
229                 wxSize client_size = GetClientSize();
230                 wxAuiNotebook* noteBook = new wxAuiNotebook(this, -1, wxPoint(client_size.x, client_size.y), wxSize(430,200), m_notebook_style);
231                 wxBitmap page_bmp = wxArtProvider::GetBitmap(wxART_NORMAL_FILE, wxART_OTHER, wxSize(16,16));
232                 return noteBook;
233         }
234
235
236         //------------------------------------------------------------------------------------------------------------
237         // Creational and initialization methods
238         //------------------------------------------------------------------------------------------------------------
239         bool wxContourMainFrame :: configurePanels( )
240         {
241                 bool configured = _theViewPanel!=NULL;
242
243                 configured &= _theViewPanel!=NULL;
244                 if( _theViewPanel!=NULL )
245                 {
246                         notebook->AddPage( _theViewPanel, wxT("       View       ") );
247                         m_mgr.Update();
248                 }
249
250
251                 if( configured )
252                 {
253                         notebook->AddPage( _instantPanel, wxT("Instant Page") );
254                         m_mgr.Update();
255                 }
256
257                 m_mgr.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).CenterPane().PaneBorder(false));
258                 m_mgr.Update();
259
260                 SetMinSize(wxSize(300,300));
261                 m_mgr.Update();
262                 return configured;
263         }
264
265
266         bool wxContourMainFrame::addNewPanel(wxPanel* panel)
267                 {
268                 bool configured = panel!=NULL;
269                 configured &= panel!=NULL;
270
271                 if( configured )
272                 {
273                         notebook->AddPage( panel, wxT("       Viewer       "), true );
274                         m_mgr.Update();
275                 }
276                 return configured;
277         }
278
279         //------------------------------------------------------------------------------------------------------------
280         //  Attributes getters and setters
281         //------------------------------------------------------------------------------------------------------------
282
283
284
285         void wxContourMainFrame :: setInstantChooserPanel(  wxInstantChooserPanel * theInstantChooserPanel )
286         {
287                 _instantPanel = theInstantChooserPanel;
288         }
289
290 //      void wxContourMainFrame :: setButtonsBar(  wxContour_ButtonsBar * theButtonsBar )
291 //      {
292 //              _buttonsBar = theButtonsBar;
293 //      }
294
295 //      void wxContourMainFrame :: setGrid(  wxContour_Grid * theGridPanel )
296 //      {
297 //              _gridPanel = theGridPanel;
298 //      }
299
300 //      void wxContourMainFrame :: setDrawToolsPanel(  wxContour_DrawToolsPanel * theDrawToolsPanel )
301 //      {
302 //              _drawToolsPanel = theDrawToolsPanel;
303 //      }
304
305 //      void wxContourMainFrame :: setOperationsToolsPanel(  wxContour_OperationsToolsPanel * theOperationsToolsPanel )
306 //      {
307 //              _operationsToolsPanel = theOperationsToolsPanel;
308 //      }
309
310 //      void wxContourMainFrame :: setAutomaticFormsPanel(  wxContour_AutomaticFormsToolsPanel * theAutoFormsPanel )
311 //      {
312 //              _autoFormsPanel = theAutoFormsPanel;
313 //      }
314
315 //      void wxContourMainFrame :: setStandardToolsPanel(  wxContour_StandardToolsPanel * theStandardToolsPanel )
316 //      {
317 //              _standardToolsPanel= theStandardToolsPanel;
318 //      }
319
320 //      void wxContourMainFrame :: setEditionToolsPanel(  wxContour_EdtionToolsPanel * theEditionToolsPanel )
321 //      {
322 //              _editionToolsPanel =  theEditionToolsPanel;
323 //      }
324
325 //      void wxContourMainFrame :: setListViewPanel(  wxContour_ListViewPanel * theListViewPanel )
326 //      {
327 //              _listViewPanel = theListViewPanel;
328 //      }
329
330
331
332 void wxContourMainFrame::onCreateContourSpline( ){
333
334         //JCP 20-10-08 Undo redo implementation
335         saveState();
336         //JCP 20-10-08 Undo redo implementation
337         createContour( 1 );
338
339 }
340 void wxContourMainFrame::onCreateContourRectangle( ){
341     //JCP 20-10-08 Undo redo implementation
342         saveState();
343         //JCP 20-10-08 Undo redo implementation
344         createContour( 2 );
345 }
346 void wxContourMainFrame::onCreateContourCircle( ){
347     //JCP 20-10-08 Undo redo implementation
348         saveState();
349         //JCP 20-10-08 Undo redo implementation
350         createContour( 3 );
351 }
352
353 void wxContourMainFrame::onCreateContourLine( ){
354     //JCP 20-10-08 Undo redo implementation
355         saveState();
356         //JCP 20-10-08 Undo redo implementation
357         createContour( 6 );
358 }
359
360 // RaC 09-09 --------------------------------------
361 void wxContourMainFrame::onCreateContourPoints( ){
362     //JCP 20-10-08 Undo redo implementation
363         saveState();
364         //JCP 20-10-08 Undo redo implementation
365         createContour( 7 );
366 }
367 // RaC 09-09 --------------------------------------
368
369 // RaC 10-09 --------------------------------------
370 void wxContourMainFrame::onCreateContourPolygon( ){
371     //JCP 20-10-08 Undo redo implementation
372         saveState();
373         //JCP 20-10-08 Undo redo implementation
374         createContour( 10 );
375 }
376 // RaC 10-09 --------------------------------------
377
378 //------------------------------------------------------------------------------------------------------------
379
380 void wxContourMainFrame :: onCreateContourBullEye(wxPanel* panel )
381 {
382         //Creating the manualBaseModel and including in the model
383         manualBaseModel * manModelContour = factoryManualContourModel(panel );
384
385         std::vector<int> instantVector;
386         _instantPanel->getInstant( instantVector );
387         std::string theName = kernelManager->createOutline(manModelContour, instantVector);
388
389         /*std::vector<int> instantVector;
390         _instantPanel->getInstant( instantVector );
391         std::string theName;
392         theName= _modelManager->createOutline( manModelContour, instantVector );*/
393         bool addedModel = theName.compare("") != 0;//??
394
395         if( addedModel )
396         {
397                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
398                 _theViewPanel->getSpacing(spc);
399                 //Adding the manualContourControler to interface objects structure
400                 //Adding the manualViewContour to interface objects structure
401                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
402                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , 4) ;
403         }
404 }
405 void wxContourMainFrame :: createContour( int typeContour )
406 {
407         //Creating the manualContourModel and including in the model
408         manualBaseModel * manModelContour = kernelManager->factoryManualContourModel(typeContour);
409
410         std::vector<int> instantVector;
411         _instantPanel->getInstant( instantVector );
412         std::string theName = kernelManager->createOutline(manModelContour, instantVector);
413
414         /*std::vector<int> instantVector;
415         _instantPanel->getInstant( instantVector );
416         std::string theName;
417         theName= _modelManager->createOutline( manModelContour, instantVector );*/
418         bool addedModel = theName.compare("") != 0;//??
419         if( addedModel )
420         {
421                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
422                 _theViewPanel->getSpacing(spc);
423                 //Adding the manualContourControler to interface objects structure
424                 //Adding the manualViewContour to interface objects structure
425                 //_sceneManager->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
426                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeContour) ;
427         }
428
429 }
430 manualBaseModel * wxContourMainFrame::factoryManualContourModel(wxPanel* panel){
431
432         manualContourModelBullEye *manModelContourBullEye = new manualContourModelBullEye();
433         manualBaseModel *manModelContour=NULL;
434         manModelContour = manModelContourBullEye;
435         if (panel!=NULL){
436                 int iCrown,sizeCrowns,iSector,sizeSectors;
437                 double radioA,radioB,ang,angDelta ;
438                 sizeCrowns = ((PanelBullEyeOptions*)panel)->GetNumberOfCrowns();
439                 for ( iCrown=0 ; iCrown<sizeCrowns ; iCrown++ )
440                 {
441                         sizeSectors = ((PanelBullEyeOptions*)panel)->GetNumberOfSections(iCrown);
442                         radioB  = ((PanelBullEyeOptions*)panel)->GetRadioOfCrown(iCrown);
443                         if (iCrown==sizeCrowns-1)
444                         {
445                                 radioA  = 0;
446                         } else {
447                                 radioA  = ((PanelBullEyeOptions*)panel)->GetRadioOfCrown(iCrown+1);
448                         }
449                         radioA=radioA/100.0;
450                         radioB=radioB/100.0;
451                         for ( iSector=0 ; iSector<sizeSectors  ; iSector++ )
452                         {
453                                 ang             = ((PanelBullEyeOptions*)panel)->GetAngOfCrownSection(iCrown,iSector);
454                                 angDelta= ((PanelBullEyeOptions*)panel)->GetAngDeltaOfCrownSection(iCrown);
455                                 manModelContourBullEye->AddSector(radioA,radioB,ang,angDelta);
456                         } // for iSector
457                 } // for iCrown
458         } // if _panelBullEyeOptions
459
460         return manModelContour;
461 }
462 void wxContourMainFrame :: saveState(){
463
464         std::string temp = kernelManager->saveState();
465         saveFileWithContours(temp);
466 }
467
468 void wxContourMainFrame::onDeleteContour(){
469         //JCP 20-10-08 Undo redo implementation
470                 saveState();
471                 //JCP 20-10-08 Undo redo implementation
472
473                 std::vector<std::string> lstKeyNameToBeErase;
474                 lstKeyNameToBeErase             = _theViewPanel->getSceneManager()->getSelectedObjects();
475                 deleteContours( lstKeyNameToBeErase );
476 /*JCP 19 - 11 - 08
477                 int i,size=_sceneManager->getSelectedObjects().size();
478                 for(i=0;i<size;i++)
479                 {
480                         std::string keyName             = _sceneManager->getSelectedObjects()[i];
481                         int ispartofstaticlist  = this->_modelManager->IsPartOfStaticList( keyName );
482                         if ( ispartofstaticlist>=0 )
483                         {
484                                 std::vector<int> tempVector;
485                                 _instantPanel->getInstant( tempVector );
486                                 Instant instant(&tempVector);
487                                 this->_modelManager->ChangeContourOfList(keyName, &instant);
488                         }
489                 }
490
491                 std::vector<std::string> lstKeyName;
492                 std::vector<std::string> lstKeyNameActualSlice;
493                 std::vector<std::string> lstKeyNameToBeErase;
494
495                 lstKeyNameToBeErase             = _sceneManager->getSelectedObjects();
496                 lstKeyNameActualSlice   = _sceneManager->GetlstContoursNameActualSlice();
497                 int k,kSize=lstKeyNameToBeErase.size();
498                 int j,jSize=lstKeyNameActualSlice.size();
499                 bool ok;
500                 for (k=0;k<kSize; k++)
501                 {
502                         ok=false;
503                         for (j=0;j<jSize; j++)
504                         {
505                                 if (lstKeyNameToBeErase[k]==lstKeyNameActualSlice[j])
506                                 {
507                                         ok=true;
508                                 }
509                         } // for j
510                         if (ok==true)
511                         {
512                                 lstKeyName.push_back( lstKeyNameToBeErase[k] );
513                         } // if ok
514                 } // for k
515
516                 deleteContours( lstKeyName );
517 JCP 19 - 11 - 08*/
518 }
519
520 void wxContourMainFrame :: deleteContours( std::vector<std::string>  keyNamesVector )
521 {
522         int i,size=keyNamesVector.size();
523         for (i=0;i<size;i++)
524         {
525                 deleteContour( keyNamesVector[i] );
526         }
527 }
528
529 void wxContourMainFrame :: deleteContour( std::string theKeyName ){
530         /*
531         manualContourModel                      * cModel;
532         manualViewBaseContour           * cViewer;
533         manualContourBaseControler      * cControler;
534
535         ContourWrap_ViewControl *conwrapviewControl =  _theViewPanel->getSceneManager()->getContourWrap_ViewControlOf( theKeyName );
536         cControler      = conwrapviewControl->getControler();*/
537
538         //JCP 21 - 11 - 2008
539         bool isedit = _theViewPanel->isEditableCControler(theKeyName);
540         bool ispartofstaticlst = kernelManager->IsPartOfStaticList(theKeyName);
541
542         if (isedit  && ispartofstaticlst)
543         {
544                 _theViewPanel->removeFromScene(theKeyName);
545
546                 kernelManager->deleteCModel(theKeyName);
547                 //_theViewPanel->getSceneManager()->removeFromScene( theKeyName );
548                 //cViewer               = conwrapviewControl->getViewer();
549                 //_theViewPanel->getSceneManager()->removeWrap( theKeyName );
550                 //cControler* conwrapviewControl->getControler();
551         //      delete cModel;
552         //      delete cViewer;
553         //      delete cControler;
554         } // if editable
555 //JCP 21 - 11 - 08
556 }
557
558 void wxContourMainFrame::onDeleteContoursActSlice(){
559         //JCP 20-10-08 Undo redo implementation
560         saveState();
561         //JCP 20-10-08 Undo redo implementation
562         deleteContours( (std::vector<std::string>)_theViewPanel->getSceneManager()->GetlstContoursNameActualSlice() );
563 }
564 void wxContourMainFrame::onDeleteAllContours(){
565         //JCP 20-10-08 Undo redo implementation
566         saveState();
567         deleteAllContours();
568 }
569 void wxContourMainFrame::deleteAllContours(){
570         //JCP 20-10-08 Undo redo implementation
571
572         wxBusyCursor wait;
573         std::vector<int> tempVector;
574         _instantPanel->getInstant( tempVector );
575
576 //JCP --08-09-2008 When using a diferent interface the _mbarrangeDeleteAll might not be initialize
577 //              the values in GetStart and GetEnd will then not be initialize also.
578 //              We use instead the values given when initializing the _deletepanel.
579
580         //int minZ = _mbarrangeDeleteAll->GetStart();
581         //int maxZ = _mbarrangeDeleteAll->GetEnd();
582         int minZ, maxZ;
583
584         minZ = 0;
585         maxZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
586
587 //JCP --08-09-2008
588
589         _theViewPanel->getSceneManager()->removeSceneContours( );
590         _theViewPanel->getSceneManager()->removeAllOutlines();
591         kernelManager->removeAllOutlines();
592 //JCP --08-09-2008
593         /*
594         if ( (minZ==0) && (maxZ==_mbarrangeDeleteAll->GetMax() ))
595         {
596                 _theViewPanel->getSceneManager()->removeSceneContours( );
597                 _modelManager->removeAllOutlines();
598                 _theViewPanel->getSceneManager()->removeAllOutlines();
599
600         } else {
601                 for ( z=minZ ; z<=maxZ ; z++)
602                 {
603                         tempVector[1]=z;
604                         Instant instant(&tempVector);
605                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
606
607                         sizeLstContourThings = lstContourThings.size();
608                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
609                         {
610                                 ContourThing **contourthing = lstContourThings[ii];
611                                 deleteContour( (*contourthing)->getName() );
612                         } //for ii
613                 }// for z
614         } // if
615 JCP --08-09-2008 */
616 }
617
618 void wxContourMainFrame::setConceptValue( std::string name, int value ){
619         _instantPanel->setConceptValue(name, value);
620 }
621
622
623 ConceptDataWrap* wxContourMainFrame::getLastConceptData(){
624         return _instantPanel->getLastConceptData();
625 }
626
627
628 bool wxContourMainFrame::getIfConceptCheckedAt( std::string name, int pos ){
629         return _instantPanel->getIfConceptCheckedAt( name, pos );
630 }
631
632
633
634 void wxContourMainFrame::ShowResultImages(int typeContourGroup, int selection, int minZ, int maxZ)
635 {
636         vtkImageData * mask;
637         vtkImageData * value;
638         this->getMaskValue(&mask, &value, typeContourGroup, selection, minZ, maxZ);
639
640         std::vector<int> nTypeView;
641         nTypeView.push_back(5);
642         nTypeView.push_back(1);
643         nTypeView.push_back(2);
644         nTypeView.push_back(0);
645
646         if (_frameShowResultImages==NULL)
647         {
648 //              wxFrame *_frameShowResultImages = new wxFrame(this, -1,_T("Result image extracted.."),wxDefaultPosition,wxSize(600,600), wxDEFAULT_FRAME_STYLE|wxSTAY_ON_TOP);
649                 _frameShowResultImages = new wxFrame(this, -1,_T("Result image extracted.."),wxDefaultPosition,wxSize(600,600), 
650                      wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT | wxRESIZE_BORDER  );
651
652                 wxAuiManager *m_mgr_noteBookViewerResult = new wxAuiManager();
653                 m_mgr_noteBookViewerResult->SetManagedWindow(_frameShowResultImages);
654
655                 wxAuiNotebook* noteBookViewerResult = new wxAuiNotebook(_frameShowResultImages, -1, wxPoint(600, 600), wxSize(430,200), m_notebook_style);
656                 m_mgr_noteBookViewerResult->AddPane(noteBookViewerResult, wxAuiPaneInfo().Name(wxT("notebook_content")).CenterPane().PaneBorder(false));
657
658                 wxPanel *panelViewer1 = new wxMaracas_N_ViewersWidget(noteBookViewerResult, value,&nTypeView);
659                 wxPanel *panelViewer2 = new wxMaracas_N_ViewersWidget(noteBookViewerResult, mask,&nTypeView);
660
661
662                 noteBookViewerResult->AddPage( panelViewer1, wxT("Image result") );
663                 noteBookViewerResult->AddPage( panelViewer2, wxT("Mask result") );
664                 m_mgr_noteBookViewerResult->Update();
665                 _frameShowResultImages->Show();
666         } // if _frameShowResultImages
667 }
668
669
670
671
672 void wxContourMainFrame::changeInstant()
673 {
674                 std::vector<int> instantVect;
675                 _instantPanel->getInstant( instantVect );
676                 int actualSlice = instantVect[1];
677
678                 kernelManager->setInstant(instantVect);
679
680             // Refresh Mask image
681                 if(_viewMaskImage!=NULL){
682                         _viewMaskImage->SetZ(actualSlice);
683                         if (_viewMaskImagePanel->IsVisible()==true)
684                         {
685                                 vtkImageData *mask, *value;
686                                 getMaskValue(&mask,&value, _contourGroup , 0, -1, -1);
687                                 _viewMaskImage->onThreshold();
688                         }
689                 }
690
691         // Refresh Threshold image
692                 if(_viewThresholdImage!=NULL){
693                         _viewThresholdImage->SetZ(actualSlice);
694                         if (_viewThresholdImagePanel->IsVisible()==true){
695                                 _viewThresholdImage->onThreshold();
696                         }
697                 }
698
699
700                 updateInstantOutlines();
701                 updateInstantImageData();
702                 updateInstantAxes();
703 }
704
705
706
707 void wxContourMainFrame :: updateInstantOutlines()
708 {
709         _theViewPanel->removeSceneContours();
710         _theViewPanel->addNameWrapperToScene();
711
712         //for( int i=0; i<size; i++)
713         //{
714         //      _theViewPanel->getSceneManager()->addToScene(namesWrapping[i]->getKeyName(), true, true, true, false, false );
715         //}
716 }
717
718 int wxContourMainFrame::getNamesWrappingSize(){
719         return kernelManager->getNamesWrappingSize();
720 }
721 std::string wxContourMainFrame::getNameWrapping(int i){
722         return kernelManager->getNameWrapping(i);
723 }
724
725 void wxContourMainFrame::updateInstantImageData()
726 {
727         std::vector<int> inst;
728         _instantPanel->getInstant(inst);
729
730         vtkImageData* img = kernelManager->getImageAtInstant(inst);
731         if(img!=NULL){
732                 _theViewPanel->changeImage(img);
733                 showAxis(false);
734         }else{
735                 int z = _instantPanel->getConceptDataOf("Axe Depth")->getActualValue();
736                 _theViewPanel->setImageSlice(z);
737         }
738 }
739
740 void wxContourMainFrame::updateInstantAxes()
741 {
742 }
743
744
745 void wxContourMainFrame::onChangeDeep(int val){
746         _instantPanel->setConceptValue( "Axe Depth", (int)val );
747         changeInstant();
748 }
749
750
751 void wxContourMainFrame::onCopy(){
752         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
753
754         std::vector<int> tempVector;
755         _instantPanel->getInstant( tempVector );
756     _performingOperation->reset();
757         _performingOperation->setStartCommand( COPY );
758         _performingOperation->setStartOperationInstantVector( tempVector );
759         _performingOperation->setKeyNamesOperationElems( currentSelection );
760 }
761
762 void wxContourMainFrame::onPaste(){
763
764
765         char theStartCommand = _performingOperation->getStartCommand();
766         if (  theStartCommand == COPY )
767         {
768                 //JCP 20-10-08 Undo redo implementation
769                 saveState();
770                 //JCP 20-10-08 Undo redo implementation
771                 std::vector<int> tempVector;
772                 _instantPanel->getInstant( tempVector );
773                 _performingOperation->setEndOperationInstantVector ( tempVector );
774                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
775                 int i,size = elems.size();
776                 for( i=0; i<size; i++ )
777                 {
778                         createCopyContourOf( elems[i], tempVector, i>0 );
779                 }
780         }
781 }
782 void wxContourMainFrame::onUndo(){
783         std::string filename;
784         if(kernelManager->onUndoSaveFile(filename)){
785                 saveFileWithContours(filename);
786         }
787         if(kernelManager->onUndo(filename)){
788                 loadState(filename);
789         }
790 }
791 void wxContourMainFrame::onRedo(){
792         std::string filename;
793         if(kernelManager->onRedo(filename)){
794                 loadState(filename);
795         }
796
797 }
798 void wxContourMainFrame :: createCopyContourOf ( std::string anExistingKName, std::vector<int> &instantNoTouchData, bool append )
799 {
800         std::string cloneName = kernelManager->createCopyContourOf( anExistingKName, instantNoTouchData );
801         manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
802         _theViewPanel->getSceneManager()->createCopyContourOf( anExistingKName, cloneName, manualModel , append );
803 }
804
805 ///AD: 03-09    Copy the object and apply the given transformation
806 void wxContourMainFrame :: createMirrorContourOf ( std::string anExistingKName, std::vector<int> &instantNoTouchData, bool append )
807 {
808         std::string cloneName = kernelManager->createCopyContourOf( anExistingKName, instantNoTouchData );
809         manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
810
811         manualPoint * refPoint1 = _refLineModel->GetManualPoint(0);
812         manualPoint * refPoint2 = _refLineModel->GetManualPoint(1);
813
814         double pnt1X = refPoint1->GetX();
815         double pnt1Y = refPoint1->GetY();
816 //      double pnt1Z = refPoint1->GetZ();
817         double pnt2X = refPoint2->GetX();
818         double pnt2Y = refPoint2->GetY();
819 //      double pnt2Z = refPoint2->GetZ();
820
821         double angle = (atan2(pnt2Y - pnt1Y, pnt2X - pnt1X) * 180 / 3.1415926535897932384626433832795)+90;
822         vtkTransform *t = vtkTransform::New();
823
824         t->PostMultiply();
825         t->Identity();
826         t->Translate(-pnt1X, -pnt1Y, 0);
827         t->RotateZ(-angle);
828         t->Scale(-1,1,1);
829         t->RotateZ(angle);
830         t->Translate(pnt1X, pnt1Y, 0);
831         t->Update();
832
833         int i,size=manualModel->GetSizeLstPoints();
834         for (i=0;i<size;i++)
835         {
836                 manualPoint * mp = manualModel->GetManualPoint(i);
837                 float vecIn[3];
838                 float vecOut[3];
839                 vecIn[0]=mp->GetX();
840                 vecIn[1]=mp->GetY();
841                 vecIn[2]=mp->GetZ();
842                 t->TransformPoint( vecIn, vecOut );
843                 mp->SetPointX( vecOut[0] );
844                 mp->SetPointY( vecOut[1] );
845                 mp->SetPointZ( vecOut[2] );
846         }
847
848         _theViewPanel->getSceneManager()->createCopyContourOf( anExistingKName, cloneName, manualModel , append );
849 }
850
851 //EED04
852 void wxContourMainFrame ::loadState(std::string filename){
853
854         deleteAllContours();
855         onLoadContours(filename,false);
856
857         /* EED Borrame
858         char tmp[255];
859         FILE *pFile=fopen(filename.c_str(),"r+");
860
861         fscanf(pFile,"%s",tmp); // --CreaContour--
862
863         fscanf(pFile,"%s",tmp); // Version
864         fscanf(pFile,"%s",tmp); // 1.0.3 || 1.0.2 || 1.0.1 || 1.0.0
865
866         deleteAllContours();
867
868         loadContours(pFile, false);
869         loadContours(pFile, true);
870
871         fclose(pFile);
872         */
873 }
874
875
876 //EED03
877 /*EED Borrame
878 void wxContourMainFrame::loadContours( FILE *pFile, bool staticContour )
879 {
880         char tmp[255];
881
882         if (staticContour==false)
883         {
884                 fscanf(pFile,"%s",tmp); // ImageDimensions
885                 fscanf(pFile,"%s",tmp); // X
886                 fscanf(pFile,"%s",tmp); // Y
887                 fscanf(pFile,"%s",tmp); // Z
888
889                 fscanf(pFile,"%s",tmp); // ImageSpacing
890                 fscanf(pFile,"%s",tmp); // X
891                 fscanf(pFile,"%s",tmp); // Y
892                 fscanf(pFile,"%s",tmp); // Z
893         }
894
895         fscanf(pFile,"%s",tmp); // NumberOfContours
896         fscanf(pFile,"%s",tmp); // ##
897         int numberOfContours = atoi(tmp);
898
899         std::vector<int> instantVector;
900         int typeContourModel;
901         manualBaseModel *manModelContour;
902         int typeView;
903
904         int i;
905         for (i=0;i<numberOfContours;i++)
906         {
907                 instantVector.clear();
908                 fscanf(pFile,"%s",tmp); // Instant
909                 fscanf(pFile,"%s",tmp); // 1
910                 instantVector.push_back( atoi(tmp) );
911                 fscanf(pFile,"%s",tmp); // 2
912                 instantVector.push_back( atoi(tmp) );
913                 fscanf(pFile,"%s",tmp); // 3
914                 instantVector.push_back( atoi(tmp) );
915                 fscanf(pFile,"%s",tmp); // 4
916                 instantVector.push_back( atoi(tmp) );
917                 fscanf(pFile,"%s",tmp); // 5
918                 instantVector.push_back( atoi(tmp) );
919                 fscanf(pFile,"%s",tmp); // 6
920                 instantVector.push_back( atoi(tmp) );
921
922                 fscanf(pFile,"%s",tmp); // TypeContourModel
923                 fscanf(pFile,"%s",tmp); // ##
924                 typeContourModel = atoi(tmp);
925
926                 manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
927                 manModelContour->Open(pFile);
928
929                 fscanf(pFile,"%s",tmp); // TypeView
930                 fscanf(pFile,"%s",tmp); // ##
931                 typeView = atoi(tmp);
932
933                 std::string theName;
934                 theName = kernelManager->createOutline( manModelContour, instantVector );
935                 bool addedModel = theName.compare("") != 0;
936                 if( addedModel )
937                 {
938                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
939                         _theViewPanel->getSpacing(spc);
940                         //Adding the manualContourControler to interface objects structure
941                         //Adding the manualViewContour to interface objects structure
942                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
943                         _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
944                 }
945
946                 if (staticContour==true)
947                 {
948                         Instant instant(&instantVector);
949                         kernelManager->changeContourOfManager( theName , &instant );
950                 }
951         }// for  numberOfContours
952 }
953 */
954
955
956 void wxContourMainFrame::onLoad()
957 {
958         std::string fileNameContourROI = GetFileLocation();
959 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
960         if(GetFileLocation().empty())
961         {
962 //------------------------------------------------------------------------------------------------------------
963                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxOPEN );
964                 if (dialog.ShowModal() == wxID_OK)
965                 {
966                         fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
967                 }
968         }
969
970         onLoadContours(fileNameContourROI,true);
971 }
972
973
974 void  wxContourMainFrame::SetZForAllContours(int pz)
975 {
976
977         //-- Normal Contours
978
979         std::vector< std::string > lstNameThings;       
980         int i,sizeLstNameThings;
981         int ii,sizeLstPoints;
982         
983         lstNameThings           = kernelManager->GetLstNameThings();
984         sizeLstNameThings       = lstNameThings.size(); 
985         for (i=0 ; i<sizeLstNameThings ; i++)
986         {
987 printf("EED wxContourMainFrame::SetZForAllContours contour=%d \n", i );
988                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
989                 sizeLstPoints = manualModel->GetSizeLstPoints();
990                 for (ii=0 ; ii<sizeLstPoints ; ii++)
991                 {
992                          manualModel->GetManualPoint(ii)->SetPointZ(-900);
993                 }// for ii  list of points
994         }// for i  list of Things
995
996         //-- Static Contours
997
998         lstNameThings           = kernelManager->GetLstNameThingsStatic();
999         sizeLstNameThings       = lstNameThings.size();
1000         for (i=0 ; i<sizeLstNameThings ; i++)
1001         {
1002                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
1003                 sizeLstPoints = manualModel->GetSizeLstPoints();
1004                 for (ii=0 ; ii<sizeLstPoints ; ii++)
1005                 {
1006                          manualModel->GetManualPoint(ii)->SetPointZ(-900);
1007                 }// for ii  list of points
1008         }// for i  list of static things
1009 }
1010
1011
1012
1013 void wxContourMainFrame::onLoadContours(std::string fileNameContourROI, bool interactiveInterface)
1014 {
1015         char tmp[255];
1016         char tmpD[255];
1017
1018         FILE *pFile =fopen(fileNameContourROI.c_str(),"r+");
1019
1020
1021 //CMRU 03-09-09- ----------------------------------------------------------------------------------------------
1022         if(pFile != NULL)
1023         {
1024 //------------------------------------------------------------------------------------------------------------
1025         fileNameContourROI.append("data");
1026                 FILE *pFileData=fopen(fileNameContourROI.c_str(),"r+");
1027                 if(pFileData != NULL)
1028                 {
1029                         fscanf(pFileData,"%s",tmpD); // --CreaContour--
1030                         fscanf(pFileData,"%s",tmpD); // Version
1031                         fscanf(pFileData,"%s",tmpD); // 1.0.3 || 1.0.2 || 1.0.1 || 1.0.0
1032
1033                         fscanf(pFileData,"%s",tmpD); // onePixelSize
1034                         fscanf(pFileData,"%s",tmpD); // #
1035                         _onePixelSize = atof(tmpD);
1036                         fscanf(pFileData,"%s",tmpD); // NumberOfContours
1037                         fscanf(pFileData,"%s",tmpD); // #
1038                 }
1039
1040                 fscanf(pFile,"%s",tmp); // --CreaContour--
1041
1042                 fscanf(pFile,"%s",tmp); // Version
1043                 fscanf(pFile,"%s",tmp); // 1.0.3 || 1.0.2 || 1.0.1 || 1.0.0
1044                 std::string version(tmp);
1045
1046
1047 printf("EED wxContourMainFrame::onLoadContours  version%s \n", version.c_str() );
1048
1049
1050                 //AD:02-06-09
1051         _tmpReadFileTypeOfTransformation=-1;
1052                 if (version=="1.0.3")
1053                 {
1054                     readDimSpc(pFile,interactiveInterface);   // DimSpc interactive ON
1055                         openContours(pFile,pFileData,false);
1056                         openContours(pFile,pFileData,true);     //Load StaticContours
1057                 }       
1058
1059                 if (version=="1.0.2")
1060                 {
1061 //EED001
1062                         readDimSpc(pFile,interactiveInterface); // DimSpc interactive ON
1063                         openContours(pFile,pFileData,false);
1064                         readDimSpc(pFile,false);                // DimSpc interactive OFF
1065                         openContours(pFile,pFileData,true);     // Load StaticContours
1066                         SetZForAllContours(-900);
1067                 }
1068
1069                 //AD:02-06-09
1070                 else if (version=="1.0.1")
1071                 {
1072                         openContours(pFile,pFileData,false); //Skips ImageDimensions and ImageSpacing
1073                         openContours(pFile,pFileData,true); //Load StaticContours, skips ImageDimensions and ImageSpacing
1074                 }
1075
1076                 //AD:02-06-09
1077                 else if (version=="1.0.0")
1078                 {
1079                         openContours(pFile,pFileData,false); //Skips ImageDimensions and ImageSpacing
1080                 }
1081
1082                 fclose(pFile);
1083
1084                 if(pFileData != NULL)
1085                 {
1086                         fclose(pFileData);
1087                 }
1088         }
1089         _theViewPanel->getSceneManager()->removeSceneContours();
1090         changeInstant();
1091 }
1092
1093
1094
1095 void wxContourMainFrame::onImport(){
1096         std::string filename, filenamecontours;
1097         wxFileDialog dialog(NULL, _T("Choose a XML Osirix File"), _T(""), _T(""), _T("*.xml"), wxOPEN );
1098
1099         if (dialog.ShowModal() == wxID_OK)
1100         {
1101                 filename = dialog.GetPath().mb_str();
1102                 filenamecontours = kernelManager->parseOsirixFile(filename);
1103
1104                 if(filenamecontours.compare("") != 0){
1105                         onLoadContours(filenamecontours,true);
1106                 }
1107
1108         }
1109 }
1110 void wxContourMainFrame::onTest(){
1111         std::string filename, filenamecontours;
1112         wxFileDialog dialog(NULL, _T("Choose a File"), _T(""), _T(""), _T("*.*"), wxOPEN );
1113
1114         if (dialog.ShowModal() == wxID_OK)
1115         {
1116                 filename = dialog.GetPath().mb_str();
1117                 std::cout << "This is the filename: " << filename << std::endl;
1118         }
1119 }
1120
1121
1122 //AD: 29-05-09
1123 void wxContourMainFrame::onSave(){
1124 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1125         if(GetFileLocation().empty())
1126         {
1127 //------------------------------------------------------------------------------------------------------------
1128                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxSAVE );
1129                 if (dialog.ShowModal() == wxID_OK)
1130                 {
1131                         std::string fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
1132                         kernelManager->setCurrentFileName(fileNameContourROI);
1133                         saveFileWithContours( fileNameContourROI );
1134                 }
1135         }
1136 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1137         else
1138         {
1139                 std::cout<<"Nombre del archivo: "<<GetFileLocation()<<std::endl;
1140                 std::string fileNameContourROI = GetFileLocation();
1141                 std::cout<<"Nombre del archivo: "<<fileNameContourROI<<std::endl;
1142                 kernelManager->setCurrentFileName(fileNameContourROI);
1143                 saveFileWithContours( fileNameContourROI);
1144         }
1145 //------------------------------------------------------------------------------------------------------------
1146 }
1147
1148 //AD: 29-05-09
1149 void wxContourMainFrame::saveFileWithContours( std::string filename )
1150 {
1151
1152         FILE *pFile=fopen(filename.c_str(),"w+");
1153
1154 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1155         filename.append("data");
1156         std::cout<<"Nombre del archivo: "<<filename<<std::endl;
1157         FILE *pFileData=fopen(filename.c_str(),"w+");
1158 //------------------------------------------------------------------------------------------------------------
1159
1160         std::vector< std::string > lstNameThings;
1161         int i,sizeLstNameThings;
1162
1163         fprintf(pFile,"--CreaContour--\n");
1164         fprintf(pFile,"Version %s\n", "1.0.3" );
1165
1166 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1167         fprintf(pFileData,"--CreaContour--\n");
1168         fprintf(pFileData,"Version %s\n", "1.0.3" );
1169         fprintf(pFileData,"OnePixelSize %f\n", _onePixelSize);
1170
1171 //------------------------------------------------------------------------------------------------------------
1172
1173         vtkImageData *image = _images[0];
1174
1175         int dimRange[3];
1176         image->GetDimensions(dimRange);
1177
1178         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1179
1180         double spaRange[3];
1181         image->GetSpacing(spaRange);
1182
1183         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1184
1185         // Normal Contours
1186
1187         lstNameThings           = kernelManager->GetLstNameThings();
1188         sizeLstNameThings       = lstNameThings.size();
1189         fprintf(pFile,"NumberOfContours %d\n", sizeLstNameThings );
1190
1191 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1192         fprintf(pFileData,"NumberOfContours %d\n", sizeLstNameThings );
1193 //------------------------------------------------------------------------------------------------------------
1194
1195
1196 // EED 2017-05-30
1197         double spc[3];
1198         spc[0]=1; 
1199         spc[1]=1; 
1200         spc[2]=1; 
1201
1202         for (i=0 ; i<sizeLstNameThings ; i++)
1203         {
1204 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1205                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
1206
1207 // EED 2017-05-30
1208 //              double sizeInPixel = manualModel ->GetPathSize(  );
1209                 double sizeInPixel = manualModel ->GetPathSize( spc );
1210
1211                 double realContourSize = sizeInPixel*_onePixelSize;
1212                 manualModel ->SetRealSize(realContourSize);
1213 //------------------------------------------------------------------------------------------------------------
1214
1215         //int size= kernelManager->GetLstNameThings().size();
1216
1217                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1218                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1219         }// for i
1220
1221         //-- Static Contours
1222
1223 //      fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1224 //      fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1225
1226         lstNameThings           = kernelManager->GetLstNameThingsStatic();
1227         sizeLstNameThings       = lstNameThings.size();
1228         fprintf(pFile,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1229
1230 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1231         fprintf(pFileData,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1232 //------------------------------------------------------------------------------------------------------------
1233
1234         for (i=0 ; i<sizeLstNameThings ; i++)
1235         {
1236                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1237                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1238         }// for i
1239         fclose(pFile);
1240         fclose(pFileData);
1241 }
1242
1243
1244 //EED02
1245 void wxContourMainFrame::readDimSpc(FILE *pFile, bool interactiveOption)
1246 {
1247         char tmp[255];
1248         int             imageDim[3];
1249         double          imageSpac[3];
1250         vtkImageData    *image          = _images[0];
1251     image->GetDimensions(imageDim);
1252     image->GetSpacing(imageSpac);
1253
1254     fscanf(pFile,"%s",tmp); // ImageDimensions
1255     fscanf(pFile,"%s",tmp); // X
1256     _tmpReadFileImageDim[0] = atoi(tmp);
1257     fscanf(pFile,"%s",tmp); // Y
1258     _tmpReadFileImageDim[1] = atoi(tmp);
1259     fscanf(pFile,"%s",tmp); // Z
1260     _tmpReadFileImageDim[2] = atoi(tmp);
1261
1262     fscanf(pFile,"%s",tmp); // ImageSpacing
1263     fscanf(pFile,"%s",tmp); // X
1264     _tmpReadFileImageSpac[0] = atof(tmp);
1265     fscanf(pFile,"%s",tmp); // Y
1266     _tmpReadFileImageSpac[1] = atof(tmp);
1267     fscanf(pFile,"%s",tmp); // Z
1268     _tmpReadFileImageSpac[2] = atof(tmp);
1269
1270
1271         if (interactiveOption==true)
1272     {
1273                 //Compare Spacing and Dims in X and Y (Necessary in Z?) - Just for Version 2
1274                 if (imageDim[0]!=_tmpReadFileImageDim[0] || imageDim[1]!=_tmpReadFileImageDim[1] || imageSpac[0]!=_tmpReadFileImageSpac[0] || imageSpac[1]!=_tmpReadFileImageSpac[1])
1275                 {
1276                         wxDialog* dial = new wxDialog (this,-1,_T("Tools"),wxDefaultPosition, wxSize(460,360));
1277                         wxSizer* buttonsSizer = dial->CreateSeparatedButtonSizer(wxOK|wxCANCEL);
1278                         wxBoxSizer *dialSizer = new wxBoxSizer(wxVERTICAL);
1279
1280                         wxString lstOptOperation[2];
1281                         lstOptOperation[0]=_T("By Dimension");
1282                         lstOptOperation[1]=_T("By Spacing");
1283                         wxRadioBox * radioOpts = new wxRadioBox(dial, -1, _T("Type of Transformation"), wxDefaultPosition, wxSize(270,45), 2 , lstOptOperation,  2, wxRA_SPECIFY_COLS);
1284
1285                         dialSizer->Add( new wxStaticText(dial,-1,_T("The image resolution is not compatible with the "))  , 0, wxGROW );
1286                         dialSizer->Add( new wxStaticText(dial,-1,_T("selected Roi file. Do you want to tranform it?"))  , 0, wxGROW );
1287                         dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );
1288                         dialSizer->Add(radioOpts,0,wxGROW);
1289                         dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );
1290                         dialSizer->Add(buttonsSizer,0,wxGROW);
1291                         dial->SetSizer(dialSizer, true);
1292                         dial->Layout();
1293                         dial->ShowModal();
1294
1295                         int _tmpReadFileTypeOfTransformation = -1;
1296 //EED                   bool transform = false;
1297
1298                         if (dial->GetReturnCode() == wxID_OK)
1299                         {
1300                                 _tmpReadFileTypeOfTransformation    = radioOpts->GetSelection();
1301                         }// if wxOK
1302
1303                 } // if dim spc
1304     } // if interactiveOption
1305 }
1306
1307
1308
1309
1310 //AD:04-06-09
1311 void wxContourMainFrame::openContours( FILE *pFile, FILE *pFileData, bool staticContour )
1312 {
1313
1314         char tmp[255];
1315
1316         vtkImageData    *image = _images[0];
1317
1318         int             imageDim[3];
1319         double          imageSpac[3];
1320     image->GetDimensions(imageDim);
1321     image->GetSpacing(imageSpac);
1322
1323
1324         fscanf(pFile,"%s",tmp); // NumberOfContours
1325         fscanf(pFile,"%s",tmp); // ##
1326         int numberOfContours = atoi(tmp);
1327
1328         std::vector<int> instantVector;
1329         int typeContourModel;
1330         manualBaseModel *manModelContour;
1331         int typeView;
1332
1333 /*
1334         if (compatible==true)
1335         {
1336                 int i;
1337                 for (i=0;i<numberOfContours;i++)
1338                 {
1339                         instantVector.clear();
1340                         fscanf(pFile,"%s",tmp); // Instant
1341
1342                         fscanf(pFile,"%s",tmp); // 1
1343                         instantVector.push_back( atoi(tmp) );
1344                         fscanf(pFile,"%s",tmp); // 2
1345                         instantVector.push_back( atoi(tmp) );
1346                         fscanf(pFile,"%s",tmp); // 3
1347                         instantVector.push_back( atoi(tmp) );
1348                         fscanf(pFile,"%s",tmp); // 4
1349                         instantVector.push_back( atoi(tmp) );
1350                         fscanf(pFile,"%s",tmp); // 5
1351                         instantVector.push_back( atoi(tmp) );
1352                         fscanf(pFile,"%s",tmp); // 6
1353                         instantVector.push_back( atoi(tmp) );
1354
1355
1356                         fscanf(pFile,"%s",tmp); // TypeContourModel
1357                         fscanf(pFile,"%s",tmp); // ##
1358                         typeContourModel = atoi(tmp);
1359
1360                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1361                         manModelContour->Open(pFile);
1362                         if(pFileData != NULL)
1363                         {
1364                                 manModelContour->OpenData(pFileData);
1365                         }
1366
1367                         fscanf(pFile,"%s",tmp); // TypeView
1368                         fscanf(pFile,"%s",tmp); // ##
1369                         typeView = atoi(tmp);
1370
1371                         std::string theName;
1372                         theName = kernelManager->createOutline( manModelContour, instantVector );
1373                         bool addedModel = theName.compare("") != 0;
1374                         if( addedModel )
1375                         {
1376                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1377                                 _theViewPanel->getSpacing(spc);
1378                                 //Adding the manualContourControler to interface objects structure
1379                                 //Adding the manualViewContour to interface objects structure
1380                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1381                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1382                         }
1383
1384                         if (staticContour) //StaticContours (will appear in all slices)
1385                         {
1386                                 Instant instant(&instantVector);
1387                                 kernelManager->changeContourOfManager( theName , &instant );
1388                         }
1389
1390                 }// for  numberOfContours
1391         }
1392
1393         else if (compatible==false)
1394         {
1395 */
1396
1397                 int i;
1398                 for (i=0;i<numberOfContours;i++)
1399                 {
1400                         instantVector.clear();
1401                         fscanf(pFile,"%s",tmp); // Instant
1402
1403                         fscanf(pFile,"%s",tmp); // 1
1404                         instantVector.push_back( atoi(tmp) );
1405                         fscanf(pFile,"%s",tmp); // 2
1406                         instantVector.push_back( atoi(tmp) );
1407                         fscanf(pFile,"%s",tmp); // 3
1408                         instantVector.push_back( atoi(tmp) );
1409                         fscanf(pFile,"%s",tmp); // 4
1410                         instantVector.push_back( atoi(tmp) );
1411                         fscanf(pFile,"%s",tmp); // 5
1412                         instantVector.push_back( atoi(tmp) );
1413                         fscanf(pFile,"%s",tmp); // 6
1414                         instantVector.push_back( atoi(tmp) );
1415
1416                         fscanf(pFile,"%s",tmp); // TypeContourModel
1417                         fscanf(pFile,"%s",tmp); // ##
1418                         typeContourModel = atoi(tmp);
1419
1420                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1421                         manModelContour->Open(pFile);
1422                         if(pFileData != NULL)
1423                         {
1424                                 manModelContour->OpenData(pFileData);
1425                         }
1426
1427             if (_tmpReadFileTypeOfTransformation==-1){
1428                 //nothing to do..
1429             } else if (_tmpReadFileTypeOfTransformation==0){
1430                 double transX, transY;
1431                 transX = (double) imageDim[0]/_tmpReadFileImageDim[0];
1432                 transY = (double) imageDim[1]/_tmpReadFileImageDim[1];
1433                 manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1434             } else if (_tmpReadFileTypeOfTransformation==1) {
1435                 double transX, transY;
1436                 transX = (double) _tmpReadFileImageSpac[0]/imageDim[0];
1437                 transY = (double) _tmpReadFileImageSpac[1]/imageDim[1];
1438                 manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1439             }
1440
1441                         fscanf(pFile,"%s",tmp); // TypeView
1442                         fscanf(pFile,"%s",tmp); // ##
1443                         typeView = atoi(tmp);
1444
1445                         std::string theName;
1446                         theName = kernelManager->createOutline( manModelContour, instantVector );
1447                         bool addedModel = theName.compare("") != 0;
1448                         if( addedModel )
1449                         {
1450                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1451                                 _theViewPanel->getSpacing(spc);
1452                                 //Adding the manualContourControler to interface objects structure
1453                                 //Adding the manualViewContour to interface objects structure
1454                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1455                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1456                         }
1457
1458                         if (staticContour) //StaticContours (will appear in all slices)
1459                         {
1460                                 Instant instant(&instantVector);
1461                                 kernelManager->changeContourOfManager( theName , &instant );
1462                         }
1463                 }// for  numberOfContours
1464
1465 /*      }    */
1466
1467 }
1468
1469 void wxContourMainFrame::RefreshInterface(){
1470         changeInstant();
1471         _theViewPanel->RefreshInterface();
1472         //wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
1473         //wxvtk2dbaseview->Refresh();
1474 }
1475
1476 vtkImageData* wxContourMainFrame::getImageData(){
1477         return _theViewPanel->getImageData();
1478 }
1479
1480 void wxContourMainFrame::onSegmentationOneSliceITK(wxString distance, wxString sigma, wxString alfa, wxString beta, wxString propagation, wxString iterations, wxString inflation)
1481 {
1482         //JCP 20-10-08 Undo redo implementation
1483         saveState();
1484         //JCP 20-10-08 Undo redo implementation
1485
1486         wxBusyCursor wait;
1487         int                                     x                                       = _theViewPanel->GetX();
1488         int                                     y                                       = _theViewPanel->GetY();
1489         int                                     z                                       = _theViewPanel->GetZ();
1490         SegmentationOneSliceITK( x,y,z,distance, sigma, alfa, beta, propagation, iterations, inflation);
1491         RefreshInterface();
1492 }
1493
1494 void wxContourMainFrame::SegmentationOneSliceITK(int x, int y, int z, wxString distanc, wxString sigm, wxString alf, wxString bet, wxString prop, wxString iter, wxString inflation)
1495 {
1496         int typeofcontour = 1;
1497         //Image Data
1498         vtkImageData    *imagedata      = getImageData();
1499
1500         //Tipo de pixeles a utilizar internamente en ITK
1501         typedef   float  InternalPixelType;
1502         const     unsigned int    Dimension = 2;
1503         typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
1504
1505         //Tipo de pixeles de salida 1
1506         typedef unsigned char OutputPixelType;
1507         typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
1508
1509         //Tipo de pixeles de salida 2
1510         typedef unsigned short OutputPixelType2;
1511         typedef itk::Image< OutputPixelType2, Dimension > OutputImageType2;
1512
1513         //DefiniciÛn del thresholder
1514         typedef itk::BinaryThresholdImageFilter<
1515                                                         InternalImageType,
1516                                                         OutputImageType    >    ThresholdingFilterType;
1517
1518         //DefiniciÛn del primer filtro de conversiÛn de pixeles
1519         typedef itk::CastImageFilter<
1520                                 OutputImageType, OutputImageType2 >  CastFilterType;
1521
1522         //DefiniciÛn del segundo tipo de conversiÛn de pixeles
1523         typedef itk::CastImageFilter<
1524                                 OutputImageType2, InternalImageType >  CastFilterType2;
1525
1526         //Tercer tipo de conversiÛn
1527         typedef itk::RescaleIntensityImageFilter<
1528                                                                 InternalImageType,
1529                                                                 OutputImageType >   CastFilterType3;
1530
1531         //Cuarto tipo de conversiÛn
1532         typedef itk::RescaleIntensityImageFilter<
1533                                                                 OutputImageType,
1534                                                                 OutputImageType >   CastFilterType4;
1535
1536         ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();
1537
1538         thresholder->SetLowerThreshold( 0.0 );
1539         thresholder->SetUpperThreshold( 128 );
1540
1541         thresholder->SetOutsideValue(  255  );
1542         thresholder->SetInsideValue(  0 );
1543
1544         //DefinciÛn de conexiÛnes entre VTK e ITK y el writer
1545         typedef itk::VTKImageToImageFilter<OutputImageType2> ConnectorType;
1546         typedef itk::ImageToVTKImageFilter<OutputImageType> ConnectorType2;
1547 //EED10JUIN2011 typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
1548
1549         ConnectorType::Pointer connector= ConnectorType::New();
1550         ConnectorType2::Pointer connector2= ConnectorType2::New();
1551
1552
1553         CastFilterType::Pointer filter=CastFilterType::New();
1554         CastFilterType2::Pointer filter2=CastFilterType2::New();
1555
1556         connector->SetInput( imagedata );
1557         filter2->SetInput(connector->GetOutput());
1558
1559         typedef   itk::CurvatureAnisotropicDiffusionImageFilter<
1560                                                                 InternalImageType,
1561                                                                 InternalImageType >  SmoothingFilterType;
1562
1563         SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New();
1564
1565         typedef   itk::GradientMagnitudeRecursiveGaussianImageFilter<
1566                                                                 InternalImageType,
1567                                                                 InternalImageType >  GradientFilterType;
1568
1569         typedef   itk::SigmoidImageFilter<
1570                                                                 InternalImageType,
1571                                                                 InternalImageType >  SigmoidFilterType;
1572
1573         GradientFilterType::Pointer  gradientMagnitude = GradientFilterType::New();
1574
1575         SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New();
1576
1577         sigmoid->SetOutputMinimum(  0.0  );
1578         sigmoid->SetOutputMaximum(  255.0  );
1579
1580
1581         typedef  itk::FastMarchingImageFilter<
1582                                                                 InternalImageType,
1583                                                                 InternalImageType >    FastMarchingFilterType;
1584
1585
1586         FastMarchingFilterType::Pointer  fastMarching = FastMarchingFilterType::New();
1587         
1588 printf("EED wxContourMainFrame::SegmentationOneSliceITK  Skypping this code.  Not compiling   GeodesicActiveContourLevelSetImageFilter     in fedora 17 with ITK 3.20.1 \n ");
1589 /*EED 17 sept 2010
1590  > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > -   Not compiling   GeodesicActiveContourLevelSetImageFilter     in fedora 17 with ITK 3.20.1
1591  
1592  
1593         typedef  itk::GeodesicActiveContourLevelSetImageFilter< InternalImageType,
1594                                         InternalImageType >    GeodesicActiveContourFilterType;
1595         GeodesicActiveContourFilterType::Pointer geodesicActiveContour =
1596                                                                                 GeodesicActiveContourFilterType::New();
1597
1598         typedef  itk::ZeroCrossingImageFilter<
1599                                                                 InternalImageType,
1600                                                                 InternalImageType >    ZeroCrossingFilterType;
1601         ZeroCrossingFilterType::Pointer zeroCrossing =
1602                                                         ZeroCrossingFilterType::New();
1603
1604         const double propagationScaling = atof( crea::wx2std(prop).c_str() );
1605
1606         geodesicActiveContour->SetPropagationScaling( propagationScaling );
1607         geodesicActiveContour->SetCurvatureScaling( 1.0 );
1608         geodesicActiveContour->SetAdvectionScaling( 1.0 );
1609
1610         geodesicActiveContour->SetMaximumRMSError( 0.02 );
1611         int it=atoi(  crea::wx2std(iter).c_str() );
1612         geodesicActiveContour->SetNumberOfIterations( it );
1613
1614         smoothing->SetInput( filter2->GetOutput() );
1615         gradientMagnitude->SetInput( smoothing->GetOutput() );
1616         sigmoid->SetInput( gradientMagnitude->GetOutput() );
1617         fastMarching->SetInput( sigmoid->GetOutput() );
1618         geodesicActiveContour->SetInput( fastMarching->GetOutput() );
1619         geodesicActiveContour->SetFeatureImage( sigmoid->GetOutput() );
1620
1621         zeroCrossing->SetInput( geodesicActiveContour->GetOutput() );
1622         //thresholder->SetInput( zeroCrossing->GetOutput() );
1623         thresholder->SetInput( geodesicActiveContour->GetOutput() );
1624         connector2->SetInput( thresholder->GetOutput()  );
1625  
1626 < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - < - 
1627 */
1628         
1629         
1630         
1631
1632         smoothing->SetTimeStep( 0.125 );
1633         smoothing->SetNumberOfIterations(  5 );
1634         smoothing->SetConductanceParameter( 9.0 );
1635
1636
1637         const double sigma = atof(  crea::wx2std(sigm).c_str() );
1638         gradientMagnitude->SetSigma(  sigma  );
1639
1640         const double alpha =  atof(  crea::wx2std(alf).c_str() );
1641         const double beta  =  atof(  crea::wx2std(bet).c_str() );
1642
1643         sigmoid->SetAlpha( alpha );
1644         sigmoid->SetBeta(  beta  );
1645
1646         typedef FastMarchingFilterType::NodeContainer  NodeContainer;
1647         typedef FastMarchingFilterType::NodeType       NodeType;
1648
1649         NodeContainer::Pointer seeds = NodeContainer::New();
1650
1651         InternalImageType::IndexType  seedPosition;
1652         seedPosition[0] = x;
1653         seedPosition[1] = y;
1654
1655         const double initialDistance = atof( crea::wx2std(distanc).c_str() );
1656
1657         NodeType node;
1658
1659         const double seedValue = - initialDistance;
1660
1661         node.SetValue( seedValue );
1662         node.SetIndex( seedPosition );
1663
1664         seeds->Initialize();
1665         seeds->InsertElement( 0, node );
1666
1667         fastMarching->SetTrialPoints( seeds );
1668
1669         fastMarching->SetSpeedConstant( 1.0 );
1670
1671         fastMarching->SetOutputSize(
1672                         connector->GetOutput()->GetBufferedRegion().GetSize() );
1673
1674         fastMarching->SetStoppingValue( 800 );
1675         try
1676     {
1677
1678         connector2->Update();
1679         vtkImageData *idata = connector2->GetOutput();
1680
1681         vtkMarchingContourFilter* cntVTK = vtkMarchingContourFilter::New( );
1682
1683         cntVTK->SetInput( idata );
1684
1685         cntVTK->SetNumberOfContours( 1 );
1686         cntVTK->SetValue( 0, 255 );
1687         cntVTK->Update( );
1688         cntVTK->UpdateInformation();
1689
1690         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1691         cpd->SetInput( cntVTK->GetOutput( ) );
1692         cpd->Update( );
1693         cpd->UpdateInformation();
1694
1695         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1696         conn->SetExtractionModeToLargestRegion( );
1697         conn->SetInput( cpd->GetOutput( ) );
1698         conn->Update( );
1699         conn->UpdateInformation();
1700
1701         vtkStripper* vtkstripper = vtkStripper::New( );
1702         vtkstripper->SetInput( conn->GetOutput() );
1703         vtkstripper->Update();
1704         vtkstripper->UpdateInformation();
1705
1706         vtkPolyData* polyDataResult =  cntVTK->GetOutput();
1707         //std::cout<<"Points "<<polyDataResult->GetNumberOfPoints()<<std::endl;
1708         polyDataResult->Update( );
1709         polyDataResult->UpdateInformation();
1710
1711         //EED
1712                 /*
1713         ofstream myfile;
1714         myfile.open ("C:/Creatis/example.txt");
1715         myfile << "\n";
1716         polyDataResult->Print(myfile);
1717         myfile << "-------------------------------------\n";
1718         polyDataResult->GetLines()->Print(myfile);
1719         myfile.close();*/
1720
1721         cntVTK          -> Delete();
1722         cpd                     -> Delete();
1723         conn            -> Delete();
1724
1725
1726         //--Calculating control points
1727
1728         std::vector<double> vecX;
1729         std::vector<double> vecY;
1730         std::vector<double> vecXo;
1731         std::vector<double> vecYo;
1732         std::vector<double>::iterator vecXoi;
1733         std::vector<double>::iterator vecYoi;
1734         std::vector<double> vecZ;
1735
1736         std::vector<double> vecCtrlPointX;
1737         std::vector<double> vecCtrlPointY;
1738         std::vector<double> vecCtrlPointZ;
1739
1740
1741         double *p;
1742         double xAct=0;
1743         double yAct=0;
1744         int ii,size=polyDataResult->GetNumberOfPoints();
1745         ofstream myfile;
1746         myfile.open ("C:/Creatis/example2.txt");
1747
1748         size=polyDataResult->GetNumberOfPoints();
1749         for (ii=0;ii<size;ii++)
1750         {
1751                 if(ii==0)
1752                 {
1753                         xAct=x;
1754                         yAct=y;
1755                 }
1756                 p       = polyDataResult->GetPoint(ii);
1757                 double x=p[0];
1758                 double y=p[1];
1759                 /*if(fabs(yAct-y)>20)
1760                 {
1761                         if((xAct-x)>1 || (xAct-x)<-1)
1762                         {
1763                         vecX.push_back( p[0] );
1764                         vecY.push_back( p[1] );
1765                         myfile <<p[0]<<","<<p[1]<<"\n";
1766                         std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1767                 std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1768                 std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1769                         vecZ.push_back( 900 );
1770                         xAct=x;
1771                         yAct=y;
1772                         }
1773                         else
1774                         {
1775                                 vecXo.push_back(p[0]);
1776                                 vecYo.push_back(p[1]);
1777                         }
1778
1779                 }
1780                 else*/ if(fabs(xAct-x)>11)
1781                 {
1782                         vecXo.push_back(p[0]);
1783                         vecYo.push_back(p[1]);
1784                 } else {
1785                         vecX.push_back( p[0] );
1786                         myfile <<p[0]<<","<<p[1]<<"\n";
1787                         //std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1788                         //std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1789                         //std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1790                         vecY.push_back( p[1] );
1791 //EED 2017-12-16
1792                         vecZ.push_back( -900 );
1793                         xAct = x;
1794                         yAct = y;
1795                 } // if xAct
1796
1797
1798         }
1799
1800         while(!vecXo.empty())
1801         {
1802                 vecX.push_back(vecXo.back());
1803                 //std::cout<<" x Siguiente "<<vecXo.back();
1804                 vecXo.pop_back();
1805 //EED 2017-12-16
1806                 vecZ.push_back( -900 );
1807         }
1808         while(!vecYo.empty())
1809         {
1810                 vecY.push_back(vecYo.back());
1811                         vecYo.pop_back();
1812         }
1813         myfile.close();
1814
1815         /*for(int l=0;l<vecX.size();l++)
1816         {
1817                 if(l==0)
1818                 {
1819             vecXo.push_back(p[0]);
1820                         vecYo.push_back(p[1]);
1821                 }
1822                 else
1823                 {
1824                         if(vecXoi[l-1]==)
1825                         {
1826                         }
1827                 }
1828
1829         }*/
1830
1831         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1832
1833         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1834
1835         int method=2;
1836         if (method==0){
1837                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1838         }
1839         else if (method==1){
1840                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1841         }
1842         else if (method==2){
1843                 extractcontrolpoints2d->SetSamplingControlPoints( 15 );
1844                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1845         }
1846         //--Adding contour to the system
1847
1848         std::vector<int> actualInstantVector;
1849         _instantPanel->getInstant( actualInstantVector );
1850         actualInstantVector[1]=z;
1851
1852         int j,sizeCtrPt = vecCtrlPointX.size();
1853
1854         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1855         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1856         if (sizeCtrPt>=3){
1857                 for (j=0 ; j<sizeCtrPt ; j++)
1858                 {
1859                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1860                 } // for
1861                 std::string theName;
1862                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1863                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1864                 bool addedModel = theName.compare("") != 0;
1865                 if( addedModel )
1866                 {
1867                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1868                         _theViewPanel->getSpacing(spc);
1869                         //Adding the manualContourControler to interface objects structure
1870                         //Adding the manualViewContour to interface objects structure
1871                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1872                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1873                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1874                 }       // if addedModel
1875         } // if sizeCtrPt
1876
1877
1878 /*
1879 //EED10JUIN2011
1880                  WriterType::Pointer writer = WriterType::New();
1881          CastFilterType3::Pointer caster = CastFilterType3::New();
1882
1883                  caster->SetInput( gradientMagnitude->GetOutput() );
1884                  writer->SetInput( caster->GetOutput() );
1885                  writer->SetFileName("Gradient Magnitude.png");
1886                  caster->SetOutputMinimum(   0 );
1887                  caster->SetOutputMaximum( 255 );
1888                  writer->Update();
1889
1890                  CastFilterType3::Pointer caster2 = CastFilterType3::New();
1891                  WriterType::Pointer writer2 = WriterType::New();
1892
1893                  caster2->SetInput( sigmoid->GetOutput() );
1894                  writer2->SetInput( caster2->GetOutput() );
1895                  writer2->SetFileName("Sigmoid.png");
1896                  caster2->SetOutputMinimum(   0 );
1897                  caster2->SetOutputMaximum( 255 );
1898                  writer2->Update();
1899
1900                  CastFilterType3::Pointer caster3 = CastFilterType3::New();
1901                  WriterType::Pointer writer3 = WriterType::New();
1902
1903                  caster3->SetInput( fastMarching->GetOutput() );
1904                  writer3->SetInput( caster3->GetOutput() );
1905                  writer3->SetFileName("FastMarching.bmp");
1906                  caster3->SetOutputMinimum(   0 );
1907                  caster3->SetOutputMaximum( 255 );
1908                  writer3->Update();
1909
1910                  CastFilterType3::Pointer caster4 = CastFilterType3::New();
1911                  WriterType::Pointer writer4 = WriterType::New();
1912
1913                  caster4->SetInput( geodesicActiveContour->GetOutput() );
1914                  writer4->SetInput( caster4->GetOutput() );
1915                  writer4->SetFileName("GeodesicActiveContour.png");
1916                  caster4->SetOutputMinimum(   0 );
1917                  caster4->SetOutputMaximum( 255 );
1918                  writer4->Update();
1919
1920                  CastFilterType3::Pointer caster5 = CastFilterType3::New();
1921                  WriterType::Pointer writer5 = WriterType::New();
1922
1923                  caster5->SetInput( zeroCrossing->GetOutput() );
1924                  writer5->SetInput( caster5->GetOutput() );
1925                  writer5->SetFileName("ZeroCrossing.bmp");
1926                  caster5->SetOutputMinimum(   0 );
1927                  caster5->SetOutputMaximum( 255 );
1928                  writer5->Update();
1929 */
1930     }
1931   catch( itk::ExceptionObject & excep )
1932     {
1933     std::cerr << "Exception caught !" << std::endl;
1934     std::cerr << excep << std::endl;
1935     }
1936 }
1937
1938 void wxContourMainFrame::onSegmentationOneSlice(int isovalue,int sampling,int method){
1939
1940         //JCP 20-10-08 Undo redo implementation
1941         saveState();
1942         //JCP 20-10-08 Undo redo implementation
1943
1944         wxBusyCursor wait;
1945         int                                     x                                       = _theViewPanel->GetX();
1946         int                                     y                                       = _theViewPanel->GetY();
1947         int                                     z                                       = _theViewPanel->GetZ();
1948         SegmentationOneSlice( x,y,z,isovalue, sampling, method );
1949         RefreshInterface();
1950 }
1951
1952
1953 void wxContourMainFrame::SegmentationOneSlice( int x, int y, int z, int isovalue, int sampling, int method )
1954 {
1955         int typeofcontour = 1;
1956         //--Extracting Contour
1957         //vtkImageData  *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
1958         vtkImageData    *imagedata      = getImageData();
1959 //              double                  *range          = imagedata->GetScalarRange();
1960 //              double                  thr                     = 1;
1961
1962         vtkImageReslice *imageReslice = vtkImageReslice::New();
1963 //EED
1964 //              double spc[3];
1965 //              imagedata->GetSpacing(spc);
1966 //              x = x*spc[0];
1967 //              y = y*spc[1];
1968 //              z = z*spc[3];
1969
1970         imageReslice->SetInput( imagedata );
1971         imageReslice->SetInformationInput(imagedata);
1972         imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
1973         imageReslice->SetResliceAxesOrigin(0,0,z);
1974         imageReslice->SetOutputDimensionality(2);
1975         imageReslice->SetInterpolationModeToLinear();
1976
1977         imagedata = imageReslice->GetOutput();
1978         imagedata->Update();
1979         imagedata->UpdateInformation();
1980
1981         vtkContourFilter* cntVTK = vtkContourFilter::New( );
1982         cntVTK->SetInput( imagedata );
1983
1984         cntVTK->SetNumberOfContours( 1 );
1985         //cntVTK->SetValue( 0, vmin );
1986 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
1987         cntVTK->SetValue( 1, isovalue );
1988 //      cntVTK->SetValue( 1, vmax );
1989         cntVTK->Update( );
1990         cntVTK->UpdateInformation();
1991
1992         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1993         cpd->SetInput( cntVTK->GetOutput( ) );
1994         cpd->ConvertLinesToPointsOff( );
1995         cpd->Update( );
1996         cpd->UpdateInformation();
1997
1998         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1999         conn->SetExtractionModeToClosestPointRegion( );
2000         //conn->SetMaxRecursionDepth( 3000 );
2001
2002         conn->SetInput( cpd->GetOutput( ) );
2003
2004         conn->SetClosestPoint( x, y, 0 );
2005         conn->Update( );
2006         conn->UpdateInformation();
2007
2008         vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
2009         cpd2->SetInput( conn->GetOutput( ) );
2010         cpd2->Update();
2011         cpd2->UpdateInformation();
2012
2013         vtkStripper* vtkstripper = vtkStripper::New( );
2014         vtkstripper->SetInput( cpd2->GetOutput() );
2015         vtkstripper->Update();
2016         vtkstripper->UpdateInformation();
2017
2018
2019         vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
2020
2021         polyDataResult->Update( );
2022         polyDataResult->UpdateInformation();
2023
2024 /* EED
2025 ofstream myfile;
2026 myfile.open ("c:/temp/example.txt");
2027 myfile << "\n";
2028 polyDataResult->Print(myfile);
2029 myfile << "-------------------------------------\n";
2030 polyDataResult->GetLines()->Print(myfile);
2031 myfile.close();
2032 */
2033
2034         cntVTK          -> Delete();
2035         cpd2            -> Delete();
2036         cpd                     -> Delete();
2037         conn            -> Delete();
2038
2039
2040 //--Calculating control points
2041
2042         std::vector<double> vecX;
2043         std::vector<double> vecY;
2044         std::vector<double> vecZ;
2045
2046         std::vector<double> vecCtrlPointX;
2047         std::vector<double> vecCtrlPointY;
2048         std::vector<double> vecCtrlPointZ;
2049
2050
2051         double *p;
2052         int ii,size=polyDataResult->GetNumberOfPoints();
2053         int id;
2054         for (ii=1;ii<=size;ii++)
2055         {
2056                 id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
2057                 p       = polyDataResult->GetPoint(id);
2058 //              double x=p[0];
2059 //              double y=p[1];
2060                 vecX.push_back( p[0] );
2061                 vecY.push_back( p[1] );
2062 //EED 2017-12-16
2063                 vecZ.push_back( -900 );
2064 //                      vecZ.push_back( p[2] );
2065         }
2066
2067
2068         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
2069         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
2070
2071 //PROOFS
2072         /*if (methodRadiobox->GetSelection()==0){
2073                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2074         }
2075         if (methodRadiobox->GetSelection()==1){
2076                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2077         }
2078         if (methodRadiobox->GetSelection()==2){
2079                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
2080                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2081         }*/
2082
2083         if (method==0){
2084                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2085         }
2086         else if (method==1){
2087                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2088         }
2089         else if (method==2){
2090                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
2091                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2092         }
2093
2094         //--Adding contour to the system
2095
2096         std::vector<int> actualInstantVector;
2097         _instantPanel->getInstant( actualInstantVector );
2098         actualInstantVector[1]=z;
2099
2100         int j,sizeCtrPt = vecCtrlPointX.size();
2101         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
2102         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
2103         if (sizeCtrPt>=3){
2104                 for (j=0 ; j<sizeCtrPt ; j++)
2105                 {
2106                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
2107                 } // for
2108                 std::string theName;
2109                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
2110                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
2111                 bool addedModel = theName.compare("") != 0;
2112                 if( addedModel )
2113                 {
2114                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2115                         _theViewPanel->getSpacing(spc);
2116                         //Adding the manualContourControler to interface objects structure
2117                         //Adding the manualViewContour to interface objects structure
2118                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2119                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
2120                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
2121                 }       // if addedModel
2122         } // if sizeCtrPt
2123 }
2124 int wxContourMainFrame::GetImageDataSizeZ(){
2125         return _theViewPanel->GetImageDataSizeZ();
2126 }
2127
2128 void wxContourMainFrame::GetImageDataRange(double *range){
2129         _theViewPanel->GetImageDataRange(range);
2130 }
2131
2132 void wxContourMainFrame::onSegmentationAllSlice(int minZ,int maxZ,int isovalue,int sampling,int method){
2133         //JCP 20-10-08 Undo redo implementation
2134         saveState();
2135         //JCP 20-10-08 Undo redo implementation
2136
2137         wxBusyCursor wait;
2138         int                                     x                                       = _theViewPanel->GetX();
2139         int                                     y                                       = _theViewPanel->GetY();
2140         int z;
2141         double porcent;
2142         wxString tmpString;
2143         double totalZ = maxZ-minZ+1;
2144         for( z=minZ ; z<=maxZ ; z++ )
2145         {
2146                 porcent = 100.0* (z-minZ)/totalZ;
2147                 tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
2148                 interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(tmpString);
2149                 //_staticTextSegmentation->SetLabel(tmpString);
2150                 SegmentationOneSlice( x,y,z,isovalue, sampling,method );
2151         }
2152         interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(_T("   "));
2153         RefreshInterface();
2154 }
2155
2156
2157 //Creates a reference line to be used as the axis of the mirroring
2158 void wxContourMainFrame::referenceLine()
2159 {
2160         if (_refLineControl==NULL)
2161         {
2162                 wxBusyCursor wait;
2163                 double spc[3];
2164
2165                 vtkImageData *vtkimagedata = _theViewPanel->getImageData();
2166                 vtkimagedata->GetSpacing(spc);
2167
2168                 wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2169
2170                 _refLineControl = new manualLineControler();
2171                 _refLineModel   = new manualContourModelLine();
2172                 _refLineView = new manualViewLine();
2173                 _refLineView->SetModel( _refLineModel );
2174                 _refLineView->SetWxVtkBaseView( viewer2D );
2175                 _refLineView->SetRange( 2 );
2176                 _refLineView->SetZ( 1200 );
2177
2178                 _refLineView->SetSpacing(spc);
2179
2180                 _refLineView->SetColorNormalContour(0, 0, 1);
2181                 _refLineView->SetColorEditContour(0, 0.5, 0.5);
2182                 _refLineView->SetWidthLine(4);
2183
2184                 _refLineControl->SetModelView( _refLineModel , _refLineView );
2185                 vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2186                 style->AddInteractorStyleMaracas( _refLineControl );
2187                 _refLineModel->SetCloseContour(false);
2188                 _refLineControl->CreateNewManualContour();
2189
2190 //AD: Inicializar el mirroring con una linea ya pintada
2191         /*
2192                 double z = _refLineControl->GetZ();
2193
2194                 int imageDim[3];
2195                 image->GetDimensions(imageDim);
2196                 double x = (double) imageDim[0]/2;
2197                 double y1 = (double) (imageDim[1]/2)+15;
2198                 double y2 = (double) (imageDim[1]/2)-15;
2199
2200                 _refLineControl->AddPoint(x,y1,z);
2201                 _refLineControl->AddPoint(x,y2,z);
2202                 _refLineControl->SetCompleteCreation(true);
2203
2204                 _refLineModel->AddPoint(x,y1,z);
2205                 _refLineModel->AddPoint(x,y2,z);
2206                 _refLineModel->UpdateSpline();
2207
2208                 _refLineView->UpdateViewPoint(0);
2209                 _refLineView->UpdateViewPoint(1);
2210         */
2211
2212                 _refLineControl->SetActive(true);
2213                 _refLineView->RefreshContour();
2214         }
2215 }
2216
2217 //Hides the referenceLine
2218 void wxContourMainFrame::refLineHide()
2219 {
2220         if (_refLineControl!=NULL)
2221         {
2222                 if (_refLineControl->GetActive())
2223                 {
2224                         _refLineView->RemoveCompleteContourActor();
2225                         _refLineControl->SetEditable(false);
2226                         _refLineControl->SetActive(false);
2227
2228                         RefreshInterface();
2229                 }
2230         }
2231 }
2232
2233 //Shows the referenceLine
2234 void wxContourMainFrame::refLineShow()
2235 {
2236         if (_refLineControl!=NULL)
2237         {
2238                 if (_refLineControl->GetActive()==false)
2239                 {
2240                         wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2241
2242                         _refLineView->SetModel( _refLineModel );
2243                         _refLineView->SetWxVtkBaseView( viewer2D );
2244                         _refLineView->SetRange( 2 );
2245                         _refLineView->SetZ( 1200 );
2246
2247                         _refLineControl->SetModelView( _refLineModel , _refLineView );
2248                         vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2249                         style->AddInteractorStyleMaracas( _refLineControl );
2250                         _refLineControl->CreateNewManualContour();
2251                         _refLineControl->SetActive(true);
2252                         _refLineView->RefreshContour();
2253
2254                         RefreshInterface();
2255                 }
2256         }
2257 }
2258
2259 void wxContourMainFrame::refLineChangeWidth(int width)
2260 {
2261         _refLineView->SetWidthLine(width);
2262         _refLineView->RefreshContour();
2263
2264         RefreshInterface();
2265 }
2266
2267
2268 void wxContourMainFrame::onMirror()
2269 {
2270         //AD:02-09
2271         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2272         std::vector<std::string> filterCurrentSelection;
2273
2274         std::vector<int> tempVector;
2275         _instantPanel->getInstant( tempVector );
2276     _performingOperation->reset();
2277         _performingOperation->setStartCommand( COPY );
2278         _performingOperation->setStartOperationInstantVector( tempVector );
2279         _performingOperation->setKeyNamesOperationElems( currentSelection );
2280
2281         char theStartCommand = _performingOperation->getStartCommand();
2282         if (  theStartCommand == COPY )
2283         {
2284                 //JCP 20-10-08 Undo redo implementation
2285                 saveState();
2286                 //JCP 20-10-08 Undo redo implementation
2287                 std::vector<int> tempVector;
2288                 _instantPanel->getInstant( tempVector );
2289                 _performingOperation->setEndOperationInstantVector ( tempVector );
2290                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
2291                 int i,size = elems.size();
2292                 for( i=0; i<size; i++ )
2293                 {
2294                         createMirrorContourOf( elems[i], tempVector, i>0 );
2295                 }
2296         }
2297
2298         //deleteContour( _refName );
2299         //_refName = "";
2300 }
2301
2302
2303 void wxContourMainFrame::showAxis(bool show)
2304 {
2305         _theViewPanel->SetVisibleAxis(show);
2306         _theViewPanel->Refresh();
2307 }
2308
2309
2310 void wxContourMainFrame::onRigidPressed(){
2311         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2312         int elementsSelected = currentSelection.size();
2313
2314         if ( elementsSelected >= 1 ){
2315                 //JCP 20-10-08 Undo redo implementation
2316                 saveState();
2317                 //JCP 20-10-08 Undo redo implementation
2318
2319                 std::vector<int> tempVector;
2320                 _instantPanel->getInstant( tempVector );
2321                 Instant instant(&tempVector);
2322
2323                 int i , size=currentSelection.size();
2324                 for ( i=0 ; i<size ; i++ )
2325                 {
2326                         kernelManager->changeContourOfManager(currentSelection[i], &instant);
2327                 } // i
2328         }
2329 }
2330
2331 void wxContourMainFrame::onWidthOfContour(double width){
2332
2333         _theViewPanel->removeSceneContours();
2334         _theViewPanel->SetWidthContour(width);
2335
2336         //_theViewPanel->getSceneManager()->SetWidthContour( width );
2337
2338         RefreshInterface();
2339 }
2340
2341 int wxContourMainFrame::getColorWindow()
2342 {
2343         /*
2344         double range[2];
2345         vtkImageData * img = getImageData();
2346         img->GetScalarRange(range);
2347
2348         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2349
2350         return (int)range[1];
2351         */
2352         return _theViewPanel->getColorWindow();
2353 }
2354
2355 int wxContourMainFrame::getWindowLevel()
2356 {
2357         /*
2358         double range[2];
2359         vtkImageData * img = getImageData();
2360         img->GetScalarRange(range);
2361
2362         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2363
2364         return (int)range[1];
2365         */
2366         return _theViewPanel->getWindowLevel();
2367 }
2368
2369 void wxContourMainFrame::onBrigthnessColorWindowLevel(int colorwindow,int windowlevel){
2370         _theViewPanel->onBrigthnessColorWindowLevel(colorwindow, windowlevel);
2371
2372         RefreshInterface();
2373 }
2374
2375 void wxContourMainFrame::onInterpolation(bool interpolate){
2376         _theViewPanel->onInterpolation(interpolate);
2377         RefreshInterface();
2378 }
2379
2380 void wxContourMainFrame::onChangeInstant(std::string name,int actual){
2381         _instantPanel->setConceptValue( name, actual );
2382 }
2383
2384
2385 void wxContourMainFrame::resetAppend(){
2386         kernelManager->resetAppend();
2387
2388 }
2389
2390
2391 void wxContourMainFrame::onSpreadAdd(){
2392         std::vector<double> vecX;
2393         std::vector<double> vecY;
2394         std::vector<double> vecZ;
2395         _theViewPanel->GetPointsOfActualContour(&vecX , &vecY , &vecZ );
2396         std::vector<int> tempVector;
2397         _instantPanel->getInstant( tempVector );
2398         std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2399         interfMainPanel::getInstance()->appendStringSpread(val);
2400 }
2401
2402
2403 void wxContourMainFrame::onSpreadAddAll(){
2404 //EED02
2405         std::vector<int> tempVector;
2406         _instantPanel->getInstant( tempVector );
2407         int minZ,maxZ;
2408     minZ        = 0;
2409     maxZ        = interfMainPanel::getInstance()->GetImageDataSizeZ();
2410         int z;
2411         int sizeLstContourThings;
2412         for ( z=minZ ; z<=maxZ ; z++ )
2413         {
2414                 tempVector[1]=z;
2415                 Instant instant(&tempVector);
2416                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2417                 sizeLstContourThings = lstContourThings.size();
2418                 if (sizeLstContourThings>=1)
2419         {
2420             std::vector<double> vecX;
2421             std::vector<double> vecY;
2422             std::vector<double> vecZ;
2423             ContourThing **contourthing = lstContourThings[0];
2424                         manualBaseModel *cModel                         =  (*contourthing)->getModel();
2425                         int i,size = cModel->GetNumberOfPointsSpline();
2426                         double x,y,z;
2427                         for (i=0; i<size; i++)
2428                         {
2429                                 cModel->GetSpline_i_Point(i, &x, &y, &z);
2430                                 vecX.push_back(x);
2431                                 vecY.push_back(y);
2432                                 vecZ.push_back(z);
2433                         } // for i
2434             std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2435             interfMainPanel::getInstance()->appendStringSpread(val);
2436         }// if sizeLstContourThings
2437     } // for z
2438 }
2439
2440
2441 void wxContourMainFrame::onSpreadGo(int type){
2442         //JCP 20-10-08 Undo redo implementation
2443         saveState();
2444         //JCP 20-10-08 Undo redo implementation
2445         wxBusyCursor wait;
2446         std::vector<double> vecCtrlPointX;
2447         std::vector<double> vecCtrlPointY;
2448         std::vector<double> vecCtrlPointZ;
2449         double  minZ,maxZ;
2450         int z;
2451
2452         std::vector<int> tempVector;
2453         _instantPanel->getInstant( tempVector );
2454 //              tempVector[1];
2455
2456         kernelManager->getMaxMinZ(&minZ,&maxZ);
2457 //JSTG_16-07-08_----------------------------------------------------------------
2458         //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
2459         kernelManager->CalculeSplinePropagation();
2460
2461         double          totalZ = maxZ-minZ+1;
2462         double          porcent;
2463         wxString        tmpString;
2464 //--------------------------------------------------------------------
2465         for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
2466         {
2467                 porcent = 100.0* (z-minZ)/totalZ;
2468                 int numero = (int)(z-minZ+1)/(int)totalZ;
2469                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2470
2471                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2472
2473                 int typeofcontour = 1;
2474                 std::string theName;
2475                 manualBaseModel* manModelContour = kernelManager->GetPoints(z, type, &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ, theName,typeofcontour, tempVector);
2476
2477                 if( manModelContour!=NULL ){
2478                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2479                         this->_theViewPanel->getSpacing(spc);
2480                         //Adding the manualContourControler to interface objects structure
2481                         //Adding the manualViewContour to interface objects structure
2482                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2483                         _theViewPanel->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
2484                 } // if addedModel
2485         }
2486         if(z > maxZ){
2487                 porcent = 100.0;
2488                 int numero = (int)(z-minZ+1)/(int)totalZ;
2489                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2490
2491                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2492         }// for z
2493         //RefreshInterface();
2494 }
2495
2496 void wxContourMainFrame::getInstantVector(std::vector<int>& tempVector){
2497
2498 }
2499
2500 std::vector<std::string> wxContourMainFrame::getOutlinesName(int slide){
2501         std::vector<int> tempVector;
2502         _instantPanel->getInstant(tempVector);
2503         //Asignation of slide number should be different ex by name
2504         tempVector[1]=slide;
2505         return kernelManager->getOutlinesNameAtInstant(tempVector);
2506 }
2507
2508
2509 void wxContourMainFrame::SetScalarRange(int grayRangeMin, int grayRangeMax)
2510 {
2511         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2512 }
2513
2514
2515 void wxContourMainFrame::onInformationContourLabels(int typeContourGroup,int selection,int minimumZ,int maximumZ,int grayRangeMin, int grayRangeMax)
2516 {
2517
2518         wxString tempString;
2519         int maxContourGroup     =       0;
2520
2521         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2522
2523         std::vector<manualBaseModel*> lstManConMod;
2524         std::vector<manualBaseModel*> lstManConModTmp;
2525         std::vector<manualBaseModel*> lstManConModExp;
2526         std::vector<double> pLstValue;
2527         std::vector<double> pLstValuePosX;
2528         std::vector<double> pLstValuePosY;
2529         std::vector<double> pLstValuePosZ;
2530
2531         int             resultSize;
2532         int             resultGrayRangeCount;
2533         double  resultMin;
2534         double  resultMax;
2535         double  resultAverage;
2536         double  resultStandardeviation;
2537
2538         std::vector<int> tempVector;
2539         _instantPanel->getInstant( tempVector );
2540
2541         int z;
2542         int ii,sizeLstContourThings;
2543
2544
2545         int minZ,maxZ;
2546         double totalZ;
2547         double porcent;
2548         wxString tmpString;
2549
2550
2551         if (selection==0 ) // actual slice
2552         {
2553                 int actualSlice = tempVector[1];
2554                 minZ    = actualSlice;
2555                 maxZ    = actualSlice;
2556         }       else  {  // slice range
2557                 minZ    = minimumZ;
2558                 maxZ    = maximumZ;
2559         }
2560
2561
2562         totalZ  = maxZ-minZ+1;
2563
2564         _contourextractdata->InitVolumeStatistics();
2565
2566 // For each slice..
2567         for ( z=minZ ; z<=maxZ ; z++ )
2568         {
2569
2570                 porcent = 100.0* (z-minZ)/totalZ;
2571                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2572
2573                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2574                 //_staticTextInformation->SetLabel(tmpString);
2575
2576                 //Extraction data from contours of each slice
2577                 _contourextractdata->SetZtoBeAnalys(z);
2578
2579                 tempVector[1]=z;
2580                 Instant instant(&tempVector);
2581                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2582                 sizeLstContourThings = lstContourThings.size();
2583
2584                 lstManConMod.clear();
2585                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2586                 {
2587                         ContourThing **contourthing = lstContourThings[ii];
2588                         lstManConMod.push_back( (*contourthing)->getModel() );
2589                 }
2590
2591                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2592
2593                 tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
2594                 interfMainPanel::getInstance()->setRowLabelInfoPanel(z, tempString);
2595                 //_grid->SetRowLabelValue(z, tempString );
2596 //EED004
2597                 int iContourGroup,sizeContourGroup;
2598                 if (typeContourGroup==3) // contour separete
2599                 {
2600                         sizeContourGroup=lstManConModExp.size();
2601                         if ( maxContourGroup<sizeContourGroup )
2602                         {
2603                                 maxContourGroup=sizeContourGroup;
2604                         }
2605                 } else {  // contour AND OR XOR
2606                         sizeContourGroup=1;
2607                         maxContourGroup=1;
2608                 }
2609
2610                 int tmpIntA;
2611
2612                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2613                         lstManConModTmp.clear();
2614
2615
2616
2617                         if (typeContourGroup==3) // contour separete
2618                         {
2619                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2620                         } else {  // contour AND OR XOR
2621                                 lstManConModTmp = lstManConModExp;
2622                         }
2623
2624                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2625                         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2626
2627                         pLstValue.clear();
2628                         pLstValuePosX.clear();
2629                         pLstValuePosY.clear();
2630                         pLstValuePosZ.clear();
2631
2632
2633                         int numberOfPixels;
2634                         _contourextractdata->GetValuesInsideCrown(  &numberOfPixels,
2635                                                                                                                 &pLstValue,
2636                                                                                                                 &pLstValuePosX,
2637                                                                                                                 &pLstValuePosY,
2638                                                                                                                 &pLstValuePosZ);
2639
2640                         resultSize=numberOfPixels;
2641                         // Statistics of each slice.
2642                         _contourextractdata->Statistics( &pLstValue,
2643                                                                                         grayRangeMin,
2644                                                                                         grayRangeMax,
2645                                                                                         &resultGrayRangeCount,
2646                                                                                         &resultSize,
2647                                                                                         &resultMin,
2648                                                                                         &resultMax,
2649                                                                                         &resultAverage,
2650                                                                                         &resultStandardeviation);
2651
2652                         if (interfMainPanel::getInstance()->getNumberColsInformationPanel()<_numberOfVariablesStatistics*(iContourGroup+1)  )
2653                         {
2654                                 interfMainPanel::getInstance()->appendColsInformationPanel(_numberOfVariablesStatistics);
2655                         }
2656
2657                         tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
2658
2659                         tempString.Printf(_T("%d"),numberOfPixels);
2660
2661                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA, tempString);
2662
2663                         tempString.Printf(_T("%d"),resultGrayRangeCount);
2664                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+1, tempString);
2665
2666                         tempString.Printf(_T("%f"),resultMin);
2667                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+2, tempString);
2668
2669                         tempString.Printf(_T("%f"),resultMax);
2670                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+3, tempString);
2671
2672                         tempString.Printf(_T("%f"),resultAverage);
2673                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+4, tempString);
2674
2675                         tempString.Printf(_T("%f"),resultStandardeviation);
2676                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+5, tempString);
2677
2678
2679                 } // for iContourGroup
2680         } // for z
2681
2682         // Print Volume Statistics
2683
2684
2685         int             vol_rCountRange;
2686         int             vol_rsize;
2687         double  vol_minValue;
2688         double  vol_maxValue;
2689         double  vol_average;
2690         double  vol_standardeviation;
2691
2692         if (selection!=0 ) // actual slice
2693         {
2694
2695                 _contourextractdata->GetVolumeStatistics(&vol_rCountRange, &vol_rsize,
2696                                                                                                  &vol_minValue, &vol_maxValue,
2697                                                                                                  &vol_average, &vol_standardeviation);
2698
2699                 interfMainPanel::getInstance()->setRowLabelInfoPanel(maxZ+2, _T("Total:"));
2700
2701                 tempString.Printf(_T("%d"),vol_rsize);
2702                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 0, tempString);
2703
2704                 tempString.Printf(_T("%d"),vol_rCountRange);
2705                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 1, tempString);
2706
2707                 tempString.Printf(_T("%f"),vol_minValue);
2708                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 2, tempString);
2709
2710                 tempString.Printf(_T("%f"),vol_maxValue);
2711                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 3, tempString);
2712
2713                 tempString.Printf(_T("%f"),vol_average);
2714                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 4, tempString);
2715
2716                 tempString.Printf(_T("%f"),vol_standardeviation);
2717                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 5, tempString);
2718         }
2719         //-----------------------------------------
2720
2721         int iTitleGroup;
2722         wxString tmpTitleString;
2723         int tmpIntB;
2724         for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
2725         {
2726                 tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
2727                 tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
2728                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString);
2729
2730                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString );
2731                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 1, _T("Size Range") );
2732                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 2, _T("Min") );
2733                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 3, _T("Max") );
2734                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 4, _T("Average") );
2735                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 5, _T("St.Dev.") );
2736                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 6, _T(" ") );
2737         }// for title
2738         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2739 }
2740
2741 //AD: 29-05-09
2742 void wxContourMainFrame::onSaveResults(std::string directory,std::string namefile, std::string filename,
2743         int typeContourGroup, int selection, int minZ, int maxZ, bool XYZValues, bool contourImage, bool statistics)
2744 {
2745         if (XYZValues)
2746         {
2747                 SaveValuesXYZ( directory , namefile, typeContourGroup );
2748         }
2749
2750         if (contourImage)
2751         {
2752                 vtkImageData * mask;
2753                 vtkImageData * value;
2754                 this->getMaskValue(&mask, &value, typeContourGroup,selection,minZ,maxZ);
2755                 this->SaveImageResult( directory , namefile, mask, value);
2756         }
2757
2758         if (statistics)
2759         {
2760                 std::ostringstream name;
2761                 name << filename << ".xls";
2762
2763
2764                 FILE *pFile=fopen(name.str().c_str(),"w+");
2765
2766
2767                 wxString tmpString;
2768                 int i,j,maxX;
2769
2770 //              int sizeZ = _theViewPanel->GetImageDataSizeZ();
2771 //              int maxY=sizeZ+2;
2772
2773                 maxX= interfMainPanel::getInstance()->getNumberColsInformationPanel();//this->_grid->GetNumberCols();
2774
2775                 // -- Title --
2776                 int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
2777                 for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
2778                 {
2779                                 // fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
2780                                 fprintf(pFile,"slice\t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle );
2781                 }
2782                 fprintf(pFile,"\n\n" );
2783
2784
2785
2786                 if (selection==0 ) // actual slice
2787                 {
2788                         std::vector<int> tempVector;
2789                         _instantPanel->getInstant( tempVector );
2790                         int actualSlice = tempVector[1];
2791                         minZ    = actualSlice;
2792                         maxZ    = actualSlice;
2793                 }
2794
2795                 // Stadistics...
2796                 for ( j=minZ; j<=maxZ ; j++)
2797                 {
2798                         fprintf(pFile,"%d\t" , j );
2799                         for (i=0 ; i<maxX ; i++){
2800                                 tmpString = interfMainPanel::getInstance()->getCellValue(j, i);//_grid->GetCellValue( j , i );
2801                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2802                         } // for i
2803                         fprintf(pFile,"\n"  );
2804                 } // for j
2805
2806
2807                 // Total of stadistics.....
2808                 if (selection!=0)
2809                 {
2810                         fprintf(pFile,"\n Total:\t"  );
2811                         for (i=0 ; i<maxX ; i++){
2812                                 tmpString = interfMainPanel::getInstance()->getCellValue(maxZ+2, i);//_grid->GetCellValue( maxZ+2 , i );
2813                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2814                         } // for i
2815                         fprintf(pFile,"\n"  );
2816                 }
2817
2818                 fclose(pFile);
2819         }
2820 }
2821
2822 //AD: 29-05-09
2823 void wxContourMainFrame::SaveValuesXYZ(std::string directory,std::string namefile,int typeContourGroup)
2824 {
2825         wxBusyCursor wait;
2826
2827         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2828         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2829
2830         std::vector<manualBaseModel*> lstManConMod;
2831         std::vector<manualBaseModel*> lstManConModTmp;
2832         std::vector<manualBaseModel*> lstManConModExp;
2833         std::vector<double> pLstValue;
2834         std::vector<double> pLstValuePosX;
2835         std::vector<double> pLstValuePosY;
2836         std::vector<double> pLstValuePosZ;
2837
2838         std::vector<int> tempVector;
2839         _instantPanel->getInstant( tempVector );
2840
2841         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2842         int z;
2843         int ii,sizeLstContourThings;
2844
2845
2846         int minZ,maxZ;
2847         double totalZ;
2848         double porcent;
2849         wxString tmpString;
2850         minZ    = 0;// _mbarrange->GetStart();
2851         maxZ    = sizeZ;//_mbarrange->GetEnd();
2852         totalZ  = maxZ-minZ+1;
2853
2854
2855 // For each slice..
2856         for ( z=0 ; z<sizeZ ; z++)
2857         {
2858
2859                 porcent = 100.0* (z-minZ)/totalZ;
2860
2861                 tmpString.Printf(_T("Saving Values"));
2862                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2863                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2864                 //_staticTextInformation->SetLabel(tmpString);
2865
2866
2867                 //Extraction data from contours of each slice
2868                 _contourextractdata->SetZtoBeAnalys( z);
2869
2870                 tempVector[1]=z;
2871                 Instant instant(&tempVector);
2872                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant(&instant);//this->_modelManager->getOutlinesAtInstant( &instant );
2873                 sizeLstContourThings = lstContourThings.size();
2874
2875                 lstManConMod.clear();
2876                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2877                 {
2878                         ContourThing **contourthing = lstContourThings[ii];
2879                         lstManConMod.push_back( (*contourthing)->getModel() );
2880                 }
2881                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2882
2883
2884 //EED004
2885
2886                 int iContourGroup,sizeContourGroup;
2887                 if (typeContourGroup==3) // contour separete
2888                 {
2889                         sizeContourGroup=lstManConModExp.size();
2890                 } else {  // contour AND OR XOR
2891                         sizeContourGroup=1;
2892                 }
2893
2894                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2895                         lstManConModTmp.clear();
2896                         if (typeContourGroup==3) // contour separete
2897                         {
2898                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2899                         } else {  // contour AND OR XOR
2900                                 lstManConModTmp = lstManConModExp;
2901                         }
2902
2903                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2904
2905                         pLstValue.clear();
2906                         pLstValuePosX.clear();
2907                         pLstValuePosY.clear();
2908                         pLstValuePosZ.clear();
2909                         int numberOfPixels;
2910                         _contourextractdata->GetValuesInsideCrown(      &numberOfPixels,
2911                                                                                                                 &pLstValue,
2912                                                                                                                 &pLstValuePosX,
2913                                                                                                                 &pLstValuePosY,
2914                                                                                                                 &pLstValuePosZ);
2915
2916                         std::string temp = directory + "/" + namefile + "-slice";
2917                         temp = temp + kernelManager->intToString(z) + "-cont" + kernelManager->intToString(iContourGroup);
2918                         temp = temp + ".txt";
2919
2920                         // LG 14/01/09 : using crea
2921                         wxString filename = crea::std2wx(temp);
2922                         /*filename.Printf(_T("%s"),directory.c_str());
2923                         filename.append(_T("\\"));
2924                         filename.append(_T("%s"),namefile.c_str());
2925                         filename.append(_T("-slice"));
2926                         filename.append(_T("%d"),z);
2927                         filename.append(_T("-cont"));
2928                         filename.append(_T("%d"),iContourGroup);
2929                         filename.append(_T(".txt"));*/
2930                         //                      filename.Printf(temp.c_str());
2931
2932
2933
2934                         FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
2935                         fprintf(pFile,"value \t x \t y \t z\n"  );
2936                         int iLstValue,sizeLstValue=pLstValue.size();
2937                         for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
2938                         {
2939                                 fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
2940                         }
2941                         fclose(pFile);
2942                 } // for  iContourGroup
2943         } // for z
2944         interfMainPanel::getInstance()->setStringInfoPanel(_T(""));
2945         //_staticTextInformation->SetLabel( _T("") );
2946
2947 }
2948
2949 void wxContourMainFrame::getMaskValue(vtkImageData ** mask,vtkImageData ** value,int typeContourGroup, int selection, int minZ, int maxZ){
2950         wxBusyCursor wait;
2951
2952         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2953         if (typeContourGroup==3)
2954         {
2955                 typeContourGroup=1;
2956         }
2957         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2958
2959         std::vector<manualBaseModel*> lstManConMod;
2960         std::vector<manualBaseModel*> lstManConModTmp;
2961         std::vector<manualBaseModel*> lstManConModExp;
2962
2963         std::vector<int> tempVector;
2964         _instantPanel->getInstant( tempVector );
2965
2966     vtkImageData *imagedata = _theViewPanel->getImageData();
2967         int ext[6];
2968         imagedata->GetExtent(ext);
2969         int sizeZimage = ext[5]-ext[4]+1;
2970         int z;
2971         int ii,sizeLstContourThings;
2972
2973         double totalZ;
2974         double porcent;
2975
2976         wxString tmpString;
2977
2978
2979         if (selection==0 ) // actual slice
2980         {
2981                 int actualSlice = tempVector[1];
2982                 minZ    = actualSlice;
2983                 maxZ    = actualSlice;
2984         }
2985
2986         totalZ  = maxZ-minZ;
2987
2988
2989         // cleanning image before range
2990         for (z=0; z<minZ; z++){
2991                 _contourextractdata->ResetImageResult(z);
2992         }
2993         // cleanning image after range
2994         for (z=maxZ+1; z<sizeZimage; z++){
2995                 _contourextractdata->ResetImageResult(z);
2996         }
2997
2998
2999 // For each slice..
3000         for ( z=minZ ; z<=maxZ ; z++)
3001         {
3002
3003                 porcent = 100.0* (z-minZ)/totalZ;
3004                 tmpString.Printf(_T("Saving Values"));
3005                 tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
3006                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
3007
3008                 //Extraction data from contours of each slice
3009                 _contourextractdata->SetZtoBeAnalys( z);
3010
3011                 tempVector[1]=z;
3012                 Instant instant(&tempVector);
3013                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
3014                 sizeLstContourThings = lstContourThings.size();
3015
3016                 lstManConMod.clear();
3017                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
3018                 {
3019                         ContourThing **contourthing = lstContourThings[ii];
3020                         lstManConMod.push_back( (*contourthing)->getModel() );
3021                 }
3022                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
3023
3024
3025                 int iContourGroup,sizeContourGroup;
3026                 if (typeContourGroup==3) // contour separete
3027                 {
3028                         sizeContourGroup=lstManConModExp.size();
3029                 } else {  // contour AND OR XOR
3030                         sizeContourGroup=1;
3031                 }
3032
3033                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
3034                         lstManConModTmp.clear();
3035                         if (typeContourGroup==3) // contour separete
3036                         {
3037                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
3038                         } else {  // contour AND OR XOR
3039                                 lstManConModTmp = lstManConModExp;
3040                         }
3041
3042                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
3043                         _contourextractdata->CalculateImageResult(); // with actual Z
3044
3045                 } // for  iContourGroup
3046         } // for z
3047
3048         (*value) = _contourextractdata->GetVtkImageValueResult();
3049         (*mask)  = _contourextractdata->GetVtkImageMaskResult();
3050
3051 }
3052
3053 std::string wxContourMainFrame::GetStringTypeImage( vtkImageData* image)
3054 {
3055         std::string result="";
3056         if ( image->GetScalarType()==VTK_CHAR )
3057         {
3058                 result="CHAR";
3059         } else if ( image->GetScalarType()==VTK_UNSIGNED_CHAR ){
3060                 result="UCHAR";
3061         } else if ( image->GetScalarType()==VTK_FLOAT ){
3062                 result="FLOAT";
3063         } else if ( image->GetScalarType()==VTK_DOUBLE ){
3064                 result="DOUBLE";
3065         } else if ( image->GetScalarType()==VTK_SHORT ){
3066                 result="SHORT";
3067         } else if ( image->GetScalarType()==VTK_UNSIGNED_SHORT ){
3068                 result="USHORT";
3069         }
3070         return result;
3071 }
3072
3073 void wxContourMainFrame::SaveImageResult(std::string directory,std::string namefile, vtkImageData* mask,vtkImageData* value)
3074 {
3075         std::string stringType;
3076         double spc[3];
3077         kernelManager->GetSpacing(spc,0);   // returns the spacing of the first image
3078         stringType              = GetStringTypeImage(value);
3079         std::string temp = directory + "/" + namefile + "-image-Value-"+stringType+".mhd";
3080
3081         wxString filename = crea::std2wx(temp);
3082
3083 // Image Value
3084         
3085         vtkImageChangeInformation *valueChInfo = vtkImageChangeInformation::New();
3086         valueChInfo->SetInput(value);
3087         valueChInfo->SetSpacingScale(spc);      
3088         vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
3089         writerValueImage->SetInput( valueChInfo->GetOutput() );
3090         writerValueImage->SetFileName( (const char *)filename.mb_str() );
3091         writerValueImage->SetFileDimensionality( 3 );
3092         writerValueImage->SetCompression(false);
3093         writerValueImage->Write( );
3094
3095 // Image Mask
3096         stringType              = GetStringTypeImage(mask);
3097         temp = directory + "/" + namefile + "-image-Mask-"+stringType+".mhd";
3098
3099         // LG 14/01/09 : using crea
3100         filename = crea::std2wx(temp);
3101         //      filename.Printf(_T(temp.c_str()));
3102
3103
3104         vtkImageChangeInformation *maskChInfo = vtkImageChangeInformation::New();
3105         maskChInfo->SetInput(mask);
3106         maskChInfo->SetSpacingScale(spc);       
3107         vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
3108         writerMaskImage->SetInput( maskChInfo->GetOutput() );
3109         writerMaskImage->SetFileName( (const char *)filename.mb_str() );
3110         writerMaskImage->SetFileDimensionality( 3 );
3111         writerMaskImage->SetCompression(false);
3112         writerMaskImage->Write( );
3113
3114         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
3115
3116 }
3117
3118
3119
3120 void wxContourMainFrame::onChangeInstantInstantPanel(std::string name,int value, int minshow, int maxshow){
3121         if( name.compare( _theViewPanel->getVerticalConceptName() ) == 0){
3122                 _theViewPanel->setActualVertical( value);
3123         }
3124         else if( name.compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( name, 0 ) )     {
3125                 _theViewPanel->setHorizontalConcept( name, minshow, maxshow, minshow, maxshow, value);
3126         }
3127
3128         changeInstant();
3129 }
3130
3131 void wxContourMainFrame::onSnakePressed(){
3132         std::vector<double> vecX;
3133         std::vector<double> vecY;
3134         std::vector<double> vecZ;
3135         _theViewPanel->GetPointsOfActualContour( &vecX , &vecY , &vecZ );
3136
3137         if (vecX.size()!=0){
3138                 std::vector<int> tempVector;
3139                 _instantPanel->getInstant( tempVector );
3140                 int i,size=vecZ.size();
3141                 int actualSlice = tempVector[1];
3142                 for ( i=0 ; i<size ; i++ )
3143                 {
3144                         vecZ[i] = actualSlice;
3145                 } // for
3146
3147                 wxDialog* dialog = new wxDialog(this, -1, wxString(_T("Snake")));
3148                 wxPanel* panel = new wxPanel(dialog,-1);
3149                 //              wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
3150          new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
3151                 dialog->ShowModal();
3152         } // if
3153
3154 }
3155
3156 void wxContourMainFrame::saveFileWithContoursAutomatique(){
3157         std::string filename = kernelManager->getCurrentFileName();
3158         if(filename.compare("")!=0){
3159                 saveFileWithContours(filename);
3160         }else{
3161                 onSave();
3162         }
3163 }
3164 void wxContourMainFrame::ShowToolsPanel(bool show){
3165         _pannew->Show(show);
3166 }
3167
3168
3169
3170 void wxContourMainFrame::SetContourGroup(int contourGroup)
3171 {
3172         _contourGroup = contourGroup;
3173 }
3174
3175
3176 wxPanel *wxContourMainFrame::getMaskImageViewPanel(wxWindow *parent)
3177 {
3178  
3179         if      (_viewMaskImagePanel==NULL)
3180         {
3181                 _contourextractdata = new ContourExtractData(true);
3182                 _contourextractdata->SetImage( _theViewPanel->getImageData() );
3183 //              double range[2];
3184 //              _theViewPanel->getImageData()->GetScalarRange(range);
3185                 //int min = (int)floor (range[0]);
3186                 //int max = (int)ceil (range[1]);
3187
3188 //EED 2017-12-17
3189                 int min = 254;
3190                 int max = 256;
3191
3192                 _viewMaskImagePanel = new ThresholdImageViewPanel( parent, -1, -1 , -1,-1,  0);
3193                 _viewMaskImage = new ThresholdImageView();
3194                 _viewMaskImage->SetImage( _contourextractdata->GetVtkImageMaskResult() );
3195                 _viewMaskImage->SetminMaxValue( min, max);
3196                 _viewMaskImage->SetBaseColor( 0,0,1 );
3197
3198
3199                 std::vector<int> colorbarposition;
3200                 colorbarposition.push_back( -999 );
3201                 colorbarposition.push_back( -999 );
3202                 _viewMaskImage->SetColorBarPosition( colorbarposition );
3203                 double spc[3];
3204                 _viewMaskImage->SetSpcBase( _theViewPanel->getImageData()->GetSpacing() );
3205                 _viewMaskImage->SetNewSpacingLayer( _theViewPanel->getImageData()->GetSpacing() );
3206
3207                 _viewMaskImagePanel->SetThresholdImageView( _viewMaskImage );
3208                 _viewMaskImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3209                 _viewMaskImage->onThresholdChangeOpacity( 25 );
3210         }
3211         return _viewMaskImagePanel;
3212 }
3213
3214
3215 wxPanel *wxContourMainFrame::getColorLayerImageViewPanel(wxWindow *parent)
3216 {
3217         if      (_viewColorLayerImagePanel==NULL)
3218         {
3219                 double range[2];
3220                 _theViewPanel->getImageData()->GetScalarRange(range);
3221                 int min = (int)floor (range[0]);
3222                 int max = (int)ceil (range[1]);
3223                 _viewColorLayerImagePanel = new ColorLayerImageViewPanel( parent, min, max, 100, 1);
3224                 _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetwxVtkBaseView( 0 , _theViewPanel->getWxVtkBaseView() );
3225         //    std::vector<double> range = bbGetInputlstRangeForColorBar();
3226         //    clivp->GetColorLayerImageViewManager()->SetRangeForColorBar( range );
3227                 std::vector<int> colorbarposition;
3228                 colorbarposition.push_back( 50 );
3229                 colorbarposition.push_back( 105 );
3230                 _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetColorBarPosition( colorbarposition );
3231         //    std::vector<double> base_color;
3232         //    _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetBaseColors( base_color );
3233         //    std::vector<double> grey_level_boundaries;
3234         //    clivp->GetColorLayerImageViewManager()->SetGreyLevelBoundaries( grey_level_boundaries );
3235                 std::vector<double> transparence_level_boundaries;
3236                 transparence_level_boundaries.push_back(0);
3237                 _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetBaseTransparence( transparence_level_boundaries );
3238                 _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetPlainOrGradientColor( false );
3239 //              _viewColorLayerImagePanel->SetFittingMode( 3 );
3240         }
3241         return _viewColorLayerImagePanel;
3242 }
3243
3244
3245 wxPanel *wxContourMainFrame::getThresholdImageViewPanel(wxWindow *parent)
3246 {
3247         if      (_viewThresholdImagePanel==NULL)
3248         {
3249                 double range[2];
3250                 _theViewPanel->getImageData()->GetScalarRange(range);
3251                 int min = (int)floor (range[0]);
3252                 int max = (int)ceil (range[1]);
3253                 int start= (max+min)/2 - (max-min)*0.25; 
3254                 int end= (max+min)/2 + (max-min)*0.25; 
3255                 _viewThresholdImagePanel = new ThresholdImageViewPanel( parent, min, max, start, end , 1);
3256                 _viewThresholdImage = new ThresholdImageView();
3257                 _viewThresholdImage->SetminMaxValue(start,end);
3258                 _viewThresholdImage->SetImage( _theViewPanel->getImageData() );
3259                 std::vector<int> colorbarposition;
3260                 colorbarposition.push_back( 10 );
3261                 colorbarposition.push_back( 105 );
3262                 _viewThresholdImage->SetColorBarPosition( colorbarposition );
3263                 double spc[3];
3264                 _viewThresholdImage->SetSpcBase( _theViewPanel->getImageData()->GetSpacing() );
3265                 _viewThresholdImage->SetNewSpacingLayer( _theViewPanel->getImageData()->GetSpacing() );
3266
3267                 _viewThresholdImage->SetBaseColor( 1,0,0 );
3268                 _viewThresholdImagePanel->SetThresholdImageView( _viewThresholdImage );
3269                 _viewThresholdImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3270                 _viewThresholdImage->onThresholdChangeOpacity( 25 );
3271                 RefreshInterface();
3272         }
3273         return _viewThresholdImagePanel;
3274 }
3275
3276 //CMRU 17-08-09-----------------------------------------------------------------------------------------------
3277 int wxContourMainFrame::getType ()
3278 {
3279         int tipo = 0;
3280         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3281
3282         if(!currentSelection.empty())
3283         {
3284                 std::string cloneName = currentSelection [0];
3285                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
3286                 tipo = manualModel-> GetTypeModel();
3287         }
3288         return tipo;
3289 }
3290
3291 double wxContourMainFrame::getContourSizeInPixels()
3292 {
3293         double contourSize = 0;
3294
3295         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();        if(!currentSelection.empty())
3296         if(!currentSelection.empty())
3297         {
3298                 std::string cloneName = currentSelection [0];
3299
3300                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3301
3302 // EED 2017-05-30
3303 //              contourSize = manualModel->GetPathSize();
3304                 double spc[3];
3305                 spc[0]=1; 
3306                 spc[1]=1; 
3307                 spc[2]=1; 
3308                 contourSize = manualModel->GetPathSize( spc );
3309         }
3310         return contourSize;
3311 }
3312
3313 manualBaseModel * wxContourMainFrame::getContour ()
3314 {
3315         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3316
3317         if(!currentSelection.empty())
3318         {
3319                 std::string cloneName = currentSelection [0];
3320                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3321                 return manualModel;
3322         }
3323         return NULL;
3324 }
3325 void wxContourMainFrame::onPrintLabel (wxString label, manualBaseModel* manualModel)
3326 {
3327         std::string labelAscii(label.ToAscii());
3328         int pos = labelAscii.find(" ");
3329
3330         int j;
3331
3332         for (j=0 ; pos != string::npos;j++)
3333         {
3334                 labelAscii.replace( pos, 1, "_" );
3335                 pos= labelAscii.find(" ");
3336         }
3337
3338         manualModel -> SetLabel(labelAscii);
3339 }
3340 void wxContourMainFrame::onInsertCalculation(manualBaseModel* manualModel)
3341 {
3342 // EED 2017-05-30
3343 //      double sizeInPixel      = manualModel ->GetPathSize(  );
3344         double spc[3];
3345         spc[0]=1; // ????
3346         spc[1]=1; // ????
3347         spc[2]=1; // ????
3348         double sizeInPixel      = manualModel ->GetPathSize( spc );
3349
3350         double onePixelRealSize = interfMainPanel::getInstance()->GetPixelValue();;
3351         double realContourSize  = sizeInPixel*onePixelRealSize;
3352         manualModel ->SetRealSize(realContourSize);
3353 }
3354
3355 double wxContourMainFrame::onePixelSize( double value)
3356 {
3357         return _onePixelSize = value;
3358 }
3359
3360 std::string wxContourMainFrame::GetFileLocation()
3361 {
3362         return _fileLocation;
3363 }
3364
3365 void wxContourMainFrame::SetFileLocation(std::string newFileLocation)
3366 {
3367         _fileLocation = newFileLocation;
3368         std::cout<<"GETFILELOCATION:"<<_fileLocation<<std::endl;
3369 }
3370 //------------------------------------------------------------------------------------------------------------
3371
3372
3373
3374
3375
3376
3377
3378
3379 void wxContourMainFrame::FlipSelectedContours(int flipDirection)
3380 {
3381         printf("EED wxContourMainFrame::FlipSelectedContours  flipDirection=%d  \n",  flipDirection ); 
3382         FlipLstOfContours( 
3383                             (std::vector<std::string>)_theViewPanel->getSceneManager()->getSelectedObjects() , 
3384                             flipDirection
3385                           );    
3386                 
3387 }
3388
3389 void wxContourMainFrame::FlipActualSliceContours(int flipDirection)
3390 {
3391         printf("EED wxContourMainFrame::FlipActualSliceContours  flipDirection=%d  \n",  flipDirection );       
3392         FlipLstOfContours( 
3393                             (std::vector<std::string>)_theViewPanel->getSceneManager()->GetlstContoursNameActualSlice() , 
3394                             flipDirection
3395                           );    
3396 }
3397
3398 void wxContourMainFrame::FlipAllContours(int flipDirection)
3399 {
3400         printf("EED wxContourMainFrame::FlipAllContours  flipDirection=%d  \n",  flipDirection );
3401         FlipLstOfContours( 
3402                             kernelManager->GetLstNameThings() , 
3403                             flipDirection
3404                           );
3405 }
3406
3407 void wxContourMainFrame::FlipLstOfContours(std::vector<std::string> lstNameThings, int flipDirection)
3408 {
3409         int ext[6];
3410         getImageData()->GetExtent(ext);         
3411         int sizeX = ext[1]-ext[0];
3412         int sizeY = ext[3]-ext[2];
3413
3414         
3415         int i,sizeLstNameThings;
3416         int ii,sizeLstPoints;
3417         
3418         sizeLstNameThings       = lstNameThings.size(); 
3419         for (i=0 ; i<sizeLstNameThings ; i++)
3420         {
3421                 printf("EED wxContourMainFrame::FlipAllContours contour=%d \n", i );
3422                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
3423                 if (flipDirection==0)
3424                 {
3425                         manualModel->Transform_Ax_Plus_B(-1,sizeX,1,0 );
3426                 } else {
3427                         manualModel->Transform_Ax_Plus_B(1,0,-1,sizeY );
3428                 }
3429         }// for i  list of Things
3430
3431         //-- Static Contours
3432
3433         lstNameThings           = kernelManager->GetLstNameThingsStatic();
3434         sizeLstNameThings       = lstNameThings.size();
3435         for (i=0 ; i<sizeLstNameThings ; i++)
3436         {
3437                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
3438                 if (flipDirection==0)
3439                 {
3440                         manualModel->Transform_Ax_Plus_B(-1,sizeX,1,0 );
3441                 } else {
3442                         manualModel->Transform_Ax_Plus_B(1,0,-1,sizeY );
3443                 }
3444         }// for i  list of static things        
3445 }
3446
3447 void wxContourMainFrame::FlipContours(int typeContourFlip, int flipDirection)
3448 {
3449         printf("EED wxContourMainFrame::FlipContours( %d , %d ) \n",typeContourFlip,  flipDirection );
3450
3451         saveState();
3452         
3453         if (typeContourFlip==0) // 
3454         {
3455                 FlipSelectedContours(flipDirection);
3456         }
3457
3458         if (typeContourFlip==1) // 
3459         {
3460                 FlipActualSliceContours(flipDirection);
3461         }
3462         
3463         if (typeContourFlip==2) // 
3464         {
3465                 FlipAllContours(flipDirection);
3466         }
3467         RefreshInterface();
3468 }
3469
3470
3471
3472
3473