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