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