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