]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Include ShivaVG into libSimGearScene
[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 <simgear/canvas/MouseEvent.hxx>
21 #include <simgear/misc/parse_color.hxx>
22 #include <simgear/scene/util/RenderConstants.hxx>
23
24 #include <osg/Camera>
25 #include <osg/Geode>
26 #include <osgText/Text>
27 #include <osgViewer/Viewer>
28
29 #include <boost/algorithm/string/predicate.hpp>
30 #include <boost/foreach.hpp>
31 #include <iostream>
32
33 namespace simgear
34 {
35 namespace canvas
36 {
37
38   //----------------------------------------------------------------------------
39   Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
40     _canvas( canvas )
41   {
42
43   }
44
45   //----------------------------------------------------------------------------
46   void Canvas::CullCallback::operator()( osg::Node* node,
47                                          osg::NodeVisitor* nv )
48   {
49     if( (nv->getTraversalMask() & simgear::MODEL_BIT) && !_canvas.expired() )
50       _canvas.lock()->enableRendering();
51
52     traverse(node, nv);
53   }
54
55   //----------------------------------------------------------------------------
56   Canvas::Canvas(SGPropertyNode* node):
57     PropertyBasedElement(node),
58     _canvas_mgr(0),
59     _size_x(-1),
60     _size_y(-1),
61     _view_width(-1),
62     _view_height(-1),
63     _status(node, "status"),
64     _status_msg(node, "status-msg"),
65     _mouse_x(node, "mouse/x"),
66     _mouse_y(node, "mouse/y"),
67     _mouse_dx(node, "mouse/dx"),
68     _mouse_dy(node, "mouse/dy"),
69     _mouse_button(node, "mouse/button"),
70     _mouse_state(node, "mouse/state"),
71     _mouse_mod(node, "mouse/mod"),
72     _mouse_scroll(node, "mouse/scroll"),
73     _mouse_event(node, "mouse/event"),
74     _sampling_dirty(false),
75     _render_dirty(true),
76     _visible(true),
77     _render_always(false)
78   {
79     _status = 0;
80     setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
81   }
82
83   //----------------------------------------------------------------------------
84   Canvas::~Canvas()
85   {
86
87   }
88
89   //----------------------------------------------------------------------------
90   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
91   {
92     _system_adapter = system_adapter;
93     _texture.setSystemAdapter(system_adapter);
94   }
95
96   //----------------------------------------------------------------------------
97   SystemAdapterPtr Canvas::getSystemAdapter() const
98   {
99     return _system_adapter;
100   }
101
102   //----------------------------------------------------------------------------
103   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
104   {
105     _canvas_mgr = canvas_mgr;
106   }
107
108   //----------------------------------------------------------------------------
109   CanvasMgr* Canvas::getCanvasMgr() const
110   {
111     return _canvas_mgr;
112   }
113
114   //----------------------------------------------------------------------------
115   void Canvas::addDependentCanvas(const CanvasWeakPtr& canvas)
116   {
117     if( canvas.expired() )
118     {
119       SG_LOG
120       (
121         SG_GENERAL,
122         SG_WARN,
123         "Canvas::addDependentCanvas: got an expired Canvas dependent on "
124         << _node->getPath()
125       );
126       return;
127     }
128
129     _dependent_canvases.insert(canvas);
130   }
131
132   //----------------------------------------------------------------------------
133   void Canvas::removeDependentCanvas(const CanvasWeakPtr& canvas)
134   {
135     _dependent_canvases.erase(canvas);
136   }
137
138   //----------------------------------------------------------------------------
139   void Canvas::enableRendering(bool force)
140   {
141     _visible = true;
142     if( force )
143       _render_dirty = true;
144   }
145
146   //----------------------------------------------------------------------------
147   void Canvas::update(double delta_time_sec)
148   {
149     if( !_texture.serviceable() )
150     {
151       if( _status != STATUS_OK )
152         return;
153
154       _texture.setSize(_size_x, _size_y);
155       _texture.useImageCoords(true);
156       _texture.useStencil(true);
157       _texture.allocRT(/*_camera_callback*/);
158
159       osg::Camera* camera = _texture.getCamera();
160
161       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
162       parseColor(_node->getStringValue("background"), clear_color);
163       camera->setClearColor(clear_color);
164
165       camera->addChild(_root_group->getMatrixTransform());
166
167       // Ensure objects are drawn in order of traversal
168       camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
169
170       if( _texture.serviceable() )
171       {
172         setStatusFlags(STATUS_OK);
173       }
174       else
175       {
176         setStatusFlags(CREATE_FAILED);
177         return;
178       }
179     }
180
181     if( _visible || _render_always )
182     {
183       if( _render_dirty )
184       {
185         // Also mark all dependent (eg. recursively used) canvases as dirty
186         BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
187         {
188           if( !canvas.expired() )
189             canvas.lock()->_render_dirty = true;
190         }
191       }
192
193       _texture.setRender(_render_dirty);
194
195       _render_dirty = false;
196       _visible = false;
197     }
198     else
199       _texture.setRender(false);
200
201     _root_group->update(delta_time_sec);
202
203     if( _sampling_dirty )
204     {
205       _texture.setSampling(
206         _node->getBoolValue("mipmapping"),
207         _node->getIntValue("coverage-samples"),
208         _node->getIntValue("color-samples")
209       );
210       _sampling_dirty = false;
211       _render_dirty = true;
212     }
213
214     while( !_dirty_placements.empty() )
215     {
216       SGPropertyNode *node = _dirty_placements.back();
217       _dirty_placements.pop_back();
218
219       if( node->getIndex() >= static_cast<int>(_placements.size()) )
220         // New placement
221         _placements.resize(node->getIndex() + 1);
222       else
223         // Remove possibly existing placements
224         _placements[ node->getIndex() ].clear();
225
226       // Get new placements
227       PlacementFactoryMap::const_iterator placement_factory =
228         _placement_factories.find( node->getStringValue("type", "object") );
229       if( placement_factory != _placement_factories.end() )
230       {
231         Placements& placements = _placements[ node->getIndex() ] =
232           placement_factory->second
233           (
234             node,
235             boost::static_pointer_cast<Canvas>(_self.lock())
236           );
237         node->setStringValue
238         (
239           "status-msg",
240           placements.empty() ? "No match" : "Ok"
241         );
242       }
243       else
244         node->setStringValue("status-msg", "Unknown placement type");
245     }
246   }
247
248   //----------------------------------------------------------------------------
249   void Canvas::setSizeX(int sx)
250   {
251     if( _size_x == sx )
252       return;
253     _size_x = sx;
254
255     // TODO resize if texture already allocated
256
257     if( _size_x <= 0 )
258       setStatusFlags(MISSING_SIZE_X);
259     else
260       setStatusFlags(MISSING_SIZE_X, false);
261
262     // reset flag to allow creation with new size
263     setStatusFlags(CREATE_FAILED, false);
264   }
265
266   //----------------------------------------------------------------------------
267   void Canvas::setSizeY(int sy)
268   {
269     if( _size_y == sy )
270       return;
271     _size_y = sy;
272
273     // TODO resize if texture already allocated
274
275     if( _size_y <= 0 )
276       setStatusFlags(MISSING_SIZE_Y);
277     else
278       setStatusFlags(MISSING_SIZE_Y, false);
279
280     // reset flag to allow creation with new size
281     setStatusFlags(CREATE_FAILED, false);
282   }
283
284   //----------------------------------------------------------------------------
285   int Canvas::getSizeX() const
286   {
287     return _size_x;
288   }
289
290   //----------------------------------------------------------------------------
291   int Canvas::getSizeY() const
292   {
293     return _size_y;
294   }
295
296   //----------------------------------------------------------------------------
297   void Canvas::setViewWidth(int w)
298   {
299     if( _view_width == w )
300       return;
301     _view_width = w;
302
303     _texture.setViewSize(_view_width, _view_height);
304   }
305
306   //----------------------------------------------------------------------------
307   void Canvas::setViewHeight(int h)
308   {
309     if( _view_height == h )
310       return;
311     _view_height = h;
312
313     _texture.setViewSize(_view_width, _view_height);
314   }
315
316   //----------------------------------------------------------------------------
317   bool Canvas::handleMouseEvent(const MouseEvent& event)
318   {
319     _mouse_x = event.x;
320     _mouse_y = event.y;
321     _mouse_dx = event.dx;
322     _mouse_dy = event.dy;
323     _mouse_button = event.button;
324     _mouse_state = event.state;
325     _mouse_mod = event.mod;
326     _mouse_scroll = event.scroll;
327     // Always set event type last because all listeners are attached to it
328     _mouse_event = event.type;
329
330     if( _root_group.get() )
331       return _root_group->handleMouseEvent(event);
332     else
333       return false;
334   }
335
336   //----------------------------------------------------------------------------
337   void Canvas::childAdded( SGPropertyNode * parent,
338                            SGPropertyNode * child )
339   {
340     if( parent != _node )
341       return;
342
343     if( child->getNameString() == "placement" )
344       _dirty_placements.push_back(child);
345     else if( _root_group.get() )
346       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
347   }
348
349   //----------------------------------------------------------------------------
350   void Canvas::childRemoved( SGPropertyNode * parent,
351                              SGPropertyNode * child )
352   {
353     _render_dirty = true;
354
355     if( parent != _node )
356       return;
357
358     if( child->getNameString() == "placement" )
359       _placements[ child->getIndex() ].clear();
360     else if( _root_group.get() )
361       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
362   }
363
364   //----------------------------------------------------------------------------
365   void Canvas::valueChanged(SGPropertyNode* node)
366   {
367     if(    boost::starts_with(node->getNameString(), "status")
368         || node->getParent()->getNameString() == "bounding-box" )
369       return;
370     _render_dirty = true;
371
372     bool handled = true;
373     if(    node->getParent()->getParent() == _node
374         && node->getParent()->getNameString() == "placement" )
375     {
376       // prevent double updates...
377       for( size_t i = 0; i < _dirty_placements.size(); ++i )
378       {
379         if( node->getParent() == _dirty_placements[i] )
380           return;
381       }
382
383       _dirty_placements.push_back(node->getParent());
384     }
385     else if( node->getParent() == _node )
386     {
387       if( node->getNameString() == "background" )
388       {
389         osg::Vec4 color;
390         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
391         {
392           _texture.getCamera()->setClearColor(color);
393           _render_dirty = true;
394         }
395       }
396       else if(    node->getNameString() == "mipmapping"
397               || node->getNameString() == "coverage-samples"
398               || node->getNameString() == "color-samples" )
399       {
400         _sampling_dirty = true;
401       }
402       else if( node->getNameString() == "render-always" )
403       {
404         _render_always = node->getBoolValue();
405       }
406       else if( node->getNameString() == "size" )
407       {
408         if( node->getIndex() == 0 )
409           setSizeX( node->getIntValue() );
410         else if( node->getIndex() == 1 )
411           setSizeY( node->getIntValue() );
412       }
413       else if( node->getNameString() == "view" )
414       {
415         if( node->getIndex() == 0 )
416           setViewWidth( node->getIntValue() );
417         else if( node->getIndex() == 1 )
418           setViewHeight( node->getIntValue() );
419       }
420       else if( node->getNameString() == "freeze" )
421         _texture.setRender( node->getBoolValue() );
422       else
423         handled = false;
424     }
425     else
426       handled = false;
427
428     if( !handled && _root_group.get() )
429       _root_group->valueChanged(node);
430   }
431
432   //----------------------------------------------------------------------------
433   osg::Texture2D* Canvas::getTexture() const
434   {
435     return _texture.getTexture();
436   }
437
438   //----------------------------------------------------------------------------
439   Canvas::CullCallbackPtr Canvas::getCullCallback() const
440   {
441     return _cull_callback;
442   }
443
444   //----------------------------------------------------------------------------
445   void Canvas::addPlacementFactory( const std::string& type,
446                                     PlacementFactory factory )
447   {
448     if( _placement_factories.find(type) != _placement_factories.end() )
449       SG_LOG
450       (
451         SG_GENERAL,
452         SG_WARN,
453         "Canvas::addPlacementFactory: replace existing factor for type " << type
454       );
455
456     _placement_factories[type] = factory;
457   }
458
459   //----------------------------------------------------------------------------
460   void Canvas::setSelf(const PropertyBasedElementPtr& self)
461   {
462     PropertyBasedElement::setSelf(self);
463
464     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
465
466     _root_group.reset( new Group(canvas, _node) );
467
468     // Remove automatically created property listener as we forward them on our
469     // own
470     _root_group->removeListener();
471
472     _cull_callback = new CullCallback(canvas);
473   }
474
475   //----------------------------------------------------------------------------
476   void Canvas::setStatusFlags(unsigned int flags, bool set)
477   {
478     if( set )
479       _status = _status | flags;
480     else
481       _status = _status & ~flags;
482     // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
483
484     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
485       _status_msg = "Missing size";
486     else if( _status & MISSING_SIZE_X )
487       _status_msg = "Missing size-x";
488     else if( _status & MISSING_SIZE_Y )
489       _status_msg = "Missing size-y";
490     else if( _status & CREATE_FAILED )
491       _status_msg = "Creating render target failed";
492     else if( _status == STATUS_OK && !_texture.serviceable() )
493       _status_msg = "Creation pending...";
494     else
495       _status_msg = "Ok";
496   }
497
498   //----------------------------------------------------------------------------
499   Canvas::PlacementFactoryMap Canvas::_placement_factories;
500
501 } // namespace canvas
502 } // namespace simgear