]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
vtkGdcmReader takes into account the user supplied function to reorder the
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkGdcmReader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/07/30 18:31:25 $
7   Version:   $Revision: 1.74 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18                                                                                 
19 //-----------------------------------------------------------------------------
20 // //////////////////////////////////////////////////////////////
21 //
22 //===>  Many users expect from vtkGdcmReader it 'orders' the images
23 //     (that's the job of gdcm::SerieHelper ...)
24 //     When user *knows* the files with same Serie UID 
25 //        have same sizes, same 'pixel' type, same color convention, ...
26 //     the right way to proceed is as follow :
27 //
28 //      gdcm::SerieHelper *sh= new gdcm::SerieHelper();
29 //      // if user wants *not* to load some parts of the file headers
30 //      sh->SetLoadMode(loadMode);
31 //      // if user wants *not* to load some files 
32 //      sh->AddRestriction(group, element, value, operator);
33 //      sh->AddRestriction( ...
34 //      sh->SetDirectory(directoryWithImages);
35 //
36 //      // if user wants to sort reverse order
37 //      sh->SetSortOrderToReverse(); 
38 //      // here, we suppose only the first Coherent File List is of interest
39 //      gdcm::FileList *l = sh->GetFirstCoherentFileList();
40 //      // if user is doesn't trust too much the files with same Serie UID 
41 //      if ( !sh->IsCoherent(l) )
42 //         return; // not same sizes, same 'pixel' type -> stop
43 //      sh->OrderFileList(l);        // sort the list
44 //
45 //      vtkGdcmReader *reader = vtkGdcmReader::New();
46 //      // if user wants to modify pixel order (Mirror, TopDown, 90°Rotate, ...)
47 //      // he has to supply the function that does the job 
48 //      // (a *very* simple example is given in vtkgdcmSerieViewer.cxx)
49 //      reader->SetUserFunction (userSuppliedFunction);
50 //      // to pass a 'Coherent File List' as produced by gdcm::SerieHelper
51 //      reader->SetCoherentFileList(l); 
52 //      reader->Update();
53  
54 // WARNING TODO CLEANME 
55 // Actual limitations of this code 
56 //  when a Coherent File List from SerieHelper is not used (bad idea :-(
57 //
58 // /////// Redundant and unnecessary header parsing
59 // In it's current state this code actually parses three times the Dicom
60 // header of a file before the corresponding image gets loaded in the
61 // ad-hoc vtkData !
62 // Here is the process:
63 //  1/ First loading happens in ExecuteInformation which, in order to
64 //     positionate the vtk extents, calls CheckFileCoherence. The purpose
65 //     of CheckFileCoherence is to make sure all the images in the future
66 //     stack are "homogenous" (same size, same representation...).
67 //     This can only be achieved by parsing all the Dicom headers...
68 //     --> to avoid loosing too much time :
69 //     If user is 150% sure *all* the files are coherent, that is to say :
70 //     they may be open, they are gdcm-readable, they have the same sizes,
71 //     they have the same 'pixel' type, they are single frame, 
72 //     they have the same color convention ...
73 //     he may use SetCheckFileCoherenceLight() to request a 'light' coherence
74 //     checking
75 //  2/ ExecuteData is then responsible for the next two loadings - 2 ?!?-:
76 //  2a/ ExecuteData calls AllocateOutputData that in turn seems to 
77 //      (indirectely call) ExecuteInformation which ends up in a second
78 //      header parsing
79 //      This is fixed by adding a test at the beginning of ExecuteInformation
80 //      on the modification of the object instance. If a modification have been
81 //      made (method Modified() ), the MTime value is increased. The fileTime
82 //      is compared to this new value to find a modification in the class
83 //      parameters
84 //  2b/ the core of ExecuteData then needs gdcm::File (which in turns
85 //      initializes gdcm::File in the constructor) in order to access
86 //      the data-image.
87 //
88 // Possible solution:
89 // maintain a list of gdcm::Files (created by say ExecuteInformation) created
90 // once and for all accross the life of vtkGdcmFile (it would only load
91 // new gdcm::File if the user changes the list). ExecuteData would then use 
92 // those gdcm::File and hence avoid calling the constructor:
93 //  - advantage: the header of the files would only be parsed once.
94 //  - drawback: once execute information is called (i.e. on creation of
95 //              a vtkGdcmFile) the gdcm::File structure is loaded in memory.
96 //              The average size of a gdcm::File being of 100Ko, 
97 //              if oneloads 10 stacks of images with say 200 images each,
98 //              you end-up with a loss of 200Mo...
99 //
100 // /////// Never unallocated memory:
101 // ExecuteData allocates space for the pixel data [which will get pointed
102 // by the vtkPointData() through the call
103 // data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);]
104 // This data is never "freed" neither in the destructor nor when the
105 // filename list is extended, ExecuteData is called a second (or third)
106 // time...
107 //
108 //
109
110 // //////////////////////////////////////////////////////////////
111
112 #include "gdcmFileHelper.h"
113 #include "gdcmFile.h"
114 #include "gdcmDocument.h"  // for NO_SEQ
115
116 #include "vtkGdcmReader.h"
117 #include "gdcmDebug.h"
118
119 //#include <stdio.h>
120 #include <vtkObjectFactory.h>
121 #include <vtkImageData.h>
122 #include <vtkPointData.h>
123 #include <vtkLookupTable.h>
124
125 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.74 $");
126 vtkStandardNewMacro(vtkGdcmReader);
127
128 //-----------------------------------------------------------------------------
129 // Constructor / Destructor
130 vtkGdcmReader::vtkGdcmReader()
131 {
132    this->LookupTable = NULL;
133    this->AllowLookupTable = 0;
134    this->LightChecking = false;
135    this->LoadMode = 0; // Load everything (possible values : NO_SEQ, NO_SHADOW,
136                        //                                    NO_SHADOWSEQ)
137    this->CoherentFileList = 0;
138    this->UserFunction     = 0;
139 }
140
141 vtkGdcmReader::~vtkGdcmReader()
142 {
143    this->RemoveAllFileName();
144    this->InternalFileNameList.clear();
145    if(this->LookupTable) 
146       this->LookupTable->Delete();
147 }
148
149 //-----------------------------------------------------------------------------
150 // Print
151 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
152 {
153    this->Superclass::PrintSelf(os,indent);
154    os << indent << "Filenames  : " << endl;
155    vtkIndent nextIndent = indent.GetNextIndent();
156    for (std::list<std::string>::iterator it = FileNameList.begin();
157         it != FileNameList.end();
158         ++it)
159    {
160       os << nextIndent << it->c_str() << endl ;
161    }
162 }
163
164 //-----------------------------------------------------------------------------
165 // Public
166 /*
167  * Remove all files from the list of images to read.
168  */
169 void vtkGdcmReader::RemoveAllFileName(void)
170 {
171    this->FileNameList.clear();
172    this->Modified();
173 }
174
175 /*
176  * Adds a file name to the list of images to read.
177  */
178 void vtkGdcmReader::AddFileName(const char* name)
179 {
180    // We need to bypass the const pointer [since list<>.push_bash() only
181    // takes a char* (but not a const char*)] by making a local copy:
182    char *LocalName = new char[strlen(name) + 1];
183    strcpy(LocalName, name);
184    this->FileNameList.push_back(LocalName);
185    delete[] LocalName;
186    this->Modified();
187 }
188
189 /*
190  * Sets up a filename to be read.
191  */
192 void vtkGdcmReader::SetFileName(const char *name) 
193 {
194    vtkImageReader2::SetFileName(name);
195    // Since we maintain a list of filenames, when building a volume,
196    // (see vtkGdcmReader::AddFileName), we additionaly need to purge
197    // this list when we manually positionate the filename.
198    vtkDebugMacro(<< "Clearing all files given with AddFileName");
199    this->FileNameList.clear();
200    this->Modified();
201 }
202
203 /*
204  * Ask for a 'light' checking -actually : just initializing-
205  *if you are 150% sure *all* the files are coherent
206  */
207 void vtkGdcmReader::SetCheckFileCoherenceLight()
208 {
209    LightChecking = true;
210 }
211
212 //-----------------------------------------------------------------------------
213 // Protected
214 /*
215  * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
216  */
217 void vtkGdcmReader::ExecuteInformation()
218 {
219    if(this->MTime>this->fileTime)
220    {
221       if ( this->CoherentFileList != 0 )
222          this->TotalNumberOfPlanes = this->CheckFileCoherenceAlreadyDone();  
223       else if ( this->LightChecking )
224          this->TotalNumberOfPlanes = this->CheckFileCoherenceLight();
225       else
226           this->TotalNumberOfPlanes = this->CheckFileCoherence();
227
228       if ( this->TotalNumberOfPlanes == 0)
229       {
230          vtkErrorMacro(<< "File set is not coherent. Exiting...");
231          return;
232       }
233       
234       // if the user has not set the extent, but has set the VOI
235       // set the z axis extent to the VOI z axis
236       if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
237       (this->DataVOI[4] || this->DataVOI[5]))
238       {
239          this->DataExtent[4] = this->DataVOI[4];
240          this->DataExtent[5] = this->DataVOI[5];
241       }
242
243       // When the user has set the VOI, check it's coherence with the file content.
244       if (this->DataVOI[0] || this->DataVOI[1] || 
245       this->DataVOI[2] || this->DataVOI[3] ||
246       this->DataVOI[4] || this->DataVOI[5])
247       { 
248          if ((this->DataVOI[0] < 0) ||
249              (this->DataVOI[1] >= this->NumColumns) ||
250              (this->DataVOI[2] < 0) ||
251              (this->DataVOI[3] >= this->NumLines) ||
252              (this->DataVOI[4] < 0) ||
253              (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
254          {
255             vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
256             this->DataVOI[0] = 0;
257             this->DataVOI[1] = this->NumColumns - 1;
258             this->DataVOI[2] = 0;
259             this->DataVOI[3] = this->NumLines - 1;
260             this->DataVOI[4] = 0;
261             this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
262          }
263       }
264
265       // Set the Extents.
266       this->DataExtent[0] = 0;
267       this->DataExtent[1] = this->NumColumns - 1;
268       this->DataExtent[2] = 0;
269       this->DataExtent[3] = this->NumLines - 1;
270       this->DataExtent[4] = 0;
271       this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
272   
273       // We don't need to set the Endian related stuff (by using
274       // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
275       // since the reading of the file is done by gdcm.
276       // But we do need to set up the data type for downstream filters:
277       if      ( ImageType == "8U" )
278       {
279          vtkDebugMacro(<< "8 bits unsigned image");
280          this->SetDataScalarTypeToUnsignedChar(); 
281       }
282       else if ( ImageType == "8S" )
283       {
284          vtkErrorMacro(<< "Cannot handle 8 bit signed files");
285          return;
286       }
287       else if ( ImageType == "16U" )
288       {
289          vtkDebugMacro(<< "16 bits unsigned image");
290          this->SetDataScalarTypeToUnsignedShort();
291       }
292       else if ( ImageType == "16S" )
293       {
294          vtkDebugMacro(<< "16 bits signed image");
295          this->SetDataScalarTypeToShort();
296       }
297       else if ( ImageType == "32U" )
298       {
299          vtkDebugMacro(<< "32 bits unsigned image");
300          vtkDebugMacro(<< "WARNING: forced to signed int !");
301          this->SetDataScalarTypeToInt();
302       }
303       else if ( ImageType == "32S" )
304       {
305          vtkDebugMacro(<< "32 bits signed image");
306          this->SetDataScalarTypeToInt();
307       }
308       else if ( ImageType == "FD" )
309       {
310          vtkDebugMacro(<< "64 bits Double image");
311          this->SetDataScalarTypeToDouble();
312       }
313       //Set number of scalar components:
314       this->SetNumberOfScalarComponents(this->NumComponents);
315
316       this->fileTime=this->MTime;
317    }
318
319    this->Superclass::ExecuteInformation();
320 }
321  
322 /*
323  * Update => ouput->Update => UpdateData => Execute => ExecuteData 
324  * (see vtkSource.cxx for last step).
325  * This function (redefinition of vtkImageReader::ExecuteData, see 
326  * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
327  * extent/axes are assumed to be the same as the file extent/order.
328  */
329 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
330 {
331    if ( CoherentFileList != 0 )   // When a list of names is passed
332    {
333       if (this->CoherentFileList->empty())
334       {
335          vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
336          return;
337       }
338    }
339    else if (this->InternalFileNameList.empty())
340    {
341       vtkErrorMacro(<< "A least a valid FileName must be specified.");
342       return;
343    }
344
345    // FIXME : extraneous parsing of header is made when allocating OuputData
346    //         --> ?!?
347    vtkImageData *data = this->AllocateOutputData(output);
348    data->SetExtent(this->DataExtent);
349    data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
350
351    // Test if output has valid extent
352    // Prevent memory errors
353    if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
354       (this->DataExtent[3]-this->DataExtent[2]>=0) &&
355       (this->DataExtent[5]-this->DataExtent[4]>=0))
356    {
357       // The memory size for a full stack of images of course depends
358       // on the number of planes and the size of each image:
359       //size_t StackNumPixels = this->NumColumns * this->NumLines
360       //                      * this->TotalNumberOfPlanes * this->NumComponents;
361       //size_t stack_size = StackNumPixels * this->PixelSize; //not used
362       // Allocate pixel data space itself.
363
364       // Variables for the UpdateProgress. We shall use 50 steps to signify
365       // the advance of the process:
366       unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
367                                          * this->TotalNumberOfPlanes
368                                          / 50.0);
369       // The actual advance measure:
370       unsigned long UpdateProgressCount = 0;
371
372       // Filling the allocated memory space with each image/volume:
373
374       unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
375
376       if ( CoherentFileList == 0 )   // When a list of names is passed
377       {         
378          for (std::list<std::string>::iterator filename  = InternalFileNameList.begin();
379               filename != InternalFileNameList.end();
380               ++filename)
381          { 
382             // Images that were tagged as unreadable in CheckFileCoherence()
383             // are substituted with a black image to let the caller visually
384             // notice something wrong is going on:
385             if (*filename != "GDCM_UNREADABLE")
386             {
387                // Update progress related for good files is made in LoadImageInMemory
388                Dest += this->LoadImageInMemory(*filename, Dest,
389                                                UpdateProgressTarget,
390                                                UpdateProgressCount);
391             } 
392             else 
393             {
394                // We insert a black image in the stack for the user to be aware that
395                // this image/volume couldn't be loaded. We simply skip one image
396                // size:
397                Dest += this->NumColumns * this->NumLines * this->PixelSize;
398
399                // Update progress related for bad files:
400                UpdateProgressCount += this->NumLines;
401                if (UpdateProgressTarget > 0)
402                {
403                   if (!(UpdateProgressCount%UpdateProgressTarget))
404                   {
405                      this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
406                   }
407                }
408             } // Else, file not loadable
409          } // Loop on files
410
411       }
412       else  // when a Coherent File List is passed
413       {
414          for (std::vector<gdcm::File* >::iterator it =  CoherentFileList->begin();
415                                                   it != CoherentFileList->end();
416                                                 ++it)
417          {
418      
419             //std::cout <<"----------------- " << (*it)->GetFileName() << std::endl;
420
421              Dest += this->LoadImageInMemory(*it, Dest,
422                                              UpdateProgressTarget,
423                                              UpdateProgressCount); 
424              // Update progress related for bad files:
425              UpdateProgressCount += this->NumLines;
426              if (UpdateProgressTarget > 0)
427              {
428                 if (!(UpdateProgressCount%UpdateProgressTarget))
429                 {
430                    this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
431                 }
432               }
433            } // Loop on files 
434
435       } 
436    }
437 }
438
439 /*
440  * vtkGdcmReader can have the file names specified through two ways:
441  * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
442  *     SetFilePattern()
443  * (2) By successive calls to vtkGdcmReader::AddFileName()
444  * When the first method was used by caller we need to update the local
445  * filename list
446  */
447 void vtkGdcmReader::BuildFileListFromPattern()
448 {
449    this->RemoveAllInternalFileName();
450
451    if ((! this->FileNameList.empty()) && this->FileName )
452    {
453       vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
454       vtkErrorMacro(<< "No images loaded ! ");
455       return;
456    }
457
458    if ((! this->FileNameList.empty()) && this->FilePrefix )
459    {
460       vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
461       vtkErrorMacro(<< "No images loaded ! ");
462       return;
463    }
464
465    if (this->FileName && this->FilePrefix)
466    {
467       vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
468       vtkErrorMacro(<< "No images loaded ! ");
469       return;
470    }
471
472    if (! this->FileNameList.empty()  )
473    {
474       vtkDebugMacro(<< "Using the AddFileName specified files");
475       this->InternalFileNameList=this->FileNameList;
476       return;
477    }
478
479    if (!this->FileName && !this->FilePrefix)
480    {
481       vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
482       vtkErrorMacro(<< "specify a FileName or FilePrefix.");
483       return;
484    }
485
486    if( this->FileName )
487    {
488       // Single file loading (as given with ::SetFileName()):
489       // Case of multi-frame file considered here
490       this->ComputeInternalFileName(this->DataExtent[4]);
491       vtkDebugMacro(<< "Adding file " << this->InternalFileName);
492       this->AddInternalFileName(this->InternalFileName);
493    }
494    else
495    {
496       // Multi file loading (as given with ::SetFilePattern()):
497       for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
498       {
499          this->ComputeInternalFileName(idx);
500          vtkDebugMacro(<< "Adding file " << this->InternalFileName);
501          this->AddInternalFileName(this->InternalFileName);
502       }
503    }
504 }
505
506 /*
507  * When more than one filename is specified (i.e. we expect loading
508  * a stack or volume) we need to check that the corresponding images/volumes
509  * to be loaded are coherent i.e. to make sure:
510  *     - they all share the same X dimensions
511  *     - they all share the same Y dimensions
512  *     - they all share the same ImageType ( 8 bit signed, or unsigned...)
513  *
514  * Eventually, we emit a warning when all the files do NOT share the
515  * Z dimension, since we can still build a stack but the
516  * files are not coherent in Z, which is probably a source a trouble...
517  *   When files are not readable (either the file cannot be opened or
518  * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
519  *   This method returns the total number of planar images to be loaded
520  * (i.e. an image represents one plane, but a volume represents many planes)
521  */
522 int vtkGdcmReader::CheckFileCoherence()
523 {
524    int ReturnedTotalNumberOfPlanes = 0;   // The returned value.
525
526    this->BuildFileListFromPattern();
527    if (this->InternalFileNameList.empty())
528    {
529       vtkErrorMacro(<< "FileNames are not set.");
530       return 0;
531    }
532
533    bool FoundReferenceFile = false;
534    int  ReferenceNZ = 0;
535
536    // Loop on the filenames:
537    // - check for their existence and gdcm "parsability"
538    // - get the coherence check done:
539    for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
540         filename != InternalFileNameList.end();
541         ++filename)
542    {
543       // The file is always added in the number of planes
544       //  - If file doesn't exist, it will be replaced by a black plane in the 
545       //    ExecuteData method
546       //  - If file has more than 1 plane, other planes will be added later to
547       //    to the ReturnedTotalNumberOfPlanes variable counter
548       ReturnedTotalNumberOfPlanes += 1;
549
550       /////// Stage 0: check for file name:
551
552       // fixme : how can the filename be equal to "GDCM_UNREADABLE"
553       //         right now ?!?
554
555       if(*filename == std::string("GDCM_UNREADABLE"))
556          continue;
557
558       /////// Stage 1: check for file readability:
559       // Stage 1.1: check for file existence.
560       FILE *fp;
561       fp = fopen(filename->c_str(),"rb");
562       if (!fp)
563       {
564          vtkErrorMacro(<< "Unable to open file " << filename->c_str());
565          vtkErrorMacro(<< "Removing this file from read files: "
566                        << filename->c_str());
567          *filename = "GDCM_UNREADABLE";
568          continue;
569       }
570       fclose(fp);
571
572       // Stage 1.2: check for Gdcm parsability
573
574       // to save some parsing time.
575       gdcm::File GdcmFile;
576       GdcmFile.SetLoadMode( LoadMode );
577       GdcmFile.SetFileName(filename->c_str() );
578       GdcmFile.Load( );
579       if (!GdcmFile.IsReadable())
580       {
581          vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
582          vtkErrorMacro(<< "Removing this file from read files: "
583                         << filename->c_str());
584          *filename = "GDCM_UNREADABLE";
585          continue;
586       }
587
588       // Stage 1.3: further gdcm compatibility on PixelType
589       std::string type = GdcmFile.GetPixelType();
590       if (   (type !=  "8U") && (type !=  "8S")
591           && (type != "16U") && (type != "16S")
592           && (type != "32U") && (type != "32S") )
593       {
594          vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
595                        << "   File type found : " << type.c_str() 
596                        << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
597                        << "   Removing this file from read files");
598          *filename = "GDCM_UNREADABLE";
599          continue;
600       }
601
602       // Stage 2: check coherence of the set of files
603       int NX = GdcmFile.GetXSize();
604       int NY = GdcmFile.GetYSize();
605       int NZ = GdcmFile.GetZSize();
606       if (FoundReferenceFile) 
607       {
608          // Stage 2.1: mandatory coherence stage:
609          if (   ( NX   != this->NumColumns )
610              || ( NY   != this->NumLines )
611              || ( type != this->ImageType ) ) 
612          {
613             vtkErrorMacro(<< "This file is not coherent with previous ones: "
614                           << filename->c_str());
615             vtkErrorMacro(<< "Removing this file from read files: "
616                           << filename->c_str());
617             *filename = "GDCM_UNREADABLE";
618             continue;
619          }
620
621          // Stage 2.2: optional coherence stage
622          if ( NZ != ReferenceNZ )
623          {
624             vtkErrorMacro(<< "File is not coherent in Z with previous ones: "
625                           << filename->c_str());
626          }
627          else
628          {
629             vtkDebugMacro(<< "File is coherent with previous ones: "
630                           << filename->c_str());
631          }
632
633          // Stage 2.3: when the file is 'multiframe', notify the caller.
634          if (NZ > 1)
635          {
636             vtkErrorMacro(<< "This file is a 'Multiframe' one: "
637                           << filename->c_str());
638          }
639
640          // Eventually, this file can be added on the stack. Update the
641          // full size of the stack
642          vtkDebugMacro("Number of planes added to the stack: " << NZ);
643          ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
644          continue;
645
646       } 
647       else 
648       {
649          // We didn't have a workable reference file yet. 
650          // Set this one as the reference.
651          FoundReferenceFile = true;
652          vtkDebugMacro(<< "This file taken as coherence reference:"
653                        << filename->c_str());
654          vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
655                        << NX << " " << NY << " " << NZ);
656          vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
657          // Set aside the size of the image
658          this->NumColumns = NX;
659          this->NumLines   = NY;
660          ReferenceNZ      = NZ;
661          ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
662          this->ImageType = type;
663          this->PixelSize = GdcmFile.GetPixelSize();
664
665          if( GdcmFile.HasLUT() && this->AllowLookupTable )
666          {
667             // I could raise an error is AllowLookupTable is on and HasLUT() off
668             this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
669          }
670          else
671          {
672             this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
673          }             
674          //Set image spacing
675          this->DataSpacing[0] = GdcmFile.GetXSpacing();
676          this->DataSpacing[1] = GdcmFile.GetYSpacing();
677          this->DataSpacing[2] = GdcmFile.GetZSpacing();
678       }
679    } // End of loop on filename
680
681    ///////// The files we CANNOT load are flaged. On debugging purposes
682    // count the loadable number of files and display their number:
683    int NumberCoherentFiles = 0;
684    for (std::list<std::string>::iterator it = InternalFileNameList.begin();
685         it != InternalFileNameList.end();
686         ++it)
687    {
688       if (*it != "GDCM_UNREADABLE")
689       {
690          NumberCoherentFiles++;
691       }
692    }
693    vtkDebugMacro(<< "Number of coherent files: " << NumberCoherentFiles);
694
695    if (ReturnedTotalNumberOfPlanes == 0)
696    {
697       vtkErrorMacro(<< "No loadable file.");
698    }
699
700    vtkDebugMacro(<< "Total number of planes on the stack: "
701                   << ReturnedTotalNumberOfPlanes);
702    
703    return ReturnedTotalNumberOfPlanes;
704 }
705
706 //-----------------------------------------------------------------------------
707 // Private
708 /*
709  * Remove all file names to the internal list of images to read.
710  */
711 void vtkGdcmReader::RemoveAllInternalFileName(void)
712 {
713    this->InternalFileNameList.clear();
714 }
715
716 /*
717  * Adds a file name to the internal list of images to read.
718  */
719 void vtkGdcmReader::AddInternalFileName(const char *name)
720 {
721    char *LocalName = new char[strlen(name) + 1];
722    strcpy(LocalName, name);
723    this->InternalFileNameList.push_back(LocalName);
724    delete[] LocalName;
725 }
726
727 /*
728  * Loads the contents of the image/volume contained by gdcm::File* f at
729  * the Dest memory address. Returns the size of the data loaded.
730  */
731 size_t vtkGdcmReader::LoadImageInMemory(
732              gdcm::File *f, 
733              unsigned char *dest,
734              const unsigned long updateProgressTarget,
735              unsigned long &updateProgressCount)
736 {
737   // vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName() << "]");
738
739    return DoTheLoadingJob (f,
740                            dest,
741                            updateProgressTarget,
742                            updateProgressCount);
743 }
744
745 /*
746  * Loads the contents of the image/volume contained by char *fileName at
747  * the dest memory address. Returns the size of the data loaded.
748  */
749 size_t vtkGdcmReader::LoadImageInMemory(
750              std::string fileName, 
751              unsigned char *dest,
752              const unsigned long updateProgressTarget,
753              unsigned long &updateProgressCount)
754 {
755    vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
756
757    gdcm::File *f;
758    f = new gdcm::File();
759    f->SetLoadMode( LoadMode );
760    f->SetFileName( fileName.c_str() );
761    f->Load( );
762
763    return DoTheLoadingJob (f,
764                            dest,
765                            updateProgressTarget,
766                            updateProgressCount);
767    delete f;
768 }
769
770 /*
771  *  Service method for LoadImageInMemory
772 */
773 size_t vtkGdcmReader::DoTheLoadingJob (gdcm::File *f,
774                                        unsigned char *dest,
775                                        const unsigned long updateProgressTarget,
776                                        unsigned long &updateProgressCount)
777 {
778    gdcm::FileHelper *fileH = new gdcm::FileHelper( f );
779    fileH->SetUserFunction( UserFunction );
780
781    size_t size;
782
783    // If the data structure of vtk for image/volume representation
784    // were straigthforwards the following would be enough:
785    //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
786    // But vtk chooses to invert the lines of an image, that is the last
787    // line comes first (for some axis related reasons?). Hence we need
788    // to load the image line by line, starting from the end.
789
790    int numColumns = fileH->GetFile()->GetXSize();
791    int numLines   = fileH->GetFile()->GetYSize();
792    int numPlanes  = fileH->GetFile()->GetZSize();
793    int lineSize   = NumComponents * numColumns * fileH->GetFile()->GetPixelSize();
794    int planeSize  = lineSize * numLines;
795
796    unsigned char *src;
797    
798    if( fileH->GetFile()->HasLUT() && AllowLookupTable )
799    {
800       size               = fileH->GetImageDataSize();
801       src                = (unsigned char*) fileH->GetImageDataRaw();
802       unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
803
804       if(!this->LookupTable)
805       {
806          this->LookupTable = vtkLookupTable::New();
807       }
808
809       this->LookupTable->SetNumberOfTableValues(256);
810       for (int tmp=0; tmp<256; tmp++)
811       {
812          this->LookupTable->SetTableValue(tmp,
813          (float)lut[4*tmp+0]/255.0,
814          (float)lut[4*tmp+1]/255.0,
815          (float)lut[4*tmp+2]/255.0,
816          1);
817       }
818       this->LookupTable->SetRange(0,255);
819       vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
820       a->GetScalars()->SetLookupTable(this->LookupTable);
821       free(lut);
822    }
823    else
824    {
825       size = fileH->GetImageDataSize();
826       src  = (unsigned char*)fileH->GetImageData();
827    } 
828
829    unsigned char *dst = dest + planeSize - lineSize;
830    for (int plane = 0; plane < numPlanes; plane++)
831    {
832       for (int line = 0; line < numLines; line++)
833       {
834          // Copy one line at proper destination:
835          memcpy((void*)dst, (void*)src, lineSize);
836          src += lineSize;
837          dst -= lineSize;
838          // Update progress related:
839          if (!(updateProgressCount%updateProgressTarget))
840          {
841             this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
842          }
843          updateProgressCount++;
844       }
845       dst += 2 * planeSize;
846    }
847    delete fileH;   
848    return size;
849 }
850
851 // -------------------------------------------------------------------------
852
853 // We assume the use *does* know all the files whose names 
854 //  are in InternalFileNameList exist, may be open, are gdcm-readable
855 //  have the same sizes, have the same 'pixel' type, are single frame
856 //  have the same color convention, ..., anything else ? 
857
858 int vtkGdcmReader::CheckFileCoherenceLight()
859 {
860    std::list<std::string>::iterator filename = InternalFileNameList.begin();
861
862    gdcm::File GdcmFile;
863    GdcmFile.SetLoadMode( LoadMode );
864    GdcmFile.SetFileName(filename->c_str() );   
865    GdcmFile.Load( );
866
867    if (!GdcmFile.IsReadable())
868    {
869       vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
870       vtkErrorMacro(<< "you should try vtkGdcmReader::CheckFileCoherence "
871                     << "instead of vtkGdcmReader::CheckFileCoherenceLight");
872       return 0;
873    }
874    int NX           = GdcmFile.GetXSize();
875    int NY           = GdcmFile.GetYSize();
876    // CheckFileCoherenceLight should be called *only* when user knows
877    // he deals with single frames files.
878    // Z size is then the number of files.
879    int NZ           = InternalFileNameList.size();
880    std::string type = GdcmFile.GetPixelType();
881    vtkDebugMacro(<< "The first file is taken as reference: "
882                  << filename->c_str());
883    vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
884                  << NX << " " << NY << " " << NZ);
885    vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
886    // Set aside the size of the image
887    this->NumColumns = NX;
888    this->NumLines   = NY;
889    this->ImageType  = type;
890    this->PixelSize  = GdcmFile.GetPixelSize();
891
892    if( GdcmFile.HasLUT() && this->AllowLookupTable )
893    {
894       // I could raise an error is AllowLookupTable is on and HasLUT() off
895       this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
896    }
897    else
898    {
899       this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
900    }
901        
902    //Set image spacing
903    this->DataSpacing[0] = GdcmFile.GetXSpacing();
904    this->DataSpacing[1] = GdcmFile.GetYSpacing();
905    this->DataSpacing[2] = GdcmFile.GetZSpacing();
906
907    return InternalFileNameList.size();
908 }
909
910 // We assume the use *does* know all the files whose names 
911 //  are in InternalFileNameList exist, may be open, are gdcm-readable
912 //  have the same sizes, have the same 'pixel' type, are single frame
913 //  have the same color convention, ..., anything else ? 
914
915 int vtkGdcmReader::CheckFileCoherenceAlreadyDone()
916 {
917    if ( CoherentFileList->empty() )
918    {
919       vtkErrorMacro(<< "Coherent File List is empty ");
920       return 0;
921    }
922
923    gdcm::File *gdcmFile = (*CoherentFileList)[0];
924
925    int NX           = gdcmFile->GetXSize();
926    int NY           = gdcmFile->GetYSize();
927    // CheckFileCoherenceLight should be called *only* when user knows
928    // he deals with single frames files.
929    // Z size is then the number of files.
930    // --> TODO : loop on the File* to get NZ of each one !
931    int NZ           = CoherentFileList->size();
932    std::string type = gdcmFile->GetPixelType();
933    //vtkDebugMacro(<< "The first file is taken as reference: "
934    //              << (*CoherentFileList)[0]->GetFileName() );
935    vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
936                  << NX << " " << NY << " " << NZ);
937    vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
938    // Set aside the size of the image
939    this->NumColumns = NX;
940    this->NumLines   = NY;
941    this->ImageType  = type;
942    this->PixelSize  = gdcmFile->GetPixelSize();
943
944    if( gdcmFile->HasLUT() && this->AllowLookupTable )
945    {
946       // I could raise an error is AllowLookupTable is on and HasLUT() off
947       this->NumComponents = gdcmFile->GetNumberOfScalarComponentsRaw();
948    }
949    else
950    {
951       this->NumComponents = gdcmFile->GetNumberOfScalarComponents(); //rgb or mono
952    }
953        
954    //Set image spacing
955    this->DataSpacing[0] = gdcmFile->GetXSpacing();
956    this->DataSpacing[1] = gdcmFile->GetYSpacing();
957    this->DataSpacing[2] = gdcmFile->GetZSpacing();
958
959    return NZ;
960 }
961 //-----------------------------------------------------------------------------