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