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

Revision 12159, 35.0 kB (checked in by robert, 4 years ago)

From Jean-Sebastien Guay, event handler for controlling the field of view of the viewer's camera using 0, - and = keys.

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