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