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

Revision 13331, 20.8 kB (checked in by robert, 5 days ago)

Added shaders to support experimental shader based displacement mapping technique osgTerrain::ShaderTerrain?.

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