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

Last change on this file since 150 was 150, checked in by Torben Dannhauer, 13 years ago
File size: 20.1 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        this->configFileName = configFileName;
26        initialized = false;
27        distortionEnabled = false;
28        parser = new CameraConfigParser();
29
30        distortedGraph = NULL;
31        cleanGraph = NULL;
32
33        distortMapTexture = NULL;
34        blendMapTexture = NULL;
35}
36
37visual_distortion::~visual_distortion(void)
38{
39        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion destroyed." << std::endl;
40}
41
42bool visual_distortion::processXMLConfiguration()
43{
44        // Init XML
45        xmlDoc* tmpDoc;
46        xmlNode* config = util::getModuleXMLConfig( configFileName, "distortion", tmpDoc );
47       
48        // extract configuration values
49        if(config)
50        {
51       
52                xmlNode* a_node = config->children;
53
54                for (xmlNode *cur_node = a_node; cur_node; cur_node = cur_node->next)
55                {
56                        std::string node_name=reinterpret_cast<const char*>(cur_node->name);
57                        OSG_ALWAYS << "----visual_distortion::processXMLConfiguration() - node type="<< cur_node->type <<", name=" << cur_node->name << std::endl;
58
59                        // Check for distortion node
60                        if(cur_node->type == XML_ELEMENT_NODE && node_name == "distortion")
61                        {
62                                xmlAttr  *attr = cur_node->properties;
63                                while ( attr ) 
64                                { 
65                                        std::string attr_name=reinterpret_cast<const char*>(attr->name);
66                                        std::string attr_value=reinterpret_cast<const char*>(attr->children->content);
67                                        if( attr_name == "channelname" )
68                                        {
69                                                std::string  channelname = attr_value;
70                                                OSG_NOTIFY(osg::ALWAYS) << "channelname:" << channelname << std::endl;
71
72                                                std::string pre_cfg("..\\resources\\distortion\\view_");
73                                                std::string pre_distortion("..\\resources\\distortion\\distort_");
74                                                std::string pre_blend("..\\resources\\distortion\\blend_");
75                                                std::string post_cfg(".cfg");
76                                                std::string post_distortion(".bmp");
77                                                std::string post_blend(".bmp");
78
79                                                // load channel config
80                                                parser->parseConfigFile((pre_cfg+channelname+post_cfg).data());
81                                                // load channel blendmap
82                                                blendMapFileName = (pre_blend+channelname+post_blend).data();
83                                                // load channel distortionmap
84                                                distortMapFileName = (pre_distortion+channelname+post_distortion).data(); 
85                                                // set channel frustum
86                                                if( parser->isConfigParsed())
87                                                        viewer->getCamera()->setProjectionMatrixAsFrustum((parser->getFrustumDataset())[0], (parser->getFrustumDataset())[1], (parser->getFrustumDataset())[2], (parser->getFrustumDataset())[3], (parser->getFrustumDataset())[4], (parser->getFrustumDataset())[5]);
88                                                else
89                                                        OSG_NOTIFY(osg::WARN) << "WARNING: Unable to parse Frustum values from '" << pre_cfg<<channelname<<post_cfg << "' -- continue without valid frustum values." << std::endl;
90                                        }
91                                        if( attr_name == "renderimplemmentation" )
92                                        {
93                                                if(attr_value=="fbo")
94                                                        renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
95                                                if(attr_value=="pbuffer")
96                                                        renderImplementation = osg::Camera::PIXEL_BUFFER;
97                                                if(attr_value=="pbuffer-rtt")
98                                                        renderImplementation = osg::Camera::PIXEL_BUFFER_RTT;
99                                                if(attr_value=="fb")
100                                                        renderImplementation = osg::Camera::FRAME_BUFFER;
101                                                if(attr_value=="window")
102                                                        renderImplementation = osg::Camera::SEPERATE_WINDOW;           
103                                        }
104                                        if( attr_name == "width" )
105                                        {
106                                                std::stringstream sstr(attr_value);
107                                                sstr >> tex_width;
108                                        }
109                                        if( attr_name == "height" )
110                                        {
111                                                std::stringstream sstr(attr_value);
112                                                sstr >> tex_height;
113                                        }
114                                        if( attr_name == "useshader" )
115                                                useShaderDistortion = (attr_value == "yes") ? true : false;
116                                        if( attr_name == "hdr" )
117                                                useHDR = (attr_value == "yes") ? true : false;
118                                        if( attr_name == "usetexturerectangle" )
119                                                useTextureRectangle = (attr_value == "yes") ? true : false;
120
121
122                                        attr = attr->next; 
123                                }       // WHILE attrib END
124                        }       // IF Node == distortion END
125
126                        // Check for distortionmap node
127                        if(cur_node->type == XML_ELEMENT_NODE && node_name == "distortionmap")
128                        {
129                                xmlAttr  *attr = cur_node->properties;
130                                while ( attr ) 
131                                { 
132                                        std::string attr_name=reinterpret_cast<const char*>(attr->name);
133                                        std::string attr_value=reinterpret_cast<const char*>(attr->children->content);
134                                        if( attr_name == "filename" )
135                                        {
136                                                distortMapFileName = attr_value;
137                                        }
138
139                                        attr = attr->next; 
140                                }
141                        }
142
143                        // Check for distortionmap node
144                        if(cur_node->type == XML_ELEMENT_NODE && node_name == "blendmap")
145                        {
146                                xmlAttr  *attr = cur_node->properties;
147                                while ( attr ) 
148                                { 
149                                        std::string attr_name=reinterpret_cast<const char*>(attr->name);
150                                        std::string attr_value=reinterpret_cast<const char*>(attr->children->content);
151                                        if( attr_name == "filename" )
152                                        {
153                                                blendMapFileName = attr_value;
154                                        }
155
156                                        attr = attr->next; 
157                                }
158                        }
159                }       // FOR all nodes END
160
161
162        }       // IF Config valid END
163        else
164                OSG_WARN << "ERROR: visual_distortion::processXMLConfiguration() - Invalid module configuration!" << std::endl;
165
166
167
168        // clean up
169        if(tmpDoc)
170        {
171                xmlFreeDoc(tmpDoc); xmlCleanupParser();
172                return true;
173        }
174
175        return true;
176}
177
178osg::Group* visual_distortion::initialize(osg::Group* subgraph, const osg::Vec4& clearColor )
179{
180        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion initialize..." << std::endl;
181
182        // Initialize variables:
183        tex_width = 2048;
184    tex_height = 2048;
185        renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
186        useTextureRectangle = false;
187        useShaderDistortion = false;
188        useHDR = false; 
189        distortMapFileName = "..\\resources\\distortion\\distort_distDisabled.bmp";
190        blendMapFileName = "..\\resources\\distortion\\blend_distDisabled.bmp";
191
192        // Process XML configuration
193        processXMLConfiguration();
194
195        // Add this node to the scenegraph to get updated during update traversal.
196        subgraph->addChild( this );
197
198        // add the keyboard handler for toggle distortion
199        arguments.getApplicationUsage()->addKeyboardMouseBinding("d", "Toggle Distortion.");
200        kBEventHandler = new ToggleDistortionKBEventHandler( this );
201        viewer->addEventHandler( kBEventHandler );
202
203        cleanGraph = subgraph;
204        distortedGraph = createPreRenderSubGraph( subgraph, clearColor );
205
206        // Create and install updateCallback (to get called for copying the main cameras view matrixes to the PRE_RENDER camera)
207        // -- must be called _AFTER_ createPreRenderSubGraph() (necessary because sceneCamera is set by createPreRenderSubGraph())
208        updateCallback = new distortionUpdateCallback( viewer, sceneCamera );
209        this->setUpdateCallback( updateCallback );
210
211        // Note down state flags..
212        initialized = true;
213        distortionEnabled = true;
214
215        distortionEnabled = true;
216        viewer->setSceneData( distortedGraph );
217       
218        return distortedGraph;
219}
220
221void visual_distortion::shutdown()
222{
223        if(initialized)
224        {
225                // Remove this Node from scenegraph
226                cleanGraph->removeChild( this );
227
228                // Remove update callback
229                this->removeUpdateCallback( updateCallback );
230                updateCallback = NULL;
231
232                OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion shutdown complete." << std::endl;
233        }
234}
235
236void visual_distortion::distortionUpdateCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
237{
238        // Copy Main Camera's matrixes to the PRE_RENDER Camera.
239        //std::cout << "distortion updatecallback" << std::endl;
240        sceneCamera->setViewMatrix( viewer->getCamera()->getViewMatrix() );
241        sceneCamera->setProjectionMatrix( viewer->getCamera()->getProjectionMatrix() );
242}
243
244void visual_distortion::toggleDistortion()
245{
246        // Toggle
247        //// If not Distorted: enabled distortion
248        if( !distortionEnabled )
249        {
250                distortionEnabled = true;
251                viewer->setSceneData( distortedGraph );
252        }
253        else    // .. otherwise disable distortion
254        {
255                distortionEnabled = false;
256                viewer->setSceneData( cleanGraph );
257        }
258}
259
260
261osg::Group* visual_distortion::createPreRenderSubGraph(osg::Group* subgraph, const osg::Vec4& clearColor )
262{
263    if (!subgraph) return 0;
264
265    // create a group to contain the flag and the pre rendering camera.
266    osg::Group* parent = new osg::Group;
267
268    // texture to render to and to use for rendering of flag.
269    osg::Texture* texture = 0;
270    if (useTextureRectangle)
271    {
272        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
273        textureRect->setTextureSize(tex_width, tex_height);
274        textureRect->setInternalFormat(GL_RGBA);
275        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
276        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
277       
278        texture = textureRect;
279    }
280    else
281    {
282        osg::Texture2D* texture2D = new osg::Texture2D;
283        texture2D->setTextureSize(tex_width, tex_height);
284        texture2D->setInternalFormat(GL_RGBA);
285        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
286        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
287       
288        texture = texture2D;
289    } 
290
291    if (useHDR)
292    {
293        texture->setInternalFormat(GL_RGBA16F_ARB);
294        texture->setSourceFormat(GL_RGBA);
295        texture->setSourceType(GL_FLOAT);
296    }
297
298    // load a distortion map texture file
299        if ( osgDB::fileExists( distortMapFileName ) )
300                distortMapTexture = loadTexture(distortMapFileName);
301        else
302        {
303                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;
304                exit(-1);
305        }
306
307    // load a blend map texture file
308        if ( osgDB::fileExists( blendMapFileName ) )
309                blendMapTexture = loadTexture(blendMapFileName);
310        else
311        {
312                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;
313                exit(-1);
314        }
315
316    // set up the plane to render the rendered view.
317    {
318        // create the quad to visualize.
319        osg::Geometry* polyGeom = new osg::Geometry();
320
321        polyGeom->setSupportsDisplayList(false);
322
323        osg::Vec3 origin(0.0f,0.0f,0.0f);
324        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
325        osg::Vec3 yAxis(0.0f,1.0f,0.0f);
326        osg::Vec3 zAxis(0.0f,0.0f,1.0f);
327        float height = 1024.0f;
328        float width = 1280.0f;
329        int noSteps = 128;
330        if (useShaderDistortion)
331            noSteps = 2;
332
333        osg::Vec3Array* vertices = new osg::Vec3Array;
334        osg::Vec2Array* texcoords = new osg::Vec2Array;
335        osg::Vec2Array* texcoords2 = useShaderDistortion?NULL:(new osg::Vec2Array);
336        osg::Vec4Array* colors = new osg::Vec4Array;
337
338        osg::Vec3 bottom = origin;
339        osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
340        osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
341
342        osg::Vec2 bottom_texcoord(0.0f,0.0f);
343        osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f);
344        osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1));
345
346        osg::Vec3 cursor = bottom;
347        osg::Vec2 texcoord = bottom_texcoord;
348        int i,j;
349        for(i=0;i<noSteps;++i)
350        {
351            osg::Vec3 cursor = bottom+dy*(float)i;
352            osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i;
353            for(j=0;j<noSteps;++j)
354            {
355                vertices->push_back(cursor);
356                if (distortMapTexture && !useShaderDistortion)
357                {
358                    osg::Vec2 imgcoord = osg::Vec2((distortMapTexture->getImage(0)->s()-1) * texcoord.x(),
359                                                   (distortMapTexture->getImage(0)->t()-1) * texcoord.y());
360                    unsigned char* pPixel = &distortMapTexture->getImage(0)->data()[(int)imgcoord.y()*distortMapTexture->getImage(0)->getRowSizeInBytes()+
361                                                                                    (int)imgcoord.x()*distortMapTexture->getImage(0)->getPixelSizeInBits()/8];
362                    texcoords->push_back(osg::Vec2(((float)pPixel[2] / 255.0f + (pPixel[0] % 16)) / 16.0f,
363                                                   1.0f - ((float)pPixel[1] / 255.0f + (pPixel[0] / 16)) / 16.0f));
364                    texcoords2->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
365                }
366                else
367                    texcoords->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
368                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
369
370                cursor += dx;
371                texcoord += dx_texcoord;
372            }
373        }
374
375        // pass the created vertex array to the points geometry object.
376        polyGeom->setVertexArray(vertices);
377
378        polyGeom->setColorArray(colors);
379        polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
380        polyGeom->setTexCoordArray(0,texcoords);
381        if (!useShaderDistortion)
382            polyGeom->setTexCoordArray(2,texcoords2);
383
384        for(i=0;i<noSteps-1;++i)
385        {
386            osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
387            for(j=0;j<noSteps;++j)
388            {
389                elements->push_back(j+(i+1)*noSteps);
390                elements->push_back(j+(i)*noSteps);
391            }
392            polyGeom->addPrimitiveSet(elements);
393        }
394
395        // new we need to add the texture to the Drawable, we do so by creating a
396        // StateSet to contain the Texture StateAttribute.
397        osg::StateSet* stateset = polyGeom->getOrCreateStateSet();
398        stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
399        stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
400        stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
401
402        osg::Geode* geode = new osg::Geode();
403        geode->addDrawable(polyGeom);
404
405        if (useShaderDistortion)
406        {
407            // apply the distortion map texture
408            if (distortMapTexture)
409                geode->getOrCreateStateSet()->setTextureAttributeAndModes(1, distortMapTexture, osg::StateAttribute::ON);
410        }
411
412        // apply the blend map texture
413        if (blendMapTexture)
414            geode->getOrCreateStateSet()->setTextureAttributeAndModes(2, blendMapTexture, osg::StateAttribute::ON);
415
416        // set up the camera to render the textured quad
417        osg::Camera* camera = new osg::Camera;
418
419        // just inherit the main cameras view
420        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
421        camera->setViewMatrix(osg::Matrix::identity());
422        //sceneCamera->setProjectionMatrixAsOrtho2D(0,viewer->getCamera()->getViewport()->width(),0,viewer->getCamera()->getViewport()->height());
423                camera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
424                /** \todo: use screen size dynamically */
425
426        // set the camera to render before the main camera.
427        camera->setRenderOrder(osg::Camera::POST_RENDER, 200);
428
429        // only clear the depth buffer
430        camera->setClearMask(0);
431
432        // add subgraph to render
433        camera->addChild(geode);
434
435        if (useShaderDistortion)
436        {
437            // create shaders for distortion
438            osg::StateSet* ss = geode->getOrCreateStateSet();
439
440            osg::Program* distortProgram = new osg::Program;
441            distortProgram->setName( "distortion" );
442            osg::Shader* distortVertObj = new osg::Shader( osg::Shader::VERTEX );
443            osg::Shader* distortFragObj = new osg::Shader( osg::Shader::FRAGMENT );
444
445            if (loadShaderSource( distortVertObj, "../resources/distortion/shader.vert" ) &&
446                loadShaderSource( distortFragObj, "../resources/distortion/shader.frag" ) &&
447                distortMapTexture)
448            {
449                distortProgram->addShader( distortFragObj );
450                distortProgram->addShader( distortVertObj );
451                ss->addUniform( new osg::Uniform("textureImage", 0) );
452                ss->addUniform( new osg::Uniform("textureDistort", 1) );
453                ss->addUniform( new osg::Uniform("textureBlend", 2) );
454                ss->setAttributeAndModes(distortProgram, osg::StateAttribute::ON);
455            }
456                        else
457                        {
458                                OSG_NOTIFY(osg::FATAL) << "##################################" << std::endl << "## Unable to activate ShaderDistortion!" << std::endl << "## ABORT" << std::endl << "##################################" << std::endl;
459                                exit(0);
460                        }
461        }
462
463        parent->addChild(camera);
464    }
465
466    // then create the camera node to do the render to texture
467    {   
468        osg::Camera* camera = new osg::Camera;
469
470        // set up the background color and clear mask.
471        camera->setClearColor(clearColor);
472        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
473
474
475        // just inherit the main cameras view
476                /* ABSOLUTE_RF required to make intersections possible.
477                Disadvantage of ABOLUTE_RF : the maincameras view matrix and projection
478                matrix has to copied to the PRE_RENDER camera by our self.
479                Therefore an update callback is installed.
480                */
481                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); 
482        camera->setProjectionMatrix(osg::Matrixd::identity());
483        camera->setViewMatrix(osg::Matrixd::identity());
484
485        // set viewport
486        camera->setViewport(0,0,tex_width,tex_height);
487
488        // set the camera to render before the main camera.
489        camera->setRenderOrder(osg::Camera::PRE_RENDER, 0);
490
491                sceneCamera = camera;
492
493        // tell the camera to use OpenGL frame buffer object where supported.
494        camera->setRenderTargetImplementation(renderImplementation);
495
496        // attach the texture and use it as the color buffer.
497        camera->attach(osg::Camera::COLOR_BUFFER, texture);     // No Multisampling/Antialiasing
498                //camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, 0, false, 4, 4); // 4x Multisampling/Antialiasing
499
500        // add subgraph to render
501        camera->addChild(subgraph);
502
503        parent->addChild(camera);
504    }   
505    return parent;
506}
507
508
509bool visual_distortion::loadShaderSource( osg::Shader* shader, const std::string& fileName )
510{
511    std::string foundFileName = osgDB::findDataFile(fileName);
512    if (foundFileName.length() != 0 )
513    {
514        return shader->loadShaderSourceFromFile( foundFileName.c_str() );
515    }
516
517    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
518
519    return false;
520}
521
522osg::Texture* visual_distortion::loadTexture( const std::string& fileName )
523{
524    std::string foundFileName = osgDB::findDataFile(fileName);
525    if (foundFileName.length() != 0 )
526    {
527        // load distortion map texture file
528        osg::Image* image = osgDB::readImageFile(foundFileName);
529        if (image)
530        {
531                        osg::Texture2D* texture = new osg::Texture2D;
532            texture->setImage(image);
533            texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);
534            texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);
535            texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP_TO_EDGE);
536            texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP_TO_EDGE);
537            return texture;
538        }
539    }
540
541    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
542
543    return NULL;
544}
Note: See TracBrowser for help on using the repository browser.