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