]> git.mxchange.org Git - flightgear.git/blob - src/Canvas/canvas.cxx
Canvas: Image/Window unifying and allow using canvas inside canvas.
[flightgear.git] / src / 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 program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "canvas.hxx"
20 #include "elements/group.hxx"
21
22 #include <Canvas/MouseEvent.hxx>
23 #include <Canvas/property_helper.hxx>
24 #include <Main/globals.hxx>
25 #include <Viewer/CameraGroup.hxx>
26 #include <Viewer/renderer.hxx>
27
28 #include <simgear/scene/util/RenderConstants.hxx>
29
30 #include <osg/Camera>
31 #include <osg/Geode>
32 #include <osgText/Text>
33 #include <osgViewer/Viewer>
34
35 #include <boost/algorithm/string/predicate.hpp>
36 #include <iostream>
37
38 //----------------------------------------------------------------------------
39 Canvas::CameraCullCallback::CameraCullCallback():
40   _render( true ),
41   _render_frame( 0 )
42 {
43
44 }
45
46 //----------------------------------------------------------------------------
47 void Canvas::CameraCullCallback::enableRendering()
48 {
49   _render = true;
50 }
51
52 //----------------------------------------------------------------------------
53 void Canvas::CameraCullCallback::operator()( osg::Node* node,
54                                              osg::NodeVisitor* nv )
55 {
56   if( !_render && nv->getTraversalNumber() != _render_frame )
57     return;
58
59   traverse(node, nv);
60
61   _render = false;
62   _render_frame = nv->getTraversalNumber();
63 }
64
65 //----------------------------------------------------------------------------
66 Canvas::CullCallback::CullCallback(CameraCullCallback* camera_cull):
67   _camera_cull( camera_cull )
68 {
69
70 }
71
72 //----------------------------------------------------------------------------
73 void Canvas::CullCallback::operator()( osg::Node* node,
74                                        osg::NodeVisitor* nv )
75 {
76   if( nv->getTraversalMask() & simgear::MODEL_BIT )
77     _camera_cull->enableRendering();
78
79   traverse(node, nv);
80 }
81
82 //------------------------------------------------------------------------------
83 Canvas::Canvas(SGPropertyNode* node):
84   PropertyBasedElement(node),
85   _size_x(-1),
86   _size_y(-1),
87   _view_width(-1),
88   _view_height(-1),
89   _status(node, "status"),
90   _status_msg(node, "status-msg"),
91   _mouse_x(node, "mouse/x"),
92   _mouse_y(node, "mouse/y"),
93   _mouse_dx(node, "mouse/dx"),
94   _mouse_dy(node, "mouse/dy"),
95   _mouse_button(node, "mouse/button"),
96   _mouse_state(node, "mouse/state"),
97   _mouse_mod(node, "mouse/mod"),
98   _mouse_scroll(node, "mouse/scroll"),
99   _mouse_event(node, "mouse/event"),
100   _sampling_dirty(false),
101   _color_dirty(true),
102   _root_group( new canvas::Group(node) ),
103   _render_always(false)
104 {
105   _status = 0;
106   setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
107
108   _camera_callback = new CameraCullCallback;
109   _cull_callback = new CullCallback(_camera_callback);
110
111   canvas::linkColorNodes
112   (
113     "color-background",
114     _node,
115     _color_background,
116     osg::Vec4f(0,0,0,1)
117   );
118 }
119
120 //------------------------------------------------------------------------------
121 Canvas::~Canvas()
122 {
123
124 }
125
126 //------------------------------------------------------------------------------
127 void Canvas::update(double delta_time_sec)
128 {
129   if( !_texture.serviceable() )
130   {
131     if( _status != STATUS_OK )
132       return;
133
134     _texture.setSize(_size_x, _size_y);
135     _texture.useImageCoords(true);
136     _texture.useStencil(true);
137     _texture.allocRT(_camera_callback);
138     _texture.getCamera()->setClearColor(osg::Vec4(0.0f, 0.0f, 0.0f , 1.0f));
139     _texture.getCamera()->addChild(_root_group->getMatrixTransform());
140
141     if( _texture.serviceable() )
142     {
143       setStatusFlags(STATUS_OK);
144     }
145     else
146     {
147       setStatusFlags(CREATE_FAILED);
148       return;
149     }
150   }
151
152   _root_group->update(delta_time_sec);
153
154   if( _sampling_dirty )
155   {
156     _texture.setSampling(
157       _node->getBoolValue("mipmapping"),
158       _node->getIntValue("coverage-samples"),
159       _node->getIntValue("color-samples")
160     );
161     _sampling_dirty = false;
162   }
163   if( _color_dirty )
164   {
165     _texture.getCamera()->setClearColor
166     (
167       osg::Vec4( _color_background[0]->getFloatValue(),
168                  _color_background[1]->getFloatValue(),
169                  _color_background[2]->getFloatValue(),
170                  _color_background[3]->getFloatValue() )
171     );
172     _color_dirty = false;
173   }
174
175   while( !_dirty_placements.empty() )
176   {
177     SGPropertyNode *node = _dirty_placements.back();
178     _dirty_placements.pop_back();
179
180     if( node->getIndex() >= static_cast<int>(_placements.size()) )
181       // New placement
182       _placements.resize(node->getIndex() + 1);
183     else
184       // Remove possibly existing placements
185       _placements[ node->getIndex() ].clear();
186
187     // Get new placements
188     PlacementFactoryMap::const_iterator placement_factory =
189       _placement_factories.find( node->getStringValue("type", "object") );
190     if( placement_factory != _placement_factories.end() )
191     {
192       canvas::Placements& placements =
193         _placements[ node->getIndex() ] =
194           placement_factory->second
195           (
196             node,
197             boost::static_pointer_cast<Canvas>(_self.lock())
198           );
199       node->setStringValue
200       (
201         "status-msg",
202         placements.empty() ? "No match" : "Ok"
203       );
204     }
205     else
206       node->setStringValue("status-msg", "Unknown placement type");
207   }
208
209   if( _render_always )
210     _camera_callback->enableRendering();
211 }
212
213 //------------------------------------------------------------------------------
214 void Canvas::setSizeX(int sx)
215 {
216   if( _size_x == sx )
217     return;
218   _size_x = sx;
219
220   // TODO resize if texture already allocated
221
222   if( _size_x <= 0 )
223     setStatusFlags(MISSING_SIZE_X);
224   else
225     setStatusFlags(MISSING_SIZE_X, false);
226
227   // reset flag to allow creation with new size
228   setStatusFlags(CREATE_FAILED, false);
229 }
230
231 //------------------------------------------------------------------------------
232 void Canvas::setSizeY(int sy)
233 {
234   if( _size_y == sy )
235     return;
236   _size_y = sy;
237
238   // TODO resize if texture already allocated
239
240   if( _size_y <= 0 )
241     setStatusFlags(MISSING_SIZE_Y);
242   else
243     setStatusFlags(MISSING_SIZE_Y, false);
244
245   // reset flag to allow creation with new size
246   setStatusFlags(CREATE_FAILED, false);
247 }
248
249 //------------------------------------------------------------------------------
250 void Canvas::setViewWidth(int w)
251 {
252   if( _view_width == w )
253     return;
254   _view_width = w;
255
256   _texture.setViewSize(_view_width, _view_height);
257 }
258
259 //------------------------------------------------------------------------------
260 void Canvas::setViewHeight(int h)
261 {
262   if( _view_height == h )
263     return;
264   _view_height = h;
265
266   _texture.setViewSize(_view_width, _view_height);
267 }
268
269 //------------------------------------------------------------------------------
270 bool Canvas::handleMouseEvent(const canvas::MouseEvent& event)
271 {
272   _mouse_x = event.x;
273   _mouse_y = event.y;
274   _mouse_dx = event.dx;
275   _mouse_dy = event.dy;
276   _mouse_button = event.button;
277   _mouse_state = event.state;
278   _mouse_mod = event.mod;
279   _mouse_scroll = event.scroll;
280   // Always set event type last because all listeners are attached to it
281   _mouse_event = event.type;
282   return true;
283 }
284
285 //------------------------------------------------------------------------------
286 void Canvas::childAdded( SGPropertyNode * parent,
287                          SGPropertyNode * child )
288 {
289   if( parent != _node )
290     return;
291
292   if( child->getNameString() == "placement" )
293     _dirty_placements.push_back(child);
294   else
295     static_cast<canvas::Element*>(_root_group.get())
296       ->childAdded(parent, child);
297 }
298
299 //------------------------------------------------------------------------------
300 void Canvas::childRemoved( SGPropertyNode * parent,
301                            SGPropertyNode * child )
302 {
303   if( parent != _node )
304     return;
305
306   if( child->getNameString() == "placement" )
307     _placements[ child->getIndex() ].clear();
308   else
309     static_cast<canvas::Element*>(_root_group.get())
310       ->childRemoved(parent, child);
311 }
312
313 //----------------------------------------------------------------------------
314 void Canvas::valueChanged(SGPropertyNode* node)
315 {
316   if( boost::starts_with(node->getNameString(), "status") )
317     return;
318
319   if( node->getParent()->getParent() == _node )
320   {
321     if(    !_color_background.empty()
322         && _color_background[0]->getParent() == node->getParent() )
323     {
324       _color_dirty = true;
325     }
326     else if( node->getParent()->getNameString() == "placement" )
327     {
328       // prevent double updates...
329       for( size_t i = 0; i < _dirty_placements.size(); ++i )
330       {
331         if( node->getParent() == _dirty_placements[i] )
332           return;
333       }
334
335       _dirty_placements.push_back(node->getParent());
336     }
337   }
338   else if( node->getParent() == _node )
339   {
340     if(    node->getNameString() == "mipmapping"
341         || node->getNameString() == "coverage-samples"
342         || node->getNameString() == "color-samples" )
343       _sampling_dirty = true;
344     else if( node->getNameString() == "render-always" )
345       _render_always = node->getBoolValue();
346     else if( node->getNameString() == "size" )
347     {
348       if( node->getIndex() == 0 )
349         setSizeX( node->getIntValue() );
350       else if( node->getIndex() == 1 )
351         setSizeY( node->getIntValue() );
352     }
353     else if( node->getNameString() == "view" )
354     {
355       if( node->getIndex() == 0 )
356         setViewWidth( node->getIntValue() );
357       else if( node->getIndex() == 1 )
358         setViewHeight( node->getIntValue() );
359     }
360   }
361
362   _root_group->valueChanged(node);
363 }
364
365 //------------------------------------------------------------------------------
366 osg::Texture2D* Canvas::getTexture() const
367 {
368   return _texture.getTexture();
369 }
370
371 //------------------------------------------------------------------------------
372 GLuint Canvas::getTexId() const
373 {
374   osg::Texture2D* tex = _texture.getTexture();
375   if( !tex )
376     return 0;
377
378 //  osgViewer::Viewer::Contexts contexts;
379 //  globals->get_renderer()->getViewer()->getContexts(contexts);
380 //
381 //  if( contexts.empty() )
382 //    return 0;
383
384   osg::Camera* guiCamera =
385     flightgear::getGUICamera(flightgear::CameraGroup::getDefault());
386
387   osg::State* state = guiCamera->getGraphicsContext()->getState(); //contexts[0]->getState();
388   if( !state )
389     return 0;
390
391   osg::Texture::TextureObject* tobj =
392     tex->getTextureObject( state->getContextID() );
393   if( !tobj )
394     return 0;
395
396   return tobj->_id;
397 }
398
399 //------------------------------------------------------------------------------
400 Canvas::CameraCullCallbackPtr Canvas::getCameraCullCallback() const
401 {
402   return _camera_callback;
403 }
404
405 //----------------------------------------------------------------------------
406 Canvas::CullCallbackPtr Canvas::getCullCallback() const
407 {
408   return _cull_callback;
409 }
410
411 //------------------------------------------------------------------------------
412 void Canvas::addPlacementFactory( const std::string& type,
413                                   canvas::PlacementFactory factory )
414 {
415   if( _placement_factories.find(type) != _placement_factories.end() )
416     SG_LOG
417     (
418       SG_GENERAL,
419       SG_WARN,
420       "Canvas::addPlacementFactory: replace existing factor for type " << type
421     );
422
423   _placement_factories[type] = factory;
424 }
425
426 //------------------------------------------------------------------------------
427 void Canvas::setStatusFlags(unsigned int flags, bool set)
428 {
429   if( set )
430     _status = _status | flags;
431   else
432     _status = _status & ~flags;
433   // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
434
435   if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
436     _status_msg = "Missing size";
437   else if( _status & MISSING_SIZE_X )
438     _status_msg = "Missing size-x";
439   else if( _status & MISSING_SIZE_Y )
440     _status_msg = "Missing size-y";
441   else if( _status & CREATE_FAILED )
442     _status_msg = "Creating render target failed";
443   else if( _status == STATUS_OK && !_texture.serviceable() )
444     _status_msg = "Creation pending...";
445   else
446     _status_msg = "Ok";
447 }
448
449 //------------------------------------------------------------------------------
450 Canvas::PlacementFactoryMap Canvas::_placement_factories;