root/OpenSceneGraph/trunk/examples/osgslice/osgslice.cpp @ 13342

Revision 7648, 9.2 kB (checked in by robert, 7 years ago)

From Roland Smeenk, "Attached you will find a large set of small typo fixes (mainly in the comments)."

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgslice.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19// Simple example of use of osg::GraphicContext to create an OpenGL
20// graphics window, and OSG for rendering.
21
22#include <osg/Timer>
23#include <osg/GraphicsContext>
24#include <osg/ApplicationUsage>
25#include <osgUtil/SceneView>
26#include <osgDB/ReadFile>
27#include <osgDB/WriteFile>
28
29#include <sstream>
30#include <iostream>
31
32#define MIN_NEARFAROFFSET 0.1
33
34class SliceProcessor
35{
36    public:
37
38        SliceProcessor() : _sliceNumber(128), _sliceDelta(0.1), _nearPlane(0.0), _farPlane(MIN_NEARFAROFFSET)
39        {
40            //
41        }
42        SliceProcessor( const double& objectRadius, unsigned int numberSlices) : _sliceNumber(numberSlices)
43        {
44            _sliceDelta = (objectRadius*2) / _sliceNumber;
45            _nearPlane = objectRadius;                          // note: distance from viewpoint is going to be set 2x radius
46            _farPlane = _nearPlane+MIN_NEARFAROFFSET;
47            _image = new osg::Image;
48            if( _sliceDelta > MIN_NEARFAROFFSET )
49            {
50                _nearFarOffset = MIN_NEARFAROFFSET;
51            }
52            else
53            {
54                _nearFarOffset = _sliceDelta;
55            }
56            _image->allocateImage( _sliceNumber, _sliceNumber,_sliceNumber, GL_RGBA, GL_UNSIGNED_BYTE );
57           
58        }
59        // needs 3D-Texture object
60        osg::Image* _image;
61        unsigned int _sliceNumber;
62        double _sliceDelta;
63        double _nearPlane;
64        double _farPlane;
65        double _nearFarOffset;
66       
67    // needs function to do rendering and slicing
68};
69
70int main( int argc, char **argv )
71{
72        // use an ArgumentParser object to manage the program arguments.
73    osg::ArgumentParser arguments(&argc,argv);
74
75    // set up the usage document, in case we need to print out how to use this program.
76    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
77    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
78    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
79    arguments.getApplicationUsage()->addCommandLineOption("-o <filename>","Object to be loaded");
80   
81    if( arguments.read( "-h" ) || arguments.read( "--help" ) )
82    {
83        std::cout << "Argumentlist:" << std::endl;
84        std::cout << "\t-o <filename> sets object to be loaded and sliced" << std::endl;
85        std::cout << "\t--slices <unsigned int> sets number of slices through the object" << std::endl;
86        std::cout << "\t--near <double> sets start for near clipping plane" << std::endl;
87        std::cout << "\t--far <double> sets start for far clipping plane" << std::endl;
88       
89        return 1;
90    }
91   
92    std::string outputName("volume_tex.dds");
93    while( arguments.read( "-o", outputName ) ) { }
94
95
96    unsigned int numberSlices = 128;
97    while( arguments.read( "--slices", numberSlices) ) { }
98
99    double nearClip=0.0f;
100    double farClip=0.0f;
101    while( arguments.read( "--near",nearClip ) ) { }
102    while( arguments.read( "--far", farClip) ) { }
103
104   
105    // load the scene.
106    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles( arguments );
107    if (!loadedModel)
108    {
109        std::cout << "No data loaded." << std::endl;
110        return 1;
111    }
112
113    const osg::BoundingSphere& bs = loadedModel->getBound();
114    SliceProcessor* sp = new SliceProcessor( (double)bs.radius(), numberSlices );
115    if (nearClip!=0.0) sp->_nearPlane = nearClip;
116    if (farClip!=0.0) sp->_farPlane = farClip;
117
118    // any option left unread are converted into errors to write out later.
119    arguments.reportRemainingOptionsAsUnrecognized();
120
121    // report any errors if they have occurred when parsing the program arguments.
122    if (arguments.errors())
123    {
124        arguments.writeErrorMessages(std::cout);
125        return 1;
126    }
127   
128
129
130    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
131    traits->x = 100;
132    traits->y = 100;
133    traits->width = numberSlices;
134    traits->height = numberSlices;
135    traits->alpha = 8;
136    traits->windowDecoration = true;
137    traits->doubleBuffer = true;
138    traits->sharedContext = 0;
139    traits->pbuffer = false;
140
141    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
142    if (!gc || !gc->valid())
143    {
144        osg::notify(osg::NOTICE)<<"Error: unable to create graphics window"<<std::endl;
145        return 1;
146    }
147   
148    gc->realize();
149    gc->makeCurrent();
150
151    // create the view of the scene.
152    osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
153    sceneView->setDefaults();
154    sceneView->setSceneData(loadedModel.get());
155
156    // initialize the view to look at the center of the scene graph
157    osg::Matrix viewMatrix;
158    // distance from viewport to object's center is set to be 2x bs.radius()
159    viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
160   
161    // turn off autocompution of near and far clipping planes
162    sceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
163
164    // set the clear color of the background to make sure that the alpha is 0.0.
165    sceneView->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
166
167    // record the timer tick at the start of rendering.     
168    osg::Timer_t start_tick = osg::Timer::instance()->tick();
169   
170    std::cout << "radius: " << bs.radius() << std::endl;
171   
172    unsigned int frameNum = 0;
173    double tmpNear, tmpFar;
174    std::string baseImageName("shot_");
175    std::string tmpImageName;
176   
177    osg::Image* tmpImage = new osg::Image;
178   
179    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
180    for( unsigned int i = 0 ; i < sp->_sliceNumber && gc->isRealized() ; ++i )
181    {
182        // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
183        osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
184        frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
185        frameStamp->setFrameNumber(frameNum++);
186       
187        // pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
188        sceneView->setFrameStamp(frameStamp.get());
189       
190        // update the viewport dimensions, incase the window has been resized.
191        sceneView->setViewport(0,0,traits->width,traits->height);
192       
193       
194        // set the view
195        sceneView->setViewMatrix(viewMatrix);
196       
197        // set Projection Matrix
198        tmpNear = sp->_nearPlane+i*sp->_sliceDelta;
199        tmpFar = sp->_farPlane+(i*sp->_sliceDelta)+sp->_nearFarOffset;
200        sceneView->setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar);
201
202        // do the update traversal the scene graph - such as updating animations
203        sceneView->update();
204       
205        // do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
206        sceneView->cull();
207       
208        // draw the rendering bins.
209        sceneView->draw();
210               
211        // Swap Buffers
212        gc->swapBuffers();
213       
214        std::cout << "before readPixels: _r = " << sp->_image->r() << std::endl;
215       
216        tmpImage->readPixels(static_cast<int>(sceneView->getViewport()->x()),
217                             static_cast<int>(sceneView->getViewport()->y()),
218                             static_cast<int>(sceneView->getViewport()->width()),
219                             static_cast<int>(sceneView->getViewport()->height()),
220                             GL_RGBA,GL_UNSIGNED_BYTE);
221       
222//        std::cout << "vor copySubImage: _r = " << sp->_image->r() << std::endl;
223        sp->_image->copySubImage( 0, 0, i, tmpImage );
224
225        /*
226        std::ostringstream o;
227        o << baseImageName << i << ".rgba";
228        tmpImageName = o.str();
229        osgDB::writeImageFile( *(sp->_image), tmpImageName );
230        std::cout << "Wrote image to file: " << tmpImageName << std::endl;
231        */
232    }
233    osgDB::writeImageFile( *(sp->_image), outputName);
234
235    return 0;
236}
Note: See TracBrowser for help on using the browser.