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