diff --git a/examples/osgvolume/osgvolume.cpp b/examples/osgvolume/osgvolume.cpp index 8dc2cd7b1..e2dc85202 100644 --- a/examples/osgvolume/osgvolume.cpp +++ b/examples/osgvolume/osgvolume.cpp @@ -91,8 +91,8 @@ struct ProcessRow virtual ~ProcessRow() {} virtual void operator() (unsigned int num, - GLenum source_pixelFormat, unsigned char* source, - GLenum dest_pixelFormat, unsigned char* dest) const + GLenum source_pixelFormat, unsigned char* source, + GLenum dest_pixelFormat, unsigned char* dest) const { switch(source_pixelFormat) { @@ -100,7 +100,7 @@ struct ProcessRow case(GL_ALPHA): switch(dest_pixelFormat) { - case(GL_LUMINANCE): + case(GL_LUMINANCE): case(GL_ALPHA): A_to_A(num, source, dest); break; case(GL_LUMINANCE_ALPHA): A_to_LA(num, source, dest); break; case(GL_RGB): A_to_RGB(num, source, dest); break; @@ -110,7 +110,7 @@ struct ProcessRow case(GL_LUMINANCE_ALPHA): switch(dest_pixelFormat) { - case(GL_LUMINANCE): + case(GL_LUMINANCE): case(GL_ALPHA): LA_to_A(num, source, dest); break; case(GL_LUMINANCE_ALPHA): LA_to_LA(num, source, dest); break; case(GL_RGB): LA_to_RGB(num, source, dest); break; @@ -120,7 +120,7 @@ struct ProcessRow case(GL_RGB): switch(dest_pixelFormat) { - case(GL_LUMINANCE): + case(GL_LUMINANCE): case(GL_ALPHA): RGB_to_A(num, source, dest); break; case(GL_LUMINANCE_ALPHA): RGB_to_LA(num, source, dest); break; case(GL_RGB): RGB_to_RGB(num, source, dest); break; @@ -130,7 +130,7 @@ struct ProcessRow case(GL_RGBA): switch(dest_pixelFormat) { - case(GL_LUMINANCE): + case(GL_LUMINANCE): case(GL_ALPHA): RGBA_to_A(num, source, dest); break; case(GL_LUMINANCE_ALPHA): RGBA_to_LA(num, source, dest); break; case(GL_RGB): RGBA_to_RGB(num, source, dest); break; @@ -141,7 +141,7 @@ struct ProcessRow } /////////////////////////////////////////////////////////////////////////////// - // alpha sources.. + // alpha sources.. virtual void A_to_A(unsigned int num, unsigned char* source, unsigned char* dest) const { for(unsigned int i=0;iget(); GLenum pixelFormat = image->getPixelFormat(); - if (pixelFormat==GL_ALPHA || - pixelFormat==GL_INTENSITY || - pixelFormat==GL_LUMINANCE || - pixelFormat==GL_LUMINANCE_ALPHA || - pixelFormat==GL_RGB || + if (pixelFormat==GL_ALPHA || + pixelFormat==GL_INTENSITY || + pixelFormat==GL_LUMINANCE || + pixelFormat==GL_LUMINANCE_ALPHA || + pixelFormat==GL_RGB || pixelFormat==GL_RGBA) { max_s = osg::maximum(image->s(), max_s); @@ -365,9 +365,9 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow, osg::notify(osg::NOTICE)<<"Image "<getFileName()<<" has unsuitable pixel format"<< std::hex<< pixelFormat << std::dec << std::endl; } } - + if (numComponentsDesired!=0) max_components = numComponentsDesired; - + GLenum desiredPixelFormat = 0; switch(max_components) { @@ -387,11 +387,11 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow, osg::notify(osg::NOTICE)<<"desiredPixelFormat = GL_RGBA" << std::endl; desiredPixelFormat = GL_RGBA; break; - } + } if (desiredPixelFormat==0) return 0; - + // compute nearest powers of two for each axis. - + int s_nearestPowerOfTwo = 1; int t_nearestPowerOfTwo = 1; int r_nearestPowerOfTwo = 1; @@ -412,12 +412,12 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow, t_nearestPowerOfTwo = max_t; r_nearestPowerOfTwo = total_r; } - + // now allocate the 3d texture; osg::ref_ptr image_3d = new osg::Image; image_3d->allocateImage(s_nearestPowerOfTwo,t_nearestPowerOfTwo,r_nearestPowerOfTwo, desiredPixelFormat,GL_UNSIGNED_BYTE); - + unsigned int r_offset = (total_rget(); GLenum pixelFormat = image->getPixelFormat(); - if (pixelFormat==GL_ALPHA || - pixelFormat==GL_LUMINANCE || - pixelFormat==GL_INTENSITY || - pixelFormat==GL_LUMINANCE_ALPHA || - pixelFormat==GL_RGB || + if (pixelFormat==GL_ALPHA || + pixelFormat==GL_LUMINANCE || + pixelFormat==GL_INTENSITY || + pixelFormat==GL_LUMINANCE_ALPHA || + pixelFormat==GL_RGB || pixelFormat==GL_RGBA) { - + int num_r = osg::minimum(image->r(), (image_3d->r() - curr_dest_r)); int num_t = osg::minimum(image->t(), image_3d->t()); int num_s = osg::minimum(image->s(), image_3d->s()); - + unsigned int s_offset_dest = (image->s()s()/2 : 0; unsigned int t_offset_dest = (image->t()t()/2 : 0; @@ -456,7 +456,7 @@ osg::Image* createTexture3D(ImageList& imageList, ProcessRow& processRow, } } } - } + } return image_3d.release(); } @@ -466,14 +466,14 @@ struct ScaleOperator ScaleOperator():_scale(1.0f) {} ScaleOperator(float scale):_scale(scale) {} ScaleOperator(const ScaleOperator& so):_scale(so._scale) {} - + ScaleOperator& operator = (const ScaleOperator& so) { _scale = so._scale; return *this; } float _scale; - inline void luminance(float& l) const { l*= _scale; } - inline void alpha(float& a) const { a*= _scale; } - inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; } + inline void luminance(float& l) const { l*= _scale; } + inline void alpha(float& a) const { a*= _scale; } + inline void luminance_alpha(float& l,float& a) const { l*= _scale; a*= _scale; } inline void rgb(float& r,float& g,float& b) const { r*= _scale; g*=_scale; b*=_scale; } inline void rgba(float& r,float& g,float& b,float& a) const { r*= _scale; g*=_scale; b*=_scale; a*=_scale; } }; @@ -484,10 +484,10 @@ struct RecordRowOperator mutable std::vector _colours; mutable unsigned int _pos; - - inline void luminance(float l) const { rgba(l,l,l,1.0f); } - inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); } - inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); } + + inline void luminance(float l) const { rgba(l,l,l,1.0f); } + inline void alpha(float a) const { rgba(1.0f,1.0f,1.0f,a); } + inline void luminance_alpha(float l,float a) const { rgba(l,l,l,a); } inline void rgb(float r,float g,float b) const { rgba(r,g,b,1.0f); } inline void rgba(float r,float g,float b,float a) const { _colours[_pos++].set(r,g,b,a); } }; @@ -499,10 +499,10 @@ struct WriteRowOperator std::vector _colours; mutable unsigned int _pos; - - inline void luminance(float& l) const { l = _colours[_pos++].r(); } - inline void alpha(float& a) const { a = _colours[_pos++].a(); } - inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); } + + inline void luminance(float& l) const { l = _colours[_pos++].r(); } + inline void alpha(float& a) const { a = _colours[_pos++].a(); } + inline void luminance_alpha(float& l,float& a) const { l = _colours[_pos].r(); a = _colours[_pos++].a(); } inline void rgb(float& r,float& g,float& b) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); } inline void rgba(float& r,float& g,float& b,float& a) const { r = _colours[_pos].r(); g = _colours[_pos].g(); b = _colours[_pos].b(); a = _colours[_pos++].a(); } }; @@ -524,20 +524,20 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent return 0; } - + GLenum dataType; switch(numberBytesPerComponent) { case 1 : dataType = GL_UNSIGNED_BYTE; break; case 2 : dataType = GL_UNSIGNED_SHORT; break; case 4 : dataType = GL_UNSIGNED_INT; break; - default : + default : osg::notify(osg::NOTICE)<<"Error: numberBytesPerComponent="< image = new osg::Image; image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, dataType); - - + + bool endianSwap = (osg::getCpuByteOrder()==osg::BigEndian) ? (endian!="big") : (endian=="big"); - + unsigned int r_offset = (sizeZ new_image = new osg::Image; new_image->allocateImage(sizeS, sizeT, sizeR, pixelFormat, GL_UNSIGNED_BYTE); - + RecordRowOperator readOp(sizeS); WriteRowOperator writeOp; @@ -605,26 +605,26 @@ osg::Image* readRaw(int sizeX, int sizeY, int sizeZ, int numberBytesPerComponent // reset the indices to beginning readOp._pos = 0; writeOp._pos = 0; - + // read the pixels into readOp's _colour array osg::readRow(sizeS, pixelFormat, dataType, image->data(0,t,r), readOp); - + // pass readOp's _colour array contents over to writeOp (note this is just a pointer swap). writeOp._colours.swap(readOp._colours); - + osg::modifyRow(sizeS, pixelFormat, GL_UNSIGNED_BYTE, new_image->data(0,t,r), writeOp); // return readOp's _colour array contents back to its rightful owner. writeOp._colours.swap(readOp._colours); } } - + image = new_image; } - + return image.release(); - - + + } enum ColourSpaceOperation @@ -640,9 +640,9 @@ struct ModulateAlphaByLuminanceOperator { ModulateAlphaByLuminanceOperator() {} - inline void luminance(float&) const {} - inline void alpha(float&) const {} - inline void luminance_alpha(float& l,float& a) const { a*= l; } + inline void luminance(float&) const {} + inline void alpha(float&) const {} + inline void luminance_alpha(float& l,float& a) const { a*= l; } inline void rgb(float&,float&,float&) const {} inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a *= l;} }; @@ -650,13 +650,13 @@ struct ModulateAlphaByLuminanceOperator struct ModulateAlphaByColourOperator { ModulateAlphaByColourOperator(const osg::Vec4& colour):_colour(colour) { _lum = _colour.length(); } - + osg::Vec4 _colour; float _lum; - inline void luminance(float&) const {} - inline void alpha(float&) const {} - inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; } + inline void luminance(float&) const {} + inline void alpha(float&) const {} + inline void luminance_alpha(float& l,float& a) const { a*= l*_lum; } inline void rgb(float&,float&,float&) const {} inline void rgba(float& r,float& g,float& b,float& a) const { a = (r*_colour.r()+g*_colour.g()+b*_colour.b()+a*_colour.a()); } }; @@ -665,9 +665,9 @@ struct ReplaceAlphaWithLuminanceOperator { ReplaceAlphaWithLuminanceOperator() {} - inline void luminance(float&) const {} - inline void alpha(float&) const {} - inline void luminance_alpha(float& l,float& a) const { a= l; } + inline void luminance(float&) const {} + inline void alpha(float&) const {} + inline void luminance_alpha(float& l,float& a) const { a= l; } inline void rgb(float&,float&,float&) const { } inline void rgba(float& r,float& g,float& b,float& a) const { float l = (r+g+b)*0.3333333; a = l; } }; @@ -679,19 +679,19 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image, case (MODULATE_ALPHA_BY_LUMINANCE): { std::cout<<"doing conversion MODULATE_ALPHA_BY_LUMINANCE"<allocateImage(image->s(), image->t(), image->r(), GL_LUMINANCE, image->getDataType()); osg::copyImage(image, 0, 0, 0, image->s(), image->t(), image->r(), - newImage, 0, 0, 0, false); + newImage, 0, 0, 0, false); return newImage; } default: @@ -712,12 +712,12 @@ osg::Image* doColourSpaceConversion(ColourSpaceOperation op, osg::Image* image, osg::TransferFunction1D* readTransferFunctionFile(const std::string& filename) { std::string foundFile = osgDB::findDataFile(filename); - if (foundFile.empty()) + if (foundFile.empty()) { std::cout<<"Error: could not find transfer function file : "<> value >> red >> green >> blue >> alpha; - if (fin) + if (fin) { std::cout<<"value = "<assign(colorMap); - + return tf; } @@ -761,10 +761,10 @@ public: OpenThreads::ScopedLock lock(mutex); glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &maximumTextureSize ); - + osg::notify(osg::NOTICE)<<"Max texture size="<setDescription(arguments.getApplicationName()+" is the example which demonstrates use of 3D textures."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); @@ -884,12 +884,12 @@ int main( int argc, char **argv ) // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); - + { osg::ref_ptr keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); - + osgGA::FlightManipulator* flightManipulator = new osgGA::FlightManipulator(); flightManipulator->setYawControlMode(osgGA::FlightManipulator::NO_AUTOMATIC_YAW); keyswitchManipulator->addMatrixManipulator( '2', "Flight", flightManipulator ); @@ -920,7 +920,7 @@ int main( int argc, char **argv ) { transferFunction = readTransferFunctionFile(tranferFunctionFile); } - + while(arguments.read("--test")) { transferFunction = new osg::TransferFunction1D; @@ -940,8 +940,8 @@ int main( int argc, char **argv ) unsigned int numSlices=500; while (arguments.read("-s",numSlices)) {} - - + + float sliceEnd=1.0f; while (arguments.read("--clip",sliceEnd)) {} @@ -949,7 +949,7 @@ int main( int argc, char **argv ) while (arguments.read("--alphaFunc",alphaFunc)) {} - + ShadingModel shadingModel = Standard; while(arguments.read("--mip")) shadingModel = MaximumIntensityProjection; @@ -964,7 +964,7 @@ int main( int argc, char **argv ) osg::ref_ptr testSupportOperation = new TestSupportOperation; viewer.setRealizeOperation(testSupportOperation.get()); - + viewer.realize(); int maximumTextureSize = testSupportOperation->maximumTextureSize; @@ -987,8 +987,8 @@ int main( int argc, char **argv ) while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; } while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; } while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; } - - + + // set up colour space operation. ColourSpaceOperation colourSpaceOperation = NO_COLOUR_SPACE_OPERATION; osg::Vec4 colourModulate(0.25f,0.25f,0.25f,0.25f); @@ -1004,61 +1004,61 @@ int main( int argc, char **argv ) RESCALE_TO_ZERO_TO_ONE_RANGE, SHIFT_MIN_TO_ZERO }; - + RescaleOperation rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE; while(arguments.read("--no-rescale")) rescaleOperation = NO_RESCALE; while(arguments.read("--rescale")) rescaleOperation = RESCALE_TO_ZERO_TO_ONE_RANGE; while(arguments.read("--shift-min-to-zero")) rescaleOperation = SHIFT_MIN_TO_ZERO; - + bool resizeToPowerOfTwo = false; - - unsigned int numComponentsDesired = 0; + + unsigned int numComponentsDesired = 0; while(arguments.read("--num-components", numComponentsDesired)) {} bool useManipulator = false; while(arguments.read("--manipulator") || arguments.read("-m")) { useManipulator = true; } - bool useShader = true; + bool useShader = true; while(arguments.read("--shader")) { useShader = true; } while(arguments.read("--no-shader")) { useShader = false; } - bool gpuTransferFunction = true; + bool gpuTransferFunction = true; while(arguments.read("--gpu-tf")) { gpuTransferFunction = true; } while(arguments.read("--cpu-tf")) { gpuTransferFunction = false; } double sequenceLength = 10.0; - while(arguments.read("--sequence-duration", sequenceLength) || - arguments.read("--sd", sequenceLength)) {} + while(arguments.read("--sequence-duration", sequenceLength) || + arguments.read("--sd", sequenceLength)) {} typedef std::list< osg::ref_ptr > Images; Images images; std::string vh_filename; - while (arguments.read("--vh", vh_filename)) + while (arguments.read("--vh", vh_filename)) { std::string raw_filename, transfer_filename; - int xdim(0), ydim(0), zdim(0); + int xdim(0), ydim(0), zdim(0); osgDB::ifstream header(vh_filename.c_str()); if (header) { header >> raw_filename >> transfer_filename >> xdim >> ydim >> zdim >> xSize >> ySize >> zSize; } - + if (xdim*ydim*zdim==0) { std::cout<<"Error in reading volume header "<> red >> green >> blue >> alpha; - if (fin) + if (fin) { colorMap[value] = osg::Vec4(red/255.0f,green/255.0f,blue/255.0f,alpha/255.0f); std::cout<<"value = "<s() != image_s || + if ((*sizeItr)->s() != image_s || (*sizeItr)->t() != image_t || (*sizeItr)->r() != image_r) { @@ -1206,14 +1206,15 @@ int main( int argc, char **argv ) } - osg::ref_ptr matrix = dynamic_cast(images.front()->getUserData()); + osg::ref_ptr details = dynamic_cast(images.front()->getUserData()); + osg::ref_ptr matrix = details ? details->getMatrix() : dynamic_cast(images.front()->getUserData()); if (!matrix) { if (xSize==0.0) xSize = static_cast(image_s); if (ySize==0.0) ySize = static_cast(image_t); if (zSize==0.0) zSize = static_cast(image_r); - + matrix = new osg::RefMatrix(xSize, 0.0, 0.0, 0.0, 0.0, ySize, 0.0, 0.0, 0.0, 0.0, zSize, 0.0, @@ -1245,7 +1246,7 @@ int main( int argc, char **argv ) computeMinMax = true; } } - + if (computeMinMax) { osg::notify(osg::NOTICE)<<"Min value "<get(), + { + osg::offsetAndScaleImage(itr->get(), osg::Vec4(offset, offset, offset, offset), osg::Vec4(scale, scale, scale, scale)); } @@ -1289,38 +1290,38 @@ int main( int argc, char **argv ) for(Images::iterator itr = images.begin(); itr != images.end(); ++itr) - { - osg::offsetAndScaleImage(itr->get(), + { + osg::offsetAndScaleImage(itr->get(), osg::Vec4(offset, offset, offset, offset), osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f)); } break; } }; - +#endif } - + if (colourSpaceOperation!=NO_COLOUR_SPACE_OPERATION) { for(Images::iterator itr = images.begin(); itr != images.end(); ++itr) - { + { (*itr) = doColourSpaceConversion(colourSpaceOperation, itr->get(), colourModulate); } } - + if (!gpuTransferFunction && transferFunction.valid()) { for(Images::iterator itr = images.begin(); itr != images.end(); ++itr) - { + { *itr = osgVolume::applyTransferFunction(itr->get(), transferFunction.get()); } } - + osg::ref_ptr image_3d = 0; if (images.size()==1) @@ -1331,24 +1332,47 @@ int main( int argc, char **argv ) else { osg::notify(osg::NOTICE)<<"Creating sequence of "< imageSequence = new osg::ImageSequence; imageSequence->setLength(sequenceLength); image_3d = imageSequence.get(); for(Images::iterator itr = images.begin(); itr != images.end(); ++itr) - { + { imageSequence->addImage(itr->get()); } imageSequence->play(); } - + osg::ref_ptr volume = new osgVolume::Volume; osg::ref_ptr tile = new osgVolume::VolumeTile; volume->addChild(tile.get()); - osg::ref_ptr layer = new osgVolume::ImageLayer(image_3d.get()); + osg::ref_ptr layer = new osgVolume::ImageLayer(image_3d.get()); + + if (details) + { + layer->setRescaleIntercept(details->getRescaleIntercept()); + layer->setRescaleSlope(details->getRescaleSlope()); + } + + switch(rescaleOperation) + { + case(NO_RESCALE): + break; + + case(RESCALE_TO_ZERO_TO_ONE_RANGE): + { + layer->rescaleToZeroToOneRange(); + break; + } + case(SHIFT_MIN_TO_ZERO): + { + layer->translateMinToZero(); + break; + } + }; layer->setLocator(new osgVolume::Locator(*matrix)); tile->setLocator(new osgVolume::Locator(*matrix)); @@ -1431,23 +1455,23 @@ int main( int argc, char **argv ) layer->addProperty(new osgVolume::AlphaFuncProperty(alphaFunc)); tile->setVolumeTechnique(new osgVolume::FixedFunctionTechnique); } - + if (!outputFile.empty()) - { + { std::string ext = osgDB::getFileExtension(outputFile); std::string name_no_ext = osgDB::getNameLessExtension(outputFile); if (ext=="osg") { if (image_3d.valid()) { - image_3d->setFileName(name_no_ext + ".dds"); + image_3d->setFileName(name_no_ext + ".dds"); osgDB::writeImageFile(*image_3d, image_3d->getFileName()); } osgDB::writeNodeFile(*volume, outputFile); } else if (ext=="ive") { - osgDB::writeNodeFile(*volume, outputFile); + osgDB::writeNodeFile(*volume, outputFile); } else if (ext=="dds") { @@ -1457,11 +1481,11 @@ int main( int argc, char **argv ) { std::cout<<"Extension not support for file output, not file written."< loadedModel = volume.get(); @@ -1494,11 +1518,11 @@ int main( int argc, char **argv ) // set the scene to render viewer.setSceneData(loadedModel.get()); - + // the the viewers main frame loop viewer.run(); - } - + } + return 0; } diff --git a/include/osgVolume/Layer b/include/osgVolume/Layer index 8c5a619b7..9801413b1 100644 --- a/include/osgVolume/Layer +++ b/include/osgVolume/Layer @@ -22,6 +22,37 @@ namespace osgVolume { +/** Data strucutre for passing details about the loading imagery on to osgVolume for use when setting up dimensions etc.*/ +class OSGVOLUME_EXPORT ImageDetails : public osg::Object +{ + public: + + ImageDetails(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ImageDetails(const ImageDetails&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgVolume, ImageDetails); + + void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; } + double getRescaleIntercept() const { return _rescaleIntercept; } + + void setRescaleSlope(double slope) { _rescaleSlope = slope; } + double getRescaleSlope() const { return _rescaleSlope; } + + void setMatrix(osg::RefMatrix* matrix) { _matrix = matrix; } + osg::RefMatrix* getMatrix() { return _matrix.get(); } + const osg::RefMatrix* getMatrix() const { return _matrix.get(); } + + protected: + + double _rescaleIntercept; + double _rescaleSlope; + osg::ref_ptr _matrix; + +}; + +/** Base class for representing a single layer of volume data.*/ class OSGVOLUME_EXPORT Layer : public osg::Object { public: @@ -30,9 +61,9 @@ class OSGVOLUME_EXPORT Layer : public osg::Object /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); - + META_Object(osgVolume, Layer); - + /** Set the file name of the data associated with this layer. */ virtual void setFileName(const std::string& filename) { _filename = filename; } @@ -42,7 +73,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object void setLocator(Locator* locator) { _locator = locator; } Locator* getLocator() { return _locator.get(); } const Locator* getLocator() const { return _locator.get(); } - + void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; } const osg::Vec4& getDefaultValue() const { return _defaultValue; } @@ -58,10 +89,10 @@ class OSGVOLUME_EXPORT Layer : public osg::Object /** Get the magnification texture filter to use when do texture associated with this layer.*/ osg::Texture::FilterMode getMagFilter() const { return _magFilter; } - /** Return image associated with layer if supported. */ + /** Return image associated with layer if supported. */ virtual osg::Image* getImage() { return 0; } - /** Return const image associated with layer if supported. */ + /** Return const image associated with layer if supported. */ virtual const osg::Image* getImage() const { return 0; } @@ -82,7 +113,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object virtual bool requiresUpdateTraversal() const { return false; } /** Call update on the Layer.*/ - virtual void update(osg::NodeVisitor& /*nv*/) {} + virtual void update(osg::NodeVisitor& /*nv*/) {} /** increment the modified count."*/ virtual void dirty() {}; @@ -104,7 +135,7 @@ class OSGVOLUME_EXPORT Layer : public osg::Object osg::Vec4 _defaultValue; osg::Texture::FilterMode _minFilter; osg::Texture::FilterMode _magFilter; - + osg::ref_ptr _property; }; @@ -117,7 +148,7 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); - + META_Object(osgVolume, ImageLayer); void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); } @@ -125,21 +156,29 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer void setImage(osg::Image* image); - /** Return image associated with layer. */ + /** Return image associated with layer. */ virtual osg::Image* getImage() { return _image.get(); } /** Return const image associated with layer. */ virtual const osg::Image* getImage() const { return _image.get(); } - + + + void setRescaleIntercept(double intercept) { _rescaleIntercept = intercept; } + double getRescaleIntercept() const { return _rescaleIntercept; } + + void setRescaleSlope(double slope) { _rescaleSlope = slope; } + double setRescaleSlope() const { return _rescaleSlope; } + + /** Compute the min and max pixel colors.*/ bool computeMinMax(osg::Vec4& min, osg::Vec4& max); - + /** Apply color transformation to pixels using c' = offset + c * scale .*/ void offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale); - + /** Compute the min max range of the image, and then remap this to a 0 to 1 range.*/ void rescaleToZeroToOneRange(); - + /** Compute the min color component of the image and then translate and pixels by this offset to make the new min component 0.*/ void translateMinToZero(); @@ -155,6 +194,8 @@ class OSGVOLUME_EXPORT ImageLayer : public Layer virtual ~ImageLayer() {} + double _rescaleIntercept; + double _rescaleSlope; osg::ref_ptr _image; }; @@ -167,7 +208,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); - + META_Object(osgVolume, CompositeLayer); void clear(); @@ -182,11 +223,11 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer void addLayer(Layer* layer) { _layers.push_back(NameLayer(layer->getFileName(),layer)); } void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); } - + unsigned int getNumLayers() const { return _layers.size(); } bool requiresUpdateTraversal() const; - + virtual void update(osg::NodeVisitor& /*nv*/); protected: @@ -196,7 +237,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer struct NameLayer { NameLayer() {} - + NameLayer(const NameLayer& cnl): filename(cnl.filename), layer(cnl.layer) {} @@ -208,7 +249,7 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer NameLayer& operator = (const NameLayer& cnl) { if (&cnl==this) return *this; - + filename = cnl.filename; layer = cnl.layer; return *this; @@ -217,9 +258,9 @@ class OSGVOLUME_EXPORT CompositeLayer : public Layer std::string filename; osg::ref_ptr layer; }; - + typedef std::vector< NameLayer > Layers; - + Layers _layers; }; diff --git a/src/osgPlugins/dicom/ReaderWriterDICOM.cpp b/src/osgPlugins/dicom/ReaderWriterDICOM.cpp index 16c24ec15..11f001582 100644 --- a/src/osgPlugins/dicom/ReaderWriterDICOM.cpp +++ b/src/osgPlugins/dicom/ReaderWriterDICOM.cpp @@ -23,9 +23,10 @@ #define HAVE_CONFIG_H #endif - #include + #include #include #include + #include #include #endif @@ -48,7 +49,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter { public: - + ReaderWriterDICOM() { supportsExtension("mag","dicom image format"); @@ -63,18 +64,18 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter std::ostream& warning() const { return osg::notify(osg::WARN); } std::ostream& notice() const { return osg::notify(osg::NOTICE); } std::ostream& info() const { return osg::notify(osg::INFO); } - + template T* readData(std::istream& fin, unsigned int length, unsigned int& numComponents) const { numComponents = length/sizeof(T); T* data = new T[numComponents]; fin.read((char*)data, numComponents*sizeof(T)); - + // read over any padding length -= numComponents*sizeof(T); while(fin && length>0) { fin.get(); --length; } - + return data; } @@ -89,8 +90,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter else out<<"."; } } - else - { + else + { for(unsigned int i=0; i Files; bool getDicomFilesInDirectory(const std::string& path, Files& files) const { @@ -143,16 +144,16 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter { ReadResult result = readImage(file, options); if (!result.validImage()) return result; - + osg::ref_ptr tile = new osgVolume::VolumeTile; tile->setVolumeTechnique(new osgVolume::RayTracedTechnique()); - + osg::ref_ptr layer= new osgVolume::ImageLayer(result.getImage()); layer->rescaleToZeroToOneRange(); - + osgVolume::SwitchProperty* sp = new osgVolume::SwitchProperty; sp->setActiveProperty(0); - + float alphaFunc = 0.1f; osgVolume::AlphaFuncProperty* ap = new osgVolume::AlphaFuncProperty(alphaFunc); @@ -206,24 +207,31 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter tile->setLayer(layer.get()); // get matrix providing size of texels (in mm) - osg::RefMatrix* matrix = dynamic_cast(result.getImage()->getUserData()); - + osgVolume::ImageDetails* details = dynamic_cast(result.getImage()->getUserData()); + osg::RefMatrix* matrix = details ? details->getMatrix() : 0; + + if (details) + { + layer->setRescaleIntercept(details->getRescaleIntercept()); + layer->setRescaleSlope(details->getRescaleSlope()); + } + if (matrix) { osgVolume::Locator* locator = new osgVolume::Locator(*matrix); tile->setLocator(locator); layer->setLocator(locator); - + // result.getImage()->setUserData(0); - + info()<<"Locator "<<*matrix<get(); - osg::RefMatrix* matrix = dynamic_cast(image->getUserData()); + osgVolume::ImageDetails* details = dynamic_cast(result.getImage()->getUserData()); + osg::RefMatrix* matrix = details ? details->getMatrix() : 0; if (matrix) { osg::Vec3 p0 = osg::Vec3(0.0, 0.0, 0.0) * (*matrix); @@ -340,18 +349,19 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter { osg::Image* image = itr->second.get(); osg::copyImage(image, 0,0,0, image->s(), image->t(), image->r(), - image3D.get(), 0, 0, r, - false); + image3D.get(), 0, 0, r, + false); r += image->r(); } osg::Image* firstImage = dim.begin()->second.get(); - osg::RefMatrix* matrix = dynamic_cast(firstImage->getUserData()); + osgVolume::ImageDetails* details = dynamic_cast(result.getImage()->getUserData()); + osg::RefMatrix* matrix = details ? details->getMatrix() : 0; if (matrix) { - image3D->setUserData( - new osg::RefMatrix(osg::Matrix::scale(1.0,1.0,totalThickness) * (*matrix)) - ); + osgVolume::ImageDetails* details3D = new osgVolume::ImageDetails(*details); + details3D->getMatrix()->preMult(osg::Matrix::scale(1.0,1.0,totalThickness)); + image3D->setUserData(details3D); } return image3D.get(); @@ -384,36 +394,36 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter std::cerr << e.GetLocation() << std::endl; return ReadResult::ERROR_IN_READING_FILE; } - + ImageType::Pointer inputImage = reader->GetOutput(); - + ImageType::RegionType region = inputImage->GetBufferedRegion(); ImageType::SizeType size = region.GetSize(); ImageType::IndexType start = region.GetIndex(); - + //inputImage->GetSpacing(); //inputImage->GetOrigin(); - + unsigned int width = size[0]; unsigned int height = size[1]; unsigned int depth = size[2]; - + osg::RefMatrix* matrix = new osg::RefMatrix; - + info()<<"width = "< matrix = new osg::RefMatrix; + osg::ref_ptr details = new osgVolume::ImageDetails; + details->setMatrix(new osg::RefMatrix); + osg::ref_ptr image; + unsigned int imageNum = 0; EP_Representation pixelRep = EPR_Uint8; int numPlanes = 0; GLenum pixelFormat = 0; GLenum dataType = 0; unsigned int pixelSize = 0; - + typedef std::list FileInfoList; FileInfoList fileInfoList; typedef std::map DistanceFileInfoMap; typedef std::map OrientationFileInfoMap; OrientationFileInfoMap orientationFileInfoMap; - + unsigned int totalNumSlices = 0; for(Files::iterator itr = files.begin(); @@ -559,7 +575,7 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter DcmFileFormat fileformat; OFCondition status = fileformat.loadFile((*itr).c_str()); if(!status.good()) return ReadResult::ERROR_IN_READING_FILE; - + FileInfo fileInfo; fileInfo.filename = *itr; @@ -569,7 +585,33 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter double imagePositionPatient[3] = {0, 0, 0}; double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; Uint16 numOfSlices = 1; - + + // code for reading the intercept and scale that is required to convert to Hounsfield units. + bool rescaling = false; + double rescaleIntercept = 0.0; + double rescaleSlope = 1.0; + const char *classUID = NULL; + if (fileformat.getDataset()->findAndGetString(DCM_SOPClassUID, classUID).good()) + { + osg::notify(osg::NOTICE)<<" classUID = "<findAndGetFloat64(DCM_RescaleIntercept, rescaleIntercept).good(); + rescaling &= fileformat.getDataset()->findAndGetFloat64(DCM_RescaleSlope, rescaleSlope).good(); + if (rescaling) + { + fileInfo.rescaleIntercept = rescaleIntercept; + fileInfo.rescaleSlope = rescaleSlope; + osg::notify(osg::NOTICE)<<" rescaleIntercept = "<second; if (dfim.empty()) return 0; @@ -721,11 +763,11 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter { totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices); } - + info()<<"Total Distance including ends "<second; - + std::auto_ptr dcmImage(new DicomImage(fileInfo.filename.c_str())); if (dcmImage.get()) { @@ -742,14 +784,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter // get the pixel data const DiPixel* pixelData = dcmImage->getInterData(); - if(!pixelData) + if(!pixelData) { warning()<<"Error: no data in DicomImage object."< imageAdapter = new osg::Image; - + EP_Representation curr_pixelRep; int curr_numPlanes; GLenum curr_pixelFormat; @@ -758,15 +800,15 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter // create the new image convertPixelTypes(pixelData, - curr_pixelRep, curr_numPlanes, - curr_dataType, curr_pixelFormat, curr_pixelSize); + curr_pixelRep, curr_numPlanes, + curr_dataType, curr_pixelFormat, curr_pixelSize); imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(), - curr_pixelFormat, - curr_pixelFormat, - curr_dataType, - (unsigned char*)(pixelData->getData()), - osg::Image::NO_DELETE); + curr_pixelFormat, + curr_pixelFormat, + curr_dataType, + (unsigned char*)(pixelData->getData()), + osg::Image::NO_DELETE); if (!image) { pixelRep = curr_pixelRep; @@ -775,6 +817,8 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter pixelFormat = curr_pixelFormat; pixelSize = curr_pixelSize; + osg::RefMatrix* matrix = details->getMatrix(); + (*matrix)(0,0) = fileInfo.matrix(0,0); (*matrix)(1,0) = fileInfo.matrix(1,0); (*matrix)(2,0) = fileInfo.matrix(2,0); @@ -784,49 +828,50 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter (*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness; (*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness; (*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness; - - + details->setRescaleIntercept(fileInfo.rescaleIntercept); + details->setRescaleSlope(fileInfo.rescaleSlope); + image = new osg::Image; - image->setUserData(matrix.get()); + image->setUserData(details.get()); image->setFileName(fileName.c_str()); - image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, - pixelFormat, dataType); - - + image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, + pixelFormat, dataType); + + matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r()))); info()<<"Image dimensions = "<s()<<", "<t()<<", "<r()<<" pixelFormat=0x"<getPlanes()>numPlanes || - pixelData->getRepresentation()>pixelRep) + pixelData->getRepresentation()>pixelRep) { info()<<"Need to reallocated "<s()<<", "<t()<<", "<r()< previous_image = image; // create the new image convertPixelTypes(pixelData, - pixelRep, numPlanes, - dataType, pixelFormat, pixelSize); - + pixelRep, numPlanes, + dataType, pixelFormat, pixelSize); + image = new osg::Image; image->setUserData(previous_image->getUserData()); image->setFileName(fileName.c_str()); - image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, - pixelFormat, dataType); - + image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, + pixelFormat, dataType); + osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum, - image.get(), 0, 0, 0, - false); - + image.get(), 0, 0, 0, + false); + } - - osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), - image.get(), 0, 0, imageNum, - false); - + + osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), + image.get(), 0, 0, imageNum, + false); + imageNum += dcmImage->getFrameCount(); } else @@ -835,14 +880,14 @@ class ReaderWriterDICOM : public osgDB::ReaderWriter } } } - + if (!image) { return ReadResult::ERROR_IN_READING_FILE; } - info()<<"Spacing = "<<*matrix<layer->requiresUpdateTraversal()) return true; } - + return false; } @@ -216,7 +240,7 @@ void CompositeLayer::update(osg::NodeVisitor& nv) { itr->layer->update(nv); } - + } @@ -231,7 +255,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) GLenum dataType = image_3d->getDataType(); unsigned int sourcePixelIncrement = 1; - unsigned int alphaOffset = 0; + unsigned int alphaOffset = 0; switch(image_3d->getPixelFormat()) { case(GL_ALPHA): @@ -269,7 +293,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) { if (dataType==GL_UNSIGNED_BYTE) - { + { unsigned char* ptr = image_3d->data(1,t,r)+alphaOffset; unsigned char* left = image_3d->data(0,t,r)+alphaOffset; unsigned char* right = image_3d->data(2,t,r)+alphaOffset; @@ -284,8 +308,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) { osg::Vec3 grad((float)(*left)-(float)(*right), - (float)(*below)-(float)(*above), - (float)(*out) -(float)(*in)); + (float)(*below)-(float)(*above), + (float)(*out) -(float)(*in)); grad.normalize(); @@ -331,8 +355,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) { osg::Vec3 grad((float)(*left)-(float)(*right), - (float)(*below)-(float)(*above), - (float)(*out) -(float)(*in)); + (float)(*below)-(float)(*above), + (float)(*out) -(float)(*in)); grad.normalize(); @@ -348,7 +372,7 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) grad.y() = osg::clampBetween((grad.y()+1.0f)*128.0f,0.0f,255.0f); grad.z() = osg::clampBetween((grad.z()+1.0f)*128.0f,0.0f,255.0f); } - + *(destination++) = (unsigned char)(grad.x()); // scale and bias X. *(destination++) = (unsigned char)(grad.y()); // scale and bias Y. @@ -381,8 +405,8 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) { osg::Vec3 grad((float)(*left)-(float)(*right), - (float)(*below)-(float)(*above), - (float)(*out) -(float)(*in)); + (float)(*below)-(float)(*above), + (float)(*out) -(float)(*in)); grad.normalize(); @@ -414,10 +438,10 @@ osg::Image* osgVolume::createNormalMapTexture(osg::Image* image_3d) } } } - - + + osg::notify(osg::INFO)<<"Created NormalMapTexture"<getColor(l); @@ -440,27 +464,27 @@ struct ApplyTransferFunctionOperator *(_data++) = (unsigned char)(c[2]*255.0f + 0.5f); *(_data++) = (unsigned char)(c[3]*255.0f + 0.5f); } - + inline void alpha(float a) const { luminance(a); - } - + } + inline void luminance_alpha(float l,float a) const - { + { luminance(l); } - + inline void rgb(float r,float g,float b) const { luminance((r+g+b)*0.3333333); } - + inline void rgba(float r,float g,float b,float a) const { luminance(a); } - + mutable osg::ref_ptr _tf; mutable unsigned char* _data; }; @@ -468,12 +492,12 @@ struct ApplyTransferFunctionOperator osg::Image* osgVolume::applyTransferFunction(osg::Image* image, osg::TransferFunction1D* transferFunction) { osg::notify(osg::INFO)<<"Applying transfer function"<allocateImage(image->s(),image->t(), image->r(), GL_RGBA, GL_UNSIGNED_BYTE); - + ApplyTransferFunctionOperator op(transferFunction, output_image->data()); - osg::readImage(image,op); - + osg::readImage(image,op); + return output_image; }