]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Add simple keyboard event demo application.
[simgear.git] / simgear / canvas / Canvas.cxx
1 // The canvas for rendering with the 2d API
2 //
3 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
18
19 #include "Canvas.hxx"
20 #include "CanvasEventManager.hxx"
21 #include "CanvasEventVisitor.hxx"
22 #include "CanvasPlacement.hxx"
23 #include <simgear/canvas/events/KeyboardEvent.hxx>
24 #include <simgear/canvas/events/MouseEvent.hxx>
25 #include <simgear/scene/util/parse_color.hxx>
26 #include <simgear/scene/util/RenderConstants.hxx>
27
28 #include <osg/Camera>
29 #include <osg/Geode>
30 #include <osgText/Text>
31 #include <osgViewer/Viewer>
32
33 #include <boost/algorithm/string/predicate.hpp>
34 #include <boost/foreach.hpp>
35
36 namespace simgear
37 {
38 namespace canvas
39 {
40
41   //----------------------------------------------------------------------------
42   Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
43     _canvas( canvas )
44   {
45
46   }
47
48   //----------------------------------------------------------------------------
49   void Canvas::CullCallback::operator()( osg::Node* node,
50                                          osg::NodeVisitor* nv )
51   {
52     if( (nv->getTraversalMask() & simgear::MODEL_BIT) )
53     {
54       CanvasPtr canvas = _canvas.lock();
55       if( canvas )
56         canvas->enableRendering();
57     }
58
59     traverse(node, nv);
60   }
61
62   //----------------------------------------------------------------------------
63   Canvas::Canvas(SGPropertyNode* node):
64     PropertyBasedElement(node),
65     _canvas_mgr(0),
66     _event_manager(new EventManager),
67     _size_x(-1),
68     _size_y(-1),
69     _view_width(-1),
70     _view_height(-1),
71     _status(node, "status"),
72     _status_msg(node, "status-msg"),
73     _sampling_dirty(false),
74     _render_dirty(true),
75     _visible(true),
76     _render_always(false)
77   {
78     _status = 0;
79     setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
80
81     _root_group.reset( new Group(this, _node) );
82
83     // Remove automatically created property listener as we forward them on our
84     // own
85     _root_group->removeListener();
86     _cull_callback = new CullCallback(this);
87   }
88
89   //----------------------------------------------------------------------------
90   Canvas::~Canvas()
91   {
92
93   }
94
95   //----------------------------------------------------------------------------
96   void Canvas::onDestroy()
97   {
98     if( _root_group )
99     {
100       _root_group->clearEventListener();
101       _root_group->onDestroy();
102     }
103   }
104
105   //----------------------------------------------------------------------------
106   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
107   {
108     _canvas_mgr = canvas_mgr;
109   }
110
111   //----------------------------------------------------------------------------
112   CanvasMgr* Canvas::getCanvasMgr() const
113   {
114     return _canvas_mgr;
115   }
116
117   //----------------------------------------------------------------------------
118   bool Canvas::isInit() const
119   {
120     return _texture.serviceable();
121   }
122
123   //----------------------------------------------------------------------------
124   void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
125   {
126     if( canvas.expired() )
127     {
128       SG_LOG
129       (
130         SG_GENERAL,
131         SG_WARN,
132         "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
133         "got an expired parent!"
134       );
135       return;
136     }
137
138     _parent_canvases.insert(canvas);
139   }
140
141   //----------------------------------------------------------------------------
142   void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
143   {
144     if( canvas.expired() )
145     {
146       SG_LOG
147       (
148         SG_GENERAL,
149         SG_WARN,
150         "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
151         " got an expired child!"
152       );
153       return;
154     }
155
156     _child_canvases.insert(canvas);
157   }
158
159   //----------------------------------------------------------------------------
160   void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
161   {
162     _parent_canvases.erase(canvas);
163   }
164
165   //----------------------------------------------------------------------------
166   void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
167   {
168     _child_canvases.erase(canvas);
169   }
170
171   //----------------------------------------------------------------------------
172   GroupPtr Canvas::createGroup(const std::string& name)
173   {
174     return _root_group->createChild<Group>(name);
175   }
176
177   //----------------------------------------------------------------------------
178   GroupPtr Canvas::getGroup(const std::string& name)
179   {
180     return _root_group->getChild<Group>(name);
181   }
182
183   //----------------------------------------------------------------------------
184   GroupPtr Canvas::getOrCreateGroup(const std::string& name)
185   {
186     return _root_group->getOrCreateChild<Group>(name);
187   }
188
189   //----------------------------------------------------------------------------
190   GroupPtr Canvas::getRootGroup()
191   {
192     return _root_group;
193   }
194
195   //----------------------------------------------------------------------------
196   void Canvas::setLayout(const LayoutRef& layout)
197   {
198     _layout = layout;
199     _layout->setCanvas(this);
200   }
201
202   //----------------------------------------------------------------------------
203   void Canvas::setFocusElement(const ElementPtr& el)
204   {
205     if( el && el->getCanvas().lock() != this )
206     {
207       SG_LOG(SG_GUI, SG_WARN, "setFocusElement: element not from this canvas");
208       return;
209     }
210
211     // TODO focus out/in events
212     _focus_element = el;
213   }
214
215   //----------------------------------------------------------------------------
216   void Canvas::enableRendering(bool force)
217   {
218     _visible = true;
219     if( force )
220       _render_dirty = true;
221   }
222
223   //----------------------------------------------------------------------------
224   void Canvas::update(double delta_time_sec)
225   {
226     if( _status & (CREATE_FAILED | MISSING_SIZE) )
227       return;
228
229     if( _status & STATUS_DIRTY )
230     {
231       _texture.setSize(_size_x, _size_y);
232
233       if( !_texture.serviceable() )
234       {
235         _texture.useImageCoords(true);
236         _texture.useStencil(true);
237         _texture.allocRT(/*_camera_callback*/);
238       }
239       else
240       {
241         // Resizing causes a new texture to be created so we need to reapply all
242         // existing placements
243         reloadPlacements();
244       }
245
246       osg::Camera* camera = _texture.getCamera();
247
248       // TODO Allow custom render order? For now just keep in order with
249       //      property tree.
250       camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
251
252       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
253       parseColor(_node->getStringValue("background"), clear_color);
254       camera->setClearColor(clear_color);
255
256       camera->addChild(_root_group->getMatrixTransform());
257
258       if( _texture.serviceable() )
259       {
260         setStatusFlags(STATUS_OK);
261         setStatusFlags(STATUS_DIRTY, false);
262         _render_dirty = true;
263       }
264       else
265       {
266         setStatusFlags(CREATE_FAILED);
267         return;
268       }
269     }
270
271     if( _layout )
272       _layout->setGeometry(SGRecti(0, 0, _view_width, _view_height));
273
274     if( _visible || _render_always )
275     {
276       BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
277       {
278         // TODO should we check if the image the child canvas is displayed
279         //      within is really visible?
280         CanvasPtr canvas = canvas_weak.lock();
281         if( canvas )
282           canvas->_visible = true;
283       }
284
285       if( _render_dirty )
286       {
287         // Also mark all canvases this canvas is displayed within as dirty
288         BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
289         {
290           CanvasPtr canvas = canvas_weak.lock();
291           if( canvas )
292             canvas->_render_dirty = true;
293         }
294       }
295
296       _texture.setRender(_render_dirty);
297
298       _render_dirty = false;
299       _visible = false;
300     }
301     else
302       _texture.setRender(false);
303
304     _root_group->update(delta_time_sec);
305
306     if( _sampling_dirty )
307     {
308       _texture.setSampling(
309         _node->getBoolValue("mipmapping"),
310         _node->getIntValue("coverage-samples"),
311         _node->getIntValue("color-samples")
312       );
313       _sampling_dirty = false;
314       _render_dirty = true;
315     }
316
317     while( !_dirty_placements.empty() )
318     {
319       SGPropertyNode *node = _dirty_placements.back();
320       _dirty_placements.pop_back();
321
322       if( node->getIndex() >= static_cast<int>(_placements.size()) )
323         // New placement
324         _placements.resize(node->getIndex() + 1);
325       else
326         // Remove possibly existing placements
327         _placements[ node->getIndex() ].clear();
328
329       // Get new placements
330       PlacementFactoryMap::const_iterator placement_factory =
331         _placement_factories.find( node->getStringValue("type", "object") );
332       if( placement_factory != _placement_factories.end() )
333       {
334         Placements& placements = _placements[ node->getIndex() ] =
335           placement_factory->second(node, this);
336         node->setStringValue
337         (
338           "status-msg",
339           placements.empty() ? "No match" : "Ok"
340         );
341       }
342       else
343         node->setStringValue("status-msg", "Unknown placement type");
344     }
345   }
346
347   //----------------------------------------------------------------------------
348   bool Canvas::addEventListener( const std::string& type,
349                                  const EventListener& cb )
350   {
351     if( !_root_group.get() )
352       throw std::runtime_error("Canvas::addEventListener: no root group!");
353
354     return _root_group->addEventListener(type, cb);
355   }
356
357   //----------------------------------------------------------------------------
358   bool Canvas::dispatchEvent(const EventPtr& event)
359   {
360     if( !_root_group.get() )
361       throw std::runtime_error("Canvas::dispatchEvent: no root group!");
362
363     return _root_group->dispatchEvent(event);
364   }
365
366   //----------------------------------------------------------------------------
367   void Canvas::setSizeX(int sx)
368   {
369     if( _size_x == sx )
370       return;
371     _size_x = sx;
372     setStatusFlags(STATUS_DIRTY);
373
374     if( _size_x <= 0 )
375       setStatusFlags(MISSING_SIZE_X);
376     else
377       setStatusFlags(MISSING_SIZE_X, false);
378
379     // reset flag to allow creation with new size
380     setStatusFlags(CREATE_FAILED, false);
381   }
382
383   //----------------------------------------------------------------------------
384   void Canvas::setSizeY(int sy)
385   {
386     if( _size_y == sy )
387       return;
388     _size_y = sy;
389     setStatusFlags(STATUS_DIRTY);
390
391     if( _size_y <= 0 )
392       setStatusFlags(MISSING_SIZE_Y);
393     else
394       setStatusFlags(MISSING_SIZE_Y, false);
395
396     // reset flag to allow creation with new size
397     setStatusFlags(CREATE_FAILED, false);
398   }
399
400   //----------------------------------------------------------------------------
401   int Canvas::getSizeX() const
402   {
403     return _size_x;
404   }
405
406   //----------------------------------------------------------------------------
407   int Canvas::getSizeY() const
408   {
409     return _size_y;
410   }
411
412   //----------------------------------------------------------------------------
413   void Canvas::setViewWidth(int w)
414   {
415     if( _view_width == w )
416       return;
417     _view_width = w;
418
419     _texture.setViewSize(_view_width, _view_height);
420   }
421
422   //----------------------------------------------------------------------------
423   void Canvas::setViewHeight(int h)
424   {
425     if( _view_height == h )
426       return;
427     _view_height = h;
428
429     _texture.setViewSize(_view_width, _view_height);
430   }
431
432   //----------------------------------------------------------------------------
433   int Canvas::getViewWidth() const
434   {
435     return _texture.getViewSize().x();
436   }
437
438   //----------------------------------------------------------------------------
439   int Canvas::getViewHeight() const
440   {
441     return _texture.getViewSize().y();
442   }
443
444   //----------------------------------------------------------------------------
445   SGRect<int> Canvas::getViewport() const
446   {
447     return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
448   }
449
450   //----------------------------------------------------------------------------
451   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
452   {
453     if( !_root_group )
454       return false;
455
456     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
457                           event->getClientPos(),
458                           _root_group );
459     if( !_root_group->accept(visitor) )
460       return false;
461
462     return _event_manager->handleEvent(event, visitor.getPropagationPath());
463   }
464
465   //----------------------------------------------------------------------------
466   bool Canvas::handleKeyboardEvent(const KeyboardEventPtr& event)
467   {
468     ElementPtr target = _focus_element.lock();
469     if( !target )
470       target = _root_group;
471     if( !target )
472       return false;
473
474     return target->dispatchEvent(event);
475   }
476
477   //----------------------------------------------------------------------------
478   bool Canvas::propagateEvent( EventPtr const& event,
479                                EventPropagationPath const& path )
480   {
481     return _event_manager->propagateEvent(event, path);
482   }
483
484   //----------------------------------------------------------------------------
485   void Canvas::childAdded( SGPropertyNode * parent,
486                            SGPropertyNode * child )
487   {
488     if( parent != _node )
489       return;
490
491     if( child->getNameString() == "placement" )
492       _dirty_placements.push_back(child);
493     else if( _root_group.get() )
494       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
495   }
496
497   //----------------------------------------------------------------------------
498   void Canvas::childRemoved( SGPropertyNode * parent,
499                              SGPropertyNode * child )
500   {
501     _render_dirty = true;
502
503     if( parent != _node )
504       return;
505
506     if( child->getNameString() == "placement" )
507       _placements[ child->getIndex() ].clear();
508     else if( _root_group.get() )
509       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
510   }
511
512   //----------------------------------------------------------------------------
513   void Canvas::valueChanged(SGPropertyNode* node)
514   {
515     const std::string& name = node->getNameString();
516
517     if(    boost::starts_with(name, "status")
518         || boost::starts_with(name, "data-") )
519       return;
520     _render_dirty = true;
521
522     bool handled = true;
523     if(    node->getParent()->getParent() == _node
524         && node->getParent()->getNameString() == "placement" )
525     {
526       size_t index = node->getIndex();
527       if( index < _placements.size() )
528       {
529         Placements& placements = _placements[index];
530         if( !placements.empty() )
531         {
532           bool placement_dirty = false;
533           BOOST_FOREACH(PlacementPtr& placement, placements)
534           {
535             // check if change can be directly handled by placement
536             if(    placement->getProps() == node->getParent()
537                 && !placement->childChanged(node) )
538               placement_dirty = true;
539           }
540
541           if( !placement_dirty )
542             return;
543         }
544       }
545
546       // prevent double updates...
547       for( size_t i = 0; i < _dirty_placements.size(); ++i )
548       {
549         if( node->getParent() == _dirty_placements[i] )
550           return;
551       }
552
553       _dirty_placements.push_back(node->getParent());
554     }
555     else if( node->getParent() == _node )
556     {
557       if( name == "background" )
558       {
559         osg::Vec4 color;
560         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
561         {
562           _texture.getCamera()->setClearColor(color);
563           _render_dirty = true;
564         }
565       }
566       else if(   name == "mipmapping"
567               || name == "coverage-samples"
568               || name == "color-samples" )
569       {
570         _sampling_dirty = true;
571       }
572       else if( name == "additive-blend" )
573       {
574         _texture.useAdditiveBlend( node->getBoolValue() );
575       }
576       else if( name == "render-always" )
577       {
578         _render_always = node->getBoolValue();
579       }
580       else if( name == "size" )
581       {
582         if( node->getIndex() == 0 )
583           setSizeX( node->getIntValue() );
584         else if( node->getIndex() == 1 )
585           setSizeY( node->getIntValue() );
586       }
587       else if( name == "update" )
588       {
589         if( _root_group )
590           _root_group->update(0);
591         return update(0);
592       }
593       else if( name == "view" )
594       {
595         if( node->getIndex() == 0 )
596           setViewWidth( node->getIntValue() );
597         else if( node->getIndex() == 1 )
598           setViewHeight( node->getIntValue() );
599       }
600       else if( name == "freeze" )
601         _texture.setRender( node->getBoolValue() );
602       else
603         handled = false;
604     }
605     else
606       handled = false;
607
608     if( !handled && _root_group.get() )
609       _root_group->valueChanged(node);
610   }
611
612   //----------------------------------------------------------------------------
613   osg::Texture2D* Canvas::getTexture() const
614   {
615     return _texture.getTexture();
616   }
617
618   //----------------------------------------------------------------------------
619   Canvas::CullCallbackPtr Canvas::getCullCallback() const
620   {
621     return _cull_callback;
622   }
623
624   //----------------------------------------------------------------------------
625   void Canvas::reloadPlacements(const std::string& type)
626   {
627     for(size_t i = 0; i < _placements.size(); ++i)
628     {
629       if( _placements[i].empty() )
630         continue;
631
632       SGPropertyNode* child = _placements[i].front()->getProps();
633       if(    type.empty()
634              // reload if type matches or no type specified
635           || child->getStringValue("type", type.c_str()) == type )
636       {
637         _dirty_placements.push_back(child);
638       }
639     }
640   }
641
642   //----------------------------------------------------------------------------
643   void Canvas::addPlacementFactory( const std::string& type,
644                                     PlacementFactory factory )
645   {
646     if( _placement_factories.find(type) != _placement_factories.end() )
647       SG_LOG
648       (
649         SG_GENERAL,
650         SG_WARN,
651         "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
652       );
653
654     _placement_factories[type] = factory;
655   }
656
657   //----------------------------------------------------------------------------
658   void Canvas::removePlacementFactory(const std::string& type)
659   {
660     PlacementFactoryMap::iterator it = _placement_factories.find(type);
661     if( it == _placement_factories.end() )
662       SG_LOG
663       (
664         SG_GENERAL,
665         SG_WARN,
666         "Canvas::removePlacementFactory: no such factory '" << type << "'"
667       );
668     else
669       _placement_factories.erase(it);
670   }
671
672
673   //----------------------------------------------------------------------------
674   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
675   {
676     _system_adapter = system_adapter;
677   }
678
679   //----------------------------------------------------------------------------
680   SystemAdapterPtr Canvas::getSystemAdapter()
681   {
682     return _system_adapter;
683   }
684
685   //----------------------------------------------------------------------------
686   void Canvas::setStatusFlags(unsigned int flags, bool set)
687   {
688     if( set )
689       _status |= flags;
690     else
691       _status &= ~flags;
692
693     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
694       _status_msg = "Missing size";
695     else if( _status & MISSING_SIZE_X )
696       _status_msg = "Missing size-x";
697     else if( _status & MISSING_SIZE_Y )
698       _status_msg = "Missing size-y";
699     else if( _status & CREATE_FAILED )
700       _status_msg = "Creating render target failed";
701     else if( _status & STATUS_DIRTY )
702       _status_msg = "Creation pending...";
703     else
704       _status_msg = "Ok";
705   }
706
707   //----------------------------------------------------------------------------
708   Canvas::PlacementFactoryMap Canvas::_placement_factories;
709   SystemAdapterPtr Canvas::_system_adapter;
710
711 } // namespace canvas
712 } // namespace simgear