]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Add method canvas::Group::getElementById
[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   void Canvas::setSizeX(int sx)
261   {
262     if( _size_x == sx )
263       return;
264     _size_x = sx;
265
266     // TODO resize if texture already allocated
267
268     if( _size_x <= 0 )
269       setStatusFlags(MISSING_SIZE_X);
270     else
271       setStatusFlags(MISSING_SIZE_X, false);
272
273     // reset flag to allow creation with new size
274     setStatusFlags(CREATE_FAILED, false);
275   }
276
277   //----------------------------------------------------------------------------
278   void Canvas::setSizeY(int sy)
279   {
280     if( _size_y == sy )
281       return;
282     _size_y = sy;
283
284     // TODO resize if texture already allocated
285
286     if( _size_y <= 0 )
287       setStatusFlags(MISSING_SIZE_Y);
288     else
289       setStatusFlags(MISSING_SIZE_Y, false);
290
291     // reset flag to allow creation with new size
292     setStatusFlags(CREATE_FAILED, false);
293   }
294
295   //----------------------------------------------------------------------------
296   int Canvas::getSizeX() const
297   {
298     return _size_x;
299   }
300
301   //----------------------------------------------------------------------------
302   int Canvas::getSizeY() const
303   {
304     return _size_y;
305   }
306
307   //----------------------------------------------------------------------------
308   void Canvas::setViewWidth(int w)
309   {
310     if( _view_width == w )
311       return;
312     _view_width = w;
313
314     _texture.setViewSize(_view_width, _view_height);
315   }
316
317   //----------------------------------------------------------------------------
318   void Canvas::setViewHeight(int h)
319   {
320     if( _view_height == h )
321       return;
322     _view_height = h;
323
324     _texture.setViewSize(_view_width, _view_height);
325   }
326
327   //----------------------------------------------------------------------------
328   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
329   {
330     _mouse_x = event->pos.x();
331     _mouse_y = event->pos.y();
332     _mouse_dx = event->delta.x();
333     _mouse_dy = event->delta.y();
334     _mouse_button = event->button;
335     _mouse_state = event->state;
336     _mouse_mod = event->mod;
337     //_mouse_scroll = event.scroll;
338     // Always set event type last because all listeners are attached to it
339     _mouse_event = event->type;
340
341     if( !_root_group.get() )
342       return false;
343
344     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
345                           event->getPos(),
346                           event->getDelta() );
347     if( !_root_group->accept(visitor) )
348       return false;
349
350     // TODO create special events like click/dblclick etc.
351
352     return visitor.propagateEvent(event);
353   }
354
355   //----------------------------------------------------------------------------
356   void Canvas::childAdded( SGPropertyNode * parent,
357                            SGPropertyNode * child )
358   {
359     if( parent != _node )
360       return;
361
362     if( child->getNameString() == "placement" )
363       _dirty_placements.push_back(child);
364     else if( _root_group.get() )
365       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
366   }
367
368   //----------------------------------------------------------------------------
369   void Canvas::childRemoved( SGPropertyNode * parent,
370                              SGPropertyNode * child )
371   {
372     _render_dirty = true;
373
374     if( parent != _node )
375       return;
376
377     if( child->getNameString() == "placement" )
378       _placements[ child->getIndex() ].clear();
379     else if( _root_group.get() )
380       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
381   }
382
383   //----------------------------------------------------------------------------
384   void Canvas::valueChanged(SGPropertyNode* node)
385   {
386     if(    boost::starts_with(node->getNameString(), "status")
387         || node->getParent()->getNameString() == "bounding-box" )
388       return;
389     _render_dirty = true;
390
391     bool handled = true;
392     if(    node->getParent()->getParent() == _node
393         && node->getParent()->getNameString() == "placement" )
394     {
395       bool placement_dirty = false;
396       BOOST_FOREACH(Placements& placements, _placements)
397       {
398         BOOST_FOREACH(PlacementPtr& placement, placements)
399         {
400           // check if change can be directly handled by placement
401           if(    placement->getProps() == node->getParent()
402               && !placement->childChanged(node) )
403             placement_dirty = true;
404         }
405       }
406
407       if( !placement_dirty )
408         return;
409
410       // prevent double updates...
411       for( size_t i = 0; i < _dirty_placements.size(); ++i )
412       {
413         if( node->getParent() == _dirty_placements[i] )
414           return;
415       }
416
417       _dirty_placements.push_back(node->getParent());
418     }
419     else if( node->getParent() == _node )
420     {
421       if( node->getNameString() == "background" )
422       {
423         osg::Vec4 color;
424         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
425         {
426           _texture.getCamera()->setClearColor(color);
427           _render_dirty = true;
428         }
429       }
430       else if(    node->getNameString() == "mipmapping"
431               || node->getNameString() == "coverage-samples"
432               || node->getNameString() == "color-samples" )
433       {
434         _sampling_dirty = true;
435       }
436       else if( node->getNameString() == "render-always" )
437       {
438         _render_always = node->getBoolValue();
439       }
440       else if( node->getNameString() == "size" )
441       {
442         if( node->getIndex() == 0 )
443           setSizeX( node->getIntValue() );
444         else if( node->getIndex() == 1 )
445           setSizeY( node->getIntValue() );
446       }
447       else if( node->getNameString() == "view" )
448       {
449         if( node->getIndex() == 0 )
450           setViewWidth( node->getIntValue() );
451         else if( node->getIndex() == 1 )
452           setViewHeight( node->getIntValue() );
453       }
454       else if( node->getNameString() == "freeze" )
455         _texture.setRender( node->getBoolValue() );
456       else
457         handled = false;
458     }
459     else
460       handled = false;
461
462     if( !handled && _root_group.get() )
463       _root_group->valueChanged(node);
464   }
465
466   //----------------------------------------------------------------------------
467   osg::Texture2D* Canvas::getTexture() const
468   {
469     return _texture.getTexture();
470   }
471
472   //----------------------------------------------------------------------------
473   Canvas::CullCallbackPtr Canvas::getCullCallback() const
474   {
475     return _cull_callback;
476   }
477
478   //----------------------------------------------------------------------------
479   void Canvas::addPlacementFactory( const std::string& type,
480                                     PlacementFactory factory )
481   {
482     if( _placement_factories.find(type) != _placement_factories.end() )
483       SG_LOG
484       (
485         SG_GENERAL,
486         SG_WARN,
487         "Canvas::addPlacementFactory: replace existing factor for type " << type
488       );
489
490     _placement_factories[type] = factory;
491   }
492
493   //----------------------------------------------------------------------------
494   void Canvas::setSelf(const PropertyBasedElementPtr& self)
495   {
496     PropertyBasedElement::setSelf(self);
497
498     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
499
500     _root_group.reset( new Group(canvas, _node) );
501
502     // Remove automatically created property listener as we forward them on our
503     // own
504     _root_group->removeListener();
505
506     _cull_callback = new CullCallback(canvas);
507   }
508
509   //----------------------------------------------------------------------------
510   void Canvas::setStatusFlags(unsigned int flags, bool set)
511   {
512     if( set )
513       _status = _status | flags;
514     else
515       _status = _status & ~flags;
516     // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
517
518     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
519       _status_msg = "Missing size";
520     else if( _status & MISSING_SIZE_X )
521       _status_msg = "Missing size-x";
522     else if( _status & MISSING_SIZE_Y )
523       _status_msg = "Missing size-y";
524     else if( _status & CREATE_FAILED )
525       _status_msg = "Creating render target failed";
526     else if( _status == STATUS_OK && !_texture.serviceable() )
527       _status_msg = "Creation pending...";
528     else
529       _status_msg = "Ok";
530   }
531
532   //----------------------------------------------------------------------------
533   Canvas::PlacementFactoryMap Canvas::_placement_factories;
534
535 } // namespace canvas
536 } // namespace simgear