1 // The canvas for rendering with the 2d API
3 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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
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>
29 #include <osgText/Text>
30 #include <osgViewer/Viewer>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
41 //----------------------------------------------------------------------------
42 Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
48 //----------------------------------------------------------------------------
49 void Canvas::CullCallback::operator()( osg::Node* node,
50 osg::NodeVisitor* nv )
52 if( (nv->getTraversalMask() & simgear::MODEL_BIT) && !_canvas.expired() )
53 _canvas.lock()->enableRendering();
58 //----------------------------------------------------------------------------
59 Canvas::Canvas(SGPropertyNode* node):
60 PropertyBasedElement(node),
62 _event_manager(new EventManager),
67 _status(node, "status"),
68 _status_msg(node, "status-msg"),
69 _sampling_dirty(false),
75 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
78 //----------------------------------------------------------------------------
84 //----------------------------------------------------------------------------
85 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
87 _system_adapter = system_adapter;
88 _texture.setSystemAdapter(system_adapter);
91 //----------------------------------------------------------------------------
92 SystemAdapterPtr Canvas::getSystemAdapter() const
94 return _system_adapter;
97 //----------------------------------------------------------------------------
98 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
100 _canvas_mgr = canvas_mgr;
103 //----------------------------------------------------------------------------
104 CanvasMgr* Canvas::getCanvasMgr() const
109 //----------------------------------------------------------------------------
110 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
112 if( canvas.expired() )
118 "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
123 _parent_canvases.insert(canvas);
126 //----------------------------------------------------------------------------
127 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
129 if( canvas.expired() )
135 "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
140 _child_canvases.insert(canvas);
143 //----------------------------------------------------------------------------
144 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
146 _parent_canvases.erase(canvas);
149 //----------------------------------------------------------------------------
150 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
152 _child_canvases.erase(canvas);
155 //----------------------------------------------------------------------------
156 GroupPtr Canvas::createGroup(const std::string& name)
158 return boost::dynamic_pointer_cast<Group>
160 _root_group->createChild("group", name)
164 //----------------------------------------------------------------------------
165 void Canvas::enableRendering(bool force)
169 _render_dirty = true;
172 //----------------------------------------------------------------------------
173 void Canvas::update(double delta_time_sec)
175 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
176 || (_status & CREATE_FAILED) )
179 if( _status == STATUS_DIRTY )
181 _texture.setSize(_size_x, _size_y);
183 if( !_texture.serviceable() )
185 _texture.useImageCoords(true);
186 _texture.useStencil(true);
187 _texture.allocRT(/*_camera_callback*/);
191 // Resizing causes a new texture to be created so we need to reapply all
192 // existing placements
196 osg::Camera* camera = _texture.getCamera();
198 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
199 parseColor(_node->getStringValue("background"), clear_color);
200 camera->setClearColor(clear_color);
202 camera->addChild(_root_group->getMatrixTransform());
204 // Ensure objects are drawn in order of traversal
205 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
207 if( _texture.serviceable() )
209 setStatusFlags(STATUS_OK);
210 setStatusFlags(STATUS_DIRTY, false);
211 _render_dirty = true;
215 setStatusFlags(CREATE_FAILED);
220 if( _visible || _render_always )
222 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
224 // TODO should we check if the image the child canvas is displayed
225 // within is really visible?
226 if( !canvas.expired() )
227 canvas.lock()->_visible = true;
232 // Also mark all canvases this canvas is displayed within as dirty
233 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
235 if( !canvas.expired() )
236 canvas.lock()->_render_dirty = true;
240 _texture.setRender(_render_dirty);
242 _render_dirty = false;
246 _texture.setRender(false);
248 _root_group->update(delta_time_sec);
250 if( _sampling_dirty )
252 _texture.setSampling(
253 _node->getBoolValue("mipmapping"),
254 _node->getIntValue("coverage-samples"),
255 _node->getIntValue("color-samples")
257 _sampling_dirty = false;
258 _render_dirty = true;
261 while( !_dirty_placements.empty() )
263 SGPropertyNode *node = _dirty_placements.back();
264 _dirty_placements.pop_back();
266 if( node->getIndex() >= static_cast<int>(_placements.size()) )
268 _placements.resize(node->getIndex() + 1);
270 // Remove possibly existing placements
271 _placements[ node->getIndex() ].clear();
273 // Get new placements
274 PlacementFactoryMap::const_iterator placement_factory =
275 _placement_factories.find( node->getStringValue("type", "object") );
276 if( placement_factory != _placement_factories.end() )
278 Placements& placements = _placements[ node->getIndex() ] =
279 placement_factory->second
282 boost::static_pointer_cast<Canvas>(_self.lock())
287 placements.empty() ? "No match" : "Ok"
291 node->setStringValue("status-msg", "Unknown placement type");
295 //----------------------------------------------------------------------------
296 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
298 if( !_root_group.get() )
299 naRuntimeError(ctx.c, "Canvas: No root group!");
301 return _root_group->addEventListener(ctx);
304 //----------------------------------------------------------------------------
305 void Canvas::setSizeX(int sx)
310 setStatusFlags(STATUS_DIRTY);
313 setStatusFlags(MISSING_SIZE_X);
315 setStatusFlags(MISSING_SIZE_X, false);
317 // reset flag to allow creation with new size
318 setStatusFlags(CREATE_FAILED, false);
321 //----------------------------------------------------------------------------
322 void Canvas::setSizeY(int sy)
327 setStatusFlags(STATUS_DIRTY);
330 setStatusFlags(MISSING_SIZE_Y);
332 setStatusFlags(MISSING_SIZE_Y, false);
334 // reset flag to allow creation with new size
335 setStatusFlags(CREATE_FAILED, false);
338 //----------------------------------------------------------------------------
339 int Canvas::getSizeX() const
344 //----------------------------------------------------------------------------
345 int Canvas::getSizeY() const
350 //----------------------------------------------------------------------------
351 void Canvas::setViewWidth(int w)
353 if( _view_width == w )
357 _texture.setViewSize(_view_width, _view_height);
360 //----------------------------------------------------------------------------
361 void Canvas::setViewHeight(int h)
363 if( _view_height == h )
367 _texture.setViewSize(_view_width, _view_height);
370 //----------------------------------------------------------------------------
371 int Canvas::getViewWidth() const
373 return _texture.getViewSize().x();
376 //----------------------------------------------------------------------------
377 int Canvas::getViewHeight() const
379 return _texture.getViewSize().y();
382 //----------------------------------------------------------------------------
383 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
385 if( !_root_group.get() )
388 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
389 event->getClientPos(),
391 if( !_root_group->accept(visitor) )
394 return _event_manager->handleEvent(event, visitor.getPropagationPath());
397 //----------------------------------------------------------------------------
398 void Canvas::childAdded( SGPropertyNode * parent,
399 SGPropertyNode * child )
401 if( parent != _node )
404 if( child->getNameString() == "placement" )
405 _dirty_placements.push_back(child);
406 else if( _root_group.get() )
407 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
410 //----------------------------------------------------------------------------
411 void Canvas::childRemoved( SGPropertyNode * parent,
412 SGPropertyNode * child )
414 _render_dirty = true;
416 if( parent != _node )
419 if( child->getNameString() == "placement" )
420 _placements[ child->getIndex() ].clear();
421 else if( _root_group.get() )
422 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
425 //----------------------------------------------------------------------------
426 void Canvas::valueChanged(SGPropertyNode* node)
428 if( boost::starts_with(node->getNameString(), "status")
429 || node->getParent()->getNameString() == "bounding-box" )
431 _render_dirty = true;
434 if( node->getParent()->getParent() == _node
435 && node->getParent()->getNameString() == "placement" )
437 bool placement_dirty = false;
438 BOOST_FOREACH(Placements& placements, _placements)
440 BOOST_FOREACH(PlacementPtr& placement, placements)
442 // check if change can be directly handled by placement
443 if( placement->getProps() == node->getParent()
444 && !placement->childChanged(node) )
445 placement_dirty = true;
449 if( !placement_dirty )
452 // prevent double updates...
453 for( size_t i = 0; i < _dirty_placements.size(); ++i )
455 if( node->getParent() == _dirty_placements[i] )
459 _dirty_placements.push_back(node->getParent());
461 else if( node->getParent() == _node )
463 if( node->getNameString() == "background" )
466 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
468 _texture.getCamera()->setClearColor(color);
469 _render_dirty = true;
472 else if( node->getNameString() == "mipmapping"
473 || node->getNameString() == "coverage-samples"
474 || node->getNameString() == "color-samples" )
476 _sampling_dirty = true;
478 else if( node->getNameString() == "additive-blend" )
480 _texture.useAdditiveBlend( node->getBoolValue() );
482 else if( node->getNameString() == "render-always" )
484 _render_always = node->getBoolValue();
486 else if( node->getNameString() == "size" )
488 if( node->getIndex() == 0 )
489 setSizeX( node->getIntValue() );
490 else if( node->getIndex() == 1 )
491 setSizeY( node->getIntValue() );
493 else if( node->getNameString() == "view" )
495 if( node->getIndex() == 0 )
496 setViewWidth( node->getIntValue() );
497 else if( node->getIndex() == 1 )
498 setViewHeight( node->getIntValue() );
500 else if( node->getNameString() == "freeze" )
501 _texture.setRender( node->getBoolValue() );
508 if( !handled && _root_group.get() )
509 _root_group->valueChanged(node);
512 //----------------------------------------------------------------------------
513 osg::Texture2D* Canvas::getTexture() const
515 return _texture.getTexture();
518 //----------------------------------------------------------------------------
519 Canvas::CullCallbackPtr Canvas::getCullCallback() const
521 return _cull_callback;
524 //----------------------------------------------------------------------------
525 void Canvas::reloadPlacements(const std::string& type)
527 for(size_t i = 0; i < _placements.size(); ++i)
529 if( _placements[i].empty() )
532 SGPropertyNode* child = _placements[i].front()->getProps();
534 // reload if type matches or no type specified
535 || child->getStringValue("type", type.c_str()) == type )
537 _dirty_placements.push_back(child);
542 //----------------------------------------------------------------------------
543 void Canvas::addPlacementFactory( const std::string& type,
544 PlacementFactory factory )
546 if( _placement_factories.find(type) != _placement_factories.end() )
551 "Canvas::addPlacementFactory: replace existing factor for type " << type
554 _placement_factories[type] = factory;
557 //----------------------------------------------------------------------------
558 void Canvas::setSelf(const PropertyBasedElementPtr& self)
560 PropertyBasedElement::setSelf(self);
562 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
564 _root_group.reset( new Group(canvas, _node) );
565 _root_group->setSelf(_root_group);
567 // Remove automatically created property listener as we forward them on our
569 _root_group->removeListener();
571 _cull_callback = new CullCallback(canvas);
574 //----------------------------------------------------------------------------
575 void Canvas::setStatusFlags(unsigned int flags, bool set)
582 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
583 _status_msg = "Missing size";
584 else if( _status & MISSING_SIZE_X )
585 _status_msg = "Missing size-x";
586 else if( _status & MISSING_SIZE_Y )
587 _status_msg = "Missing size-y";
588 else if( _status & CREATE_FAILED )
589 _status_msg = "Creating render target failed";
590 else if( _status == STATUS_DIRTY )
591 _status_msg = "Creation pending...";
596 //----------------------------------------------------------------------------
597 Canvas::PlacementFactoryMap Canvas::_placement_factories;
599 } // namespace canvas
600 } // namespace simgear