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