root/OpenSceneGraph/trunk/src/osgShadow/ShadowMap.cpp

Revision 15016, 23.0 kB (checked in by robert, 19 months ago)

Release OpenSceneGraph-3.5.1

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#include <osgShadow/ShadowMap>
15#include <osgShadow/ShadowedScene>
16#include <osg/Notify>
17#include <osg/ComputeBoundsVisitor>
18#include <osg/PolygonOffset>
19#include <osg/CullFace>
20#include <osg/io_utils>
21
22using namespace osgShadow;
23
24#include <iostream>
25//for debug
26#include <osg/LightSource>
27#include <osg/PolygonMode>
28#include <osg/Geometry>
29#include <osgDB/ReadFile>
30#include <osgText/Text>
31
32#define IMPROVE_TEXGEN_PRECISION 1
33
34//////////////////////////////////////////////////////////////////
35// fragment shader
36//
37static const char fragmentShaderSource_noBaseTexture[] =
38    "uniform sampler2DShadow osgShadow_shadowTexture; \n"
39    "uniform vec2 osgShadow_ambientBias; \n"
40    "\n"
41    "void main(void) \n"
42    "{ \n"
43    "    gl_FragColor = gl_Color * (osgShadow_ambientBias.x + shadow2DProj( osgShadow_shadowTexture, gl_TexCoord[0] ) * osgShadow_ambientBias.y); \n"
44    "}\n";
45
46//////////////////////////////////////////////////////////////////
47// fragment shader
48//
49static const char fragmentShaderSource_withBaseTexture[] =
50    "uniform sampler2D osgShadow_baseTexture; \n"
51    "uniform sampler2DShadow osgShadow_shadowTexture; \n"
52    "uniform vec2 osgShadow_ambientBias; \n"
53    "\n"
54    "void main(void) \n"
55    "{ \n"
56    "    vec4 color = gl_Color * texture2D( osgShadow_baseTexture, gl_TexCoord[0].xy ); \n"
57    "    gl_FragColor = color * (osgShadow_ambientBias.x + shadow2DProj( osgShadow_shadowTexture, gl_TexCoord[1] ) * osgShadow_ambientBias.y); \n"
58    "}\n";
59
60//////////////////////////////////////////////////////////////////
61// fragment shader
62//
63static const char fragmentShaderSource_debugHUD[] =
64    "uniform sampler2D osgShadow_shadowTexture; \n"
65    " \n"
66    "void main(void) \n"
67    "{ \n"
68    "   vec4 texResult = texture2D(osgShadow_shadowTexture, gl_TexCoord[0].st ); \n"
69    "   float value = texResult.r; \n"
70    "   gl_FragColor = vec4( value, value, value, 0.8 ); \n"
71    "} \n";
72
73ShadowMap::ShadowMap():
74    _baseTextureUnit(0),
75    _shadowTextureUnit(1),
76    _polyOffset(1.0,1.0),
77    _ambientBias(0.5f,0.5f),
78    _textureSize(1024,1024)
79{
80}
81
82ShadowMap::ShadowMap(const ShadowMap& copy, const osg::CopyOp& copyop):
83ShadowTechnique(copy,copyop),
84    _baseTextureUnit(copy._baseTextureUnit),
85    _shadowTextureUnit(copy._shadowTextureUnit),
86    _polyOffset(copy._polyOffset),
87    _ambientBias(copy._ambientBias),
88    _textureSize(copy._textureSize)
89{
90}
91
92void ShadowMap::setTextureUnit(unsigned int unit)
93{
94    _shadowTextureUnit = unit;
95}
96
97void ShadowMap::setPolygonOffset(const osg::Vec2& polyOffset)
98{
99    _polyOffset = polyOffset;
100}
101
102void ShadowMap::setAmbientBias(const osg::Vec2& ambientBias)
103{
104    _ambientBias = ambientBias;
105    if (_ambientBiasUniform.valid()) _ambientBiasUniform->set(_ambientBias);
106}
107
108void ShadowMap::setTextureSize(const osg::Vec2s& textureSize)
109{
110    _textureSize = textureSize;
111    dirty();
112}
113
114void ShadowMap::setLight(osg::Light* light)
115{
116    _light = light;
117}
118
119
120void ShadowMap::setLight(osg::LightSource* ls)
121{
122    _ls = ls;
123    _light = _ls->getLight();
124}
125
126void ShadowMap::createUniforms()
127{
128    _uniformList.clear();
129
130    osg::Uniform* baseTextureSampler = new osg::Uniform("osgShadow_baseTexture",(int)_baseTextureUnit);
131    _uniformList.push_back(baseTextureSampler);
132
133    osg::Uniform* shadowTextureSampler = new osg::Uniform("osgShadow_shadowTexture",(int)_shadowTextureUnit);
134    _uniformList.push_back(shadowTextureSampler);
135
136    _ambientBiasUniform = new osg::Uniform("osgShadow_ambientBias",_ambientBias);
137    _uniformList.push_back(_ambientBiasUniform.get());
138
139}
140
141void ShadowMap::createShaders()
142{
143    // if we are not given shaders, use the default
144    if( _shaderList.empty() )
145    {
146        if (_shadowTextureUnit==0)
147        {
148            osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_noBaseTexture);
149            _shaderList.push_back(fragment_shader);
150        }
151        else
152        {
153            osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture);
154            _shaderList.push_back(fragment_shader);
155
156        }
157    }
158}
159
160void ShadowMap::init()
161{
162    if (!_shadowedScene) return;
163
164    _texture = new osg::Texture2D;
165    _texture->setTextureSize(_textureSize.x(), _textureSize.y());
166    _texture->setInternalFormat(GL_DEPTH_COMPONENT);
167    _texture->setShadowComparison(true);
168    _texture->setShadowTextureMode(osg::Texture2D::LUMINANCE);
169    _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
170    _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
171
172    // the shadow comparison should fail if object is outside the texture
173    _texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
174    _texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
175    _texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
176
177    // set up the render to texture camera.
178    {
179        // create the camera
180        _camera = new osg::Camera;
181
182        _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT);
183
184        _camera->setCullCallback(new CameraCullCallback(this));
185
186        _camera->setClearMask(GL_DEPTH_BUFFER_BIT);
187        //_camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
188        _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
189        _camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
190
191        // set viewport
192        _camera->setViewport(0,0,_textureSize.x(),_textureSize.y());
193
194        // set the camera to render before the main camera.
195        _camera->setRenderOrder(osg::Camera::PRE_RENDER);
196
197        // tell the camera to use OpenGL frame buffer object where supported.
198        _camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
199        //_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW);
200
201        // attach the texture and use it as the color buffer.
202        _camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get());
203
204        osg::StateSet* stateset = _camera->getOrCreateStateSet();
205
206
207#if 1
208        // cull front faces so that only backfaces contribute to depth map
209
210
211        osg::ref_ptr<osg::CullFace> cull_face = new osg::CullFace;
212        cull_face->setMode(osg::CullFace::FRONT);
213        stateset->setAttribute(cull_face.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
214        stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
215
216        // negative polygonoffset - move the backface nearer to the eye point so that backfaces
217        // shadow themselves
218        float factor = -_polyOffset[0];
219        float units =  -_polyOffset[1];
220
221        osg::ref_ptr<osg::PolygonOffset> polygon_offset = new osg::PolygonOffset;
222        polygon_offset->setFactor(factor);
223        polygon_offset->setUnits(units);
224        stateset->setAttribute(polygon_offset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
225        stateset->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
226#else
227        // disabling cull faces so that only front and backfaces contribute to depth map
228        stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
229
230        // negative polygonoffset - move the backface nearer to the eye point
231        // so that front faces do not shadow themselves.
232        float factor = _polyOffset[0];
233        float units =  _polyOffset[1];
234
235        osg::ref_ptr<osg::PolygonOffset> polygon_offset = new osg::PolygonOffset;
236        polygon_offset->setFactor(factor);
237        polygon_offset->setUnits(units);
238        stateset->setAttribute(polygon_offset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
239        stateset->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
240#endif
241    }
242
243    {
244        _stateset = new osg::StateSet;
245        _stateset->setTextureAttributeAndModes(_shadowTextureUnit,_texture.get(),osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
246        _stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
247        _stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
248        _stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
249        _stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
250
251        _texgen = new osg::TexGen;
252
253        // add Program, when empty of Shaders then we are using fixed functionality
254        _program = new osg::Program;
255        _stateset->setAttribute(_program.get());
256
257        // create default shaders if needed
258        createShaders();
259
260        // add the shader list to the program
261        for(ShaderList::const_iterator itr=_shaderList.begin();
262            itr!=_shaderList.end();
263            ++itr)
264        {
265            _program->addShader(itr->get());
266        }
267
268        // create own uniforms
269        createUniforms();
270
271        // add the uniform list to the stateset
272        for(UniformList::const_iterator itr=_uniformList.begin();
273            itr!=_uniformList.end();
274            ++itr)
275        {
276            _stateset->addUniform(itr->get());
277        }
278
279        {
280            // fake texture for baseTexture, add a fake texture
281            // we support by default at least one texture layer
282            // without this fake texture we can not support
283            // textured and not textured scene
284
285            // TODO: at the moment the PSSM supports just one texture layer in the GLSL shader, multitexture are
286            //       not yet supported !
287
288            osg::Image* image = new osg::Image;
289            // allocate the image data, noPixels x 1 x 1 with 4 rgba floats - equivalent to a Vec4!
290            int noPixels = 1;
291            image->allocateImage(noPixels,1,1,GL_RGBA,GL_FLOAT);
292            image->setInternalTextureFormat(GL_RGBA);
293            // fill in the image data.
294            osg::Vec4* dataPtr = (osg::Vec4*)image->data();
295            osg::Vec4 color(1,1,1,1);
296            *dataPtr = color;
297            // make fake texture
298            osg::Texture2D* fakeTex = new osg::Texture2D;
299            fakeTex->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_EDGE);
300            fakeTex->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_EDGE);
301            fakeTex->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
302            fakeTex->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
303            fakeTex->setImage(image);
304            // add fake texture
305            _stateset->setTextureAttribute(_baseTextureUnit,fakeTex,osg::StateAttribute::ON);
306            _stateset->setTextureMode(_baseTextureUnit,GL_TEXTURE_2D,osg::StateAttribute::ON);
307            _stateset->setTextureMode(_baseTextureUnit,GL_TEXTURE_3D,osg::StateAttribute::OFF);
308            #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE)
309                _stateset->setTextureMode(_baseTextureUnit,GL_TEXTURE_1D,osg::StateAttribute::OFF);
310            #endif
311        }
312    }
313
314    _dirty = false;
315}
316
317
318void ShadowMap::update(osg::NodeVisitor& nv)
319{
320    _shadowedScene->osg::Group::traverse(nv);
321}
322
323void ShadowMap::cull(osgUtil::CullVisitor& cv)
324{
325    // record the traversal mask on entry so we can reapply it later.
326    unsigned int traversalMask = cv.getTraversalMask();
327
328    osgUtil::RenderStage* orig_rs = cv.getRenderStage();
329
330    // do traversal of shadow receiving scene which does need to be decorated by the shadow map
331    {
332        cv.pushStateSet(_stateset.get());
333
334        _shadowedScene->osg::Group::traverse(cv);
335
336        cv.popStateSet();
337
338    }
339
340    // need to compute view frustum for RTT camera.
341    // 1) get the light position
342    // 2) get the center and extents of the view frustum
343
344    const osg::Light* selectLight = 0;
345    osg::Vec4 lightpos;
346    osg::Vec3 lightDir;
347
348    //MR testing giving a specific light
349    osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList();
350    for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
351        itr != aml.end();
352        ++itr)
353    {
354        const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
355        if (light)
356        {
357            if( _light.valid()) {
358                if( _light.get() == light )
359                    selectLight = light;
360                else
361                    continue;
362            }
363            else
364                selectLight = light;
365
366            osg::RefMatrix* matrix = itr->second.get();
367            if (matrix)
368            {
369                lightpos = light->getPosition() * (*matrix);
370                lightDir = osg::Matrix::transform3x3( light->getDirection(), *matrix );
371            }
372            else
373            {
374                lightpos = light->getPosition();
375                lightDir = light->getDirection();
376            }
377
378        }
379    }
380
381    osg::Matrix eyeToWorld;
382    eyeToWorld.invert(*cv.getModelViewMatrix());
383
384    lightpos = lightpos * eyeToWorld;
385    lightDir = osg::Matrix::transform3x3( lightDir, eyeToWorld );
386    lightDir.normalize();
387
388    if (selectLight)
389    {
390
391        // set to ambient on light to black so that the ambient bias uniform can take it's affect
392        const_cast<osg::Light*>(selectLight)->setAmbient(osg::Vec4(0.0f,0.0f,0.0f,1.0f));
393
394        //std::cout<<"----- VxOSG::ShadowMap selectLight spot cutoff "<<selectLight->getSpotCutoff()<<std::endl;
395
396        float fov = selectLight->getSpotCutoff() * 2;
397        if(fov < 180.0f)   // spotlight, then we don't need the bounding box
398        {
399            osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z());
400            _camera->setProjectionMatrixAsPerspective(fov, 1.0, 0.1, 1000.0);
401            _camera->setViewMatrixAsLookAt(position,position+lightDir,computeOrthogonalVector(lightDir));
402        }
403        else
404        {
405            // get the bounds of the model.
406            osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
407            cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask());
408
409            _shadowedScene->osg::Group::traverse(cbbv);
410
411            osg::BoundingBox bb = cbbv.getBoundingBox();
412
413            if (lightpos[3]!=0.0)   // point light
414            {
415                osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z());
416
417                float centerDistance = (position-bb.center()).length();
418
419                float znear = centerDistance-bb.radius();
420                float zfar  = centerDistance+bb.radius();
421                float zNearRatio = 0.001f;
422                if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
423
424                float top   = (bb.radius()/centerDistance)*znear;
425                float right = top;
426
427                _camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar);
428                _camera->setViewMatrixAsLookAt(position,bb.center(),computeOrthogonalVector(bb.center()-position));
429            }
430            else    // directional light
431            {
432                // make an orthographic projection
433                osg::Vec3 lightDir(lightpos.x(), lightpos.y(), lightpos.z());
434                lightDir.normalize();
435
436                // set the position far away along the light direction
437                osg::Vec3 position = bb.center() + lightDir * bb.radius() * 2;
438
439                float centerDistance = (position-bb.center()).length();
440
441                float znear = centerDistance-bb.radius();
442                float zfar  = centerDistance+bb.radius();
443                float zNearRatio = 0.001f;
444                if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
445
446                float top   = bb.radius();
447                float right = top;
448
449                _camera->setProjectionMatrixAsOrtho(-right, right, -top, top, znear, zfar);
450                _camera->setViewMatrixAsLookAt(position,bb.center(),computeOrthogonalVector(lightDir));
451            }
452
453
454        }
455
456        cv.setTraversalMask( traversalMask &
457            getShadowedScene()->getCastsShadowTraversalMask() );
458
459        // do RTT camera traversal
460        _camera->accept(cv);
461
462        _texgen->setMode(osg::TexGen::EYE_LINEAR);
463
464#if IMPROVE_TEXGEN_PRECISION
465        // compute the matrix which takes a vertex from local coords into tex coords
466        // We actually use two matrices one used to define texgen
467        // and second that will be used as modelview when appling to OpenGL
468        _texgen->setPlanesFromMatrix( _camera->getProjectionMatrix() *
469                                      osg::Matrix::translate(1.0,1.0,1.0) *
470                                      osg::Matrix::scale(0.5f,0.5f,0.5f) );
471
472        // Place texgen with modelview which removes big offsets (making it float friendly)
473        osg::RefMatrix * refMatrix = new osg::RefMatrix
474            ( _camera->getInverseViewMatrix() * *cv.getModelViewMatrix() );
475
476        cv.getRenderStage()->getPositionalStateContainer()->
477             addPositionedTextureAttribute( _shadowTextureUnit, refMatrix, _texgen.get() );
478#else
479        // compute the matrix which takes a vertex from local coords into tex coords
480        // will use this later to specify osg::TexGen..
481        osg::Matrix MVPT = _camera->getViewMatrix() *
482               _camera->getProjectionMatrix() *
483               osg::Matrix::translate(1.0,1.0,1.0) *
484               osg::Matrix::scale(0.5f,0.5f,0.5f);
485
486        _texgen->setPlanesFromMatrix(MVPT);
487
488        orig_rs->getPositionalStateContainer()->addPositionedTextureAttribute(_shadowTextureUnit, cv.getModelViewMatrix(), _texgen.get());
489#endif
490    } // if(selectLight)
491
492
493    // reapply the original traversal mask
494    cv.setTraversalMask( traversalMask );
495}
496
497void ShadowMap::cleanSceneGraph()
498{
499}
500
501///////////////////// Debug Methods
502
503////////////////////////////////////////////////////////////////////////////////
504// Callback used by debugging hud to display Shadow Map in color buffer
505// OSG does not allow to use the same GL Texture Id with different glTexParams.
506// Callback simply turns shadow compare mode off via GL while rendering hud and
507// restores it afterwards.
508////////////////////////////////////////////////////////////////////////////////
509class ShadowMap::DrawableDrawWithDepthShadowComparisonOffCallback:
510    public osg::Drawable::DrawCallback
511{
512public:
513    //
514    DrawableDrawWithDepthShadowComparisonOffCallback
515        ( osg::Texture2D * texture, unsigned stage = 0 )
516            : _texture( texture ), _stage( stage )
517    {
518    }
519
520    virtual void drawImplementation
521        ( osg::RenderInfo & ri,const osg::Drawable* drawable ) const
522    {
523        if( _texture.valid() ) {
524            // make sure proper texture is currently applied
525            ri.getState()->applyTextureAttribute( _stage, _texture.get() );
526
527            // Turn off depth comparison mode
528            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
529                             GL_NONE );
530        }
531
532        drawable->drawImplementation(ri);
533
534        if( _texture.valid() ) {
535            // Turn it back on
536            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
537                             GL_COMPARE_R_TO_TEXTURE_ARB );
538        }
539    }
540
541    osg::ref_ptr< osg::Texture2D > _texture;
542    unsigned                       _stage;
543};
544
545////////////////////////////////////////////////////////////////////////////////
546osg::ref_ptr<osg::Camera> ShadowMap::makeDebugHUD()
547{
548    // Make sure we attach initialized texture to HUD
549    if( !_texture.valid() )    init();
550
551    osg::ref_ptr<osg::Camera> camera = new osg::Camera;
552
553    osg::Vec2 size(1280, 1024);
554    // set the projection matrix
555    camera->setProjectionMatrix(osg::Matrix::ortho2D(0,size.x(),0,size.y()));
556
557    // set the view matrix
558    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
559    camera->setViewMatrix(osg::Matrix::identity());
560
561    // only clear the depth buffer
562    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
563    camera->setClearColor(osg::Vec4(0.2f, 0.3f, 0.5f, 0.2f));
564    //camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
565
566    // draw subgraph after main camera view.
567    camera->setRenderOrder(osg::Camera::POST_RENDER);
568
569    // we don't want the camera to grab event focus from the viewers main camera(s).
570    camera->setAllowEventFocus(false);
571
572    osg::Geode* geode = new osg::Geode;
573
574    osg::Vec3 position(10.0f,size.y()-100.0f,0.0f);
575    osg::Vec3 delta(0.0f,-120.0f,0.0f);
576    float length = 300.0f;
577
578    // turn the text off to avoid linking with osgText
579#if 0
580    std::string timesFont("fonts/arial.ttf");
581
582    {
583        osgText::Text* text = new  osgText::Text;
584        geode->addDrawable( text );
585
586        text->setFont(timesFont);
587        text->setPosition(position);
588        text->setText("Shadow Map HUD");
589
590        position += delta;
591    }
592#endif
593
594    osg::Vec3 widthVec(length, 0.0f, 0.0f);
595    osg::Vec3 depthVec(0.0f,length, 0.0f);
596    osg::Vec3 centerBase( 10.0f + length/2, size.y()-length/2, 0.0f);
597    centerBase += delta;
598
599    osg::Geometry *geometry = osg::createTexturedQuadGeometry
600        ( centerBase-widthVec*0.5f-depthVec*0.5f, widthVec, depthVec );
601
602    geode->addDrawable( geometry );
603
604    geometry->setDrawCallback
605        ( new DrawableDrawWithDepthShadowComparisonOffCallback( _texture.get() ) );
606
607    osg::StateSet* stateset = geode->getOrCreateStateSet();
608
609    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
610    stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
611    stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
612
613    // test with regular texture
614    //stateset->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")));
615
616    stateset->setTextureAttributeAndModes(0,_texture.get(),osg::StateAttribute::ON);
617
618    //test to check the texture coordinates generated during shadow pass
619#if 0
620    stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
621    stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
622    stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
623    stateset->setTextureMode(_shadowTextureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
624
625    // create TexGen node
626    osg::ref_ptr<osg::TexGenNode> texGenNode = new osg::TexGenNode;
627    texGenNode->setTextureUnit(_shadowTextureUnit);
628    texGenNode->setTexGen(_texgen.get());
629    camera->addChild(texGenNode.get());
630#endif
631    //shader for correct display
632
633    osg::ref_ptr<osg::Program> program = new osg::Program;
634    stateset->setAttribute(program.get());
635
636    osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_debugHUD);
637    program->addShader(fragment_shader);
638
639    camera->addChild(geode);
640
641    return camera;
642}
643
644//////////////////////// End Debug Section
Note: See TracBrowser for help on using the browser.