]> 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.1
758         std::string version(tmp);
759
760         deleteAllContours();
761
762         openContours(pFile,false);
763         if (version!="1.0.0"){
764                 openContours(pFile,true);
765         }
766
767         fclose(pFile);
768         
769         //_theViewPanel->getSceneManager()->removeSceneContours();
770         //changeInstant();
771
772 }
773
774 void wxContourMainFrame::onLoad(){
775         char tmp[255];
776         wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxOPEN );
777         if (dialog.ShowModal() == wxID_OK)
778         {
779                 std::string fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
780                 FILE *pFile=fopen(fileNameContourROI.c_str(),"r+");
781
782                 fscanf(pFile,"%s",tmp); // --CreaContour--
783
784                 fscanf(pFile,"%s",tmp); // Version
785                 fscanf(pFile,"%s",tmp); // 1.0.1 || 1.0.0
786                 std::string version(tmp);
787                 
788                 //AD:02-06-09
789                 if (version=="1.0.1")
790                 {
791                         openContours(pFile,false);
792                 }
793                 
794                 //AD:02-06-09
795                 else if (version=="1.0.0")
796                 {
797                         openContours(pFile,true);
798                 }
799 //                        _theViewPanel->getSceneManager()->openFileWithContours(ff);
800
801                 fclose(pFile);
802         }
803         _theViewPanel->getSceneManager()->removeSceneContours();
804         changeInstant();
805 }
806
807 //AD: 29-05-09
808 void wxContourMainFrame::onSave(){
809         wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxSAVE );
810         if (dialog.ShowModal() == wxID_OK)
811         {
812                 std::string fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
813                 kernelManager->setCurrentFileName(fileNameContourROI);
814                 saveFileWithContours( fileNameContourROI );
815         }
816 }
817
818 //AD: 29-05-09
819 void wxContourMainFrame::saveFileWithContours( std::string filename )
820 {
821
822         FILE *pFile=fopen(filename.c_str(),"w+");
823         std::vector< std::string > lstNameThings;
824         int i,sizeLstNameThings; 
825
826         fprintf(pFile,"--CreaContour--\n");
827         fprintf(pFile,"Version %s\n", "1.0.1" );
828
829         // Normal Contours
830         lstNameThings           = kernelManager->GetLstNameThings();
831         sizeLstNameThings       = lstNameThings.size(); 
832         fprintf(pFile,"NumberOfContours %d\n", sizeLstNameThings );
833
834         vtkImageData *image = _images[0];
835
836         int dimRange[3];
837         image->GetDimensions(dimRange);
838
839         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
840
841         double spaRange[3];
842         image->GetSpacing(spaRange);
843
844         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
845
846         for (i=0 ; i<sizeLstNameThings ; i++) 
847         {
848                 kernelManager->SaveThingName( pFile, lstNameThings[i] );
849                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
850         }// for i
851
852         //-- Contours Statics 
853         lstNameThings           = kernelManager->GetLstNameThingsStatic();
854         sizeLstNameThings       = lstNameThings.size(); 
855         fprintf(pFile,"NumberOfContoursStatic %d\n", sizeLstNameThings );
856         for (i=0 ; i<sizeLstNameThings ; i++) 
857         {
858                 kernelManager->SaveThingName( pFile, lstNameThings[i] );
859                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
860         }// for i
861         fclose(pFile);
862 }
863
864 //AD:02-06-09: TODO: Adjust spacing and dimensions to Rois comming from images with different specifications
865 void wxContourMainFrame::openContours( FILE *pFile, bool staticContour ){
866         char tmp[255];
867         fscanf(pFile,"%s",tmp); // NumberOfContours 
868         fscanf(pFile,"%s",tmp); // ##
869         int numberOfContours = atoi(tmp);  
870
871         std::vector<int> instantVector;
872         int typeContourModel;
873         manualContourModel *manModelContour;
874         int typeView;
875
876         vtkImageData *image = _images[0];
877         int imageDim[3];
878         image->GetDimensions(imageDim);
879         double imageSpac[3];
880         image->GetSpacing(imageSpac);
881
882         int tempDim[3];
883         double tempSpac[3];
884
885         fscanf(pFile,"%s",tmp); // ImageDimensions
886         fscanf(pFile,"%s",tmp); // X
887         tempDim[0] = atoi(tmp);
888         fscanf(pFile,"%s",tmp); // Y
889         tempDim[1] = atoi(tmp);
890         fscanf(pFile,"%s",tmp); // Z
891         tempDim[2] = atoi(tmp);
892
893         fscanf(pFile,"%s",tmp); // ImageSpacing
894         fscanf(pFile,"%s",tmp); // X
895         tempSpac[0] = atof(tmp);
896         fscanf(pFile,"%s",tmp); // Y
897         tempSpac[1] = atof(tmp);
898         fscanf(pFile,"%s",tmp); // Z
899         tempSpac[2] = atof(tmp);
900
901         bool compatible = true;
902
903         //Compare Spacing and Dims in X and Y (Necessary in Z?)
904         if (imageDim[0]!=tempDim[0] || imageDim[1]!=tempDim[1] || 
905                 imageSpac[0]!=tempSpac[0] || imageSpac[1]!=tempSpac[1])
906         {
907                 compatible = false;
908         }
909
910         if (compatible==true)
911         {
912                 int i;
913                 for (i=0;i<numberOfContours;i++)
914                 {
915                         instantVector.clear();
916                         fscanf(pFile,"%s",tmp); // Instant
917
918                         fscanf(pFile,"%s",tmp); // 1
919                         instantVector.push_back( atoi(tmp) );
920                         fscanf(pFile,"%s",tmp); // 2
921                         instantVector.push_back( atoi(tmp) );
922                         fscanf(pFile,"%s",tmp); // 3
923                         instantVector.push_back( atoi(tmp) );
924                         fscanf(pFile,"%s",tmp); // 4
925                         instantVector.push_back( atoi(tmp) );
926                         fscanf(pFile,"%s",tmp); // 5
927                         instantVector.push_back( atoi(tmp) );
928                         fscanf(pFile,"%s",tmp); // 6
929                         instantVector.push_back( atoi(tmp) );
930
931
932                         fscanf(pFile,"%s",tmp); // TypeContourModel
933                         fscanf(pFile,"%s",tmp); // ##
934                         typeContourModel = atoi(tmp);
935
936                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
937                         manModelContour->Open(pFile);
938
939                         fscanf(pFile,"%s",tmp); // TypeView
940                         fscanf(pFile,"%s",tmp); // ##
941                         typeView = atoi(tmp);  
942
943
944         //                      if (typeView==1) 
945         //                      {
946         //                      }
947
948
949                         std::string theName;
950                         theName = kernelManager->createOutline( manModelContour, instantVector );
951                         bool addedModel = theName.compare("") != 0;
952                         if( addedModel )
953                         {
954                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
955                                 _theViewPanel->getSpacing(spc);                                 
956                                 //Adding the manualContourControler to interface objects structure
957                                 //Adding the manualViewContour to interface objects structure           
958                                 //_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.
959                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
960                         }       
961
962                         if (staticContour==true)
963                         {
964                                 Instant instant(&instantVector);
965                                 kernelManager->changeContourOfManager( theName , &instant );
966                         }
967
968                 }// for  numberOfContours
969         }
970
971         else if (compatible==false)
972         {
973                 wxMessageBox(_T("The actual image is not compatible with the selected Roi file"), _T("Error"), wxICON_ERROR | wxOK);
974         }
975 }
976
977 void wxContourMainFrame::RefreshInterface(){
978         changeInstant();
979         _theViewPanel->RefreshInterface();
980         //wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
981         //wxvtk2dbaseview->Refresh();
982 }
983
984 vtkImageData* wxContourMainFrame::getImageData(){
985         return _theViewPanel->getImageData();
986 }
987
988 void wxContourMainFrame::onSegmentationOneSliceITK(wxString distance, wxString sigma, wxString alfa, wxString beta, wxString propagation, wxString iterations, wxString inflation)
989 {
990         //JCP 20-10-08 Undo redo implementation
991         saveState();
992         //JCP 20-10-08 Undo redo implementation
993         
994         wxBusyCursor wait;
995         int                                     x                                       = _theViewPanel->GetX();
996         int                                     y                                       = _theViewPanel->GetY();
997         int                                     z                                       = _theViewPanel->GetZ();
998         SegmentationOneSliceITK( x,y,z,distance, sigma, alfa, beta, propagation, iterations, inflation);
999         RefreshInterface();
1000 }
1001
1002 void wxContourMainFrame::SegmentationOneSliceITK(int x, int y, int z, wxString distanc, wxString sigm, wxString alf, wxString bet, wxString prop, wxString iter, wxString inflation)
1003 {
1004         int typeofcontour = 1;
1005         //Image Data
1006         vtkImageData    *imagedata      = getImageData();
1007         
1008         //Tipo de pixeles a utilizar internamente en ITK
1009         typedef   float  InternalPixelType;
1010         const     unsigned int    Dimension = 2;
1011         typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
1012
1013         //Tipo de pixeles de salida 1
1014         typedef unsigned char OutputPixelType;
1015         typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
1016
1017         //Tipo de pixeles de salida 2
1018         typedef unsigned short OutputPixelType2;
1019         typedef itk::Image< OutputPixelType2, Dimension > OutputImageType2;
1020
1021         //DefiniciÛn del thresholder
1022         typedef itk::BinaryThresholdImageFilter< 
1023                                                         InternalImageType, 
1024                                                         OutputImageType    >    ThresholdingFilterType;
1025           
1026         //DefiniciÛn del primer filtro de conversiÛn de pixeles
1027         typedef itk::CastImageFilter<
1028                                 OutputImageType, OutputImageType2 >  CastFilterType;
1029
1030         //DefiniciÛn del segundo tipo de conversiÛn de pixeles
1031         typedef itk::CastImageFilter<
1032                                 OutputImageType2, InternalImageType >  CastFilterType2;
1033
1034         //Tercer tipo de conversiÛn
1035         typedef itk::RescaleIntensityImageFilter< 
1036                                                                 InternalImageType, 
1037                                                                 OutputImageType >   CastFilterType3;
1038
1039         //Cuarto tipo de conversiÛn
1040         typedef itk::RescaleIntensityImageFilter< 
1041                                                                 OutputImageType, 
1042                                                                 OutputImageType >   CastFilterType4;
1043
1044         ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();
1045                                 
1046         thresholder->SetLowerThreshold( 0.0 );
1047         thresholder->SetUpperThreshold( 128 );
1048
1049         thresholder->SetOutsideValue(  255  );
1050         thresholder->SetInsideValue(  0 );
1051
1052         //DefinciÛn de conexiÛnes entre VTK e ITK y el writer
1053         typedef itk::VTKImageToImageFilter<OutputImageType2> ConnectorType;
1054         typedef itk::ImageToVTKImageFilter<OutputImageType> ConnectorType2;
1055         typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
1056
1057         ConnectorType::Pointer connector= ConnectorType::New();
1058         ConnectorType2::Pointer connector2= ConnectorType2::New();
1059           
1060
1061         CastFilterType::Pointer filter=CastFilterType::New();
1062         CastFilterType2::Pointer filter2=CastFilterType2::New();
1063
1064         connector->SetInput( imagedata );
1065         filter2->SetInput(connector->GetOutput());
1066
1067         typedef   itk::CurvatureAnisotropicDiffusionImageFilter< 
1068                                                                 InternalImageType, 
1069                                                                 InternalImageType >  SmoothingFilterType;
1070
1071         SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New();
1072
1073         typedef   itk::GradientMagnitudeRecursiveGaussianImageFilter< 
1074                                                                 InternalImageType, 
1075                                                                 InternalImageType >  GradientFilterType;
1076
1077         typedef   itk::SigmoidImageFilter<                               
1078                                                                 InternalImageType, 
1079                                                                 InternalImageType >  SigmoidFilterType;
1080
1081         GradientFilterType::Pointer  gradientMagnitude = GradientFilterType::New();
1082
1083         SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New();
1084
1085         sigmoid->SetOutputMinimum(  0.0  );
1086         sigmoid->SetOutputMaximum(  255.0  );
1087
1088
1089         typedef  itk::FastMarchingImageFilter< 
1090                                                                 InternalImageType, 
1091                                                                 InternalImageType >    FastMarchingFilterType;
1092
1093
1094         FastMarchingFilterType::Pointer  fastMarching = FastMarchingFilterType::New();
1095
1096         typedef  itk::GeodesicActiveContourLevelSetImageFilter< InternalImageType, 
1097                                         InternalImageType >    GeodesicActiveContourFilterType;
1098         GeodesicActiveContourFilterType::Pointer geodesicActiveContour = 
1099                                                                                 GeodesicActiveContourFilterType::New();
1100
1101         typedef  itk::ZeroCrossingImageFilter< 
1102                                                                 InternalImageType, 
1103                                                                 InternalImageType >    ZeroCrossingFilterType;
1104         ZeroCrossingFilterType::Pointer zeroCrossing =
1105                                                         ZeroCrossingFilterType::New();
1106
1107         const double propagationScaling = atof( crea::wx2std(prop).c_str() );
1108
1109         geodesicActiveContour->SetPropagationScaling( propagationScaling );
1110         geodesicActiveContour->SetCurvatureScaling( 1.0 );
1111         geodesicActiveContour->SetAdvectionScaling( 1.0 );
1112
1113         geodesicActiveContour->SetMaximumRMSError( 0.02 );
1114         int it=atoi(  crea::wx2std(iter).c_str() );
1115         geodesicActiveContour->SetNumberOfIterations( it );
1116
1117         smoothing->SetInput( filter2->GetOutput() );
1118         gradientMagnitude->SetInput( smoothing->GetOutput() );
1119         sigmoid->SetInput( gradientMagnitude->GetOutput() );
1120         fastMarching->SetInput( sigmoid->GetOutput() );
1121         geodesicActiveContour->SetInput( fastMarching->GetOutput() );
1122         geodesicActiveContour->SetFeatureImage( sigmoid->GetOutput() );
1123           
1124         zeroCrossing->SetInput( geodesicActiveContour->GetOutput() );
1125         //thresholder->SetInput( zeroCrossing->GetOutput() );
1126         thresholder->SetInput( geodesicActiveContour->GetOutput() );
1127         connector2->SetInput( thresholder->GetOutput()  );
1128           
1129
1130         smoothing->SetTimeStep( 0.125 );
1131         smoothing->SetNumberOfIterations(  5 );
1132         smoothing->SetConductanceParameter( 9.0 );
1133
1134
1135         const double sigma = atof(  crea::wx2std(sigm).c_str() );
1136         gradientMagnitude->SetSigma(  sigma  );
1137
1138         const double alpha =  atof(  crea::wx2std(alf).c_str() );
1139         const double beta  =  atof(  crea::wx2std(bet).c_str() );
1140
1141         sigmoid->SetAlpha( alpha );
1142         sigmoid->SetBeta(  beta  );
1143           
1144         typedef FastMarchingFilterType::NodeContainer  NodeContainer;
1145         typedef FastMarchingFilterType::NodeType       NodeType;
1146
1147         NodeContainer::Pointer seeds = NodeContainer::New();
1148
1149         InternalImageType::IndexType  seedPosition;
1150         seedPosition[0] = x;
1151         seedPosition[1] = y;
1152
1153         const double initialDistance = atof( crea::wx2std(distanc).c_str() );
1154
1155         NodeType node;
1156
1157         const double seedValue = - initialDistance;
1158
1159         node.SetValue( seedValue );
1160         node.SetIndex( seedPosition );
1161                 
1162         seeds->Initialize();
1163         seeds->InsertElement( 0, node );
1164
1165         fastMarching->SetTrialPoints( seeds );
1166
1167         fastMarching->SetSpeedConstant( 1.0 );
1168           
1169         fastMarching->SetOutputSize( 
1170                         connector->GetOutput()->GetBufferedRegion().GetSize() );
1171           
1172         fastMarching->SetStoppingValue( 800 );
1173         try
1174     {
1175                 
1176         connector2->Update();
1177         vtkImageData *idata = connector2->GetOutput();
1178
1179         vtkMarchingContourFilter* cntVTK = vtkMarchingContourFilter::New( );
1180         
1181         cntVTK->SetInput( idata );
1182         
1183         cntVTK->SetNumberOfContours( 1 );
1184         cntVTK->SetValue( 0, 255 );
1185         cntVTK->Update( );
1186         cntVTK->UpdateInformation();
1187                 
1188         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1189         cpd->SetInput( cntVTK->GetOutput( ) );
1190         cpd->Update( );
1191         cpd->UpdateInformation();
1192
1193         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1194         conn->SetExtractionModeToLargestRegion( );
1195         conn->SetInput( cpd->GetOutput( ) );
1196         conn->Update( );
1197         conn->UpdateInformation();
1198
1199         vtkStripper* vtkstripper = vtkStripper::New( );
1200         vtkstripper->SetInput( conn->GetOutput() );
1201         vtkstripper->Update();
1202         vtkstripper->UpdateInformation();
1203
1204
1205         vtkPolyData* polyDataResult =  cntVTK->GetOutput();
1206         //std::cout<<"Points "<<polyDataResult->GetNumberOfPoints()<<std::endl;
1207         polyDataResult->Update( );
1208         polyDataResult->UpdateInformation();
1209
1210         //EED
1211                 /*
1212         ofstream myfile;
1213         myfile.open ("C:/Creatis/example.txt");
1214         myfile << "\n";
1215         polyDataResult->Print(myfile);
1216         myfile << "-------------------------------------\n";
1217         polyDataResult->GetLines()->Print(myfile);
1218         myfile.close();*/
1219
1220         cntVTK          -> Delete();
1221         cpd                     -> Delete();
1222         conn            -> Delete();
1223
1224
1225         //--Calculating control points
1226
1227         std::vector<double> vecX;
1228         std::vector<double> vecY;
1229         std::vector<double> vecXo;
1230         std::vector<double> vecYo;
1231         std::vector<double>::iterator vecXoi;
1232         std::vector<double>::iterator vecYoi;
1233         std::vector<double> vecZ;
1234
1235         std::vector<double> vecCtrlPointX;
1236         std::vector<double> vecCtrlPointY;
1237         std::vector<double> vecCtrlPointZ;
1238
1239
1240         double *p;
1241         double xAct=0;
1242         double yAct=0;
1243         int ii,size=polyDataResult->GetNumberOfPoints();
1244         ofstream myfile;
1245         myfile.open ("C:/Creatis/example2.txt");
1246
1247         size=polyDataResult->GetNumberOfPoints();
1248         for (ii=0;ii<size;ii++)
1249         {
1250                 if(ii==0)
1251                 {
1252                         xAct=x;
1253                         yAct=y;
1254                 }
1255                 p       = polyDataResult->GetPoint(ii);
1256                 double x=p[0];
1257                 double y=p[1];
1258                 /*if(fabs(yAct-y)>20)
1259                 {
1260                         if((xAct-x)>1 || (xAct-x)<-1)
1261                         {
1262                         vecX.push_back( p[0] );
1263                         vecY.push_back( p[1] );
1264                         myfile <<p[0]<<","<<p[1]<<"\n";
1265                         std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1266                 std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1267                 std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1268                         vecZ.push_back( 900 );
1269                         xAct=x;
1270                         yAct=y;
1271                         }
1272                         else
1273                         {
1274                                 vecXo.push_back(p[0]);
1275                                 vecYo.push_back(p[1]);
1276                         }
1277                         
1278                 }
1279                 else*/ if(fabs(xAct-x)>11)
1280                 {
1281                         vecXo.push_back(p[0]);
1282                         vecYo.push_back(p[1]);
1283                 }
1284                 else
1285                 {
1286                 vecX.push_back( p[0] );
1287                 myfile <<p[0]<<","<<p[1]<<"\n";
1288                 //std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1289                 //std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1290                 //std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1291                 vecY.push_back( p[1] );
1292                 vecZ.push_back( 900 );
1293                 xAct=x;
1294                 yAct=y;
1295                 }
1296                 
1297                 
1298         }
1299
1300         while(!vecXo.empty())
1301         {
1302                 vecX.push_back(vecXo.back());
1303                 //std::cout<<" x Siguiente "<<vecXo.back();
1304                 vecXo.pop_back();
1305                 vecZ.push_back( 900 );
1306         }
1307         while(!vecYo.empty())
1308         {
1309                 vecY.push_back(vecYo.back());
1310                         vecYo.pop_back();
1311         }
1312         myfile.close();
1313
1314         /*for(int l=0;l<vecX.size();l++)
1315         {
1316                 if(l==0)
1317                 {
1318             vecXo.push_back(p[0]);
1319                         vecYo.push_back(p[1]);
1320                 }
1321                 else
1322                 {
1323                         if(vecXoi[l-1]==)
1324                         {
1325                         }
1326                 }
1327
1328         }*/
1329
1330         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1331
1332         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1333         
1334         int method=2;
1335         if (method==0){
1336                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1337         }
1338         else if (method==1){
1339                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1340         }
1341         else if (method==2){
1342                 extractcontrolpoints2d->SetSamplingControlPoints( 15 );
1343                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1344         }
1345         //--Adding contour to the system
1346
1347         std::vector<int> actualInstantVector;
1348         _instantPanel->getInstant( actualInstantVector );
1349         actualInstantVector[1]=z;
1350
1351         int j,sizeCtrPt = vecCtrlPointX.size();
1352         
1353         manualContourModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1354         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1355         if (sizeCtrPt>=3){
1356                 for (j=0 ; j<sizeCtrPt ; j++)
1357                 {
1358                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1359                 } // for
1360                 std::string theName;
1361                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1362                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1363                 bool addedModel = theName.compare("") != 0;
1364                 if( addedModel )
1365                 {
1366                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1367                         _theViewPanel->getSpacing(spc); 
1368                         //Adding the manualContourControler to interface objects structure
1369                         //Adding the manualViewContour to interface objects structure           
1370                         //_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.
1371                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1372                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1373                 }       // if addedModel
1374         } // if sizeCtrPt
1375
1376                 
1377                  
1378                  WriterType::Pointer writer = WriterType::New();
1379          CastFilterType3::Pointer caster = CastFilterType3::New();
1380                  
1381                  caster->SetInput( gradientMagnitude->GetOutput() );
1382                  writer->SetInput( caster->GetOutput() );
1383                  writer->SetFileName("Gradient Magnitude.png");
1384                  caster->SetOutputMinimum(   0 );
1385                  caster->SetOutputMaximum( 255 );
1386                  writer->Update();
1387                 
1388                  CastFilterType3::Pointer caster2 = CastFilterType3::New();
1389                  WriterType::Pointer writer2 = WriterType::New();
1390
1391                  caster2->SetInput( sigmoid->GetOutput() );
1392                  writer2->SetInput( caster2->GetOutput() );
1393                  writer2->SetFileName("Sigmoid.png");
1394                  caster2->SetOutputMinimum(   0 );
1395                  caster2->SetOutputMaximum( 255 );
1396                  writer2->Update();
1397
1398                  CastFilterType3::Pointer caster3 = CastFilterType3::New();
1399                  WriterType::Pointer writer3 = WriterType::New();
1400
1401                  caster3->SetInput( fastMarching->GetOutput() );
1402                  writer3->SetInput( caster3->GetOutput() );
1403                  writer3->SetFileName("FastMarching.bmp");
1404                  caster3->SetOutputMinimum(   0 );
1405                  caster3->SetOutputMaximum( 255 );
1406                  writer3->Update();
1407
1408                  CastFilterType3::Pointer caster4 = CastFilterType3::New();
1409                  WriterType::Pointer writer4 = WriterType::New();
1410
1411                  caster4->SetInput( geodesicActiveContour->GetOutput() );
1412                  writer4->SetInput( caster4->GetOutput() );
1413                  writer4->SetFileName("GeodesicActiveContour.png");
1414                  caster4->SetOutputMinimum(   0 );
1415                  caster4->SetOutputMaximum( 255 );
1416                  writer4->Update();
1417
1418                  CastFilterType3::Pointer caster5 = CastFilterType3::New();
1419                  WriterType::Pointer writer5 = WriterType::New();
1420
1421                  caster5->SetInput( zeroCrossing->GetOutput() );
1422                  writer5->SetInput( caster5->GetOutput() );
1423                  writer5->SetFileName("ZeroCrossing.bmp");
1424                  caster5->SetOutputMinimum(   0 );
1425                  caster5->SetOutputMaximum( 255 );
1426                  writer5->Update();
1427     }
1428   catch( itk::ExceptionObject & excep )
1429     {
1430     std::cerr << "Exception caught !" << std::endl;
1431     std::cerr << excep << std::endl;
1432     }
1433 }
1434
1435 void wxContourMainFrame::onSegmentationOneSlice(int isovalue,int sampling,int method){
1436         
1437         //JCP 20-10-08 Undo redo implementation
1438         saveState();
1439         //JCP 20-10-08 Undo redo implementation
1440         
1441         wxBusyCursor wait;
1442         int                                     x                                       = _theViewPanel->GetX();
1443         int                                     y                                       = _theViewPanel->GetY();
1444         int                                     z                                       = _theViewPanel->GetZ();
1445         SegmentationOneSlice( x,y,z,isovalue, sampling, method );
1446         RefreshInterface();
1447 }
1448
1449
1450 void wxContourMainFrame::SegmentationOneSlice( int x, int y, int z, int isovalue, int sampling, int method )
1451 {               
1452         int typeofcontour = 1;
1453         //--Extracting Contour
1454         //vtkImageData  *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
1455         vtkImageData    *imagedata      = getImageData();
1456 //              double                  *range          = imagedata->GetScalarRange();  
1457 //              double                  thr                     = 1;
1458
1459         vtkImageReslice *imageReslice = vtkImageReslice::New();
1460 //EED
1461 //              double spc[3];
1462 //              imagedata->GetSpacing(spc);
1463 //              x = x*spc[0];
1464 //              y = y*spc[1];
1465 //              z = z*spc[3];
1466
1467         imageReslice->SetInput( imagedata );
1468         imageReslice->SetInformationInput(imagedata);
1469         imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
1470         imageReslice->SetResliceAxesOrigin(0,0,z);
1471         imageReslice->SetOutputDimensionality(2);
1472         imageReslice->SetInterpolationModeToLinear();
1473
1474         imagedata = imageReslice->GetOutput();
1475         imagedata->Update();
1476         imagedata->UpdateInformation();
1477
1478         vtkContourFilter* cntVTK = vtkContourFilter::New( );
1479         cntVTK->SetInput( imagedata );
1480
1481         cntVTK->SetNumberOfContours( 1 );
1482         //cntVTK->SetValue( 0, vmin );
1483 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
1484         cntVTK->SetValue( 1, isovalue );
1485 //      cntVTK->SetValue( 1, vmax );
1486         cntVTK->Update( );
1487         cntVTK->UpdateInformation();
1488                 
1489         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1490         cpd->SetInput( cntVTK->GetOutput( ) );
1491         cpd->ConvertLinesToPointsOff( );
1492         cpd->Update( );
1493         cpd->UpdateInformation();
1494
1495         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1496         conn->SetExtractionModeToClosestPointRegion( );
1497         //conn->SetMaxRecursionDepth( 3000 );
1498                 
1499         conn->SetInput( cpd->GetOutput( ) );
1500                 
1501         conn->SetClosestPoint( x, y, 0 );
1502         conn->Update( );
1503         conn->UpdateInformation();
1504                 
1505         vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
1506         cpd2->SetInput( conn->GetOutput( ) );
1507         cpd2->Update();
1508         cpd2->UpdateInformation();
1509
1510         vtkStripper* vtkstripper = vtkStripper::New( );
1511         vtkstripper->SetInput( cpd2->GetOutput() );
1512         vtkstripper->Update();
1513         vtkstripper->UpdateInformation();
1514
1515
1516         vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
1517
1518         polyDataResult->Update( );
1519         polyDataResult->UpdateInformation();
1520
1521 /* EED
1522 ofstream myfile;
1523 myfile.open ("c:/temp/example.txt");
1524 myfile << "\n";
1525 polyDataResult->Print(myfile);
1526 myfile << "-------------------------------------\n";
1527 polyDataResult->GetLines()->Print(myfile);
1528 myfile.close();
1529 */
1530
1531         cntVTK          -> Delete();
1532         cpd2            -> Delete();
1533         cpd                     -> Delete();
1534         conn            -> Delete();
1535
1536
1537 //--Calculating control points
1538
1539         std::vector<double> vecX;
1540         std::vector<double> vecY;
1541         std::vector<double> vecZ;
1542
1543         std::vector<double> vecCtrlPointX;
1544         std::vector<double> vecCtrlPointY;
1545         std::vector<double> vecCtrlPointZ;
1546
1547
1548         double *p;
1549         int ii,size=polyDataResult->GetNumberOfPoints();
1550         int id;
1551         for (ii=1;ii<=size;ii++)
1552         {
1553                 id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
1554                 p       = polyDataResult->GetPoint(id);
1555 //              double x=p[0];
1556 //              double y=p[1];
1557                 vecX.push_back( p[0] );
1558                 vecY.push_back( p[1] );
1559                 vecZ.push_back( 900 );
1560 //                      vecZ.push_back( p[2] );
1561         }
1562
1563
1564         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1565         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1566
1567 //PROOFS
1568         /*if (methodRadiobox->GetSelection()==0){
1569                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1570         }
1571         if (methodRadiobox->GetSelection()==1){
1572                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1573         }
1574         if (methodRadiobox->GetSelection()==2){
1575                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1576                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1577         }*/
1578
1579         if (method==0){
1580                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1581         }
1582         else if (method==1){
1583                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1584         }
1585         else if (method==2){
1586                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1587                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1588         }
1589
1590         //--Adding contour to the system
1591
1592         std::vector<int> actualInstantVector;
1593         _instantPanel->getInstant( actualInstantVector );
1594         actualInstantVector[1]=z;
1595
1596         int j,sizeCtrPt = vecCtrlPointX.size();
1597         manualContourModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1598         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1599         if (sizeCtrPt>=3){
1600                 for (j=0 ; j<sizeCtrPt ; j++)
1601                 {
1602                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1603                 } // for
1604                 std::string theName;
1605                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1606                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1607                 bool addedModel = theName.compare("") != 0;
1608                 if( addedModel )
1609                 {
1610                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1611                         _theViewPanel->getSpacing(spc);                                 
1612                         //Adding the manualContourControler to interface objects structure
1613                         //Adding the manualViewContour to interface objects structure           
1614                         //_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.
1615                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1616                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1617                 }       // if addedModel
1618         } // if sizeCtrPt
1619 }
1620 int wxContourMainFrame::GetImageDataSizeZ(){
1621         return _theViewPanel->GetImageDataSizeZ();
1622 }
1623
1624 void wxContourMainFrame::GetImageDataRange(double *range){
1625         _theViewPanel->GetImageDataRange(range);
1626 }
1627
1628 void wxContourMainFrame::onSegmentationAllSlice(int minZ,int maxZ,int isovalue,int sampling,int method){
1629         //JCP 20-10-08 Undo redo implementation
1630         saveState();
1631         //JCP 20-10-08 Undo redo implementation
1632         
1633         wxBusyCursor wait;
1634         int                                     x                                       = _theViewPanel->GetX();
1635         int                                     y                                       = _theViewPanel->GetY();
1636         int z;
1637         double porcent; 
1638         wxString tmpString;     
1639         double totalZ = maxZ-minZ+1;
1640         for( z=minZ ; z<=maxZ ; z++ )
1641         {
1642                 porcent = 100.0* (z-minZ)/totalZ;
1643                 tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
1644                 interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(tmpString);
1645                 //_staticTextSegmentation->SetLabel(tmpString);
1646                 SegmentationOneSlice( x,y,z,isovalue, sampling,method );
1647         }
1648         interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(_T("   "));
1649         RefreshInterface();
1650 }
1651
1652
1653 //Creates a reference line to be used as the axis of the mirroring
1654 void wxContourMainFrame::referenceLine()
1655 {
1656         if (_refLineControl==NULL)
1657         {
1658                 wxBusyCursor wait;
1659                 double spc[3];
1660
1661                 vtkImageData *vtkimagedata = _theViewPanel->getImageData();
1662                 vtkimagedata->GetSpacing(spc);
1663
1664                 wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
1665
1666                 _refLineControl = new manualLineControler();
1667                 _refLineModel   = new manualContourModelLine();
1668                 _refLineView = new manualViewLine();
1669                 _refLineView->SetModel( _refLineModel );
1670                 _refLineView->SetWxVtkBaseView( viewer2D );
1671                 _refLineView->SetRange( 2 );
1672                 _refLineView->SetZ( 1200 );
1673
1674                 _refLineView->SetSpacing(spc);
1675
1676                 _refLineView->SetColorNormalContour(0, 0, 1);
1677                 _refLineView->SetColorEditContour(0, 0.5, 0.5);
1678                 _refLineView->SetWidthLine(4);
1679
1680                 _refLineControl->SetModelView( _refLineModel , _refLineView );
1681                 vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
1682                 style->AddInteractorStyleMaracas( _refLineControl );
1683                 _refLineModel->SetCloseContour(false);
1684                 _refLineControl->CreateNewManualContour();
1685
1686 //EED??         double z = _refLineControl->GetZ();
1687         /*
1688                 _refLineControl->AddPoint(50,100,z);
1689                 _refLineControl->AddPoint(80,40,z);
1690                 _refLineControl->SetCompleteCreation(true);
1691
1692                 _refLineModel->AddPoint(50,100,z);
1693                 _refLineModel->AddPoint(80,40,z);
1694                 _refLineModel->UpdateSpline();
1695
1696                 _refLineView->UpdateViewPoint(0);
1697                 _refLineView->UpdateViewPoint(1);
1698         */
1699
1700                 _refLineControl->SetActive(true);
1701                 _refLineView->RefreshContour();
1702         }
1703 }
1704
1705 //Hides the referenceLine
1706 void wxContourMainFrame::refLineHide()
1707 {
1708         if (_refLineControl!=NULL)
1709         {
1710                 if (_refLineControl->GetActive())
1711                 {
1712                         _refLineView->RemoveCompleteContourActor();
1713                         _refLineControl->SetEditable(false);
1714                         _refLineControl->SetActive(false);
1715
1716                         RefreshInterface();
1717                 }
1718         }
1719 }
1720
1721 //Shows the referenceLine
1722 void wxContourMainFrame::refLineShow()
1723 {
1724         if (_refLineControl!=NULL)
1725         {
1726                 if (_refLineControl->GetActive()==false)
1727                 {
1728                         wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
1729
1730                         _refLineView->SetModel( _refLineModel );
1731                         _refLineView->SetWxVtkBaseView( viewer2D );
1732                         _refLineView->SetRange( 2 );
1733                         _refLineView->SetZ( 1200 );
1734
1735                         _refLineControl->SetModelView( _refLineModel , _refLineView );
1736                         vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
1737                         style->AddInteractorStyleMaracas( _refLineControl );
1738                         _refLineControl->CreateNewManualContour();
1739                         _refLineControl->SetActive(true);
1740                         _refLineView->RefreshContour();
1741
1742                         RefreshInterface();
1743                 }
1744         }
1745 }
1746
1747 void wxContourMainFrame::refLineChangeWidth(int width)
1748 {
1749         _refLineView->SetWidthLine(width);
1750         _refLineView->RefreshContour();
1751
1752         RefreshInterface();
1753 }
1754
1755
1756 void wxContourMainFrame::onMirror()
1757 {
1758         //AD:02-09
1759         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
1760         std::vector<std::string> filterCurrentSelection;
1761
1762         std::vector<int> tempVector;
1763         _instantPanel->getInstant( tempVector );
1764     _performingOperation->reset();
1765         _performingOperation->setStartCommand( COPY );
1766         _performingOperation->setStartOperationInstantVector( tempVector );
1767         _performingOperation->setKeyNamesOperationElems( currentSelection );
1768
1769         char theStartCommand = _performingOperation->getStartCommand();
1770         if (  theStartCommand == COPY )
1771         {
1772                 //JCP 20-10-08 Undo redo implementation
1773                 saveState();
1774                 //JCP 20-10-08 Undo redo implementation
1775                 std::vector<int> tempVector;
1776                 _instantPanel->getInstant( tempVector );
1777                 _performingOperation->setEndOperationInstantVector ( tempVector );
1778                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
1779                 int i,size = elems.size();                      
1780                 for( i=0; i<size; i++ )
1781                 {                               
1782                         createMirrorContourOf( elems[i], tempVector, i>0 );
1783                 }               
1784         }
1785
1786         //deleteContour( _refName );
1787         //_refName = "";
1788 }
1789
1790 void wxContourMainFrame::onThreshold()
1791 {
1792         int     z = _theViewPanel->GetZ();
1793         double range[2];
1794
1795         vtkImageData * img = getImageData();
1796         img->GetScalarRange(range);
1797
1798         int minTot = floor (range[0]);
1799         int maxTot = ceil (range[1]);
1800
1801         double minMax[2];
1802         _pannew->onThresholdInstantChange(minMax);
1803         int minVal = floor (minMax[0]);
1804         int maxVal = floor (minMax[1]);
1805
1806         if (!_actorPresent)
1807         {
1808                 if (_imageReslicer==NULL)
1809                 {
1810                         _imageReslicer = vtkImageReslice::New();
1811                         _imageReslicer->SetInput( img );
1812                         _imageReslicer->SetInformationInput(img);
1813                         _imageReslicer->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
1814                         _imageReslicer->SetOutputDimensionality(2);
1815                         _imageReslicer->SetInterpolationModeToLinear();
1816                 }
1817
1818                 _imageReslicer->SetResliceAxesOrigin(0,0,z);
1819
1820                 img = _imageReslicer->GetOutput();
1821                 img->Update();
1822                 img->UpdateInformation();
1823
1824                 wxVtkBaseView * baseView = _theViewPanel->getWxVtkBaseView();
1825
1826                 if (_thresholdTable==NULL)
1827                 {
1828                         //Lookup Table
1829                         _thresholdTable = vtkLookupTable::New();
1830                         _thresholdTable->SetNumberOfTableValues(maxTot+1);
1831                         _thresholdTable->SetTableRange(range); 
1832                         _thresholdTable->SetAlphaRange(0, 1);
1833                         _thresholdTable->SetValueRange(0, 1);
1834                         _thresholdTable->SetSaturationRange(0, 0); 
1835                         _thresholdTable->SetRampToLinear( );
1836                 }
1837
1838                 //Assign a fake color for the upper image, and set the white as transparent
1839                 int i;
1840                 for(i = minTot; i <= maxTot; i++)
1841                 {
1842                         if( i >= minVal && i <= maxVal )
1843                         {
1844                                 _thresholdTable->SetTableValue(i, 1.0, 0.0, 0.0, 1);
1845                         }
1846                         else if( i >= minTot && i < minVal )
1847                         {
1848                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1849                         }
1850                         else if( i > maxVal && i < maxTot )
1851                         {
1852                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1853                         }
1854                         else
1855                         {
1856                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1857                         }
1858                 }
1859                 _thresholdTable->Build( );
1860         
1861                 if (_thresholdMapper==NULL)
1862                 {
1863                         _thresholdMapper = vtkImageMapToColors::New( );
1864                 }
1865                 
1866                 _thresholdMapper->SetLookupTable( _thresholdTable );
1867                 _thresholdMapper->SetInput( img );
1868
1869                 if (_thresholdActor==NULL)
1870                 {
1871                         _thresholdActor = vtkImageActor::New( );
1872                         _thresholdActor->SetOpacity( 0.6 );
1873                         _thresholdActor->InterpolateOn(  );
1874                         _thresholdActor->SetPosition( 0,0, 900-1 );
1875                 }
1876                 
1877                 _thresholdActor->SetInput( _thresholdMapper->GetOutput() );
1878
1879                 baseView->GetRenderer()->AddActor( _thresholdActor );
1880                 _actorPresent = true;
1881         }
1882
1883         else
1884         {
1885                 _imageReslicer->SetResliceAxesOrigin(0,0,z);
1886                 img = _imageReslicer->GetOutput();
1887                 img->Update();
1888                 img->UpdateInformation();
1889
1890                 //Assign a fake color for the upper image, and set the white as transparent
1891                 int i;
1892                 for(i = minTot; i <= maxTot; i++)
1893                 {
1894                         if( i >= minVal && i <= maxVal )
1895                         {
1896                                 _thresholdTable->SetTableValue(i, 1.0, 0.0, 0.0, 1);
1897                         }
1898                         else if( i >= minTot && i < minVal )
1899                         {
1900                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1901                         }
1902                         else if( i > maxVal && i < maxTot )
1903                         {
1904                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1905                         }
1906                         else
1907                         {
1908                                 _thresholdTable->SetTableValue(i, 1.0, 1.0, 1.0, 0); //transparent
1909                         }
1910                 }
1911
1912                 _thresholdTable->Build( );
1913                 _thresholdMapper->SetLookupTable( _thresholdTable );
1914                 _thresholdMapper->SetInput( img );
1915                 _thresholdActor->SetInput( _thresholdMapper->GetOutput() );
1916         }
1917                         /*
1918                                 vtkImageViewer2* viewer = vtkImageViewer2::New();        
1919                                 viewer->SetInput( upperImageActor->GetInput() ); 
1920                                 viewer->SetColorLevel((range[1]-range[0])/2);
1921                                 viewer->SetColorWindow(range[1]);
1922                                 viewer->GetRenderer()->AddActor( upperImageActor );
1923                                 viewer->Render();
1924                         */
1925         _theViewPanel->RefreshInterface();
1926 }
1927
1928
1929 void wxContourMainFrame::onThresholdChange()
1930 {
1931         if (_actorPresent)
1932         {
1933                 onThreshold();
1934         }
1935 }
1936
1937 void wxContourMainFrame::onThresholdInterpolation(bool interpolate)
1938 {
1939         if (_thresholdActor!=NULL)
1940         {
1941                 if (interpolate)
1942                 {
1943                         _thresholdActor->InterpolateOn( );
1944                 }
1945
1946                 else
1947                 {
1948                         _thresholdActor->InterpolateOff( );
1949                 }
1950
1951                 _theViewPanel->RefreshInterface();
1952         }
1953 }
1954
1955 void wxContourMainFrame::onThresholdChangeOpacity (int opacity)
1956 {
1957         if (_actorPresent)
1958         {
1959                 _thresholdActor->SetOpacity(opacity*0.1);
1960         }
1961
1962         _theViewPanel->RefreshInterface();
1963 }
1964
1965 void wxContourMainFrame::onThresholdRemove()
1966 {
1967         if (_actorPresent)
1968         {
1969                 wxVtkBaseView * baseView = _theViewPanel->getWxVtkBaseView();
1970                 baseView->GetRenderer()->RemoveActor( _thresholdActor );
1971                 _actorPresent = false;
1972         }
1973
1974         _theViewPanel->RefreshInterface();
1975 }
1976
1977 void wxContourMainFrame::showAxis(bool show)
1978 {
1979         _theViewPanel->SetVisibleAxis(show);
1980         _theViewPanel->Refresh();
1981 }
1982
1983
1984 void wxContourMainFrame::onRigidPressed(){
1985         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
1986         int elementsSelected = currentSelection.size();
1987
1988         if ( elementsSelected >= 1 ){
1989                 //JCP 20-10-08 Undo redo implementation
1990                 saveState();
1991                 //JCP 20-10-08 Undo redo implementation
1992
1993                 std::vector<int> tempVector;
1994                 _instantPanel->getInstant( tempVector );
1995                 Instant instant(&tempVector);
1996
1997                 int i , size=currentSelection.size();
1998                 for ( i=0 ; i<size ; i++ )
1999                 {
2000                         kernelManager->changeContourOfManager(currentSelection[i], &instant);
2001                 } // i
2002         }
2003 }
2004
2005 void wxContourMainFrame::onWidthOfContour(double width){
2006
2007         _theViewPanel->removeSceneContours();
2008         _theViewPanel->SetWidthContour(width);
2009         
2010         //_theViewPanel->getSceneManager()->SetWidthContour( width );
2011
2012         RefreshInterface();
2013 }
2014
2015 int wxContourMainFrame::getColorWindow()
2016 {
2017         /*
2018         double range[2];
2019         vtkImageData * img = getImageData();
2020         img->GetScalarRange(range);
2021
2022         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2023         
2024         return (int)range[1];
2025         */
2026         return _theViewPanel->getColorWindow();
2027 }
2028
2029 int wxContourMainFrame::getWindowLevel()
2030 {
2031         /*
2032         double range[2];
2033         vtkImageData * img = getImageData();
2034         img->GetScalarRange(range);
2035
2036         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2037         
2038         return (int)range[1];
2039         */
2040         return _theViewPanel->getWindowLevel();
2041 }
2042
2043 void wxContourMainFrame::onBrigthnessColorWindowLevel(int colorwindow,int windowlevel){
2044         _theViewPanel->onBrigthnessColorWindowLevel(colorwindow, windowlevel);
2045
2046         RefreshInterface();
2047 }
2048
2049 void wxContourMainFrame::onInterpolation(bool interpolate){
2050         _theViewPanel->onInterpolation(interpolate);    
2051         RefreshInterface();
2052 }
2053
2054 void wxContourMainFrame::onChangeInstant(std::string name,int actual){
2055         _instantPanel->setConceptValue( name, actual );
2056 }
2057
2058 void wxContourMainFrame::resetAppend(){
2059         kernelManager->resetAppend();
2060         
2061 }
2062
2063 void wxContourMainFrame::onSpreadAdd(){
2064         std::vector<double> vecX; 
2065         std::vector<double> vecY; 
2066         std::vector<double> vecZ; 
2067         _theViewPanel->GetPointsOfActualContour(&vecX , &vecY , &vecZ );
2068         
2069         std::vector<int> tempVector;
2070         _instantPanel->getInstant( tempVector );
2071
2072         std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2073
2074         interfMainPanel::getInstance()->appendStringSpread(val);
2075         
2076 }
2077
2078 void wxContourMainFrame::onSpreadGo(int type){
2079
2080         //JCP 20-10-08 Undo redo implementation
2081         saveState();
2082         //JCP 20-10-08 Undo redo implementation
2083
2084         wxBusyCursor wait;      
2085         std::vector<double> vecCtrlPointX;
2086         std::vector<double> vecCtrlPointY;
2087         std::vector<double> vecCtrlPointZ;
2088         double  minZ,maxZ;
2089         int z;
2090
2091         std::vector<int> tempVector;
2092         _instantPanel->getInstant( tempVector );
2093 //              tempVector[1];
2094
2095         kernelManager->getMaxMinZ(&minZ,&maxZ);
2096 //JSTG_16-07-08_----------------------------------------------------------------
2097         //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
2098         kernelManager->CalculeSplinePropagation();
2099
2100         double          totalZ = maxZ-minZ+1;
2101         double          porcent;
2102         wxString        tmpString;
2103 //--------------------------------------------------------------------
2104         for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
2105         {
2106                 porcent = 100.0* (z-minZ)/totalZ;
2107                 int numero = (int)(z-minZ+1)/(int)totalZ;
2108                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2109                 
2110                 interfMainPanel::getInstance()->setStringSpread(stringtemp);    
2111
2112                 int typeofcontour = 1;
2113                 std::string theName;
2114                 manualContourModel* manModelContour = kernelManager->GetPoints(z, type, &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ, theName,typeofcontour, tempVector);
2115
2116                 if( manModelContour!=NULL ){
2117                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2118                         this->_theViewPanel->getSpacing(spc);                                   
2119                         //Adding the manualContourControler to interface objects structure
2120                         //Adding the manualViewContour to interface objects structure           
2121                         //_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.
2122                         _theViewPanel->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
2123                 } // if addedModel
2124         } 
2125         if(z > maxZ){
2126                 porcent = 100.0;
2127                 int numero = (int)(z-minZ+1)/(int)totalZ;
2128                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2129                 
2130                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2131         }// for z
2132         //RefreshInterface();
2133 }
2134
2135 void wxContourMainFrame::getInstantVector(std::vector<int>& tempVector){
2136         
2137 }
2138
2139 std::vector<std::string> wxContourMainFrame::getOutlinesName(int slide){
2140         std::vector<int> tempVector;
2141         _instantPanel->getInstant(tempVector);
2142         //Asignation of slide number should be different ex by name
2143         tempVector[1]=slide;
2144         return kernelManager->getOutlinesNameAtInstant(tempVector);
2145 }
2146
2147 void wxContourMainFrame::onInformationContourLabels(int typeContourGroup,int selection,int minimumZ,int maximumZ)
2148 {
2149         int maxContourGroup     =       0;
2150
2151         ContourExtractData      *contourextractdata = new ContourExtractData();
2152         
2153         contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2154
2155         std::vector<manualContourModel*> lstManConMod;
2156         std::vector<manualContourModel*> lstManConModTmp;
2157         std::vector<manualContourModel*> lstManConModExp;
2158         std::vector<double> pLstValue;
2159         std::vector<double> pLstValuePosX;
2160         std::vector<double> pLstValuePosY;
2161         std::vector<double> pLstValuePosZ;
2162
2163         int             resultSize; 
2164         int             resultGrayRangeCount;
2165         double  resultMin; 
2166         double  resultMax;
2167         double  resultAverage;
2168         double  resultStandardeviation;
2169
2170         std::vector<int> tempVector;
2171         _instantPanel->getInstant( tempVector );
2172
2173         vtkImageData *imagedata = _theViewPanel->getImageData();
2174         int sizeZ = _theViewPanel->GetImageDataSizeZ();
2175         int z;
2176         int ii,sizeLstContourThings;
2177
2178
2179         int minZ,maxZ;
2180         double totalZ;
2181         double porcent; 
2182         wxString tmpString;
2183
2184         
2185
2186         if (selection==0 ) // actual slice
2187         {
2188                 std::vector<int> tempVector;
2189                 _instantPanel->getInstant( tempVector );
2190                 int actualSlice = tempVector[1];
2191                 minZ    = actualSlice;
2192                 maxZ    = actualSlice;
2193         }
2194         else if (selection==2 ) // All slices
2195         {
2196                 minZ    = 0;
2197                 maxZ    = sizeZ-1;
2198         }
2199         else if (selection==1 ) // slice range
2200         {
2201                 minZ    = minimumZ;
2202                 maxZ    = maximumZ;
2203         }
2204         
2205
2206         totalZ  = maxZ-minZ+1;
2207         contourextractdata->SetImage( imagedata);
2208
2209 // For each slice..
2210         for ( z=minZ ; z<=maxZ ; z++ )
2211         {
2212                 
2213                 porcent = 100.0* (z-minZ)/totalZ;
2214                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2215
2216                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);          
2217                 //_staticTextInformation->SetLabel(tmpString);
2218
2219                 //Extraction data from contours of each slice
2220                 contourextractdata->SetZtoBeAnalys(z);
2221
2222                 tempVector[1]=z;
2223                 Instant instant(&tempVector);
2224                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2225                 sizeLstContourThings = lstContourThings.size();
2226
2227                 lstManConMod.clear();
2228                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2229                 {
2230                         ContourThing **contourthing = lstContourThings[ii];
2231                         lstManConMod.push_back( (*contourthing)->getModel() );
2232                 }
2233                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2234
2235
2236                 wxString tempString;
2237                 tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
2238                 interfMainPanel::getInstance()->setRowLabelInfoPanel(z, tempString);
2239                 //_grid->SetRowLabelValue(z, tempString );
2240 //EED004
2241                 int iContourGroup,sizeContourGroup;
2242                 if (typeContourGroup==3) // contour separete
2243                 {
2244                         sizeContourGroup=lstManConModExp.size();
2245                         if ( maxContourGroup<sizeContourGroup ) 
2246                         {
2247                                 maxContourGroup=sizeContourGroup;
2248                         }
2249                 } else {  // contour AND OR XOR
2250                         sizeContourGroup=1;
2251                         maxContourGroup=1;
2252                 }
2253
2254                 int tmpIntA;
2255
2256
2257
2258                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2259                         lstManConModTmp.clear();
2260                         if (typeContourGroup==3) // contour separete
2261                         {
2262                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2263                         } else {  // contour AND OR XOR
2264                                 lstManConModTmp = lstManConModExp;
2265                         }
2266
2267                         contourextractdata->SetLstManualContourModel( lstManConModTmp );
2268
2269                         pLstValue.clear();
2270                         pLstValuePosX.clear();
2271                         pLstValuePosY.clear();
2272                         pLstValuePosZ.clear();
2273                         contourextractdata->GetValuesInsideCrown(       &pLstValue,
2274                                                                                                                 &pLstValuePosX,
2275                                                                                                                 &pLstValuePosY,
2276                                                                                                                 &pLstValuePosZ);
2277                         // Statistics of each slice.
2278                         contourextractdata->Statistics( &pLstValue,
2279                                                                                         minimumZ,
2280                                                                                         maximumZ,
2281                                                                                         &resultGrayRangeCount, 
2282                                                                                         &resultSize, 
2283                                                                                         &resultMin, 
2284                                                                                         &resultMax,
2285                                                                                         &resultAverage,
2286                                                                                         &resultStandardeviation);
2287                         
2288                         if (interfMainPanel::getInstance()->getNumberColsInformationPanel()<_numberOfVariablesStatistics*(iContourGroup+1)  )
2289                         {
2290                                 interfMainPanel::getInstance()->appendColsInformationPanel(_numberOfVariablesStatistics);
2291                         }
2292
2293                         tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
2294
2295                         tempString.Printf(_T("%d"),resultSize);
2296                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA, tempString);  
2297
2298                         tempString.Printf(_T("%d"),resultGrayRangeCount);
2299                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+1, tempString);
2300                         
2301                         tempString.Printf(_T("%f"),resultMin);
2302                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+2, tempString);
2303                         
2304                         tempString.Printf(_T("%f"),resultMax);
2305                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+3, tempString);
2306                         
2307                         tempString.Printf(_T("%f"),resultAverage);
2308                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+4, tempString);
2309                         
2310                         tempString.Printf(_T("%f"),resultStandardeviation);
2311                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+5, tempString);
2312                         
2313
2314                 } // for iContourGroup
2315         } // for z
2316
2317         int iTitleGroup;
2318         wxString tmpTitleString;
2319         int tmpIntB;
2320         for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
2321         {
2322                 tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
2323                 tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
2324                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString);
2325
2326                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString );
2327                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 1, _T("Size Range") );
2328                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 2, _T("Min") );
2329                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 3, _T("Max") );
2330                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 4, _T("Average") );
2331                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 5, _T("St.Dev.") );
2332                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 6, _T(" ") );
2333         }
2334
2335         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2336         delete contourextractdata;
2337 }
2338
2339 //AD: 29-05-09
2340 void wxContourMainFrame::onSaveResults(std::string directory,std::string namefile, std::string filename, 
2341         int typeContourGroup, bool XYZValues, bool contourImage, bool statistics)
2342 {
2343         if (XYZValues)
2344         {
2345                 SaveValuesXYZ( directory , namefile, typeContourGroup );
2346         }
2347
2348         if (contourImage)
2349         {
2350                 vtkImageData * mask;
2351                 vtkImageData * value;
2352                 this->getMaskValue(&mask, &value, typeContourGroup);
2353                 this->SaveImageResult( directory , namefile, mask, value);
2354         }
2355         
2356         if (statistics)
2357         {
2358                 std::ostringstream name;
2359                 name << filename << ".xls";
2360                 
2361
2362                 FILE *pFile=fopen(name.str().c_str(),"w+");
2363
2364                 int sizeZ = _theViewPanel->GetImageDataSizeZ();
2365
2366                 wxString tmpString;
2367                 int i,j,maxX,maxY=sizeZ;
2368                 maxX= interfMainPanel::getInstance()->getNumberColsInformationPanel();//this->_grid->GetNumberCols();
2369
2370                 int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
2371                 for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
2372                 {
2373                                 // fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
2374                                 fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle );
2375                 }
2376                 fprintf(pFile,"\n" );
2377
2378
2379
2380                 for ( j=0; j<maxY ; j++)
2381                 {
2382                         fprintf(pFile,"%d\t" , j );
2383                         for (i=0 ; i<maxX ; i++){
2384                                 tmpString = interfMainPanel::getInstance()->getCellValue(j, i);//_grid->GetCellValue( j , i );
2385                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2386                         } // for i
2387                         fprintf(pFile,"\n"  );
2388                 } // for j
2389
2390                 fclose(pFile);
2391         }
2392 }
2393
2394 //AD: 29-05-09
2395 void wxContourMainFrame::SaveValuesXYZ(std::string directory,std::string namefile,int typeContourGroup)
2396 {
2397         wxBusyCursor wait;
2398         ContourExtractData      *contourextractdata = new ContourExtractData();
2399         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2400         contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2401
2402         std::vector<manualContourModel*> lstManConMod;
2403         std::vector<manualContourModel*> lstManConModTmp;
2404         std::vector<manualContourModel*> lstManConModExp;
2405         std::vector<double> pLstValue;
2406         std::vector<double> pLstValuePosX;
2407         std::vector<double> pLstValuePosY;
2408         std::vector<double> pLstValuePosZ;
2409
2410         std::vector<int> tempVector;
2411         _instantPanel->getInstant( tempVector );
2412
2413         vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
2414         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2415         int z;
2416         int ii,sizeLstContourThings;
2417
2418
2419         int minZ,maxZ;
2420         double totalZ;
2421         double porcent; 
2422         wxString tmpString;
2423         minZ    = 0;// _mbarrange->GetStart();
2424         maxZ    = sizeZ;//_mbarrange->GetEnd();
2425         totalZ  = maxZ-minZ+1;
2426
2427         contourextractdata->SetImage( imagedata);
2428
2429 // For each slice..
2430         for ( z=0 ; z<sizeZ ; z++)
2431         {
2432
2433                 porcent = 100.0* (z-minZ)/totalZ;
2434                 
2435                 tmpString.Printf(_T("Saving Values"));
2436                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2437                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2438                 //_staticTextInformation->SetLabel(tmpString);
2439
2440
2441                 //Extraction data from contours of each slice
2442                 contourextractdata->SetZtoBeAnalys( z);
2443
2444                 tempVector[1]=z;
2445                 Instant instant(&tempVector);
2446                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant(&instant);//this->_modelManager->getOutlinesAtInstant( &instant );
2447                 sizeLstContourThings = lstContourThings.size();
2448
2449                 lstManConMod.clear();
2450                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2451                 {
2452                         ContourThing **contourthing = lstContourThings[ii];
2453                         lstManConMod.push_back( (*contourthing)->getModel() );
2454                 }
2455                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2456
2457
2458 //EED004
2459
2460                 int iContourGroup,sizeContourGroup;
2461                 if (typeContourGroup==3) // contour separete
2462                 {
2463                         sizeContourGroup=lstManConModExp.size();
2464                 } else {  // contour AND OR XOR
2465                         sizeContourGroup=1;
2466                 }
2467
2468                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2469                         lstManConModTmp.clear();
2470                         if (typeContourGroup==3) // contour separete
2471                         {
2472                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2473                         } else {  // contour AND OR XOR
2474                                 lstManConModTmp = lstManConModExp;
2475                         }
2476
2477                         contourextractdata->SetLstManualContourModel( lstManConModTmp );
2478
2479                         pLstValue.clear();
2480                         pLstValuePosX.clear();
2481                         pLstValuePosY.clear();
2482                         pLstValuePosZ.clear();
2483                         contourextractdata->GetValuesInsideCrown(       &pLstValue,
2484                                                                                                                 &pLstValuePosX,
2485                                                                                                                 &pLstValuePosY,
2486                                                                                                                 &pLstValuePosZ);
2487
2488                         std::string temp = directory + "/" + namefile + "-slice";
2489                         temp = temp + kernelManager->intToString(z) + "-cont" + kernelManager->intToString(iContourGroup);
2490                         temp = temp + ".txt";
2491
2492                         // LG 14/01/09 : using crea
2493                         wxString filename = crea::std2wx(temp);
2494                         /*filename.Printf(_T("%s"),directory.c_str());
2495                         filename.append(_T("\\"));
2496                         filename.append(_T("%s"),namefile.c_str());
2497                         filename.append(_T("-slice"));
2498                         filename.append(_T("%d"),z);
2499                         filename.append(_T("-cont"));
2500                         filename.append(_T("%d"),iContourGroup);
2501                         filename.append(_T(".txt"));*/
2502                         //                      filename.Printf(temp.c_str());
2503
2504                         
2505
2506                         FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
2507                         fprintf(pFile,"value \t x \t y \t z\n"  );
2508                         int iLstValue,sizeLstValue=pLstValue.size();
2509                         for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
2510                         {
2511                                 fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
2512                         }
2513                         fclose(pFile);
2514                 } // for  iContourGroup
2515         } // for z
2516         interfMainPanel::getInstance()->setStringInfoPanel(_T(""));
2517         //_staticTextInformation->SetLabel( _T("") );
2518         delete contourextractdata;
2519 }
2520
2521 void wxContourMainFrame::getMaskValue(vtkImageData ** mask,vtkImageData ** value,int typeContourGroup){
2522         wxBusyCursor wait;
2523         ContourExtractData      *contourextractdata = new ContourExtractData( true );
2524         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2525         if (typeContourGroup==3)
2526         {
2527                 typeContourGroup=1;
2528         }
2529         contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2530
2531         std::vector<manualContourModel*> lstManConMod;
2532         std::vector<manualContourModel*> lstManConModTmp;
2533         std::vector<manualContourModel*> lstManConModExp;
2534
2535         std::vector<int> tempVector;
2536         _instantPanel->getInstant( tempVector );
2537
2538         vtkImageData *imagedata = _theViewPanel->getImageData();
2539         int sizeZ = _theViewPanel->GetImageDataSizeZ();
2540         int z;
2541         int ii,sizeLstContourThings;
2542
2543
2544         int minZ,maxZ;
2545         double totalZ;
2546         double porcent; 
2547
2548         wxString tmpString;
2549
2550         minZ    = 0;// _mbarrange->GetStart();
2551         maxZ    = sizeZ;//_mbarrange->GetEnd();
2552         totalZ  = maxZ-minZ+1;
2553
2554         contourextractdata->SetImage( imagedata);
2555
2556 // For each slice..
2557         for ( z=0 ; z<sizeZ ; z++)
2558         {
2559
2560                 porcent = 100.0* (z-minZ)/totalZ;
2561                 tmpString.Printf(_T("Saving Values"));
2562                 tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2563                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2564
2565                 //Extraction data from contours of each slice
2566                 contourextractdata->SetZtoBeAnalys( z);
2567
2568                 tempVector[1]=z;
2569                 Instant instant(&tempVector);
2570                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2571                 sizeLstContourThings = lstContourThings.size();
2572
2573                 lstManConMod.clear();
2574                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2575                 {
2576                         ContourThing **contourthing = lstContourThings[ii];
2577                         lstManConMod.push_back( (*contourthing)->getModel() );
2578                 }
2579                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2580
2581
2582                 int iContourGroup,sizeContourGroup;
2583                 if (typeContourGroup==3) // contour separete
2584                 {
2585                         sizeContourGroup=lstManConModExp.size();
2586                 } else {  // contour AND OR XOR
2587                         sizeContourGroup=1;
2588                 }
2589
2590                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2591                         lstManConModTmp.clear();
2592                         if (typeContourGroup==3) // contour separete
2593                         {
2594                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2595                         } else {  // contour AND OR XOR
2596                                 lstManConModTmp = lstManConModExp;
2597                         }
2598
2599                         contourextractdata->SetLstManualContourModel( lstManConModTmp );
2600                         contourextractdata->CalculateImageResult(); // with actual Z
2601
2602                 } // for  iContourGroup
2603         } // for z
2604
2605         (*value) = contourextractdata->GetVtkImageValueResult();
2606         (*mask) = contourextractdata->GetVtkImageMaskResult();
2607         delete contourextractdata;
2608 }
2609
2610 void wxContourMainFrame::SaveImageResult(std::string directory,std::string namefile, vtkImageData* mask,vtkImageData* value)
2611 {
2612         
2613         std::string temp = directory + "/" + namefile + "-Value.mhd";
2614
2615         wxString filename = crea::std2wx(temp);
2616         // LG 
2617         //      filename.Printf(_T(temp.c_str()));
2618         //filename.Printf(_T("%s\\%s-Value.mhd",directory.c_str(),namefile.c_str(),z);
2619         /*filename.Printf(_T("%s"),directory.c_str());
2620         filename.append(_T("\\"));
2621         filename.append(_T("%s"),namefile.c_str());
2622         filename.append(_T("-Value.mhd"));*/
2623
2624 // Image Value
2625         vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
2626         writerValueImage->SetInput( value );
2627         writerValueImage->SetFileName( (const char *)filename.mb_str() );
2628         writerValueImage->SetFileDimensionality( 3 );
2629         writerValueImage->Write( );
2630
2631 // Image Mask
2632         //              filename.Printf("%s\\%s-Mask.mhd",directory.c_str(),namefile.c_str(),z);
2633         temp = directory + "/" + namefile + "-Mask.mhd";
2634
2635         // LG 14/01/09 : using crea
2636         filename = crea::std2wx(temp);
2637         //      filename.Printf(_T(temp.c_str()));
2638
2639         /*filename.Printf(_T("%s"),directory.c_str());
2640         filename.append(_T("\\"));
2641         filename.append(_T("%s"),namefile.c_str());
2642         filename.append(_T("-Mask.mhd"));*/
2643
2644         vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
2645         writerMaskImage->SetInput( mask );
2646         writerMaskImage->SetFileName( (const char *)filename.mb_str() );
2647         writerMaskImage->SetFileDimensionality( 3 );
2648         writerMaskImage->Write( );
2649
2650         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2651         
2652 }
2653
2654
2655
2656 void wxContourMainFrame::onChangeInstantInstantPanel(std::string name,int value, int minshow, int maxshow){
2657         if( name.compare( _theViewPanel->getVerticalConceptName() ) == 0){
2658                 _theViewPanel->setActualVertical( value);
2659         }
2660         else if( name.compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( name, 0 ) )     {
2661                 _theViewPanel->setHorizontalConcept( name, minshow, maxshow, minshow, maxshow, value);
2662         }
2663
2664         changeInstant();
2665 }
2666
2667 void wxContourMainFrame::onSnakePressed(){
2668         std::vector<double> vecX; 
2669         std::vector<double> vecY; 
2670         std::vector<double> vecZ; 
2671         _theViewPanel->GetPointsOfActualContour( &vecX , &vecY , &vecZ );       
2672
2673         if (vecX.size()!=0){
2674                 std::vector<int> tempVector;
2675                 _instantPanel->getInstant( tempVector );
2676                 int i,size=vecZ.size();
2677                 int actualSlice = tempVector[1];
2678                 for ( i=0 ; i<size ; i++ )
2679                 {
2680                         vecZ[i] = actualSlice;
2681                 } // for
2682
2683                 wxDialog* dialog = new wxDialog(this, -1, wxString(_T("Snake")));
2684                 wxPanel* panel = new wxPanel(dialog,-1); 
2685                 //              wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2686          new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2687                 dialog->ShowModal();
2688         } // if 
2689
2690 }
2691
2692 void wxContourMainFrame::saveFileWithContoursAutomatique(){
2693         std::string filename = kernelManager->getCurrentFileName();
2694         if(filename.compare("")!=0){
2695                 saveFileWithContours(filename);
2696         }else{
2697                 onSave();
2698         }
2699 }
2700 void wxContourMainFrame::ShowToolsPanel(bool show){
2701         _pannew->Show(show);
2702 }
2703