root/OpenSceneGraph/trunk/examples/osgshadow/osgshadow.cpp @ 13110

Revision 13110, 46.7 kB (checked in by robert, 6 days ago)

Release OpenSceneGraph-3.2.1

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[6941]1/* OpenSceneGraph example, osgshadow.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
[5701]19#include <osg/ArgumentParser>
[6235]20#include <osg/ComputeBoundsVisitor>
21#include <osg/Texture2D>
[6237]22#include <osg/ShapeDrawable>
23#include <osg/MatrixTransform>
[6865]24#include <osg/Geometry>
[5701]25
[5956]26#include <osgGA/TrackballManipulator>
[6030]27#include <osgGA/FlightManipulator>
28#include <osgGA/DriveManipulator>
29#include <osgGA/KeySwitchMatrixManipulator>
[6010]30#include <osgGA/AnimationPathManipulator>
[6030]31#include <osgGA/TerrainManipulator>
32#include <osgGA/AnimationPathManipulator>
[6036]33#include <osgGA/StateSetManipulator>
[5641]34
[5956]35#include <osgViewer/Viewer>
[6864]36#include <osgViewer/ViewerEventHandlers>
[5956]37
[6126]38#include <osgShadow/ShadowedScene>
39#include <osgShadow/ShadowVolume>
[6235]40#include <osgShadow/ShadowTexture>
41#include <osgShadow/ShadowMap>
[7219]42#include <osgShadow/SoftShadowMap>
[7441]43#include <osgShadow/ParallelSplitShadowMap>
[8920]44#include <osgShadow/LightSpacePerspectiveShadowMap>
[9405]45#include <osgShadow/StandardShadowMap>
[12743]46#include <osgShadow/ViewDependentShadowMap>
[5641]47
[12780]48#include <osgUtil/Optimizer>
49
[5641]50#include <osgDB/ReadFile>
[6010]51#include <osgDB/WriteFile>
[5641]52
[12199]53#include <osg/io_utils>
[5956]54#include <iostream>
[5641]55
[8920]56
[6237]57// for the grid data..
[8920]58#include "terrain_coords.h"
59// for the model number four - island scene
60#include "IslandScene.h"
[6045]61
[7957]62
[12159]63class ChangeFOVHandler : public osgGA::GUIEventHandler
64{
65public:
66    ChangeFOVHandler(osg::Camera* camera)
67        : _camera(camera)
68    {
69        double fovy, aspectRatio, zNear, zFar;
70        _camera->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
71        std::cout << "FOV is " << fovy << std::endl;
72    }
73
74    /** Deprecated, Handle events, return true if handled, false otherwise. */
75    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
76    {
77        if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
78        {
79            if (ea.getKey() == '-' || ea.getKey() == '=' || ea.getKey() == '0')
80            {
81                double fovy, aspectRatio, zNear, zFar;
82                _camera->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
83
84                if (ea.getKey() == '-')
85                {
86                    fovy -= 5.0;
87                }
88
89                if (ea.getKey() == '=')
90                {
91                    fovy += 5.0;
92                }
93
94                if (ea.getKey() == '0')
95                {
96                    fovy = 45.0;
97                }
98
99                std::cout << "Setting FOV to " << fovy << std::endl;
100                _camera->getProjectionMatrix().makePerspective(fovy, aspectRatio, zNear, zFar);
101
102                return true;
103            }
104        }
105
106        return false;
107    }
108
109    osg::ref_ptr<osg::Camera> _camera;
110};
111
112
[12189]113class DumpShadowVolumesHandler : public osgGA::GUIEventHandler
114{
115public:
116    DumpShadowVolumesHandler(  )
117    {
118        set( false );
119    }
[12159]120
[13078]121    bool get() { return _value; }
122    void set( bool value ) { _value = value; }
[12189]123
124    /** Deprecated, Handle events, return true if handled, false otherwise. */
125    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
126    {
127        if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
128        {
129            if (ea.getKey() == 'D' )
130            {
131                set( true );
132                return true;
133            }
134        }
135
136        return false;
137    }
138
139    bool  _value;
140};
141
142
[12763]143class LightAnimationHandler : public osgGA::GUIEventHandler
144{
145public:
146    LightAnimationHandler(bool flag=true): _animating(flag) {}
147
148    void setAnimating(bool flag) { _animating = flag; }
149    bool getAnimating() const { return _animating; }
150
151    /** Deprecated, Handle events, return true if handled, false otherwise. */
152    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
153    {
154        if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
155        {
156            if (ea.getKey() == 'p' )
157            {
158                _animating = !_animating;
159                return true;
160            }
161        }
162
163        return false;
164    }
165
166    bool  _animating;
167};
168
169
[8920]170static int ReceivesShadowTraversalMask = 0x1;
171static int CastsShadowTraversalMask = 0x2;
172
[6237]173namespace ModelOne
[6045]174{
[5747]175
[6237]176    enum Faces
[6045]177    {
[6237]178        FRONT_FACE = 1,
179        BACK_FACE = 2,
180        LEFT_FACE = 4,
181        RIGHT_FACE = 8,
182        TOP_FACE = 16,
[7957]183        BOTTOM_FACE = 32
[6237]184    };
[5747]185
[6237]186    osg::Node* createCube(unsigned int mask)
[6045]187    {
[6237]188        osg::Geode* geode = new osg::Geode;
189
190        osg::Geometry* geometry = new osg::Geometry;
191        geode->addDrawable(geometry);
192
193        osg::Vec3Array* vertices = new osg::Vec3Array;
194        geometry->setVertexArray(vertices);
195
196        osg::Vec3Array* normals = new osg::Vec3Array;
197        geometry->setNormalArray(normals);
198        geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
199
200        osg::Vec4Array* colours = new osg::Vec4Array;
201        geometry->setColorArray(colours);
202        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
203        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
204
205
206        osg::Vec3 origin(0.0f,0.0f,0.0f);
207        osg::Vec3 dx(2.0f,0.0f,0.0f);
208        osg::Vec3 dy(0.0f,1.0f,0.0f);
209        osg::Vec3 dz(0.0f,0.0f,1.0f);
210
211        osg::Vec3 px(1.0f,0.0,0.0f);
212        osg::Vec3 nx(-1.0f,0.0,0.0f);
213        osg::Vec3 py(0.0f,1.0f,0.0f);
214        osg::Vec3 ny(0.0f,-1.0f,0.0f);
215        osg::Vec3 pz(0.0f,0.0f,1.0f);
216        osg::Vec3 nz(0.0f,0.0f,-1.0f);
217
218        if (mask & FRONT_FACE)
219        {
[7957]220            // front face
[6237]221            vertices->push_back(origin);
222            vertices->push_back(origin+dx);
223            vertices->push_back(origin+dx+dz);
224            vertices->push_back(origin+dz);
225            normals->push_back(ny);
226            normals->push_back(ny);
227            normals->push_back(ny);
228            normals->push_back(ny);
229        }
230
231        if (mask & BACK_FACE)
232        {
[7957]233            // back face
[6237]234            vertices->push_back(origin+dy);
235            vertices->push_back(origin+dy+dz);
236            vertices->push_back(origin+dy+dx+dz);
237            vertices->push_back(origin+dy+dx);
238            normals->push_back(py);
239            normals->push_back(py);
240            normals->push_back(py);
241            normals->push_back(py);
242        }
243
244        if (mask & LEFT_FACE)
245        {
[7957]246            // left face
[6237]247            vertices->push_back(origin+dy);
248            vertices->push_back(origin);
249            vertices->push_back(origin+dz);
250            vertices->push_back(origin+dy+dz);
251            normals->push_back(nx);
252            normals->push_back(nx);
253            normals->push_back(nx);
254            normals->push_back(nx);
255        }
256
257        if (mask & RIGHT_FACE)
258        {
[7957]259            // right face
[6237]260            vertices->push_back(origin+dx+dy);
261            vertices->push_back(origin+dx+dy+dz);
262            vertices->push_back(origin+dx+dz);
263            vertices->push_back(origin+dx);
264            normals->push_back(px);
265            normals->push_back(px);
266            normals->push_back(px);
267            normals->push_back(px);
268        }
269
270        if (mask & TOP_FACE)
271        {
[7957]272            // top face
[6237]273            vertices->push_back(origin+dz);
274            vertices->push_back(origin+dz+dx);
275            vertices->push_back(origin+dz+dx+dy);
276            vertices->push_back(origin+dz+dy);
277            normals->push_back(pz);
278            normals->push_back(pz);
279            normals->push_back(pz);
280            normals->push_back(pz);
281        }
282
283        if (mask & BOTTOM_FACE)
284        {
[7957]285            // bottom face
[6237]286            vertices->push_back(origin);
287            vertices->push_back(origin+dy);
288            vertices->push_back(origin+dx+dy);
289            vertices->push_back(origin+dx);
290            normals->push_back(nz);
291            normals->push_back(nz);
292            normals->push_back(nz);
293            normals->push_back(nz);
294        }
295
296        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));
297
298        return geode;
[6045]299    }
[6043]300
[6237]301    class SwitchHandler : public osgGA::GUIEventHandler
[6045]302    {
[6237]303    public:
[6043]304
[6237]305        SwitchHandler():
306            _childNum(0) {}
307
308        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& /*aa*/, osg::Object* object, osg::NodeVisitor* /*nv*/)
309        {
310            osg::Switch* sw = dynamic_cast<osg::Switch*>(object);
311            if (!sw) return false;
312
313            if (ea.getHandled()) return false;
314
315            switch(ea.getEventType())
316            {
317                case(osgGA::GUIEventAdapter::KEYDOWN):
318                {
319                    if (ea.getKey()=='n')
320                    {
321                        ++_childNum;
322                        if (_childNum >= sw->getNumChildren()) _childNum = 0;
323
324                        sw->setSingleChildOn(_childNum);
325                        return true;
[7957]326                    }
[6237]327                    break;
328                }
329                default:
330                    break;
331            }
332            return false;
333        }
334
335    protected:
336
337        virtual ~SwitchHandler() {}
338        unsigned int    _childNum;
339
340    };
341
342
343    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
[6045]344    {
[6237]345        osg::Switch* sw = new osg::Switch;
346        sw->setEventCallback(new ModelOne::SwitchHandler);
347
348        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE), true);
349        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE), false);
350        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE), false);
351        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE), false);
352        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE), false);
353        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE | ModelOne::BOTTOM_FACE), false);
[7957]354
355        return sw;
[6045]356    }
[6237]357}
[6043]358
[6237]359namespace ModelTwo
360{
361    osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
[6045]362    {
[7957]363        // set up the animation path
[6237]364        osg::AnimationPath* animationPath = new osg::AnimationPath;
365        animationPath->setLoopMode(osg::AnimationPath::LOOP);
366
367        int numSamples = 40;
368        float yaw = 0.0f;
369        float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
370        float roll = osg::inDegrees(30.0f);
371
372        double time=0.0f;
373        double time_delta = looptime/(double)numSamples;
374        for(int i=0;i<numSamples;++i)
375        {
376            osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
377            osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
378
379            animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
380
381            yaw += yaw_delta;
382            time += time_delta;
383
384        }
[7957]385        return animationPath;
[6045]386    }
387
[6237]388    osg::Node* createBase(const osg::Vec3& center,float radius)
[6045]389    {
[6043]390
[6237]391        osg::Geode* geode = new osg::Geode;
[6043]392
[6237]393        // set up the texture of the base.
394        osg::StateSet* stateset = new osg::StateSet();
395        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
396        if (image)
397        {
398            osg::Texture2D* texture = new osg::Texture2D;
399            texture->setImage(image);
400            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
401        }
[6045]402
[6237]403        geode->setStateSet( stateset );
[6051]404
[6237]405
406        osg::HeightField* grid = new osg::HeightField;
407        grid->allocate(38,39);
408        grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
409        grid->setXInterval(radius*2.0f/(float)(38-1));
410        grid->setYInterval(radius*2.0f/(float)(39-1));
411
412        float minHeight = FLT_MAX;
413        float maxHeight = -FLT_MAX;
414
415
416        unsigned int r;
417        for(r=0;r<39;++r)
[6045]418        {
[6237]419            for(unsigned int c=0;c<38;++c)
[6045]420            {
[6237]421                float h = vertex[r+c*39][2];
422                if (h>maxHeight) maxHeight=h;
423                if (h<minHeight) minHeight=h;
424            }
425        }
[6045]426
[6237]427        float hieghtScale = radius*0.5f/(maxHeight-minHeight);
428        float hieghtOffset = -(minHeight+maxHeight)*0.5f;
429
430        for(r=0;r<39;++r)
431        {
432            for(unsigned int c=0;c<38;++c)
433            {
434                float h = vertex[r+c*39][2];
435                grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
[6045]436            }
437        }
[6237]438
439        geode->addDrawable(new osg::ShapeDrawable(grid));
440
441        osg::Group* group = new osg::Group;
442        group->addChild(geode);
443
444        return group;
445
[6045]446    }
447
[6237]448    osg::Node* createMovingModel(const osg::Vec3& center, float radius)
449    {
450        float animationLength = 10.0f;
[6045]451
[6237]452        osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
[6045]453
[6237]454        osg::Group* model = new osg::Group;
[6045]455
[12529]456        osg::Node* cessna = osgDB::readNodeFile("cessna.osgt");
[6237]457        if (cessna)
458        {
459            const osg::BoundingSphere& bs = cessna->getBound();
460
461            float size = radius/bs.radius()*0.3f;
462            osg::MatrixTransform* positioned = new osg::MatrixTransform;
463            positioned->setDataVariance(osg::Object::STATIC);
464            positioned->setMatrix(osg::Matrix::translate(-bs.center())*
465                                  osg::Matrix::scale(size,size,size)*
466                                  osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
467
468            positioned->addChild(cessna);
469
470            osg::MatrixTransform* xform = new osg::MatrixTransform;
471            xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
472            xform->addChild(positioned);
473
474            model->addChild(xform);
475        }
476
477        return model;
478    }
479
480    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
481    {
482        osg::Vec3 center(0.0f,0.0f,0.0f);
483        float radius = 100.0f;
484        osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
485
486        // the shadower model
487        osg::Node* shadower = createMovingModel(center,radius*0.5f);
488        shadower->setNodeMask(CastsShadowTraversalMask);
489
490        // the shadowed model
491        osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
[6823]492        shadowed->setNodeMask(ReceivesShadowTraversalMask);
[7957]493
[6237]494        osg::Group* group = new osg::Group;
495
496        group->addChild(shadowed);
497        group->addChild(shadower);
[7957]498
[6237]499        return group;
500    }
501}
502
503namespace ModelThree
504{
505    osg::Group* createModel(osg::ArgumentParser& arguments)
506    {
507        osg::Group* scene = new osg::Group;
508
509        osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
510        scene->addChild(geode_1.get());
511
512        osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
513        osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
514        transform_2->addChild(geode_2.get());
[12189]515//        transform_2->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(45.0f)));
[6237]516        scene->addChild(transform_2.get());
517
518        osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
519        osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
520        transform_3->addChild(geode_3.get());
[12189]521//        transform_3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(-22.5f)));
[6237]522        scene->addChild(transform_3.get());
523
524        const float radius = 0.8f;
525        const float height = 1.0f;
526        osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
527        hints->setDetailRatio(2.0f);
528        osg::ref_ptr<osg::ShapeDrawable> shape;
529        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
530        shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
[12766]531        shape->setName("base box");
[6237]532        geode_1->addDrawable(shape.get());
533
534        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2), hints.get());
535        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
[12766]536        shape->setName("center sphere");
[6237]537        geode_1->addDrawable(shape.get());
538
539        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
540        shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
[12766]541        shape->setName("cyan sphere");
[6237]542        geode_2->addDrawable(shape.get());
543
544        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
545        shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
[12766]546        shape->setName("green box");
[6237]547        geode_2->addDrawable(shape.get());
548
549        shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
550        shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
[12766]551        shape->setName("blue cone");
[6237]552        geode_2->addDrawable(shape.get());
553
554        shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
555        shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
[12766]556        shape->setName("red cyclinder");
[6237]557        geode_2->addDrawable(shape.get());
558
559        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f, 0.1f), hints.get());
560        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
[12766]561        shape->setName("rotating box");
[6237]562        geode_3->addDrawable(shape.get());
563
564        // material
565        osg::ref_ptr<osg::Material> matirial = new osg::Material;
566        matirial->setColorMode(osg::Material::DIFFUSE);
567        matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
568        matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
569        matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
570        scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
571
572        bool withBaseTexture = true;
573        while(arguments.read("--with-base-texture")) { withBaseTexture = true; }
574        while(arguments.read("--no-base-texture")) { withBaseTexture = false; }
575
576        if (withBaseTexture)
577        {
578            scene->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")), osg::StateAttribute::ON);
579        }
580
581        return scene;
582    }
[7957]583
[6237]584}
585
586
[12779]587namespace ModelFive
588{
[12780]589    struct UseVBOVisitor : public osg::NodeVisitor
590    {
591        UseVBOVisitor():
[13078]592            osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
[12780]593
594        virtual void apply(osg::Geode& geode)
595        {
596            for(unsigned int i=0; i<geode.getNumDrawables(); ++i)
597            {
598                osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));
599                if (geometry)
600                {
601                    geometry->setUseVertexBufferObjects(true);
602                }
603            }
604        }
605    };
606
[13078]607
[12779]608    osg::AnimationPathCallback* createAnimationPathCallback( float radius, float time )
609    {
610        osg::ref_ptr<osg::AnimationPath> path = new osg::AnimationPath;
611        path->setLoopMode( osg::AnimationPath::LOOP );
612
613        unsigned int numSamples = 32;
614        float delta_yaw = 2.0f * osg::PI/((float)numSamples - 1.0f);
615        float delta_time = time / (float)numSamples;
616        for ( unsigned int i=0; i<numSamples; ++i )
617        {
618            float yaw = delta_yaw * (float)i;
619            osg::Vec3 pos( sinf(yaw)*radius, cosf(yaw)*radius, 0.0f );
620            osg::Quat rot( -yaw, osg::Z_AXIS );
621            path->insert( delta_time * (float)i, osg::AnimationPath::ControlPoint(pos, rot) );
622        }
623
624        osg::ref_ptr<osg::AnimationPathCallback> apcb = new osg::AnimationPathCallback;
625        apcb->setAnimationPath( path.get() );
626        return apcb.release();
627    }
628
629    osg::Group* createModel(osg::ArgumentParser& arguments)
630    {
631        // Set the ground (only receives shadow)
632        osg::ref_ptr<osg::MatrixTransform> groundNode = new osg::MatrixTransform;
633        groundNode->addChild( osgDB::readNodeFile("lz.osg") );
634        groundNode->setMatrix( osg::Matrix::translate(200.0f, 200.0f,-200.0f) );
[12780]635        groundNode->setNodeMask( ReceivesShadowTraversalMask );
[12779]636
637        // Set the cessna (only casts shadow)
638        osg::ref_ptr<osg::MatrixTransform> cessnaNode = new osg::MatrixTransform;
639        cessnaNode->addChild( osgDB::readNodeFile("cessna.osg.0,0,90.rot") );
640        cessnaNode->addUpdateCallback( createAnimationPathCallback(50.0f, 6.0f) );
[12780]641        cessnaNode->setNodeMask( CastsShadowTraversalMask );
[12779]642
[12782]643        // cessna is really poorly optimized so fix this by optimizing the mesh and use VBO's.
644        osgUtil::Optimizer optimizer;
645        optimizer.optimize(cessnaNode.get(), osgUtil::Optimizer::INDEX_MESH |
646                                             osgUtil::Optimizer::VERTEX_POSTTRANSFORM |
647                                             osgUtil::Optimizer::VERTEX_PRETRANSFORM);
648
649        UseVBOVisitor useVBOVisitor;
650        cessnaNode->accept(useVBOVisitor);
651
652
[12779]653        osg::ref_ptr<osg::Group> shadowRoot = new osg::Group;
654        shadowRoot->addChild( groundNode.get() );
655        for ( unsigned int i=0; i<10; ++i )
656        {
657            for ( unsigned int j=0; j<10; ++j )
658            {
659                osg::ref_ptr<osg::MatrixTransform> cessnaInstance = new osg::MatrixTransform;
660                cessnaInstance->setMatrix( osg::Matrix::translate((float)i*50.0f-25.0f, (float)j*50.0f-25.0f, 0.0f) );
661                cessnaInstance->addChild( cessnaNode.get() );
662                shadowRoot->addChild( cessnaInstance.get() );
663            }
664        }
665
[12780]666
[12779]667        return shadowRoot.release();
668    }
669}
670
[6235]671osg::Node* createTestModel(osg::ArgumentParser& arguments)
[6045]672{
[6235]673    if (arguments.read("-1"))
674    {
[6237]675        return ModelOne::createModel(arguments);
[6235]676    }
677    else if (arguments.read("-2"))
678    {
[6237]679        return ModelTwo::createModel(arguments);
[6235]680    }
[8920]681    else if (arguments.read("-4"))
682    {
683        return ModelFour::createModel(arguments);
684    }
[12779]685    else if (arguments.read("-5"))
686    {
687        return ModelFive::createModel(arguments);
688    }
[6235]689    else /*if (arguments.read("-3"))*/
690    {
[6237]691        return ModelThree::createModel(arguments);
[6235]692    }
[7957]693
[6045]694}
695
[12199]696
[5641]697int main(int argc, char** argv)
698{
699    // use an ArgumentParser object to manage the program arguments.
[5701]700    osg::ArgumentParser arguments(&argc, argv);
[5641]701
702    // set up the usage document, in case we need to print out how to use this program.
703    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
704    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
705    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
[6035]706    arguments.getApplicationUsage()->addCommandLineOption("--positionalLight", "Use a positional light.");
707    arguments.getApplicationUsage()->addCommandLineOption("--directionalLight", "Use a direction light.");
708    arguments.getApplicationUsage()->addCommandLineOption("--noUpdate", "Disable the updating the of light source.");
[8920]709
710    arguments.getApplicationUsage()->addCommandLineOption("--castsShadowMask", "Override default castsShadowMask (default - 0x2)");
711    arguments.getApplicationUsage()->addCommandLineOption("--receivesShadowMask", "Override default receivesShadowMask (default - 0x1)");
712
[6035]713    arguments.getApplicationUsage()->addCommandLineOption("--base", "Add a base geometry to test shadows.");
[6238]714    arguments.getApplicationUsage()->addCommandLineOption("--sv", "Select ShadowVolume implementation.");
[7219]715    arguments.getApplicationUsage()->addCommandLineOption("--ssm", "Select SoftShadowMap implementation.");
[6238]716    arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation.");
[8920]717
[7441]718    arguments.getApplicationUsage()->addCommandLineOption("--pssm", "Select ParallelSplitShadowMap implementation.");//ADEGLI
719    arguments.getApplicationUsage()->addCommandLineOption("--mapcount", "ParallelSplitShadowMap texture count.");//ADEGLI
[7452]720    arguments.getApplicationUsage()->addCommandLineOption("--mapres", "ParallelSplitShadowMap texture resolution.");//ADEGLI
721    arguments.getApplicationUsage()->addCommandLineOption("--debug-color", "ParallelSplitShadowMap display debugging color (only the first 3 maps are color r=0,g=1,b=2.");//ADEGLI
[7462]722    arguments.getApplicationUsage()->addCommandLineOption("--minNearSplit", "ParallelSplitShadowMap shadow map near offset.");//ADEGLI
723    arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "ParallelSplitShadowMap max far distance to shadow.");//ADEGLI
[7497]724    arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "ParallelSplitShadowMap move the virtual frustum behind the real camera, (also back ground object can cast shadow).");//ADEGLI
[7462]725    arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Factor", "ParallelSplitShadowMap set PolygonOffset factor.");//ADEGLI
726    arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Unit", "ParallelSplitShadowMap set PolygonOffset unit.");//ADEGLI
[7441]727
[8920]728    arguments.getApplicationUsage()->addCommandLineOption("--lispsm", "Select LightSpacePerspectiveShadowMap implementation.");
[12189]729    arguments.getApplicationUsage()->addCommandLineOption("--msm", "Select MinimalShadowMap implementation.");
[12207]730    arguments.getApplicationUsage()->addCommandLineOption("--ViewBounds", "MSM, LiSPSM optimize shadow for view frustum (weakest option)");
731    arguments.getApplicationUsage()->addCommandLineOption("--CullBounds", "MSM, LiSPSM optimize shadow for bounds of culled objects in view frustum (better option).");
732    arguments.getApplicationUsage()->addCommandLineOption("--DrawBounds", "MSM, LiSPSM optimize shadow for bounds of predrawn pixels in view frustum (best & default).");
[12192]733    arguments.getApplicationUsage()->addCommandLineOption("--mapres", "MSM, LiSPSM & texture resolution.");
[12207]734    arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "MSM, LiSPSM max far distance to shadow.");
735    arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "MSM, LiSPSM move the virtual frustum behind the real camera, (also back ground object can cast shadow).");
736    arguments.getApplicationUsage()->addCommandLineOption("--minLightMargin", "MSM, LiSPSM the same as --moveVCamFactor.");
[7957]737
[6304]738    arguments.getApplicationUsage()->addCommandLineOption("-1", "Use test model one.");
739    arguments.getApplicationUsage()->addCommandLineOption("-2", "Use test model two.");
[8920]740    arguments.getApplicationUsage()->addCommandLineOption("-3", "Use test model three (default).");
741    arguments.getApplicationUsage()->addCommandLineOption("-4", "Use test model four - island scene.");
[6035]742    arguments.getApplicationUsage()->addCommandLineOption("--two-sided", "Use two-sided stencil extension for shadow volumes.");
743    arguments.getApplicationUsage()->addCommandLineOption("--two-pass", "Use two-pass stencil for shadow volumes.");
[13108]744    arguments.getApplicationUsage()->addCommandLineOption("--near-far-mode","COMPUTE_NEAR_USING_PRIMITIVES, COMPUTE_NEAR_FAR_USING_PRIMITIVES, COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES, DO_NOT_COMPUTE_NEAR_FAR");
[13110]745    arguments.getApplicationUsage()->addCommandLineOption("--max-shadow-distance","<float> Maximum distance that the shadow map should extend from the eye point.");
[5641]746
747    // construct the viewer.
[7499]748    osgViewer::Viewer viewer(arguments);
[5641]749
750    // if user request help write it out to cout.
751    if (arguments.read("-h") || arguments.read("--help"))
752    {
753        arguments.getApplicationUsage()->write(std::cout);
754        return 1;
755    }
[12196]756
[12203]757    double zNear=1.0, zMid=10.0, zFar=1000.0;
758    if (arguments.read("--depth-partition",zNear, zMid, zFar))
[12196]759    {
[12202]760        // set up depth partitioning
[12203]761        osg::ref_ptr<osgViewer::DepthPartitionSettings> dps = new osgViewer::DepthPartitionSettings;
762        dps->_mode = osgViewer::DepthPartitionSettings::FIXED_RANGE;
763        dps->_zNear = zNear;
764        dps->_zMid = zMid;
765        dps->_zFar = zFar;
766        viewer.setUpDepthPartition(dps.get());
[12196]767    }
768
[12203]769    if (arguments.read("--dp"))
770    {
771        // set up depth partitioning
772        viewer.setUpDepthPartition();
773    }
774
[12174]775    float fov = 0.0;
776    while (arguments.read("--fov",fov)) {}
[5641]777
[12174]778    osg::Vec4 lightpos(0.0,0.0,1,0.0);
[12743]779    bool spotlight = false;
[12174]780    while (arguments.read("--positionalLight")) { lightpos.set(0.5,0.5,1.5,1.0); }
781    while (arguments.read("--directionalLight")) { lightpos.set(0.0,0.0,1,0.0); }
[12743]782    while (arguments.read("--spotLight")) { lightpos.set(0.5,0.5,1.5,1.0); spotlight = true; }
[5779]783
[12743]784    bool keepLightPos = false;
785    osg::Vec3 spotLookat(0.0,0.0,0.0);
786    while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z(), lightpos.w())) { keepLightPos = true; }
787    while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=1.0; keepLightPos = true; }
788    while ( arguments.read("--light-dir", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=0.0; keepLightPos = true; }
789    while ( arguments.read("--spot-lookat", spotLookat.x(), spotLookat.y(), spotLookat.z())) { }
[12174]790
791
[8920]792    while (arguments.read("--castsShadowMask", CastsShadowTraversalMask ));
793    while (arguments.read("--receivesShadowMask", ReceivesShadowTraversalMask ));
794
[5779]795    bool updateLightPosition = true;
[5782]796    while (arguments.read("--noUpdate")) updateLightPosition = false;
[5779]797
[6030]798    // set up the camera manipulators.
[6010]799    {
[6030]800        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
801
802        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
803        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
804        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
805        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
806
807        std::string pathfile;
808        char keyForAnimationPath = '5';
809        while (arguments.read("-p",pathfile))
810        {
811            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
[7957]812            if (apm || !apm->valid())
[6030]813            {
814                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
815                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
816                keyswitchManipulator->selectMatrixManipulator(num);
817                ++keyForAnimationPath;
818            }
819        }
820
821        viewer.setCameraManipulator( keyswitchManipulator.get() );
[6010]822    }
823
[6036]824    // add the state manipulator
825    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
826
[6030]827    // add stats
828    viewer.addEventHandler( new osgViewer::StatsHandler() );
[6010]829
[7499]830    // add the record camera path handler
831    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
[5779]832
[12174]833    // add the window size toggle handler
834    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
835
[7990]836    // add the threading handler
837    viewer.addEventHandler( new osgViewer::ThreadingHandler() );
[5786]838
[6235]839    osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene;
[7957]840
[13107]841    osgShadow::ShadowSettings* settings = shadowedScene->getShadowSettings();
842    settings->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
843    settings->setCastsShadowTraversalMask(CastsShadowTraversalMask);
[7957]844
[13108]845    std::string nearFarMode("");
846    if (arguments.read("--near-far-mode",nearFarMode))
847    {
848        if (nearFarMode=="COMPUTE_NEAR_USING_PRIMITIVES")                settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_USING_PRIMITIVES);
849        else if (nearFarMode=="COMPUTE_NEAR_FAR_USING_PRIMITIVES")       settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
850        else if (nearFarMode=="DO_NOT_COMPUTE_NEAR_FAR")                 settings->setComputeNearFarModeOverride(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
851        else if (nearFarMode=="COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES") settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES);
852
853        OSG_NOTICE<<"ComputeNearFarModeOverride set to ";
854        switch(settings->getComputeNearFarModeOverride())
855        {
856            case(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES): OSG_NOTICE<<"COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES"; break;
857            case(osg::CullSettings::COMPUTE_NEAR_USING_PRIMITIVES): OSG_NOTICE<<"COMPUTE_NEAR_USING_PRIMITIVES"; break;
858            case(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES): OSG_NOTICE<<"COMPUTE_NEAR_FAR_USING_PRIMITIVES"; break;
859            case(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR): OSG_NOTICE<<"DO_NOT_COMPUTE_NEAR_FAR"; break;
860        }
861        OSG_NOTICE<<std::endl;
862    }
[13110]863
864    double distance;
865    if (arguments.read("--max-shadow-distance",distance))
866    {
867        settings->setMaximumShadowMapDistance(distance);
868        OSG_NOTICE<<"MaximumShadowMapDistance set to "<<settings->getMaximumShadowMapDistance()<<std::endl;
869    }
870
[13108]871   
[12189]872    osg::ref_ptr<osgShadow::MinimalShadowMap> msm = NULL;
[12199]873    if (arguments.read("--no-shadows"))
[6235]874    {
[12199]875        OSG_NOTICE<<"Not using a ShadowTechnique"<<std::endl;
876        shadowedScene->setShadowTechnique(0);
877    }
878    else if (arguments.read("--sv"))
879    {
[6238]880        // hint to tell viewer to request stencil buffer when setting up windows
881        osg::DisplaySettings::instance()->setMinimumNumStencilBits(8);
882
[6235]883        osg::ref_ptr<osgShadow::ShadowVolume> sv = new osgShadow::ShadowVolume;
884        sv->setDynamicShadowVolumes(updateLightPosition);
885        while (arguments.read("--two-sided")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_SIDED);
886        while (arguments.read("--two-pass")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_PASS);
887
888        shadowedScene->setShadowTechnique(sv.get());
889    }
890    else if (arguments.read("--st"))
891    {
892        osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture;
893        shadowedScene->setShadowTechnique(st.get());
894    }
[9405]895    else if (arguments.read("--stsm"))
896    {
897        osg::ref_ptr<osgShadow::StandardShadowMap> st = new osgShadow::StandardShadowMap;
898        shadowedScene->setShadowTechnique(st.get());
899    }
[6235]900    else if (arguments.read("--pssm"))
901    {
[7441]902        int mapcount = 3;
903        while (arguments.read("--mapcount", mapcount));
904        osg::ref_ptr<osgShadow::ParallelSplitShadowMap> pssm = new osgShadow::ParallelSplitShadowMap(NULL,mapcount);
[7452]905
[7462]906        int mapres = 1024;
[7957]907        while (arguments.read("--mapres", mapres))
[7462]908            pssm->setTextureResolution(mapres);
[7957]909
[7452]910        while (arguments.read("--debug-color")) { pssm->setDebugColorOn(); }
911
[7957]912
[7462]913        int minNearSplit=0;
914        while (arguments.read("--minNearSplit", minNearSplit))
915            if ( minNearSplit > 0 ) {
916                pssm->setMinNearDistanceForSplits(minNearSplit);
917                std::cout << "ParallelSplitShadowMap : setMinNearDistanceForSplits(" << minNearSplit <<")" << std::endl;
918            }
919
920        int maxfardist = 0;
921        while (arguments.read("--maxFarDist", maxfardist))
922            if ( maxfardist > 0 ) {
923                pssm->setMaxFarDistance(maxfardist);
924                std::cout << "ParallelSplitShadowMap : setMaxFarDistance(" << maxfardist<<")" << std::endl;
925            }
926
[7497]927        int moveVCamFactor = 0;
928        while (arguments.read("--moveVCamFactor", moveVCamFactor))
929            if ( maxfardist > 0 ) {
930                pssm->setMoveVCamBehindRCamFactor(moveVCamFactor);
931                std::cout << "ParallelSplitShadowMap : setMoveVCamBehindRCamFactor(" << moveVCamFactor<<")" << std::endl;
932            }
933
[7957]934
[13078]935
[8379]936        double polyoffsetfactor = pssm->getPolygonOffset().x();
937        double polyoffsetunit   = pssm->getPolygonOffset().y();
[7462]938        while (arguments.read("--PolyOffset-Factor", polyoffsetfactor));
939        while (arguments.read("--PolyOffset-Unit", polyoffsetunit));
[13078]940        pssm->setPolygonOffset(osg::Vec2(polyoffsetfactor,polyoffsetunit));
[7462]941
[6235]942        shadowedScene->setShadowTechnique(pssm.get());
943    }
[7219]944    else if (arguments.read("--ssm"))
945    {
946        osg::ref_ptr<osgShadow::SoftShadowMap> sm = new osgShadow::SoftShadowMap;
947        shadowedScene->setShadowTechnique(sm.get());
948    }
[12750]949    else if( arguments.read("--vdsm") )
950    {
[12782]951        while( arguments.read("--debugHUD") ) settings->setDebugDraw( true );
952        if (arguments.read("--persp")) settings->setShadowMapProjectionHint(osgShadow::ShadowSettings::PERSPECTIVE_SHADOW_MAP);
953        if (arguments.read("--ortho")) settings->setShadowMapProjectionHint(osgShadow::ShadowSettings::ORTHOGRAPHIC_SHADOW_MAP);
[12762]954
955        unsigned int unit=1;
[12782]956        if (arguments.read("--unit",unit)) settings->setBaseShadowTextureUnit(unit);
[13078]957
[12768]958        double n=0.0;
[12782]959        if (arguments.read("-n",n)) settings->setMinimumShadowMapNearFarRatio(n);
[12768]960
[12893]961        unsigned int numShadowMaps;
962        if (arguments.read("--num-sm",numShadowMaps)) settings->setNumShadowMapsPerLight(numShadowMaps);
963
964        if (arguments.read("--parallel-split") || arguments.read("--ps") ) settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::PARALLEL_SPLIT);
965        if (arguments.read("--cascaded")) settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::CASCADED);
966
967
[12830]968        int mapres = 1024;
969        while (arguments.read("--mapres", mapres))
970            settings->setTextureSize(osg::Vec2s(mapres,mapres));
971
[12782]972        osg::ref_ptr<osgShadow::ViewDependentShadowMap> vdsm = new osgShadow::ViewDependentShadowMap;
[12750]973        shadowedScene->setShadowTechnique(vdsm.get());
974    }
[13078]975    else if ( arguments.read("--lispsm") )
[8920]976    {
977        if( arguments.read( "--ViewBounds" ) )
[12189]978            msm = new osgShadow::LightSpacePerspectiveShadowMapVB;
[8920]979        else if( arguments.read( "--CullBounds" ) )
[12189]980            msm = new osgShadow::LightSpacePerspectiveShadowMapCB;
[8920]981        else // if( arguments.read( "--DrawBounds" ) ) // default
[12189]982            msm = new osgShadow::LightSpacePerspectiveShadowMapDB;
[13078]983    }
[12189]984    else if( arguments.read("--msm") )
985    {
986       if( arguments.read( "--ViewBounds" ) )
987            msm = new osgShadow::MinimalShadowMap;
988       else if( arguments.read( "--CullBounds" ) )
989            msm = new osgShadow::MinimalCullBoundsShadowMap;
990       else // if( arguments.read( "--DrawBounds" ) ) // default
991            msm = new osgShadow::MinimalDrawBoundsShadowMap;
992    }
[6235]993    else /* if (arguments.read("--sm")) */
994    {
995        osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
996        shadowedScene->setShadowTechnique(sm.get());
[7539]997
998        int mapres = 1024;
[7957]999        while (arguments.read("--mapres", mapres))
[7539]1000            sm->setTextureSize(osg::Vec2s(mapres,mapres));
[8920]1001    }
[7957]1002
[12192]1003    if( msm )// Set common MSM & LISPSM arguments
[12189]1004    {
1005        shadowedScene->setShadowTechnique( msm.get() );
[12748]1006        while( arguments.read("--debugHUD") ) msm->setDebugDraw( true );
[12189]1007
1008        float minLightMargin = 10.f;
1009        float maxFarPlane = 0;
1010        unsigned int texSize = 1024;
1011        unsigned int baseTexUnit = 0;
1012        unsigned int shadowTexUnit = 1;
1013
1014        while ( arguments.read("--moveVCamFactor", minLightMargin ) );
1015        while ( arguments.read("--minLightMargin", minLightMargin ) );
1016        while ( arguments.read("--maxFarDist", maxFarPlane ) );
1017        while ( arguments.read("--mapres", texSize ));
1018        while ( arguments.read("--baseTextureUnit", baseTexUnit) );
1019        while ( arguments.read("--shadowTextureUnit", shadowTexUnit) );
1020
1021        msm->setMinLightMargin( minLightMargin );
1022        msm->setMaxFarPlane( maxFarPlane );
1023        msm->setTextureSize( osg::Vec2s( texSize, texSize ) );
1024        msm->setShadowTextureCoordIndex( shadowTexUnit );
1025        msm->setShadowTextureUnit( shadowTexUnit );
1026        msm->setBaseTextureCoordIndex( baseTexUnit );
1027        msm->setBaseTextureUnit( baseTexUnit );
1028    }
1029
[12831]1030    OSG_INFO<<"shadowedScene->getShadowTechnique()="<<shadowedScene->getShadowTechnique()<<std::endl;
[12199]1031
[7497]1032    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
1033    if (model.valid())
1034    {
1035        model->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);
1036    }
1037    else
1038    {
1039        model = createTestModel(arguments);
1040    }
[6235]1041
[7957]1042    // get the bounds of the model.
[7497]1043    osg::ComputeBoundsVisitor cbbv;
1044    model->accept(cbbv);
1045    osg::BoundingBox bb = cbbv.getBoundingBox();
1046
[12743]1047    if (lightpos.w()==1.0 && !keepLightPos)
[7497]1048    {
[12174]1049        lightpos.x() = bb.xMin()+(bb.xMax()-bb.xMin())*lightpos.x();
1050        lightpos.y() = bb.yMin()+(bb.yMax()-bb.yMin())*lightpos.y();
1051        lightpos.z() = bb.zMin()+(bb.zMax()-bb.zMin())*lightpos.z();
[7497]1052    }
[13078]1053
[6235]1054    if ( arguments.read("--base"))
1055    {
1056
[5786]1057        osg::Geode* geode = new osg::Geode;
[7957]1058
[5786]1059        osg::Vec3 widthVec(bb.radius(), 0.0f, 0.0f);
1060        osg::Vec3 depthVec(0.0f, bb.radius(), 0.0f);
1061        osg::Vec3 centerBase( (bb.xMin()+bb.xMax())*0.5f, (bb.yMin()+bb.yMax())*0.5f, bb.zMin()-bb.radius()*0.1f );
[7957]1062
1063        geode->addDrawable( osg::createTexturedQuadGeometry( centerBase-widthVec*1.5f-depthVec*1.5f,
[5956]1064                                                             widthVec*3.0f, depthVec*3.0f) );
[7957]1065
[6823]1066        geode->setNodeMask(shadowedScene->getReceivesShadowTraversalMask());
[7957]1067
[6235]1068        geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")));
1069
1070        shadowedScene->addChild(geode);
[5786]1071    }
1072
[6235]1073    osg::ref_ptr<osg::LightSource> ls = new osg::LightSource;
1074    ls->getLight()->setPosition(lightpos);
[7957]1075
[12743]1076    if (spotlight)
[7539]1077    {
[12743]1078        osg::Vec3 center = spotLookat;
[7539]1079        osg::Vec3 lightdir = center - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z());
1080        lightdir.normalize();
1081        ls->getLight()->setDirection(lightdir);
[7545]1082        ls->getLight()->setSpotCutoff(25.0f);
[7539]1083
1084        //set the LightSource, only for checking, there is only 1 light in the scene
[8920]1085        osgShadow::ShadowMap* shadowMap = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique());
1086        if( shadowMap ) shadowMap->setLight(ls.get());
[7539]1087    }
1088
[6235]1089    if ( arguments.read("--coloured-light"))
[5779]1090    {
[6235]1091        ls->getLight()->setAmbient(osg::Vec4(1.0,0.0,0.0,1.0));
1092        ls->getLight()->setDiffuse(osg::Vec4(0.0,1.0,0.0,1.0));
[5779]1093    }
1094    else
1095    {
[6235]1096        ls->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1.0));
1097        ls->getLight()->setDiffuse(osg::Vec4(0.8,0.8,0.8,1.0));
[5779]1098    }
[7497]1099
[6141]1100    shadowedScene->addChild(model.get());
1101    shadowedScene->addChild(ls.get());
[7957]1102
[6141]1103    viewer.setSceneData(shadowedScene.get());
[7539]1104
[12189]1105    osg::ref_ptr< DumpShadowVolumesHandler > dumpShadowVolumes = new DumpShadowVolumesHandler;
1106
[12159]1107    viewer.addEventHandler(new ChangeFOVHandler(viewer.getCamera()));
[12189]1108    viewer.addEventHandler( dumpShadowVolumes.get() );
[12159]1109
[5641]1110    // create the windows and run the threads.
1111    viewer.realize();
[12202]1112
[12174]1113    if (fov!=0.0)
1114    {
1115        double fovy, aspectRatio, zNear, zFar;
1116        viewer.getCamera()->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
[5641]1117
[12174]1118        std::cout << "Setting FOV to " << fov << std::endl;
1119        viewer.getCamera()->getProjectionMatrix().makePerspective(fov, aspectRatio, zNear, zFar);
1120    }
1121
[7539]1122    // it is done after viewer.realize() so that the windows are already initialized
1123    if ( arguments.read("--debugHUD"))
1124    {
1125        osgViewer::Viewer::Windows windows;
1126        viewer.getWindows(windows);
[7957]1127
[7539]1128        if (windows.empty()) return 1;
[7957]1129
[7539]1130        osgShadow::ShadowMap* sm = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique());
[13078]1131        if( sm ) {
[8920]1132            osg::ref_ptr<osg::Camera> hudCamera = sm->makeDebugHUD();
[7957]1133
[8920]1134            // set up cameras to rendering on the first window available.
1135            hudCamera->setGraphicsContext(windows[0]);
1136            hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);
[7539]1137
[8920]1138            viewer.addSlave(hudCamera.get(), false);
1139        }
[7539]1140    }
1141
[12763]1142    osg::ref_ptr<LightAnimationHandler> lightAnimationHandler = updateLightPosition ? new LightAnimationHandler : 0;
1143    if (lightAnimationHandler) viewer.addEventHandler(lightAnimationHandler.get());
[7539]1144
[12763]1145
[12529]1146    // osgDB::writeNodeFile(*group,"test.osgt");
[13078]1147
[5641]1148    while (!viewer.done())
1149    {
[8920]1150        {
1151            osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() );
[13078]1152
[8920]1153            if( msm ) {
1154
[13078]1155                // If scene decorated by CoordinateSystemNode try to find localToWorld
[8920]1156                // and set modellingSpaceToWorld matrix to optimize scene bounds computation
1157
1158                osg::NodePath np = viewer.getCoordinateSystemNodePath();
1159                if( !np.empty() ) {
[13078]1160                    osg::CoordinateSystemNode * csn =
[8920]1161                        dynamic_cast<osg::CoordinateSystemNode *>( np.back() );
1162
1163                    if( csn ) {
[13078]1164                        osg::Vec3d pos =
[8920]1165                            viewer.getCameraManipulator()->getMatrix().getTrans();
1166
1167                        msm->setModellingSpaceToWorldTransform
1168                            ( csn->computeLocalCoordinateFrame( pos ) );
1169                    }
1170                }
[13078]1171            }
[8920]1172        }
1173
[12763]1174        if (lightAnimationHandler.valid() && lightAnimationHandler ->getAnimating())
[5779]1175        {
[6051]1176            float t = viewer.getFrameStamp()->getSimulationTime();
[8920]1177
[12174]1178            if (lightpos.w()==1.0)
[5779]1179            {
[7545]1180                lightpos.set(bb.center().x()+sinf(t)*bb.radius(), bb.center().y() + cosf(t)*bb.radius(), bb.zMax() + bb.radius()*3.0f  ,1.0f);
[5779]1181            }
1182            else
1183            {
[6141]1184                lightpos.set(sinf(t),cosf(t),1.0f,0.0f);
[5779]1185            }
[6141]1186            ls->getLight()->setPosition(lightpos);
[7957]1187
[7441]1188            osg::Vec3f lightDir(-lightpos.x(),-lightpos.y(),-lightpos.z());
[7539]1189            if(spotlight)
[7957]1190                lightDir =  osg::Vec3(bb.center().x()+sinf(t)*bb.radius()/2.0, bb.center().y() + cosf(t)*bb.radius()/2.0, bb.center().z())
[7539]1191                - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z()) ;
[7441]1192            lightDir.normalize();
1193            ls->getLight()->setDirection(lightDir);
[5956]1194        }
[5779]1195
[12189]1196        if( dumpShadowVolumes->get() )
1197        {
1198            dumpShadowVolumes->set( false );
1199
1200            static int dumpFileNo = 0;
1201            dumpFileNo ++;
1202            char filename[256];
[12529]1203            std::sprintf( filename, "shadowDump%d.osgt", dumpFileNo );
[13078]1204
[12189]1205            osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() );
1206
[13078]1207            if( msm ) msm->setDebugDump( filename );
[12189]1208        }
1209
[5956]1210        viewer.frame();
[5641]1211    }
[7957]1212
[5641]1213    return 0;
1214}
Note: See TracBrowser for help on using the browser.