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