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