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