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