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