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

Revision 1902, 10.7 kB (checked in by robert, 11 years ago)

Updated NEWS for the release.

Fixed warnings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/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
10#include <osgDB/Registry>
11#include <osgDB/ReadFile>
12#include <osgDB/WriteFile>
13
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/Optimizer>
19#include <osgUtil/IntersectVisitor>
20
21#include <osg/OccluderNode>
22#include <osg/Geometry>
23
24
25class OccluderEventHandler : public osgGA::GUIEventHandler
26{
27    public:
28   
29        OccluderEventHandler(osgProducer::Viewer* viewer):_viewer(viewer) {}
30   
31        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
32
33        virtual void accept(osgGA::GUIEventHandlerVisitor& v)
34        {
35            v.visit(*this);
36        }
37       
38        void addPoint(const osg::Vec3& pos);
39               
40        void endOccluder();
41       
42        osg::Group* rootNode() { return dynamic_cast<osg::Group*>(_viewer->getSceneData()); }
43       
44       
45        osgProducer::Viewer*                    _viewer;
46        osg::ref_ptr<osg::Group>                _rootnode;
47        osg::ref_ptr<osg::Group>                _occluders;
48        osg::ref_ptr<osg::ConvexPlanarOccluder> _convexPlanarOccluder;
49};
50
51bool OccluderEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
52{
53    switch(ea.getEventType())
54    {
55        case(osgGA::GUIEventAdapter::KEYDOWN):
56        {
57            if (ea.getKey()=='a')
58            {
59
60                float x = ea.getXnormalized();
61                float y = ea.getYnormalized();
62 
63                osgUtil::IntersectVisitor::HitList hitList;
64                if (!_viewer->computeIntersections(x,y,hitList))
65                {
66                     return true;
67                }
68
69                if (!hitList.empty())
70                {
71
72                    osgUtil::Hit& hit = hitList.front();
73                    addPoint(hit.getWorldIntersectPoint());
74                }
75
76                return true;
77            }
78            else if (ea.getKey()=='e')
79            {
80                endOccluder();
81                return true;
82            }
83            else if (ea.getKey()=='O')
84            {
85                if (_occluders.valid())
86                {
87                   
88                    if (osgDB::writeNodeFile(*_occluders,"saved_occluders.osg"))
89                        std::cout<<"saved occluders to 'saved_occluders.osg'"<<std::endl;
90                }
91                else
92                {
93                    std::cout<<"no occluders to save"<<std::endl;
94                }
95                return true;
96            }
97            return false;
98        }
99
100        default:
101            return false;
102    }
103}
104
105void OccluderEventHandler::addPoint(const osg::Vec3& pos)
106{
107    std::cout<<"add point "<<pos<<std::endl;
108   
109    if (!_convexPlanarOccluder.valid()) _convexPlanarOccluder = new osg::ConvexPlanarOccluder;
110   
111    osg::ConvexPlanarPolygon& occluder = _convexPlanarOccluder->getOccluder();
112    occluder.add(pos);
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    osgProducer::Viewer viewer(arguments);
282
283    // set up the value with sensible default event handlers.
284    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
285
286    bool manuallyCreateOccluders = false;
287    while (arguments.read("-m")) { manuallyCreateOccluders = true; }
288
289    if (manuallyCreateOccluders)
290    {
291        viewer.getEventHandlerList().push_front(new OccluderEventHandler(&viewer));
292    }
293
294    // get details on keyboard and mouse bindings used by the viewer.
295    viewer.getUsage(*arguments.getApplicationUsage());
296
297    // if user request help write it out to cout.
298    if (arguments.read("-h") || arguments.read("--help"))
299    {
300        arguments.getApplicationUsage()->write(std::cout);
301        return 1;
302    }
303
304    // any option left unread are converted into errors to write out later.
305    arguments.reportRemainingOptionsAsUnrecognized();
306
307    // report any errors if they have occured when parsing the program aguments.
308    if (arguments.errors())
309    {
310        arguments.writeErrorMessages(std::cout);
311        return 1;
312    }
313
314    // load the nodes from the commandline arguments.
315    osg::Node* loadedmodel = osgDB::readNodeFiles(arguments);
316    if (!loadedmodel)
317    {
318        return 1;
319    }
320   
321    // run optimization over the scene graph
322    osgUtil::Optimizer optimzer;
323    optimzer.optimize(loadedmodel);
324
325    // add the occluders to the loaded model.
326    osg::ref_ptr<osg::Group> rootnode;
327   
328    if (manuallyCreateOccluders)
329    {
330        rootnode = new osg::Group;
331        rootnode->addChild(loadedmodel);
332    }
333    else   
334    {
335        rootnode = createOccludersAroundModel(loadedmodel);
336    }
337   
338     
339    // add a viewport to the viewer and attach the scene graph.
340    viewer.setSceneData( rootnode.get() );
341
342
343    // create the windows and run the threads.
344    viewer.realize();
345
346
347    while( !viewer.done() )
348    {
349        // wait for all cull and draw threads to complete.
350        viewer.sync();
351
352        // update the scene by traversing it with the the update visitor which will
353        // call all node update callbacks and animations.
354        viewer.update();
355         
356        // fire off the cull and draw traversals of the scene.
357        viewer.frame();
358       
359    }
360
361    viewer.sync();
362
363    return 0;
364}
Note: See TracBrowser for help on using the browser.