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