]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Canvas: More helper functions and cleanup.
[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::setSystemAdapter(const SystemAdapterPtr& system_adapter)
85   {
86     _system_adapter = system_adapter;
87     _texture.setSystemAdapter(system_adapter);
88   }
89
90   //----------------------------------------------------------------------------
91   SystemAdapterPtr Canvas::getSystemAdapter() const
92   {
93     return _system_adapter;
94   }
95
96   //----------------------------------------------------------------------------
97   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
98   {
99     _canvas_mgr = canvas_mgr;
100   }
101
102   //----------------------------------------------------------------------------
103   CanvasMgr* Canvas::getCanvasMgr() const
104   {
105     return _canvas_mgr;
106   }
107
108   //----------------------------------------------------------------------------
109   bool Canvas::isInit() const
110   {
111     return _texture.serviceable();
112   }
113
114   //----------------------------------------------------------------------------
115   void Canvas::destroy()
116   {
117     if( _root_group )
118       _root_group->clearEventListener();
119
120     // TODO check if really not in use anymore
121     getProps()->getParent()
122               ->removeChild( getProps()->getName(),
123                              getProps()->getIndex(),
124                              false );
125   }
126
127   //----------------------------------------------------------------------------
128   void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
129   {
130     if( canvas.expired() )
131     {
132       SG_LOG
133       (
134         SG_GENERAL,
135         SG_WARN,
136         "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
137       );
138       return;
139     }
140
141     _parent_canvases.insert(canvas);
142   }
143
144   //----------------------------------------------------------------------------
145   void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
146   {
147     if( canvas.expired() )
148     {
149       SG_LOG
150       (
151         SG_GENERAL,
152         SG_WARN,
153         "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
154       );
155       return;
156     }
157
158     _child_canvases.insert(canvas);
159   }
160
161   //----------------------------------------------------------------------------
162   void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
163   {
164     _parent_canvases.erase(canvas);
165   }
166
167   //----------------------------------------------------------------------------
168   void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
169   {
170     _child_canvases.erase(canvas);
171   }
172
173   //----------------------------------------------------------------------------
174   GroupPtr Canvas::createGroup(const std::string& name)
175   {
176     return _root_group->createChild<Group>(name);
177   }
178
179   //----------------------------------------------------------------------------
180   GroupPtr Canvas::getGroup(const std::string& name)
181   {
182     return _root_group->getChild<Group>(name);
183   }
184
185   //----------------------------------------------------------------------------
186   GroupPtr Canvas::getOrCreateGroup(const std::string& name)
187   {
188     return _root_group->getOrCreateChild<Group>(name);
189   }
190
191   //----------------------------------------------------------------------------
192   GroupPtr Canvas::getRootGroup()
193   {
194     return _root_group;
195   }
196
197   //----------------------------------------------------------------------------
198   void Canvas::enableRendering(bool force)
199   {
200     _visible = true;
201     if( force )
202       _render_dirty = true;
203   }
204
205   //----------------------------------------------------------------------------
206   void Canvas::update(double delta_time_sec)
207   {
208     if(    (!_texture.serviceable() && _status != STATUS_DIRTY)
209         || (_status & CREATE_FAILED) )
210       return;
211
212     if( _status == STATUS_DIRTY )
213     {
214       _texture.setSize(_size_x, _size_y);
215
216       if( !_texture.serviceable() )
217       {
218         _texture.useImageCoords(true);
219         _texture.useStencil(true);
220         _texture.allocRT(/*_camera_callback*/);
221       }
222       else
223       {
224         // Resizing causes a new texture to be created so we need to reapply all
225         // existing placements
226         reloadPlacements();
227       }
228
229       osg::Camera* camera = _texture.getCamera();
230
231       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
232       parseColor(_node->getStringValue("background"), clear_color);
233       camera->setClearColor(clear_color);
234
235       camera->addChild(_root_group->getMatrixTransform());
236
237       // Ensure objects are drawn in order of traversal
238       camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
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   naRef Canvas::addEventListener(const nasal::CallContext& ctx)
330   {
331     if( !_root_group.get() )
332       naRuntimeError(ctx.c, "Canvas: No root group!");
333
334     return _root_group->addEventListener(ctx);
335   }
336
337   //----------------------------------------------------------------------------
338   void Canvas::setSizeX(int sx)
339   {
340     if( _size_x == sx )
341       return;
342     _size_x = sx;
343     setStatusFlags(STATUS_DIRTY);
344
345     if( _size_x <= 0 )
346       setStatusFlags(MISSING_SIZE_X);
347     else
348       setStatusFlags(MISSING_SIZE_X, false);
349
350     // reset flag to allow creation with new size
351     setStatusFlags(CREATE_FAILED, false);
352   }
353
354   //----------------------------------------------------------------------------
355   void Canvas::setSizeY(int sy)
356   {
357     if( _size_y == sy )
358       return;
359     _size_y = sy;
360     setStatusFlags(STATUS_DIRTY);
361
362     if( _size_y <= 0 )
363       setStatusFlags(MISSING_SIZE_Y);
364     else
365       setStatusFlags(MISSING_SIZE_Y, false);
366
367     // reset flag to allow creation with new size
368     setStatusFlags(CREATE_FAILED, false);
369   }
370
371   //----------------------------------------------------------------------------
372   int Canvas::getSizeX() const
373   {
374     return _size_x;
375   }
376
377   //----------------------------------------------------------------------------
378   int Canvas::getSizeY() const
379   {
380     return _size_y;
381   }
382
383   //----------------------------------------------------------------------------
384   void Canvas::setViewWidth(int w)
385   {
386     if( _view_width == w )
387       return;
388     _view_width = w;
389
390     _texture.setViewSize(_view_width, _view_height);
391   }
392
393   //----------------------------------------------------------------------------
394   void Canvas::setViewHeight(int h)
395   {
396     if( _view_height == h )
397       return;
398     _view_height = h;
399
400     _texture.setViewSize(_view_width, _view_height);
401   }
402
403   //----------------------------------------------------------------------------
404   int Canvas::getViewWidth() const
405   {
406     return _texture.getViewSize().x();
407   }
408
409   //----------------------------------------------------------------------------
410   int Canvas::getViewHeight() const
411   {
412     return _texture.getViewSize().y();
413   }
414
415   //----------------------------------------------------------------------------
416   SGRect<int> Canvas::getViewport() const
417   {
418     return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
419   }
420
421   //----------------------------------------------------------------------------
422   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
423   {
424     if( !_root_group.get() )
425       return false;
426
427     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
428                           event->getClientPos(),
429                           event->getDelta() );
430     if( !_root_group->accept(visitor) )
431       return false;
432
433     return _event_manager->handleEvent(event, visitor.getPropagationPath());
434   }
435
436   //----------------------------------------------------------------------------
437   void Canvas::childAdded( SGPropertyNode * parent,
438                            SGPropertyNode * child )
439   {
440     if( parent != _node )
441       return;
442
443     if( child->getNameString() == "placement" )
444       _dirty_placements.push_back(child);
445     else if( _root_group.get() )
446       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
447   }
448
449   //----------------------------------------------------------------------------
450   void Canvas::childRemoved( SGPropertyNode * parent,
451                              SGPropertyNode * child )
452   {
453     _render_dirty = true;
454
455     if( parent != _node )
456       return;
457
458     if( child->getNameString() == "placement" )
459       _placements[ child->getIndex() ].clear();
460     else if( _root_group.get() )
461       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
462   }
463
464   //----------------------------------------------------------------------------
465   void Canvas::valueChanged(SGPropertyNode* node)
466   {
467     if(    boost::starts_with(node->getNameString(), "status")
468         || node->getParent()->getNameString() == "bounding-box" )
469       return;
470     _render_dirty = true;
471
472     bool handled = true;
473     if(    node->getParent()->getParent() == _node
474         && node->getParent()->getNameString() == "placement" )
475     {
476       bool placement_dirty = false;
477       BOOST_FOREACH(Placements& placements, _placements)
478       {
479         BOOST_FOREACH(PlacementPtr& placement, placements)
480         {
481           // check if change can be directly handled by placement
482           if(    placement->getProps() == node->getParent()
483               && !placement->childChanged(node) )
484             placement_dirty = true;
485         }
486       }
487
488       if( !placement_dirty )
489         return;
490
491       // prevent double updates...
492       for( size_t i = 0; i < _dirty_placements.size(); ++i )
493       {
494         if( node->getParent() == _dirty_placements[i] )
495           return;
496       }
497
498       _dirty_placements.push_back(node->getParent());
499     }
500     else if( node->getParent() == _node )
501     {
502       if( node->getNameString() == "background" )
503       {
504         osg::Vec4 color;
505         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
506         {
507           _texture.getCamera()->setClearColor(color);
508           _render_dirty = true;
509         }
510       }
511       else if(    node->getNameString() == "mipmapping"
512               || node->getNameString() == "coverage-samples"
513               || node->getNameString() == "color-samples" )
514       {
515         _sampling_dirty = true;
516       }
517       else if( node->getNameString() == "additive-blend" )
518       {
519         _texture.useAdditiveBlend( node->getBoolValue() );
520       }
521       else if( node->getNameString() == "render-always" )
522       {
523         _render_always = node->getBoolValue();
524       }
525       else if( node->getNameString() == "size" )
526       {
527         if( node->getIndex() == 0 )
528           setSizeX( node->getIntValue() );
529         else if( node->getIndex() == 1 )
530           setSizeY( node->getIntValue() );
531       }
532       else if( node->getNameString() == "view" )
533       {
534         if( node->getIndex() == 0 )
535           setViewWidth( node->getIntValue() );
536         else if( node->getIndex() == 1 )
537           setViewHeight( node->getIntValue() );
538       }
539       else if( node->getNameString() == "freeze" )
540         _texture.setRender( node->getBoolValue() );
541       else
542         handled = false;
543     }
544     else
545       handled = false;
546
547     if( !handled && _root_group.get() )
548       _root_group->valueChanged(node);
549   }
550
551   //----------------------------------------------------------------------------
552   osg::Texture2D* Canvas::getTexture() const
553   {
554     return _texture.getTexture();
555   }
556
557   //----------------------------------------------------------------------------
558   Canvas::CullCallbackPtr Canvas::getCullCallback() const
559   {
560     return _cull_callback;
561   }
562
563   //----------------------------------------------------------------------------
564   void Canvas::reloadPlacements(const std::string& type)
565   {
566     for(size_t i = 0; i < _placements.size(); ++i)
567     {
568       if( _placements[i].empty() )
569         continue;
570
571       SGPropertyNode* child = _placements[i].front()->getProps();
572       if(    type.empty()
573              // reload if type matches or no type specified
574           || child->getStringValue("type", type.c_str()) == type )
575       {
576         _dirty_placements.push_back(child);
577       }
578     }
579   }
580
581   //----------------------------------------------------------------------------
582   void Canvas::addPlacementFactory( const std::string& type,
583                                     PlacementFactory factory )
584   {
585     if( _placement_factories.find(type) != _placement_factories.end() )
586       SG_LOG
587       (
588         SG_GENERAL,
589         SG_WARN,
590         "Canvas::addPlacementFactory: replace existing factor for type " << type
591       );
592
593     _placement_factories[type] = factory;
594   }
595
596   //----------------------------------------------------------------------------
597   void Canvas::setSelf(const PropertyBasedElementPtr& self)
598   {
599     PropertyBasedElement::setSelf(self);
600
601     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
602
603     _root_group.reset( new Group(canvas, _node) );
604     _root_group->setSelf(_root_group);
605
606     // Remove automatically created property listener as we forward them on our
607     // own
608     _root_group->removeListener();
609
610     _cull_callback = new CullCallback(canvas);
611   }
612
613   //----------------------------------------------------------------------------
614   void Canvas::setStatusFlags(unsigned int flags, bool set)
615   {
616     if( set )
617       _status |= flags;
618     else
619       _status &= ~flags;
620
621     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
622       _status_msg = "Missing size";
623     else if( _status & MISSING_SIZE_X )
624       _status_msg = "Missing size-x";
625     else if( _status & MISSING_SIZE_Y )
626       _status_msg = "Missing size-y";
627     else if( _status & CREATE_FAILED )
628       _status_msg = "Creating render target failed";
629     else if( _status == STATUS_DIRTY )
630       _status_msg = "Creation pending...";
631     else
632       _status_msg = "Ok";
633   }
634
635   //----------------------------------------------------------------------------
636   Canvas::PlacementFactoryMap Canvas::_placement_factories;
637
638 } // namespace canvas
639 } // namespace simgear