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/MouseEvent.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>
40 //----------------------------------------------------------------------------
41 Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
47 //----------------------------------------------------------------------------
48 void Canvas::CullCallback::operator()( osg::Node* node,
49 osg::NodeVisitor* nv )
51 if( (nv->getTraversalMask() & simgear::MODEL_BIT) )
53 CanvasPtr canvas = _canvas.lock();
55 canvas->enableRendering();
61 //----------------------------------------------------------------------------
62 Canvas::Canvas(SGPropertyNode* node):
63 PropertyBasedElement(node),
65 _event_manager(new EventManager),
70 _status(node, "status"),
71 _status_msg(node, "status-msg"),
72 _sampling_dirty(false),
78 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
80 _root_group.reset( new Group(this, _node) );
82 // Remove automatically created property listener as we forward them on our
84 _root_group->removeListener();
85 _cull_callback = new CullCallback(this);
88 //----------------------------------------------------------------------------
94 //----------------------------------------------------------------------------
95 void Canvas::onDestroy()
99 _root_group->clearEventListener();
100 _root_group->onDestroy();
104 //----------------------------------------------------------------------------
105 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
107 _canvas_mgr = canvas_mgr;
110 //----------------------------------------------------------------------------
111 CanvasMgr* Canvas::getCanvasMgr() const
116 //----------------------------------------------------------------------------
117 bool Canvas::isInit() const
119 return _texture.serviceable();
122 //----------------------------------------------------------------------------
123 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
125 if( canvas.expired() )
131 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
132 "got an expired parent!"
137 _parent_canvases.insert(canvas);
140 //----------------------------------------------------------------------------
141 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
143 if( canvas.expired() )
149 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
150 " got an expired child!"
155 _child_canvases.insert(canvas);
158 //----------------------------------------------------------------------------
159 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
161 _parent_canvases.erase(canvas);
164 //----------------------------------------------------------------------------
165 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
167 _child_canvases.erase(canvas);
170 //----------------------------------------------------------------------------
171 GroupPtr Canvas::createGroup(const std::string& name)
173 return _root_group->createChild<Group>(name);
176 //----------------------------------------------------------------------------
177 GroupPtr Canvas::getGroup(const std::string& name)
179 return _root_group->getChild<Group>(name);
182 //----------------------------------------------------------------------------
183 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
185 return _root_group->getOrCreateChild<Group>(name);
188 //----------------------------------------------------------------------------
189 GroupPtr Canvas::getRootGroup()
194 //----------------------------------------------------------------------------
195 void Canvas::enableRendering(bool force)
199 _render_dirty = true;
202 //----------------------------------------------------------------------------
203 void Canvas::update(double delta_time_sec)
205 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
206 || (_status & CREATE_FAILED) )
209 if( _status == STATUS_DIRTY )
211 _texture.setSize(_size_x, _size_y);
213 if( !_texture.serviceable() )
215 _texture.useImageCoords(true);
216 _texture.useStencil(true);
217 _texture.allocRT(/*_camera_callback*/);
221 // Resizing causes a new texture to be created so we need to reapply all
222 // existing placements
226 osg::Camera* camera = _texture.getCamera();
228 // TODO Allow custom render order? For now just keep in order with
230 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
232 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
233 parseColor(_node->getStringValue("background"), clear_color);
234 camera->setClearColor(clear_color);
236 camera->addChild(_root_group->getMatrixTransform());
238 if( _texture.serviceable() )
240 setStatusFlags(STATUS_OK);
241 setStatusFlags(STATUS_DIRTY, false);
242 _render_dirty = true;
246 setStatusFlags(CREATE_FAILED);
251 if( _visible || _render_always )
253 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
255 // TODO should we check if the image the child canvas is displayed
256 // within is really visible?
257 CanvasPtr canvas = canvas_weak.lock();
259 canvas->_visible = true;
264 // Also mark all canvases this canvas is displayed within as dirty
265 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
267 CanvasPtr canvas = canvas_weak.lock();
269 canvas->_render_dirty = true;
273 _texture.setRender(_render_dirty);
275 _render_dirty = false;
279 _texture.setRender(false);
281 _root_group->update(delta_time_sec);
283 if( _sampling_dirty )
285 _texture.setSampling(
286 _node->getBoolValue("mipmapping"),
287 _node->getIntValue("coverage-samples"),
288 _node->getIntValue("color-samples")
290 _sampling_dirty = false;
291 _render_dirty = true;
294 while( !_dirty_placements.empty() )
296 SGPropertyNode *node = _dirty_placements.back();
297 _dirty_placements.pop_back();
299 if( node->getIndex() >= static_cast<int>(_placements.size()) )
301 _placements.resize(node->getIndex() + 1);
303 // Remove possibly existing placements
304 _placements[ node->getIndex() ].clear();
306 // Get new placements
307 PlacementFactoryMap::const_iterator placement_factory =
308 _placement_factories.find( node->getStringValue("type", "object") );
309 if( placement_factory != _placement_factories.end() )
311 Placements& placements = _placements[ node->getIndex() ] =
312 placement_factory->second(node, this);
316 placements.empty() ? "No match" : "Ok"
320 node->setStringValue("status-msg", "Unknown placement type");
324 //----------------------------------------------------------------------------
325 bool Canvas::addEventListener( const std::string& type,
326 const EventListener& cb )
328 if( !_root_group.get() )
329 throw std::runtime_error("Canvas::addEventListener: no root group!");
331 return _root_group->addEventListener(type, cb);
334 //----------------------------------------------------------------------------
335 bool Canvas::dispatchEvent(const EventPtr& event)
337 if( !_root_group.get() )
338 throw std::runtime_error("Canvas::dispatchEvent: no root group!");
340 return _root_group->dispatchEvent(event);
343 //----------------------------------------------------------------------------
344 void Canvas::setSizeX(int sx)
349 setStatusFlags(STATUS_DIRTY);
352 setStatusFlags(MISSING_SIZE_X);
354 setStatusFlags(MISSING_SIZE_X, false);
356 // reset flag to allow creation with new size
357 setStatusFlags(CREATE_FAILED, false);
360 //----------------------------------------------------------------------------
361 void Canvas::setSizeY(int sy)
366 setStatusFlags(STATUS_DIRTY);
369 setStatusFlags(MISSING_SIZE_Y);
371 setStatusFlags(MISSING_SIZE_Y, false);
373 // reset flag to allow creation with new size
374 setStatusFlags(CREATE_FAILED, false);
377 //----------------------------------------------------------------------------
378 int Canvas::getSizeX() const
383 //----------------------------------------------------------------------------
384 int Canvas::getSizeY() const
389 //----------------------------------------------------------------------------
390 void Canvas::setViewWidth(int w)
392 if( _view_width == w )
396 _texture.setViewSize(_view_width, _view_height);
399 //----------------------------------------------------------------------------
400 void Canvas::setViewHeight(int h)
402 if( _view_height == h )
406 _texture.setViewSize(_view_width, _view_height);
409 //----------------------------------------------------------------------------
410 int Canvas::getViewWidth() const
412 return _texture.getViewSize().x();
415 //----------------------------------------------------------------------------
416 int Canvas::getViewHeight() const
418 return _texture.getViewSize().y();
421 //----------------------------------------------------------------------------
422 SGRect<int> Canvas::getViewport() const
424 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
427 //----------------------------------------------------------------------------
428 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
433 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
434 event->getClientPos(),
436 if( !_root_group->accept(visitor) )
439 return _event_manager->handleEvent(event, visitor.getPropagationPath());
442 //----------------------------------------------------------------------------
443 bool Canvas::propagateEvent( EventPtr const& event,
444 EventPropagationPath const& path )
446 return _event_manager->propagateEvent(event, path);
449 //----------------------------------------------------------------------------
450 void Canvas::childAdded( SGPropertyNode * parent,
451 SGPropertyNode * child )
453 if( parent != _node )
456 if( child->getNameString() == "placement" )
457 _dirty_placements.push_back(child);
458 else if( _root_group.get() )
459 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
462 //----------------------------------------------------------------------------
463 void Canvas::childRemoved( SGPropertyNode * parent,
464 SGPropertyNode * child )
466 _render_dirty = true;
468 if( parent != _node )
471 if( child->getNameString() == "placement" )
472 _placements[ child->getIndex() ].clear();
473 else if( _root_group.get() )
474 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
477 //----------------------------------------------------------------------------
478 void Canvas::valueChanged(SGPropertyNode* node)
480 const std::string& name = node->getNameString();
482 if( boost::starts_with(name, "status")
483 || boost::starts_with(name, "data-") )
485 _render_dirty = true;
488 if( node->getParent()->getParent() == _node
489 && node->getParent()->getNameString() == "placement" )
491 size_t index = node->getIndex();
492 if( index < _placements.size() )
494 Placements& placements = _placements[index];
495 if( !placements.empty() )
497 bool placement_dirty = false;
498 BOOST_FOREACH(PlacementPtr& placement, placements)
500 // check if change can be directly handled by placement
501 if( placement->getProps() == node->getParent()
502 && !placement->childChanged(node) )
503 placement_dirty = true;
506 if( !placement_dirty )
511 // prevent double updates...
512 for( size_t i = 0; i < _dirty_placements.size(); ++i )
514 if( node->getParent() == _dirty_placements[i] )
518 _dirty_placements.push_back(node->getParent());
520 else if( node->getParent() == _node )
522 if( name == "background" )
525 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
527 _texture.getCamera()->setClearColor(color);
528 _render_dirty = true;
531 else if( name == "mipmapping"
532 || name == "coverage-samples"
533 || name == "color-samples" )
535 _sampling_dirty = true;
537 else if( name == "additive-blend" )
539 _texture.useAdditiveBlend( node->getBoolValue() );
541 else if( name == "render-always" )
543 _render_always = node->getBoolValue();
545 else if( name == "size" )
547 if( node->getIndex() == 0 )
548 setSizeX( node->getIntValue() );
549 else if( node->getIndex() == 1 )
550 setSizeY( node->getIntValue() );
552 else if( name == "view" )
554 if( node->getIndex() == 0 )
555 setViewWidth( node->getIntValue() );
556 else if( node->getIndex() == 1 )
557 setViewHeight( node->getIntValue() );
559 else if( name == "freeze" )
560 _texture.setRender( node->getBoolValue() );
567 if( !handled && _root_group.get() )
568 _root_group->valueChanged(node);
571 //----------------------------------------------------------------------------
572 osg::Texture2D* Canvas::getTexture() const
574 return _texture.getTexture();
577 //----------------------------------------------------------------------------
578 Canvas::CullCallbackPtr Canvas::getCullCallback() const
580 return _cull_callback;
583 //----------------------------------------------------------------------------
584 void Canvas::reloadPlacements(const std::string& type)
586 for(size_t i = 0; i < _placements.size(); ++i)
588 if( _placements[i].empty() )
591 SGPropertyNode* child = _placements[i].front()->getProps();
593 // reload if type matches or no type specified
594 || child->getStringValue("type", type.c_str()) == type )
596 _dirty_placements.push_back(child);
601 //----------------------------------------------------------------------------
602 void Canvas::addPlacementFactory( const std::string& type,
603 PlacementFactory factory )
605 if( _placement_factories.find(type) != _placement_factories.end() )
610 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
613 _placement_factories[type] = factory;
616 //----------------------------------------------------------------------------
617 void Canvas::removePlacementFactory(const std::string& type)
619 PlacementFactoryMap::iterator it = _placement_factories.find(type);
620 if( it == _placement_factories.end() )
625 "Canvas::removePlacementFactory: no such factory '" << type << "'"
628 _placement_factories.erase(it);
632 //----------------------------------------------------------------------------
633 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
635 _system_adapter = system_adapter;
638 //----------------------------------------------------------------------------
639 SystemAdapterPtr Canvas::getSystemAdapter()
641 return _system_adapter;
644 //----------------------------------------------------------------------------
645 void Canvas::setStatusFlags(unsigned int flags, bool set)
652 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
653 _status_msg = "Missing size";
654 else if( _status & MISSING_SIZE_X )
655 _status_msg = "Missing size-x";
656 else if( _status & MISSING_SIZE_Y )
657 _status_msg = "Missing size-y";
658 else if( _status & CREATE_FAILED )
659 _status_msg = "Creating render target failed";
660 else if( _status == STATUS_DIRTY )
661 _status_msg = "Creation pending...";
666 //----------------------------------------------------------------------------
667 Canvas::PlacementFactoryMap Canvas::_placement_factories;
668 SystemAdapterPtr Canvas::_system_adapter;
670 } // namespace canvas
671 } // namespace simgear