root/OpenSceneGraph/trunk/examples/osgoccluder/osgoccluder.cpp @ 6916

Revision 6916, 10.1 kB (checked in by robert, 8 years ago)

From Martin Lavery and Robert Osfield, added fallbacks for when now command line args are provided.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgViewer/Viewer>
2
3#include <osg/MatrixTransform>
4#include <osg/Billboard>
5#include <osg/Geode>
6#include <osg/Group>
7#include <osg/Notify>
8#include <osg/LineSegment>
9#include <osg/io_utils>
10
11#include <osgDB/Registry>
12#include <osgDB/ReadFile>
13#include <osgDB/WriteFile>
14
15#include <osgGA/TrackballManipulator>
16#include <osgGA/FlightManipulator>
17#include <osgGA/DriveManipulator>
18
19#include <osgUtil/Optimizer>
20#include <osgUtil/IntersectVisitor>
21
22#include <osg/OccluderNode>
23#include <osg/Geometry>
24#include <osg/ShapeDrawable>
25
26#include <iostream>
27
28class OccluderEventHandler : public osgGA::GUIEventHandler
29{
30    public:
31   
32        OccluderEventHandler(osgViewer::Viewer* viewer):_viewer(viewer) {}
33   
34        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
35
36        void addPoint(const osg::Vec3& pos);
37               
38        void endOccluder();
39       
40        osg::Group* rootNode() { return dynamic_cast<osg::Group*>(_viewer->getSceneData()); }
41       
42       
43        osgViewer::Viewer*                    _viewer;
44        osg::ref_ptr<osg::Group>                _occluders;
45        osg::ref_ptr<osg::ConvexPlanarOccluder> _convexPlanarOccluder;
46};
47
48bool OccluderEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
49{
50    switch(ea.getEventType())
51    {
52        case(osgGA::GUIEventAdapter::KEYDOWN):
53        {
54            if (ea.getKey()=='a')
55
56            {
57                osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
58                osgUtil::LineSegmentIntersector::Intersections intersections;
59                if (view && view->computeIntersections(ea.getX(), ea.getY(), intersections))
60                {
61                    const osgUtil::LineSegmentIntersector::Intersection& hit = *(intersections.begin());
62                    if (hit.matrix.valid()) addPoint(hit.localIntersectionPoint * (*hit.matrix));
63                    else addPoint(hit.localIntersectionPoint);
64                }
65
66                return true;
67            }
68            else if (ea.getKey()=='e')
69            {
70                endOccluder();
71                return true;
72            }
73            else if (ea.getKey()=='O')
74            {
75                if (_occluders.valid())
76                {
77                   
78                    if (osgDB::writeNodeFile(*_occluders,"saved_occluders.osg"))
79                        std::cout<<"saved occluders to 'saved_occluders.osg'"<<std::endl;
80                }
81                else
82                {
83                    std::cout<<"no occluders to save"<<std::endl;
84                }
85                return true;
86            }
87            return false;
88        }
89
90        default:
91            return false;
92    }
93}
94
95void OccluderEventHandler::addPoint(const osg::Vec3& pos)
96{
97    std::cout<<"add point "<<pos<<std::endl;
98   
99    if (!_convexPlanarOccluder.valid()) _convexPlanarOccluder = new osg::ConvexPlanarOccluder;
100   
101    osg::ConvexPlanarPolygon& occluder = _convexPlanarOccluder->getOccluder();
102    occluder.add(pos);
103
104//     
105//     osg::BoundingSphere bs = rootNode()->getBound();
106//
107//     osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(pos,bs.radius()*0.001f));
108//     osg::Geode* geode = new osg::Geode;
109//     geode->addDrawable(sd);
110//
111//     rootNode()->addChild(geode);
112//
113   
114}
115               
116void OccluderEventHandler::endOccluder()
117{
118    if (_convexPlanarOccluder.valid())
119    {
120        if (_convexPlanarOccluder->getOccluder().getVertexList().size()>=3)
121        {
122            osg::OccluderNode* occluderNode = new osg::OccluderNode;
123            occluderNode->setOccluder(_convexPlanarOccluder.get());
124
125            if (!_occluders.valid())
126            {
127                _occluders = new osg::Group;
128                if (rootNode()) rootNode()->addChild(_occluders.get());
129            }
130            _occluders->addChild(occluderNode);
131
132            std::cout<<"created occluder"<<std::endl;
133        }
134        else
135        {
136            std::cout<<"Occluder requires at least 3 points to create occluder."<<std::endl;
137        }
138    }
139    else
140    {
141        std::cout<<"No occluder points to create occluder with."<<std::endl;
142    }
143   
144    // reset current occluder.
145    _convexPlanarOccluder = NULL;
146}
147
148
149osg::Node* createOccluder(const osg::Vec3& v1,const osg::Vec3& v2,const osg::Vec3& v3,const osg::Vec3& v4,float holeRatio=-1.0f)
150{
151   // create and occluder which will site along side the loadmodel model.
152    osg::OccluderNode* occluderNode = new osg::OccluderNode;
153
154    // create the convex planer occluder
155    osg::ConvexPlanarOccluder* cpo = new osg::ConvexPlanarOccluder;
156
157    // attach it to the occluder node.
158    occluderNode->setOccluder(cpo);
159    occluderNode->setName("occluder");
160   
161    // set the occluder up for the front face of the bounding box.
162    osg::ConvexPlanarPolygon& occluder = cpo->getOccluder();
163    occluder.add(v1);
164    occluder.add(v2);
165    occluder.add(v3);
166    occluder.add(v4);
167
168    // create a whole at the center of the occluder if needed.
169    if (holeRatio>0.0f)
170    {
171        // create hole.
172        float ratio = holeRatio;
173        float one_minus_ratio = 1-ratio;
174        osg::Vec3 center = (v1+v2+v3+v4)*0.25f;
175        osg::Vec3 v1dash = v1*ratio + center*one_minus_ratio;
176        osg::Vec3 v2dash = v2*ratio + center*one_minus_ratio;
177        osg::Vec3 v3dash = v3*ratio + center*one_minus_ratio;
178        osg::Vec3 v4dash = v4*ratio + center*one_minus_ratio;
179
180        osg::ConvexPlanarPolygon hole;
181        hole.add(v1dash);
182        hole.add(v2dash);
183        hole.add(v3dash);
184        hole.add(v4dash);
185
186        cpo->addHole(hole);
187    }   
188   
189
190   // create a drawable for occluder.
191    osg::Geometry* geom = new osg::Geometry;
192   
193    osg::Vec3Array* coords = new osg::Vec3Array(occluder.getVertexList().begin(),occluder.getVertexList().end());
194    geom->setVertexArray(coords);
195   
196    osg::Vec4Array* colors = new osg::Vec4Array(1);
197    (*colors)[0].set(1.0f,1.0f,1.0f,0.5f);
198    geom->setColorArray(colors);
199    geom->setColorBinding(osg::Geometry::BIND_OVERALL);
200   
201    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
202   
203    osg::Geode* geode = new osg::Geode;
204    geode->addDrawable(geom);
205   
206    osg::StateSet* stateset = new osg::StateSet;
207    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
208    stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
209    stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
210   
211    geom->setStateSet(stateset);
212   
213    // add the occluder geode as a child of the occluder,
214    // as the occluder can't self occlude its subgraph the
215    // geode will never be occluder by this occluder.
216    occluderNode->addChild(geode);   
217   
218    return occluderNode;
219 
220 }
221
222osg::Group* createOccludersAroundModel(osg::Node* model)
223{
224    osg::Group* scene = new osg::Group;
225    scene->setName("rootgroup");
226
227
228    // add the loaded model into a the scene group.
229    scene->addChild(model);
230    model->setName("model");
231
232    // get the bounding volume of the model.
233    const osg::BoundingSphere bs = model->getBound();
234   
235    // create a bounding box around the sphere.
236    osg::BoundingBox bb;
237    bb.expandBy(bs);
238
239   // front
240   scene->addChild(createOccluder(bb.corner(0),
241                                  bb.corner(1),
242                                  bb.corner(5),
243                                  bb.corner(4)));
244
245   // right side
246   scene->addChild(createOccluder(bb.corner(1),
247                                  bb.corner(3),
248                                  bb.corner(7),
249                                  bb.corner(5)));
250
251   // left side
252   scene->addChild(createOccluder(bb.corner(2),
253                                  bb.corner(0),
254                                  bb.corner(4),
255                                  bb.corner(6)));
256
257   // back side
258   scene->addChild(createOccluder(bb.corner(3),
259                                  bb.corner(2),
260                                  bb.corner(6),
261                                  bb.corner(7),
262                                  0.5f)); // create a hole half the size of the occluder.
263
264    return scene;
265}
266
267
268int main( int argc, char **argv )
269{
270
271    // use an ArgumentParser object to manage the program arguments.
272    osg::ArgumentParser arguments(&argc,argv);
273
274    // set up the usage document, in case we need to print out how to use this program.
275    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of convex planer occluders.");
276    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
277    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
278    arguments.getApplicationUsage()->addCommandLineOption("-m","Mannually create occluders");
279   
280    // initialize the viewer.
281    osgViewer::Viewer viewer;
282
283    bool manuallyCreateOccluders = false;
284    while (arguments.read("-m")) { manuallyCreateOccluders = true; }
285
286    if (manuallyCreateOccluders)
287    {
288        viewer.addEventHandler(new OccluderEventHandler(&viewer));
289    }
290
291    // if user request help write it out to cout.
292    if (arguments.read("-h") || arguments.read("--help"))
293    {
294        arguments.getApplicationUsage()->write(std::cout);
295        return 1;
296    }
297
298    // load the nodes from the commandline arguments.
299    osg::Node* loadedmodel = osgDB::readNodeFiles(arguments);
300   
301    // if not loaded assume no arguments passed in, try use default mode instead.
302    if (!loadedmodel) loadedmodel = osgDB::readNodeFile("glider.osg");
303   
304    if (!loadedmodel)
305    {
306        osg::notify(osg::NOTICE)<<"Please sepecify and model filename on the command line."<<std::endl;
307        return 1;
308    }
309   
310    // run optimization over the scene graph
311    osgUtil::Optimizer optimzer;
312    optimzer.optimize(loadedmodel);
313
314    // add the occluders to the loaded model.
315    osg::ref_ptr<osg::Group> rootnode;
316   
317    if (manuallyCreateOccluders)
318    {
319        rootnode = new osg::Group;
320        rootnode->addChild(loadedmodel);
321    }
322    else   
323    {
324        rootnode = createOccludersAroundModel(loadedmodel);
325    }
326   
327     
328    // add a viewport to the viewer and attach the scene graph.
329    viewer.setSceneData( rootnode.get() );
330
331    return viewer.run();
332}
Note: See TracBrowser for help on using the browser.