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 "CanvasPlacement.hxx"
23 #include <simgear/canvas/events/KeyboardEvent.hxx>
24 #include <simgear/canvas/events/MouseEvent.hxx>
25 #include <simgear/scene/util/parse_color.hxx>
26 #include <simgear/scene/util/RenderConstants.hxx>
30 #include <osgText/Text>
31 #include <osgViewer/Viewer>
33 #include <boost/algorithm/string/predicate.hpp>
34 #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) )
54 CanvasPtr canvas = _canvas.lock();
56 canvas->enableRendering();
62 //----------------------------------------------------------------------------
63 Canvas::Canvas(SGPropertyNode* node):
64 PropertyBasedElement(node),
66 _event_manager(new EventManager),
71 _status(node, "status"),
72 _status_msg(node, "status-msg"),
73 _sampling_dirty(false),
79 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
81 _root_group.reset( new Group(this, _node) );
83 // Remove automatically created property listener as we forward them on our
85 _root_group->removeListener();
86 _cull_callback = new CullCallback(this);
89 //----------------------------------------------------------------------------
95 //----------------------------------------------------------------------------
96 void Canvas::onDestroy()
100 _root_group->clearEventListener();
101 _root_group->onDestroy();
105 //----------------------------------------------------------------------------
106 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
108 _canvas_mgr = canvas_mgr;
111 //----------------------------------------------------------------------------
112 CanvasMgr* Canvas::getCanvasMgr() const
117 //----------------------------------------------------------------------------
118 bool Canvas::isInit() const
120 return _texture.serviceable();
123 //----------------------------------------------------------------------------
124 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
126 if( canvas.expired() )
132 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
133 "got an expired parent!"
138 _parent_canvases.insert(canvas);
141 //----------------------------------------------------------------------------
142 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
144 if( canvas.expired() )
150 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
151 " got an expired child!"
156 _child_canvases.insert(canvas);
159 //----------------------------------------------------------------------------
160 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
162 _parent_canvases.erase(canvas);
165 //----------------------------------------------------------------------------
166 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
168 _child_canvases.erase(canvas);
171 //----------------------------------------------------------------------------
172 GroupPtr Canvas::createGroup(const std::string& name)
174 return _root_group->createChild<Group>(name);
177 //----------------------------------------------------------------------------
178 GroupPtr Canvas::getGroup(const std::string& name)
180 return _root_group->getChild<Group>(name);
183 //----------------------------------------------------------------------------
184 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
186 return _root_group->getOrCreateChild<Group>(name);
189 //----------------------------------------------------------------------------
190 GroupPtr Canvas::getRootGroup()
195 //----------------------------------------------------------------------------
196 void Canvas::setLayout(const LayoutRef& layout)
199 _layout->setCanvas(this);
202 //----------------------------------------------------------------------------
203 void Canvas::setFocusElement(const ElementPtr& el)
205 if( el && el->getCanvas().lock() != this )
207 SG_LOG(SG_GUI, SG_WARN, "setFocusElement: element not from this canvas");
211 // TODO focus out/in events
215 //----------------------------------------------------------------------------
216 void Canvas::enableRendering(bool force)
220 _render_dirty = true;
223 //----------------------------------------------------------------------------
224 void Canvas::update(double delta_time_sec)
226 if( _status & (CREATE_FAILED | MISSING_SIZE) )
229 if( _status & STATUS_DIRTY )
231 _texture.setSize(_size_x, _size_y);
233 if( !_texture.serviceable() )
235 _texture.useImageCoords(true);
236 _texture.useStencil(true);
237 _texture.allocRT(/*_camera_callback*/);
241 // Resizing causes a new texture to be created so we need to reapply all
242 // existing placements
246 osg::Camera* camera = _texture.getCamera();
248 // TODO Allow custom render order? For now just keep in order with
250 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
252 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
253 parseColor(_node->getStringValue("background"), clear_color);
254 camera->setClearColor(clear_color);
256 camera->addChild(_root_group->getMatrixTransform());
258 if( _texture.serviceable() )
260 setStatusFlags(STATUS_OK);
261 setStatusFlags(STATUS_DIRTY, false);
262 _render_dirty = true;
266 setStatusFlags(CREATE_FAILED);
272 _layout->setGeometry(SGRecti(0, 0, _view_width, _view_height));
274 if( _visible || _render_always )
276 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
278 // TODO should we check if the image the child canvas is displayed
279 // within is really visible?
280 CanvasPtr canvas = canvas_weak.lock();
282 canvas->_visible = true;
287 // Also mark all canvases this canvas is displayed within as dirty
288 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
290 CanvasPtr canvas = canvas_weak.lock();
292 canvas->_render_dirty = true;
296 _texture.setRender(_render_dirty);
298 _render_dirty = false;
302 _texture.setRender(false);
304 _root_group->update(delta_time_sec);
306 if( _sampling_dirty )
308 _texture.setSampling(
309 _node->getBoolValue("mipmapping"),
310 _node->getIntValue("coverage-samples"),
311 _node->getIntValue("color-samples")
313 _sampling_dirty = false;
314 _render_dirty = true;
317 while( !_dirty_placements.empty() )
319 SGPropertyNode *node = _dirty_placements.back();
320 _dirty_placements.pop_back();
322 if( node->getIndex() >= static_cast<int>(_placements.size()) )
324 _placements.resize(node->getIndex() + 1);
326 // Remove possibly existing placements
327 _placements[ node->getIndex() ].clear();
329 // Get new placements
330 PlacementFactoryMap::const_iterator placement_factory =
331 _placement_factories.find( node->getStringValue("type", "object") );
332 if( placement_factory != _placement_factories.end() )
334 Placements& placements = _placements[ node->getIndex() ] =
335 placement_factory->second(node, this);
339 placements.empty() ? "No match" : "Ok"
343 node->setStringValue("status-msg", "Unknown placement type");
347 //----------------------------------------------------------------------------
348 bool Canvas::addEventListener( const std::string& type,
349 const EventListener& cb )
351 if( !_root_group.get() )
352 throw std::runtime_error("Canvas::addEventListener: no root group!");
354 return _root_group->addEventListener(type, cb);
357 //----------------------------------------------------------------------------
358 bool Canvas::dispatchEvent(const EventPtr& event)
360 if( !_root_group.get() )
361 throw std::runtime_error("Canvas::dispatchEvent: no root group!");
363 return _root_group->dispatchEvent(event);
366 //----------------------------------------------------------------------------
367 void Canvas::setSizeX(int sx)
372 setStatusFlags(STATUS_DIRTY);
375 setStatusFlags(MISSING_SIZE_X);
377 setStatusFlags(MISSING_SIZE_X, false);
379 // reset flag to allow creation with new size
380 setStatusFlags(CREATE_FAILED, false);
383 //----------------------------------------------------------------------------
384 void Canvas::setSizeY(int sy)
389 setStatusFlags(STATUS_DIRTY);
392 setStatusFlags(MISSING_SIZE_Y);
394 setStatusFlags(MISSING_SIZE_Y, false);
396 // reset flag to allow creation with new size
397 setStatusFlags(CREATE_FAILED, false);
400 //----------------------------------------------------------------------------
401 int Canvas::getSizeX() const
406 //----------------------------------------------------------------------------
407 int Canvas::getSizeY() const
412 //----------------------------------------------------------------------------
413 void Canvas::setViewWidth(int w)
415 if( _view_width == w )
419 _texture.setViewSize(_view_width, _view_height);
422 //----------------------------------------------------------------------------
423 void Canvas::setViewHeight(int h)
425 if( _view_height == h )
429 _texture.setViewSize(_view_width, _view_height);
432 //----------------------------------------------------------------------------
433 int Canvas::getViewWidth() const
435 return _texture.getViewSize().x();
438 //----------------------------------------------------------------------------
439 int Canvas::getViewHeight() const
441 return _texture.getViewSize().y();
444 //----------------------------------------------------------------------------
445 SGRect<int> Canvas::getViewport() const
447 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
450 //----------------------------------------------------------------------------
451 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
456 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
457 event->getClientPos(),
459 if( !_root_group->accept(visitor) )
462 return _event_manager->handleEvent(event, visitor.getPropagationPath());
465 //----------------------------------------------------------------------------
466 bool Canvas::handleKeyboardEvent(const KeyboardEventPtr& event)
468 ElementPtr target = _focus_element.lock();
470 target = _root_group;
474 return target->dispatchEvent(event);
477 //----------------------------------------------------------------------------
478 bool Canvas::propagateEvent( EventPtr const& event,
479 EventPropagationPath const& path )
481 return _event_manager->propagateEvent(event, path);
484 //----------------------------------------------------------------------------
485 void Canvas::childAdded( SGPropertyNode * parent,
486 SGPropertyNode * child )
488 if( parent != _node )
491 if( child->getNameString() == "placement" )
492 _dirty_placements.push_back(child);
493 else if( _root_group.get() )
494 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
497 //----------------------------------------------------------------------------
498 void Canvas::childRemoved( SGPropertyNode * parent,
499 SGPropertyNode * child )
501 _render_dirty = true;
503 if( parent != _node )
506 if( child->getNameString() == "placement" )
507 _placements[ child->getIndex() ].clear();
508 else if( _root_group.get() )
509 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
512 //----------------------------------------------------------------------------
513 void Canvas::valueChanged(SGPropertyNode* node)
515 const std::string& name = node->getNameString();
517 if( boost::starts_with(name, "status")
518 || boost::starts_with(name, "data-") )
520 _render_dirty = true;
523 if( node->getParent()->getParent() == _node
524 && node->getParent()->getNameString() == "placement" )
526 size_t index = node->getIndex();
527 if( index < _placements.size() )
529 Placements& placements = _placements[index];
530 if( !placements.empty() )
532 bool placement_dirty = false;
533 BOOST_FOREACH(PlacementPtr& placement, placements)
535 // check if change can be directly handled by placement
536 if( placement->getProps() == node->getParent()
537 && !placement->childChanged(node) )
538 placement_dirty = true;
541 if( !placement_dirty )
546 // prevent double updates...
547 for( size_t i = 0; i < _dirty_placements.size(); ++i )
549 if( node->getParent() == _dirty_placements[i] )
553 _dirty_placements.push_back(node->getParent());
555 else if( node->getParent() == _node )
557 if( name == "background" )
560 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
562 _texture.getCamera()->setClearColor(color);
563 _render_dirty = true;
566 else if( name == "mipmapping"
567 || name == "coverage-samples"
568 || name == "color-samples" )
570 _sampling_dirty = true;
572 else if( name == "additive-blend" )
574 _texture.useAdditiveBlend( node->getBoolValue() );
576 else if( name == "render-always" )
578 _render_always = node->getBoolValue();
580 else if( name == "size" )
582 if( node->getIndex() == 0 )
583 setSizeX( node->getIntValue() );
584 else if( node->getIndex() == 1 )
585 setSizeY( node->getIntValue() );
587 else if( name == "update" )
590 _root_group->update(0);
593 else if( name == "view" )
595 if( node->getIndex() == 0 )
596 setViewWidth( node->getIntValue() );
597 else if( node->getIndex() == 1 )
598 setViewHeight( node->getIntValue() );
600 else if( name == "freeze" )
601 _texture.setRender( node->getBoolValue() );
608 if( !handled && _root_group.get() )
609 _root_group->valueChanged(node);
612 //----------------------------------------------------------------------------
613 osg::Texture2D* Canvas::getTexture() const
615 return _texture.getTexture();
618 //----------------------------------------------------------------------------
619 Canvas::CullCallbackPtr Canvas::getCullCallback() const
621 return _cull_callback;
624 //----------------------------------------------------------------------------
625 void Canvas::reloadPlacements(const std::string& type)
627 for(size_t i = 0; i < _placements.size(); ++i)
629 if( _placements[i].empty() )
632 SGPropertyNode* child = _placements[i].front()->getProps();
634 // reload if type matches or no type specified
635 || child->getStringValue("type", type.c_str()) == type )
637 _dirty_placements.push_back(child);
642 //----------------------------------------------------------------------------
643 void Canvas::addPlacementFactory( const std::string& type,
644 PlacementFactory factory )
646 if( _placement_factories.find(type) != _placement_factories.end() )
651 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
654 _placement_factories[type] = factory;
657 //----------------------------------------------------------------------------
658 void Canvas::removePlacementFactory(const std::string& type)
660 PlacementFactoryMap::iterator it = _placement_factories.find(type);
661 if( it == _placement_factories.end() )
666 "Canvas::removePlacementFactory: no such factory '" << type << "'"
669 _placement_factories.erase(it);
673 //----------------------------------------------------------------------------
674 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
676 _system_adapter = system_adapter;
679 //----------------------------------------------------------------------------
680 SystemAdapterPtr Canvas::getSystemAdapter()
682 return _system_adapter;
685 //----------------------------------------------------------------------------
686 void Canvas::setStatusFlags(unsigned int flags, bool set)
693 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
694 _status_msg = "Missing size";
695 else if( _status & MISSING_SIZE_X )
696 _status_msg = "Missing size-x";
697 else if( _status & MISSING_SIZE_Y )
698 _status_msg = "Missing size-y";
699 else if( _status & CREATE_FAILED )
700 _status_msg = "Creating render target failed";
701 else if( _status & STATUS_DIRTY )
702 _status_msg = "Creation pending...";
707 //----------------------------------------------------------------------------
708 Canvas::PlacementFactoryMap Canvas::_placement_factories;
709 SystemAdapterPtr Canvas::_system_adapter;
711 } // namespace canvas
712 } // namespace simgear