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::setSystemAdapter(const SystemAdapterPtr& system_adapter)
96 _system_adapter = system_adapter;
97 _texture.setSystemAdapter(system_adapter);
100 //----------------------------------------------------------------------------
101 SystemAdapterPtr Canvas::getSystemAdapter() const
103 return _system_adapter;
106 //----------------------------------------------------------------------------
107 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
109 _canvas_mgr = canvas_mgr;
112 //----------------------------------------------------------------------------
113 CanvasMgr* Canvas::getCanvasMgr() const
118 //----------------------------------------------------------------------------
119 bool Canvas::isInit() const
121 return _texture.serviceable();
124 //----------------------------------------------------------------------------
125 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
127 if( canvas.expired() )
133 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
134 "got an expired parent!"
139 _parent_canvases.insert(canvas);
142 //----------------------------------------------------------------------------
143 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
145 if( canvas.expired() )
151 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
152 " got an expired child!"
157 _child_canvases.insert(canvas);
160 //----------------------------------------------------------------------------
161 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
163 _parent_canvases.erase(canvas);
166 //----------------------------------------------------------------------------
167 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
169 _child_canvases.erase(canvas);
172 //----------------------------------------------------------------------------
173 GroupPtr Canvas::createGroup(const std::string& name)
175 return _root_group->createChild<Group>(name);
178 //----------------------------------------------------------------------------
179 GroupPtr Canvas::getGroup(const std::string& name)
181 return _root_group->getChild<Group>(name);
184 //----------------------------------------------------------------------------
185 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
187 return _root_group->getOrCreateChild<Group>(name);
190 //----------------------------------------------------------------------------
191 GroupPtr Canvas::getRootGroup()
196 //----------------------------------------------------------------------------
197 void Canvas::enableRendering(bool force)
201 _render_dirty = true;
204 //----------------------------------------------------------------------------
205 void Canvas::update(double delta_time_sec)
207 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
208 || (_status & CREATE_FAILED) )
211 if( _status == STATUS_DIRTY )
213 _texture.setSize(_size_x, _size_y);
215 if( !_texture.serviceable() )
217 _texture.useImageCoords(true);
218 _texture.useStencil(true);
219 _texture.allocRT(/*_camera_callback*/);
223 // Resizing causes a new texture to be created so we need to reapply all
224 // existing placements
228 osg::Camera* camera = _texture.getCamera();
230 // TODO Allow custom render order? For now just keep in order with
232 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
234 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
235 parseColor(_node->getStringValue("background"), clear_color);
236 camera->setClearColor(clear_color);
238 camera->addChild(_root_group->getMatrixTransform());
240 if( _texture.serviceable() )
242 setStatusFlags(STATUS_OK);
243 setStatusFlags(STATUS_DIRTY, false);
244 _render_dirty = true;
248 setStatusFlags(CREATE_FAILED);
253 if( _visible || _render_always )
255 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
257 // TODO should we check if the image the child canvas is displayed
258 // within is really visible?
259 if( !canvas.expired() )
260 canvas.lock()->_visible = true;
265 // Also mark all canvases this canvas is displayed within as dirty
266 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
268 if( !canvas.expired() )
269 canvas.lock()->_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
315 boost::static_pointer_cast<Canvas>(_self.lock())
320 placements.empty() ? "No match" : "Ok"
324 node->setStringValue("status-msg", "Unknown placement type");
328 //----------------------------------------------------------------------------
329 bool Canvas::addEventListener( const std::string& type,
330 const EventListener& cb )
332 if( !_root_group.get() )
333 throw std::runtime_error("Canvas::AddEventListener: no root group!");
335 return _root_group->addEventListener(type, cb);
338 //----------------------------------------------------------------------------
339 void Canvas::setSizeX(int sx)
344 setStatusFlags(STATUS_DIRTY);
347 setStatusFlags(MISSING_SIZE_X);
349 setStatusFlags(MISSING_SIZE_X, false);
351 // reset flag to allow creation with new size
352 setStatusFlags(CREATE_FAILED, false);
355 //----------------------------------------------------------------------------
356 void Canvas::setSizeY(int sy)
361 setStatusFlags(STATUS_DIRTY);
364 setStatusFlags(MISSING_SIZE_Y);
366 setStatusFlags(MISSING_SIZE_Y, false);
368 // reset flag to allow creation with new size
369 setStatusFlags(CREATE_FAILED, false);
372 //----------------------------------------------------------------------------
373 int Canvas::getSizeX() const
378 //----------------------------------------------------------------------------
379 int Canvas::getSizeY() const
384 //----------------------------------------------------------------------------
385 void Canvas::setViewWidth(int w)
387 if( _view_width == w )
391 _texture.setViewSize(_view_width, _view_height);
394 //----------------------------------------------------------------------------
395 void Canvas::setViewHeight(int h)
397 if( _view_height == h )
401 _texture.setViewSize(_view_width, _view_height);
404 //----------------------------------------------------------------------------
405 int Canvas::getViewWidth() const
407 return _texture.getViewSize().x();
410 //----------------------------------------------------------------------------
411 int Canvas::getViewHeight() const
413 return _texture.getViewSize().y();
416 //----------------------------------------------------------------------------
417 SGRect<int> Canvas::getViewport() const
419 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
422 //----------------------------------------------------------------------------
423 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
425 if( !_root_group.get() )
428 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
429 event->getClientPos(),
432 if( !_root_group->accept(visitor) )
435 return _event_manager->handleEvent(event, visitor.getPropagationPath());
438 //----------------------------------------------------------------------------
439 void Canvas::childAdded( SGPropertyNode * parent,
440 SGPropertyNode * child )
442 if( parent != _node )
445 if( child->getNameString() == "placement" )
446 _dirty_placements.push_back(child);
447 else if( _root_group.get() )
448 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
451 //----------------------------------------------------------------------------
452 void Canvas::childRemoved( SGPropertyNode * parent,
453 SGPropertyNode * child )
455 _render_dirty = true;
457 if( parent != _node )
460 if( child->getNameString() == "placement" )
461 _placements[ child->getIndex() ].clear();
462 else if( _root_group.get() )
463 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
466 //----------------------------------------------------------------------------
467 void Canvas::valueChanged(SGPropertyNode* node)
469 if( boost::starts_with(node->getNameString(), "status")
470 || node->getParent()->getNameString() == "bounding-box" )
472 _render_dirty = true;
475 if( node->getParent()->getParent() == _node
476 && node->getParent()->getNameString() == "placement" )
478 size_t index = node->getIndex();
479 if( index < _placements.size() )
481 Placements& placements = _placements[index];
482 if( !placements.empty() )
484 bool placement_dirty = false;
485 BOOST_FOREACH(PlacementPtr& placement, placements)
487 // check if change can be directly handled by placement
488 if( placement->getProps() == node->getParent()
489 && !placement->childChanged(node) )
490 placement_dirty = true;
493 if( !placement_dirty )
498 // prevent double updates...
499 for( size_t i = 0; i < _dirty_placements.size(); ++i )
501 if( node->getParent() == _dirty_placements[i] )
505 _dirty_placements.push_back(node->getParent());
507 else if( node->getParent() == _node )
509 if( node->getNameString() == "background" )
512 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
514 _texture.getCamera()->setClearColor(color);
515 _render_dirty = true;
518 else if( node->getNameString() == "mipmapping"
519 || node->getNameString() == "coverage-samples"
520 || node->getNameString() == "color-samples" )
522 _sampling_dirty = true;
524 else if( node->getNameString() == "additive-blend" )
526 _texture.useAdditiveBlend( node->getBoolValue() );
528 else if( node->getNameString() == "render-always" )
530 _render_always = node->getBoolValue();
532 else if( node->getNameString() == "size" )
534 if( node->getIndex() == 0 )
535 setSizeX( node->getIntValue() );
536 else if( node->getIndex() == 1 )
537 setSizeY( node->getIntValue() );
539 else if( node->getNameString() == "view" )
541 if( node->getIndex() == 0 )
542 setViewWidth( node->getIntValue() );
543 else if( node->getIndex() == 1 )
544 setViewHeight( node->getIntValue() );
546 else if( node->getNameString() == "freeze" )
547 _texture.setRender( node->getBoolValue() );
554 if( !handled && _root_group.get() )
555 _root_group->valueChanged(node);
558 //----------------------------------------------------------------------------
559 osg::Texture2D* Canvas::getTexture() const
561 return _texture.getTexture();
564 //----------------------------------------------------------------------------
565 Canvas::CullCallbackPtr Canvas::getCullCallback() const
567 return _cull_callback;
570 //----------------------------------------------------------------------------
571 void Canvas::reloadPlacements(const std::string& type)
573 for(size_t i = 0; i < _placements.size(); ++i)
575 if( _placements[i].empty() )
578 SGPropertyNode* child = _placements[i].front()->getProps();
580 // reload if type matches or no type specified
581 || child->getStringValue("type", type.c_str()) == type )
583 _dirty_placements.push_back(child);
588 //----------------------------------------------------------------------------
589 void Canvas::addPlacementFactory( const std::string& type,
590 PlacementFactory factory )
592 if( _placement_factories.find(type) != _placement_factories.end() )
597 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
600 _placement_factories[type] = factory;
603 //----------------------------------------------------------------------------
604 void Canvas::removePlacementFactory(const std::string& type)
606 PlacementFactoryMap::iterator it = _placement_factories.find(type);
607 if( it == _placement_factories.end() )
612 "Canvas::removePlacementFactory: no such factory '" << type << "'"
615 _placement_factories.erase(it);
618 //----------------------------------------------------------------------------
619 void Canvas::setSelf(const PropertyBasedElementPtr& self)
621 PropertyBasedElement::setSelf(self);
623 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
625 _root_group.reset( new Group(canvas, _node) );
626 _root_group->setSelf(_root_group);
628 // Remove automatically created property listener as we forward them on our
630 _root_group->removeListener();
632 _cull_callback = new CullCallback(canvas);
635 //----------------------------------------------------------------------------
636 void Canvas::setStatusFlags(unsigned int flags, bool set)
643 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
644 _status_msg = "Missing size";
645 else if( _status & MISSING_SIZE_X )
646 _status_msg = "Missing size-x";
647 else if( _status & MISSING_SIZE_Y )
648 _status_msg = "Missing size-y";
649 else if( _status & CREATE_FAILED )
650 _status_msg = "Creating render target failed";
651 else if( _status == STATUS_DIRTY )
652 _status_msg = "Creation pending...";
657 //----------------------------------------------------------------------------
658 Canvas::PlacementFactoryMap Canvas::_placement_factories;
660 } // namespace canvas
661 } // namespace simgear