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) && !_canvas.expired() )
52 _canvas.lock()->enableRendering();
57 //----------------------------------------------------------------------------
58 Canvas::Canvas(SGPropertyNode* node):
59 PropertyBasedElement(node),
61 _event_manager(new EventManager),
66 _status(node, "status"),
67 _status_msg(node, "status-msg"),
68 _sampling_dirty(false),
74 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
77 //----------------------------------------------------------------------------
83 //----------------------------------------------------------------------------
84 void Canvas::onDestroy()
88 _root_group->clearEventListener();
89 _root_group->onDestroy();
93 //----------------------------------------------------------------------------
94 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
96 _canvas_mgr = canvas_mgr;
99 //----------------------------------------------------------------------------
100 CanvasMgr* Canvas::getCanvasMgr() const
105 //----------------------------------------------------------------------------
106 bool Canvas::isInit() const
108 return _texture.serviceable();
111 //----------------------------------------------------------------------------
112 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
114 if( canvas.expired() )
120 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
121 "got an expired parent!"
126 _parent_canvases.insert(canvas);
129 //----------------------------------------------------------------------------
130 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
132 if( canvas.expired() )
138 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
139 " got an expired child!"
144 _child_canvases.insert(canvas);
147 //----------------------------------------------------------------------------
148 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
150 _parent_canvases.erase(canvas);
153 //----------------------------------------------------------------------------
154 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
156 _child_canvases.erase(canvas);
159 //----------------------------------------------------------------------------
160 GroupPtr Canvas::createGroup(const std::string& name)
162 return _root_group->createChild<Group>(name);
165 //----------------------------------------------------------------------------
166 GroupPtr Canvas::getGroup(const std::string& name)
168 return _root_group->getChild<Group>(name);
171 //----------------------------------------------------------------------------
172 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
174 return _root_group->getOrCreateChild<Group>(name);
177 //----------------------------------------------------------------------------
178 GroupPtr Canvas::getRootGroup()
183 //----------------------------------------------------------------------------
184 void Canvas::enableRendering(bool force)
188 _render_dirty = true;
191 //----------------------------------------------------------------------------
192 void Canvas::update(double delta_time_sec)
194 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
195 || (_status & CREATE_FAILED) )
198 if( _status == STATUS_DIRTY )
200 _texture.setSize(_size_x, _size_y);
202 if( !_texture.serviceable() )
204 _texture.useImageCoords(true);
205 _texture.useStencil(true);
206 _texture.allocRT(/*_camera_callback*/);
210 // Resizing causes a new texture to be created so we need to reapply all
211 // existing placements
215 osg::Camera* camera = _texture.getCamera();
217 // TODO Allow custom render order? For now just keep in order with
219 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
221 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
222 parseColor(_node->getStringValue("background"), clear_color);
223 camera->setClearColor(clear_color);
225 camera->addChild(_root_group->getMatrixTransform());
227 if( _texture.serviceable() )
229 setStatusFlags(STATUS_OK);
230 setStatusFlags(STATUS_DIRTY, false);
231 _render_dirty = true;
235 setStatusFlags(CREATE_FAILED);
240 if( _visible || _render_always )
242 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
244 // TODO should we check if the image the child canvas is displayed
245 // within is really visible?
246 if( !canvas.expired() )
247 canvas.lock()->_visible = true;
252 // Also mark all canvases this canvas is displayed within as dirty
253 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
255 if( !canvas.expired() )
256 canvas.lock()->_render_dirty = true;
260 _texture.setRender(_render_dirty);
262 _render_dirty = false;
266 _texture.setRender(false);
268 _root_group->update(delta_time_sec);
270 if( _sampling_dirty )
272 _texture.setSampling(
273 _node->getBoolValue("mipmapping"),
274 _node->getIntValue("coverage-samples"),
275 _node->getIntValue("color-samples")
277 _sampling_dirty = false;
278 _render_dirty = true;
281 while( !_dirty_placements.empty() )
283 SGPropertyNode *node = _dirty_placements.back();
284 _dirty_placements.pop_back();
286 if( node->getIndex() >= static_cast<int>(_placements.size()) )
288 _placements.resize(node->getIndex() + 1);
290 // Remove possibly existing placements
291 _placements[ node->getIndex() ].clear();
293 // Get new placements
294 PlacementFactoryMap::const_iterator placement_factory =
295 _placement_factories.find( node->getStringValue("type", "object") );
296 if( placement_factory != _placement_factories.end() )
298 Placements& placements = _placements[ node->getIndex() ] =
299 placement_factory->second
302 boost::static_pointer_cast<Canvas>(_self.lock())
307 placements.empty() ? "No match" : "Ok"
311 node->setStringValue("status-msg", "Unknown placement type");
315 //----------------------------------------------------------------------------
316 bool Canvas::addEventListener( const std::string& type,
317 const EventListener& cb )
319 if( !_root_group.get() )
320 throw std::runtime_error("Canvas::AddEventListener: no root group!");
322 return _root_group->addEventListener(type, cb);
325 //----------------------------------------------------------------------------
326 void Canvas::setSizeX(int sx)
331 setStatusFlags(STATUS_DIRTY);
334 setStatusFlags(MISSING_SIZE_X);
336 setStatusFlags(MISSING_SIZE_X, false);
338 // reset flag to allow creation with new size
339 setStatusFlags(CREATE_FAILED, false);
342 //----------------------------------------------------------------------------
343 void Canvas::setSizeY(int sy)
348 setStatusFlags(STATUS_DIRTY);
351 setStatusFlags(MISSING_SIZE_Y);
353 setStatusFlags(MISSING_SIZE_Y, false);
355 // reset flag to allow creation with new size
356 setStatusFlags(CREATE_FAILED, false);
359 //----------------------------------------------------------------------------
360 int Canvas::getSizeX() const
365 //----------------------------------------------------------------------------
366 int Canvas::getSizeY() const
371 //----------------------------------------------------------------------------
372 void Canvas::setViewWidth(int w)
374 if( _view_width == w )
378 _texture.setViewSize(_view_width, _view_height);
381 //----------------------------------------------------------------------------
382 void Canvas::setViewHeight(int h)
384 if( _view_height == h )
388 _texture.setViewSize(_view_width, _view_height);
391 //----------------------------------------------------------------------------
392 int Canvas::getViewWidth() const
394 return _texture.getViewSize().x();
397 //----------------------------------------------------------------------------
398 int Canvas::getViewHeight() const
400 return _texture.getViewSize().y();
403 //----------------------------------------------------------------------------
404 SGRect<int> Canvas::getViewport() const
406 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
409 //----------------------------------------------------------------------------
410 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
412 if( !_root_group.get() )
415 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
416 event->getClientPos(),
418 if( !_root_group->accept(visitor) )
421 return _event_manager->handleEvent(event, visitor.getPropagationPath());
424 //----------------------------------------------------------------------------
425 void Canvas::childAdded( SGPropertyNode * parent,
426 SGPropertyNode * child )
428 if( parent != _node )
431 if( child->getNameString() == "placement" )
432 _dirty_placements.push_back(child);
433 else if( _root_group.get() )
434 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
437 //----------------------------------------------------------------------------
438 void Canvas::childRemoved( SGPropertyNode * parent,
439 SGPropertyNode * child )
441 _render_dirty = true;
443 if( parent != _node )
446 if( child->getNameString() == "placement" )
447 _placements[ child->getIndex() ].clear();
448 else if( _root_group.get() )
449 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
452 //----------------------------------------------------------------------------
453 void Canvas::valueChanged(SGPropertyNode* node)
455 if( boost::starts_with(node->getNameString(), "status") )
457 _render_dirty = true;
460 if( node->getParent()->getParent() == _node
461 && node->getParent()->getNameString() == "placement" )
463 size_t index = node->getIndex();
464 if( index < _placements.size() )
466 Placements& placements = _placements[index];
467 if( !placements.empty() )
469 bool placement_dirty = false;
470 BOOST_FOREACH(PlacementPtr& placement, placements)
472 // check if change can be directly handled by placement
473 if( placement->getProps() == node->getParent()
474 && !placement->childChanged(node) )
475 placement_dirty = true;
478 if( !placement_dirty )
483 // prevent double updates...
484 for( size_t i = 0; i < _dirty_placements.size(); ++i )
486 if( node->getParent() == _dirty_placements[i] )
490 _dirty_placements.push_back(node->getParent());
492 else if( node->getParent() == _node )
494 if( node->getNameString() == "background" )
497 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
499 _texture.getCamera()->setClearColor(color);
500 _render_dirty = true;
503 else if( node->getNameString() == "mipmapping"
504 || node->getNameString() == "coverage-samples"
505 || node->getNameString() == "color-samples" )
507 _sampling_dirty = true;
509 else if( node->getNameString() == "additive-blend" )
511 _texture.useAdditiveBlend( node->getBoolValue() );
513 else if( node->getNameString() == "render-always" )
515 _render_always = node->getBoolValue();
517 else if( node->getNameString() == "size" )
519 if( node->getIndex() == 0 )
520 setSizeX( node->getIntValue() );
521 else if( node->getIndex() == 1 )
522 setSizeY( node->getIntValue() );
524 else if( node->getNameString() == "view" )
526 if( node->getIndex() == 0 )
527 setViewWidth( node->getIntValue() );
528 else if( node->getIndex() == 1 )
529 setViewHeight( node->getIntValue() );
531 else if( node->getNameString() == "freeze" )
532 _texture.setRender( node->getBoolValue() );
539 if( !handled && _root_group.get() )
540 _root_group->valueChanged(node);
543 //----------------------------------------------------------------------------
544 osg::Texture2D* Canvas::getTexture() const
546 return _texture.getTexture();
549 //----------------------------------------------------------------------------
550 Canvas::CullCallbackPtr Canvas::getCullCallback() const
552 return _cull_callback;
555 //----------------------------------------------------------------------------
556 void Canvas::reloadPlacements(const std::string& type)
558 for(size_t i = 0; i < _placements.size(); ++i)
560 if( _placements[i].empty() )
563 SGPropertyNode* child = _placements[i].front()->getProps();
565 // reload if type matches or no type specified
566 || child->getStringValue("type", type.c_str()) == type )
568 _dirty_placements.push_back(child);
573 //----------------------------------------------------------------------------
574 void Canvas::addPlacementFactory( const std::string& type,
575 PlacementFactory factory )
577 if( _placement_factories.find(type) != _placement_factories.end() )
582 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
585 _placement_factories[type] = factory;
588 //----------------------------------------------------------------------------
589 void Canvas::removePlacementFactory(const std::string& type)
591 PlacementFactoryMap::iterator it = _placement_factories.find(type);
592 if( it == _placement_factories.end() )
597 "Canvas::removePlacementFactory: no such factory '" << type << "'"
600 _placement_factories.erase(it);
604 //----------------------------------------------------------------------------
605 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
607 _system_adapter = system_adapter;
610 //----------------------------------------------------------------------------
611 SystemAdapterPtr Canvas::getSystemAdapter()
613 return _system_adapter;
616 //----------------------------------------------------------------------------
617 void Canvas::setSelf(const PropertyBasedElementPtr& self)
619 PropertyBasedElement::setSelf(self);
621 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
623 _root_group.reset( new Group(canvas, _node) );
624 _root_group->setSelf(_root_group);
626 // Remove automatically created property listener as we forward them on our
628 _root_group->removeListener();
630 _cull_callback = new CullCallback(canvas);
633 //----------------------------------------------------------------------------
634 void Canvas::setStatusFlags(unsigned int flags, bool set)
641 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
642 _status_msg = "Missing size";
643 else if( _status & MISSING_SIZE_X )
644 _status_msg = "Missing size-x";
645 else if( _status & MISSING_SIZE_Y )
646 _status_msg = "Missing size-y";
647 else if( _status & CREATE_FAILED )
648 _status_msg = "Creating render target failed";
649 else if( _status == STATUS_DIRTY )
650 _status_msg = "Creation pending...";
655 //----------------------------------------------------------------------------
656 Canvas::PlacementFactoryMap Canvas::_placement_factories;
657 SystemAdapterPtr Canvas::_system_adapter;
659 } // namespace canvas
660 } // namespace simgear