source: osgVisual/src/distortion/visual_distortion.cpp @ 146

Last change on this file since 146 was 145, checked in by Torben Dannhauer, 14 years ago
File size: 19.5 KB
Line 
1/* -*-c++-*- osgVisual - Copyright (C) 2009-2010 Torben Dannhauer
2 *
3 * This library is based on OpenSceneGraph, open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * osgVisual requires for some proprietary modules a license from the correspondig manufacturer.
9 * You have to aquire licenses for all used proprietary modules.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * OpenSceneGraph Public License for more details.
15*/
16
17#include <visual_distortion.h>
18
19using namespace osgVisual;
20
21visual_distortion::visual_distortion(osgViewer::Viewer* viewer_, osg::ArgumentParser& arguments_, std::string configFileName) : viewer(viewer_), arguments(arguments_)
22{
23        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion instantiated." << std::endl;
24
25        initialized = false;
26        distortionEnabled = false;
27        parser = new CameraConfigParser();
28
29        distortedGraph = NULL;
30        cleanGraph = NULL;
31
32        distortMapTexture = NULL;
33        blendMapTexture = NULL;
34}
35
36visual_distortion::~visual_distortion(void)
37{
38        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion destroyed." << std::endl;
39}
40
41bool visual_distortion::processCommandlineparameters()
42{
43        // Distortion files.
44        arguments.getApplicationUsage()->addCommandLineOption("-C <channelname>","Setup the channel name, this is the preset for blendmap, distortionmap and camera configuration file.");
45    arguments.getApplicationUsage()->addCommandLineOption("--distortionmap","Set a distortion map file name.");
46    arguments.getApplicationUsage()->addCommandLineOption("--blendmap","Set a blend map file name.");
47
48        // Render implementation.
49        arguments.getApplicationUsage()->addCommandLineOption("--shaderDistortion","Use OpenGL shader for distortion and blending.");
50        arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
51    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
52    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
53    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
54
55        // Texture
56    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");         // used for all render implementations
57    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");       // used for all render implementations
58
59        // Texture Rectangle?
60    arguments.getApplicationUsage()->addCommandLineOption("--texture-rectangle","Use osg::TextureRectangle for doing the render to texure to.");
61
62        // HDR?
63    arguments.getApplicationUsage()->addCommandLineOption("--hdr","Render distortion as HDR.");
64
65        arguments.getApplicationUsage()->addKeyboardMouseBinding("d", "Toggle Distortion.");
66
67        // Read out Distortion CMDLine arguments
68        tex_width = 2048;
69    tex_height = 2048;
70    while (arguments.read("--width", tex_width)) {}
71    while (arguments.read("--height", tex_height)) {}
72
73        renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
74
75    while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
76    while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
77    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::Camera::PIXEL_BUFFER_RTT; }
78    while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
79    while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
80
81    useTextureRectangle = false;
82    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
83        useShaderDistortion = false;
84    while (arguments.read("--shaderDistortion")) { useShaderDistortion = true; }
85    useHDR = false; 
86    while (arguments.read("--hdr")) { useHDR = true; }
87
88        distortMapFileName = "..\\resources\\distortion\\distort_distDisabled.bmp";
89    while (arguments.read("--distortionmap", distortMapFileName)) { }
90        blendMapFileName = "..\\resources\\distortion\\blend_distDisabled.bmp";
91    while (arguments.read("--blendmap", blendMapFileName)) { }
92
93        std::string pre_cfg("..\\resources\\distortion\\view_");
94        std::string pre_distortion("..\\resources\\distortion\\distort_");
95        std::string pre_blend("..\\resources\\distortion\\blend_");
96        std::string post_cfg(".cfg");
97        std::string post_distortion(".bmp");
98        std::string post_blend(".bmp");
99        std::string channelname;
100        while (arguments.read("-C",channelname))
101        {
102                OSG_NOTIFY(osg::INFO) << "channelname:" << channelname << std::endl;
103                // load channel config
104                parser->parseConfigFile((pre_cfg+channelname+post_cfg).data());
105                // load channel blendmap
106                blendMapFileName = (pre_blend+channelname+post_blend).data();
107                // load channel distortionmap
108                distortMapFileName = (pre_distortion+channelname+post_distortion).data(); 
109                // set channel frustum
110                if( parser->isConfigParsed())
111                        viewer->getCamera()->setProjectionMatrixAsFrustum((parser->getFrustumDataset())[0], (parser->getFrustumDataset())[1], (parser->getFrustumDataset())[2], (parser->getFrustumDataset())[3], (parser->getFrustumDataset())[4], (parser->getFrustumDataset())[5]);
112                else
113                        OSG_NOTIFY(osg::WARN) << "WARNING: Unable to parse Frustum values from '" << pre_cfg<<channelname<<post_cfg << "' -- continue without valid frustum values." << std::endl;
114        }
115
116         // report any errors if they have occurred when parsing the program arguments.
117    if (arguments.errors())
118    {
119        arguments.writeErrorMessages(std::cout);
120                exit(1);
121    }
122        return true;
123}
124
125osg::Group* visual_distortion::initialize(osg::Group* subgraph, const osg::Vec4& clearColor )
126{
127        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion initialize..." << std::endl;
128
129        // Process Commandline arguments:
130        processCommandlineparameters();
131
132        // Add this node to the scenegraph to get updated during update traversal.
133        subgraph->addChild( this );
134
135        // add the keyboard handler for toggle distortion
136        kBEventHandler = new ToggleDistortionKBEventHandler( this );
137        viewer->addEventHandler( kBEventHandler );
138
139        cleanGraph = subgraph;
140        distortedGraph = createPreRenderSubGraph( subgraph, clearColor );
141
142        // Create and install updateCallback (to get called for copying the main cameras view matrixes to the PRE_RENDER camera)
143        // -- must be called _AFTER_ createPreRenderSubGraph() (necessary because sceneCamera is set by createPreRenderSubGraph())
144        updateCallback = new distortionUpdateCallback( viewer, sceneCamera );
145        this->setUpdateCallback( updateCallback );
146
147        // Note down state flags..
148        initialized = true;
149        distortionEnabled = true;
150
151        distortionEnabled = true;
152        viewer->setSceneData( distortedGraph );
153       
154        return distortedGraph;
155}
156
157void visual_distortion::shutdown()
158{
159        if(initialized)
160        {
161                // Remove this Node from scenegraph
162                cleanGraph->removeChild( this );
163
164                // Remove update callback
165                this->removeUpdateCallback( updateCallback );
166                updateCallback = NULL;
167
168                OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion shutdown complete." << std::endl;
169        }
170}
171
172void visual_distortion::distortionUpdateCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
173{
174        // Copy Main Camera's matrixes to the PRE_RENDER Camera.
175        //std::cout << "distortion updatecallback" << std::endl;
176        sceneCamera->setViewMatrix( viewer->getCamera()->getViewMatrix() );
177        sceneCamera->setProjectionMatrix( viewer->getCamera()->getProjectionMatrix() );
178}
179
180void visual_distortion::toggleDistortion()
181{
182        // Toggle
183        //// If not Distorted: enabled distortion
184        if( !distortionEnabled )
185        {
186                distortionEnabled = true;
187                viewer->setSceneData( distortedGraph );
188        }
189        else    // .. otherwise disable distortion
190        {
191                distortionEnabled = false;
192                viewer->setSceneData( cleanGraph );
193        }
194}
195
196
197osg::Group* visual_distortion::createPreRenderSubGraph(osg::Group* subgraph, const osg::Vec4& clearColor )
198{
199    if (!subgraph) return 0;
200
201    // create a group to contain the flag and the pre rendering camera.
202    osg::Group* parent = new osg::Group;
203
204    // texture to render to and to use for rendering of flag.
205    osg::Texture* texture = 0;
206    if (useTextureRectangle)
207    {
208        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
209        textureRect->setTextureSize(tex_width, tex_height);
210        textureRect->setInternalFormat(GL_RGBA);
211        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
212        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
213       
214        texture = textureRect;
215    }
216    else
217    {
218        osg::Texture2D* texture2D = new osg::Texture2D;
219        texture2D->setTextureSize(tex_width, tex_height);
220        texture2D->setInternalFormat(GL_RGBA);
221        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
222        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
223       
224        texture = texture2D;
225    } 
226
227    if (useHDR)
228    {
229        texture->setInternalFormat(GL_RGBA16F_ARB);
230        texture->setSourceFormat(GL_RGBA);
231        texture->setSourceType(GL_FLOAT);
232    }
233
234    // load a distortion map texture file
235        if ( osgDB::fileExists( distortMapFileName ) )
236                distortMapTexture = loadTexture(distortMapFileName);
237        else
238        {
239                OSG_NOTIFY(osg::FATAL) << "ERROR: Distortionmap file'" << distortMapFileName << "' not found! Please change the channelname, filename or copy the desired file to the applications root folder!" << std::endl;
240                exit(-1);
241        }
242
243    // load a blend map texture file
244        if ( osgDB::fileExists( blendMapFileName ) )
245                blendMapTexture = loadTexture(blendMapFileName);
246        else
247        {
248                OSG_NOTIFY(osg::FATAL) << "ERROR: Blendmap file'" << blendMapFileName << "' not found! Please change the channelname, filename or copy the desired file to the applications root folder!" << std::endl;
249                exit(-1);
250        }
251
252    // set up the plane to render the rendered view.
253    {
254        // create the quad to visualize.
255        osg::Geometry* polyGeom = new osg::Geometry();
256
257        polyGeom->setSupportsDisplayList(false);
258
259        osg::Vec3 origin(0.0f,0.0f,0.0f);
260        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
261        osg::Vec3 yAxis(0.0f,1.0f,0.0f);
262        osg::Vec3 zAxis(0.0f,0.0f,1.0f);
263        float height = 1024.0f;
264        float width = 1280.0f;
265        int noSteps = 128;
266        if (useShaderDistortion)
267            noSteps = 2;
268
269        osg::Vec3Array* vertices = new osg::Vec3Array;
270        osg::Vec2Array* texcoords = new osg::Vec2Array;
271        osg::Vec2Array* texcoords2 = useShaderDistortion?NULL:(new osg::Vec2Array);
272        osg::Vec4Array* colors = new osg::Vec4Array;
273
274        osg::Vec3 bottom = origin;
275        osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
276        osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
277
278        osg::Vec2 bottom_texcoord(0.0f,0.0f);
279        osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f);
280        osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1));
281
282        osg::Vec3 cursor = bottom;
283        osg::Vec2 texcoord = bottom_texcoord;
284        int i,j;
285        for(i=0;i<noSteps;++i)
286        {
287            osg::Vec3 cursor = bottom+dy*(float)i;
288            osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i;
289            for(j=0;j<noSteps;++j)
290            {
291                vertices->push_back(cursor);
292                if (distortMapTexture && !useShaderDistortion)
293                {
294                    osg::Vec2 imgcoord = osg::Vec2((distortMapTexture->getImage(0)->s()-1) * texcoord.x(),
295                                                   (distortMapTexture->getImage(0)->t()-1) * texcoord.y());
296                    unsigned char* pPixel = &distortMapTexture->getImage(0)->data()[(int)imgcoord.y()*distortMapTexture->getImage(0)->getRowSizeInBytes()+
297                                                                                    (int)imgcoord.x()*distortMapTexture->getImage(0)->getPixelSizeInBits()/8];
298                    texcoords->push_back(osg::Vec2(((float)pPixel[2] / 255.0f + (pPixel[0] % 16)) / 16.0f,
299                                                   1.0f - ((float)pPixel[1] / 255.0f + (pPixel[0] / 16)) / 16.0f));
300                    texcoords2->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
301                }
302                else
303                    texcoords->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
304                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
305
306                cursor += dx;
307                texcoord += dx_texcoord;
308            }
309        }
310
311        // pass the created vertex array to the points geometry object.
312        polyGeom->setVertexArray(vertices);
313
314        polyGeom->setColorArray(colors);
315        polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
316        polyGeom->setTexCoordArray(0,texcoords);
317        if (!useShaderDistortion)
318            polyGeom->setTexCoordArray(2,texcoords2);
319
320        for(i=0;i<noSteps-1;++i)
321        {
322            osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
323            for(j=0;j<noSteps;++j)
324            {
325                elements->push_back(j+(i+1)*noSteps);
326                elements->push_back(j+(i)*noSteps);
327            }
328            polyGeom->addPrimitiveSet(elements);
329        }
330
331        // new we need to add the texture to the Drawable, we do so by creating a
332        // StateSet to contain the Texture StateAttribute.
333        osg::StateSet* stateset = polyGeom->getOrCreateStateSet();
334        stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
335        stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
336        stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
337
338        osg::Geode* geode = new osg::Geode();
339        geode->addDrawable(polyGeom);
340
341        if (useShaderDistortion)
342        {
343            // apply the distortion map texture
344            if (distortMapTexture)
345                geode->getOrCreateStateSet()->setTextureAttributeAndModes(1, distortMapTexture, osg::StateAttribute::ON);
346        }
347
348        // apply the blend map texture
349        if (blendMapTexture)
350            geode->getOrCreateStateSet()->setTextureAttributeAndModes(2, blendMapTexture, osg::StateAttribute::ON);
351
352        // set up the camera to render the textured quad
353        osg::Camera* camera = new osg::Camera;
354
355        // just inherit the main cameras view
356        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
357        camera->setViewMatrix(osg::Matrix::identity());
358        //sceneCamera->setProjectionMatrixAsOrtho2D(0,viewer->getCamera()->getViewport()->width(),0,viewer->getCamera()->getViewport()->height());
359                camera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
360                /** \todo: use screen size dynamically */
361
362        // set the camera to render before the main camera.
363        camera->setRenderOrder(osg::Camera::POST_RENDER, 200);
364
365        // only clear the depth buffer
366        camera->setClearMask(0);
367
368        // add subgraph to render
369        camera->addChild(geode);
370
371        if (useShaderDistortion)
372        {
373            // create shaders for distortion
374            osg::StateSet* ss = geode->getOrCreateStateSet();
375
376            osg::Program* distortProgram = new osg::Program;
377            distortProgram->setName( "distortion" );
378            osg::Shader* distortVertObj = new osg::Shader( osg::Shader::VERTEX );
379            osg::Shader* distortFragObj = new osg::Shader( osg::Shader::FRAGMENT );
380
381            if (loadShaderSource( distortVertObj, "shader.vert" ) &&
382                loadShaderSource( distortFragObj, "shader.frag" ) &&
383                distortMapTexture)
384            {
385                distortProgram->addShader( distortFragObj );
386                distortProgram->addShader( distortVertObj );
387                ss->addUniform( new osg::Uniform("textureImage", 0) );
388                ss->addUniform( new osg::Uniform("textureDistort", 1) );
389                ss->addUniform( new osg::Uniform("textureBlend", 2) );
390                ss->setAttributeAndModes(distortProgram, osg::StateAttribute::ON);
391            }
392                        else
393                        {
394                                OSG_NOTIFY(osg::FATAL) << "##################################" << std::endl << "## Unable to activate ShaderDistortion!" << std::endl << "## ABORT" << std::endl << "##################################" << std::endl;
395                                exit(0);
396                        }
397        }
398
399        parent->addChild(camera);
400    }
401
402    // then create the camera node to do the render to texture
403    {   
404        osg::Camera* camera = new osg::Camera;
405
406        // set up the background color and clear mask.
407        camera->setClearColor(clearColor);
408        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
409
410
411        // just inherit the main cameras view
412                /* ABSOLUTE_RF required to make intersections possible.
413                Disadvantage of ABOLUTE_RF : the maincameras view matrix and projection
414                matrix has to copied to the PRE_RENDER camera by our self.
415                Therefore an update callback is installed.
416                */
417                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); 
418        camera->setProjectionMatrix(osg::Matrixd::identity());
419        camera->setViewMatrix(osg::Matrixd::identity());
420
421        // set viewport
422        camera->setViewport(0,0,tex_width,tex_height);
423
424        // set the camera to render before the main camera.
425        camera->setRenderOrder(osg::Camera::PRE_RENDER, 0);
426
427                sceneCamera = camera;
428
429        // tell the camera to use OpenGL frame buffer object where supported.
430        camera->setRenderTargetImplementation(renderImplementation);
431
432        // attach the texture and use it as the color buffer.
433        camera->attach(osg::Camera::COLOR_BUFFER, texture);     // No Multisampling/Antialiasing
434                //camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, 0, false, 4, 4); // 4x Multisampling/Antialiasing
435
436        // add subgraph to render
437        camera->addChild(subgraph);
438
439        parent->addChild(camera);
440    }   
441    return parent;
442}
443
444
445bool visual_distortion::loadShaderSource( osg::Shader* shader, const std::string& fileName )
446{
447    std::string foundFileName = osgDB::findDataFile(fileName);
448    if (foundFileName.length() != 0 )
449    {
450        return shader->loadShaderSourceFromFile( foundFileName.c_str() );
451    }
452
453    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
454
455    return false;
456}
457
458osg::Texture* visual_distortion::loadTexture( const std::string& fileName )
459{
460    std::string foundFileName = osgDB::findDataFile(fileName);
461    if (foundFileName.length() != 0 )
462    {
463        // load distortion map texture file
464        osg::Image* image = osgDB::readImageFile(foundFileName);
465        if (image)
466        {
467                        osg::Texture2D* texture = new osg::Texture2D;
468            texture->setImage(image);
469            texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);
470            texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);
471            texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP_TO_EDGE);
472            texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP_TO_EDGE);
473            return texture;
474        }
475    }
476
477    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
478
479    return NULL;
480}
Note: See TracBrowser for help on using the repository browser.