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