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>
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 void Canvas::setSizeX(int sx)
340 setStatusFlags(STATUS_DIRTY);
343 setStatusFlags(MISSING_SIZE_X);
345 setStatusFlags(MISSING_SIZE_X, false);
347 // reset flag to allow creation with new size
348 setStatusFlags(CREATE_FAILED, false);
351 //----------------------------------------------------------------------------
352 void Canvas::setSizeY(int sy)
357 setStatusFlags(STATUS_DIRTY);
360 setStatusFlags(MISSING_SIZE_Y);
362 setStatusFlags(MISSING_SIZE_Y, false);
364 // reset flag to allow creation with new size
365 setStatusFlags(CREATE_FAILED, false);
368 //----------------------------------------------------------------------------
369 int Canvas::getSizeX() const
374 //----------------------------------------------------------------------------
375 int Canvas::getSizeY() const
380 //----------------------------------------------------------------------------
381 void Canvas::setViewWidth(int w)
383 if( _view_width == w )
387 _texture.setViewSize(_view_width, _view_height);
390 //----------------------------------------------------------------------------
391 void Canvas::setViewHeight(int h)
393 if( _view_height == h )
397 _texture.setViewSize(_view_width, _view_height);
400 //----------------------------------------------------------------------------
401 int Canvas::getViewWidth() const
403 return _texture.getViewSize().x();
406 //----------------------------------------------------------------------------
407 int Canvas::getViewHeight() const
409 return _texture.getViewSize().y();
412 //----------------------------------------------------------------------------
413 SGRect<int> Canvas::getViewport() const
415 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
418 //----------------------------------------------------------------------------
419 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
421 if( !_root_group.get() )
424 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
425 event->getClientPos(),
427 if( !_root_group->accept(visitor) )
430 return _event_manager->handleEvent(event, visitor.getPropagationPath());
433 //----------------------------------------------------------------------------
434 void Canvas::childAdded( SGPropertyNode * parent,
435 SGPropertyNode * child )
437 if( parent != _node )
440 if( child->getNameString() == "placement" )
441 _dirty_placements.push_back(child);
442 else if( _root_group.get() )
443 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
446 //----------------------------------------------------------------------------
447 void Canvas::childRemoved( SGPropertyNode * parent,
448 SGPropertyNode * child )
450 _render_dirty = true;
452 if( parent != _node )
455 if( child->getNameString() == "placement" )
456 _placements[ child->getIndex() ].clear();
457 else if( _root_group.get() )
458 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
461 //----------------------------------------------------------------------------
462 void Canvas::valueChanged(SGPropertyNode* node)
464 if( boost::starts_with(node->getNameString(), "status") )
466 _render_dirty = true;
469 if( node->getParent()->getParent() == _node
470 && node->getParent()->getNameString() == "placement" )
472 size_t index = node->getIndex();
473 if( index < _placements.size() )
475 Placements& placements = _placements[index];
476 if( !placements.empty() )
478 bool placement_dirty = false;
479 BOOST_FOREACH(PlacementPtr& placement, placements)
481 // check if change can be directly handled by placement
482 if( placement->getProps() == node->getParent()
483 && !placement->childChanged(node) )
484 placement_dirty = true;
487 if( !placement_dirty )
492 // prevent double updates...
493 for( size_t i = 0; i < _dirty_placements.size(); ++i )
495 if( node->getParent() == _dirty_placements[i] )
499 _dirty_placements.push_back(node->getParent());
501 else if( node->getParent() == _node )
503 if( node->getNameString() == "background" )
506 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
508 _texture.getCamera()->setClearColor(color);
509 _render_dirty = true;
512 else if( node->getNameString() == "mipmapping"
513 || node->getNameString() == "coverage-samples"
514 || node->getNameString() == "color-samples" )
516 _sampling_dirty = true;
518 else if( node->getNameString() == "additive-blend" )
520 _texture.useAdditiveBlend( node->getBoolValue() );
522 else if( node->getNameString() == "render-always" )
524 _render_always = node->getBoolValue();
526 else if( node->getNameString() == "size" )
528 if( node->getIndex() == 0 )
529 setSizeX( node->getIntValue() );
530 else if( node->getIndex() == 1 )
531 setSizeY( node->getIntValue() );
533 else if( node->getNameString() == "view" )
535 if( node->getIndex() == 0 )
536 setViewWidth( node->getIntValue() );
537 else if( node->getIndex() == 1 )
538 setViewHeight( node->getIntValue() );
540 else if( node->getNameString() == "freeze" )
541 _texture.setRender( node->getBoolValue() );
548 if( !handled && _root_group.get() )
549 _root_group->valueChanged(node);
552 //----------------------------------------------------------------------------
553 osg::Texture2D* Canvas::getTexture() const
555 return _texture.getTexture();
558 //----------------------------------------------------------------------------
559 Canvas::CullCallbackPtr Canvas::getCullCallback() const
561 return _cull_callback;
564 //----------------------------------------------------------------------------
565 void Canvas::reloadPlacements(const std::string& type)
567 for(size_t i = 0; i < _placements.size(); ++i)
569 if( _placements[i].empty() )
572 SGPropertyNode* child = _placements[i].front()->getProps();
574 // reload if type matches or no type specified
575 || child->getStringValue("type", type.c_str()) == type )
577 _dirty_placements.push_back(child);
582 //----------------------------------------------------------------------------
583 void Canvas::addPlacementFactory( const std::string& type,
584 PlacementFactory factory )
586 if( _placement_factories.find(type) != _placement_factories.end() )
591 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
594 _placement_factories[type] = factory;
597 //----------------------------------------------------------------------------
598 void Canvas::removePlacementFactory(const std::string& type)
600 PlacementFactoryMap::iterator it = _placement_factories.find(type);
601 if( it == _placement_factories.end() )
606 "Canvas::removePlacementFactory: no such factory '" << type << "'"
609 _placement_factories.erase(it);
613 //----------------------------------------------------------------------------
614 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
616 _system_adapter = system_adapter;
619 //----------------------------------------------------------------------------
620 SystemAdapterPtr Canvas::getSystemAdapter()
622 return _system_adapter;
625 //----------------------------------------------------------------------------
626 void Canvas::setStatusFlags(unsigned int flags, bool set)
633 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
634 _status_msg = "Missing size";
635 else if( _status & MISSING_SIZE_X )
636 _status_msg = "Missing size-x";
637 else if( _status & MISSING_SIZE_Y )
638 _status_msg = "Missing size-y";
639 else if( _status & CREATE_FAILED )
640 _status_msg = "Creating render target failed";
641 else if( _status == STATUS_DIRTY )
642 _status_msg = "Creation pending...";
647 //----------------------------------------------------------------------------
648 Canvas::PlacementFactoryMap Canvas::_placement_factories;
649 SystemAdapterPtr Canvas::_system_adapter;
651 } // namespace canvas
652 } // namespace simgear