source: experimental/distortionNG/extViewer.cpp @ 361

Last change on this file since 361 was 361, checked in by Torben Dannhauer, 13 years ago
File size: 14.7 KB
Line 
1/* osgVisual test. distortionNG, experimental.
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#include "extViewer.h"
20
21#include <osg/Switch>
22#include <osg/PolygonOffset>
23#include <osg/Texture2D>
24#include <osg/TextureRectangle>
25#include <osg/TexMat>
26#include <osg/ComputeBoundsVisitor>
27#include <osg/Vec2>
28
29#include <osgDB/ReadFile>
30#include <osgDB/FileUtils>
31
32#include <osgUtil/SmoothingVisitor>
33
34
35extViewer::extViewer() : Viewer()
36{
37}
38
39extViewer::extViewer(osg::ArgumentParser& arguments) : Viewer(arguments)
40{
41        // Add help for command-line options here
42    arguments.getApplicationUsage()->addCommandLineOption("--distort","load distortion file and set up geometrical distortion for viewer. This includes blending");
43    arguments.getApplicationUsage()->addCommandLineOption("--blend","Set up viewer for simple intensity map blending.");
44
45        std::string distortionSetFilename = "";
46        std::string intensityMapFilename = "";
47        while( arguments.read("--blend",intensityMapFilename) ) {}
48        while( arguments.read("--distort",distortionSetFilename) ) {}
49
50        if( !intensityMapFilename.empty() )
51        {
52                OSG_ALWAYS<<"Pure blendmap setup with : "<<intensityMapFilename<<std::endl;
53                setUpIntensityMapBlending(intensityMapFilename);
54        }
55        else if( !distortionSetFilename.empty() )
56        {
57                OSG_ALWAYS<<"Set up distortion by loaded distortionSet: "<<distortionSetFilename<<std::endl;
58
59                osg::Object* distSet = osgDB::readObjectFile( distortionSetFilename );
60                if( distSet != NULL )
61                {
62                        OSG_ALWAYS<<"read distortionSet success"<<std::endl;
63                        setUpViewForManualDistortion(static_cast<osgViewer::DistortionSet*>(distSet));
64                }
65                else
66                {
67                        OSG_ALWAYS<<"read distortionSet failed"<<std::endl;
68                }
69        }       
70       
71}
72
73extViewer::extViewer(const osgViewer::Viewer& viewer, const osg::CopyOp& copyop) : Viewer(viewer, copyop)
74{
75
76}
77
78extViewer::~extViewer()
79{
80
81}
82
83static osg::Geometry* createMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, unsigned int columns, unsigned int rows, const osg::Matrix& projectorMatrix)
84{
85        // Create Quad to render on
86        osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
87
88        geom->setUseDisplayList( false );
89
90        osg::Vec3 xAxis(widthVector);
91    float width = widthVector.length();
92    xAxis /= width;
93
94    osg::Vec3 yAxis(heightVector);
95    float height = heightVector.length();
96    yAxis /= height;
97
98        osg::Vec3 dx = xAxis*(width/((float)(columns-1)));
99    osg::Vec3 dy = yAxis*(height/((float)(rows-1)));
100
101
102        // Create vertices and coordinates
103        osg::Vec3Array* vertices = new osg::Vec3Array;
104    osg::Vec2Array* texcoords0 = new osg::Vec2Array;
105    osg::Vec4Array* colors = new osg::Vec4Array;
106
107        geom->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
108
109        for ( unsigned int row=0; row<rows; row++ )
110        {
111                for ( unsigned int col=0; col<columns; col++ )
112                {
113                        // Create coordinates of the mesh node (geometry).
114                        vertices->push_back( origin+dy*row+dx*col );
115
116                        // Create tex coordinates
117                        osg::Vec2 texcoord = osg::Vec2((float)col/(float)(columns-1), (float)row/(float)(rows-1));
118
119                        // Set Coordinates for RTT-Texture (scene rendering)
120                        texcoords0->push_back( texcoord );
121
122                        // Set Color of the mesh node
123                        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
124                }
125        }
126
127        // Pass the created vertex array to the points geometry object.
128        geom->setUseVertexBufferObjects( true );
129        geom->setVertexArray(vertices);
130
131        geom->setColorArray(colors);
132    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
133
134    geom->setTexCoordArray(0,texcoords0);
135
136        // Quads grid
137        for ( unsigned int row=0; row<rows-1; row++ )   // each strip consists of two affected vertex rows, so we need only row-1 strips.
138        {
139                osg::ref_ptr<osg::DrawElementsUInt> de = new osg::DrawElementsUInt(osg::PrimitiveSet::QUAD_STRIP, columns*2);   // columns*2 = number of involved vertices for this strip.
140                for ( unsigned int col=0; col<columns; col++ )
141                {
142                        (*de)[col*2 + 0] = row*columns + col;
143                        (*de)[col*2 + 1] = (row+1)*columns + col;
144                }
145                geom->addPrimitiveSet( de.get() );
146        }
147
148        //// Triangle grid
149        //for ( unsigned int row=0; row<rows-1; row++ ) // each strip consists of two affected vertex rows, so we need only row-1 strips.
150        //{
151        //      osg::ref_ptr<osg::DrawElementsUInt> de = new osg::DrawElementsUInt(osg::PrimitiveSet::TRIANGLE_STRIP, columns * 2 );   
152        //      for ( unsigned int col=0; col<columns; col++ )
153        //      {
154        //              (*de)[col*2 + 0] = row*columns + col;
155        //              (*de)[col*2 + 1] = (row+1)*columns + col;
156        //      }
157        //      geom->addPrimitiveSet( de.get() );
158        //}
159
160        return geom.release();
161}
162
163
164void extViewer::setUpViewForManualDistortion(osgViewer::DistortionSet* distSet, unsigned int screenNum, const osg::Matrixd& projectorMatrix)
165{
166        OSG_INFO<<"View::setUpViewForManualDistortion(sn="<<screenNum<<")"<<std::endl;
167
168        if(distSet == NULL)
169        {
170        OSG_NOTICE<<"Error, no DistortionSet specified, cannot setup distortion."<<std::endl;
171        return;
172        }
173        _distortionSet = distSet;
174
175    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
176    if (!wsi)
177    {
178        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
179        return;
180    }
181
182        osg::GraphicsContext::ScreenIdentifier si;
183    si.readDISPLAY();
184
185    // displayNum has not been set so reset it to 0.
186    if (si.displayNum<0) si.displayNum = 0;
187
188    si.screenNum = screenNum;
189
190    unsigned int width, height;
191    wsi->getScreenResolution(si, width, height);
192
193        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
194    traits->hostName = si.hostName;
195    traits->displayNum = si.displayNum;
196    traits->screenNum = si.screenNum;
197    traits->x = 0;
198    traits->y = 0;
199    traits->width = width;
200    traits->height = height;
201    traits->windowDecoration = false;
202    traits->doubleBuffer = true;
203    traits->sharedContext = 0;
204
205        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
206    if (!gc)
207    {
208        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
209        return;
210    }
211
212        // Set up projection Matrix as it is done in View::setUpViewOnSingleScreen(
213        double fovy, aspectRatio, zNear, zFar;
214        _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
215
216        double newAspectRatio = double(traits->width) / double(traits->height);
217        double aspectRatioChange = newAspectRatio / aspectRatio;
218        if (aspectRatioChange != 1.0)
219        {
220                _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
221        }
222
223
224    int tex_width = width;
225    int tex_height = height;
226
227    int camera_width = tex_width;
228    int camera_height = tex_height;
229
230    osg::TextureRectangle* sceneTexture = new osg::TextureRectangle;
231
232    sceneTexture->setTextureSize(tex_width, tex_height);
233    sceneTexture->setInternalFormat(GL_RGB);
234    sceneTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
235    sceneTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
236    sceneTexture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
237    sceneTexture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
238
239
240#if 0
241    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
242    GLenum buffer = GL_FRONT;
243#else
244    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
245    GLenum buffer = GL_FRONT;
246#endif
247
248        // Scene camera
249    {
250        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
251        camera->setName("Scene cam");
252        camera->setGraphicsContext(gc.get());
253        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
254        camera->setDrawBuffer(buffer);
255        camera->setReadBuffer(buffer);
256        camera->setAllowEventFocus(false);
257        // tell the camera to use OpenGL frame buffer object where supported.
258        camera->setRenderTargetImplementation(renderTargetImplementation);
259        // attach the texture and use it as the color buffer.
260        camera->attach(osg::Camera::COLOR_BUFFER, sceneTexture);
261
262        addSlave(camera.get(), _distortionSet->getProjectionOffset(), _distortionSet->getViewOffset() );
263
264    }
265
266    // distortion correction set up.
267    {
268                osg::ref_ptr<osg::Switch> root = _distortionSet->getDistortionInternals();
269                osg::Geode* meshGeode = new osg::Geode();
270                root->addChild(meshGeode, true);        // Child #0  (adds mesh,shader,.. so camera renders mesh (and  thus render the scene))
271               
272
273                // new we need to add the scene texture to the mesh, we do so by creating a
274        // StateSet to contain the Texture StateAttribute.
275            osg::StateSet* stateset = meshGeode->getOrCreateStateSet();
276        stateset->setTextureAttributeAndModes(_distortionSet->getTexUnitScene(), sceneTexture,osg::StateAttribute::ON);
277        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
278
279                osg::TexMat* texmat = new osg::TexMat;
280            texmat->setScaleByTextureRectangleSize(true);
281        stateset->setTextureAttributeAndModes(_distortionSet->getTexUnitScene(), texmat, osg::StateAttribute::ON);
282
283                osg::Geometry* distortionMesh = createMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), _distortionSet->getDistortionMeshColumns(), _distortionSet->getDistortionMeshColumns(), projectorMatrix);
284                meshGeode->addDrawable(distortionMesh);
285
286                setUpIntensityMapBlending(_distortionSet, screenNum);
287
288        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
289        camera->setGraphicsContext(gc.get());
290        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
291        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
292        camera->setViewport(new osg::Viewport(0, 0, width, height));
293        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
294        camera->setDrawBuffer(buffer);
295        camera->setReadBuffer(buffer);
296        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
297        camera->setAllowEventFocus(false);
298        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
299        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
300
301        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
302        camera->setViewMatrix(osg::Matrix::identity());
303
304                camera->addChild(root);
305                _distortionSet->setDistortionCamera( camera );
306
307                // Ensure selector is visible:
308                meshGeode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
309                meshGeode->getOrCreateStateSet()->setAttributeAndModes( new osg::PolygonOffset(1.0f, 1.0f) );
310               
311        camera->setName("Dist Cam");
312
313        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
314    }
315}
316
317void extViewer::setUpIntensityMapBlending(osgViewer::DistortionSet* distSet, unsigned int screenNum)
318{
319        osg::Image* intensityMap = _distortionSet->getIntensityMap();
320        osg::StateSet* stateset = _distortionSet->getDistortionInternals()->getChild(osgViewer::DistortionSet::MESH)->getOrCreateStateSet();
321
322        if(intensityMap == NULL)        return;
323
324        if(stateset == NULL)
325        {
326                OSG_NOTICE<<"Error, no intensityMap or stateset for intensityMapBlending specified."<<std::endl;
327                return;
328        }
329
330        osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
331    if (!wsi)
332    {
333        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
334        return;
335    }
336
337        osg::GraphicsContext::ScreenIdentifier si;
338    si.readDISPLAY();
339
340    // displayNum has not been set so reset it to 0.
341    if (si.displayNum<0) si.displayNum = 0;
342
343    si.screenNum = screenNum;
344
345    unsigned int width, height;
346    wsi->getScreenResolution(si, width, height);
347
348        // Resize intensityMap if the dimensions are wrong
349        if(intensityMap->s()!=width || intensityMap->t()!=height)
350                intensityMap->scaleImage(width, height, intensityMap->r());
351
352        osg::TextureRectangle* intensityMapTexture = new osg::TextureRectangle(intensityMap);
353        intensityMapTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
354        intensityMapTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
355        intensityMapTexture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
356        intensityMapTexture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
357
358    stateset->setTextureAttributeAndModes(_distortionSet->getTexUnitIntensityMap(), intensityMapTexture, osg::StateAttribute::ON);
359
360        // create shader for blending
361        osg::Program* IntensityMapProgram = new osg::Program;
362        IntensityMapProgram->setName( "intensityMapBlending" );
363        osg::Shader* shaderIntensityMap = osg::Shader::readShaderFile( osg::Shader::FRAGMENT, "shaderIntensityMap.frag" ); 
364        shaderIntensityMap->setName("shaderIntensityMap");
365        _distortionSet->setShaderIntensityMap( shaderIntensityMap );
366
367        if ( shaderIntensityMap )
368        {
369                IntensityMapProgram->addShader( shaderIntensityMap );
370                stateset->addUniform( new osg::Uniform("sceneTexture", (int)_distortionSet->getTexUnitScene()) );
371                stateset->addUniform( new osg::Uniform("intensityMapTexture", (int)_distortionSet->getTexUnitIntensityMap()) );
372                stateset->setAttributeAndModes(IntensityMapProgram, osg::StateAttribute::ON);
373        }
374}
375
376void extViewer::setUpIntensityMapBlending(std::string intensityMap)
377{
378        // Try to load intensityMap
379        osg::Image* intMap = osgDB::readImageFile(intensityMap);
380        if (!intMap)
381        {
382                osg::notify(osg::WARN) << "Quitting, couldn't find intensity map: " << intensityMap << std::endl;
383                return;
384        } 
385
386        // Create DistortionSet
387        osgViewer::DistortionSet* ds = new osgViewer::DistortionSet();
388        ds->setIntensityMap( intMap );
389        ds->setDistortionMeshRows( 2 );
390        ds->setDistortionMeshColumns( 2 );
391        ds->setTexUnitScene( 0 );
392        ds->setTexUnitIntensityMap( 1 );
393
394        setUpViewForManualDistortion(ds);
395}
Note: See TracBrowser for help on using the repository browser.