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 //----------------------------------------------------------------------------
78 void Canvas::onDestroy()
82 _root_group->clearEventListener();
83 _root_group->onDestroy();
87 //----------------------------------------------------------------------------
88 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
90 _system_adapter = system_adapter;
91 _texture.setSystemAdapter(system_adapter);
94 //----------------------------------------------------------------------------
95 SystemAdapterPtr Canvas::getSystemAdapter() const
97 return _system_adapter;
100 //----------------------------------------------------------------------------
101 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
103 _canvas_mgr = canvas_mgr;
106 //----------------------------------------------------------------------------
107 CanvasMgr* Canvas::getCanvasMgr() const
112 //----------------------------------------------------------------------------
113 bool Canvas::isInit() const
115 return _texture.serviceable();
118 //----------------------------------------------------------------------------
119 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
121 if( canvas.expired() )
127 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
128 "got an expired parent!"
133 _parent_canvases.insert(canvas);
136 //----------------------------------------------------------------------------
137 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
139 if( canvas.expired() )
145 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
146 " got an expired child!"
151 _child_canvases.insert(canvas);
154 //----------------------------------------------------------------------------
155 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
157 _parent_canvases.erase(canvas);
160 //----------------------------------------------------------------------------
161 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
163 _child_canvases.erase(canvas);
166 //----------------------------------------------------------------------------
167 GroupPtr Canvas::createGroup(const std::string& name)
169 return _root_group->createChild<Group>(name);
172 //----------------------------------------------------------------------------
173 GroupPtr Canvas::getGroup(const std::string& name)
175 return _root_group->getChild<Group>(name);
178 //----------------------------------------------------------------------------
179 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
181 return _root_group->getOrCreateChild<Group>(name);
184 //----------------------------------------------------------------------------
185 GroupPtr Canvas::getRootGroup()
190 //----------------------------------------------------------------------------
191 void Canvas::enableRendering(bool force)
195 _render_dirty = true;
198 //----------------------------------------------------------------------------
199 void Canvas::update(double delta_time_sec)
201 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
202 || (_status & CREATE_FAILED) )
205 if( _status == STATUS_DIRTY )
207 _texture.setSize(_size_x, _size_y);
209 if( !_texture.serviceable() )
211 _texture.useImageCoords(true);
212 _texture.useStencil(true);
213 _texture.allocRT(/*_camera_callback*/);
217 // Resizing causes a new texture to be created so we need to reapply all
218 // existing placements
222 osg::Camera* camera = _texture.getCamera();
224 // TODO Allow custom render order? For now just keep in order with
226 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
228 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
229 parseColor(_node->getStringValue("background"), clear_color);
230 camera->setClearColor(clear_color);
232 camera->addChild(_root_group->getMatrixTransform());
234 if( _texture.serviceable() )
236 setStatusFlags(STATUS_OK);
237 setStatusFlags(STATUS_DIRTY, false);
238 _render_dirty = true;
242 setStatusFlags(CREATE_FAILED);
247 if( _visible || _render_always )
249 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
251 // TODO should we check if the image the child canvas is displayed
252 // within is really visible?
253 if( !canvas.expired() )
254 canvas.lock()->_visible = true;
259 // Also mark all canvases this canvas is displayed within as dirty
260 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
262 if( !canvas.expired() )
263 canvas.lock()->_render_dirty = true;
267 _texture.setRender(_render_dirty);
269 _render_dirty = false;
273 _texture.setRender(false);
275 _root_group->update(delta_time_sec);
277 if( _sampling_dirty )
279 _texture.setSampling(
280 _node->getBoolValue("mipmapping"),
281 _node->getIntValue("coverage-samples"),
282 _node->getIntValue("color-samples")
284 _sampling_dirty = false;
285 _render_dirty = true;
288 while( !_dirty_placements.empty() )
290 SGPropertyNode *node = _dirty_placements.back();
291 _dirty_placements.pop_back();
293 if( node->getIndex() >= static_cast<int>(_placements.size()) )
295 _placements.resize(node->getIndex() + 1);
297 // Remove possibly existing placements
298 _placements[ node->getIndex() ].clear();
300 // Get new placements
301 PlacementFactoryMap::const_iterator placement_factory =
302 _placement_factories.find( node->getStringValue("type", "object") );
303 if( placement_factory != _placement_factories.end() )
305 Placements& placements = _placements[ node->getIndex() ] =
306 placement_factory->second
309 boost::static_pointer_cast<Canvas>(_self.lock())
314 placements.empty() ? "No match" : "Ok"
318 node->setStringValue("status-msg", "Unknown placement type");
322 //----------------------------------------------------------------------------
323 bool Canvas::addEventListener( const std::string& type,
324 const EventListener& cb )
326 if( !_root_group.get() )
327 throw std::runtime_error("Canvas::AddEventListener: no root group!");
329 return _root_group->addEventListener(type, cb);
332 //----------------------------------------------------------------------------
333 void Canvas::setSizeX(int sx)
338 setStatusFlags(STATUS_DIRTY);
341 setStatusFlags(MISSING_SIZE_X);
343 setStatusFlags(MISSING_SIZE_X, false);
345 // reset flag to allow creation with new size
346 setStatusFlags(CREATE_FAILED, false);
349 //----------------------------------------------------------------------------
350 void Canvas::setSizeY(int sy)
355 setStatusFlags(STATUS_DIRTY);
358 setStatusFlags(MISSING_SIZE_Y);
360 setStatusFlags(MISSING_SIZE_Y, false);
362 // reset flag to allow creation with new size
363 setStatusFlags(CREATE_FAILED, false);
366 //----------------------------------------------------------------------------
367 int Canvas::getSizeX() const
372 //----------------------------------------------------------------------------
373 int Canvas::getSizeY() const
378 //----------------------------------------------------------------------------
379 void Canvas::setViewWidth(int w)
381 if( _view_width == w )
385 _texture.setViewSize(_view_width, _view_height);
388 //----------------------------------------------------------------------------
389 void Canvas::setViewHeight(int h)
391 if( _view_height == h )
395 _texture.setViewSize(_view_width, _view_height);
398 //----------------------------------------------------------------------------
399 int Canvas::getViewWidth() const
401 return _texture.getViewSize().x();
404 //----------------------------------------------------------------------------
405 int Canvas::getViewHeight() const
407 return _texture.getViewSize().y();
410 //----------------------------------------------------------------------------
411 SGRect<int> Canvas::getViewport() const
413 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
416 //----------------------------------------------------------------------------
417 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
419 if( !_root_group.get() )
422 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
423 event->getClientPos(),
426 if( !_root_group->accept(visitor) )
429 return _event_manager->handleEvent(event, visitor.getPropagationPath());
432 //----------------------------------------------------------------------------
433 void Canvas::childAdded( SGPropertyNode * parent,
434 SGPropertyNode * child )
436 if( parent != _node )
439 if( child->getNameString() == "placement" )
440 _dirty_placements.push_back(child);
441 else if( _root_group.get() )
442 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
445 //----------------------------------------------------------------------------
446 void Canvas::childRemoved( SGPropertyNode * parent,
447 SGPropertyNode * child )
449 _render_dirty = true;
451 if( parent != _node )
454 if( child->getNameString() == "placement" )
455 _placements[ child->getIndex() ].clear();
456 else if( _root_group.get() )
457 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
460 //----------------------------------------------------------------------------
461 void Canvas::valueChanged(SGPropertyNode* node)
463 if( boost::starts_with(node->getNameString(), "status")
464 || node->getParent()->getNameString() == "bounding-box" )
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 factor for type " << type
594 _placement_factories[type] = factory;
597 //----------------------------------------------------------------------------
598 void Canvas::setSelf(const PropertyBasedElementPtr& self)
600 PropertyBasedElement::setSelf(self);
602 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
604 _root_group.reset( new Group(canvas, _node) );
605 _root_group->setSelf(_root_group);
607 // Remove automatically created property listener as we forward them on our
609 _root_group->removeListener();
611 _cull_callback = new CullCallback(canvas);
614 //----------------------------------------------------------------------------
615 void Canvas::setStatusFlags(unsigned int flags, bool set)
622 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
623 _status_msg = "Missing size";
624 else if( _status & MISSING_SIZE_X )
625 _status_msg = "Missing size-x";
626 else if( _status & MISSING_SIZE_Y )
627 _status_msg = "Missing size-y";
628 else if( _status & CREATE_FAILED )
629 _status_msg = "Creating render target failed";
630 else if( _status == STATUS_DIRTY )
631 _status_msg = "Creation pending...";
636 //----------------------------------------------------------------------------
637 Canvas::PlacementFactoryMap Canvas::_placement_factories;
639 } // namespace canvas
640 } // namespace simgear