]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
First working version of DOM like Canvas event 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 "CanvasEventVisitor.hxx"
21 #include <simgear/canvas/MouseEvent.hxx>
22 #include <simgear/canvas/CanvasPlacement.hxx>
23 #include <simgear/scene/util/parse_color.hxx>
24 #include <simgear/scene/util/RenderConstants.hxx>
25
26 #include <osg/Camera>
27 #include <osg/Geode>
28 #include <osgText/Text>
29 #include <osgViewer/Viewer>
30
31 #include <boost/algorithm/string/predicate.hpp>
32 #include <boost/foreach.hpp>
33 #include <iostream>
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     _size_x(-1),
62     _size_y(-1),
63     _view_width(-1),
64     _view_height(-1),
65     _status(node, "status"),
66     _status_msg(node, "status-msg"),
67     _mouse_x(node, "mouse/x"),
68     _mouse_y(node, "mouse/y"),
69     _mouse_dx(node, "mouse/dx"),
70     _mouse_dy(node, "mouse/dy"),
71     _mouse_button(node, "mouse/button"),
72     _mouse_state(node, "mouse/state"),
73     _mouse_mod(node, "mouse/mod"),
74     _mouse_scroll(node, "mouse/scroll"),
75     _mouse_event(node, "mouse/event"),
76     _sampling_dirty(false),
77     _render_dirty(true),
78     _visible(true),
79     _render_always(false)
80   {
81     _status = 0;
82     setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
83   }
84
85   //----------------------------------------------------------------------------
86   Canvas::~Canvas()
87   {
88
89   }
90
91   //----------------------------------------------------------------------------
92   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
93   {
94     _system_adapter = system_adapter;
95     _texture.setSystemAdapter(system_adapter);
96   }
97
98   //----------------------------------------------------------------------------
99   SystemAdapterPtr Canvas::getSystemAdapter() const
100   {
101     return _system_adapter;
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   void Canvas::addDependentCanvas(const CanvasWeakPtr& canvas)
118   {
119     if( canvas.expired() )
120     {
121       SG_LOG
122       (
123         SG_GENERAL,
124         SG_WARN,
125         "Canvas::addDependentCanvas: got an expired Canvas dependent on "
126         << _node->getPath()
127       );
128       return;
129     }
130
131     _dependent_canvases.insert(canvas);
132   }
133
134   //----------------------------------------------------------------------------
135   void Canvas::removeDependentCanvas(const CanvasWeakPtr& canvas)
136   {
137     _dependent_canvases.erase(canvas);
138   }
139
140   //----------------------------------------------------------------------------
141   GroupPtr Canvas::createGroup(const std::string& name)
142   {
143     return boost::dynamic_pointer_cast<Group>
144     (
145       _root_group->createChild("group", name)
146     );
147   }
148
149   //----------------------------------------------------------------------------
150   void Canvas::enableRendering(bool force)
151   {
152     _visible = true;
153     if( force )
154       _render_dirty = true;
155   }
156
157   //----------------------------------------------------------------------------
158   void Canvas::update(double delta_time_sec)
159   {
160     if( !_texture.serviceable() )
161     {
162       if( _status != STATUS_OK )
163         return;
164
165       _texture.setSize(_size_x, _size_y);
166       _texture.useImageCoords(true);
167       _texture.useStencil(true);
168       _texture.allocRT(/*_camera_callback*/);
169
170       osg::Camera* camera = _texture.getCamera();
171
172       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
173       parseColor(_node->getStringValue("background"), clear_color);
174       camera->setClearColor(clear_color);
175
176       camera->addChild(_root_group->getMatrixTransform());
177
178       // Ensure objects are drawn in order of traversal
179       camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
180
181       if( _texture.serviceable() )
182       {
183         setStatusFlags(STATUS_OK);
184       }
185       else
186       {
187         setStatusFlags(CREATE_FAILED);
188         return;
189       }
190     }
191
192     if( _visible || _render_always )
193     {
194       if( _render_dirty )
195       {
196         // Also mark all dependent (eg. recursively used) canvases as dirty
197         BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
198         {
199           if( !canvas.expired() )
200             canvas.lock()->_render_dirty = true;
201         }
202       }
203
204       _texture.setRender(_render_dirty);
205
206       _render_dirty = false;
207       _visible = false;
208     }
209     else
210       _texture.setRender(false);
211
212     _root_group->update(delta_time_sec);
213
214     if( _sampling_dirty )
215     {
216       _texture.setSampling(
217         _node->getBoolValue("mipmapping"),
218         _node->getIntValue("coverage-samples"),
219         _node->getIntValue("color-samples")
220       );
221       _sampling_dirty = false;
222       _render_dirty = true;
223     }
224
225     while( !_dirty_placements.empty() )
226     {
227       SGPropertyNode *node = _dirty_placements.back();
228       _dirty_placements.pop_back();
229
230       if( node->getIndex() >= static_cast<int>(_placements.size()) )
231         // New placement
232         _placements.resize(node->getIndex() + 1);
233       else
234         // Remove possibly existing placements
235         _placements[ node->getIndex() ].clear();
236
237       // Get new placements
238       PlacementFactoryMap::const_iterator placement_factory =
239         _placement_factories.find( node->getStringValue("type", "object") );
240       if( placement_factory != _placement_factories.end() )
241       {
242         Placements& placements = _placements[ node->getIndex() ] =
243           placement_factory->second
244           (
245             node,
246             boost::static_pointer_cast<Canvas>(_self.lock())
247           );
248         node->setStringValue
249         (
250           "status-msg",
251           placements.empty() ? "No match" : "Ok"
252         );
253       }
254       else
255         node->setStringValue("status-msg", "Unknown placement type");
256     }
257   }
258
259   //----------------------------------------------------------------------------
260   naRef Canvas::addEventListener(const nasal::CallContext& ctx)
261   {
262     if( !_root_group.get() )
263       naRuntimeError(ctx.c, "Canvas: No root group!");
264
265     return _root_group->addEventListener(ctx);
266   }
267
268   //----------------------------------------------------------------------------
269   void Canvas::setSizeX(int sx)
270   {
271     if( _size_x == sx )
272       return;
273     _size_x = sx;
274
275     // TODO resize if texture already allocated
276
277     if( _size_x <= 0 )
278       setStatusFlags(MISSING_SIZE_X);
279     else
280       setStatusFlags(MISSING_SIZE_X, false);
281
282     // reset flag to allow creation with new size
283     setStatusFlags(CREATE_FAILED, false);
284   }
285
286   //----------------------------------------------------------------------------
287   void Canvas::setSizeY(int sy)
288   {
289     if( _size_y == sy )
290       return;
291     _size_y = sy;
292
293     // TODO resize if texture already allocated
294
295     if( _size_y <= 0 )
296       setStatusFlags(MISSING_SIZE_Y);
297     else
298       setStatusFlags(MISSING_SIZE_Y, false);
299
300     // reset flag to allow creation with new size
301     setStatusFlags(CREATE_FAILED, false);
302   }
303
304   //----------------------------------------------------------------------------
305   int Canvas::getSizeX() const
306   {
307     return _size_x;
308   }
309
310   //----------------------------------------------------------------------------
311   int Canvas::getSizeY() const
312   {
313     return _size_y;
314   }
315
316   //----------------------------------------------------------------------------
317   void Canvas::setViewWidth(int w)
318   {
319     if( _view_width == w )
320       return;
321     _view_width = w;
322
323     _texture.setViewSize(_view_width, _view_height);
324   }
325
326   //----------------------------------------------------------------------------
327   void Canvas::setViewHeight(int h)
328   {
329     if( _view_height == h )
330       return;
331     _view_height = h;
332
333     _texture.setViewSize(_view_width, _view_height);
334   }
335
336   //----------------------------------------------------------------------------
337   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
338   {
339     _mouse_x = event->pos.x();
340     _mouse_y = event->pos.y();
341     _mouse_dx = event->delta.x();
342     _mouse_dy = event->delta.y();
343     _mouse_button = event->button;
344     _mouse_state = event->state;
345     _mouse_mod = event->mod;
346     //_mouse_scroll = event.scroll;
347     // Always set event type last because all listeners are attached to it
348     _mouse_event = event->type;
349
350     if( !_root_group.get() )
351       return false;
352
353     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
354                           event->getPos(),
355                           event->getDelta() );
356     if( !_root_group->accept(visitor) )
357       return false;
358
359     // TODO create special events like click/dblclick etc.
360
361     return visitor.propagateEvent(event);
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
511     // Remove automatically created property listener as we forward them on our
512     // own
513     _root_group->removeListener();
514
515     _cull_callback = new CullCallback(canvas);
516   }
517
518   //----------------------------------------------------------------------------
519   void Canvas::setStatusFlags(unsigned int flags, bool set)
520   {
521     if( set )
522       _status = _status | flags;
523     else
524       _status = _status & ~flags;
525     // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
526
527     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
528       _status_msg = "Missing size";
529     else if( _status & MISSING_SIZE_X )
530       _status_msg = "Missing size-x";
531     else if( _status & MISSING_SIZE_Y )
532       _status_msg = "Missing size-y";
533     else if( _status & CREATE_FAILED )
534       _status_msg = "Creating render target failed";
535     else if( _status == STATUS_OK && !_texture.serviceable() )
536       _status_msg = "Creation pending...";
537     else
538       _status_msg = "Ok";
539   }
540
541   //----------------------------------------------------------------------------
542   Canvas::PlacementFactoryMap Canvas::_placement_factories;
543
544 } // namespace canvas
545 } // namespace simgear