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

Revision 7219, 25.0 kB (checked in by robert, 7 years ago)

Added support for SoftShadowMap? into osgshadow example

  • 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
44#include <osgDB/ReadFile>
45#include <osgDB/WriteFile>
46
47#include <iostream>
48
49// for the grid data..
50#include "../osghangglide/terrain_coords.h"
51
52const int ReceivesShadowTraversalMask = 0x1;
53const int CastsShadowTraversalMask = 0x2;
54 
55namespace ModelOne
56{
57
58    enum Faces
59    {
60        FRONT_FACE = 1,
61        BACK_FACE = 2,
62        LEFT_FACE = 4,
63        RIGHT_FACE = 8,
64        TOP_FACE = 16,
65        BOTTOM_FACE = 32       
66    };
67
68    osg::Node* createCube(unsigned int mask)
69    {
70        osg::Geode* geode = new osg::Geode;
71
72        osg::Geometry* geometry = new osg::Geometry;
73        geode->addDrawable(geometry);
74
75        osg::Vec3Array* vertices = new osg::Vec3Array;
76        geometry->setVertexArray(vertices);
77
78        osg::Vec3Array* normals = new osg::Vec3Array;
79        geometry->setNormalArray(normals);
80        geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
81
82        osg::Vec4Array* colours = new osg::Vec4Array;
83        geometry->setColorArray(colours);
84        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
85        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
86
87
88        osg::Vec3 origin(0.0f,0.0f,0.0f);
89        osg::Vec3 dx(2.0f,0.0f,0.0f);
90        osg::Vec3 dy(0.0f,1.0f,0.0f);
91        osg::Vec3 dz(0.0f,0.0f,1.0f);
92
93        osg::Vec3 px(1.0f,0.0,0.0f);
94        osg::Vec3 nx(-1.0f,0.0,0.0f);
95        osg::Vec3 py(0.0f,1.0f,0.0f);
96        osg::Vec3 ny(0.0f,-1.0f,0.0f);
97        osg::Vec3 pz(0.0f,0.0f,1.0f);
98        osg::Vec3 nz(0.0f,0.0f,-1.0f);
99
100        if (mask & FRONT_FACE)
101        {
102            // front face   
103            vertices->push_back(origin);
104            vertices->push_back(origin+dx);
105            vertices->push_back(origin+dx+dz);
106            vertices->push_back(origin+dz);
107            normals->push_back(ny);
108            normals->push_back(ny);
109            normals->push_back(ny);
110            normals->push_back(ny);
111        }
112
113        if (mask & BACK_FACE)
114        {
115            // back face   
116            vertices->push_back(origin+dy);
117            vertices->push_back(origin+dy+dz);
118            vertices->push_back(origin+dy+dx+dz);
119            vertices->push_back(origin+dy+dx);
120            normals->push_back(py);
121            normals->push_back(py);
122            normals->push_back(py);
123            normals->push_back(py);
124        }
125
126        if (mask & LEFT_FACE)
127        {
128            // left face   
129            vertices->push_back(origin+dy);
130            vertices->push_back(origin);
131            vertices->push_back(origin+dz);
132            vertices->push_back(origin+dy+dz);
133            normals->push_back(nx);
134            normals->push_back(nx);
135            normals->push_back(nx);
136            normals->push_back(nx);
137        }
138
139        if (mask & RIGHT_FACE)
140        {
141            // right face   
142            vertices->push_back(origin+dx+dy);
143            vertices->push_back(origin+dx+dy+dz);
144            vertices->push_back(origin+dx+dz);
145            vertices->push_back(origin+dx);
146            normals->push_back(px);
147            normals->push_back(px);
148            normals->push_back(px);
149            normals->push_back(px);
150        }
151
152        if (mask & TOP_FACE)
153        {
154            // top face   
155            vertices->push_back(origin+dz);
156            vertices->push_back(origin+dz+dx);
157            vertices->push_back(origin+dz+dx+dy);
158            vertices->push_back(origin+dz+dy);
159            normals->push_back(pz);
160            normals->push_back(pz);
161            normals->push_back(pz);
162            normals->push_back(pz);
163        }
164
165        if (mask & BOTTOM_FACE)
166        {
167            // bottom face   
168            vertices->push_back(origin);
169            vertices->push_back(origin+dy);
170            vertices->push_back(origin+dx+dy);
171            vertices->push_back(origin+dx);
172            normals->push_back(nz);
173            normals->push_back(nz);
174            normals->push_back(nz);
175            normals->push_back(nz);
176        }
177
178        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));
179
180        return geode;
181    }
182
183    class SwitchHandler : public osgGA::GUIEventHandler
184    {
185    public:
186
187        SwitchHandler():
188            _childNum(0) {}
189
190        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& /*aa*/, osg::Object* object, osg::NodeVisitor* /*nv*/)
191        {
192            osg::Switch* sw = dynamic_cast<osg::Switch*>(object);
193            if (!sw) return false;
194
195            if (ea.getHandled()) return false;
196
197            switch(ea.getEventType())
198            {
199                case(osgGA::GUIEventAdapter::KEYDOWN):
200                {
201                    if (ea.getKey()=='n')
202                    {
203                        ++_childNum;
204                        if (_childNum >= sw->getNumChildren()) _childNum = 0;
205
206                        sw->setSingleChildOn(_childNum);
207                        return true;
208                    }               
209                    break;
210                }
211                default:
212                    break;
213            }
214            return false;
215        }
216
217    protected:
218
219        virtual ~SwitchHandler() {}
220        unsigned int    _childNum;
221
222    };
223
224
225    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
226    {
227        osg::Switch* sw = new osg::Switch;
228        sw->setEventCallback(new ModelOne::SwitchHandler);
229
230        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE), true);
231        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE), false);
232        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE), false);
233        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE), false);
234        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE), false);
235        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE | ModelOne::BOTTOM_FACE), false);
236       
237        return sw;   
238    }
239}
240
241namespace ModelTwo
242{
243    osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
244    {
245        // set up the animation path
246        osg::AnimationPath* animationPath = new osg::AnimationPath;
247        animationPath->setLoopMode(osg::AnimationPath::LOOP);
248
249        int numSamples = 40;
250        float yaw = 0.0f;
251        float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
252        float roll = osg::inDegrees(30.0f);
253
254        double time=0.0f;
255        double time_delta = looptime/(double)numSamples;
256        for(int i=0;i<numSamples;++i)
257        {
258            osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
259            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)));
260
261            animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
262
263            yaw += yaw_delta;
264            time += time_delta;
265
266        }
267        return animationPath;   
268    }
269
270    osg::Node* createBase(const osg::Vec3& center,float radius)
271    {
272
273        osg::Geode* geode = new osg::Geode;
274
275        // set up the texture of the base.
276        osg::StateSet* stateset = new osg::StateSet();
277        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
278        if (image)
279        {
280            osg::Texture2D* texture = new osg::Texture2D;
281            texture->setImage(image);
282            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
283        }
284
285        geode->setStateSet( stateset );
286
287
288        osg::HeightField* grid = new osg::HeightField;
289        grid->allocate(38,39);
290        grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
291        grid->setXInterval(radius*2.0f/(float)(38-1));
292        grid->setYInterval(radius*2.0f/(float)(39-1));
293
294        float minHeight = FLT_MAX;
295        float maxHeight = -FLT_MAX;
296
297
298        unsigned int r;
299        for(r=0;r<39;++r)
300        {
301            for(unsigned int c=0;c<38;++c)
302            {
303                float h = vertex[r+c*39][2];
304                if (h>maxHeight) maxHeight=h;
305                if (h<minHeight) minHeight=h;
306            }
307        }
308
309        float hieghtScale = radius*0.5f/(maxHeight-minHeight);
310        float hieghtOffset = -(minHeight+maxHeight)*0.5f;
311
312        for(r=0;r<39;++r)
313        {
314            for(unsigned int c=0;c<38;++c)
315            {
316                float h = vertex[r+c*39][2];
317                grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
318            }
319        }
320
321        geode->addDrawable(new osg::ShapeDrawable(grid));
322
323        osg::Group* group = new osg::Group;
324        group->addChild(geode);
325
326        return group;
327
328    }
329
330    osg::Node* createMovingModel(const osg::Vec3& center, float radius)
331    {
332        float animationLength = 10.0f;
333
334        osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
335
336        osg::Group* model = new osg::Group;
337
338        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
339        if (cessna)
340        {
341            const osg::BoundingSphere& bs = cessna->getBound();
342
343            float size = radius/bs.radius()*0.3f;
344            osg::MatrixTransform* positioned = new osg::MatrixTransform;
345            positioned->setDataVariance(osg::Object::STATIC);
346            positioned->setMatrix(osg::Matrix::translate(-bs.center())*
347                                  osg::Matrix::scale(size,size,size)*
348                                  osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
349
350            positioned->addChild(cessna);
351
352            osg::MatrixTransform* xform = new osg::MatrixTransform;
353            xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
354            xform->addChild(positioned);
355
356            model->addChild(xform);
357        }
358
359        return model;
360    }
361
362    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
363    {
364        osg::Vec3 center(0.0f,0.0f,0.0f);
365        float radius = 100.0f;
366        osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
367
368        // the shadower model
369        osg::Node* shadower = createMovingModel(center,radius*0.5f);
370        shadower->setNodeMask(CastsShadowTraversalMask);
371
372        // the shadowed model
373        osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
374        shadowed->setNodeMask(ReceivesShadowTraversalMask);
375       
376        osg::Group* group = new osg::Group;
377
378        group->addChild(shadowed);
379        group->addChild(shadower);
380       
381        return group;
382    }
383}
384
385namespace ModelThree
386{
387    osg::Group* createModel(osg::ArgumentParser& arguments)
388    {
389        osg::Group* scene = new osg::Group;
390
391        osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
392        scene->addChild(geode_1.get());
393
394        osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
395        osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
396        transform_2->addChild(geode_2.get());
397        transform_2->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(45.0f)));
398        scene->addChild(transform_2.get());
399
400        osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
401        osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
402        transform_3->addChild(geode_3.get());
403        transform_3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(-22.5f)));
404        scene->addChild(transform_3.get());
405
406        const float radius = 0.8f;
407        const float height = 1.0f;
408        osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
409        hints->setDetailRatio(2.0f);
410        osg::ref_ptr<osg::ShapeDrawable> shape;
411
412        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
413        shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
414        geode_1->addDrawable(shape.get());
415
416        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2), hints.get());
417        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
418        geode_1->addDrawable(shape.get());
419
420        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
421        shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
422        geode_2->addDrawable(shape.get());
423
424        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
425        shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
426        geode_2->addDrawable(shape.get());
427
428        shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
429        shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
430        geode_2->addDrawable(shape.get());
431
432        shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
433        shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
434        geode_2->addDrawable(shape.get());
435
436        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f, 0.1f), hints.get());
437        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
438        geode_3->addDrawable(shape.get());
439
440        // material
441        osg::ref_ptr<osg::Material> matirial = new osg::Material;
442        matirial->setColorMode(osg::Material::DIFFUSE);
443        matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
444        matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
445        matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
446        scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
447
448        bool withBaseTexture = true;
449        while(arguments.read("--with-base-texture")) { withBaseTexture = true; }
450        while(arguments.read("--no-base-texture")) { withBaseTexture = false; }
451
452        if (withBaseTexture)
453        {
454            scene->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")), osg::StateAttribute::ON);
455        }
456
457        return scene;
458    }
459   
460}
461
462
463osg::Node* createTestModel(osg::ArgumentParser& arguments)
464{
465    if (arguments.read("-1"))
466    {
467        return ModelOne::createModel(arguments);
468    }
469    else if (arguments.read("-2"))
470    {
471        return ModelTwo::createModel(arguments);
472    }
473    else /*if (arguments.read("-3"))*/
474    {
475        return ModelThree::createModel(arguments);
476    }
477   
478}
479
480int main(int argc, char** argv)
481{
482    // use an ArgumentParser object to manage the program arguments.
483    osg::ArgumentParser arguments(&argc, argv);
484
485    // set up the usage document, in case we need to print out how to use this program.
486    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
487    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
488    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
489    arguments.getApplicationUsage()->addCommandLineOption("--positionalLight", "Use a positional light.");
490    arguments.getApplicationUsage()->addCommandLineOption("--directionalLight", "Use a direction light.");
491    arguments.getApplicationUsage()->addCommandLineOption("--noUpdate", "Disable the updating the of light source.");
492    arguments.getApplicationUsage()->addCommandLineOption("--base", "Add a base geometry to test shadows.");
493    arguments.getApplicationUsage()->addCommandLineOption("--sv", "Select ShadowVolume implementation.");
494    arguments.getApplicationUsage()->addCommandLineOption("--ssm", "Select SoftShadowMap implementation.");
495    arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation.");
496//    arguments.getApplicationUsage()->addCommandLineOption("--pssm", "Select ParallelSplitShadowMap implementation.");
497    arguments.getApplicationUsage()->addCommandLineOption("-1", "Use test model one.");
498    arguments.getApplicationUsage()->addCommandLineOption("-2", "Use test model two.");
499    arguments.getApplicationUsage()->addCommandLineOption("-3", "Use test model three.");
500    arguments.getApplicationUsage()->addCommandLineOption("--two-sided", "Use two-sided stencil extension for shadow volumes.");
501    arguments.getApplicationUsage()->addCommandLineOption("--two-pass", "Use two-pass stencil for shadow volumes.");
502
503
504    // construct the viewer.
505    osgViewer::Viewer viewer;
506
507    // if user request help write it out to cout.
508    if (arguments.read("-h") || arguments.read("--help"))
509    {
510        arguments.getApplicationUsage()->write(std::cout);
511        return 1;
512    }
513
514    // default to single threaded during dev work.
515    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
516   
517    while (arguments.read("--SingleThreaded")) viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
518    while (arguments.read("--CullDrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
519    while (arguments.read("--DrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
520    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
521
522
523    bool postionalLight = true;
524    while (arguments.read("--positionalLight")) postionalLight = true;
525    while (arguments.read("--directionalLight")) postionalLight = false;
526
527    bool updateLightPosition = true;
528    while (arguments.read("--noUpdate")) updateLightPosition = false;
529
530
531    int screenNum = -1;
532    while (arguments.read("--screen", screenNum)) viewer.setUpViewOnSingleScreen(screenNum);
533
534    // set up the camera manipulators.
535    {
536        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
537
538        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
539        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
540        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
541        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
542
543        std::string pathfile;
544        char keyForAnimationPath = '5';
545        while (arguments.read("-p",pathfile))
546        {
547            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
548            if (apm || !apm->valid())
549            {
550                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
551                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
552                keyswitchManipulator->selectMatrixManipulator(num);
553                ++keyForAnimationPath;
554            }
555        }
556
557        viewer.setCameraManipulator( keyswitchManipulator.get() );
558    }
559
560    // add the state manipulator
561    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
562
563    // add stats
564    viewer.addEventHandler( new osgViewer::StatsHandler() );
565
566    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
567    if (model.valid())
568    {
569        model->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);
570    }
571    else
572    {
573        model = createTestModel(arguments);
574    }
575
576    // get the bounds of the model.   
577    osg::ComputeBoundsVisitor cbbv;
578    model->accept(cbbv);
579    osg::BoundingBox bb = cbbv.getBoundingBox();
580
581    osg::Vec4 lightpos;
582   
583    if (postionalLight)
584    {
585        lightpos.set(bb.center().x(), bb.center().y(), bb.zMax() + bb.radius()  ,1.0f);
586    }
587    else
588    {
589        lightpos.set(0.5f,0.25f,0.8f,0.0f);
590    }
591
592
593    osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene;
594   
595    shadowedScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
596    shadowedScene->setCastsShadowTraversalMask(CastsShadowTraversalMask);
597   
598   
599    if (arguments.read("--sv"))
600    {
601        // hint to tell viewer to request stencil buffer when setting up windows
602        osg::DisplaySettings::instance()->setMinimumNumStencilBits(8);
603
604        osg::ref_ptr<osgShadow::ShadowVolume> sv = new osgShadow::ShadowVolume;
605        sv->setDynamicShadowVolumes(updateLightPosition);
606        while (arguments.read("--two-sided")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_SIDED);
607        while (arguments.read("--two-pass")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_PASS);
608
609        shadowedScene->setShadowTechnique(sv.get());
610    }
611    else if (arguments.read("--st"))
612    {
613        osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture;
614        shadowedScene->setShadowTechnique(st.get());
615    }
616#if 0   
617    else if (arguments.read("--pssm"))
618    {
619        osg::ref_ptr<osgShadow::ParallelSplitShadowMap> pssm = new osgShadow::ParallelSplitShadowMap;
620        shadowedScene->setShadowTechnique(pssm.get());
621    }
622#endif   
623    else if (arguments.read("--ssm"))
624    {
625        osg::ref_ptr<osgShadow::SoftShadowMap> sm = new osgShadow::SoftShadowMap;
626        shadowedScene->setShadowTechnique(sm.get());
627    }
628    else /* if (arguments.read("--sm")) */
629    {
630        osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
631        shadowedScene->setShadowTechnique(sm.get());
632    }
633
634    if ( arguments.read("--base"))
635    {
636
637        osg::Geode* geode = new osg::Geode;
638       
639        osg::Vec3 widthVec(bb.radius(), 0.0f, 0.0f);
640        osg::Vec3 depthVec(0.0f, bb.radius(), 0.0f);
641        osg::Vec3 centerBase( (bb.xMin()+bb.xMax())*0.5f, (bb.yMin()+bb.yMax())*0.5f, bb.zMin()-bb.radius()*0.1f );
642       
643        geode->addDrawable( osg::createTexturedQuadGeometry( centerBase-widthVec*1.5f-depthVec*1.5f,
644                                                             widthVec*3.0f, depthVec*3.0f) );
645                                                             
646        geode->setNodeMask(shadowedScene->getReceivesShadowTraversalMask());
647       
648        geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")));
649
650        shadowedScene->addChild(geode);
651    }
652
653    osg::ref_ptr<osg::LightSource> ls = new osg::LightSource;
654    ls->getLight()->setPosition(lightpos);
655    if ( arguments.read("--coloured-light"))
656    {
657        ls->getLight()->setAmbient(osg::Vec4(1.0,0.0,0.0,1.0));
658        ls->getLight()->setDiffuse(osg::Vec4(0.0,1.0,0.0,1.0));
659    }
660    else
661    {
662        ls->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1.0));
663        ls->getLight()->setDiffuse(osg::Vec4(0.8,0.8,0.8,1.0));
664    }
665   
666    shadowedScene->addChild(model.get());
667    shadowedScene->addChild(ls.get());
668   
669    viewer.setSceneData(shadowedScene.get());
670   
671    // create the windows and run the threads.
672    viewer.realize();
673
674    // osgDB::writeNodeFile(*group,"test.osg");
675
676    while (!viewer.done())
677    {
678        if (updateLightPosition)
679        {
680            float t = viewer.getFrameStamp()->getSimulationTime();
681            if (postionalLight)
682            {
683                lightpos.set(bb.center().x()+sinf(t)*bb.radius(), bb.center().y() + cosf(t)*bb.radius(), bb.zMax() + bb.radius()  ,1.0f);
684            }
685            else
686            {
687                lightpos.set(sinf(t),cosf(t),1.0f,0.0f);
688            }
689            ls->getLight()->setPosition(lightpos);
690        }
691
692        viewer.frame();
693    }
694   
695    return 0;
696}
Note: See TracBrowser for help on using the browser.