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

Revision 8920, 33.3 kB (checked in by robert, 6 years ago)

From Wojciech Lweandowski, added support for noew LispSM shadow technique (use --lispsm on CmdLine?) and added IslandScene? database (use -4 on CmdLine?).

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