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

Revision 12192, 37.7 kB (checked in by robert, 3 years ago)

Removed TrapezoidalShadowMap? due to discovery of patent on algorithm.

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