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