source: experimental/distortionNG/extViewer.cpp @ 387

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