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