root/OpenSceneGraph/trunk/src/osgShadow/ViewDependentShadowMap.cpp @ 13109

Revision 13109, 85.6 kB (checked in by robert, 7 days ago)

Release OpenSceneGraph-3.2.1

Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2011 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/ViewDependentShadowMap>
15#include <osgShadow/ShadowedScene>
16#include <osg/CullFace>
17#include <osg/Geode>
18#include <osg/io_utils>
19
20#include <sstream>
21
22using namespace osgShadow;
23
24//////////////////////////////////////////////////////////////////
25// fragment shader
26//
27#if 0
28static const char fragmentShaderSource_withBaseTexture[] =
29        "uniform sampler2D baseTexture;                                          \n"
30        "uniform sampler2DShadow shadowTexture;                                  \n"
31        "                                                                        \n"
32        "void main(void)                                                         \n"
33        "{                                                                       \n"
34        "  vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor;     \n"
35        "  vec4 color = texture2D( baseTexture, gl_TexCoord[0].xy );                                            \n"
36        "  color *= mix( colorAmbientEmissive, gl_Color, shadow2DProj( shadowTexture, gl_TexCoord[1] ).r );     \n"
37        "  gl_FragColor = color;                                                                                \n"
38        "} \n";
39#else
40static const char fragmentShaderSource_withBaseTexture[] =
41        "uniform sampler2D baseTexture;                                          \n"
42        "uniform int baseTextureUnit;                                            \n"
43        "uniform sampler2DShadow shadowTexture0;                                 \n"
44        "uniform int shadowTextureUnit0;                                         \n"
45        "                                                                        \n"
46        "void main(void)                                                         \n"
47        "{                                                                       \n"
48        "  vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor;     \n"
49        "  vec4 color = texture2D( baseTexture, gl_TexCoord[baseTextureUnit].xy );                                              \n"
50        "  color *= mix( colorAmbientEmissive, gl_Color, shadow2DProj( shadowTexture0, gl_TexCoord[shadowTextureUnit0] ).r );     \n"
51        "  gl_FragColor = color;                                                                                                \n"
52        "} \n";
53
54static const char fragmentShaderSource_withBaseTexture_twoShadowMaps[] =
55        "uniform sampler2D baseTexture;                                          \n"
56        "uniform int baseTextureUnit;                                            \n"
57        "uniform sampler2DShadow shadowTexture0;                                 \n"
58        "uniform int shadowTextureUnit0;                                         \n"
59        "uniform sampler2DShadow shadowTexture1;                                 \n"
60        "uniform int shadowTextureUnit1;                                         \n"
61        "                                                                        \n"
62        "void main(void)                                                         \n"
63        "{                                                                       \n"
64        "  vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor;     \n"
65        "  vec4 color = texture2D( baseTexture, gl_TexCoord[baseTextureUnit].xy );              \n"
66        "  float shadow0 = shadow2DProj( shadowTexture0, gl_TexCoord[shadowTextureUnit0] ).r;   \n"
67        "  float shadow1 = shadow2DProj( shadowTexture1, gl_TexCoord[shadowTextureUnit1] ).r;   \n"
68        "  color *= mix( colorAmbientEmissive, gl_Color, shadow0*shadow1 );                     \n"
69        "  gl_FragColor = color;                                                                \n"
70        "} \n";
71#endif
72
73template<class T>
74class RenderLeafTraverser : public T
75{
76public:
77
78    RenderLeafTraverser()
79    {
80    }
81
82    void traverse(const osgUtil::RenderStage* rs)
83    {
84        traverse(static_cast<const osgUtil::RenderBin*>(rs));
85    }
86
87    void traverse(const osgUtil::RenderBin* renderBin)
88    {
89        const osgUtil::RenderBin::RenderBinList& rbl = renderBin->getRenderBinList();
90        for(osgUtil::RenderBin::RenderBinList::const_iterator itr = rbl.begin();
91            itr != rbl.end();
92            ++itr)
93        {
94            traverse(itr->second.get());
95        }
96
97        const osgUtil::RenderBin::RenderLeafList& rll = renderBin->getRenderLeafList();
98        for(osgUtil::RenderBin::RenderLeafList::const_iterator itr = rll.begin();
99            itr != rll.end();
100            ++itr)
101        {
102            handle(*itr);
103        }
104
105        const osgUtil::RenderBin::StateGraphList& rgl = renderBin->getStateGraphList();
106        for(osgUtil::RenderBin::StateGraphList::const_iterator itr = rgl.begin();
107            itr != rgl.end();
108            ++itr)
109        {
110            traverse(*itr);
111        }
112
113    }
114
115    void traverse(const osgUtil::StateGraph* stateGraph)
116    {
117        const osgUtil::StateGraph::ChildList& cl = stateGraph->_children;
118        for(osgUtil::StateGraph::ChildList::const_iterator itr = cl.begin();
119            itr != cl.end();
120            ++itr)
121        {
122            traverse(itr->second.get());
123        }
124
125        const osgUtil::StateGraph::LeafList& ll = stateGraph->_leaves;
126        for(osgUtil::StateGraph::LeafList::const_iterator itr = ll.begin();
127            itr != ll.end();
128            ++itr)
129        {
130            handle(itr->get());
131        }
132    }
133
134    inline void handle(const osgUtil::RenderLeaf* renderLeaf)
135    {
136        this->operator()(renderLeaf);
137    }
138};
139
140///////////////////////////////////////////////////////////////////////////////////////////////
141//
142// VDSMCameraCullCallback
143//
144class VDSMCameraCullCallback : public osg::NodeCallback
145{
146    public:
147
148        VDSMCameraCullCallback(ViewDependentShadowMap* vdsm, osg::Polytope& polytope);
149
150        virtual void operator()(osg::Node*, osg::NodeVisitor* nv);
151
152        osg::RefMatrix* getProjectionMatrix() { return _projectionMatrix.get(); }
153        osgUtil::RenderStage* getRenderStage() { return _renderStage.get(); }
154
155    protected:
156
157        ViewDependentShadowMap*                 _vdsm;
158        osg::ref_ptr<osg::RefMatrix>            _projectionMatrix;
159        osg::ref_ptr<osgUtil::RenderStage>      _renderStage;
160        osg::Polytope                           _polytope;
161};
162
163VDSMCameraCullCallback::VDSMCameraCullCallback(ViewDependentShadowMap* vdsm, osg::Polytope& polytope):
164    _vdsm(vdsm),
165    _polytope(polytope)
166{
167}
168
169void VDSMCameraCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
170{
171    osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
172    osg::Camera* camera = dynamic_cast<osg::Camera*>(node);
173    OSG_INFO<<"VDSMCameraCullCallback::operator()(osg::Node* "<<camera<<", osg::NodeVisitor* "<<cv<<")"<<std::endl;
174
175#if 1
176    if (!_polytope.empty())
177    {
178        OSG_INFO<<"Pushing custom Polytope"<<std::endl;
179
180        osg::CullingSet& cs = cv->getProjectionCullingStack().back();
181
182        cs.setFrustum(_polytope);
183
184        cv->pushCullingSet();
185    }
186#endif
187    if (_vdsm->getShadowedScene())
188    {
189        _vdsm->getShadowedScene()->osg::Group::traverse(*nv);
190    }
191#if 1
192    if (!_polytope.empty())
193    {
194        OSG_INFO<<"Popping custom Polytope"<<std::endl;
195        cv->popCullingSet();
196    }
197#endif
198
199    _renderStage = cv->getCurrentRenderBin()->getStage();
200
201    OSG_INFO<<"VDSM second : _renderStage = "<<_renderStage<<std::endl;
202
203    if (cv->getComputeNearFarMode() != osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
204    {
205        // make sure that the near plane is computed correctly.
206        cv->computeNearPlane();
207
208        osg::Matrixd projection = *(cv->getProjectionMatrix());
209
210        OSG_INFO<<"RTT Projection matrix "<<projection<<std::endl;
211
212        osg::Matrix::value_type left, right, bottom, top, zNear, zFar;
213        osg::Matrix::value_type epsilon = 1e-6;
214        if (fabs(projection(0,3))<epsilon  && fabs(projection(1,3))<epsilon  && fabs(projection(2,3))<epsilon )
215        {
216            projection.getOrtho(left, right,
217                                bottom, top,
218                                zNear,  zFar);
219
220            OSG_INFO<<"Ortho zNear="<<zNear<<", zFar="<<zFar<<std::endl;
221        }
222        else
223        {
224            projection.getFrustum(left, right,
225                                bottom, top,
226                                zNear,  zFar);
227
228            OSG_INFO<<"Frustum zNear="<<zNear<<", zFar="<<zFar<<std::endl;
229        }
230
231        OSG_INFO<<"Calculated zNear = "<<cv->getCalculatedNearPlane()<<", zFar = "<<cv->getCalculatedFarPlane()<<std::endl;
232
233        zNear = osg::maximum(zNear, cv->getCalculatedNearPlane());
234        zFar = osg::minimum(zFar, cv->getCalculatedFarPlane());
235
236        cv->setCalculatedNearPlane(zNear);
237        cv->setCalculatedFarPlane(zFar);
238
239        cv->clampProjectionMatrix(projection, zNear, zFar);
240
241        //OSG_INFO<<"RTT zNear = "<<zNear<<", zFar = "<<zFar<<std::endl;
242        OSG_INFO<<"RTT Projection matrix after clamping "<<projection<<std::endl;
243
244        camera->setProjectionMatrix(projection);
245
246        _projectionMatrix = cv->getProjectionMatrix();
247    }
248}
249
250
251class ComputeLightSpaceBounds : public osg::NodeVisitor, public osg::CullStack
252{
253public:
254    ComputeLightSpaceBounds(osg::Viewport* viewport, const osg::Matrixd& projectionMatrix, osg::Matrixd& viewMatrix):
255        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
256    {
257        setCullingMode(osg::CullSettings::VIEW_FRUSTUM_CULLING);
258
259        pushViewport(viewport);
260        pushProjectionMatrix(new osg::RefMatrix(projectionMatrix));
261        pushModelViewMatrix(new osg::RefMatrix(viewMatrix),osg::Transform::ABSOLUTE_RF);
262    }
263
264    void apply(osg::Node& node)
265    {
266        if (isCulled(node)) return;
267
268        // push the culling mode.
269        pushCurrentMask();
270
271        traverse(node);
272
273        // pop the culling mode.
274        popCurrentMask();
275    }
276
277    void apply(osg::Geode& node)
278    {
279        if (isCulled(node)) return;
280
281        // push the culling mode.
282        pushCurrentMask();
283
284        for(unsigned int i=0; i<node.getNumDrawables();++i)
285        {
286            if (node.getDrawable(i))
287            {
288                updateBound(node.getDrawable(i)->getBound());
289            }
290        }
291
292        // pop the culling mode.
293        popCurrentMask();
294    }
295
296    void apply(osg::Billboard&)
297    {
298        OSG_INFO<<"Warning Billboards not yet supported"<<std::endl;
299        return;
300    }
301
302    void apply(osg::Projection&)
303    {
304        // projection nodes won't affect a shadow map so their subgraphs should be ignored
305        return;
306    }
307
308    void apply(osg::Transform& transform)
309    {
310        if (isCulled(transform)) return;
311
312        // push the culling mode.
313        pushCurrentMask();
314
315        // absolute transforms won't affect a shadow map so their subgraphs should be ignored.
316        if (transform.getReferenceFrame()==osg::Transform::RELATIVE_RF)
317        {
318            osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix(*getModelViewMatrix());
319            transform.computeLocalToWorldMatrix(*matrix,this);
320            pushModelViewMatrix(matrix.get(), transform.getReferenceFrame());
321
322            traverse(transform);
323
324            popModelViewMatrix();
325        }
326
327        // pop the culling mode.
328        popCurrentMask();
329
330    }
331
332    void apply(osg::Camera&)
333    {
334        // camera nodes won't affect a shadow map so their subgraphs should be ignored
335        return;
336    }
337
338    void updateBound(const osg::BoundingBox& bb)
339    {
340        if (!bb.valid()) return;
341
342        const osg::Matrix& matrix = *getModelViewMatrix() * *getProjectionMatrix();
343
344        update(bb.corner(0) * matrix);
345        update(bb.corner(1) * matrix);
346        update(bb.corner(2) * matrix);
347        update(bb.corner(3) * matrix);
348        update(bb.corner(4) * matrix);
349        update(bb.corner(5) * matrix);
350        update(bb.corner(6) * matrix);
351        update(bb.corner(7) * matrix);
352    }
353
354    void update(const osg::Vec3& v)
355    {
356        if (v.z()<-1.0f)
357        {
358            //OSG_NOTICE<<"discarding("<<v<<")"<<std::endl;
359            return;
360        }
361        float x = v.x();
362        if (x<-1.0f) x=-1.0f;
363        if (x>1.0f) x=1.0f;
364        float y = v.y();
365        if (y<-1.0f) y=-1.0f;
366        if (y>1.0f) y=1.0f;
367        _bb.expandBy(osg::Vec3(x,y,v.z()));
368    }
369
370    osg::BoundingBox _bb;
371};
372
373///////////////////////////////////////////////////////////////////////////////////////////////
374//
375// LightData
376//
377ViewDependentShadowMap::LightData::LightData(ViewDependentShadowMap::ViewDependentData* vdd):
378    _viewDependentData(vdd),
379    directionalLight(false)
380{
381}
382
383void ViewDependentShadowMap::LightData::setLightData(osg::RefMatrix* lm, const osg::Light* l, const osg::Matrixd& modelViewMatrix)
384{
385    lightMatrix = lm;
386    light = l;
387
388    lightPos = light->getPosition();
389    directionalLight = (light->getPosition().w()== 0.0);
390    if (directionalLight)
391    {
392        lightPos3.set(0.0, 0.0, 0.0); // directional light has no destinct position
393        lightDir.set(-lightPos.x(), -lightPos.y(), -lightPos.z());
394        lightDir.normalize();
395        OSG_INFO<<"   Directional light, lightPos="<<lightPos<<", lightDir="<<lightDir<<std::endl;
396        if (lightMatrix.valid())
397        {
398            OSG_INFO<<"   Light matrix "<<*lightMatrix<<std::endl;
399            osg::Matrix lightToLocalMatrix(*lightMatrix * osg::Matrix::inverse(modelViewMatrix) );
400            lightDir = osg::Matrix::transform3x3( lightDir, lightToLocalMatrix );
401            lightDir.normalize();
402            OSG_INFO<<"   new LightDir ="<<lightDir<<std::endl;
403        }
404    }
405    else
406    {
407        OSG_INFO<<"   Positional light, lightPos="<<lightPos<<std::endl;
408        lightDir = light->getDirection();
409        lightDir.normalize();
410        if (lightMatrix.valid())
411        {
412            OSG_INFO<<"   Light matrix "<<*lightMatrix<<std::endl;
413            osg::Matrix lightToLocalMatrix(*lightMatrix * osg::Matrix::inverse(modelViewMatrix) );
414            lightPos = lightPos * lightToLocalMatrix;
415            lightDir = osg::Matrix::transform3x3( lightDir, lightToLocalMatrix );
416            lightDir.normalize();
417            OSG_INFO<<"   new LightPos ="<<lightPos<<std::endl;
418            OSG_INFO<<"   new LightDir ="<<lightDir<<std::endl;
419        }
420        lightPos3.set(lightPos.x()/lightPos.w(), lightPos.y()/lightPos.w(), lightPos.z()/lightPos.w());
421    }
422}
423
424///////////////////////////////////////////////////////////////////////////////////////////////
425//
426// ShadowData
427//
428ViewDependentShadowMap::ShadowData::ShadowData(ViewDependentShadowMap::ViewDependentData* vdd):
429    _viewDependentData(vdd),
430    _textureUnit(0)
431{
432
433    const ShadowSettings* settings = vdd->getViewDependentShadowMap()->getShadowedScene()->getShadowSettings();
434
435    bool debug = settings->getDebugDraw();
436
437    // set up texgen
438    _texgen = new osg::TexGen;
439
440    // set up the texture
441    _texture = new osg::Texture2D;
442
443    osg::Vec2s textureSize = debug ? osg::Vec2s(512,512) : settings->getTextureSize();
444    _texture->setTextureSize(textureSize.x(), textureSize.y());
445
446    if (debug)
447    {
448        _texture->setInternalFormat(GL_RGB);
449    }
450    else
451    {
452        _texture->setInternalFormat(GL_DEPTH_COMPONENT);
453        _texture->setShadowComparison(true);
454        _texture->setShadowTextureMode(osg::Texture2D::LUMINANCE);
455    }
456
457    _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
458    _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
459
460    // the shadow comparison should fail if object is outside the texture
461    _texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
462    _texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
463    _texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
464    //_texture->setBorderColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
465
466    // set up the camera
467    _camera = new osg::Camera;
468    _camera->setName("ShadowCamera");
469    _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT);
470
471    //_camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
472    _camera->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
473
474    _camera->setComputeNearFarMode(osg::Camera::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES);
475    //_camera->setComputeNearFarMode(osg::Camera::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
476
477    // switch off small feature culling as this can cull out geometry that will still be large enough once perspective correction takes effect.
478    _camera->setCullingMode(_camera->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING);
479
480    // set viewport
481    _camera->setViewport(0,0,textureSize.x(),textureSize.y());
482
483
484    if (debug)
485    {
486        // clear just the depth buffer
487        _camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
488
489        // render after the main camera
490        _camera->setRenderOrder(osg::Camera::POST_RENDER);
491
492        // attach the texture and use it as the color buffer.
493        //_camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get());
494        _camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
495    }
496    else
497    {
498        // clear the depth and colour bufferson each clear.
499        _camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
500
501        // set the camera to render before the main camera.
502        _camera->setRenderOrder(osg::Camera::PRE_RENDER);
503
504        // tell the camera to use OpenGL frame buffer object where supported.
505        _camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
506
507        // attach the texture and use it as the color buffer.
508        _camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get());
509        //_camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
510    }
511}
512
513void ViewDependentShadowMap::ShadowData::releaseGLObjects(osg::State* state) const
514{
515    OSG_INFO<<"ViewDependentShadowMap::ShadowData::releaseGLObjects"<<std::endl;
516    _texture->releaseGLObjects(state);
517    _camera->releaseGLObjects(state);
518}
519
520///////////////////////////////////////////////////////////////////////////////////////////////
521//
522// Frustum
523//
524ViewDependentShadowMap::Frustum::Frustum(osgUtil::CullVisitor* cv, double minZNear, double maxZFar):
525    corners(8),
526    faces(6),
527    edges(12)
528{
529    projectionMatrix = *(cv->getProjectionMatrix());
530    modelViewMatrix = *(cv->getModelViewMatrix());
531
532    OSG_INFO<<"Projection matrix "<<projectionMatrix<<std::endl;
533
534    if (cv->getComputeNearFarMode()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
535    {
536        osg::Matrix::value_type zNear = osg::maximum<osg::Matrix::value_type>(cv->getCalculatedNearPlane(),minZNear);
537        osg::Matrix::value_type zFar = osg::minimum<osg::Matrix::value_type>(cv->getCalculatedFarPlane(),maxZFar);
538
539        cv->clampProjectionMatrix(projectionMatrix, zNear, zFar);
540
541        OSG_INFO<<"zNear = "<<zNear<<", zFar = "<<zFar<<std::endl;
542        OSG_INFO<<"Projection matrix after clamping "<<projectionMatrix<<std::endl;
543    }
544
545    corners[0].set(-1.0,-1.0,-1.0);
546    corners[1].set(1.0,-1.0,-1.0);
547    corners[2].set(1.0,-1.0,1.0);
548    corners[3].set(-1.0,-1.0,1.0);
549    corners[4].set(-1.0,1.0,-1.0);
550    corners[5].set(1.0,1.0,-1.0);
551    corners[6].set(1.0,1.0,1.0);
552    corners[7].set(-1.0,1.0,1.0);
553
554    osg::Matrixd clipToWorld;
555    clipToWorld.invert(modelViewMatrix * projectionMatrix);
556
557    // transform frustum corners from clipspace to world coords, and compute center
558    for(Vertices::iterator itr = corners.begin();
559        itr != corners.end();
560        ++itr)
561    {
562        *itr = (*itr) * clipToWorld;
563
564        OSG_INFO<<"   corner "<<*itr<<std::endl;
565    }
566
567    // compute eye point
568    eye = osg::Vec3d(0.0,0.0,0.0) * osg::Matrix::inverse(modelViewMatrix);
569
570    // compute center and the frustumCenterLine
571    centerNearPlane = (corners[0]+corners[1]+corners[5]+corners[4])*0.25;
572    centerFarPlane = (corners[3]+corners[2]+corners[6]+corners[7])*0.25;
573    center = (centerNearPlane+centerFarPlane)*0.5;
574    frustumCenterLine = centerFarPlane-centerNearPlane;
575    frustumCenterLine.normalize();
576
577    OSG_INFO<<"   center "<<center<<std::endl;
578
579    faces[0].push_back(0);
580    faces[0].push_back(3);
581    faces[0].push_back(7);
582    faces[0].push_back(4);
583
584    faces[1].push_back(1);
585    faces[1].push_back(5);
586    faces[1].push_back(6);
587    faces[1].push_back(2);
588
589    faces[2].push_back(0);
590    faces[2].push_back(1);
591    faces[2].push_back(2);
592    faces[2].push_back(3);
593
594    faces[3].push_back(4);
595    faces[3].push_back(7);
596    faces[3].push_back(6);
597    faces[3].push_back(5);
598
599    faces[4].push_back(0);
600    faces[4].push_back(4);
601    faces[4].push_back(5);
602    faces[4].push_back(1);
603
604    faces[5].push_back(2);
605    faces[5].push_back(6);
606    faces[5].push_back(7);
607    faces[5].push_back(3);
608
609    edges[0].push_back(0); edges[0].push_back(1); // corner points on edge
610    edges[0].push_back(2); edges[0].push_back(4); // faces on edge
611
612    edges[1].push_back(1); edges[1].push_back(2); // corner points on edge
613    edges[1].push_back(2); edges[1].push_back(1); // faces on edge
614
615    edges[2].push_back(2); edges[2].push_back(3); // corner points on edge
616    edges[2].push_back(2); edges[2].push_back(5); // faces on edge
617
618    edges[3].push_back(3); edges[3].push_back(0); // corner points on edge
619    edges[3].push_back(2); edges[3].push_back(0); // faces on edge
620
621
622    edges[4].push_back(0); edges[4].push_back(4); // corner points on edge
623    edges[4].push_back(0); edges[4].push_back(4); // faces on edge
624
625    edges[5].push_back(1); edges[5].push_back(5); // corner points on edge
626    edges[5].push_back(4); edges[5].push_back(1); // faces on edge
627
628    edges[6].push_back(2); edges[6].push_back(6); // corner points on edge
629    edges[6].push_back(1); edges[6].push_back(5); // faces on edge
630
631    edges[7].push_back(3); edges[7].push_back(7); // corner points on edge
632    edges[7].push_back(5); edges[7].push_back(0); // faces on edge
633
634
635    edges[8].push_back(4); edges[8].push_back(5); // corner points on edge
636    edges[8].push_back(3); edges[8].push_back(4); // faces on edge
637
638    edges[9].push_back(5); edges[9].push_back(6); // corner points on edge
639    edges[9].push_back(3); edges[9].push_back(1); // faces on edge
640
641    edges[10].push_back(6);edges[10].push_back(7); // corner points on edge
642    edges[10].push_back(3);edges[10].push_back(5); // faces on edge
643
644    edges[11].push_back(7); edges[11].push_back(4); // corner points on edge
645    edges[11].push_back(3); edges[11].push_back(0); // faces on edge
646}
647
648
649///////////////////////////////////////////////////////////////////////////////////////////////
650//
651// ViewDependentData
652//
653ViewDependentShadowMap::ViewDependentData::ViewDependentData(ViewDependentShadowMap* vdsm):
654    _viewDependentShadowMap(vdsm)
655{
656    OSG_INFO<<"ViewDependentData::ViewDependentData()"<<this<<std::endl;
657    _stateset = new osg::StateSet;
658}
659
660void ViewDependentShadowMap::ViewDependentData::releaseGLObjects(osg::State* state) const
661{
662    for(ShadowDataList::const_iterator itr = _shadowDataList.begin();
663        itr != _shadowDataList.end();
664        ++itr)
665    {
666        (*itr)->releaseGLObjects(state);
667    }
668}
669
670///////////////////////////////////////////////////////////////////////////////////////////////
671//
672// ViewDependentShadowMap
673//
674ViewDependentShadowMap::ViewDependentShadowMap():
675    ShadowTechnique()
676{
677    _shadowRecievingPlaceholderStateSet = new osg::StateSet;
678}
679
680ViewDependentShadowMap::ViewDependentShadowMap(const ViewDependentShadowMap& vdsm, const osg::CopyOp& copyop):
681    ShadowTechnique(vdsm,copyop)
682{
683    _shadowRecievingPlaceholderStateSet = new osg::StateSet;
684}
685
686ViewDependentShadowMap::~ViewDependentShadowMap()
687{
688}
689
690
691void ViewDependentShadowMap::init()
692{
693    if (!_shadowedScene) return;
694
695    OSG_INFO<<"ViewDependentShadowMap::init()"<<std::endl;
696
697    createShaders();
698
699    _dirty = false;
700}
701
702void ViewDependentShadowMap::cleanSceneGraph()
703{
704    OSG_INFO<<"ViewDependentShadowMap::cleanSceneGraph()"<<std::endl;
705}
706
707ViewDependentShadowMap::ViewDependentData* ViewDependentShadowMap::createViewDependentData(osgUtil::CullVisitor* cv)
708{
709    return new ViewDependentData(this);
710}
711
712ViewDependentShadowMap::ViewDependentData* ViewDependentShadowMap::getViewDependentData(osgUtil::CullVisitor* cv)
713{
714    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_viewDependentDataMapMutex);
715    ViewDependentDataMap::iterator itr = _viewDependentDataMap.find(cv);
716    if (itr!=_viewDependentDataMap.end()) return itr->second.get();
717
718    osg::ref_ptr<ViewDependentData> vdd = createViewDependentData(cv);
719    _viewDependentDataMap[cv] = vdd;
720    return vdd.release();
721}
722
723void ViewDependentShadowMap::update(osg::NodeVisitor& nv)
724{
725    OSG_INFO<<"ViewDependentShadowMap::update(osg::NodeVisitor& "<<&nv<<")"<<std::endl;
726    _shadowedScene->osg::Group::traverse(nv);
727}
728
729void ViewDependentShadowMap::cull(osgUtil::CullVisitor& cv)
730{
731    OSG_INFO<<std::endl<<std::endl<<"ViewDependentShadowMap::cull(osg::CullVisitor&"<<&cv<<")"<<std::endl;
732
733    if (!_shadowCastingStateSet)
734    {
735        OSG_INFO<<"Warning, init() has not yet been called so ShadowCastingStateSet has not been setup yet, unable to create shadows."<<std::endl;
736        _shadowedScene->osg::Group::traverse(cv);
737        return;
738    }
739
740    ViewDependentData* vdd = getViewDependentData(&cv);
741
742    if (!vdd)
743    {
744        OSG_INFO<<"Warning, now ViewDependentData created, unable to create shadows."<<std::endl;
745        _shadowedScene->osg::Group::traverse(cv);
746        return;
747    }
748
749    ShadowSettings* settings = getShadowedScene()->getShadowSettings();
750
751    OSG_INFO<<"cv->getProjectionMatrix()="<<*cv.getProjectionMatrix()<<std::endl;
752
753    osg::CullSettings::ComputeNearFarMode cachedNearFarMode = cv.getComputeNearFarMode();
754
755    osg::RefMatrix& viewProjectionMatrix = *cv.getProjectionMatrix();
756
757    // check whether this main views projection is perspective or orthographic
758    bool orthographicViewFrustum = viewProjectionMatrix(0,3)==0.0 &&
759                                   viewProjectionMatrix(1,3)==0.0 &&
760                                   viewProjectionMatrix(2,3)==0.0;
761
762    double minZNear = 0.0;
763    double maxZFar = DBL_MAX;
764
765    if (cachedNearFarMode==osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
766    {
767        double left, right, top, bottom;
768        if (orthographicViewFrustum)
769        {
770            viewProjectionMatrix.getOrtho(left, right, bottom, top, minZNear, maxZFar);
771        }
772        else
773        {
774            viewProjectionMatrix.getFrustum(left, right, bottom, top, minZNear, maxZFar);
775        }
776        OSG_INFO<<"minZNear="<<minZNear<<", maxZFar="<<maxZFar<<std::endl;
777    }
778
779    // set the compute near/far mode to the highest quality setting to ensure we push the near plan out as far as possible
780    if (settings->getComputeNearFarModeOverride()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
781    {
782        cv.setComputeNearFarMode(settings->getComputeNearFarModeOverride());
783    }
784
785    // 1. Traverse main scene graph
786    cv.pushStateSet( _shadowRecievingPlaceholderStateSet.get() );
787
788    osg::ref_ptr<osgUtil::StateGraph> decoratorStateGraph = cv.getCurrentStateGraph();
789
790    cullShadowReceivingScene(&cv);
791
792    cv.popStateSet();
793
794    if (cv.getComputeNearFarMode()!=osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR)
795    {
796        OSG_INFO<<"Just done main subgraph traversak"<<std::endl;
797        // make sure that the near plane is computed correctly so that any projection matrix computations
798        // are all done correctly.
799        cv.computeNearPlane();
800    }
801
802    //minZNear = osg::maximum(10.0,minZNear);
803    //maxZFar = osg::minimum(60.0,maxZFar);
804
805    Frustum frustum(&cv, minZNear, maxZFar);
806
807    // return compute near far mode back to it's original settings
808    cv.setComputeNearFarMode(cachedNearFarMode);
809
810    OSG_INFO<<"frustum.eye="<<frustum.eye<<", frustum.centerNearPlane, "<<frustum.centerNearPlane<<" distance = "<<(frustum.eye-frustum.centerNearPlane).length()<<std::endl;
811
812
813    // 2. select active light sources
814    //    create a list of light sources + their matrices to place them
815    selectActiveLights(&cv, vdd);
816
817
818    unsigned int pos_x = 0;
819    unsigned int textureUnit = settings->getBaseShadowTextureUnit();
820    unsigned int numValidShadows = 0;
821
822    ShadowDataList& sdl = vdd->getShadowDataList();
823    ShadowDataList previous_sdl;
824    previous_sdl.swap(sdl);
825
826    unsigned int numShadowMapsPerLight = settings->getNumShadowMapsPerLight();
827    if (numShadowMapsPerLight>2)
828    {
829        OSG_NOTICE<<"numShadowMapsPerLight of "<<numShadowMapsPerLight<<" is greater than maximum supported, falling back to 2."<<std::endl;
830        numShadowMapsPerLight = 2;
831    }
832
833    LightDataList& pll = vdd->getLightDataList();
834    for(LightDataList::iterator itr = pll.begin();
835        itr != pll.end();
836        ++itr)
837    {
838        // 3. create per light/per shadow map division of lightspace/frustum
839        //    create a list of light/shadow map data structures
840
841        LightData& pl = **itr;
842
843        // 3.1 compute light space polytope
844        //
845        osg::Polytope polytope = computeLightViewFrustumPolytope(frustum, pl);
846
847        // if polytope is empty then no rendering.
848        if (polytope.empty())
849        {
850            OSG_NOTICE<<"Polytope empty no shadow to render"<<std::endl;
851            continue;
852        }
853
854        // 3.2 compute RTT camera view+projection matrix settings
855        //
856        osg::Matrixd projectionMatrix;
857        osg::Matrixd viewMatrix;
858        if (!computeShadowCameraSettings(frustum, pl, projectionMatrix, viewMatrix))
859        {
860            OSG_NOTICE<<"No valid Camera settings, no shadow to render"<<std::endl;
861            continue;
862        }
863
864        // if we are using multiple shadow maps and CastShadowTraversalMask is being used
865        // traverse the scene to compute the extents of the objects
866        if (/*numShadowMapsPerLight>1 &&*/ _shadowedScene->getCastsShadowTraversalMask()!=0xffffffff)
867        {
868            // osg::ElapsedTime timer;
869
870            osg::ref_ptr<osg::Viewport> viewport = new osg::Viewport(0,0,2048,2048);
871            ComputeLightSpaceBounds clsb(viewport.get(), projectionMatrix, viewMatrix);
872            clsb.setTraversalMask(_shadowedScene->getCastsShadowTraversalMask());
873
874            osg::Matrixd invertModelView;
875            invertModelView.invert(viewMatrix);
876            osg::Polytope local_polytope(polytope);
877            local_polytope.transformProvidingInverse(invertModelView);
878
879            osg::CullingSet& cs = clsb.getProjectionCullingStack().back();
880            cs.setFrustum(local_polytope);
881            clsb.pushCullingSet();
882
883            _shadowedScene->accept(clsb);
884
885            // OSG_NOTICE<<"Extents of LightSpace "<<clsb._bb.xMin()<<", "<<clsb._bb.xMax()<<", "<<clsb._bb.yMin()<<", "<<clsb._bb.yMax()<<", "<<clsb._bb.zMin()<<", "<<clsb._bb.zMax()<<std::endl;
886            // OSG_NOTICE<<"  time "<<timer.elapsedTime_m()<<"ms, mask = "<<std::hex<<_shadowedScene->getCastsShadowTraversalMask()<<std::endl;
887
888            if (clsb._bb.xMin()>-1.0f || clsb._bb.xMax()<1.0f || clsb._bb.yMin()>-1.0f || clsb._bb.yMax()<1.0f)
889            {
890                // OSG_NOTICE<<"Need to clamp projection matrix"<<std::endl;
891
892#if 1
893                double xMid = (clsb._bb.xMin()+clsb._bb.xMax())*0.5f;
894                double xRange = clsb._bb.xMax()-clsb._bb.xMin();
895#else
896                double xMid = 0.0;
897                double xRange = 2.0;
898#endif
899                double yMid = (clsb._bb.yMin()+clsb._bb.yMax())*0.5f;
900                double yRange = (clsb._bb.yMax()-clsb._bb.yMin());
901
902                // OSG_NOTICE<<"  xMid="<<xMid<<", yMid="<<yMid<<", xRange="<<xRange<<", yRange="<<yRange<<std::endl;
903
904                projectionMatrix =
905                    projectionMatrix *
906                    osg::Matrixd::translate(osg::Vec3d(-xMid,-yMid,0.0)) *
907                    osg::Matrixd::scale(osg::Vec3d(2.0/xRange, 2.0/yRange,1.0));
908
909            }
910
911        }
912
913        double splitPoint = 0.0;
914
915        if (numShadowMapsPerLight>1)
916        {
917            osg::Vec3d eye_v = frustum.eye * viewMatrix;
918            osg::Vec3d center_v = frustum.center * viewMatrix;
919            osg::Vec3d viewdir_v = center_v-eye_v; viewdir_v.normalize();
920            osg::Vec3d lightdir(0.0,0.0,-1.0);
921
922            double dotProduct_v = lightdir * viewdir_v;
923            double angle = acosf(dotProduct_v);
924
925            osg::Vec3d eye_ls = eye_v * projectionMatrix;
926
927            OSG_INFO<<"Angle between view vector and eye "<<osg::RadiansToDegrees(angle)<<std::endl;
928            OSG_INFO<<"eye_ls="<<eye_ls<<std::endl;
929
930            if (eye_ls.y()>=-1.0 && eye_ls.y()<=1.0)
931            {
932                OSG_INFO<<"Eye point inside light space clip region   "<<std::endl;
933                splitPoint = 0.0;
934            }
935            else
936            {
937                double n = -1.0-eye_ls.y();
938                double f = 1.0-eye_ls.y();
939                double sqrt_nf = sqrt(n*f);
940                double mid = eye_ls.y()+sqrt_nf;
941                double ratioOfMidToUseForSplit = 0.8;
942                splitPoint = mid * ratioOfMidToUseForSplit;
943
944                OSG_INFO<<"  n="<<n<<", f="<<f<<", sqrt_nf="<<sqrt_nf<<" mid="<<mid<<std::endl;
945            }
946        }
947
948        // 4. For each light/shadow map
949        for (unsigned int sm_i=0; sm_i<numShadowMapsPerLight; ++sm_i)
950        {
951            osg::ref_ptr<ShadowData> sd;
952
953            if (previous_sdl.empty())
954            {
955                OSG_INFO<<"Create new ShadowData"<<std::endl;
956                sd = new ShadowData(vdd);
957            }
958            else
959            {
960                OSG_INFO<<"Taking ShadowData from from of previous_sdl"<<std::endl;
961                sd = previous_sdl.front();
962                previous_sdl.erase(previous_sdl.begin());
963            }
964
965            osg::ref_ptr<osg::Camera> camera = sd->_camera;
966
967            camera->setProjectionMatrix(projectionMatrix);
968            camera->setViewMatrix(viewMatrix);
969
970            if (settings->getDebugDraw())
971            {
972                camera->getViewport()->x() = pos_x;
973                pos_x += camera->getViewport()->width() + 40;
974            }
975
976            // transform polytope in model coords into light spaces eye coords.
977            osg::Matrixd invertModelView;
978            invertModelView.invert(camera->getViewMatrix());
979
980            osg::Polytope local_polytope(polytope);
981            local_polytope.transformProvidingInverse(invertModelView);
982
983
984            if (numShadowMapsPerLight>1)
985            {
986                // compute the start and end range in non-dimensional coords
987#if 0
988                double r_start = (sm_i==0) ? -1.0 : (double(sm_i)/double(numShadowMapsPerLight)*2.0-1.0);
989                double r_end = (sm_i+1==numShadowMapsPerLight) ? 1.0 : (double(sm_i+1)/double(numShadowMapsPerLight)*2.0-1.0);
990#endif
991
992                // hardwired for 2 splits
993                double r_start = (sm_i==0) ? -1.0 : splitPoint;
994                double r_end = (sm_i+1==numShadowMapsPerLight) ? 1.0 : splitPoint;
995
996                // for all by the last shadowmap shift the r_end so that it overlaps slightly with the next shadowmap
997                // to prevent a seam showing through between the shadowmaps
998                if (sm_i+1<numShadowMapsPerLight) r_end+=0.01;
999
1000
1001                if (sm_i>0)
1002                {
1003                    // not the first shadowmap so insert a polytope to clip the scene from before r_start
1004
1005                    // plane in clip space coords
1006                    osg::Plane plane(0.0,1.0,0.0,-r_start);
1007
1008                    // transform into eye coords
1009                    plane.transformProvidingInverse(projectionMatrix);
1010                    local_polytope.getPlaneList().push_back(plane);
1011
1012                    //OSG_NOTICE<<"Adding r_start plane "<<plane<<std::endl;
1013
1014                }
1015
1016                if (sm_i+1<numShadowMapsPerLight)
1017                {
1018                    // not the last shadowmap so insert a polytope to clip the scene from beyond r_end
1019
1020                    // plane in clip space coords
1021                    osg::Plane plane(0.0,-1.0,0.0,r_end);
1022
1023                    // transform into eye coords
1024                    plane.transformProvidingInverse(projectionMatrix);
1025                    local_polytope.getPlaneList().push_back(plane);
1026
1027                    //OSG_NOTICE<<"Adding r_end plane "<<plane<<std::endl;
1028                }
1029
1030                local_polytope.setupMask();
1031
1032
1033                // OSG_NOTICE<<"Need to adjust RTT camera projection and view matrix here, r_start="<<r_start<<", r_end="<<r_end<<std::endl;
1034                // OSG_NOTICE<<"  textureUnit = "<<textureUnit<<std::endl;
1035
1036                double mid_r = (r_start+r_end)*0.5;
1037                double range_r = (r_end-r_start);
1038
1039                // OSG_NOTICE<<"  mid_r = "<<mid_r<<", range_r = "<<range_r<<std::endl;
1040
1041                camera->setProjectionMatrix(
1042                    camera->getProjectionMatrix() *
1043                    osg::Matrixd::translate(osg::Vec3d(0.0,-mid_r,0.0)) *
1044                    osg::Matrixd::scale(osg::Vec3d(1.0,2.0/range_r,1.0)));
1045
1046            }
1047
1048
1049            osg::ref_ptr<VDSMCameraCullCallback> vdsmCallback = new VDSMCameraCullCallback(this, local_polytope);
1050            camera->setCullCallback(vdsmCallback.get());
1051
1052            // 4.3 traverse RTT camera
1053            //
1054
1055            cv.pushStateSet(_shadowCastingStateSet.get());
1056
1057            cullShadowCastingScene(&cv, camera.get());
1058
1059            cv.popStateSet();
1060
1061            if (!orthographicViewFrustum && settings->getShadowMapProjectionHint()==ShadowSettings::PERSPECTIVE_SHADOW_MAP)
1062            {
1063                adjustPerspectiveShadowMapCameraSettings(vdsmCallback->getRenderStage(), frustum, pl, camera.get());
1064                if (vdsmCallback->getProjectionMatrix())
1065                {
1066                    vdsmCallback->getProjectionMatrix()->set(camera->getProjectionMatrix());
1067                }
1068            }
1069
1070            // 4.4 compute main scene graph TexGen + uniform settings + setup state
1071            //
1072            assignTexGenSettings(&cv, camera.get(), textureUnit, sd->_texgen.get());
1073
1074            // mark the light as one that has active shadows and requires shaders
1075            pl.textureUnits.push_back(textureUnit);
1076
1077            // pass on shadow data to ShadowDataList
1078            sd->_textureUnit = textureUnit;
1079
1080            if (textureUnit >= 8)
1081            {
1082                OSG_NOTICE<<"Shadow texture unit is invalid for texgen, will not be used."<<std::endl;
1083            }
1084            else
1085            {
1086                sdl.push_back(sd);
1087            }
1088
1089            // increment counters.
1090            ++textureUnit;
1091            ++numValidShadows ;
1092        }
1093    }
1094
1095    if (numValidShadows>0)
1096    {
1097        decoratorStateGraph->setStateSet(selectStateSetForRenderingShadow(*vdd));
1098    }
1099
1100    // OSG_NOTICE<<"End of shadow setup Projection matrix "<<*cv.getProjectionMatrix()<<std::endl;
1101}
1102
1103bool ViewDependentShadowMap::selectActiveLights(osgUtil::CullVisitor* cv, ViewDependentData* vdd) const
1104{
1105    OSG_INFO<<"selectActiveLights"<<std::endl;
1106
1107    LightDataList& pll = vdd->getLightDataList();
1108
1109    LightDataList previous_ldl;
1110    previous_ldl.swap(pll);
1111
1112    //MR testing giving a specific light
1113    osgUtil::RenderStage * rs = cv->getCurrentRenderBin()->getStage();
1114
1115    OSG_INFO<<"selectActiveLights osgUtil::RenderStage="<<rs<<std::endl;
1116
1117    osg::Matrixd modelViewMatrix = *(cv->getModelViewMatrix());
1118
1119    osgUtil::PositionalStateContainer::AttrMatrixList& aml =
1120        rs->getPositionalStateContainer()->getAttrMatrixList();
1121
1122
1123    const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
1124
1125    for(osgUtil::PositionalStateContainer::AttrMatrixList::reverse_iterator itr = aml.rbegin();
1126        itr != aml.rend();
1127        ++itr)
1128    {
1129        const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
1130        if (light && light->getLightNum() >= 0)
1131        {
1132            // is LightNum matched to that defined in settings
1133            if (settings && settings->getLightNum()>=0 && light->getLightNum()!=settings->getLightNum()) continue;
1134
1135            LightDataList::iterator pll_itr = pll.begin();
1136            for(; pll_itr != pll.end(); ++pll_itr)
1137            {
1138                if ((*pll_itr)->light->getLightNum()==light->getLightNum()) break;
1139            }
1140
1141            if (pll_itr==pll.end())
1142            {
1143                OSG_INFO<<"Light num "<<light->getLightNum()<<std::endl;
1144                LightData* ld = new LightData(vdd);
1145                ld->setLightData(itr->second.get(), light, modelViewMatrix);
1146                pll.push_back(ld);
1147            }
1148            else
1149            {
1150                OSG_INFO<<"Light num "<<light->getLightNum()<<" already used, ignore light"<<std::endl;
1151            }
1152        }
1153    }
1154
1155    return !pll.empty();
1156}
1157
1158void ViewDependentShadowMap::createShaders()
1159{
1160    OSG_INFO<<"ViewDependentShadowMap::createShaders()"<<std::endl;
1161
1162    unsigned int _baseTextureUnit = 0;
1163
1164    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_accessUnfiromsAndProgramMutex);
1165
1166    _shadowCastingStateSet = new osg::StateSet;
1167
1168    ShadowSettings* settings = getShadowedScene()->getShadowSettings();
1169
1170    if (!settings->getDebugDraw())
1171    {
1172        // note soft (attribute only no mode override) setting. When this works ?
1173        // 1. for objects prepared for backface culling
1174        //    because they usually also set CullFace and CullMode on in their state
1175        //    For them we override CullFace but CullMode remains set by them
1176        // 2. For one faced, trees, and similar objects which cannot use
1177        //    backface nor front face so they usually use CullMode off set here.
1178        //    In this case we will draw them in their entirety.
1179
1180        _shadowCastingStateSet->setAttribute( new osg::CullFace( osg::CullFace::FRONT ),
1181                osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
1182
1183        // make sure GL_CULL_FACE is off by default
1184        // we assume that if object has cull face attribute set to back
1185        // it will also set cull face mode ON so no need for override
1186        _shadowCastingStateSet->setMode( GL_CULL_FACE, osg::StateAttribute::OFF );
1187    }
1188
1189#if 1
1190    float factor = 1.1;
1191    float units =  4.0;
1192#else
1193    float factor = -1.1;
1194    float units =  -4.0;
1195#endif
1196    _polygonOffset = new osg::PolygonOffset(factor, units);
1197    _shadowCastingStateSet->setAttribute(_polygonOffset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
1198    _shadowCastingStateSet->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
1199
1200
1201    _uniforms.clear();
1202    osg::ref_ptr<osg::Uniform> baseTextureSampler = new osg::Uniform("baseTexture",(int)_baseTextureUnit);
1203    _uniforms.push_back(baseTextureSampler.get());
1204
1205    osg::ref_ptr<osg::Uniform> baseTextureUnit = new osg::Uniform("baseTextureUnit",(int)_baseTextureUnit);
1206    _uniforms.push_back(baseTextureUnit.get());
1207
1208    for(unsigned int sm_i=0; sm_i<settings->getNumShadowMapsPerLight(); ++sm_i)
1209    {
1210        {
1211            std::stringstream sstr;
1212            sstr<<"shadowTexture"<<sm_i;
1213            osg::ref_ptr<osg::Uniform> shadowTextureSampler = new osg::Uniform(sstr.str().c_str(),(int)(settings->getBaseShadowTextureUnit()+sm_i));
1214            _uniforms.push_back(shadowTextureSampler.get());
1215        }
1216
1217        {
1218            std::stringstream sstr;
1219            sstr<<"shadowTextureUnit"<<sm_i;
1220            osg::ref_ptr<osg::Uniform> shadowTextureUnit = new osg::Uniform(sstr.str().c_str(),(int)(settings->getBaseShadowTextureUnit()+sm_i));
1221            _uniforms.push_back(shadowTextureUnit.get());
1222        }
1223    }
1224
1225    switch(settings->getShaderHint())
1226    {
1227        case(ShadowSettings::NO_SHADERS):
1228        {
1229            OSG_INFO<<"No shaders provided by, user must supply own shaders"<<std::endl;
1230            break;
1231        }
1232        case(ShadowSettings::PROVIDE_VERTEX_AND_FRAGMENT_SHADER):
1233        case(ShadowSettings::PROVIDE_FRAGMENT_SHADER):
1234        {
1235            _program = new osg::Program;
1236
1237            //osg::ref_ptr<osg::Shader> fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_noBaseTexture);
1238            if (settings->getNumShadowMapsPerLight()==2)
1239            {
1240                _program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture_twoShadowMaps));
1241            }
1242            else
1243            {
1244                _program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture));
1245            }
1246
1247            break;
1248        }
1249    }
1250
1251    {
1252        osg::ref_ptr<osg::Image> image = new osg::Image;
1253        image->allocateImage( 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE );
1254        *(osg::Vec4ub*)image->data() = osg::Vec4ub( 0xFF, 0xFF, 0xFF, 0xFF );
1255
1256        _fallbackBaseTexture = new osg::Texture2D(image.get());
1257        _fallbackBaseTexture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::REPEAT);
1258        _fallbackBaseTexture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::REPEAT);
1259        _fallbackBaseTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
1260        _fallbackBaseTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
1261
1262        _fallbackShadowMapTexture = new osg::Texture2D(image.get());
1263        _fallbackShadowMapTexture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::REPEAT);
1264        _fallbackShadowMapTexture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::REPEAT);
1265        _fallbackShadowMapTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
1266        _fallbackShadowMapTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
1267
1268    }
1269}
1270
1271osg::Polytope ViewDependentShadowMap::computeLightViewFrustumPolytope(Frustum& frustum, LightData& positionedLight)
1272{
1273    OSG_INFO<<"computeLightViewFrustumPolytope()"<<std::endl;
1274
1275    osg::Polytope polytope;
1276    polytope.setToUnitFrustum();
1277
1278    polytope.transformProvidingInverse( frustum.projectionMatrix );
1279    polytope.transformProvidingInverse( frustum.modelViewMatrix );
1280
1281    osg::Polytope lightVolumePolytope;
1282
1283    if (positionedLight.directionalLight)
1284    {
1285        osg::Polytope::PlaneList& planes = polytope.getPlaneList();
1286        osg::Polytope::ClippingMask selector_mask = 0x1;
1287        osg::Polytope::ClippingMask result_mask = 0x0;
1288        for(unsigned int i=0; i<planes.size(); ++i, selector_mask <<= 1)
1289        {
1290            OSG_INFO<<"      plane "<<planes[i]<<"  planes["<<i<<"].dotProductNormal(lightDir)="<<planes[i].dotProductNormal(positionedLight.lightDir);
1291            if (planes[i].dotProductNormal(positionedLight.lightDir)>=0.0)
1292            {
1293                OSG_INFO<<"     Need remove side "<<i<<std::endl;
1294            }
1295            else
1296            {
1297                OSG_INFO<<std::endl;
1298                lightVolumePolytope.add(planes[i]);
1299                result_mask = result_mask | selector_mask;
1300            }
1301        }
1302
1303        OSG_INFO<<"    planes.size() = "<<planes.size()<<std::endl;
1304        OSG_INFO<<"    planes.getResultMask() = "<<polytope.getResultMask()<<std::endl;
1305        OSG_INFO<<"    resultMask = "<<result_mask<<std::endl;
1306        polytope.setResultMask(result_mask);
1307    }
1308    else
1309    {
1310        const osg::Polytope::PlaneList& planes = polytope.getPlaneList();
1311        osg::Polytope::ClippingMask selector_mask = 0x1;
1312        osg::Polytope::ClippingMask result_mask = 0x0;
1313        for(unsigned int i=0; i<planes.size(); ++i, selector_mask <<= 1)
1314        {
1315
1316            double d = planes[i].distance(positionedLight.lightPos3);
1317            OSG_INFO<<"      plane "<<planes[i]<<"  planes["<<i<<"].distance(lightPos3)="<<d;
1318            if (d<0.0)
1319            {
1320                OSG_INFO<<"     Need remove side "<<i<<std::endl;
1321            }
1322            else
1323            {
1324                OSG_INFO<<std::endl;
1325                lightVolumePolytope.add(planes[i]);
1326                result_mask = result_mask | selector_mask;
1327            }
1328        }
1329        OSG_INFO<<"    planes.size() = "<<planes.size()<<std::endl;
1330        OSG_INFO<<"    planes.getResultMask() = "<<polytope.getResultMask()<<std::endl;
1331        OSG_INFO<<"    resultMask = "<<result_mask<<std::endl;
1332        polytope.setResultMask(result_mask);
1333    }
1334
1335    OSG_INFO<<"Which frustum edges are active?"<<std::endl;
1336    for(unsigned int i=0; i<12; ++i)
1337    {
1338        Frustum::Indices& indices = frustum.edges[i];
1339
1340        unsigned int corner_a = indices[0];
1341        unsigned int corner_b = indices[1];
1342        unsigned int face_a = indices[2];
1343        unsigned int face_b = indices[3];
1344        bool face_a_active = (polytope.getResultMask()&(0x1<<face_a))!=0;
1345        bool face_b_active = (polytope.getResultMask()&(0x1<<face_b))!=0;
1346        unsigned int numActive = 0;
1347        if (face_a_active) ++numActive;
1348        if (face_b_active) ++numActive;
1349        if (numActive==1)
1350        {
1351
1352            osg::Plane boundaryPlane;
1353
1354            if (positionedLight.directionalLight)
1355            {
1356                osg::Vec3d normal = (frustum.corners[corner_b]-frustum.corners[corner_a])^positionedLight.lightDir;
1357                normal.normalize();
1358                boundaryPlane.set(normal, frustum.corners[corner_a]);
1359            }
1360            else
1361            {
1362                boundaryPlane.set(positionedLight.lightPos3, frustum.corners[corner_a], frustum.corners[corner_b]);
1363            }
1364
1365            OSG_INFO<<"Boundary Edge "<<i<<", corner_a="<<corner_a<<", corner_b="<<corner_b<<", face_a_active="<<face_a_active<<", face_b_active="<<face_b_active;
1366            if (boundaryPlane.distance(frustum.center)<0.0)
1367            {
1368                boundaryPlane.flip();
1369                OSG_INFO<<", flipped boundary edge "<<boundaryPlane<<std::endl;
1370            }
1371            else
1372            {
1373                OSG_INFO<<", no need to flip boundary edge "<<boundaryPlane<<std::endl;
1374            }
1375            lightVolumePolytope.add(boundaryPlane);
1376        }
1377        else OSG_INFO<<"Internal Edge "<<i<<", corner_a="<<corner_a<<", corner_b="<<corner_b<<", face_a_active="<<face_a_active<<", face_b_active="<<face_b_active<<std::endl;
1378    }
1379
1380
1381    const osg::Polytope::PlaneList& planes = lightVolumePolytope.getPlaneList();
1382    for(unsigned int i=0; i<planes.size(); ++i)
1383    {
1384        OSG_INFO<<"      plane "<<planes[i]<<"  "<<((lightVolumePolytope.getResultMask() & (0x1<<i))?"on":"off")<<std::endl;
1385    }
1386
1387    return lightVolumePolytope;
1388}
1389
1390bool ViewDependentShadowMap::computeShadowCameraSettings(Frustum& frustum, LightData& positionedLight, osg::Matrixd& projectionMatrix, osg::Matrixd& viewMatrix)
1391{
1392    OSG_INFO<<"standardShadowMapCameraSettings()"<<std::endl;
1393
1394    osg::Vec3d lightSide;
1395
1396    const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
1397
1398    double dotProduct_v = positionedLight.lightDir * frustum.frustumCenterLine;
1399    double gamma_v = acos(dotProduct_v);
1400    if (gamma_v<osg::DegreesToRadians(settings->getPerspectiveShadowMapCutOffAngle()) || gamma_v>osg::DegreesToRadians(180.0-settings->getPerspectiveShadowMapCutOffAngle()))
1401    {
1402        OSG_INFO<<"View direction and Light direction below tolerance"<<std::endl;
1403        osg::Vec3d viewSide = osg::Matrixd::transform3x3(frustum.modelViewMatrix, osg::Vec3d(1.0,0.0,0.0));
1404        lightSide = positionedLight.lightDir ^ (viewSide ^ positionedLight.lightDir);
1405        lightSide.normalize();
1406    }
1407    else
1408    {
1409        lightSide = positionedLight.lightDir ^ frustum.frustumCenterLine;
1410        lightSide.normalize();
1411    }
1412
1413    osg::Vec3d lightUp = lightSide ^ positionedLight.lightDir;
1414
1415#if 0
1416    OSG_NOTICE<<"positionedLight.lightDir="<<positionedLight.lightDir<<std::endl;
1417    OSG_NOTICE<<"lightSide="<<lightSide<<std::endl;
1418    OSG_NOTICE<<"lightUp="<<lightUp<<std::endl;
1419#endif
1420
1421
1422    if (positionedLight.directionalLight)
1423    {
1424        double xMin=0.0, xMax=0.0;
1425        double yMin=0.0, yMax=0.0;
1426        double zMin=0.0, zMax=0.0;
1427
1428        for(Frustum::Vertices::iterator itr = frustum.corners.begin();
1429            itr != frustum.corners.end();
1430            ++itr)
1431        {
1432            osg::Vec3d cornerDelta(*itr - frustum.center);
1433            osg::Vec3d cornerInLightCoords(cornerDelta*lightSide,
1434                                           cornerDelta*lightUp,
1435                                           cornerDelta*positionedLight.lightDir);
1436
1437            OSG_INFO<<"    corner ="<<*itr<<" in lightcoords "<<cornerInLightCoords<<std::endl;
1438
1439            xMin = osg::minimum( xMin, cornerInLightCoords.x());
1440            xMax = osg::maximum( xMax, cornerInLightCoords.x());
1441            yMin = osg::minimum( yMin, cornerInLightCoords.y());
1442            yMax = osg::maximum( yMax, cornerInLightCoords.y());
1443            zMin = osg::minimum( zMin, cornerInLightCoords.z());
1444            zMax = osg::maximum( zMax, cornerInLightCoords.z());
1445        }
1446
1447        OSG_INFO<<"before bs xMin="<<xMin<<", xMax="<<xMax<<", yMin="<<yMin<<", yMax="<<yMax<<", zMin="<<zMin<<", zMax="<<zMax<<std::endl;
1448
1449        osg::BoundingSphere bs = _shadowedScene->getBound();
1450        osg::Vec3d modelCenterRelativeFrustumCenter(bs.center()-frustum.center);
1451        osg::Vec3d modelCenterInLightCoords(modelCenterRelativeFrustumCenter*lightSide,
1452                                            modelCenterRelativeFrustumCenter*lightUp,
1453                                            modelCenterRelativeFrustumCenter*positionedLight.lightDir);
1454
1455        OSG_INFO<<"modelCenterInLight="<<modelCenterInLightCoords<<" radius="<<bs.radius()<<std::endl;
1456        double radius(bs.radius());
1457
1458        xMin = osg::maximum(xMin, modelCenterInLightCoords.x()-radius);
1459        xMax = osg::minimum(xMax, modelCenterInLightCoords.x()+radius);
1460        yMin = osg::maximum(yMin, modelCenterInLightCoords.y()-radius);
1461        yMax = osg::minimum(yMax, modelCenterInLightCoords.y()+radius);
1462        zMin = modelCenterInLightCoords.z()-radius;
1463        zMax = osg::minimum(zMax, modelCenterInLightCoords.z()+radius);
1464
1465        OSG_INFO<<"after bs xMin="<<xMin<<", xMax="<<xMax<<", yMin="<<yMin<<", yMax="<<yMax<<", zMin="<<zMin<<", zMax="<<zMax<<std::endl;
1466
1467        if (xMin>=xMax || yMin>=yMax || zMin>=zMax)
1468        {
1469            OSG_INFO<<"Warning nothing available to create shadows"<<zMax<<std::endl;
1470            return false;
1471        }
1472        else
1473        {
1474            projectionMatrix.makeOrtho(xMin,xMax, yMin, yMax,0.0,zMax-zMin);
1475            viewMatrix.makeLookAt(frustum.center+positionedLight.lightDir*zMin, frustum.center+positionedLight.lightDir*zMax, lightUp);
1476        }
1477    }
1478    else
1479    {
1480        double zMax=-DBL_MAX;
1481
1482        OSG_INFO<<"lightDir = "<<positionedLight.lightDir<<std::endl;
1483        OSG_INFO<<"lightPos3 = "<<positionedLight.lightPos3<<std::endl;
1484        for(Frustum::Vertices::iterator itr = frustum.corners.begin();
1485            itr != frustum.corners.end();
1486            ++itr)
1487        {
1488            osg::Vec3d cornerDelta(*itr - positionedLight.lightPos3);
1489            osg::Vec3d cornerInLightCoords(cornerDelta*lightSide,
1490                                           cornerDelta*lightUp,
1491                                           cornerDelta*positionedLight.lightDir);
1492
1493            OSG_INFO<<"   cornerInLightCoords= "<<cornerInLightCoords<<std::endl;
1494
1495            zMax = osg::maximum( zMax, cornerInLightCoords.z());
1496        }
1497
1498        OSG_INFO<<"zMax = "<<zMax<<std::endl;
1499
1500        if (zMax<0.0)
1501        {
1502            // view frustum entirely behind light
1503            return false;
1504        }
1505
1506        double minRatio = 0.0001;
1507        double zMin=zMax*minRatio;
1508
1509        double fov = positionedLight.light->getSpotCutoff() * 2.0;
1510        if(fov < 180.0)   // spotlight
1511        {
1512            projectionMatrix.makePerspective(fov, 1.0, zMin, zMax);
1513            viewMatrix.makeLookAt(positionedLight.lightPos3,
1514                                          positionedLight.lightPos3+positionedLight.lightDir, lightUp);
1515        }
1516        else
1517        {
1518            double fovMAX = 160.0f;
1519            fov = 0.0;
1520
1521            // calculate the max FOV from the corners of the frustum relative to the light position
1522            for(Frustum::Vertices::iterator itr = frustum.corners.begin();
1523                itr != frustum.corners.end();
1524                ++itr)
1525            {
1526                osg::Vec3d cornerDelta(*itr - positionedLight.lightPos3);
1527                double length = cornerDelta.length();
1528
1529                if (length==0.0) fov = osg::minimum(fov, 180.0);
1530                else
1531                {
1532                    double dotProduct = cornerDelta*positionedLight.lightDir;
1533                    double angle = 2.0*osg::RadiansToDegrees( acos(dotProduct/length) );
1534                    fov = osg::maximum(fov, angle);
1535                }
1536            }
1537
1538            OSG_INFO<<"Computed fov = "<<fov<<std::endl;
1539
1540            if (fov>fovMAX)
1541            {
1542                OSG_INFO<<"Clampping fov = "<<fov<<std::endl;
1543                fov=fovMAX;
1544            }
1545
1546            projectionMatrix.makePerspective(fov, 1.0, zMin, zMax);
1547            viewMatrix.makeLookAt(positionedLight.lightPos3,
1548                                  positionedLight.lightPos3+positionedLight.lightDir, lightUp);
1549
1550        }
1551    }
1552    return true;
1553}
1554
1555struct ConvexHull
1556{
1557    typedef std::vector<osg::Vec3d> Vertices;
1558    typedef std::pair< osg::Vec3d, osg::Vec3d > Edge;
1559    typedef std::list< Edge > Edges;
1560
1561    Edges _edges;
1562
1563    bool valid() const { return !_edges.empty(); }
1564
1565    void setToFrustum(ViewDependentShadowMap::Frustum& frustum)
1566    {
1567        _edges.push_back( Edge(frustum.corners[0],frustum.corners[1]) );
1568        _edges.push_back( Edge(frustum.corners[1],frustum.corners[2]) );
1569        _edges.push_back( Edge(frustum.corners[2],frustum.corners[3]) );
1570        _edges.push_back( Edge(frustum.corners[3],frustum.corners[0]) );
1571
1572        _edges.push_back( Edge(frustum.corners[4],frustum.corners[5]) );
1573        _edges.push_back( Edge(frustum.corners[5],frustum.corners[6]) );
1574        _edges.push_back( Edge(frustum.corners[6],frustum.corners[7]) );
1575        _edges.push_back( Edge(frustum.corners[7],frustum.corners[4]) );
1576
1577        _edges.push_back( Edge(frustum.corners[0],frustum.corners[4]) );
1578        _edges.push_back( Edge(frustum.corners[1],frustum.corners[5]) );
1579        _edges.push_back( Edge(frustum.corners[2],frustum.corners[6]) );
1580        _edges.push_back( Edge(frustum.corners[3],frustum.corners[7]) );
1581    }
1582
1583    void transform(const osg::Matrixd& m)
1584    {
1585        for(Edges::iterator itr = _edges.begin();
1586            itr != _edges.end();
1587            ++itr)
1588        {
1589            itr->first = itr->first * m;
1590            itr->second = itr->second * m;
1591        }
1592    }
1593
1594    void clip(const osg::Plane& plane)
1595    {
1596        Vertices intersections;
1597
1598        // OSG_NOTICE<<"clip("<<plane<<") edges.size()="<<_edges.size()<<std::endl;
1599        for(Edges::iterator itr = _edges.begin();
1600            itr != _edges.end();
1601            )
1602        {
1603            double d0 = plane.distance(itr->first);
1604            double d1 = plane.distance(itr->second);
1605            if (d0<0.0 && d1<0.0)
1606            {
1607                // OSG_NOTICE<<"  Edge completely outside, removing"<<std::endl;
1608                Edges::iterator to_delete_itr = itr;
1609                ++itr;
1610                _edges.erase(to_delete_itr);
1611            }
1612            else if (d0>=0.0 && d1>=0.0)
1613            {
1614                // OSG_NOTICE<<"  Edge completely inside"<<std::endl;
1615                ++itr;
1616            }
1617            else
1618            {
1619                osg::Vec3d& v0 = itr->first;
1620                osg::Vec3d& v1 = itr->second;
1621                osg::Vec3d intersection = v0 - (v1-v0)*(d0/(d1-d0));
1622                intersections.push_back(intersection);
1623                // OSG_NOTICE<<"  Edge across clip plane, v0="<<v0<<", v1="<<v1<<", intersection= "<<intersection<<std::endl;
1624                if (d0<0.0)
1625                {
1626                    // move first vertex on edge
1627                    v0 = intersection;
1628                }
1629                else
1630                {
1631                    // move second vertex on edge
1632                    v1 = intersection;
1633                }
1634
1635                ++itr;
1636            }
1637        }
1638        // OSG_NOTICE<<"After clipping, have "<<intersections.size()<<" to insert"<<std::endl;
1639
1640        if (intersections.size() < 2)
1641        {
1642            return;
1643        }
1644
1645        if (intersections.size() == 2)
1646        {
1647            _edges.push_back( Edge(intersections[0], intersections[1]) );
1648            return;
1649        }
1650
1651        if (intersections.size() == 3)
1652        {
1653            _edges.push_back( Edge(intersections[0], intersections[1]) );
1654            _edges.push_back( Edge(intersections[1], intersections[2]) );
1655            _edges.push_back( Edge(intersections[2], intersections[0]) );
1656            return;
1657        }
1658
1659        // more than 3 intersections so have to sort them in clockwise order so that
1660        // we can generate the edges correctly.
1661
1662        osg::Vec3d normal(plane.getNormal());
1663
1664        osg::Vec3d side_x = osg::Vec3d(1.0,0.0,0.0) ^ normal;
1665        osg::Vec3d side_y = osg::Vec3d(0.0,1.0,0.0) ^ normal;
1666        osg::Vec3d side = (side_x.length2()>=side_y.length2()) ? side_x : side_y;
1667        side.normalize();
1668
1669        osg::Vec3d up = side ^ normal;
1670        up.normalize();
1671
1672        osg::Vec3d center;
1673        for(Vertices::iterator itr = intersections.begin();
1674            itr != intersections.end();
1675            ++itr)
1676        {
1677            center += *itr;
1678        }
1679
1680        center /= double(intersections.size());
1681
1682        typedef std::map<double, osg::Vec3d> VertexMap;
1683        VertexMap vertexMap;
1684        for(Vertices::iterator itr = intersections.begin();
1685            itr != intersections.end();
1686            ++itr)
1687        {
1688            osg::Vec3d dv = (*itr-center);
1689            double h = dv * side;
1690            double v = dv * up;
1691            double angle = atan2(h,v);
1692            // OSG_NOTICE<<"angle = "<<osg::RadiansToDegrees(angle)<<", h="<<h<<" v= "<<v<<std::endl;
1693            vertexMap[angle] = *itr;
1694        }
1695
1696        osg::Vec3d previous_v = vertexMap.rbegin()->second;
1697        for(VertexMap::iterator itr = vertexMap.begin();
1698            itr != vertexMap.end();
1699            ++itr)
1700        {
1701            _edges.push_back(Edge(previous_v, itr->second));
1702            previous_v = itr->second;
1703        }
1704
1705        // OSG_NOTICE<<"  after clip("<<plane<<") edges.size()="<<_edges.size()<<std::endl;
1706    }
1707
1708    void clip(const osg::Polytope& polytope)
1709    {
1710        const osg::Polytope::PlaneList& planes = polytope.getPlaneList();
1711        for(osg::Polytope::PlaneList::const_iterator itr = planes.begin();
1712            itr != planes.end();
1713            ++itr)
1714        {
1715            clip(*itr);
1716        }
1717    }
1718
1719    double min(unsigned int index) const
1720    {
1721        double m = DBL_MAX;
1722        for(Edges::const_iterator itr = _edges.begin();
1723            itr != _edges.end();
1724            ++itr)
1725        {
1726            const Edge& edge = *itr;
1727            if (edge.first[index]<m) m = edge.first[index];
1728            if (edge.second[index]<m) m = edge.second[index];
1729        }
1730        return m;
1731    }
1732
1733    double max(unsigned int index) const
1734    {
1735        double m = -DBL_MAX;
1736        for(Edges::const_iterator itr = _edges.begin();
1737            itr != _edges.end();
1738            ++itr)
1739        {
1740            const Edge& edge = *itr;
1741            if (edge.first[index]>m) m = edge.first[index];
1742            if (edge.second[index]>m) m = edge.second[index];
1743        }
1744        return m;
1745    }
1746
1747    double minRatio(const osg::Vec3d& eye, unsigned int index) const
1748    {
1749        double m = DBL_MAX;
1750        osg::Vec3d delta;
1751        double ratio;
1752        for(Edges::const_iterator itr = _edges.begin();
1753            itr != _edges.end();
1754            ++itr)
1755        {
1756            const Edge& edge = *itr;
1757
1758            delta = edge.first-eye;
1759            ratio = delta[index]/delta[1];
1760            if (ratio<m) m = ratio;
1761
1762            delta = edge.second-eye;
1763            ratio = delta[index]/delta[1];
1764            if (ratio<m) m = ratio;
1765        }
1766        return m;
1767    }
1768
1769    double maxRatio(const osg::Vec3d& eye, unsigned int index) const
1770    {
1771        double m = -DBL_MAX;
1772        osg::Vec3d delta;
1773        double ratio;
1774        for(Edges::const_iterator itr = _edges.begin();
1775            itr != _edges.end();
1776            ++itr)
1777        {
1778            const Edge& edge = *itr;
1779
1780            delta = edge.first-eye;
1781            ratio = delta[index]/delta[1];
1782            if (ratio>m) m = ratio;
1783
1784            delta = edge.second-eye;
1785            ratio = delta[index]/delta[1];
1786            if (ratio>m) m = ratio;
1787        }
1788        return m;
1789    }
1790
1791    void output(std::ostream& out)
1792    {
1793        out<<"ConvexHull"<<std::endl;
1794        for(Edges::const_iterator itr = _edges.begin();
1795            itr != _edges.end();
1796            ++itr)
1797        {
1798            const Edge& edge = *itr;
1799            out<<"   edge ("<<edge.first<<") ("<<edge.second<<")"<<std::endl;
1800        }
1801    }
1802};
1803
1804
1805struct RenderLeafBounds
1806{
1807    RenderLeafBounds():
1808        computeRatios(false),
1809        numRenderLeaf(0),
1810        n(0.0),
1811        previous_modelview(0),
1812        clip_min_x(-1.0), clip_max_x(1.0),
1813        clip_min_y(-1.0), clip_max_y(1.0),
1814        clip_min_z(-1.0), clip_max_z(1.0),
1815        clip_min_x_ratio(-DBL_MAX), clip_max_x_ratio(DBL_MAX),
1816        clip_min_z_ratio(-DBL_MAX), clip_max_z_ratio(DBL_MAX),
1817        min_x_ratio(DBL_MAX), max_x_ratio(-DBL_MAX),
1818        min_z_ratio(DBL_MAX), max_z_ratio(-DBL_MAX),
1819        min_x(1.0), max_x(-1.0),
1820        min_y(1.0), max_y(-1.0),
1821        min_z(1.0), max_z(-1.0)
1822    {
1823        //OSG_NOTICE<<std::endl<<"RenderLeafBounds"<<std::endl;
1824    }
1825
1826    void set(const osg::Matrixd& p)
1827    {
1828        computeRatios = false;
1829        light_p = p;
1830        clip_min_x = -DBL_MAX; clip_max_x = DBL_MAX;
1831        clip_min_y = -DBL_MAX; clip_max_y = DBL_MAX;
1832        clip_min_z = -DBL_MAX; clip_max_z = DBL_MAX;
1833        min_x = DBL_MAX; max_x = -DBL_MAX;
1834        min_y = DBL_MAX; max_y = -DBL_MAX;
1835        min_z = DBL_MAX; max_z = -DBL_MAX;
1836    }
1837
1838    void set(const osg::Matrixd& p, osg::Vec3d& e_ls, double nr)
1839    {
1840        computeRatios = true;
1841        light_p = p;
1842        eye_ls = e_ls;
1843        n = nr;
1844    }
1845
1846    void operator() (const osgUtil::RenderLeaf* renderLeaf)
1847    {
1848        ++numRenderLeaf;
1849
1850        if (renderLeaf->_modelview.get()!=previous_modelview)
1851        {
1852            previous_modelview = renderLeaf->_modelview.get();
1853            if (previous_modelview)
1854            {
1855                light_mvp.mult(*renderLeaf->_modelview, light_p);
1856            }
1857            else
1858            {
1859                // no modelview matrix (such as when LightPointNode is in the scene graph) so assume
1860                // that modelview matrix is indentity.
1861                light_mvp = light_p;
1862            }
1863            // OSG_INFO<<"Computing new light_mvp "<<light_mvp<<std::endl;
1864        }
1865        else
1866        {
1867            // OSG_INFO<<"Reusing light_mvp "<<light_mvp<<std::endl;
1868        }
1869
1870        const osg::BoundingBox& bb = renderLeaf->_drawable->getBound();
1871        if (bb.valid())
1872        {
1873            // OSG_NOTICE<<"checked extents of "<<renderLeaf->_drawable->getName()<<std::endl;
1874            handle(osg::Vec3d(bb.xMin(),bb.yMin(),bb.zMin()));
1875            handle(osg::Vec3d(bb.xMax(),bb.yMin(),bb.zMin()));
1876            handle(osg::Vec3d(bb.xMin(),bb.yMax(),bb.zMin()));
1877            handle(osg::Vec3d(bb.xMax(),bb.yMax(),bb.zMin()));
1878            handle(osg::Vec3d(bb.xMin(),bb.yMin(),bb.zMax()));
1879            handle(osg::Vec3d(bb.xMax(),bb.yMin(),bb.zMax()));
1880            handle(osg::Vec3d(bb.xMin(),bb.yMax(),bb.zMax()));
1881            handle(osg::Vec3d(bb.xMax(),bb.yMax(),bb.zMax()));
1882        }
1883        else
1884        {
1885            OSG_INFO<<"bb invalid"<<std::endl;
1886        }
1887    }
1888
1889    void handle(const osg::Vec3d& v)
1890    {
1891        osg::Vec3d ls = v * light_mvp;
1892
1893        // OSG_NOTICE<<"   corner v="<<v<<", ls="<<ls<<std::endl;
1894
1895        if (computeRatios)
1896        {
1897            osg::Vec3d delta = ls-eye_ls;
1898
1899            double x_ratio, z_ratio;
1900            if (delta.y()>n)
1901            {
1902                x_ratio = delta.x()/delta.y();
1903                z_ratio = delta.z()/delta.y();
1904            }
1905            else
1906            {
1907                x_ratio = delta.x()/n;
1908                z_ratio = delta.z()/n;
1909            }
1910
1911            if (x_ratio<min_x_ratio) min_x_ratio = x_ratio;
1912            if (x_ratio>max_x_ratio) max_x_ratio = x_ratio;
1913            if (z_ratio<min_z_ratio) min_z_ratio = z_ratio;
1914            if (z_ratio>max_z_ratio) max_z_ratio = z_ratio;
1915        }
1916
1917        // clip to the light space
1918        if (ls.x()<clip_min_x) ls.x()=clip_min_x;
1919        if (ls.x()>clip_max_x) ls.x()=clip_max_x;
1920        if (ls.y()<clip_min_y) ls.y()=clip_min_y;
1921        if (ls.y()>clip_max_y) ls.y()=clip_max_y;
1922        if (ls.z()<clip_min_z) ls.z()=clip_min_z;
1923        if (ls.z()>clip_max_z) ls.z()=clip_max_z;
1924
1925        // compute the xyz range.
1926        if (ls.x()<min_x) min_x=ls.x();
1927        if (ls.x()>max_x) max_x=ls.x();
1928        if (ls.y()<min_y) min_y=ls.y();
1929        if (ls.y()>max_y) max_y=ls.y();
1930        if (ls.z()<min_z) { min_z=ls.z(); /* OSG_NOTICE<<" - ";*/ }
1931        if (ls.z()>max_z) { max_z=ls.z(); /* OSG_NOTICE<<" + ";*/ }
1932
1933        // OSG_NOTICE<<"   bb.z() in ls = "<<ls.z()<<std::endl;
1934
1935    }
1936
1937    bool                computeRatios;
1938
1939    unsigned int        numRenderLeaf;
1940
1941    osg::Matrixd        light_p;
1942    osg::Vec3d          eye_ls;
1943    double              n;
1944
1945    osg::Matrixd        light_mvp;
1946    osg::RefMatrix*     previous_modelview;
1947    unsigned int        numLeaves;
1948
1949    double clip_min_x, clip_max_x;
1950    double clip_min_y, clip_max_y;
1951    double clip_min_z, clip_max_z;
1952
1953    double clip_min_x_ratio, clip_max_x_ratio;
1954    double clip_min_z_ratio, clip_max_z_ratio;
1955
1956    double min_x_ratio, max_x_ratio;
1957    double min_z_ratio, max_z_ratio;
1958    double min_x, max_x;
1959    double min_y, max_y;
1960    double min_z, max_z;
1961};
1962
1963bool ViewDependentShadowMap::adjustPerspectiveShadowMapCameraSettings(osgUtil::RenderStage* renderStage, Frustum& frustum, LightData& positionedLight, osg::Camera* camera)
1964{
1965    const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
1966
1967    //frustum.projectionMatrix;
1968    //frustum.modelViewMatrix;
1969
1970    osg::Matrixd light_p = camera->getProjectionMatrix();
1971    osg::Matrixd light_v = camera->getViewMatrix();
1972    osg::Matrixd light_vp = light_v * light_p;
1973    osg::Vec3d lightdir(0.0,0.0,-1.0);
1974
1975    // check whether this light space projection is perspective or orthographic.
1976    bool orthographicLightSpaceProjection = light_p(0,3)==0.0 && light_p(1,3)==0.0 && light_p(2,3)==0.0;
1977
1978    if (!orthographicLightSpaceProjection)
1979    {
1980        OSG_INFO<<"perspective light space projection not yet supported."<<std::endl;
1981        return false;
1982    }
1983
1984
1985    //OSG_NOTICE<<"light_v="<<light_v<<std::endl;
1986    //OSG_NOTICE<<"light_p="<<light_p<<std::endl;
1987
1988    ConvexHull convexHull;
1989    convexHull.setToFrustum(frustum);
1990
1991#if 0
1992    OSG_NOTICE<<"ws ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
1993    OSG_NOTICE<<"ws ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
1994    OSG_NOTICE<<"ws ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
1995
1996    convexHull.output(osg::notify(osg::NOTICE));
1997#endif
1998
1999    convexHull.transform(light_vp);
2000
2001#if 0
2002    convexHull.output(osg::notify(osg::NOTICE));
2003
2004    OSG_NOTICE<<"ls ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
2005    OSG_NOTICE<<"ls ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
2006    OSG_NOTICE<<"ls ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
2007#endif
2008
2009#if 0
2010    // only applicable when the light space contains the whole model contained in the view frustum.
2011    {
2012        convexHull.clip(osg::Plane(0.0,0.0,1,1.0)); // clip by near plane of light space.
2013        convexHull.clip(osg::Plane(0.0,0.0,-1,1.0));  // clip by far plane of light space.
2014    }
2015#endif
2016
2017#if 1
2018    if (renderStage)
2019    {
2020#if 1
2021        osg::ElapsedTime timer;
2022#endif
2023
2024        RenderLeafTraverser<RenderLeafBounds> rli;
2025        rli.set(light_p);
2026        rli.traverse(renderStage);
2027
2028        if (rli.numRenderLeaf==0)
2029        {
2030            return false;
2031        }
2032#if 0
2033        OSG_NOTICE<<"New Time for RenderLeafTraverser "<<timer.elapsedTime_m()<<"ms, number of render leaves "<<rli.numRenderLeaf<<std::endl;
2034        OSG_NOTICE<<"   scene bounds min_x="<<rli.min_x<<", max_x="<<rli.max_x<<std::endl;
2035        OSG_NOTICE<<"   scene bounds min_y="<<rli.min_y<<", max_y="<<rli.max_y<<std::endl;
2036        OSG_NOTICE<<"   scene bounds min_z="<<rli.min_z<<", max_z="<<rli.max_z<<std::endl;
2037#endif
2038
2039#if 0
2040        double widest_x = osg::maximum(fabs(rli.min_x), fabs(rli.max_x));
2041        double widest_y = osg::maximum(fabs(rli.min_y), fabs(rli.max_y));
2042        double widest_z = osg::maximum(fabs(rli.min_z), fabs(rli.max_z));
2043#endif
2044
2045#if 1
2046#if 1
2047        convexHull.clip(osg::Plane(1.0,0.0,0.0,-rli.min_x));
2048        convexHull.clip(osg::Plane(-1.0,0.0,0.0,rli.max_x));
2049#else
2050        convexHull.clip(osg::Plane(1.0,0.0,0.0,widest_x));
2051        convexHull.clip(osg::Plane(-1.0,0.0,0.0,widest_x));
2052#endif
2053#if 1
2054        convexHull.clip(osg::Plane(0.0,1.0,0.0,-rli.min_y));
2055        convexHull.clip(osg::Plane(0.0,-1.0,0.0,rli.max_y));
2056#endif
2057#endif
2058
2059#if 0
2060        convexHull.clip(osg::Plane(0.0,0.0,1.0,-rli.min_z));
2061        convexHull.clip(osg::Plane(0.0,0.0,-1.0,rli.max_z));
2062#else
2063        convexHull.clip(osg::Plane(0.0,0.0,1.0,1.0));
2064        convexHull.clip(osg::Plane(0.0,0.0,-1.0,1.0));
2065#endif
2066
2067#if 0
2068        OSG_NOTICE<<"widest_x = "<<widest_x<<std::endl;
2069        OSG_NOTICE<<"widest_y = "<<widest_y<<std::endl;
2070        OSG_NOTICE<<"widest_z = "<<widest_z<<std::endl;
2071#endif
2072    }
2073#endif
2074
2075#if 0
2076    convexHull.output(osg::notify(osg::NOTICE));
2077
2078    OSG_NOTICE<<"after clipped ls ConvexHull xMin="<<convexHull.min(0)<<", xMax="<<convexHull.max(0)<<std::endl;
2079    OSG_NOTICE<<"after clipped ls ConvexHull yMin="<<convexHull.min(1)<<", yMax="<<convexHull.max(1)<<std::endl;
2080    OSG_NOTICE<<"after clipped ls ConvexHull zMin="<<convexHull.min(2)<<", zMax="<<convexHull.max(2)<<std::endl;
2081#endif
2082
2083    double xMin=-1.0, xMax=1.0;
2084    double yMin=-1.0, yMax=1.0;
2085    double zMin=-1.0, zMax=1.0;
2086
2087    if (convexHull.valid())
2088    {
2089        double widest_x = osg::maximum(fabs(convexHull.min(0)), fabs(convexHull.max(0)));
2090        xMin = osg::maximum(-1.0,-widest_x);
2091        xMax = osg::minimum(1.0,widest_x);
2092        yMin = osg::maximum(-1.0,convexHull.min(1));
2093        yMax = osg::minimum(1.0,convexHull.max(1));
2094    }
2095    else
2096    {
2097        // clipping of convex hull has invalidated it, so reset it so later checks on it provide valid results.
2098        convexHull.setToFrustum(frustum);
2099        convexHull.transform(light_vp);
2100    }
2101
2102#if 0
2103    OSG_NOTICE<<"xMin = "<<xMin<<", \txMax = "<<xMax<<std::endl;
2104    OSG_NOTICE<<"yMin = "<<yMin<<", \tyMax = "<<yMax<<std::endl;
2105    OSG_NOTICE<<"zMin = "<<zMin<<", \tzMax = "<<zMax<<std::endl;
2106#endif
2107
2108#if 1
2109    // we always want the lightspace to include the computed near plane.
2110    zMin = -1.0;
2111    if (xMin!=-1.0 || yMin!=-1.0 || zMin!=-1.0 ||
2112        xMax!=1.0 || yMax!=1.0 || zMax!=1.0)
2113    {
2114        osg::Matrix m;
2115        m.makeTranslate(osg::Vec3d(-0.5*(xMax+xMin),
2116                                    -0.5*(yMax+yMin),
2117                                    -0.5*(zMax+zMin)));
2118
2119        m.postMultScale(osg::Vec3d(2.0/(xMax-xMin),
2120                                   2.0/(yMax-yMin),
2121                                   2.0/(zMax-zMin)));
2122
2123        convexHull.transform(m);
2124        light_p.postMult(m);
2125        light_vp = light_v * light_p;
2126
2127#if 0
2128        OSG_NOTICE<<"Adjusting projection matrix "<<m<<std::endl;
2129        convexHull.output(osg::notify(osg::NOTICE));
2130#endif
2131        camera->setProjectionMatrix(light_p);
2132    }
2133
2134#endif
2135
2136    osg::Vec3d eye_v = frustum.eye * light_v;
2137    //osg::Vec3d centerNearPlane_v = frustum.centerNearPlane * light_v;
2138    osg::Vec3d center_v = frustum.center * light_v;
2139    osg::Vec3d viewdir_v = center_v-eye_v; viewdir_v.normalize();
2140
2141    double dotProduct_v = lightdir * viewdir_v;
2142    double gamma_v = acos(dotProduct_v);
2143    if (gamma_v<osg::DegreesToRadians(settings->getPerspectiveShadowMapCutOffAngle()) || gamma_v>osg::DegreesToRadians(180-settings->getPerspectiveShadowMapCutOffAngle()))
2144    {
2145        // OSG_NOTICE<<"Light and view vectors near parrallel - use standard shadow map."<<std::endl;
2146        return true;
2147    }
2148
2149    //OSG_NOTICE<<"gamma="<<osg::RadiansToDegrees(gamma_v)<<std::endl;
2150    //OSG_NOTICE<<"eye_v="<<eye_v<<std::endl;
2151    //OSG_NOTICE<<"viewdir_v="<<viewdir_v<<std::endl;
2152
2153    osg::Vec3d eye_ls = frustum.eye * light_vp;
2154#if 0
2155    if (eye_ls.y()>-1.0)
2156    {
2157        OSG_NOTICE<<"Eye point within light space - use standard shadow map."<<std::endl;
2158        return true;
2159    }
2160#endif
2161
2162    //osg::Vec3d centerNearPlane_ls = frustum.centerNearPlane * light_vp;
2163    //osg::Vec3d centerFarPlane_ls = frustum.centerFarPlane * light_vp;
2164    osg::Vec3d center_ls = frustum.center * light_vp;
2165    osg::Vec3d viewdir_ls = center_ls-eye_ls; viewdir_ls.normalize();
2166
2167    osg::Vec3d side = lightdir ^ viewdir_ls; side.normalize();
2168    osg::Vec3d up = side ^ lightdir;
2169
2170    double d = 2.0;
2171
2172    double alpha = osg::DegreesToRadians(30.0);
2173    double n = tan(alpha)*tan(osg::PI_2-gamma_v)*tan(osg::PI_2-gamma_v);
2174    //double n = tan(alpha)*tan(osg::PI_2-gamma_v);
2175
2176    //OSG_NOTICE<<"n = "<<n<<", eye_ls.y()="<<eye_ls.y()<<", eye_v="<<eye_v<<", eye="<<frustum.eye<<std::endl;
2177    double min_n = osg::maximum(-1.0-eye_ls.y(), settings->getMinimumShadowMapNearFarRatio());
2178    if (n<min_n)
2179    {
2180        //OSG_NOTICE<<"Clamping n to eye point"<<std::endl;
2181        n=min_n;
2182    }
2183
2184    //n = min_n;
2185
2186    //n = 0.01;
2187
2188    //n = z_n;
2189
2190    double f = n+d;
2191
2192    double a = (f+n)/(f-n);
2193    double b = -2.0*f*n/(f-n);
2194
2195    osg::Vec3d virtual_eye(0.0,-1.0-n, eye_ls.z());
2196
2197    osg::Matrixd lightView;
2198    lightView.makeLookAt(virtual_eye, virtual_eye+lightdir, up);
2199
2200#if 0
2201    OSG_NOTICE<<"n = "<<n<<", f="<<f<<std::endl;
2202    OSG_NOTICE<<"eye_ls = "<<eye_ls<<", virtual_eye="<<virtual_eye<<std::endl;
2203    OSG_NOTICE<<"frustum.eyes="<<frustum.eye<<std::endl;
2204#endif
2205
2206    double min_x_ratio = 0.0;
2207    double max_x_ratio = 0.0;
2208    double min_z_ratio = FLT_MAX;
2209    double max_z_ratio = -FLT_MAX;
2210
2211    min_x_ratio = convexHull.valid() ? convexHull.minRatio(virtual_eye,0) : -DBL_MAX;
2212    max_x_ratio = convexHull.valid() ? convexHull.maxRatio(virtual_eye,0) : DBL_MAX;
2213    //min_z_ratio = convexHull.minRatio(virtual_eye,2);
2214    //max_z_ratio = convexHull.maxRatio(virtual_eye,2);
2215
2216#if 0
2217    OSG_NOTICE<<"convexHull min_x_ratio = "<<min_x_ratio<<std::endl;
2218    OSG_NOTICE<<"convexHull max_x_ratio = "<<max_x_ratio<<std::endl;
2219    OSG_NOTICE<<"convexHull min_z_ratio = "<<min_z_ratio<<std::endl;
2220    OSG_NOTICE<<"convexHull max_z_ratio = "<<max_z_ratio<<std::endl;
2221#endif
2222
2223    #if 1
2224    if (renderStage)
2225    {
2226#if 1
2227        osg::ElapsedTime timer;
2228#endif
2229
2230        RenderLeafTraverser<RenderLeafBounds> rli;
2231        rli.set(light_p, virtual_eye, n);
2232        rli.traverse(renderStage);
2233
2234        if (rli.numRenderLeaf==0)
2235        {
2236            return false;
2237        }
2238
2239#if 0
2240        OSG_NOTICE<<"Time for RenderLeafTraverser "<<timer.elapsedTime_m()<<"ms, number of render leaves "<<rli.numRenderLeaf<<std::endl;
2241        OSG_NOTICE<<"scene bounds min_x="<<rli.min_x<<", max_x="<<rli.max_x<<std::endl;
2242        OSG_NOTICE<<"scene bounds min_y="<<rli.min_y<<", max_y="<<rli.max_y<<std::endl;
2243        OSG_NOTICE<<"scene bounds min_z="<<rli.min_z<<", max_z="<<rli.max_z<<std::endl;
2244        OSG_NOTICE<<"min_x_ratio="<<rli.min_x_ratio<<", max_x_ratio="<<rli.max_x_ratio<<std::endl;
2245        OSG_NOTICE<<"min_z_ratio="<<rli.min_z_ratio<<", max_z_ratio="<<rli.max_z_ratio<<std::endl;
2246#endif
2247        if (rli.min_x_ratio>min_x_ratio) min_x_ratio = rli.min_x_ratio;
2248        if (rli.max_x_ratio<max_x_ratio) max_x_ratio = rli.max_x_ratio;
2249
2250        /*if (rli.min_z_ratio>min_z_ratio)*/ min_z_ratio = rli.min_z_ratio;
2251        /*if (rli.max_z_ratio<max_z_ratio)*/ max_z_ratio = rli.max_z_ratio;
2252    }
2253#endif
2254    double best_x_ratio = osg::maximum(fabs(min_x_ratio),fabs(max_x_ratio));
2255    double best_z_ratio = osg::maximum(fabs(min_z_ratio),fabs(max_z_ratio));
2256
2257    //best_z_ratio = osg::maximum(1.0, best_z_ratio);
2258#if 0
2259    OSG_NOTICE<<"min_x_ratio = "<<min_x_ratio<<std::endl;
2260    OSG_NOTICE<<"max_x_ratio = "<<max_x_ratio<<std::endl;
2261    OSG_NOTICE<<"best_x_ratio = "<<best_x_ratio<<std::endl;
2262    OSG_NOTICE<<"min_z_ratio = "<<min_z_ratio<<std::endl;
2263    OSG_NOTICE<<"max_z_ratio = "<<max_z_ratio<<std::endl;
2264    OSG_NOTICE<<"best_z_ratio = "<<best_z_ratio<<std::endl;
2265#endif
2266
2267    //best_z_ratio *= 10.0;
2268
2269    osg::Matrixd lightPerspective( 1.0/best_x_ratio,  0.0, 0.0,  0.0,
2270                                   0.0,  a,   0.0,  1.0,
2271                                   0.0,  0.0, 1.0/best_z_ratio,  0.0,
2272                                   0.0,  b,   0.0,  0.0 );
2273    osg::Matrixd light_persp = light_p * lightView * lightPerspective;
2274
2275#if 0
2276    OSG_NOTICE<<"light_p = "<<light_p<<std::endl;
2277    OSG_NOTICE<<"lightView = "<<lightView<<std::endl;
2278    OSG_NOTICE<<"lightPerspective = "<<lightPerspective<<std::endl;
2279    OSG_NOTICE<<"light_persp result = "<<light_persp<<std::endl;
2280#endif
2281    camera->setProjectionMatrix(light_persp);
2282
2283    return true;
2284}
2285
2286bool ViewDependentShadowMap::assignTexGenSettings(osgUtil::CullVisitor* cv, osg::Camera* camera, unsigned int textureUnit, osg::TexGen* texgen)
2287{
2288    OSG_INFO<<"assignTexGenSettings() textureUnit="<<textureUnit<<" texgen="<<texgen<<std::endl;
2289
2290    texgen->setMode(osg::TexGen::EYE_LINEAR);
2291
2292    // compute the matrix which takes a vertex from local coords into tex coords
2293    // We actually use two matrices one used to define texgen
2294    // and second that will be used as modelview when appling to OpenGL
2295    texgen->setPlanesFromMatrix( camera->getProjectionMatrix() *
2296                                 osg::Matrix::translate(1.0,1.0,1.0) *
2297                                 osg::Matrix::scale(0.5,0.5,0.5) );
2298
2299    // Place texgen with modelview which removes big offsets (making it float friendly)
2300    osg::ref_ptr<osg::RefMatrix> refMatrix =
2301        new osg::RefMatrix( camera->getInverseViewMatrix() * (*(cv->getModelViewMatrix())) );
2302
2303    cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( textureUnit, refMatrix.get(), texgen );
2304
2305
2306    return true;
2307}
2308
2309void ViewDependentShadowMap::cullShadowReceivingScene(osgUtil::CullVisitor* cv) const
2310{
2311    OSG_INFO<<"cullShadowReceivingScene()"<<std::endl;
2312
2313    // record the traversal mask on entry so we can reapply it later.
2314    unsigned int traversalMask = cv->getTraversalMask();
2315
2316    cv->setTraversalMask( traversalMask & _shadowedScene->getShadowSettings()->getReceivesShadowTraversalMask() );
2317
2318    _shadowedScene->osg::Group::traverse(*cv);
2319
2320    cv->setTraversalMask( traversalMask );
2321
2322    return;
2323}
2324
2325void ViewDependentShadowMap::cullShadowCastingScene(osgUtil::CullVisitor* cv, osg::Camera* camera) const
2326{
2327    OSG_INFO<<"cullShadowCastingScene()"<<std::endl;
2328
2329    // record the traversal mask on entry so we can reapply it later.
2330    unsigned int traversalMask = cv->getTraversalMask();
2331
2332    cv->setTraversalMask( traversalMask & _shadowedScene->getShadowSettings()->getCastsShadowTraversalMask() );
2333
2334        if (camera) camera->accept(*cv);
2335
2336    cv->setTraversalMask( traversalMask );
2337
2338    return;
2339}
2340
2341osg::StateSet* ViewDependentShadowMap::selectStateSetForRenderingShadow(ViewDependentData& vdd) const
2342{
2343    OSG_INFO<<"   selectStateSetForRenderingShadow() "<<vdd.getStateSet()<<std::endl;
2344
2345    osg::ref_ptr<osg::StateSet> stateset = vdd.getStateSet();
2346
2347    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_accessUnfiromsAndProgramMutex);
2348   
2349    vdd.getStateSet()->clear();
2350
2351    vdd.getStateSet()->setTextureAttributeAndModes(0, _fallbackBaseTexture.get(), osg::StateAttribute::ON);
2352
2353    for(Uniforms::const_iterator itr=_uniforms.begin();
2354        itr!=_uniforms.end();
2355        ++itr)
2356    {
2357        OSG_INFO<<"addUniform("<<(*itr)->getName()<<")"<<std::endl;
2358        stateset->addUniform(itr->get());
2359    }
2360
2361    if (_program.valid())
2362    {
2363        stateset->setAttribute(_program.get());
2364    }
2365
2366    LightDataList& pll = vdd.getLightDataList();
2367    for(LightDataList::iterator itr = pll.begin();
2368        itr != pll.end();
2369        ++itr)
2370    {
2371        // 3. create per light/per shadow map division of lightspace/frustum
2372        //    create a list of light/shadow map data structures
2373
2374        LightData& pl = (**itr);
2375
2376        // if no texture units have been activated for this light then no shadow state required.
2377        if (pl.textureUnits.empty()) continue;
2378
2379        for(LightData::ActiveTextureUnits::iterator atu_itr = pl.textureUnits.begin();
2380            atu_itr != pl.textureUnits.end();
2381            ++atu_itr)
2382        {
2383            OSG_INFO<<"   Need to assign state for "<<*atu_itr<<std::endl;
2384        }
2385
2386    }
2387
2388    const ShadowSettings* settings = getShadowedScene()->getShadowSettings();
2389    unsigned int shadowMapModeValue = settings->getUseOverrideForShadowMapTexture() ?
2390                                            osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE :
2391                                            osg::StateAttribute::ON;
2392
2393
2394    ShadowDataList& sdl = vdd.getShadowDataList();
2395    for(ShadowDataList::iterator itr = sdl.begin();
2396        itr != sdl.end();
2397        ++itr)
2398    {
2399        // 3. create per light/per shadow map division of lightspace/frustum
2400        //    create a list of light/shadow map data structures
2401
2402        ShadowData& sd = (**itr);
2403
2404        OSG_INFO<<"   ShadowData for "<<sd._textureUnit<<std::endl;
2405
2406        stateset->setTextureAttributeAndModes(sd._textureUnit, sd._texture.get(), shadowMapModeValue);
2407
2408        stateset->setTextureMode(sd._textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
2409        stateset->setTextureMode(sd._textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
2410        stateset->setTextureMode(sd._textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
2411        stateset->setTextureMode(sd._textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
2412    }
2413
2414    return vdd.getStateSet();
2415}
2416
2417void ViewDependentShadowMap::resizeGLObjectBuffers(unsigned int maxSize)
2418{
2419    // the way that ViewDependentData is mapped shouldn't
2420}
2421
2422void ViewDependentShadowMap::releaseGLObjects(osg::State* state) const
2423{
2424    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_viewDependentDataMapMutex);
2425    for(ViewDependentDataMap::const_iterator itr = _viewDependentDataMap.begin();
2426        itr != _viewDependentDataMap.end();
2427        ++itr)
2428    {
2429        ViewDependentData* vdd = itr->second.get();
2430        if (vdd)
2431        {
2432            vdd->releaseGLObjects(state);
2433        }
2434    }
2435}
Note: See TracBrowser for help on using the browser.