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