root/OpenSceneGraph/trunk/examples/osgoscdevice/osgoscdevice.cpp @ 13376

Revision 13376, 20.5 kB (checked in by robert, 14 hours ago)

Added support for writing the file path of a script to the lua package.path to help with loading scripts within lua.

  • Property svn:executable set to *
Line 
1/* OpenSceneGraph example, osgcubemap.
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 <iostream>
20
21#include <osgUtil/Optimizer>
22#include <osgDB/ReadFile>
23
24#include <osg/Material>
25#include <osg/Geode>
26#include <osg/BlendFunc>
27#include <osg/Depth>
28#include <osg/Projection>
29#include <osg/PolygonOffset>
30#include <osg/MatrixTransform>
31#include <osg/Camera>
32#include <osg/ValueObject>
33#include <osg/FrontFace>
34#include <osgDB/ReadFile>
35
36#include <osgText/Text>
37
38#include <osgGA/Device>
39#include <osgGA/TrackballManipulator>
40#include <osgGA/FlightManipulator>
41#include <osgGA/StateSetManipulator>
42#include <osgViewer/ViewerEventHandlers>
43
44#include <osgViewer/CompositeViewer>
45
46#include <osgFX/Scribe>
47
48#include <osg/io_utils>
49
50
51// class to handle events with a pick
52class PickHandler : public osgGA::GUIEventHandler {
53public:
54
55    PickHandler(osgGA::Device* device):
56        _device(device) {}
57       
58    ~PickHandler() {}
59   
60    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
61
62    virtual void pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea);
63
64    void setLabel(const std::string& name, float x, float y)
65    {
66        osg::ref_ptr<osgGA::GUIEventAdapter> ea = new osgGA::GUIEventAdapter();
67        ea->setEventType(osgGA::GUIEventAdapter::USER);
68        ea->setName("pick-result");
69        ea->setUserValue("name", name);
70        ea->setUserValue("x", x);
71        ea->setUserValue("y", y);
72       
73        _device->sendEvent(*ea);
74    }
75   
76protected:
77
78    osg::ref_ptr<osgGA::Device>  _device;
79};
80
81bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
82{
83    switch(ea.getEventType())
84    {
85        case(osgGA::GUIEventAdapter::PUSH):
86        {
87            osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
88            if (view) pick(view,ea);
89            return false;
90        }
91       
92        case(osgGA::GUIEventAdapter::KEYUP):
93        {
94            if (ea.getKey() == 't')
95            {
96                osg::ref_ptr<osgGA::GUIEventAdapter> user_event = new osgGA::GUIEventAdapter();
97                user_event->setEventType(osgGA::GUIEventAdapter::USER);
98                user_event->setUserValue("vec2f", osg::Vec2f(1.0f,2.0f));
99                user_event->setUserValue("vec3f", osg::Vec3f(1.0f,2.0f, 3.0f));
100                user_event->setUserValue("vec4f", osg::Vec4f(1.0f,2.0f, 3.0f, 4.0f));
101               
102                user_event->setUserValue("vec2d", osg::Vec2d(1.0,2.0));
103                user_event->setUserValue("vec3d", osg::Vec3d(1.0,2.0, 3.0));
104                user_event->setUserValue("vec4d", osg::Vec4d(1.0,2.0, 3.0, 4.0));
105               
106                user_event->setName("osc_test_1");
107               
108                _device->sendEvent(*user_event);
109            }
110           
111        }
112         
113        default:
114            return false;
115    }
116}
117
118void PickHandler::pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea)
119{
120    osgUtil::LineSegmentIntersector::Intersections intersections;
121
122    std::string gdlist="";
123    float x = ea.getX();
124    float y = ea.getY();
125    if (view->computeIntersections(ea, intersections))
126    {
127        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
128            hitr != intersections.end();
129            ++hitr)
130        {
131            std::ostringstream os;
132            if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty()))
133            {
134                // the geodes are identified by name.
135                os<<"Object \""<<hitr->nodePath.back()->getName()<<"\""<<std::endl;
136            }
137            else if (hitr->drawable.valid())
138            {
139                os<<"Object \""<<hitr->drawable->className()<<"\""<<std::endl;
140            }
141
142            os<<"        local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<"  normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl;
143            os<<"        world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<"  normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl;
144            const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList;
145            for(unsigned int i=0;i<vil.size();++i)
146            {
147                os<<"        vertex indices ["<<i<<"] = "<<vil[i]<<std::endl;
148            }
149           
150            gdlist += os.str();
151        }
152    }
153    setLabel(gdlist, x, y);
154}
155
156
157class UserEventHandler : public osgGA::GUIEventHandler {
158public:
159
160    UserEventHandler(osgText::Text* text) : osgGA::GUIEventHandler(), _text(text) {}
161       
162    ~UserEventHandler() {}
163   
164    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
165private:
166    osg::ref_ptr<osgText::Text> _text;
167};
168
169
170class MyValueListVisitor : public osg::ValueObject::GetValueVisitor {
171public:
172    virtual void apply(bool value)          { _ss << value << " (bool)"; }
173    virtual void apply(char value)          { _ss << value << " (char)"; }
174    virtual void apply(unsigned char value) { _ss << value << " (unsigned char)"; }
175    virtual void apply(short value)         { _ss << value << " (short)"; }
176    virtual void apply(unsigned short value){ _ss << value << " (unsigned short)"; }
177    virtual void apply(int value)           { _ss << value << " (int)"; }
178    virtual void apply(unsigned int value)  { _ss << value << " (unsigned int)"; }
179    virtual void apply(float value)         { _ss << value << " (float)"; }
180    virtual void apply(double value)        { _ss << value << " (double)"; }
181    virtual void apply(const std::string& value)    { _ss << value << " (std::string)"; }
182    virtual void apply(const osg::Vec2f& value)     { _ss << value << " (osg::Vec2f)"; }
183    virtual void apply(const osg::Vec3f& value)     { _ss << value << " (osg::Vec3f)"; }
184    virtual void apply(const osg::Vec4f& value)     { _ss << value << " (osg::Vec4f)"; }
185    virtual void apply(const osg::Vec2d& value)     { _ss << value << " (osg::Vec2d)"; }
186    virtual void apply(const osg::Vec3d& value)     { _ss << value << " (osg::Vec3d)"; }
187    virtual void apply(const osg::Vec4d& value)     { _ss << value << " (osg::Vec4d)"; }
188    virtual void apply(const osg::Quat& value)      { _ss << value << " (osg::Quat)"; }
189    virtual void apply(const osg::Plane& value)     { _ss << value << " (osg::Plane)"; }
190    virtual void apply(const osg::Matrixf& value)   { _ss << value << " (osg::Matrixf)"; }
191    virtual void apply(const osg::Matrixd& value)   { _ss << value << " (osg::Matrixd)"; }
192    std::string value() const { return _ss.str(); }
193    void clear() {_ss.clear(); }
194private:
195    std::ostringstream _ss;
196};
197
198bool UserEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
199{
200    if (ea.getEventType() == osgGA::GUIEventAdapter::USER) {
201        OSG_ALWAYS << "handle user-event: " << ea.getName() << std::endl;
202       
203        if (ea.getName() == "/pick-result")
204        {
205            std::string name("");
206            float x(0), y(0);
207            ea.getUserValue("name", name);
208            ea.getUserValue("x", x);
209            ea.getUserValue("y", y);
210            std::ostringstream ss;
211            ss << "Name: " << std::endl << name << std::endl << std::endl;
212            ss << "x: " << y << " y: " << y << std::endl;
213           
214            _text->setText(ss.str());
215        }
216        else if(ea.getName() == "/osgga")
217        {
218            osg::Vec4 rect;
219            ea.getUserValue("resize", rect);
220            osg::View* view = dynamic_cast<osgViewer::View*>(&aa);
221            if (view && (rect[2] > 0) && (rect[3] > 0))
222            {
223                OSG_ALWAYS << "resizing view to " << rect << std::endl;
224                osgViewer::GraphicsWindow* win = view->getCamera()->getGraphicsContext() ? dynamic_cast<osgViewer::GraphicsWindow*>(view->getCamera()->getGraphicsContext()) : NULL;
225                if (win)
226                    win->setWindowRectangle(rect[2] + 10 + rect[0], rect[1], rect[2], rect[3]);
227            }
228        }
229        else {
230            const osg::UserDataContainer* udc = ea.getUserDataContainer();
231            if (udc)
232            {
233                OSG_ALWAYS << "contents of " << udc->getName() << ": " << std::endl;
234                for(unsigned int i = 0; i < udc->getNumUserObjects(); ++i)
235                {
236                    const osg::ValueObject* vo = dynamic_cast<const osg::ValueObject*>(udc->getUserObject(i));
237                    OSG_ALWAYS << "  " << vo->getName() << ": ";
238                   
239                    MyValueListVisitor vlv;
240                    vo->get(vlv);
241                    OSG_ALWAYS << vlv.value() << std::endl;
242                }
243            }
244        }
245        return true;
246    }
247   
248    return false;
249}
250
251osg::Node* createHUD()
252{
253
254    // create the hud. derived from osgHud.cpp
255    // adds a set of quads, each in a separate Geode - which can be picked individually
256    // eg to be used as a menuing/help system!
257    // Can pick texts too!
258
259    osg::Camera* hudCamera = new osg::Camera;
260    hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
261    hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
262    hudCamera->setViewMatrix(osg::Matrix::identity());
263    hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
264    hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
265   
266    std::string timesFont("fonts/times.ttf");
267   
268    // turn lighting off for the text and disable depth test to ensure its always ontop.
269    osg::Vec3 position(150.0f,800.0f,0.0f);
270    osg::Vec3 delta(0.0f,-60.0f,0.0f);
271   
272    {
273        osg::Geode* geode = new osg::Geode();
274        osg::StateSet* stateset = geode->getOrCreateStateSet();
275        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
276        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
277        geode->setName("simple");
278        hudCamera->addChild(geode);
279       
280        osgText::Text* text = new  osgText::Text;
281        geode->addDrawable( text );
282       
283        text->setFont(timesFont);
284        text->setText("Picking in Head Up Displays is simple!");
285        text->setPosition(position);
286       
287        position += delta;
288    }   
289   
290   
291    for (int i=0; i<5; i++) {
292        osg::Vec3 dy(0.0f,-30.0f,0.0f);
293        osg::Vec3 dx(120.0f,0.0f,0.0f);
294        osg::Geode* geode = new osg::Geode();
295        osg::StateSet* stateset = geode->getOrCreateStateSet();
296        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
297        osg::Geometry *quad=new osg::Geometry;
298        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
299        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
300        std::string name="subOption";
301        name += " ";
302        name += std::string(opts[i]);
303        geode->setName(name);
304        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
305        osg::Vec4Array* colors = new osg::Vec4Array;
306        colors = new osg::Vec4Array;
307        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
308        quad->setColorArray(colors);
309        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
310        (*vertices)[0]=position;
311        (*vertices)[1]=position+dx;
312        (*vertices)[2]=position+dx+dy;
313        (*vertices)[3]=position+dy;
314        quad->setVertexArray(vertices);
315        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
316        geode->addDrawable(quad);
317        hudCamera->addChild(geode);
318       
319        position += delta;
320    }   
321   
322   
323   
324    { // this displays what has been selected
325        osg::Geode* geode = new osg::Geode();
326        osg::StateSet* stateset = geode->getOrCreateStateSet();
327        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
328        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
329        geode->setName("The text label");
330        hudCamera->addChild(geode);
331       
332        position += delta;
333    }   
334   
335    return hudCamera;
336
337}
338
339
340class ForwardToDeviceEventHandler : public osgGA::GUIEventHandler {
341public:
342    ForwardToDeviceEventHandler(osgGA::Device* device) : osgGA::GUIEventHandler(), _device(device) {}
343   
344    virtual bool handle (const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *, osg::NodeVisitor *)
345    {
346        _device->sendEvent(ea);
347        return false;
348    }
349   
350protected:
351    osg::ref_ptr<osgGA::Device> _device;
352};
353
354class OscServiceDiscoveredEventHandler: public ForwardToDeviceEventHandler {
355public:
356    OscServiceDiscoveredEventHandler() : ForwardToDeviceEventHandler(NULL) {}
357   
358    virtual bool handle (const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *o, osg::NodeVisitor *nv)
359    {
360        if (_device.valid())
361            return ForwardToDeviceEventHandler::handle(ea, aa, o, nv);
362       
363        if (ea.getEventType() == osgGA::GUIEventAdapter::USER)
364        {
365            if (ea.getName() == "/zeroconf/service-added")
366            {
367                std::string host;
368                unsigned int port;
369                ea.getUserValue("host", host);
370                ea.getUserValue("port", port);
371               
372                OSG_ALWAYS << "new osc-service discovered: " << host << ":" << port << std::endl;
373               
374                std::ostringstream ss ;
375                ss << host << ":" << port << ".sender.osc";
376                _device = osgDB::readFile<osgGA::Device>(ss.str());
377               
378                osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
379                if (view)
380                    view->addEventHandler(new PickHandler(_device.get()));
381                return true;
382            }
383        }
384        return false;
385    }
386   
387};
388
389int main( int argc, char **argv )
390{
391
392    // use an ArgumentParser object to manage the program arguments.
393    osg::ArgumentParser arguments(&argc,argv);
394   
395    arguments.getApplicationUsage()->addCommandLineOption("--zeroconf","uses zeroconf to advertise the osc-plugin and to discover it");
396    arguments.getApplicationUsage()->addCommandLineOption("--sender","create a view which sends its events via osc");
397    arguments.getApplicationUsage()->addCommandLineOption("--recevier","create a view which receive its events via osc");
398   
399
400
401    // read the scene from the list of file specified commandline args.
402    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
403
404    if (!scene)
405    {
406        std::cout << argv[0] << ": requires filename argument." << std::endl;
407        return 1;
408    }
409   
410    bool use_zeroconf(false);
411    bool use_sender(false);
412    bool use_receiver(false);
413    if(arguments.find("--zeroconf") > 0) { use_zeroconf = true; }
414    if(arguments.find("--sender") > 0) { use_sender = true; }
415    if(arguments.find("--receiver") > 0) { use_receiver = true; }
416    // construct the viewer.
417    osgViewer::CompositeViewer viewer(arguments);
418   
419    // receiver view
420    if (use_receiver) {
421        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
422        traits->x = 600;
423        traits->y = 100;
424        traits->width = 400;
425        traits->height = 400;
426        traits->windowDecoration = true;
427        traits->doubleBuffer = true;
428        traits->sharedContext = 0;
429        traits->windowName = "Receiver / view two";
430       
431        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
432       
433        osgViewer::View* view = new osgViewer::View;
434        view->setName("View two");
435        viewer.addView(view);
436       
437        osg::Group* group = new osg::Group();
438        group->addChild(scene.get());
439        osg::Geode* geode = new osg::Geode();
440        group->addChild(geode);
441       
442        osgText::Text* text = new osgText::Text();
443        geode->addDrawable( text );
444       
445        text->setFont("Arial.ttf");
446        text->setText("Waiting for data");
447        text->setPosition(osg::Vec3(-50,0,30));
448        text->setAxisAlignment(osgText::TextBase::SCREEN);
449        text->setDataVariance(osg::Object::DYNAMIC);
450        text->setCharacterSize(2.0f);
451        view->setSceneData(group);
452        view->getCamera()->setName("Cam two");
453        view->getCamera()->setViewport(new osg::Viewport(0,0, traits->width, traits->height));
454        view->getCamera()->setGraphicsContext(gc.get());
455
456        view->addEventHandler( new osgViewer::StatsHandler );
457        view->addEventHandler( new UserEventHandler(text) );
458
459        osg::ref_ptr<osgGA::Device> device = osgDB::readFile<osgGA::Device>("0.0.0.0:9000.receiver.osc");
460        if (device.valid() && (device->getCapabilities() & osgGA::Device::RECEIVE_EVENTS))
461        {
462            view->addDevice(device.get());
463           
464            // add a zeroconf device, advertising the osc-device
465            if(use_zeroconf)
466            {
467                osgGA::Device* zeroconf_device = osgDB::readFile<osgGA::Device>("_osc._udp:9000.advertise.zeroconf");
468                if (zeroconf_device)
469                {
470                    view->addDevice(zeroconf_device);
471                }
472            }
473        }
474        else {
475            OSG_WARN << "could not open osc-device, receiving will not work" << std::endl;
476        }
477    }
478
479    // sender view
480    if(use_sender) {
481        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
482        traits->x = 100;
483        traits->y = 100;
484        traits->width = 400;
485        traits->height = 400;
486        traits->windowDecoration = true;
487        traits->doubleBuffer = true;
488        traits->sharedContext = 0;
489        traits->windowName = "Sender / view one";
490       
491        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
492
493       
494        osgViewer::View* view = new osgViewer::View;
495        view->setName("View one");
496        viewer.addView(view);
497       
498        osg::Group* g = new osg::Group();
499        g->addChild(scene.get());
500        g->addChild(createHUD());
501        view->setSceneData(g);
502        view->getCamera()->setName("Cam one");
503        view->getCamera()->setViewport(new osg::Viewport(0,0, traits->width, traits->height));
504        view->getCamera()->setGraphicsContext(gc.get());
505        view->setCameraManipulator(new osgGA::TrackballManipulator);
506
507        // add the state manipulator
508        osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
509        statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet());
510
511        view->addEventHandler( statesetManipulator.get() );
512        view->addEventHandler( new osgViewer::StatsHandler );
513       
514        if (use_zeroconf)
515        {
516            osgGA::Device* zeroconf_device = osgDB::readFile<osgGA::Device>("_osc._udp.discover.zeroconf");
517            if(zeroconf_device) {
518                view->addDevice(zeroconf_device);
519                view->getEventHandlers().push_front(new OscServiceDiscoveredEventHandler());
520               
521            }
522        }
523        else
524        {
525            osg::ref_ptr<osgGA::Device> device = osgDB::readFile<osgGA::Device>("localhost:9000.sender.osc");
526            if (device.valid() && (device->getCapabilities() & osgGA::Device::SEND_EVENTS))
527            {
528                // add as first event handler, so it gets ALL events ...
529                view->getEventHandlers().push_front(new ForwardToDeviceEventHandler(device.get()));
530               
531                // add the demo-pick-event-handler
532                view->addEventHandler(new PickHandler(device.get()));
533            }
534            else {
535                OSG_WARN << "could not open osc-device, sending will not work" << std::endl;
536            }
537        }
538    }
539
540   
541
542
543    while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); }
544    while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullDrawThreadPerContext); }
545    while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullThreadPerCameraDrawThreadPerContext); }
546
547     // run the viewer's main frame loop
548     return viewer.run();
549}
Note: See TracBrowser for help on using the browser.