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