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