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