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