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

Revision 12203, 38.5 kB (checked in by robert, 3 years ago)

Moved intial cut of depth partition support into osgViewer::View via two new methods:

/** Convenience method for setting up multiple slave cameras that depth partition the specified camera.*/
bool setUpDepthPartitionForCamera(osg::Camera* cameraToPartition, DepthPartitionSettings?* dps=0);

/** Convenience method for setting up multiple slave cameras that depth partition each of the view's active cameras.*/
bool setUpDepthPartition(DepthPartitionSettings?* dsp=0);

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