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