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