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

Revision 12768, 40.7 kB (checked in by robert, 3 years ago)

Added support for setting the MinimumShadowMapNearFarRatio?.

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