OpenSceneGraph Forum Forum Index OpenSceneGraph Forum
Official forum which mirrors the existent OSG mailing lists. Messages posted here are forwarded to the mailing list and vice versa.
 
   FAQFAQ    SearchSearch    MemberlistMemberlist    RulesRules    UsergroupsUsergroups    RegisterRegister 
 Mail2Forum SettingsMail2Forum Settings  ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 
   AlbumAlbum  OpenSceneGraph IRC ChatOpenSceneGraph IRC Chat   SmartFeedSmartFeed 

using modern shaders with osg - setting vertex attribute layout

Goto page Previous  1, 2
 
Post new topic   Reply to topic    OpenSceneGraph Forum Forum Index -> General
View previous topic :: View next topic  
Author Message
antiro42
User


Joined: 01 Sep 2017
Posts: 40

PostPosted: Sat Sep 02, 2017 7:36 pm    Post subject:
Reply with quote

Hi Sebastian,

I'm compiling under debian jessie 64 bits and am running a NVIDIA GTX 970. The drivers have been updates recently and I am running version 384.69 now.

I included a compilable minimal example based on the osgmultiplerendertargets example. Without VertexAttributeAliasing it generates two texture using MRT, a red and a green one, it then combines these in a second pass to generate the final texture (yellow). (The red and green intermediate textures are shown in small quads to the side.)

When I enable the attribute aliasing (as in the included code), the two textures generated in the MRT pass turn into gradients, as if something has gone wrong with the mapping.

Screenshots:
The expected result (which I get without attribute aliasing): https://ibb.co/kHEogv
The result with aliasing: https://ibb.co/d9cfuF

Code:
/* OpenSceneGraph example, osgmultiplerendertargets.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/ColorMask>
#include <osg/Material>
#include <osg/Capability>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgViewer/Viewer>

#include <iostream>
#include <stdio.h>

#include <osg/PolygonMode>
//#include "RenderingUtility.h" //to easily view intermediate textures
//
// Below is relatively straight forward example of using the OpenGL multiple render targets (MRT) extension
// to FrameBufferObjects/GLSL shaders.
//
// Another, more sophisticated MRT example can be found in the osgstereomatch example.
//

osg::Geode *createScreenQuad(float width,
                                           float height,
                                           float scale,
                                           osg::Vec3 corner)
{
      osg::Geometry* geom = osg::createTexturedQuadGeometry(
            corner,
            osg::Vec3(width, 0, 0),
            osg::Vec3(0, height, 0),
            0,
            0,
            scale,
            scale);
      osg::ref_ptr<osg::Geode> quad = new osg::Geode;
      quad->addDrawable(geom);
      int values = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED;
      quad->getOrCreateStateSet()->setAttribute(
            new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK,
                                           osg::PolygonMode::FILL),
            values);
      quad->getOrCreateStateSet()->setMode(GL_LIGHTING, values);
      return quad.release();
}


osg::Camera *createHUDCamera(double left=0,
                                           double right=1,
                                           double bottom=0,
                                           double top=1)
{
      osg::ref_ptr<osg::Camera> camera = new osg::Camera;
      camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
      camera->setClearMask(GL_DEPTH_BUFFER_BIT);
      camera->setRenderOrder(osg::Camera::POST_RENDER);
      camera->setAllowEventFocus(false);
      camera->setProjectionMatrix(osg::Matrix::ortho2D(left, right, bottom, top));
      camera->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
      return camera.release();
}

osg::ref_ptr<osg::Camera> createTextureDisplayQuad(
      const osg::Vec3 &pos,
      osg::StateAttribute *tex,
      float scale,
      float width=0.3,
      float height=0.2)
{
      osg::ref_ptr<osg::Camera> hc = createHUDCamera();
      hc->addChild(createScreenQuad(width, height, scale, pos));
      hc->getOrCreateStateSet()->setTextureAttributeAndModes(0, tex);
      return hc;
}


// The callback modifies an input image.
struct MyCameraPostDrawCallback : public osg::Camera::DrawCallback
{
    MyCameraPostDrawCallback(osg::Image* image):
        _image(image)
    {
    }

    virtual void operator () (const osg::Camera& /*camera*/) const
    {
        if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE)
        {
            // we'll pick out the center 1/2 of the whole image,
            int column_start = _image->s()/4;
            int column_end = 3*column_start;

            int row_start = _image->t()/4;
            int row_end = 3*row_start;

            // and then halve their contribution
            for(int r=row_start; r<row_end; ++r)
            {
                unsigned char* data = _image->data(column_start, r);
                for(int c=column_start; c<column_end; ++c)
                {
                    (*data) = (*data)/2; ++data;
                    (*data) = (*data)/2; ++data;
                    (*data) = (*data)/2; ++data;
                    (*data) = 255; ++data;
                }
            }

            _image->dirty();
        }
        else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT)
        {
            // we'll pick out the center 1/2 of the whole image,
            int column_start = _image->s()/4;
            int column_end = 3*column_start;

            int row_start = _image->t()/4;
            int row_end = 3*row_start;

            // and then halve their contribution
            for(int r=row_start; r<row_end; ++r)
            {
                float* data = (float*)_image->data(column_start, r);
                for(int c=column_start; c<column_end; ++c)
                {
                    (*data) = (*data)/2.0; ++data;
                    (*data) = (*data)/2.0; ++data;
                    (*data) = (*data)/2.0; ++data;
                    (*data) = 1.0f; ++data;
                }
            }

            _image->dirty();

            //print out the first three values
            float* data = (float*)_image->data(0, 0);
            fprintf(stderr,"Float pixel data: r %e g %e b %e\n", data[0], data[1], data[2]);
        }
    }

    osg::Image* _image;
};

#define NUM_TEXTURES 2

// The quad geometry is used by the render to texture camera to generate multiple textures.
osg::Group* createRTTQuad(unsigned int tex_width, unsigned int tex_height, bool useHDR)
{
    osg::Group *top_group = new osg::Group;

    osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;

    osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
    // counter-clockwise
    quad_coords->push_back(osg::Vec3d(0, 0, -1));
    quad_coords->push_back(osg::Vec3d(1, 0, -1));
    quad_coords->push_back(osg::Vec3d(1, 1, -1));
    quad_coords->push_back(osg::Vec3d(0, 1, -1));

    osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
    quad_tcoords->push_back(osg::Vec2(0, 0));
    quad_tcoords->push_back(osg::Vec2(tex_width, 0));
    quad_tcoords->push_back(osg::Vec2(tex_width, tex_height));
    quad_tcoords->push_back(osg::Vec2(0, tex_height));

    osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
    osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);

    osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
    quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

    quad_geom->setVertexArray(quad_coords.get());
    quad_geom->setTexCoordArray(0, quad_tcoords.get());
    quad_geom->addPrimitiveSet(quad_da.get());
    quad_geom->setColorArray(quad_colors.get(), osg::Array::BIND_OVERALL);

    osg::StateSet *stateset = quad_geom->getOrCreateStateSet();
    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);

    stateset->addUniform(new osg::Uniform("width", (int)tex_width));

    // Attach shader, glFragData is used to create data for multiple render targets

    if (useHDR) {
        static const char *shaderSource = {
            "uniform int width;"
            "void main(void)\n"
            "{\n"
            "    gl_FragData[0] = vec4(-1e-12,0,0,1);\n"
            "    gl_FragData[1] = vec4(0,1e-12,0,1);\n"
            "    gl_FragData[2] = vec4(0,0,1e-12,1);\n"
            "    gl_FragData[3] = vec4(0,0,1e-12,1);\n"
            "}\n"
        };

        osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
        osg::ref_ptr<osg::Program> program = new osg::Program;
        program->addShader(fshader.get());
        stateset->setAttributeAndModes(program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
    } else {
            static const char *shaderSource = {
            "uniform int width;"
            "void main(void)\n"
            "{\n"
            "    gl_FragData[0] = vec4(1,0,0,1);\n"
            "    gl_FragData[1] = vec4(0,1,0,1);\n"
            "    gl_FragData[2] = vec4(0,0,1,1);\n"
            "    gl_FragData[3] = vec4(0,0,1,1);\n"
            "}\n"
        };

        osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
        osg::ref_ptr<osg::Program> program = new osg::Program;
        program->addShader(fshader.get());
        stateset->setAttributeAndModes(program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
    }

    quad_geode->addDrawable(quad_geom.get());

    top_group->addChild(quad_geode.get());

    return top_group;
}


      osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0}; //moved to global scope to easily view intermediate textures
// Here a scene consisting of a single quad is created. This scene is viewed by the screen camera.
// The quad is textured using a shader and the multiple textures generated in the RTT stage.
osg::Node* createScene(osg::Node* cam_subgraph, unsigned int tex_width, unsigned int tex_height, bool useHDR, bool useImage, bool useMultiSample)
{
    if (!cam_subgraph) return 0;

    // create a group to contain the quad and the pre render camera.
    osg::Group* parent = new osg::Group;

    // textures to render to and to use for texturing of the final quad
      //osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0,0,0};

    for (int i=0;i<NUM_TEXTURES;i++) {
        textureRect[i] = new osg::TextureRectangle;
        textureRect[i]->setTextureSize(tex_width, tex_height);
        textureRect[i]->setInternalFormat(GL_RGBA);
        textureRect[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
        textureRect[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);

        if (useHDR)
        {
            // Default HDR format
            textureRect[i]->setInternalFormat(GL_RGBA32F_ARB);

            // GL_FLOAT_RGBA32_NV might be supported on pre 8-series GPUs
            //textureRect[i]->setInternalFormat(GL_FLOAT_RGBA32_NV);

            // GL_RGBA16F_ARB can be used with this example,
            // but modify e-12 and e12 in the shaders accordingly
            //textureRect[i]->setInternalFormat(GL_RGBA16F_ARB);

            textureRect[i]->setSourceFormat(GL_RGBA);
            textureRect[i]->setSourceType(GL_FLOAT);
        }
    }

    // first create the geometry of the quad
    {
        osg::Geometry* polyGeom = new osg::Geometry();

        polyGeom->setSupportsDisplayList(false);

        osg::Vec3Array* vertices = new osg::Vec3Array;
        osg::Vec2Array* texcoords = new osg::Vec2Array;

        vertices->push_back(osg::Vec3d(0,0,0));
        texcoords->push_back(osg::Vec2(0,0));

        vertices->push_back(osg::Vec3d(1,0,0));
        texcoords->push_back(osg::Vec2(tex_width,0));

        vertices->push_back(osg::Vec3d(1,0,1));
        texcoords->push_back(osg::Vec2(tex_width,tex_height));

        vertices->push_back(osg::Vec3d(0,0,1));
        texcoords->push_back(osg::Vec2(0,tex_height));

        polyGeom->setVertexArray(vertices);
        polyGeom->setTexCoordArray(0,texcoords);

        osg::Vec4Array* colors = new osg::Vec4Array;
        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
        polyGeom->setColorArray(colors, osg::Array::BIND_OVERALL);

        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,vertices->size()));

        // now we need to add the textures (generated by RTT) to the Drawable.
        osg::StateSet* stateset = new osg::StateSet;
        for (int i=0;i<NUM_TEXTURES;i++){
            stateset->setTextureAttributeAndModes(i, textureRect[i], osg::StateAttribute::ON);
        }

        polyGeom->setStateSet(stateset);

        // Attach a shader to the final quad to combine the input textures.
        if (useHDR) {
            static const char *shaderSource = {
                "uniform sampler2DRect textureID0;\n"
                "uniform sampler2DRect textureID1;\n"
                "uniform sampler2DRect textureID2;\n"
                "uniform sampler2DRect textureID3;\n"
                "uniform float width;\n"
                "uniform float height; \n"
                "void main(void)\n"
                "{\n"
                "    gl_FragData[0] = \n"
                "     vec4(  -1e12 * texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + \n"
                "     vec4(   1e12 * texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + \n"
                "     vec4(   1e12 * texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + \n"
                "     vec4(-0.5e12 * texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1);  \n"
                "}\n"
            };
            osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
            osg::ref_ptr<osg::Program> program = new osg::Program;
            program->addShader( fshader.get());
            stateset->setAttributeAndModes( program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
        } else {
            static const char *shaderSource = {
                "uniform sampler2DRect textureID0;\n"
                "uniform sampler2DRect textureID1;\n"
                "uniform sampler2DRect textureID2;\n"
                "uniform sampler2DRect textureID3;\n"
                "void main(void)\n"
                "{\n"
                "    gl_FragData[0] = \n"
                        "          vec4(texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + \n"
                "          vec4(texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + \n"
                "          vec4(texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + \n"
                "     -0.5*vec4(texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1);  \n"
                "}\n"
            };
            osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
            osg::ref_ptr<osg::Program> program = new osg::Program;
            program->addShader( fshader.get());
            stateset->setAttributeAndModes( program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );

        }

        stateset->addUniform(new osg::Uniform("textureID0", 0));
        stateset->addUniform(new osg::Uniform("textureID1", 1));
        stateset->addUniform(new osg::Uniform("textureID2", 2));
        stateset->addUniform(new osg::Uniform("textureID3", 3));

        //stateset->setDataVariance(osg::Object::DYNAMIC);

        osg::Geode* geode = new osg::Geode();
        geode->addDrawable(polyGeom);

        parent->addChild(geode);
    }

    // now create the camera to do the multiple render to texture
    {
        osg::Camera* camera = new osg::Camera;

        // set up the background color and clear mask.
        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // the camera is going to look at our input quad
        camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
        camera->setViewMatrix(osg::Matrix::identity());

        // set viewport
        camera->setViewport(0, 0, tex_width, tex_height);

        // set the camera to render before the main camera.
        camera->setRenderOrder(osg::Camera::PRE_RENDER);

        // tell the camera to use OpenGL frame buffer objects
        camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

        // attach the textures to use
        for (int i=0; i<NUM_TEXTURES; i++) {
            if (useMultiSample)
                camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), textureRect[i], 0, 0, false, 4, 4);
            else
                camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), textureRect[i]);


        }

#if 0
        // test for new glEnablei/glDisablei functionality.
        camera->getOrCreateStateSet()->setAttribute(new osg::Enablei(GL_BLEND, 0));
        camera->getOrCreateStateSet()->setAttribute(new osg::Disablei(GL_BLEND, 1));
#endif

        // we can also read back any of the targets as an image, modify this image and push it back
        if (useImage) {
            // which texture to get the image from
            const int tex_to_get = 0;

            osg::Image* image = new osg::Image;
            if (useHDR) {
                image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT);
            } else {
                image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
            }

            // attach the image so its copied on each frame.
            camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0 + tex_to_get), image);

            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));

            // push back the image to the texture
            textureRect[tex_to_get]->setImage(0, image);
        }

        // add the subgraph to render
        camera->addChild(cam_subgraph);

        parent->addChild(camera);
    }

    return parent;
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " demonstrates the use of multiple render targets (MRT) with frame buffer objects (FBOs). A render to texture (RTT) camera is used to render to four textures using a single shader. The four textures are then combined to texture the viewed geometry.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information.");
    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
    arguments.getApplicationUsage()->addCommandLineOption("--image","Render one of the targets to an image, then apply a post draw callback to modify it and use this image to update the final texture. Print some texture values when using HDR.");
    arguments.getApplicationUsage()->addCommandLineOption("--hdr","Use high dynamic range (HDR). Create floating point textures to render to.");

    // construct the viewer.
    osgViewer::Viewer viewer(arguments);

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    unsigned tex_width = 512;
    unsigned tex_height = 512;
    while (arguments.read("--width", tex_width)) {}
    while (arguments.read("--height", tex_height)) {}

    bool useHDR = false;
    while (arguments.read("--hdr")) { useHDR = true; }

    bool useImage = false;
    while (arguments.read("--image")) { useImage = true; }

    bool useMultiSample = false;
    while (arguments.read("--ms")) { useMultiSample = true; }

    osg::Group* subGraph = createRTTQuad(tex_width, tex_height, useHDR);

    osg::Group* rootNode = new osg::Group();
    rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage, useMultiSample));

      rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage, useMultiSample));


   //Some code to view the intermediate textures
       osg::ref_ptr<osg::Camera> testTex =
            createTextureDisplayQuad(osg::Vec3(0, 0.7, 0),
                                                 textureRect[0],
                                                 tex_width);
osg::ref_ptr<osg::Camera> testTex2 =
            createTextureDisplayQuad(osg::Vec3(0, 0.35, 0),
                                                 textureRect[1],
                                                 tex_width);

rootNode->addChild(testTex);
rootNode->addChild(testTex2);

      // add model to the viewer.
      viewer.setSceneData( rootNode );
      viewer.realize();
      viewer.getCamera()->getGraphicsContext()->getState()->setUseVertexAttributeAliasing(true);

      return viewer.run();
}




Thank you!!

Cheers,
antiro[/code]
Back to top
View user's profile Send private message
SMesserschmidt (Sebastian Messerschmidt)
Forum Moderator


Joined: 10 Sep 2013
Posts: 796

PostPosted: Sat Sep 02, 2017 9:33 pm    Post subject:
using modern shaders with osg - setting vertex attribute layout
Reply with quote

Hi. Sorry I don't on my computer right now, but it seems you are not providing vertex shaders. I'm not sure, but that might cause trouble. I'll get back to the issue tommorow or on Monday.

Cheers
Sebastian
--
Sent from my Android phone with GMX Mail. Please excuse my brevity.
On 9/2/17, 21:36 antiro black <> wrote:
Quote:

Hi Sebastian,
I'm compiling under debian jessie 64 bits and am running a NVIDIA GTX 970. The drivers have been updates recently and I am running version 384.69 now.
I included a compilable minimal example based on the osgmultiplerendertargets example. Without VertexAttributeAliasing it generates two texture using MRT, a red and a green one, it then combines these in a second pass to generate the final texture (yellow). (The red and green intermediate textures are shown in small quads to the side.)
When I enable the attribute aliasing (as in the included code), the two textures generated in the MRT pass turn into gradients, as if something has gone wrong with the mapping.
Screenshots: The expected result (which I get without attribute aliasing): https://ibb.co/kHEogv The result with aliasing: https://ibb.co/d9cfuF
Code: /* OpenSceneGraph example, osgmultiplerendertargets. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
#include <osg/GLExtensions> #include <osg/Node> #include <osg/Geometry> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/Texture2D> #include <osg/TextureRectangle> #include <osg/ColorMask> #include <osg/Material> #include <osg/Capability>
#include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator>
#include <osgViewer/Viewer>
#include <iostream> #include <stdio.h>
#include <osg/PolygonMode> //#include "RenderingUtility.h" //to easily view intermediate textures // // Below is relatively straight forward example of using the OpenGL multiple render targets (MRT) extension // to FrameBufferObjects/GLSL shaders. // // Another, more sophisticated MRT example can be found in the osgstereomatch example. //
osg::Geode *createScreenQuad(float width, float height, float scale, osg::Vec3 corner) { osg::Geometry* geom = osg::createTexturedQuadGeometry( corner, osg::Vec3(width, 0, 0), osg::Vec3(0, height, 0), 0, 0, scale, scale); osg::ref_ptr<osg::Geode> quad = new osg::Geode; quad->addDrawable(geom); int values = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED; quad->getOrCreateStateSet()->setAttribute( new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::FILL), values); quad->getOrCreateStateSet()->setMode(GL_LIGHTING, values); return quad.release(); }
osg::Camera *createHUDCamera(double left=0, double right=1, double bottom=0, double top=1) { osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); camera->setClearMask(GL_DEPTH_BUFFER_BIT); camera->setRenderOrder(osg::Camera::POST_RENDER); camera->setAllowEventFocus(false); camera->setProjectionMatrix(osg::Matrix::ortho2D(left, right, bottom, top)); camera->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); return camera.release(); }
osg::ref_ptr<osg::Camera> createTextureDisplayQuad( const osg::Vec3 &pos, osg::StateAttribute *tex, float scale, float width=0.3, float height=0.2) { osg::ref_ptr<osg::Camera> hc = createHUDCamera(); hc->addChild(createScreenQuad(width, height, scale, pos)); hc->getOrCreateStateSet()->setTextureAttributeAndModes(0, tex); return hc; }
// The callback modifies an input image. struct MyCameraPostDrawCallback : public osg::Camera::DrawCallback { MyCameraPostDrawCallback(osg::Image* image): _image(image) { }
virtual void operator () (const osg::Camera& /*camera*/) const { if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE) { // we'll pick out the center 1/2 of the whole image, int column_start = _image->s()/4; int column_end = 3*column_start;
int row_start = _image->t()/4; int row_end = 3*row_start;
// and then halve their contribution for(int r=row_start; r<row_end; ++r) { unsigned char* data = _image->data(column_start, r); for(int c=column_start; c<column_end; ++c) { (*data) = (*data)/2; ++data; (*data) = (*data)/2; ++data; (*data) = (*data)/2; ++data; (*data) = 255; ++data; } }
_image->dirty(); } else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT) { // we'll pick out the center 1/2 of the whole image, int column_start = _image->s()/4; int column_end = 3*column_start;
int row_start = _image->t()/4; int row_end = 3*row_start;
// and then halve their contribution for(int r=row_start; r<row_end; ++r) { float* data = (float*)_image->data(column_start, r); for(int c=column_start; c<column_end; ++c) { (*data) = (*data)/2.0; ++data; (*data) = (*data)/2.0; ++data; (*data) = (*data)/2.0; ++data; (*data) = 1.0f; ++data; } }
_image->dirty();
//print out the first three values float* data = (float*)_image->data(0, 0); fprintf(stderr,"Float pixel data: r %e g %e b %en", data[0], data[1], data[2]); } }
osg::Image* _image; };
#define NUM_TEXTURES 2
// The quad geometry is used by the render to texture camera to generate multiple textures. osg::Group* createRTTQuad(unsigned int tex_width, unsigned int tex_height, bool useHDR) { osg::Group *top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords // counter-clockwise quad_coords->push_back(osg::Vec3d(0, 0, -1)); quad_coords->push_back(osg::Vec3d(1, 0, -1)); quad_coords->push_back(osg::Vec3d(1, 1, -1)); quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords quad_tcoords->push_back(osg::Vec2(0, 0)); quad_tcoords->push_back(osg::Vec2(tex_width, 0)); quad_tcoords->push_back(osg::Vec2(tex_width, tex_height)); quad_tcoords->push_back(osg::Vec2(0, tex_height));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry; osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array; quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get()); quad_geom->setTexCoordArray(0, quad_tcoords.get()); quad_geom->addPrimitiveSet(quad_da.get()); quad_geom->setColorArray(quad_colors.get(), osg::Array::BIND_OVERALL);
osg::StateSet *stateset = quad_geom->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
stateset->addUniform(new osg::Uniform("width", (int)tex_width));
// Attach shader, glFragData is used to create data for multiple render targets
if (useHDR) { static const char *shaderSource = { "uniform int width;" "void main(void)n" "{n" " gl_FragData[0] = vec4(-1e-12,0,0,1);n" " gl_FragData[1] = vec4(0,1e-12,0,1);n" " gl_FragData[2] = vec4(0,0,1e-12,1);n" " gl_FragData[3] = vec4(0,0,1e-12,1);n" "}n" };
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource); osg::ref_ptr<osg::Program> program = new osg::Program; program->addShader(fshader.get()); stateset->setAttributeAndModes(program.get(), osg::StateAttribute:ShockedN | osg::StateAttribute::OVERRIDE ); } else { static const char *shaderSource = { "uniform int width;" "void main(void)n" "{n" " gl_FragData[0] = vec4(1,0,0,1);n" " gl_FragData[1] = vec4(0,1,0,1);n" " gl_FragData[2] = vec4(0,0,1,1);n" " gl_FragData[3] = vec4(0,0,1,1);n" "}n" };
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource); osg::ref_ptr<osg::Program> program = new osg::Program; program->addShader(fshader.get()); stateset->setAttributeAndModes(program.get(), osg::StateAttribute:ShockedN | osg::StateAttribute::OVERRIDE ); }
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group; }
osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0}; //moved to global scope to easily view intermediate textures // Here a scene consisting of a single quad is created. This scene is viewed by the screen camera. // The quad is textured using a shader and the multiple textures generated in the RTT stage. osg::Node* createScene(osg::Node* cam_subgraph, unsigned int tex_width, unsigned int tex_height, bool useHDR, bool useImage, bool useMultiSample) { if (!cam_subgraph) return 0;
// create a group to contain the quad and the pre render camera. osg::Group* parent = new osg::Group;
// textures to render to and to use for texturing of the final quad //osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0,0,0};
for (int i=0;i<NUM_TEXTURES;i++) { textureRect[i] = new osg::TextureRectangle; textureRect[i]->setTextureSize(tex_width, tex_height); textureRect[i]->setInternalFormat(GL_RGBA); textureRect[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); textureRect[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
if (useHDR) { // Default HDR format textureRect[i]->setInternalFormat(GL_RGBA32F_ARB);
// GL_FLOAT_RGBA32_NV might be supported on pre 8-series GPUs //textureRect[i]->setInternalFormat(GL_FLOAT_RGBA32_NV);
// GL_RGBA16F_ARB can be used with this example, // but modify e-12 and e12 in the shaders accordingly //textureRect[i]->setInternalFormat(GL_RGBA16F_ARB);
textureRect[i]->setSourceFormat(GL_RGBA); textureRect[i]->setSourceType(GL_FLOAT); } }
// first create the geometry of the quad { osg::Geometry* polyGeom = new osg::Geometry();
polyGeom->setSupportsDisplayList(false);
osg::Vec3Array* vertices = new osg::Vec3Array; osg::Vec2Array* texcoords = new osg::Vec2Array;
vertices->push_back(osg::Vec3d(0,0,0)); texcoords->push_back(osg::Vec2(0,0));
vertices->push_back(osg::Vec3d(1,0,0)); texcoords->push_back(osg::Vec2(tex_width,0));
vertices->push_back(osg::Vec3d(1,0,1)); texcoords->push_back(osg::Vec2(tex_width,tex_height));
vertices->push_back(osg::Vec3d(0,0,1)); texcoords->push_back(osg::Vec2(0,tex_height));
polyGeom->setVertexArray(vertices); polyGeom->setTexCoordArray(0,texcoords);
osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); polyGeom->setColorArray(colors, osg::Array::BIND_OVERALL);
polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,vertices->size()));
// now we need to add the textures (generated by RTT) to the Drawable. osg::StateSet* stateset = new osg::StateSet; for (int i=0;i<NUM_TEXTURES;i++){ stateset->setTextureAttributeAndModes(i, textureRect[i], osg::StateAttribute:ShockedN); }
polyGeom->setStateSet(stateset);
// Attach a shader to the final quad to combine the input textures. if (useHDR) { static const char *shaderSource = { "uniform sampler2DRect textureID0;n" "uniform sampler2DRect textureID1;n" "uniform sampler2DRect textureID2;n" "uniform sampler2DRect textureID3;n" "uniform float width;n" "uniform float height; n" "void main(void)n" "{n" " gl_FragData[0] = n" " vec4( -1e12 * texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + n" " vec4( 1e12 * texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + n" " vec4( 1e12 * texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + n" " vec4(-0.5e12 * texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1); n" "}n" }; osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource); osg::ref_ptr<osg::Program> program = new osg::Program; program->addShader( fshader.get()); stateset->setAttributeAndModes( program.get(), osg::StateAttribute:ShockedN | osg::StateAttribute::OVERRIDE ); } else { static const char *shaderSource = { "uniform sampler2DRect textureID0;n" "uniform sampler2DRect textureID1;n" "uniform sampler2DRect textureID2;n" "uniform sampler2DRect textureID3;n" "void main(void)n" "{n" " gl_FragData[0] = n" " vec4(texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + n" " vec4(texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + n" " vec4(texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + n" " -0.5*vec4(texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1); n" "}n" }; osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource); osg::ref_ptr<osg::Program> program = new osg::Program; program->addShader( fshader.get()); stateset->setAttributeAndModes( program.get(), osg::StateAttribute:ShockedN | osg::StateAttribute::OVERRIDE );
}
stateset->addUniform(new osg::Uniform("textureID0", 0)); stateset->addUniform(new osg::Uniform("textureID1", 1)); stateset->addUniform(new osg::Uniform("textureID2", 2)); stateset->addUniform(new osg::Uniform("textureID3", 3));
//stateset->setDataVariance(osg::Object::DYNAMIC);
osg::Geode* geode = new osg::Geode(); geode->addDrawable(polyGeom);
parent->addChild(geode); }
// now create the camera to do the multiple render to texture { osg::Camera* camera = new osg::Camera;
// set up the background color and clear mask. camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f)); camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// the camera is going to look at our input quad camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1)); camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); camera->setViewMatrix(osg::Matrix::identity());
// set viewport camera->setViewport(0, 0, tex_width, tex_height);
// set the camera to render before the main camera. camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer objects camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach the textures to use for (int i=0; i<NUM_TEXTURES; i++) { if (useMultiSample) camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), textureRect[i], 0, 0, false, 4, 4); else camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), textureRect[i]);
}
#if 0 // test for new glEnablei/glDisablei functionality. camera->getOrCreateStateSet()->setAttribute(new osg::Enablei(GL_BLEND, 0)); camera->getOrCreateStateSet()->setAttribute(new osg::Disablei(GL_BLEND, 1)); #endif
// we can also read back any of the targets as an image, modify this image and push it back if (useImage) { // which texture to get the image from const int tex_to_get = 0;
osg::Image* image = new osg::Image; if (useHDR) { image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT); } else { image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE); }
// attach the image so its copied on each frame. camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0 + tex_to_get), image);
camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
// push back the image to the texture textureRect[tex_to_get]->setImage(0, image); }
// add the subgraph to render camera->addChild(cam_subgraph);
parent->addChild(camera); }
return parent; }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " demonstrates the use of multiple render targets (MRT) with frame buffer objects (FBOs). A render to texture (RTT) camera is used to render to four textures using a single shader. The four textures are then combined to texture the viewed geometry."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information."); arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--image","Render one of the targets to an image, then apply a post draw callback to modify it and use this image to update the final texture. Print some texture values when using HDR."); arguments.getApplicationUsage()->addCommandLineOption("--hdr","Use high dynamic range (HDR). Create floating point textures to render to.");
// construct the viewer. osgViewer::Viewer viewer(arguments);
// if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; }
unsigned tex_width = 512; unsigned tex_height = 512; while (arguments.read("--width", tex_width)) {} while (arguments.read("--height", tex_height)) {}
bool useHDR = false; while (arguments.read("--hdr")) { useHDR = true; }
bool useImage = false; while (arguments.read("--image")) { useImage = true; }
bool useMultiSample = false; while (arguments.read("--ms")) { useMultiSample = true; }
osg::Group* subGraph = createRTTQuad(tex_width, tex_height, useHDR);
osg::Group* rootNode = new osg::Group(); rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage, useMultiSample));
rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage, useMultiSample));
//Some code to view the intermediate textures osg::ref_ptr<osg::Camera> testTex = createTextureDisplayQuad(osg::Vec3(0, 0.7, 0), textureRect[0], tex_width); osg::ref_ptr<osg::Camera> testTex2 = createTextureDisplayQuad(osg::Vec3(0, 0.35, 0), textureRect[1], tex_width);
rootNode->addChild(testTex); rootNode->addChild(testTex2);
// add model to the viewer. viewer.setSceneData( rootNode ); viewer.realize(); viewer.getCamera()->getGraphicsContext()->getState()->setUseVertexAttributeAliasing(true);
return viewer.run(); }
Thank you!!
Cheers, antiro[/code]
------------------ Read this topic online here: http://forum.openscenegraph.org/viewtopic.php?p=71613#71613
_______________________________________________ osg-users mailing list (
Only registered users can see emails on this board!
Get registred or enter the forums!
) http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org


------------------
Post generated by Mail2Forum
Back to top
View user's profile Send private message
SMesserschmidt (Sebastian Messerschmidt)
Forum Moderator


Joined: 10 Sep 2013
Posts: 796

PostPosted: Sun Sep 03, 2017 2:25 pm    Post subject:
using modern shaders with osg - setting vertex attribute layout
Reply with quote

Hi Antiro,

I've cleaned up the example (removed the image mod, hdr etc.) and
supplied vertex shaders (once you move towards aliasing, you basically
need to replace ALL fixed function stuff).

You were right about the viewer.realize before setting up the aliasing
however. This is due the the context not being available before
realizing it.


(Some additonal notes: you don't need to use texture rectangle. Instead
in deferred steps simply use texelFetch in conjunction with textureSize
on Texture2D targets.
)


Below you find the adapted example, giving the desired result:
#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/ColorMask>
#include <osg/Material>
#include <osg/Capability>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgViewer/Viewer>

#include <iostream>
#include <stdio.h>

#include <osg/PolygonMode>

static std::string vertex_shader =
{
"#version 330\n"
"layout(location = 0) in vec4 osg_Vertex; \n"
"layout(location = 1) in vec3 osg_Normal; \n"
"layout(location = 2) in vec4 osg_Color; \n"
"layout(location = 3) in vec4 osg_MultiTexCoord0; \n"
"uniform mat4 osg_ModelViewProjectionMatrix; \n"
"out vec2 texture_coords;"
"void main(void) \n"
"{ \n"
"texture_coords = osg_MultiTexCoord0.st;\n"
" gl_Position = osg_ModelViewProjectionMatrix * osg_Vertex; \n"
"}\n"
};

static std::string def_frag_shader =
{
"#version 330\n"
"uniform sampler2DRect textureID0;\n"

"in vec2 texture_coords;"
"out vec4 target;"
"void main(void)\n"
"{\n"
" target = vec4(texture( textureID0, texture_coords.st ).rgb, 1); \n"
"}\n"
};

osg::Geode *createScreenQuad(float width,
float height,
float scale,
osg::Vec3 corner)
{
osg::Geometry* geom = osg::createTexturedQuadGeometry(
corner,
osg::Vec3(width, 0, 0),
osg::Vec3(0, height, 0),
0,
0,
scale,
scale);
osg::ref_ptr<osg::Geode> quad = new osg::Geode;
quad->addDrawable(geom);
int values = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED;
quad->getOrCreateStateSet()->setAttribute(
new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK,
osg::PolygonMode::FILL),
values);
quad->getOrCreateStateSet()->setMode(GL_LIGHTING, values);
return quad.release();
}


osg::Camera *createHUDCamera(double left = 0,
double right = 1,
double bottom = 0,
double top = 1)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
camera->setClearMask(GL_DEPTH_BUFFER_BIT);
camera->setRenderOrder(osg::Camera::POST_RENDER);
camera->setAllowEventFocus(false);
camera->setProjectionMatrix(osg::Matrix::ortho2D(left, right, bottom,
top));
camera->getOrCreateStateSet()->setMode(GL_LIGHTING,
osg::StateAttribute::OFF);
return camera.release();
}

osg::ref_ptr<osg::Camera> createTextureDisplayQuad(
const osg::Vec3 &pos,
osg::StateAttribute *tex,
float scale,
float width = 0.3,
float height = 0.2)
{
osg::ref_ptr<osg::Camera> hc = createHUDCamera();
hc->addChild(createScreenQuad(width, height, scale, pos));
hc->getOrCreateStateSet()->setTextureAttributeAndModes(0, tex);
//need shader!!

osg::ref_ptr<osg::Program> program = new osg::Program;
osg::ref_ptr<osg::Shader> vshader = new
osg::Shader(osg::Shader::VERTEX, vertex_shader);
osg::ref_ptr<osg::Shader> fshader = new
osg::Shader(osg::Shader::FRAGMENT, def_frag_shader);
program->addShader(vshader.get());
program->addShader(fshader.get());
hc->getOrCreateStateSet()->setAttributeAndModes(program.get(),
osg::StateAttribute:ShockedN | osg::StateAttribute::OVERRIDE);

return hc;
}


#define NUM_TEXTURES 2

// The quad geometry is used by the render to texture camera to generate
multiple textures.
osg::Group* createRTTQuad(unsigned int tex_width, unsigned int
tex_height, bool useHDR)
{
osg::Group *top_group = new osg::Group;

osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;

osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; //
vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));

osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; //
texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(tex_width, 0));
quad_tcoords->push_back(osg::Vec2(tex_width, tex_height));
quad_tcoords->push_back(osg::Vec2(0, tex_height));

osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new
osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4);

osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));

quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get(), osg::Array::BIND_OVERALL);

osg::StateSet *stateset = quad_geom->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

stateset->addUniform(new osg::Uniform("width", (int)tex_width));

// Attach shader, glFragData is used to create data for multiple render
targets

{
static const char *shaderSource = {
"uniform int width;"
"void main(void)\n"
"{\n"
" gl_FragData[0] = vec4(1,0,0,1);\n"
" gl_FragData[1] = vec4(0,1,0,1);\n"
" gl_FragData[2] = vec4(0,0,1,1);\n"
" gl_FragData[3] = vec4(0,0,1,1);\n"
"}\n"
};

osg::ref_ptr<osg::Shader> fshader = new
osg::Shader(osg::Shader::FRAGMENT, shaderSource);
osg::ref_ptr<osg::Program> program = new osg::Program;
osg::ref_ptr<osg::Shader> vshader = new
osg::Shader(osg::Shader::VERTEX, vertex_shader);
program->addShader(vshader.get());

program->addShader(fshader.get());
stateset->setAttributeAndModes(program.get(), osg::StateAttribute:ShockedN
| osg::StateAttribute::OVERRIDE);
}

quad_geode->addDrawable(quad_geom.get());

top_group->addChild(quad_geode.get());

return top_group;
}


osg::TextureRectangle* textureRect[NUM_TEXTURES] = { 0,0 }; //moved to
global scope to easily view intermediate textures
// Here a scene consisting of a single quad is created.
This scene is viewed by the screen camera.
// The quad is textured using a shader and the multiple
textures generated in the RTT stage.
osg::Node* createScene(osg::Node* cam_subgraph, unsigned int tex_width,
unsigned int tex_height, bool useHDR, bool useImage, bool useMultiSample)
{
if (!cam_subgraph) return 0;

// create a group to contain the quad and the pre render camera.
osg::Group* parent = new osg::Group;

// textures to render to and to use for texturing of the final quad
//osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0,0,0};

for (int i = 0; i < NUM_TEXTURES; i++)
{
textureRect[i] = new osg::TextureRectangle;
textureRect[i]->setTextureSize(tex_width, tex_height);
textureRect[i]->setInternalFormat(GL_RGBA);
textureRect[i]->setFilter(osg::Texture2D::MIN_FILTER,
osg::Texture2D::LINEAR);
textureRect[i]->setFilter(osg::Texture2D::MAG_FILTER,
osg::Texture2D::LINEAR);
}

// first create the geometry of the quad
{
osg::Geometry* polyGeom = new osg::Geometry();

polyGeom->setSupportsDisplayList(false);

osg::Vec3Array* vertices = new osg::Vec3Array;
osg::Vec2Array* texcoords = new osg::Vec2Array;

vertices->push_back(osg::Vec3d(0, 0, 0));
texcoords->push_back(osg::Vec2(0, 0));

vertices->push_back(osg::Vec3d(1, 0, 0));
texcoords->push_back(osg::Vec2(tex_width, 0));

vertices->push_back(osg::Vec3d(1, 0, 1));
texcoords->push_back(osg::Vec2(tex_width, tex_height));

vertices->push_back(osg::Vec3d(0, 0, 1));
texcoords->push_back(osg::Vec2(0, tex_height));

polyGeom->setVertexArray(vertices);
polyGeom->setTexCoordArray(0, texcoords);

osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
polyGeom->setColorArray(colors, osg::Array::BIND_OVERALL);

polyGeom->addPrimitiveSet(new
osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertices->size()));

// now we need to add the textures (generated by RTT) to the Drawable.
osg::StateSet* stateset = new osg::StateSet;
for (int i = 0; i < NUM_TEXTURES; i++) {
stateset->setTextureAttributeAndModes(i, textureRect[i],
osg::StateAttribute:ShockedN);
}

polyGeom->setStateSet(stateset);

// Attach a shader to the final quad to combine the input textures.
{
static const char *shaderSource = {
"#version 330\n"
"uniform sampler2DRect textureID0;\n"
"uniform sampler2DRect textureID1;\n"
"uniform sampler2DRect textureID2;\n"
"uniform sampler2DRect textureID3;\n"

"in vec2 texture_coords;"
"void main(void)\n"
"{\n"
" gl_FragData[0] = \n"
" vec4(texture2DRect( textureID0, texture_coords.st ).rgb,
1) + \n"
" vec4(texture2DRect( textureID1, texture_coords.st ).rgb,
1) + \n"
" vec4(texture2DRect( textureID2, texture_coords.st ).rgb,
1) + \n"
" -0.5*vec4(texture2DRect( textureID3, texture_coords.st ).rgb,
1); \n"
"}\n"
};
osg::ref_ptr<osg::Shader> fshader = new
osg::Shader(osg::Shader::FRAGMENT, shaderSource);
osg::ref_ptr<osg::Program> program = new osg::Program;
osg::ref_ptr<osg::Shader> vshader = new
osg::Shader(osg::Shader::VERTEX, vertex_shader);
program->addShader(vshader.get());

program->addShader(fshader.get());
stateset->setAttributeAndModes(program.get(), osg::StateAttribute:ShockedN
| osg::StateAttribute::OVERRIDE);

}

stateset->addUniform(new osg::Uniform("textureID0", 0));
stateset->addUniform(new osg::Uniform("textureID1", 1));
stateset->addUniform(new osg::Uniform("textureID2", 2));
stateset->addUniform(new osg::Uniform("textureID3", 3));

//stateset->setDataVariance(osg::Object::DYNAMIC);

osg::Geode* geode = new osg::Geode();
geode->addDrawable(polyGeom);

parent->addChild(geode);
}

// now create the camera to do the multiple render to texture
{
osg::Camera* camera = new osg::Camera;

// set up the background color and clear mask.
camera->setClearColor(osg::Vec4(0.1f, 0.1f, 0.3f, 1.0f));
camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// the camera is going to look at our input quad
camera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1, 0, 1));
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
camera->setViewMatrix(osg::Matrix::identity());

// set viewport
camera->setViewport(0, 0, tex_width, tex_height);

// set the camera to render before the main camera.
camera->setRenderOrder(osg::Camera::PRE_RENDER);

// tell the camera to use OpenGL frame buffer objects
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

// attach the textures to use
for (int i = 0; i < NUM_TEXTURES; i++) {

camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0 +
i), textureRect[i]);
}




// add the subgraph to render
camera->addChild(cam_subgraph);

parent->addChild(camera);
}

return parent;
}

int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc, argv);

// construct the viewer.
osgViewer::Viewer viewer(arguments);

unsigned tex_width = 512;
unsigned tex_height = 512;


osg::Group* subGraph = createRTTQuad(tex_width, tex_height, false);

osg::Group* rootNode = new osg::Group();
rootNode->addChild(createScene(subGraph, tex_width, tex_height, false,
false, false));

rootNode->addChild(createScene(subGraph, tex_width, tex_height, false,
false, false));


//Some code to view the intermediate textures
osg::ref_ptr<osg::Camera> testTex =
createTextureDisplayQuad(osg::Vec3(0, 0.7, 0),
textureRect[0],
tex_width);
osg::ref_ptr<osg::Camera> testTex2 =
createTextureDisplayQuad(osg::Vec3(0, 0.35, 0),
textureRect[1],
tex_width);

rootNode->addChild(testTex);
rootNode->addChild(testTex2);

// add model to the viewer.
viewer.setSceneData(rootNode);
viewer.realize();
viewer.getCamera()->getGraphicsContext()->getState()->setUseModelViewAndProjectionUniforms(true);
viewer.getCamera()->getGraphicsContext()->getState()->setUseVertexAttributeAliasing(true);

return viewer.run();
}



------------------
Post generated by Mail2Forum
Back to top
View user's profile Send private message
antiro42
User


Joined: 01 Sep 2017
Posts: 40

PostPosted: Sun Sep 03, 2017 3:28 pm    Post subject:
Reply with quote

Hi Sebastian,

Thank you so much for all the time you've put into this! After adding the shaders to the CreateTextureDisplayQuad() function in the big project which I'm porting to OSG, it now also has the same output with aliasing on. I would have probably spend weeks hitting my head against the wall before I would have realized what the problem was! I guess that is the danger of starting with some example code which you don't fully understand...

About your remark on texelFetch and textureRectangles: My project already used texelFetch, but I wanted to stay as close to the example code as possible while figuring out what the effect of setUseVertexAttributeAliasing was and how to get it to work with my own shaders.

Now I can start converting all my shaders to use the osg_matrices and the osg layout for the attributes Very Happy

Thank you again!

Cheers,
antiro
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OpenSceneGraph Forum Forum Index -> General All times are GMT
Goto page Previous  1, 2
Page 2 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum

Similar Topics
Topic Author Forum Replies Posted
No new posts Transform matrix as Uniform to shaders freqfly General 3 Thu Oct 05, 2017 4:19 am View latest post
No new posts How to pre-compile shaders before act... kornerr General 1 Thu Sep 28, 2017 8:42 pm View latest post
No new posts Post Processing Effect - Vertex Shade... guyv General 27 Sat Sep 16, 2017 3:48 am View latest post
No new posts Pro Process Effect Vertex Shader not ... guyv General 1 Fri Sep 15, 2017 10:22 pm View latest post
No new posts Post Process Effect Vertex Shader guyv General 1 Fri Sep 15, 2017 8:29 pm View latest post


Board Security Anti Bot Question MOD - phpBB MOD against Spam Bots
Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP