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