ok .. make sense. Here is updated code, if some one wants to benefit from.
LightLobes with handling of obstacles :). Thanks to Wojiech, Robert and the
online community
Nick

http://www.linkedin.com/in/tnick
Sent from Devlet, Ankara, Turkey

On Fri, Jan 15, 2010 at 3:53 PM, Wojciech Lewandowski <[email protected]
> wrote:

>  0.0 <= shadow2DProj( shadow_texture, projShadow ).r  <= 1.0
>
> Shimering is a result of self shadowing. Boosting  depths in shadow map
> with glPolygonOffset usuallly fixes this. There are many schools for
> PolygonOffset settings. I usually set glPolygonOffset( 1.1, 4.0 ) and draw
> objects with front face culling (see StandardShadowMap::ViewData::init(0 for
> details ).  But for this setup models need to work correctly with backface
> culling on. If you do not enforce backface culling PolygonOffset may need
> different initialization.
>
> Wojtek
>
> ----- Original Message -----
>
> *From:* Trajce Nikolov <[email protected]>
> *To:* OpenSceneGraph Users <[email protected]>
> *Sent:* Friday, January 15, 2010 2:46 PM
> *Subject:* Re: [osg-users] light lobes and shadow maps
>
> one more question. What are the possible values for shadow2DProj(
> shadow_texture, projShadow ).r ? I am trying to put the light attenuation
> back ..... and to avoid the shimmering
> Nick
>
> http://www.linkedin.com/in/tnick
> Sent from Devlet, Ankara, Turkey
>
> On Fri, Jan 15, 2010 at 3:35 PM, Trajce Nikolov 
> <[email protected]>wrote:
>
>> Hey Wojtek !!!! Thanks a lot. !! I will tune it to fix the shimmering
>>
>>
>> Nick
>>
>> http://www.linkedin.com/in/tnick
>>
>>
>>   On Fri, Jan 15, 2010 at 3:08 PM, Wojciech Lewandowski <
>> [email protected]> wrote:
>>
>>>  Trajce,
>>>
>>> Attached is a fixed source code. There is a lots of shadow shimmering on
>>> my GF8800. You will have to add some depth bias while rendering shadow map.
>>> Selection proper PolygonOffset values is usually a matter of trial and error
>>> so leave this for you.
>>>
>>> Wojtek
>>>
>>> ----- Original Message -----
>>>
>>> *From:* Trajce Nikolov <[email protected]>
>>> *To:* OpenSceneGraph Users <[email protected]>
>>> *Sent:* Friday, January 15, 2010 9:58 AM
>>> *Subject:* Re: [osg-users] light lobes and shadow maps
>>>
>>> ABout the code. I use shader to simulate lght lobes thru phong lighting
>>> in the shader. Then I use shadow maps to detect the area behind the
>>> obstacles that need not to be lighten. Most is mixture of shadow maps
>>> technique with lighting scheme. Code snippets borrowed from all around
>>>
>>> Nick
>>>
>>> http://www.linkedin.com/in/tnick
>>> Sent from Devlet, Ankara, Turkey
>>>
>>> On Fri, Jan 15, 2010 at 10:54 AM, Trajce Nikolov <
>>> [email protected]> wrote:
>>>
>>>> Hi Guys,
>>>>
>>>> here is the code.
>>>>
>>>> Nick
>>>>
>>>> http://www.linkedin.com/in/tnick
>>>> Sent from Devlet, Ankara, Turkey
>>>>
>>>> On Thu, Jan 14, 2010 at 11:42 PM, Wojciech Lewandowski <
>>>> [email protected]> wrote:
>>>>
>>>>>  Hi Nick,
>>>>>
>>>>> Post the troublesome code and elaborate a bit more about the problem.
>>>>> If its really a minute or two I am sure someone will be able to help.
>>>>>
>>>>> Wojtek Lewandowski
>>>>>
>>>>>  *From:* Trajce Nikolov <[email protected]>
>>>>> *Sent:* Thursday, January 14, 2010 8:58 PM
>>>>> *To:* OpenSceneGraph Users <[email protected]>
>>>>> *Subject:* [osg-users] light lobes and shadow maps
>>>>>
>>>>> Hi community,
>>>>>
>>>>> I have some shader that does some lighting in the scene. Now studying
>>>>> osgShadow and the techniques. I want to a shadow map technique to disable
>>>>> the lightening of the scene behind obstacles. I have some code done, but 
>>>>> not
>>>>> working. I need some help, someone experienced with GLSL to spend a minute
>>>>> or to to have a look and if possible to spot the problem. Anyone?
>>>>>
>>>>> Thanks a lot
>>>>>
>>>>> Nick
>>>>>
>>>>> http://www.linkedin.com/in/tnick
>>>>> Sent from Izmit, 41, Turkey
>>>>>
>>>>> ------------------------------
>>>>>
>>>>> _______________________________________________
>>>>> osg-users mailing list
>>>>> [email protected]
>>>>>
>>>>> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>>>>>
>>>>>
>>>>> _______________________________________________
>>>>> osg-users mailing list
>>>>> [email protected]
>>>>>
>>>>> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>>>>>
>>>>>
>>>>
>>>  ------------------------------
>>>
>>> _______________________________________________
>>> osg-users mailing list
>>> [email protected]
>>> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>>>
>>>
>>> _______________________________________________
>>> osg-users mailing list
>>> [email protected]
>>> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>>>
>>>
>>
>  ------------------------------
>
> _______________________________________________
> osg-users mailing list
> [email protected]
> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>
>
> _______________________________________________
> osg-users mailing list
> [email protected]
> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>
>
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This application is open source and may be redistributed and/or modified   
 * freely and without restriction, both in commericial and non commericial 
applications,
 * as long as this copyright notice is maintained.
 * 
 * This application is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>

#include <osg/Switch>
#include <osg/LightSource>
#include <osgText/Text>

#include <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <osgSim/OverlayNode>
#include <osg/Geode>
#include <osgText/Text3D>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>
#include <osg/TexGen>
#include <osg/TexGenNode>

#include <osg/CullFace>
#include <osg/PolygonOffset>

#include <iostream>
#include <sstream>

#include <osg/Geometry>
#include <osg/Geode>
#include <osg/LightSource>
#include <osg/LightModel>
#include <osg/Program>
#include <osg/ImageStream>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/BlendFunc>
#include <osg/AlphaFunc>
#include <osg/Material>

#include <osgUtil/SmoothingVisitor>
#include <osg/ShapeDrawable>

#include <osg/PositionAttitudeTransform>
#include <osg/TextureRectangle>

#if 1
osg::Matrixd createTransformMatrix(double x, double y, double z, double h, 
double p, double r)
{
        osg::Matrixd mxR;
        mxR.makeRotate(osg::DegreesToRadians(r),osg::Vec3(0,1,0));
        osg::Matrixd mxP;
        mxP.makeRotate(osg::DegreesToRadians(p),osg::Vec3(1,0,0));
        osg::Matrixd mxH;
        mxH.makeRotate(osg::DegreesToRadians(h),osg::Vec3(0,0,1));
        osg::Matrixd mxT;
        mxT.makeTranslate(osg::Vec3(x,y,z));

        return (mxR*mxP*mxH*mxT);
}

class DrawableDrawWithDepthShadowComparisonOffCallback: 
    public osg::Drawable::DrawCallback
{
public:
    // 
    DrawableDrawWithDepthShadowComparisonOffCallback
        ( osg::Texture2D * texture, unsigned stage = 0 )
            : _texture( texture ), _stage( stage )
    {
    }

    virtual void drawImplementation
        ( osg::RenderInfo & ri,const osg::Drawable* drawable ) const
    {
        if( _texture.valid() ) {
            // make sure proper texture is currently applied
            ri.getState()->applyTextureAttribute( _stage, _texture.get() );

            // Turn off depth comparison mode
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, 
                             GL_NONE );
        }

        drawable->drawImplementation(ri);

        if( _texture.valid() ) {
            // Turn it back on
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, 
                             GL_COMPARE_R_TO_TEXTURE_ARB );
        }
    }

    osg::ref_ptr< osg::Texture2D > _texture;
    unsigned                       _stage;
};

class MoveLightNodeCallback : public osg::NodeCallback
{
public:
        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {
                osg::MatrixTransform* mx = 
dynamic_cast<osg::MatrixTransform*>(node);
                if (mx)
                {
                        osg::Quat q = mx->getMatrix().getRotate();
                        osg::Vec3 t = mx->getMatrix().getTrans();

                        static double v = 0.03;
                        t.y() += v;
                        if (t.y()>10 || t.y()<-10)
                                v *= -1.0;

                        
mx->setMatrix(osg::Matrix::rotate(q)*osg::Matrix::translate(t));
                }
                traverse(node,nv);
        }
};

class AttachNodeUpdateCallback : public osg::NodeCallback
{
public:
        AttachNodeUpdateCallback(osg::MatrixTransform* mx, const osg::Vec3& t = 
osg::Vec3(0,0,0))
                : mMx(mx)
                , mOffset(t)
                , mLocalRotate(false)
        {
        }

        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {
                osg::Camera* camera = dynamic_cast<osg::Camera*>(node);
                if (!camera) return;

                osg::Matrixd mx = mMx->getMatrix();
                osg::Quat q = mx.getRotate();
                osg::Vec3 t = mx.getTrans();

                osg::Quat fq;
                fq.makeRotate(osg::Vec3(0,0,-1),osg::Vec3(0,1,0));

                osg::Matrixd mO;
                mO.makeTranslate(mOffset);
                osg::Matrixd mR;
                mR.makeRotate(q);
                osg::Matrixd mT;
                mT.makeTranslate(t);
                osg::Matrixd mF;
                mF.makeRotate(fq);

                osg::Matrixd m;
                if (mLocalRotate)
                {
                        osg::Matrix ml;
                        ml.makeRotate(mRotation);

                        m = mF * ml * mO * mR * mT;
                }
                else
                {
                        m = mF * mO * mR * mT;
                }
                
                camera->setViewMatrix(osg::Matrixd::inverse(m));

                traverse(node,nv);
        }

        void setLocalRotation(const osg::Quat& r)
        {
                mLocalRotate = true;
                mRotation = r;
        }
        void resetLocalRotation()
        {
                mLocalRotate = false;
        }

protected:
        osg::MatrixTransform*   mMx;
        osg::Vec3                               mOffset;
        bool                                    mLocalRotate;
        osg::Quat                               mRotation;
};

class UpdateLMVPM : public osg::Uniform::Callback
{
public:
        UpdateLMVPM(osg::Camera* camera)
                : mCamera(camera)
        {
        }
        virtual void operator () (osg::Uniform* u, osg::NodeVisitor*)
        {
                osg::Matrixd lmvpm =
                                mCamera->getViewMatrix() * 
mCamera->getProjectionMatrix() * 
                osg::Matrix::translate( 1,1,1 ) * osg::Matrix::scale( 0.5, 0.5, 
0.5 );

                u->set(lmvpm);
        }

protected:
        osg::Camera* mCamera;
};

osg::Node* createScene(osg::ArgumentParser& arguments, osgViewer::Viewer* 
viewer = 0)
{
        osg::Group* group = new osg::Group;
        osg::Group* scene = new osg::Group;
        scene->addChild(group);

        scene->getOrCreateStateSet()->setAttribute( new osg::CullFace, 
osg::StateAttribute::ON  );
        scene->getOrCreateStateSet()->setAttribute( new osg::PolygonOffset( 
1.1, 4.0 ),osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
    scene->getOrCreateStateSet()->setMode( 
GL_POLYGON_OFFSET_FILL,osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE 
);

        osg::MatrixTransform* mx = 0;
        osg::MatrixTransform* mx2 = 0;
        osg::Geometry* scenegeometry = 0;

        osg::Geode* geode = new osg::Geode;
        group->addChild(geode);

        // "TERRAIN"
        {
                mx2 = new osg::MatrixTransform;
                mx2->setMatrix(osg::Matrix::scale(osg::Vec3(35,35,35)));
                group->addChild(mx2);

                osg::Geode* geode = new osg::Geode;
                mx2->addChild(geode);

                scenegeometry = new osg::Geometry;
                geode->addDrawable(scenegeometry);

                osg::Vec3Array* vxs = new osg::Vec3Array;
                vxs->push_back( osg::Vec3(-0.5,-0.5,0) );
                vxs->push_back( osg::Vec3(0.5,-0.5,0) );
                vxs->push_back( osg::Vec3(0.5,0.5,0) );
                vxs->push_back( osg::Vec3(-0.5,0.5,0) );
                scenegeometry->setVertexArray( vxs );

                osg::Vec2Array* uvs = new osg::Vec2Array;
                uvs->push_back( osg::Vec2(0,0) );
                uvs->push_back( osg::Vec2(1,0) );
                uvs->push_back( osg::Vec2(1,1) );
                uvs->push_back( osg::Vec2(0,1) );
                scenegeometry->setTexCoordArray(0,uvs);

                for (unsigned int i=0; i<10; ++i)
                {
                        double pos = -0.5+(0.1*i);
                        double w = 0.05;
                        vxs->push_back( osg::Vec3(pos,0.0,-0.1) );
                        vxs->push_back( osg::Vec3(pos+w,0.0,-0.1) );
                        vxs->push_back( osg::Vec3(pos+w,0.0,0.1) );
                        vxs->push_back( osg::Vec3(pos,0.0,0.1) );
                
                        uvs->push_back( osg::Vec2(0,0) );
                        uvs->push_back( osg::Vec2(1,0) );
                        uvs->push_back( osg::Vec2(1,1) );
                        uvs->push_back( osg::Vec2(0,1) );
                }
                

                osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
                if (image)
                {
                        osg::Texture2D* texture = new osg::Texture2D;
                        texture->setImage(image);
                        
scenegeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
                }

                scenegeometry->addPrimitiveSet( new 
osg::DrawArrays(osg::PrimitiveSet::QUADS,0,vxs->size()) );

                osg::Material* mt = new osg::Material;
                
mt->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.3,0.3,0.3,1));
                
mt->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.9,0.5,0.5,1));
                
mt->setSpecular(osg::Material::FRONT_AND_BACK,osg::Vec4(0.6,0.6,0.6,1));
                mt->setShininess(osg::Material::FRONT_AND_BACK,60);
                
scenegeometry->getOrCreateStateSet()->setAttributeAndModes(mt,osg::StateAttribute::ON);
                
        }

        // "LIGHT SOURCE"
        {
                for (unsigned int i=1; i<=1; ++i)
                {
                        osg::LightSource* light = new osg::LightSource;

                        light->getLight()->setLightNum(i);
                        light->getLight()->setAmbient(osg::Vec4(0,0,0,1));
                        light->getLight()->setDiffuse(osg::Vec4(0,10,0,1));
                        light->getLight()->setSpecular(osg::Vec4(1,1,1,1));
                        light->getLight()->setConstantAttenuation(0.01);
                        light->getLight()->setSpotCutoff(20);
                        
light->setStateSetModes(*group->getOrCreateStateSet(),osg::StateAttribute::ON);
                        light->getLight()->setDirection(osg::Vec3(0,1,0));
                        light->getLight()->setPosition(osg::Vec4(0,0,0,1));
                        mx = new osg::MatrixTransform;
                        
mx->setMatrix(createTransformMatrix(15-i*2.5,-4,3,0,-45,0));
                        mx->setUpdateCallback(new MoveLightNodeCallback );
                        mx->addChild(light);

                        osg::Geode* geode = new osg::Geode;
                        mx->addChild(geode);

                        float radius = 0.2f;
                        osg::TessellationHints* hints = new 
osg::TessellationHints;
                        hints->setDetailRatio(0.5f);
                    geode->addDrawable(new osg::ShapeDrawable(new 
osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));

                        group->addChild(mx);
                }
        }
        // SCENE LIGHTING
        {
                const char* microshaderVertSource = 
            "uniform mat4 osg_ViewMatrixInverse; // Automatically updated by 
OSG\n"
                        "varying vec3 normal, eyeVec;\n"
                        "varying vec3 lightDirs[8];\n"
                        "varying vec4 projShadow;\n"
                        " uniform mat4 LightModelViewProjectionMatrix;\n"
                        "\n"
                        "void main()\n"
                        "{      \n"
                        "       gl_TexCoord[0] = gl_MultiTexCoord0;\n"
                        "       normal = gl_NormalMatrix * gl_Normal;\n"
                        "       \n"
                        "       vec3 vVertex = vec3(gl_ModelViewMatrix * 
gl_Vertex);\n"
                        "       lightDirs[0] = 
vec3(gl_LightSource[0].position.xyz - vVertex);\n"
                        "       lightDirs[1] = 
vec3(gl_LightSource[1].position.xyz - vVertex);\n"
                        "       lightDirs[2] = 
vec3(gl_LightSource[2].position.xyz - vVertex);\n"
                        "       lightDirs[3] = 
vec3(gl_LightSource[3].position.xyz - vVertex);\n"
                        "       lightDirs[4] = 
vec3(gl_LightSource[4].position.xyz - vVertex);\n"
                        "       lightDirs[5] = 
vec3(gl_LightSource[5].position.xyz - vVertex);\n"
                        "       lightDirs[6] = 
vec3(gl_LightSource[6].position.xyz - vVertex);\n"
                        "       lightDirs[7] = 
vec3(gl_LightSource[7].position.xyz - vVertex);\n"
                        "       eyeVec = -vVertex;\n"
            "   // We need vertex in world spaces \n"
            "   // ie something like: glVertex * gl_ModelMatrix \n"
            "   // but there is no such thing like gl_ModelMatrix in GL \n"
            "   // but we could get it from view space by multiplication by 
inverted viewMatrix \n"
            "   // gl_Vertex * gl_ModelViewMatrix * osg_ViewMatrixInverse \n"
            "   vec4 worldSpaceVertex = osg_ViewMatrixInverse * vec4( vVertex, 
1.0 ); \n"
                        "       projShadow = LightModelViewProjectionMatrix * 
worldSpaceVertex;\n"
                        "\n"
                        "       gl_Position = ftransform();             \n"
                        "}\n";

                const char* microshaderFragSource =
                        "uniform sampler2D color_texture;\n"
                        "uniform sampler2DShadow shadow_texture;\n"
                        "varying vec4 projShadow;\n"
                        "\n"
                        "uniform bool fogActive;\n"
                        "\n"
                        "const int NumEnabledLights = 1; \n"
                        "\n"
                        "varying vec3 normal, eyeVec;\n"
                        "varying vec3 lightDirs[8];\n"
                        "\n"
                        "const float cos_outer_cone_angle = 0.8; // 36 
degrees\n"
                        "\n"
                        "void main (void)\n"
                        "{\n"
                        "vec4 combined_color = vec4(0.0);\n"
                        "for (int i = 1; i < 1+NumEnabledLights; i++)\n" 
                        "{ \n" 
                        "       vec4 final_color =\n"
                        "       (gl_FrontLightModelProduct.sceneColor * 
gl_FrontMaterial.ambient) +\n"
                        "       (gl_LightSource[i].ambient * 
gl_FrontMaterial.ambient);\n"
                        "\n"
                        "       float distSqr = 
dot(lightDirs[i],lightDirs[i]);\n"
                        "       float invRadius = 
gl_LightSource[i].constantAttenuation;\n"
                        "       float att = clamp(1.0-invRadius * 
sqrt(distSqr), 0.0, 1.0);\n"
                        "       vec3 L = lightDirs[i] * inversesqrt(distSqr);\n"
                        "       vec3 D = 
normalize(gl_LightSource[i].spotDirection);\n"
                        "\n"
                        "       float cos_cur_angle = dot(-L, D);\n"
                        "\n"
                        "       float cos_inner_cone_angle = 
gl_LightSource[i].spotCosCutoff;\n"
                        "\n"
                        "       float cos_inner_minus_outer_angle = \n"
                        "                 cos_inner_cone_angle - 
cos_outer_cone_angle;\n"
                        "       \n"
                        "       float spot = 0.0;\n"
                        "       spot = clamp((cos_cur_angle - 
cos_outer_cone_angle) / \n"
                        "                  cos_inner_minus_outer_angle, 0.0, 
1.0);\n"
                        "\n"
                        "       vec3 N = normalize(normal);\n"
                        "\n"
                        "       float lambertTerm = max( dot(N,L), 0.0);\n"
                        "       if(lambertTerm > 0.0)\n"
                        "       {\n"
                        "               final_color += 
gl_LightSource[i].diffuse *\n"
                        "                       gl_FrontMaterial.diffuse *\n"
                        "                       lambertTerm * spot * att;\n"
                        "\n"
                        "               vec3 E = normalize(eyeVec);\n"
                        "               vec3 R = reflect(-L, N);\n"
                        "\n"
                        "               float specular = pow( max(dot(R, E), 
0.0),\n"
                        "                       gl_FrontMaterial.shininess );\n"
                        "\n"
                        "               final_color += 
gl_LightSource[i].specular *\n"
                        "                       gl_FrontMaterial.specular *\n"
                        "                       specular * spot * att;\n"
                        "       }\n"
                        "       vec4 clr = shadow2DProj( shadow_texture, 
projShadow ).r == 0.0 ? vec4(0.0) : final_color;\n" 
                        "       combined_color += clr;\n"
                        "}\n"
                        "       {\n"
                        "               vec4 final_color = \n"
                        "               (gl_FrontLightModelProduct.sceneColor * 
gl_FrontMaterial.ambient) + \n"
                        "               (gl_LightSource[0].ambient * 
gl_FrontMaterial.ambient);\n"
                        "\n"                                                    
                        "               vec3 N = normalize(normal);\n"
                        "               vec3 L = normalize(lightDirs[0]);\n"
                        "\n"
                        "               float lambertTerm = dot(N,L);\n"
                        "\n"
                        "               if(lambertTerm > 0.0)\n"
                        "               {\n"
                        "                       final_color += 
gl_LightSource[0].diffuse * \n"
                        "                              gl_FrontMaterial.diffuse 
* \n"
                        "                                          lambertTerm; 
\n"
                        "\n"
                        "                       vec3 E = normalize(eyeVec);\n"
                        "                       vec3 R = reflect(-L, N);\n"
                        "                       float specular = pow( 
max(dot(R, E), 0.0), \n"
                        "                                
gl_FrontMaterial.shininess );\n"
                        "                       final_color += 
gl_LightSource[0].specular * \n"
                        "                              
gl_FrontMaterial.specular * \n"
                        "                                          specular;    
\n"
                        "               }\n"
                        "               combined_color += final_color;\n"
                        "       }\n"
                        "       vec4 preFogColor = texture2D(color_texture, 
gl_TexCoord[0].st) * combined_color;\n"
                        "       if (fogActive)\n"
                        "       {\n"
                        "               const float LOG2 = 1.442695;\n"
                        "               float z = gl_FragCoord.z / 
gl_FragCoord.w;\n"
                        "               float fogFactor = exp2( -gl_Fog.density 
* \n"
                        "                       gl_Fog.density * \n"
                        "                       z * \n"
                        "                       z * \n"
                        "                       LOG2 );\n"
                        "               fogFactor = clamp(fogFactor, 0.0, 
1.0);\n"
                        "               gl_FragColor = mix(gl_Fog.color, 
preFogColor, fogFactor );"
                        "       }\n"
                        "       else gl_FragColor = preFogColor;\n"
//            "   gl_FragColor = ( projShadow / projShadow.w ); \n"
                        "}\n";
                

                osg::Program* program = new osg::Program;
        program->setName( "microshader" );
                program->addShader( new osg::Shader( osg::Shader::VERTEX, 
microshaderVertSource ) );
        program->addShader( new osg::Shader( osg::Shader::FRAGMENT, 
microshaderFragSource ) );
        group->getOrCreateStateSet()->setAttributeAndModes( program, 
osg::StateAttribute::ON );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("fogActive",false) );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("color_texture",0) );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("shadow_texture",1) );

        }
        // HUD
        {
                osg::Camera* camera = new osg::Camera;
                scene->addChild(camera);        

                double width = 1280;
                double height = 1024;

                
camera->setProjectionMatrix(osg::Matrix::ortho2D(0,width,0,height));
                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
                camera->setViewMatrix(osg::Matrix::identity());
                camera->setClearMask(GL_DEPTH_BUFFER_BIT);
                camera->setRenderOrder(osg::Camera::POST_RENDER);
                camera->setAllowEventFocus(false);

                osg::Geode* geode = new osg::Geode;
                camera->addChild(geode);
                
camera->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF|osg::StateAttribute::OVERRIDE|osg::StateAttribute::PROTECTED);

                double offset = 50;
                double wf = 512;
                double hf = 512;
                osg::Geometry *geometry = 
osg::createTexturedQuadGeometry(osg::Vec3(offset,2*offset,-0.1),osg::Vec3(wf,0,0),osg::Vec3(0,hf,0));
                geode->addDrawable(geometry);

                osg::Shader* shader = new osg::Shader( osg::Shader::FRAGMENT,
#if 0
                        "uniform sampler2D texture; \n"
                        " \n"
                        "void main(void) \n"
                        "{ \n"
                        "   float value = texture2D(texture, gl_TexCoord[0].st 
).r; \n"
                        "   gl_FragColor = vec4( value, value, value, 0.8 ); \n"
                        "} \n"
#else
                        "uniform sampler2D texture;                             
                 \n"
                        "                                                       
                 \n"
                        "void main(void)                                        
                 \n"
                        "{                                                      
                 \n"
                        "    float f = texture2D( texture, gl_TexCoord[0].st 
).r;                \n"
                        "                                                       
                                                                                
         \n"
                        "                                                       
                 \n"
                        "    f = 256.0 * f;                                     
                 \n"
                        "    float fC = floor( f ) / 256.0;                     
                 \n" 
                        "                                                       
                 \n"
                        "    f = 256.0 * fract( f );                            
                 \n"
                        "    float fS = floor( f ) / 256.0;                     
                 \n"  
                        "                                                       
                 \n"
                        "    f = 256.0 * fract( f );                            
                 \n"
                        "    float fH = floor( f ) / 256.0;                     
                 \n"
                        "                                                       
                 \n"
                        "    fS *= 0.5;                                         
                 \n"
                        "    fH = ( fH  * 0.34 + 0.66 ) * ( 1.0 - fS );         
                 \n"
                        "                                                       
                 \n"
                        "    vec3 rgb = vec3( ( fC > 0.5 ? ( 1.0 - fC ) : fC ), 
                 \n"
                        "                     abs( fC - 0.333333 ),             
                 \n"
                        "                     abs( fC - 0.666667 ) );           
                 \n"
                        "                                                       
                 \n"   
                        "    rgb = min( vec3( 1.0, 1.0, 1.0 ), 3.0 * rgb );     
                 \n"
                        "                                                       
                 \n"
                        "    float fMax = max( max( rgb.r, rgb.g ), rgb.b );    
                 \n"
                        "    fMax = 1.0 / fMax;                                 
                 \n"  
                        "                                                       
                 \n"
                        "    vec3 color = fMax * rgb;                           
                 \n"
                        "                                                       
                 \n"
                        "    gl_FragColor =  vec4( fS + fH * color, 1 ) * 
gl_Color;              \n"
                        "}                                                      
                 \n"  
#endif
                ); 
                osg::Program* program = new osg::Program;
                program->addShader( shader );
                geometry->getOrCreateStateSet()->setAttribute( program );
                geometry->getOrCreateStateSet()->addUniform( new osg::Uniform( 
"texture" , 0 ) );

                osg::Texture2D* dbgDepthTexture = new osg::Texture2D;
                dbgDepthTexture->setTextureSize(512, 512);
                dbgDepthTexture->setInternalFormat(GL_DEPTH_COMPONENT);
                
dbgDepthTexture->setShadowTextureMode(osg::Texture2D::LUMINANCE);
                dbgDepthTexture->setShadowComparison(true);
                dbgDepthTexture->setShadowCompareFunc(osg::Texture::LEQUAL);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_S, 
osg::Texture::CLAMP_TO_EDGE);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_T, 
osg::Texture::CLAMP_TO_EDGE);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_R, 
osg::Texture::CLAMP_TO_EDGE);
                
dbgDepthTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
                
dbgDepthTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
                
geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0,dbgDepthTexture,osg::StateAttribute::ON);

                
scenegeometry->getOrCreateStateSet()->setTextureAttributeAndModes(1,dbgDepthTexture,osg::StateAttribute::ON);

                geometry->setDrawCallback( new 
DrawableDrawWithDepthShadowComparisonOffCallback(dbgDepthTexture) );

                // LIGHT CAMERA
                {
                        osg::Camera* camera = new osg::Camera;
                        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
                        camera->setProjectionMatrixAsPerspective(70, 1, 0.001, 
100 );
                        camera->setViewport(0,0,512,512);
                        
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
                        camera->setClearColor(osg::Vec4(1.f,1.f,1.f,1.0f));
                        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
                        
camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
                        camera->addChild(mx2);
                        camera->setRenderOrder(osg::Camera::PRE_RENDER);
                        
camera->attach(osg::Camera::DEPTH_BUFFER,dbgDepthTexture);
                        camera->setCullingActive(true);
                        camera->setUpdateCallback( new 
AttachNodeUpdateCallback(mx) );

                        {
                                osg::Matrixd mxd = mx->getMatrix();
                                osg::Quat q = mxd.getRotate();
                                osg::Vec3 t = mxd.getTrans();

                                osg::Quat fq;
                                
fq.makeRotate(osg::Vec3(0,0,-1),osg::Vec3(0,1,0));

                                osg::Matrixd mR;
                                mR.makeRotate(q);
                                osg::Matrixd mT;
                                mT.makeTranslate(t);
                                osg::Matrixd mF;
                                mF.makeRotate(fq);

                                osg::Matrixd m;
                                m = mF * mR * mT;

                                camera->setViewMatrix(osg::Matrixd::inverse(m));
                        }

                        osg::Matrixd lmvpm =
                                camera->getViewMatrix() * 
camera->getProjectionMatrix() * 
                osg::Matrix::translate( 1,1,1 ) * osg::Matrix::scale( 0.5, 0.5, 
0.5 );
                        osg::Uniform* u = new 
osg::Uniform("LightModelViewProjectionMatrix",lmvpm);
                        u->setUpdateCallback( new UpdateLMVPM(camera) );
                        group->getOrCreateStateSet()->addUniform( u );
            

                        scene->addChild(camera);

                }
        }

        return scene;
}
#endif

void setupViewer(osgViewer::Viewer* viewer, osg::ArgumentParser& arguments)
{
        // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = 
new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new 
osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new 
osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new 
osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new 
osgGA::TerrainManipulator() );

        viewer->setCameraManipulator( keyswitchManipulator.get() );
    }

        // add the state manipulator
    viewer->addEventHandler( new 
osgGA::StateSetManipulator(viewer->getCamera()->getOrCreateStateSet()) );
    
    // add the thread model handler
    viewer->addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
        
    // add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer->addEventHandler(new 
osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // add the record camera path handler
    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);

    // add the LOD Scale handler
    viewer->addEventHandler(new osgViewer::LODScaleHandler);

    // add the screen capture handler
    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
}

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

    
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+"
 is the standard OpenSceneGraph example which loads and visualises 3d models.");
    
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+"
 [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image 
<filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem 
<filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("--login <url> 
<username> <password>","Provide authentication information for http file 
access.");

        osg::ref_ptr<osgViewer::Viewer> viewer = new 
osgViewer::Viewer(arguments);
        viewer->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1));
        viewer->getLight()->setDiffuse(osg::Vec4(0.7,0.5,0.5,1));

    unsigned int helpType = 0;
    if ((helpType = arguments.readHelpType()))
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }
    
    // report any errors if they have occurred when parsing the program 
arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }
    
#if 0
    if (arguments.argc()<=1)
    {
        
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }
#endif

    std::string url, username, password;
    while(arguments.read("--login",url, username, password))
    {
        if (!osgDB::Registry::instance()->getAuthenticationMap())
        {
            osgDB::Registry::instance()->setAuthenticationMap(new 
osgDB::AuthenticationMap);
            
osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
                url,
                new osgDB::AuthenticationDetails(username, password)
            );
        }
    }


        setupViewer(viewer.get(),arguments);

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel) 
    {
                loadedModel = createScene(arguments,viewer.get());
                
//arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        //std::cout << arguments.getApplicationName() <<": No data loaded" << 
std::endl;
        //return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program 
arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }


    // optimize the scene graph, remove redundant nodes and state etc.
#if 0
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

        osgUtil::SmoothingVisitor sv;
        loadedModel->accept(sv);
#endif

    viewer->setSceneData( loadedModel.get() );

    viewer->realize();

        while (!viewer->done())
        {
                viewer->frame();
        }

        viewer = 0;

    return 0;

}
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to