source: experimental/distortionNG/extViewer.cpp @ 351

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