]> Creatis software - creaContours.git/blob - lib/Interface_ManagerContour_NDimensions/wxContourMainFrame.cxx
4e810cae54fe05a8a5bb78e44665db12ee571ddd
[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         
1030 //------------------------------------------------------------------------------------------------------------
1031         
1032         vtkImageData *image = _images[0];
1033
1034         int dimRange[3];
1035         image->GetDimensions(dimRange);
1036
1037         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1038
1039         double spaRange[3];
1040         image->GetSpacing(spaRange);
1041
1042         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1043
1044         // Normal Contours
1045         
1046         lstNameThings           = kernelManager->GetLstNameThings();
1047         sizeLstNameThings       = lstNameThings.size(); 
1048         fprintf(pFile,"NumberOfContours %d\n", sizeLstNameThings );
1049
1050 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1051         fprintf(pFileData,"NumberOfContours %d\n", sizeLstNameThings );
1052 //------------------------------------------------------------------------------------------------------------
1053
1054         for (i=0 ; i<sizeLstNameThings ; i++) 
1055         {
1056 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1057                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
1058                 double sizeInPixel = manualModel ->GetPathSize();
1059                 double realContourSize = sizeInPixel*_onePixelSize;
1060                 manualModel ->SetRealSize(realContourSize);
1061 //------------------------------------------------------------------------------------------------------------
1062
1063         //int size= kernelManager->GetLstNameThings().size();
1064
1065                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1066                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1067         }// for i
1068
1069         //-- Static Contours
1070
1071         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1072         
1073         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1074         
1075         lstNameThings           = kernelManager->GetLstNameThingsStatic();
1076         sizeLstNameThings       = lstNameThings.size(); 
1077         fprintf(pFile,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1078
1079 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1080         fprintf(pFileData,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1081 //------------------------------------------------------------------------------------------------------------
1082
1083         for (i=0 ; i<sizeLstNameThings ; i++) 
1084         {
1085                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1086                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1087         }// for i
1088         fclose(pFile);
1089         fclose(pFileData);
1090 }
1091
1092 //AD:04-06-09
1093 void wxContourMainFrame::openContours( FILE *pFile, FILE *pFileData, int version, bool staticContour )
1094 {
1095         char tmp[255];
1096         
1097         vtkImageData *image = _images[0];
1098         int imageDim[3];
1099         double imageSpac[3];
1100         int tempDim[3];
1101         double tempSpac[3];
1102         
1103         bool compatible = true;
1104         
1105         //Version==2    
1106         if (version==2)
1107         {
1108                 image->GetDimensions(imageDim);
1109                 image->GetSpacing(imageSpac);
1110
1111                 fscanf(pFile,"%s",tmp); // ImageDimensions
1112                 fscanf(pFile,"%s",tmp); // X
1113                 tempDim[0] = atoi(tmp);
1114                 fscanf(pFile,"%s",tmp); // Y
1115                 tempDim[1] = atoi(tmp);
1116                 fscanf(pFile,"%s",tmp); // Z
1117                 tempDim[2] = atoi(tmp);
1118
1119                 fscanf(pFile,"%s",tmp); // ImageSpacing
1120                 fscanf(pFile,"%s",tmp); // X
1121                 tempSpac[0] = atof(tmp);
1122                 fscanf(pFile,"%s",tmp); // Y
1123                 tempSpac[1] = atof(tmp);
1124                 fscanf(pFile,"%s",tmp); // Z
1125                 tempSpac[2] = atof(tmp);
1126                 
1127                 //Compare Spacing and Dims in X and Y (Necessary in Z?) - Just for Version 2
1128                 if (imageDim[0]!=tempDim[0] || imageDim[1]!=tempDim[1] || imageSpac[0]!=tempSpac[0] || imageSpac[1]!=tempSpac[1])
1129                 {
1130                         compatible = false;
1131                 }
1132         }
1133         
1134         fscanf(pFile,"%s",tmp); // NumberOfContours 
1135         fscanf(pFile,"%s",tmp); // ##
1136         int numberOfContours = atoi(tmp);  
1137
1138         std::vector<int> instantVector;
1139         int typeContourModel;
1140         manualBaseModel *manModelContour;
1141         int typeView;
1142
1143         if (compatible==true)
1144         {
1145                 int i;
1146                 for (i=0;i<numberOfContours;i++)
1147                 {
1148                         instantVector.clear();
1149                         fscanf(pFile,"%s",tmp); // Instant
1150
1151                         fscanf(pFile,"%s",tmp); // 1
1152                         instantVector.push_back( atoi(tmp) );
1153                         fscanf(pFile,"%s",tmp); // 2
1154                         instantVector.push_back( atoi(tmp) );
1155                         fscanf(pFile,"%s",tmp); // 3
1156                         instantVector.push_back( atoi(tmp) );
1157                         fscanf(pFile,"%s",tmp); // 4
1158                         instantVector.push_back( atoi(tmp) );
1159                         fscanf(pFile,"%s",tmp); // 5
1160                         instantVector.push_back( atoi(tmp) );
1161                         fscanf(pFile,"%s",tmp); // 6
1162                         instantVector.push_back( atoi(tmp) );
1163
1164
1165                         fscanf(pFile,"%s",tmp); // TypeContourModel
1166                         fscanf(pFile,"%s",tmp); // ##
1167                         typeContourModel = atoi(tmp);
1168
1169                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1170                         manModelContour->Open(pFile);
1171                         if(pFileData != NULL)
1172                         {
1173                                 manModelContour->OpenData(pFileData);
1174                         }
1175
1176                         fscanf(pFile,"%s",tmp); // TypeView
1177                         fscanf(pFile,"%s",tmp); // ##
1178                         typeView = atoi(tmp);  
1179
1180                         std::string theName;
1181                         theName = kernelManager->createOutline( manModelContour, instantVector );
1182                         bool addedModel = theName.compare("") != 0;
1183                         if( addedModel )
1184                         {
1185                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1186                                 _theViewPanel->getSpacing(spc);                                 
1187                                 //Adding the manualContourControler to interface objects structure
1188                                 //Adding the manualViewContour to interface objects structure           
1189                                 //_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.
1190                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1191                         }       
1192
1193                         if (staticContour) //StaticContours (will appear in all slices)
1194                         {
1195                                 Instant instant(&instantVector);
1196                                 kernelManager->changeContourOfManager( theName , &instant );
1197                         }
1198
1199                 }// for  numberOfContours       
1200         }
1201
1202         else if (compatible==false)
1203         {
1204                 wxDialog* dial = new wxDialog (this,-1,_T("Tools"),wxDefaultPosition, wxSize(260,160));
1205                 wxSizer* buttonsSizer = dial->CreateSeparatedButtonSizer(wxOK|wxCANCEL);
1206                 wxBoxSizer *dialSizer = new wxBoxSizer(wxVERTICAL);
1207
1208                 wxString lstOptOperation[2];
1209                 lstOptOperation[0]=_T("By Dimension");
1210                 lstOptOperation[1]=_T("By Spacing");
1211                 wxRadioBox * radioOpts = new wxRadioBox(dial, -1, _T("Type of Transformation"), wxDefaultPosition, wxSize(270,45), 2 , lstOptOperation,  2, wxRA_SPECIFY_COLS);         
1212                 
1213                 dialSizer->Add( new wxStaticText(dial,-1,_T("The image resolution is not compatible with the "))  , 0, wxGROW );
1214                 dialSizer->Add( new wxStaticText(dial,-1,_T("selected Roi file. Do you want to tranform it?"))  , 0, wxGROW );  
1215                 dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );               
1216                 dialSizer->Add(radioOpts,0,wxGROW);
1217                 dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );       
1218                 dialSizer->Add(buttonsSizer,0,wxGROW);
1219                 dial->SetSizer(dialSizer, true);
1220                 dial->Layout();
1221                 dial->ShowModal();
1222                 
1223                 int typeOfTransformation = -1;
1224                 bool transform = false;
1225
1226                 if (dial->GetReturnCode() == wxID_OK)
1227                 {
1228                         typeOfTransformation = radioOpts->GetSelection();
1229                         transform = true;
1230                 }
1231         
1232                 int i;
1233                 for (i=0;i<numberOfContours;i++)
1234                 {
1235                         instantVector.clear();
1236                         fscanf(pFile,"%s",tmp); // Instant
1237
1238                         fscanf(pFile,"%s",tmp); // 1
1239                         instantVector.push_back( atoi(tmp) );
1240                         fscanf(pFile,"%s",tmp); // 2
1241                         instantVector.push_back( atoi(tmp) );
1242                         fscanf(pFile,"%s",tmp); // 3
1243                         instantVector.push_back( atoi(tmp) );
1244                         fscanf(pFile,"%s",tmp); // 4
1245                         instantVector.push_back( atoi(tmp) );
1246                         fscanf(pFile,"%s",tmp); // 5
1247                         instantVector.push_back( atoi(tmp) );
1248                         fscanf(pFile,"%s",tmp); // 6
1249                         instantVector.push_back( atoi(tmp) );
1250
1251                         fscanf(pFile,"%s",tmp); // TypeContourModel
1252                         fscanf(pFile,"%s",tmp); // ##
1253                         typeContourModel = atoi(tmp);
1254
1255                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1256                         manModelContour->Open(pFile);
1257                         if(pFileData != NULL)
1258                         {
1259                                 manModelContour->OpenData(pFileData);
1260                         }
1261                         if (transform==true)
1262                         {
1263                                 if (typeOfTransformation==0)
1264                                 {
1265                                         double transX, transY;
1266                                         transX = (double) imageDim[0]/tempDim[0];
1267                                         transY = (double) imageDim[1]/tempDim[1];
1268                                         manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1269                                 }
1270                                 else if (typeOfTransformation==1)
1271                                 {
1272                                         double transX, transY;
1273                                         transX = (double) tempSpac[0]/imageSpac[0];
1274                                         transY = (double) tempSpac[1]/imageSpac[1];
1275                                         manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1276                                 }
1277                         }
1278
1279                         fscanf(pFile,"%s",tmp); // TypeView
1280                         fscanf(pFile,"%s",tmp); // ##
1281                         typeView = atoi(tmp);  
1282
1283                         std::string theName;
1284                         theName = kernelManager->createOutline( manModelContour, instantVector );
1285                         bool addedModel = theName.compare("") != 0;
1286                         if( addedModel )
1287                         {
1288                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1289                                 _theViewPanel->getSpacing(spc);                                 
1290                                 //Adding the manualContourControler to interface objects structure
1291                                 //Adding the manualViewContour to interface objects structure           
1292                                 //_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.
1293                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1294                         }       
1295
1296                         if (staticContour) //StaticContours (will appear in all slices)
1297                         {
1298                                 Instant instant(&instantVector);
1299                                 kernelManager->changeContourOfManager( theName , &instant );
1300                         }
1301                 }// for  numberOfContours       
1302         }
1303 }
1304
1305 void wxContourMainFrame::RefreshInterface(){
1306         changeInstant();
1307         _theViewPanel->RefreshInterface();
1308         //wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
1309         //wxvtk2dbaseview->Refresh();
1310 }
1311
1312 vtkImageData* wxContourMainFrame::getImageData(){
1313         return _theViewPanel->getImageData();
1314 }
1315
1316 void wxContourMainFrame::onSegmentationOneSliceITK(wxString distance, wxString sigma, wxString alfa, wxString beta, wxString propagation, wxString iterations, wxString inflation)
1317 {
1318         //JCP 20-10-08 Undo redo implementation
1319         saveState();
1320         //JCP 20-10-08 Undo redo implementation
1321         
1322         wxBusyCursor wait;
1323         int                                     x                                       = _theViewPanel->GetX();
1324         int                                     y                                       = _theViewPanel->GetY();
1325         int                                     z                                       = _theViewPanel->GetZ();
1326         SegmentationOneSliceITK( x,y,z,distance, sigma, alfa, beta, propagation, iterations, inflation);
1327         RefreshInterface();
1328 }
1329
1330 void wxContourMainFrame::SegmentationOneSliceITK(int x, int y, int z, wxString distanc, wxString sigm, wxString alf, wxString bet, wxString prop, wxString iter, wxString inflation)
1331 {
1332         int typeofcontour = 1;
1333         //Image Data
1334         vtkImageData    *imagedata      = getImageData();
1335         
1336         //Tipo de pixeles a utilizar internamente en ITK
1337         typedef   float  InternalPixelType;
1338         const     unsigned int    Dimension = 2;
1339         typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
1340
1341         //Tipo de pixeles de salida 1
1342         typedef unsigned char OutputPixelType;
1343         typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
1344
1345         //Tipo de pixeles de salida 2
1346         typedef unsigned short OutputPixelType2;
1347         typedef itk::Image< OutputPixelType2, Dimension > OutputImageType2;
1348
1349         //DefiniciÛn del thresholder
1350         typedef itk::BinaryThresholdImageFilter< 
1351                                                         InternalImageType, 
1352                                                         OutputImageType    >    ThresholdingFilterType;
1353           
1354         //DefiniciÛn del primer filtro de conversiÛn de pixeles
1355         typedef itk::CastImageFilter<
1356                                 OutputImageType, OutputImageType2 >  CastFilterType;
1357
1358         //DefiniciÛn del segundo tipo de conversiÛn de pixeles
1359         typedef itk::CastImageFilter<
1360                                 OutputImageType2, InternalImageType >  CastFilterType2;
1361
1362         //Tercer tipo de conversiÛn
1363         typedef itk::RescaleIntensityImageFilter< 
1364                                                                 InternalImageType, 
1365                                                                 OutputImageType >   CastFilterType3;
1366
1367         //Cuarto tipo de conversiÛn
1368         typedef itk::RescaleIntensityImageFilter< 
1369                                                                 OutputImageType, 
1370                                                                 OutputImageType >   CastFilterType4;
1371
1372         ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();
1373                                 
1374         thresholder->SetLowerThreshold( 0.0 );
1375         thresholder->SetUpperThreshold( 128 );
1376
1377         thresholder->SetOutsideValue(  255  );
1378         thresholder->SetInsideValue(  0 );
1379
1380         //DefinciÛn de conexiÛnes entre VTK e ITK y el writer
1381         typedef itk::VTKImageToImageFilter<OutputImageType2> ConnectorType;
1382         typedef itk::ImageToVTKImageFilter<OutputImageType> ConnectorType2;
1383         typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
1384
1385         ConnectorType::Pointer connector= ConnectorType::New();
1386         ConnectorType2::Pointer connector2= ConnectorType2::New();
1387           
1388
1389         CastFilterType::Pointer filter=CastFilterType::New();
1390         CastFilterType2::Pointer filter2=CastFilterType2::New();
1391
1392         connector->SetInput( imagedata );
1393         filter2->SetInput(connector->GetOutput());
1394
1395         typedef   itk::CurvatureAnisotropicDiffusionImageFilter< 
1396                                                                 InternalImageType, 
1397                                                                 InternalImageType >  SmoothingFilterType;
1398
1399         SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New();
1400
1401         typedef   itk::GradientMagnitudeRecursiveGaussianImageFilter< 
1402                                                                 InternalImageType, 
1403                                                                 InternalImageType >  GradientFilterType;
1404
1405         typedef   itk::SigmoidImageFilter<                               
1406                                                                 InternalImageType, 
1407                                                                 InternalImageType >  SigmoidFilterType;
1408
1409         GradientFilterType::Pointer  gradientMagnitude = GradientFilterType::New();
1410
1411         SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New();
1412
1413         sigmoid->SetOutputMinimum(  0.0  );
1414         sigmoid->SetOutputMaximum(  255.0  );
1415
1416
1417         typedef  itk::FastMarchingImageFilter< 
1418                                                                 InternalImageType, 
1419                                                                 InternalImageType >    FastMarchingFilterType;
1420
1421
1422         FastMarchingFilterType::Pointer  fastMarching = FastMarchingFilterType::New();
1423
1424         typedef  itk::GeodesicActiveContourLevelSetImageFilter< InternalImageType, 
1425                                         InternalImageType >    GeodesicActiveContourFilterType;
1426         GeodesicActiveContourFilterType::Pointer geodesicActiveContour = 
1427                                                                                 GeodesicActiveContourFilterType::New();
1428
1429         typedef  itk::ZeroCrossingImageFilter< 
1430                                                                 InternalImageType, 
1431                                                                 InternalImageType >    ZeroCrossingFilterType;
1432         ZeroCrossingFilterType::Pointer zeroCrossing =
1433                                                         ZeroCrossingFilterType::New();
1434
1435         const double propagationScaling = atof( crea::wx2std(prop).c_str() );
1436
1437         geodesicActiveContour->SetPropagationScaling( propagationScaling );
1438         geodesicActiveContour->SetCurvatureScaling( 1.0 );
1439         geodesicActiveContour->SetAdvectionScaling( 1.0 );
1440
1441         geodesicActiveContour->SetMaximumRMSError( 0.02 );
1442         int it=atoi(  crea::wx2std(iter).c_str() );
1443         geodesicActiveContour->SetNumberOfIterations( it );
1444
1445         smoothing->SetInput( filter2->GetOutput() );
1446         gradientMagnitude->SetInput( smoothing->GetOutput() );
1447         sigmoid->SetInput( gradientMagnitude->GetOutput() );
1448         fastMarching->SetInput( sigmoid->GetOutput() );
1449         geodesicActiveContour->SetInput( fastMarching->GetOutput() );
1450         geodesicActiveContour->SetFeatureImage( sigmoid->GetOutput() );
1451           
1452         zeroCrossing->SetInput( geodesicActiveContour->GetOutput() );
1453         //thresholder->SetInput( zeroCrossing->GetOutput() );
1454         thresholder->SetInput( geodesicActiveContour->GetOutput() );
1455         connector2->SetInput( thresholder->GetOutput()  );
1456           
1457
1458         smoothing->SetTimeStep( 0.125 );
1459         smoothing->SetNumberOfIterations(  5 );
1460         smoothing->SetConductanceParameter( 9.0 );
1461
1462
1463         const double sigma = atof(  crea::wx2std(sigm).c_str() );
1464         gradientMagnitude->SetSigma(  sigma  );
1465
1466         const double alpha =  atof(  crea::wx2std(alf).c_str() );
1467         const double beta  =  atof(  crea::wx2std(bet).c_str() );
1468
1469         sigmoid->SetAlpha( alpha );
1470         sigmoid->SetBeta(  beta  );
1471           
1472         typedef FastMarchingFilterType::NodeContainer  NodeContainer;
1473         typedef FastMarchingFilterType::NodeType       NodeType;
1474
1475         NodeContainer::Pointer seeds = NodeContainer::New();
1476
1477         InternalImageType::IndexType  seedPosition;
1478         seedPosition[0] = x;
1479         seedPosition[1] = y;
1480
1481         const double initialDistance = atof( crea::wx2std(distanc).c_str() );
1482
1483         NodeType node;
1484
1485         const double seedValue = - initialDistance;
1486
1487         node.SetValue( seedValue );
1488         node.SetIndex( seedPosition );
1489                 
1490         seeds->Initialize();
1491         seeds->InsertElement( 0, node );
1492
1493         fastMarching->SetTrialPoints( seeds );
1494
1495         fastMarching->SetSpeedConstant( 1.0 );
1496           
1497         fastMarching->SetOutputSize( 
1498                         connector->GetOutput()->GetBufferedRegion().GetSize() );
1499           
1500         fastMarching->SetStoppingValue( 800 );
1501         try
1502     {
1503                 
1504         connector2->Update();
1505         vtkImageData *idata = connector2->GetOutput();
1506
1507         vtkMarchingContourFilter* cntVTK = vtkMarchingContourFilter::New( );
1508         
1509         cntVTK->SetInput( idata );
1510         
1511         cntVTK->SetNumberOfContours( 1 );
1512         cntVTK->SetValue( 0, 255 );
1513         cntVTK->Update( );
1514         cntVTK->UpdateInformation();
1515                 
1516         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1517         cpd->SetInput( cntVTK->GetOutput( ) );
1518         cpd->Update( );
1519         cpd->UpdateInformation();
1520
1521         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1522         conn->SetExtractionModeToLargestRegion( );
1523         conn->SetInput( cpd->GetOutput( ) );
1524         conn->Update( );
1525         conn->UpdateInformation();
1526
1527         vtkStripper* vtkstripper = vtkStripper::New( );
1528         vtkstripper->SetInput( conn->GetOutput() );
1529         vtkstripper->Update();
1530         vtkstripper->UpdateInformation();
1531
1532
1533         vtkPolyData* polyDataResult =  cntVTK->GetOutput();
1534         //std::cout<<"Points "<<polyDataResult->GetNumberOfPoints()<<std::endl;
1535         polyDataResult->Update( );
1536         polyDataResult->UpdateInformation();
1537
1538         //EED
1539                 /*
1540         ofstream myfile;
1541         myfile.open ("C:/Creatis/example.txt");
1542         myfile << "\n";
1543         polyDataResult->Print(myfile);
1544         myfile << "-------------------------------------\n";
1545         polyDataResult->GetLines()->Print(myfile);
1546         myfile.close();*/
1547
1548         cntVTK          -> Delete();
1549         cpd                     -> Delete();
1550         conn            -> Delete();
1551
1552
1553         //--Calculating control points
1554
1555         std::vector<double> vecX;
1556         std::vector<double> vecY;
1557         std::vector<double> vecXo;
1558         std::vector<double> vecYo;
1559         std::vector<double>::iterator vecXoi;
1560         std::vector<double>::iterator vecYoi;
1561         std::vector<double> vecZ;
1562
1563         std::vector<double> vecCtrlPointX;
1564         std::vector<double> vecCtrlPointY;
1565         std::vector<double> vecCtrlPointZ;
1566
1567
1568         double *p;
1569         double xAct=0;
1570         double yAct=0;
1571         int ii,size=polyDataResult->GetNumberOfPoints();
1572         ofstream myfile;
1573         myfile.open ("C:/Creatis/example2.txt");
1574
1575         size=polyDataResult->GetNumberOfPoints();
1576         for (ii=0;ii<size;ii++)
1577         {
1578                 if(ii==0)
1579                 {
1580                         xAct=x;
1581                         yAct=y;
1582                 }
1583                 p       = polyDataResult->GetPoint(ii);
1584                 double x=p[0];
1585                 double y=p[1];
1586                 /*if(fabs(yAct-y)>20)
1587                 {
1588                         if((xAct-x)>1 || (xAct-x)<-1)
1589                         {
1590                         vecX.push_back( p[0] );
1591                         vecY.push_back( p[1] );
1592                         myfile <<p[0]<<","<<p[1]<<"\n";
1593                         std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1594                 std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1595                 std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1596                         vecZ.push_back( 900 );
1597                         xAct=x;
1598                         yAct=y;
1599                         }
1600                         else
1601                         {
1602                                 vecXo.push_back(p[0]);
1603                                 vecYo.push_back(p[1]);
1604                         }
1605                         
1606                 }
1607                 else*/ if(fabs(xAct-x)>11)
1608                 {
1609                         vecXo.push_back(p[0]);
1610                         vecYo.push_back(p[1]);
1611                 }
1612                 else
1613                 {
1614                 vecX.push_back( p[0] );
1615                 myfile <<p[0]<<","<<p[1]<<"\n";
1616                 //std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1617                 //std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1618                 //std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1619                 vecY.push_back( p[1] );
1620                 vecZ.push_back( 900 );
1621                 xAct=x;
1622                 yAct=y;
1623                 }
1624                 
1625                 
1626         }
1627
1628         while(!vecXo.empty())
1629         {
1630                 vecX.push_back(vecXo.back());
1631                 //std::cout<<" x Siguiente "<<vecXo.back();
1632                 vecXo.pop_back();
1633                 vecZ.push_back( 900 );
1634         }
1635         while(!vecYo.empty())
1636         {
1637                 vecY.push_back(vecYo.back());
1638                         vecYo.pop_back();
1639         }
1640         myfile.close();
1641
1642         /*for(int l=0;l<vecX.size();l++)
1643         {
1644                 if(l==0)
1645                 {
1646             vecXo.push_back(p[0]);
1647                         vecYo.push_back(p[1]);
1648                 }
1649                 else
1650                 {
1651                         if(vecXoi[l-1]==)
1652                         {
1653                         }
1654                 }
1655
1656         }*/
1657
1658         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1659
1660         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1661         
1662         int method=2;
1663         if (method==0){
1664                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1665         }
1666         else if (method==1){
1667                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1668         }
1669         else if (method==2){
1670                 extractcontrolpoints2d->SetSamplingControlPoints( 15 );
1671                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1672         }
1673         //--Adding contour to the system
1674
1675         std::vector<int> actualInstantVector;
1676         _instantPanel->getInstant( actualInstantVector );
1677         actualInstantVector[1]=z;
1678
1679         int j,sizeCtrPt = vecCtrlPointX.size();
1680         
1681         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1682         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1683         if (sizeCtrPt>=3){
1684                 for (j=0 ; j<sizeCtrPt ; j++)
1685                 {
1686                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1687                 } // for
1688                 std::string theName;
1689                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1690                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1691                 bool addedModel = theName.compare("") != 0;
1692                 if( addedModel )
1693                 {
1694                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1695                         _theViewPanel->getSpacing(spc); 
1696                         //Adding the manualContourControler to interface objects structure
1697                         //Adding the manualViewContour to interface objects structure           
1698                         //_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.
1699                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1700                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1701                 }       // if addedModel
1702         } // if sizeCtrPt
1703
1704                 
1705                  
1706                  WriterType::Pointer writer = WriterType::New();
1707          CastFilterType3::Pointer caster = CastFilterType3::New();
1708                  
1709                  caster->SetInput( gradientMagnitude->GetOutput() );
1710                  writer->SetInput( caster->GetOutput() );
1711                  writer->SetFileName("Gradient Magnitude.png");
1712                  caster->SetOutputMinimum(   0 );
1713                  caster->SetOutputMaximum( 255 );
1714                  writer->Update();
1715                 
1716                  CastFilterType3::Pointer caster2 = CastFilterType3::New();
1717                  WriterType::Pointer writer2 = WriterType::New();
1718
1719                  caster2->SetInput( sigmoid->GetOutput() );
1720                  writer2->SetInput( caster2->GetOutput() );
1721                  writer2->SetFileName("Sigmoid.png");
1722                  caster2->SetOutputMinimum(   0 );
1723                  caster2->SetOutputMaximum( 255 );
1724                  writer2->Update();
1725
1726                  CastFilterType3::Pointer caster3 = CastFilterType3::New();
1727                  WriterType::Pointer writer3 = WriterType::New();
1728
1729                  caster3->SetInput( fastMarching->GetOutput() );
1730                  writer3->SetInput( caster3->GetOutput() );
1731                  writer3->SetFileName("FastMarching.bmp");
1732                  caster3->SetOutputMinimum(   0 );
1733                  caster3->SetOutputMaximum( 255 );
1734                  writer3->Update();
1735
1736                  CastFilterType3::Pointer caster4 = CastFilterType3::New();
1737                  WriterType::Pointer writer4 = WriterType::New();
1738
1739                  caster4->SetInput( geodesicActiveContour->GetOutput() );
1740                  writer4->SetInput( caster4->GetOutput() );
1741                  writer4->SetFileName("GeodesicActiveContour.png");
1742                  caster4->SetOutputMinimum(   0 );
1743                  caster4->SetOutputMaximum( 255 );
1744                  writer4->Update();
1745
1746                  CastFilterType3::Pointer caster5 = CastFilterType3::New();
1747                  WriterType::Pointer writer5 = WriterType::New();
1748
1749                  caster5->SetInput( zeroCrossing->GetOutput() );
1750                  writer5->SetInput( caster5->GetOutput() );
1751                  writer5->SetFileName("ZeroCrossing.bmp");
1752                  caster5->SetOutputMinimum(   0 );
1753                  caster5->SetOutputMaximum( 255 );
1754                  writer5->Update();
1755     }
1756   catch( itk::ExceptionObject & excep )
1757     {
1758     std::cerr << "Exception caught !" << std::endl;
1759     std::cerr << excep << std::endl;
1760     }
1761 }
1762
1763 void wxContourMainFrame::onSegmentationOneSlice(int isovalue,int sampling,int method){
1764         
1765         //JCP 20-10-08 Undo redo implementation
1766         saveState();
1767         //JCP 20-10-08 Undo redo implementation
1768         
1769         wxBusyCursor wait;
1770         int                                     x                                       = _theViewPanel->GetX();
1771         int                                     y                                       = _theViewPanel->GetY();
1772         int                                     z                                       = _theViewPanel->GetZ();
1773         SegmentationOneSlice( x,y,z,isovalue, sampling, method );
1774         RefreshInterface();
1775 }
1776
1777
1778 void wxContourMainFrame::SegmentationOneSlice( int x, int y, int z, int isovalue, int sampling, int method )
1779 {               
1780         int typeofcontour = 1;
1781         //--Extracting Contour
1782         //vtkImageData  *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
1783         vtkImageData    *imagedata      = getImageData();
1784 //              double                  *range          = imagedata->GetScalarRange();  
1785 //              double                  thr                     = 1;
1786
1787         vtkImageReslice *imageReslice = vtkImageReslice::New();
1788 //EED
1789 //              double spc[3];
1790 //              imagedata->GetSpacing(spc);
1791 //              x = x*spc[0];
1792 //              y = y*spc[1];
1793 //              z = z*spc[3];
1794
1795         imageReslice->SetInput( imagedata );
1796         imageReslice->SetInformationInput(imagedata);
1797         imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
1798         imageReslice->SetResliceAxesOrigin(0,0,z);
1799         imageReslice->SetOutputDimensionality(2);
1800         imageReslice->SetInterpolationModeToLinear();
1801
1802         imagedata = imageReslice->GetOutput();
1803         imagedata->Update();
1804         imagedata->UpdateInformation();
1805
1806         vtkContourFilter* cntVTK = vtkContourFilter::New( );
1807         cntVTK->SetInput( imagedata );
1808
1809         cntVTK->SetNumberOfContours( 1 );
1810         //cntVTK->SetValue( 0, vmin );
1811 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
1812         cntVTK->SetValue( 1, isovalue );
1813 //      cntVTK->SetValue( 1, vmax );
1814         cntVTK->Update( );
1815         cntVTK->UpdateInformation();
1816                 
1817         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1818         cpd->SetInput( cntVTK->GetOutput( ) );
1819         cpd->ConvertLinesToPointsOff( );
1820         cpd->Update( );
1821         cpd->UpdateInformation();
1822
1823         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1824         conn->SetExtractionModeToClosestPointRegion( );
1825         //conn->SetMaxRecursionDepth( 3000 );
1826                 
1827         conn->SetInput( cpd->GetOutput( ) );
1828                 
1829         conn->SetClosestPoint( x, y, 0 );
1830         conn->Update( );
1831         conn->UpdateInformation();
1832                 
1833         vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
1834         cpd2->SetInput( conn->GetOutput( ) );
1835         cpd2->Update();
1836         cpd2->UpdateInformation();
1837
1838         vtkStripper* vtkstripper = vtkStripper::New( );
1839         vtkstripper->SetInput( cpd2->GetOutput() );
1840         vtkstripper->Update();
1841         vtkstripper->UpdateInformation();
1842
1843
1844         vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
1845
1846         polyDataResult->Update( );
1847         polyDataResult->UpdateInformation();
1848
1849 /* EED
1850 ofstream myfile;
1851 myfile.open ("c:/temp/example.txt");
1852 myfile << "\n";
1853 polyDataResult->Print(myfile);
1854 myfile << "-------------------------------------\n";
1855 polyDataResult->GetLines()->Print(myfile);
1856 myfile.close();
1857 */
1858
1859         cntVTK          -> Delete();
1860         cpd2            -> Delete();
1861         cpd                     -> Delete();
1862         conn            -> Delete();
1863
1864
1865 //--Calculating control points
1866
1867         std::vector<double> vecX;
1868         std::vector<double> vecY;
1869         std::vector<double> vecZ;
1870
1871         std::vector<double> vecCtrlPointX;
1872         std::vector<double> vecCtrlPointY;
1873         std::vector<double> vecCtrlPointZ;
1874
1875
1876         double *p;
1877         int ii,size=polyDataResult->GetNumberOfPoints();
1878         int id;
1879         for (ii=1;ii<=size;ii++)
1880         {
1881                 id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
1882                 p       = polyDataResult->GetPoint(id);
1883 //              double x=p[0];
1884 //              double y=p[1];
1885                 vecX.push_back( p[0] );
1886                 vecY.push_back( p[1] );
1887                 vecZ.push_back( 900 );
1888 //                      vecZ.push_back( p[2] );
1889         }
1890
1891
1892         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1893         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1894
1895 //PROOFS
1896         /*if (methodRadiobox->GetSelection()==0){
1897                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1898         }
1899         if (methodRadiobox->GetSelection()==1){
1900                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1901         }
1902         if (methodRadiobox->GetSelection()==2){
1903                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1904                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1905         }*/
1906
1907         if (method==0){
1908                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1909         }
1910         else if (method==1){
1911                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1912         }
1913         else if (method==2){
1914                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1915                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1916         }
1917
1918         //--Adding contour to the system
1919
1920         std::vector<int> actualInstantVector;
1921         _instantPanel->getInstant( actualInstantVector );
1922         actualInstantVector[1]=z;
1923
1924         int j,sizeCtrPt = vecCtrlPointX.size();
1925         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1926         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1927         if (sizeCtrPt>=3){
1928                 for (j=0 ; j<sizeCtrPt ; j++)
1929                 {
1930                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1931                 } // for
1932                 std::string theName;
1933                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1934                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1935                 bool addedModel = theName.compare("") != 0;
1936                 if( addedModel )
1937                 {
1938                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1939                         _theViewPanel->getSpacing(spc);                                 
1940                         //Adding the manualContourControler to interface objects structure
1941                         //Adding the manualViewContour to interface objects structure           
1942                         //_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.
1943                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1944                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1945                 }       // if addedModel
1946         } // if sizeCtrPt
1947 }
1948 int wxContourMainFrame::GetImageDataSizeZ(){
1949         return _theViewPanel->GetImageDataSizeZ();
1950 }
1951
1952 void wxContourMainFrame::GetImageDataRange(double *range){
1953         _theViewPanel->GetImageDataRange(range);
1954 }
1955
1956 void wxContourMainFrame::onSegmentationAllSlice(int minZ,int maxZ,int isovalue,int sampling,int method){
1957         //JCP 20-10-08 Undo redo implementation
1958         saveState();
1959         //JCP 20-10-08 Undo redo implementation
1960         
1961         wxBusyCursor wait;
1962         int                                     x                                       = _theViewPanel->GetX();
1963         int                                     y                                       = _theViewPanel->GetY();
1964         int z;
1965         double porcent; 
1966         wxString tmpString;     
1967         double totalZ = maxZ-minZ+1;
1968         for( z=minZ ; z<=maxZ ; z++ )
1969         {
1970                 porcent = 100.0* (z-minZ)/totalZ;
1971                 tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
1972                 interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(tmpString);
1973                 //_staticTextSegmentation->SetLabel(tmpString);
1974                 SegmentationOneSlice( x,y,z,isovalue, sampling,method );
1975         }
1976         interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(_T("   "));
1977         RefreshInterface();
1978 }
1979
1980
1981 //Creates a reference line to be used as the axis of the mirroring
1982 void wxContourMainFrame::referenceLine()
1983 {
1984         if (_refLineControl==NULL)
1985         {
1986                 wxBusyCursor wait;
1987                 double spc[3];
1988
1989                 vtkImageData *vtkimagedata = _theViewPanel->getImageData();
1990                 vtkimagedata->GetSpacing(spc);
1991
1992                 wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
1993
1994                 _refLineControl = new manualLineControler();
1995                 _refLineModel   = new manualContourModelLine();
1996                 _refLineView = new manualViewLine();
1997                 _refLineView->SetModel( _refLineModel );
1998                 _refLineView->SetWxVtkBaseView( viewer2D );
1999                 _refLineView->SetRange( 2 );
2000                 _refLineView->SetZ( 1200 );
2001
2002                 _refLineView->SetSpacing(spc);
2003
2004                 _refLineView->SetColorNormalContour(0, 0, 1);
2005                 _refLineView->SetColorEditContour(0, 0.5, 0.5);
2006                 _refLineView->SetWidthLine(4);
2007
2008                 _refLineControl->SetModelView( _refLineModel , _refLineView );
2009                 vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2010                 style->AddInteractorStyleMaracas( _refLineControl );
2011                 _refLineModel->SetCloseContour(false);
2012                 _refLineControl->CreateNewManualContour();
2013
2014 //AD: Inicializar el mirroring con una linea ya pintada 
2015         /*
2016                 double z = _refLineControl->GetZ();
2017
2018                 int imageDim[3];
2019                 image->GetDimensions(imageDim);
2020                 double x = (double) imageDim[0]/2;
2021                 double y1 = (double) (imageDim[1]/2)+15;
2022                 double y2 = (double) (imageDim[1]/2)-15;
2023
2024                 _refLineControl->AddPoint(x,y1,z);
2025                 _refLineControl->AddPoint(x,y2,z);
2026                 _refLineControl->SetCompleteCreation(true);
2027
2028                 _refLineModel->AddPoint(x,y1,z);
2029                 _refLineModel->AddPoint(x,y2,z);
2030                 _refLineModel->UpdateSpline();
2031
2032                 _refLineView->UpdateViewPoint(0);
2033                 _refLineView->UpdateViewPoint(1);
2034         */
2035
2036                 _refLineControl->SetActive(true);
2037                 _refLineView->RefreshContour();
2038         }
2039 }
2040
2041 //Hides the referenceLine
2042 void wxContourMainFrame::refLineHide()
2043 {
2044         if (_refLineControl!=NULL)
2045         {
2046                 if (_refLineControl->GetActive())
2047                 {
2048                         _refLineView->RemoveCompleteContourActor();
2049                         _refLineControl->SetEditable(false);
2050                         _refLineControl->SetActive(false);
2051
2052                         RefreshInterface();
2053                 }
2054         }
2055 }
2056
2057 //Shows the referenceLine
2058 void wxContourMainFrame::refLineShow()
2059 {
2060         if (_refLineControl!=NULL)
2061         {
2062                 if (_refLineControl->GetActive()==false)
2063                 {
2064                         wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2065
2066                         _refLineView->SetModel( _refLineModel );
2067                         _refLineView->SetWxVtkBaseView( viewer2D );
2068                         _refLineView->SetRange( 2 );
2069                         _refLineView->SetZ( 1200 );
2070
2071                         _refLineControl->SetModelView( _refLineModel , _refLineView );
2072                         vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2073                         style->AddInteractorStyleMaracas( _refLineControl );
2074                         _refLineControl->CreateNewManualContour();
2075                         _refLineControl->SetActive(true);
2076                         _refLineView->RefreshContour();
2077
2078                         RefreshInterface();
2079                 }
2080         }
2081 }
2082
2083 void wxContourMainFrame::refLineChangeWidth(int width)
2084 {
2085         _refLineView->SetWidthLine(width);
2086         _refLineView->RefreshContour();
2087
2088         RefreshInterface();
2089 }
2090
2091
2092 void wxContourMainFrame::onMirror()
2093 {
2094         //AD:02-09
2095         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2096         std::vector<std::string> filterCurrentSelection;
2097
2098         std::vector<int> tempVector;
2099         _instantPanel->getInstant( tempVector );
2100     _performingOperation->reset();
2101         _performingOperation->setStartCommand( COPY );
2102         _performingOperation->setStartOperationInstantVector( tempVector );
2103         _performingOperation->setKeyNamesOperationElems( currentSelection );
2104
2105         char theStartCommand = _performingOperation->getStartCommand();
2106         if (  theStartCommand == COPY )
2107         {
2108                 //JCP 20-10-08 Undo redo implementation
2109                 saveState();
2110                 //JCP 20-10-08 Undo redo implementation
2111                 std::vector<int> tempVector;
2112                 _instantPanel->getInstant( tempVector );
2113                 _performingOperation->setEndOperationInstantVector ( tempVector );
2114                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
2115                 int i,size = elems.size();                      
2116                 for( i=0; i<size; i++ )
2117                 {                               
2118                         createMirrorContourOf( elems[i], tempVector, i>0 );
2119                 }               
2120         }
2121
2122         //deleteContour( _refName );
2123         //_refName = "";
2124 }
2125
2126
2127 void wxContourMainFrame::showAxis(bool show)
2128 {
2129         _theViewPanel->SetVisibleAxis(show);
2130         _theViewPanel->Refresh();
2131 }
2132
2133
2134 void wxContourMainFrame::onRigidPressed(){
2135         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2136         int elementsSelected = currentSelection.size();
2137
2138         if ( elementsSelected >= 1 ){
2139                 //JCP 20-10-08 Undo redo implementation
2140                 saveState();
2141                 //JCP 20-10-08 Undo redo implementation
2142
2143                 std::vector<int> tempVector;
2144                 _instantPanel->getInstant( tempVector );
2145                 Instant instant(&tempVector);
2146
2147                 int i , size=currentSelection.size();
2148                 for ( i=0 ; i<size ; i++ )
2149                 {
2150                         kernelManager->changeContourOfManager(currentSelection[i], &instant);
2151                 } // i
2152         }
2153 }
2154
2155 void wxContourMainFrame::onWidthOfContour(double width){
2156
2157         _theViewPanel->removeSceneContours();
2158         _theViewPanel->SetWidthContour(width);
2159         
2160         //_theViewPanel->getSceneManager()->SetWidthContour( width );
2161
2162         RefreshInterface();
2163 }
2164
2165 int wxContourMainFrame::getColorWindow()
2166 {
2167         /*
2168         double range[2];
2169         vtkImageData * img = getImageData();
2170         img->GetScalarRange(range);
2171
2172         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2173         
2174         return (int)range[1];
2175         */
2176         return _theViewPanel->getColorWindow();
2177 }
2178
2179 int wxContourMainFrame::getWindowLevel()
2180 {
2181         /*
2182         double range[2];
2183         vtkImageData * img = getImageData();
2184         img->GetScalarRange(range);
2185
2186         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2187         
2188         return (int)range[1];
2189         */
2190         return _theViewPanel->getWindowLevel();
2191 }
2192
2193 void wxContourMainFrame::onBrigthnessColorWindowLevel(int colorwindow,int windowlevel){
2194         _theViewPanel->onBrigthnessColorWindowLevel(colorwindow, windowlevel);
2195
2196         RefreshInterface();
2197 }
2198
2199 void wxContourMainFrame::onInterpolation(bool interpolate){
2200         _theViewPanel->onInterpolation(interpolate);    
2201         RefreshInterface();
2202 }
2203
2204 void wxContourMainFrame::onChangeInstant(std::string name,int actual){
2205         _instantPanel->setConceptValue( name, actual );
2206 }
2207
2208 void wxContourMainFrame::resetAppend(){
2209         kernelManager->resetAppend();
2210         
2211 }
2212
2213 void wxContourMainFrame::onSpreadAdd(){
2214         std::vector<double> vecX; 
2215         std::vector<double> vecY; 
2216         std::vector<double> vecZ; 
2217         _theViewPanel->GetPointsOfActualContour(&vecX , &vecY , &vecZ );
2218         
2219         std::vector<int> tempVector;
2220         _instantPanel->getInstant( tempVector );
2221
2222         std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2223
2224         interfMainPanel::getInstance()->appendStringSpread(val);
2225         
2226 }
2227
2228 void wxContourMainFrame::onSpreadGo(int type){
2229
2230         //JCP 20-10-08 Undo redo implementation
2231         saveState();
2232         //JCP 20-10-08 Undo redo implementation
2233
2234         wxBusyCursor wait;      
2235         std::vector<double> vecCtrlPointX;
2236         std::vector<double> vecCtrlPointY;
2237         std::vector<double> vecCtrlPointZ;
2238         double  minZ,maxZ;
2239         int z;
2240
2241         std::vector<int> tempVector;
2242         _instantPanel->getInstant( tempVector );
2243 //              tempVector[1];
2244
2245         kernelManager->getMaxMinZ(&minZ,&maxZ);
2246 //JSTG_16-07-08_----------------------------------------------------------------
2247         //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
2248         kernelManager->CalculeSplinePropagation();
2249
2250         double          totalZ = maxZ-minZ+1;
2251         double          porcent;
2252         wxString        tmpString;
2253 //--------------------------------------------------------------------
2254         for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
2255         {
2256                 porcent = 100.0* (z-minZ)/totalZ;
2257                 int numero = (int)(z-minZ+1)/(int)totalZ;
2258                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2259                 
2260                 interfMainPanel::getInstance()->setStringSpread(stringtemp);    
2261
2262                 int typeofcontour = 1;
2263                 std::string theName;
2264                 manualBaseModel* manModelContour = kernelManager->GetPoints(z, type, &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ, theName,typeofcontour, tempVector);
2265
2266                 if( manModelContour!=NULL ){
2267                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2268                         this->_theViewPanel->getSpacing(spc);                                   
2269                         //Adding the manualContourControler to interface objects structure
2270                         //Adding the manualViewContour to interface objects structure           
2271                         //_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.
2272                         _theViewPanel->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
2273                 } // if addedModel
2274         } 
2275         if(z > maxZ){
2276                 porcent = 100.0;
2277                 int numero = (int)(z-minZ+1)/(int)totalZ;
2278                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2279                 
2280                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2281         }// for z
2282         //RefreshInterface();
2283 }
2284
2285 void wxContourMainFrame::getInstantVector(std::vector<int>& tempVector){
2286         
2287 }
2288
2289 std::vector<std::string> wxContourMainFrame::getOutlinesName(int slide){
2290         std::vector<int> tempVector;
2291         _instantPanel->getInstant(tempVector);
2292         //Asignation of slide number should be different ex by name
2293         tempVector[1]=slide;
2294         return kernelManager->getOutlinesNameAtInstant(tempVector);
2295 }
2296
2297
2298
2299 void wxContourMainFrame::onInformationContourLabels(int typeContourGroup,int selection,int minimumZ,int maximumZ,int grayRangeMin, int grayRangeMax)
2300 {
2301 //EED01Juillet2009      GenerateContourExtractData();
2302         
2303         wxString tempString;
2304         int maxContourGroup     =       0;
2305         
2306         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2307
2308         std::vector<manualBaseModel*> lstManConMod;
2309         std::vector<manualBaseModel*> lstManConModTmp;
2310         std::vector<manualBaseModel*> lstManConModExp;
2311         std::vector<double> pLstValue;
2312         std::vector<double> pLstValuePosX;
2313         std::vector<double> pLstValuePosY;
2314         std::vector<double> pLstValuePosZ;
2315
2316         int             resultSize; 
2317         int             resultGrayRangeCount;
2318         double  resultMin; 
2319         double  resultMax;
2320         double  resultAverage;
2321         double  resultStandardeviation;
2322
2323         std::vector<int> tempVector;
2324         _instantPanel->getInstant( tempVector );
2325
2326 //EED01Juillet2009      vtkImageData *imagedata = _theViewPanel->getImageData();
2327 //      int sizeZ = _theViewPanel->GetImageDataSizeZ();
2328         int z;
2329         int ii,sizeLstContourThings;
2330
2331
2332         int minZ,maxZ;
2333         double totalZ;
2334         double porcent; 
2335         wxString tmpString;
2336
2337
2338         if (selection==0 ) // actual slice
2339         {
2340                 int actualSlice = tempVector[1];
2341                 minZ    = actualSlice;
2342                 maxZ    = actualSlice;
2343         }       else  {  // slice range
2344                 minZ    = minimumZ;
2345                 maxZ    = maximumZ;
2346         }
2347         
2348
2349         totalZ  = maxZ-minZ+1;
2350 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2351
2352         _contourextractdata->InitVolumeStatistics();
2353         
2354 // For each slice..
2355         for ( z=minZ ; z<=maxZ ; z++ )
2356         {
2357                 
2358                 porcent = 100.0* (z-minZ)/totalZ;
2359                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2360
2361                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);          
2362                 //_staticTextInformation->SetLabel(tmpString);
2363
2364                 //Extraction data from contours of each slice
2365                 _contourextractdata->SetZtoBeAnalys(z);
2366
2367                 tempVector[1]=z;
2368                 Instant instant(&tempVector);
2369                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2370                 sizeLstContourThings = lstContourThings.size();
2371
2372                 lstManConMod.clear();
2373                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2374                 {
2375                         ContourThing **contourthing = lstContourThings[ii];
2376                         lstManConMod.push_back( (*contourthing)->getModel() );
2377                 }
2378
2379                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2380
2381                 tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
2382                 interfMainPanel::getInstance()->setRowLabelInfoPanel(z, tempString);
2383                 //_grid->SetRowLabelValue(z, tempString );
2384 //EED004
2385                 int iContourGroup,sizeContourGroup;
2386                 if (typeContourGroup==3) // contour separete
2387                 {
2388                         sizeContourGroup=lstManConModExp.size();
2389                         if ( maxContourGroup<sizeContourGroup ) 
2390                         {
2391                                 maxContourGroup=sizeContourGroup;
2392                         }
2393                 } else {  // contour AND OR XOR
2394                         sizeContourGroup=1;
2395                         maxContourGroup=1;
2396                 }
2397
2398                 int tmpIntA;
2399
2400                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2401                         lstManConModTmp.clear();
2402
2403                         
2404
2405                         if (typeContourGroup==3) // contour separete
2406                         {
2407                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2408                         } else {  // contour AND OR XOR
2409                                 lstManConModTmp = lstManConModExp;
2410                         }
2411
2412                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2413
2414                         pLstValue.clear();
2415                         pLstValuePosX.clear();
2416                         pLstValuePosY.clear();
2417                         pLstValuePosZ.clear();
2418                         _contourextractdata->GetValuesInsideCrown(      &pLstValue,
2419                                                                                                                 &pLstValuePosX,
2420                                                                                                                 &pLstValuePosY,
2421                                                                                                                 &pLstValuePosZ);
2422
2423                         // Statistics of each slice.
2424                         _contourextractdata->Statistics( &pLstValue,
2425                                                                                         grayRangeMin,
2426                                                                                         grayRangeMax,
2427                                                                                         &resultGrayRangeCount, 
2428                                                                                         &resultSize, 
2429                                                                                         &resultMin, 
2430                                                                                         &resultMax,
2431                                                                                         &resultAverage,
2432                                                                                         &resultStandardeviation);
2433                         
2434                         if (interfMainPanel::getInstance()->getNumberColsInformationPanel()<_numberOfVariablesStatistics*(iContourGroup+1)  )
2435                         {
2436                                 interfMainPanel::getInstance()->appendColsInformationPanel(_numberOfVariablesStatistics);
2437                         }
2438
2439                         tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
2440
2441                         tempString.Printf(_T("%d"),resultSize);
2442                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA, tempString);  
2443
2444                         tempString.Printf(_T("%d"),resultGrayRangeCount);
2445                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+1, tempString);
2446                         
2447                         tempString.Printf(_T("%f"),resultMin);
2448                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+2, tempString);
2449                         
2450                         tempString.Printf(_T("%f"),resultMax);
2451                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+3, tempString);
2452                         
2453                         tempString.Printf(_T("%f"),resultAverage);
2454                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+4, tempString);
2455                         
2456                         tempString.Printf(_T("%f"),resultStandardeviation);
2457                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+5, tempString);
2458                         
2459
2460                 } // for iContourGroup
2461         } // for z
2462
2463         // Print Volume Statistics
2464
2465
2466         int             vol_rCountRange; 
2467         int             vol_rsize;
2468         double  vol_minValue;
2469         double  vol_maxValue;
2470         double  vol_average;
2471         double  vol_standardeviation;
2472         
2473         if (selection!=0 ) // actual slice
2474         {
2475
2476                 _contourextractdata->GetVolumeStatistics(&vol_rCountRange, &vol_rsize,
2477                                                                                                  &vol_minValue, &vol_maxValue,
2478                                                                                                  &vol_average, &vol_standardeviation);
2479
2480                 interfMainPanel::getInstance()->setRowLabelInfoPanel(maxZ+2, _T("Total:"));
2481         
2482                 tempString.Printf(_T("%d"),vol_rsize);
2483                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 0, tempString);   
2484         
2485                 tempString.Printf(_T("%d"),vol_rCountRange);
2486                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 1, tempString);
2487         
2488                 tempString.Printf(_T("%f"),vol_minValue);
2489                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 2, tempString);
2490         
2491                 tempString.Printf(_T("%f"),vol_maxValue);
2492                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 3, tempString);
2493         
2494                 tempString.Printf(_T("%f"),vol_average);
2495                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 4, tempString);
2496         
2497                 tempString.Printf(_T("%f"),vol_standardeviation);
2498                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 5, tempString);
2499         }
2500         //-----------------------------------------
2501         
2502         int iTitleGroup;
2503         wxString tmpTitleString;
2504         int tmpIntB;
2505         for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
2506         {
2507                 tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
2508                 tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
2509                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString);
2510
2511                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString );
2512                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 1, _T("Size Range") );
2513                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 2, _T("Min") );
2514                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 3, _T("Max") );
2515                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 4, _T("Average") );
2516                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 5, _T("St.Dev.") );
2517                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 6, _T(" ") );
2518         }// for title
2519         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2520 }
2521
2522 //AD: 29-05-09
2523 void wxContourMainFrame::onSaveResults(std::string directory,std::string namefile, std::string filename, 
2524         int typeContourGroup, int selection, int minZ, int maxZ, bool XYZValues, bool contourImage, bool statistics)
2525 {
2526         if (XYZValues)
2527         {
2528                 SaveValuesXYZ( directory , namefile, typeContourGroup );
2529         }
2530
2531         if (contourImage)
2532         {
2533                 vtkImageData * mask;
2534                 vtkImageData * value;
2535                 this->getMaskValue(&mask, &value, typeContourGroup,selection,minZ,maxZ);
2536                 this->SaveImageResult( directory , namefile, mask, value);
2537         }
2538         
2539         if (statistics)
2540         {
2541                 std::ostringstream name;
2542                 name << filename << ".xls";
2543                 
2544
2545                 FILE *pFile=fopen(name.str().c_str(),"w+");
2546
2547
2548                 wxString tmpString;
2549                 int i,j,maxX;
2550                 
2551 //              int sizeZ = _theViewPanel->GetImageDataSizeZ();
2552 //              int maxY=sizeZ+2;
2553                 
2554                 maxX= interfMainPanel::getInstance()->getNumberColsInformationPanel();//this->_grid->GetNumberCols();
2555
2556                 // -- Title --
2557                 int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
2558                 for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
2559                 {
2560                                 // fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
2561                                 fprintf(pFile,"slice\t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle );
2562                 }
2563                 fprintf(pFile,"\n\n" );
2564
2565                 
2566                 
2567                 if (selection==0 ) // actual slice
2568                 {
2569                         std::vector<int> tempVector;
2570                         _instantPanel->getInstant( tempVector );
2571                         int actualSlice = tempVector[1];
2572                         minZ    = actualSlice;
2573                         maxZ    = actualSlice;
2574                 }
2575                 
2576                 // Stadistics...
2577                 for ( j=minZ; j<=maxZ ; j++)
2578                 {
2579                         fprintf(pFile,"%d\t" , j );
2580                         for (i=0 ; i<maxX ; i++){
2581                                 tmpString = interfMainPanel::getInstance()->getCellValue(j, i);//_grid->GetCellValue( j , i );
2582                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2583                         } // for i
2584                         fprintf(pFile,"\n"  );
2585                 } // for j
2586
2587                 
2588                 // Total of stadistics.....
2589                 if (selection!=0)
2590                 {
2591                         fprintf(pFile,"\n Total:\t"  );
2592                         for (i=0 ; i<maxX ; i++){
2593                                 tmpString = interfMainPanel::getInstance()->getCellValue(maxZ+2, i);//_grid->GetCellValue( maxZ+2 , i );
2594                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2595                         } // for i
2596                         fprintf(pFile,"\n"  );
2597                 }
2598                 
2599                 fclose(pFile);
2600         }
2601 }
2602
2603 //AD: 29-05-09
2604 void wxContourMainFrame::SaveValuesXYZ(std::string directory,std::string namefile,int typeContourGroup)
2605 {
2606         wxBusyCursor wait;
2607 //EED01Juillet2009      GenerateContourExtractData();
2608         
2609         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2610         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2611
2612         std::vector<manualBaseModel*> lstManConMod;
2613         std::vector<manualBaseModel*> lstManConModTmp;
2614         std::vector<manualBaseModel*> lstManConModExp;
2615         std::vector<double> pLstValue;
2616         std::vector<double> pLstValuePosX;
2617         std::vector<double> pLstValuePosY;
2618         std::vector<double> pLstValuePosZ;
2619
2620         std::vector<int> tempVector;
2621         _instantPanel->getInstant( tempVector );
2622
2623 //EED01Juillet2009      vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
2624         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2625         int z;
2626         int ii,sizeLstContourThings;
2627
2628
2629         int minZ,maxZ;
2630         double totalZ;
2631         double porcent; 
2632         wxString tmpString;
2633         minZ    = 0;// _mbarrange->GetStart();
2634         maxZ    = sizeZ;//_mbarrange->GetEnd();
2635         totalZ  = maxZ-minZ+1;
2636
2637 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2638
2639 // For each slice..
2640         for ( z=0 ; z<sizeZ ; z++)
2641         {
2642
2643                 porcent = 100.0* (z-minZ)/totalZ;
2644                 
2645                 tmpString.Printf(_T("Saving Values"));
2646                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2647                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2648                 //_staticTextInformation->SetLabel(tmpString);
2649
2650
2651                 //Extraction data from contours of each slice
2652                 _contourextractdata->SetZtoBeAnalys( z);
2653
2654                 tempVector[1]=z;
2655                 Instant instant(&tempVector);
2656                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant(&instant);//this->_modelManager->getOutlinesAtInstant( &instant );
2657                 sizeLstContourThings = lstContourThings.size();
2658
2659                 lstManConMod.clear();
2660                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2661                 {
2662                         ContourThing **contourthing = lstContourThings[ii];
2663                         lstManConMod.push_back( (*contourthing)->getModel() );
2664                 }
2665                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2666
2667
2668 //EED004
2669
2670                 int iContourGroup,sizeContourGroup;
2671                 if (typeContourGroup==3) // contour separete
2672                 {
2673                         sizeContourGroup=lstManConModExp.size();
2674                 } else {  // contour AND OR XOR
2675                         sizeContourGroup=1;
2676                 }
2677
2678                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2679                         lstManConModTmp.clear();
2680                         if (typeContourGroup==3) // contour separete
2681                         {
2682                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2683                         } else {  // contour AND OR XOR
2684                                 lstManConModTmp = lstManConModExp;
2685                         }
2686
2687                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2688
2689                         pLstValue.clear();
2690                         pLstValuePosX.clear();
2691                         pLstValuePosY.clear();
2692                         pLstValuePosZ.clear();
2693                         _contourextractdata->GetValuesInsideCrown(      &pLstValue,
2694                                                                                                                 &pLstValuePosX,
2695                                                                                                                 &pLstValuePosY,
2696                                                                                                                 &pLstValuePosZ);
2697
2698                         std::string temp = directory + "/" + namefile + "-slice";
2699                         temp = temp + kernelManager->intToString(z) + "-cont" + kernelManager->intToString(iContourGroup);
2700                         temp = temp + ".txt";
2701
2702                         // LG 14/01/09 : using crea
2703                         wxString filename = crea::std2wx(temp);
2704                         /*filename.Printf(_T("%s"),directory.c_str());
2705                         filename.append(_T("\\"));
2706                         filename.append(_T("%s"),namefile.c_str());
2707                         filename.append(_T("-slice"));
2708                         filename.append(_T("%d"),z);
2709                         filename.append(_T("-cont"));
2710                         filename.append(_T("%d"),iContourGroup);
2711                         filename.append(_T(".txt"));*/
2712                         //                      filename.Printf(temp.c_str());
2713
2714                         
2715
2716                         FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
2717                         fprintf(pFile,"value \t x \t y \t z\n"  );
2718                         int iLstValue,sizeLstValue=pLstValue.size();
2719                         for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
2720                         {
2721                                 fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
2722                         }
2723                         fclose(pFile);
2724                 } // for  iContourGroup
2725         } // for z
2726         interfMainPanel::getInstance()->setStringInfoPanel(_T(""));
2727         //_staticTextInformation->SetLabel( _T("") );
2728
2729 }
2730
2731 void wxContourMainFrame::getMaskValue(vtkImageData ** mask,vtkImageData ** value,int typeContourGroup, int selection, int minZ, int maxZ){
2732         wxBusyCursor wait;
2733 //EED01Juillet2009      GenerateContourExtractData();
2734
2735         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2736         if (typeContourGroup==3)
2737         {
2738                 typeContourGroup=1;
2739         }
2740         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2741
2742         std::vector<manualBaseModel*> lstManConMod;
2743         std::vector<manualBaseModel*> lstManConModTmp;
2744         std::vector<manualBaseModel*> lstManConModExp;
2745
2746         std::vector<int> tempVector;
2747         _instantPanel->getInstant( tempVector );
2748
2749     vtkImageData *imagedata = _theViewPanel->getImageData();
2750         int ext[6];
2751         imagedata->GetExtent(ext);
2752         int sizeZimage = ext[5]-ext[4]+1;
2753         int z;
2754         int ii,sizeLstContourThings;
2755
2756
2757         double totalZ;
2758         double porcent; 
2759
2760         wxString tmpString;
2761         
2762         
2763         if (selection==0 ) // actual slice
2764         {
2765                 int actualSlice = tempVector[1];
2766                 minZ    = actualSlice;
2767                 maxZ    = actualSlice;
2768         }       
2769         
2770         totalZ  = maxZ-minZ;
2771
2772 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2773
2774         // cleanning image before range 
2775         for (z=0; z<minZ; z++){
2776                 _contourextractdata->ResetImageResult(z);
2777         }
2778         // cleanning image after range 
2779         for (z=maxZ+1; z<sizeZimage; z++){
2780                 _contourextractdata->ResetImageResult(z);
2781         }
2782         
2783         
2784 // For each slice..
2785         for ( z=minZ ; z<=maxZ ; z++)
2786         {
2787
2788                 porcent = 100.0* (z-minZ)/totalZ;
2789                 tmpString.Printf(_T("Saving Values"));
2790                 tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2791                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2792
2793                 //Extraction data from contours of each slice
2794                 _contourextractdata->SetZtoBeAnalys( z);
2795
2796                 tempVector[1]=z;
2797                 Instant instant(&tempVector);
2798                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2799                 sizeLstContourThings = lstContourThings.size();
2800
2801                 lstManConMod.clear();
2802                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2803                 {
2804                         ContourThing **contourthing = lstContourThings[ii];
2805                         lstManConMod.push_back( (*contourthing)->getModel() );
2806                 }
2807                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2808
2809
2810                 int iContourGroup,sizeContourGroup;
2811                 if (typeContourGroup==3) // contour separete
2812                 {
2813                         sizeContourGroup=lstManConModExp.size();
2814                 } else {  // contour AND OR XOR
2815                         sizeContourGroup=1;
2816                 }
2817
2818                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2819                         lstManConModTmp.clear();
2820                         if (typeContourGroup==3) // contour separete
2821                         {
2822                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2823                         } else {  // contour AND OR XOR
2824                                 lstManConModTmp = lstManConModExp;
2825                         }
2826
2827                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2828                         _contourextractdata->CalculateImageResult(); // with actual Z
2829
2830                 } // for  iContourGroup
2831         } // for z
2832
2833         (*value) = _contourextractdata->GetVtkImageValueResult();
2834         (*mask)  = _contourextractdata->GetVtkImageMaskResult();
2835
2836 }
2837
2838 void wxContourMainFrame::SaveImageResult(std::string directory,std::string namefile, vtkImageData* mask,vtkImageData* value)
2839 {
2840         
2841         std::string temp = directory + "/" + namefile + "-Value.mhd";
2842
2843         wxString filename = crea::std2wx(temp);
2844         // LG 
2845         //      filename.Printf(_T(temp.c_str()));
2846         //filename.Printf(_T("%s\\%s-Value.mhd",directory.c_str(),namefile.c_str(),z);
2847         /*filename.Printf(_T("%s"),directory.c_str());
2848         filename.append(_T("\\"));
2849         filename.append(_T("%s"),namefile.c_str());
2850         filename.append(_T("-Value.mhd"));*/
2851
2852 // Image Value
2853         vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
2854         writerValueImage->SetInput( value );
2855         writerValueImage->SetFileName( (const char *)filename.mb_str() );
2856         writerValueImage->SetFileDimensionality( 3 );
2857         writerValueImage->Write( );
2858
2859 // Image Mask
2860         //              filename.Printf("%s\\%s-Mask.mhd",directory.c_str(),namefile.c_str(),z);
2861         temp = directory + "/" + namefile + "-Mask.mhd";
2862
2863         // LG 14/01/09 : using crea
2864         filename = crea::std2wx(temp);
2865         //      filename.Printf(_T(temp.c_str()));
2866
2867         /*filename.Printf(_T("%s"),directory.c_str());
2868         filename.append(_T("\\"));
2869         filename.append(_T("%s"),namefile.c_str());
2870         filename.append(_T("-Mask.mhd"));*/
2871
2872         vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
2873         writerMaskImage->SetInput( mask );
2874         writerMaskImage->SetFileName( (const char *)filename.mb_str() );
2875         writerMaskImage->SetFileDimensionality( 3 );
2876         writerMaskImage->Write( );
2877
2878         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2879         
2880 }
2881
2882
2883
2884 void wxContourMainFrame::onChangeInstantInstantPanel(std::string name,int value, int minshow, int maxshow){
2885         if( name.compare( _theViewPanel->getVerticalConceptName() ) == 0){
2886                 _theViewPanel->setActualVertical( value);
2887         }
2888         else if( name.compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( name, 0 ) )     {
2889                 _theViewPanel->setHorizontalConcept( name, minshow, maxshow, minshow, maxshow, value);
2890         }
2891
2892         changeInstant();
2893 }
2894
2895 void wxContourMainFrame::onSnakePressed(){
2896         std::vector<double> vecX; 
2897         std::vector<double> vecY; 
2898         std::vector<double> vecZ; 
2899         _theViewPanel->GetPointsOfActualContour( &vecX , &vecY , &vecZ );       
2900
2901         if (vecX.size()!=0){
2902                 std::vector<int> tempVector;
2903                 _instantPanel->getInstant( tempVector );
2904                 int i,size=vecZ.size();
2905                 int actualSlice = tempVector[1];
2906                 for ( i=0 ; i<size ; i++ )
2907                 {
2908                         vecZ[i] = actualSlice;
2909                 } // for
2910
2911                 wxDialog* dialog = new wxDialog(this, -1, wxString(_T("Snake")));
2912                 wxPanel* panel = new wxPanel(dialog,-1); 
2913                 //              wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2914          new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2915                 dialog->ShowModal();
2916         } // if 
2917
2918 }
2919
2920 void wxContourMainFrame::saveFileWithContoursAutomatique(){
2921         std::string filename = kernelManager->getCurrentFileName();
2922         if(filename.compare("")!=0){
2923                 saveFileWithContours(filename);
2924         }else{
2925                 onSave();
2926         }
2927 }
2928 void wxContourMainFrame::ShowToolsPanel(bool show){
2929         _pannew->Show(show);
2930 }
2931
2932
2933
2934 void wxContourMainFrame::SetContourGroup(int contourGroup)
2935 {
2936         _contourGroup = contourGroup;
2937 }
2938
2939
2940 wxPanel *wxContourMainFrame::getMaskImageViewPanel(wxWindow *parent)
2941 {
2942         
2943         if      (_viewMaskImagePanel==NULL)
2944         {
2945                 _contourextractdata = new ContourExtractData(true);
2946                 _contourextractdata->SetImage( _theViewPanel->getImageData() );
2947                 
2948 //              double range[2];
2949 //              _theViewPanel->getImageData()->GetScalarRange(range);
2950                 //int min = (int)floor (range[0]);
2951                 //int max = (int)ceil (range[1]);
2952                 int min = 254;
2953                 int max = 256;
2954                 
2955                 _viewMaskImagePanel = new ThresholdImageViewPanel( parent, -1, -1 , 0);
2956                 _viewMaskImage = new ThresholdImageView();
2957                 _viewMaskImage->SetImage(_contourextractdata->GetVtkImageMaskResult() );
2958                 _viewMaskImage->SetminMaxValue( min, max);
2959                 _viewMaskImage->SetBaseColor( 0,0,1 );
2960                 _viewMaskImagePanel->SetThresholdImageView( _viewMaskImage );
2961                 _viewMaskImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
2962                 
2963         }
2964         return _viewMaskImagePanel;
2965 }
2966
2967 wxPanel *wxContourMainFrame::getThresholdImageViewPanel(wxWindow *parent)
2968 {
2969         if      (_viewThresholdImagePanel==NULL)
2970         {
2971                 double range[2];
2972                 _theViewPanel->getImageData()->GetScalarRange(range);
2973                 int min = (int)floor (range[0]);
2974                 int max = (int)ceil (range[1]);         
2975                 _viewThresholdImagePanel = new ThresholdImageViewPanel( parent, min, max , 1);
2976                 _viewThresholdImage = new ThresholdImageView();
2977                 _viewThresholdImage->SetImage( _theViewPanel->getImageData() );
2978                 _viewThresholdImage->SetminMaxValue( min, max);
2979                 _viewThresholdImage->SetBaseColor( 1,0,0 );
2980                 _viewThresholdImagePanel->SetThresholdImageView( _viewThresholdImage );
2981                 _viewThresholdImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
2982         }
2983         return _viewThresholdImagePanel;
2984 }
2985
2986 //CMRU 17-08-09-----------------------------------------------------------------------------------------------
2987 int wxContourMainFrame::getType ()
2988 {
2989         int tipo = 0;
2990         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2991
2992         if(!currentSelection.empty())
2993         {
2994                 std::string cloneName = currentSelection [0];
2995                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
2996                 tipo = manualModel-> GetTypeModel();    
2997         }
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 //------------------------------------------------------------------------------------------------------------