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 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
225 parseColor(_node->getStringValue("background"), clear_color);
226 camera->setClearColor(clear_color);
228 camera->addChild(_root_group->getMatrixTransform());
230 if( _texture.serviceable() )
232 setStatusFlags(STATUS_OK);
233 setStatusFlags(STATUS_DIRTY, false);
234 _render_dirty = true;
238 setStatusFlags(CREATE_FAILED);
243 if( _visible || _render_always )
245 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
247 // TODO should we check if the image the child canvas is displayed
248 // within is really visible?
249 if( !canvas.expired() )
250 canvas.lock()->_visible = true;
255 // Also mark all canvases this canvas is displayed within as dirty
256 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
258 if( !canvas.expired() )
259 canvas.lock()->_render_dirty = true;
263 _texture.setRender(_render_dirty);
265 _render_dirty = false;
269 _texture.setRender(false);
271 _root_group->update(delta_time_sec);
273 if( _sampling_dirty )
275 _texture.setSampling(
276 _node->getBoolValue("mipmapping"),
277 _node->getIntValue("coverage-samples"),
278 _node->getIntValue("color-samples")
280 _sampling_dirty = false;
281 _render_dirty = true;
284 while( !_dirty_placements.empty() )
286 SGPropertyNode *node = _dirty_placements.back();
287 _dirty_placements.pop_back();
289 if( node->getIndex() >= static_cast<int>(_placements.size()) )
291 _placements.resize(node->getIndex() + 1);
293 // Remove possibly existing placements
294 _placements[ node->getIndex() ].clear();
296 // Get new placements
297 PlacementFactoryMap::const_iterator placement_factory =
298 _placement_factories.find( node->getStringValue("type", "object") );
299 if( placement_factory != _placement_factories.end() )
301 Placements& placements = _placements[ node->getIndex() ] =
302 placement_factory->second
305 boost::static_pointer_cast<Canvas>(_self.lock())
310 placements.empty() ? "No match" : "Ok"
314 node->setStringValue("status-msg", "Unknown placement type");
318 //----------------------------------------------------------------------------
319 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
321 if( !_root_group.get() )
322 naRuntimeError(ctx.c, "Canvas: No root group!");
324 return _root_group->addEventListener(ctx);
327 //----------------------------------------------------------------------------
328 void Canvas::setSizeX(int sx)
333 setStatusFlags(STATUS_DIRTY);
336 setStatusFlags(MISSING_SIZE_X);
338 setStatusFlags(MISSING_SIZE_X, false);
340 // reset flag to allow creation with new size
341 setStatusFlags(CREATE_FAILED, false);
344 //----------------------------------------------------------------------------
345 void Canvas::setSizeY(int sy)
350 setStatusFlags(STATUS_DIRTY);
353 setStatusFlags(MISSING_SIZE_Y);
355 setStatusFlags(MISSING_SIZE_Y, false);
357 // reset flag to allow creation with new size
358 setStatusFlags(CREATE_FAILED, false);
361 //----------------------------------------------------------------------------
362 int Canvas::getSizeX() const
367 //----------------------------------------------------------------------------
368 int Canvas::getSizeY() const
373 //----------------------------------------------------------------------------
374 void Canvas::setViewWidth(int w)
376 if( _view_width == w )
380 _texture.setViewSize(_view_width, _view_height);
383 //----------------------------------------------------------------------------
384 void Canvas::setViewHeight(int h)
386 if( _view_height == h )
390 _texture.setViewSize(_view_width, _view_height);
393 //----------------------------------------------------------------------------
394 int Canvas::getViewWidth() const
396 return _texture.getViewSize().x();
399 //----------------------------------------------------------------------------
400 int Canvas::getViewHeight() const
402 return _texture.getViewSize().y();
405 //----------------------------------------------------------------------------
406 SGRect<int> Canvas::getViewport() const
408 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
411 //----------------------------------------------------------------------------
412 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
414 if( !_root_group.get() )
417 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
418 event->getClientPos(),
421 if( !_root_group->accept(visitor) )
424 return _event_manager->handleEvent(event, visitor.getPropagationPath());
427 //----------------------------------------------------------------------------
428 void Canvas::childAdded( SGPropertyNode * parent,
429 SGPropertyNode * child )
431 if( parent != _node )
434 if( child->getNameString() == "placement" )
435 _dirty_placements.push_back(child);
436 else if( _root_group.get() )
437 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
440 //----------------------------------------------------------------------------
441 void Canvas::childRemoved( SGPropertyNode * parent,
442 SGPropertyNode * child )
444 _render_dirty = true;
446 if( parent != _node )
449 if( child->getNameString() == "placement" )
450 _placements[ child->getIndex() ].clear();
451 else if( _root_group.get() )
452 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
455 //----------------------------------------------------------------------------
456 void Canvas::valueChanged(SGPropertyNode* node)
458 if( boost::starts_with(node->getNameString(), "status")
459 || node->getParent()->getNameString() == "bounding-box" )
461 _render_dirty = true;
464 if( node->getParent()->getParent() == _node
465 && node->getParent()->getNameString() == "placement" )
467 size_t index = node->getIndex();
468 if( index < _placements.size() )
470 Placements& placements = _placements[index];
471 if( !placements.empty() )
473 bool placement_dirty = false;
474 BOOST_FOREACH(PlacementPtr& placement, placements)
476 // check if change can be directly handled by placement
477 if( placement->getProps() == node->getParent()
478 && !placement->childChanged(node) )
479 placement_dirty = true;
482 if( !placement_dirty )
487 // prevent double updates...
488 for( size_t i = 0; i < _dirty_placements.size(); ++i )
490 if( node->getParent() == _dirty_placements[i] )
494 _dirty_placements.push_back(node->getParent());
496 else if( node->getParent() == _node )
498 if( node->getNameString() == "background" )
501 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
503 _texture.getCamera()->setClearColor(color);
504 _render_dirty = true;
507 else if( node->getNameString() == "mipmapping"
508 || node->getNameString() == "coverage-samples"
509 || node->getNameString() == "color-samples" )
511 _sampling_dirty = true;
513 else if( node->getNameString() == "additive-blend" )
515 _texture.useAdditiveBlend( node->getBoolValue() );
517 else if( node->getNameString() == "render-always" )
519 _render_always = node->getBoolValue();
521 else if( node->getNameString() == "size" )
523 if( node->getIndex() == 0 )
524 setSizeX( node->getIntValue() );
525 else if( node->getIndex() == 1 )
526 setSizeY( node->getIntValue() );
528 else if( node->getNameString() == "view" )
530 if( node->getIndex() == 0 )
531 setViewWidth( node->getIntValue() );
532 else if( node->getIndex() == 1 )
533 setViewHeight( node->getIntValue() );
535 else if( node->getNameString() == "freeze" )
536 _texture.setRender( node->getBoolValue() );
543 if( !handled && _root_group.get() )
544 _root_group->valueChanged(node);
547 //----------------------------------------------------------------------------
548 osg::Texture2D* Canvas::getTexture() const
550 return _texture.getTexture();
553 //----------------------------------------------------------------------------
554 Canvas::CullCallbackPtr Canvas::getCullCallback() const
556 return _cull_callback;
559 //----------------------------------------------------------------------------
560 void Canvas::reloadPlacements(const std::string& type)
562 for(size_t i = 0; i < _placements.size(); ++i)
564 if( _placements[i].empty() )
567 SGPropertyNode* child = _placements[i].front()->getProps();
569 // reload if type matches or no type specified
570 || child->getStringValue("type", type.c_str()) == type )
572 _dirty_placements.push_back(child);
577 //----------------------------------------------------------------------------
578 void Canvas::addPlacementFactory( const std::string& type,
579 PlacementFactory factory )
581 if( _placement_factories.find(type) != _placement_factories.end() )
586 "Canvas::addPlacementFactory: replace existing factor for type " << type
589 _placement_factories[type] = factory;
592 //----------------------------------------------------------------------------
593 void Canvas::setSelf(const PropertyBasedElementPtr& self)
595 PropertyBasedElement::setSelf(self);
597 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
599 _root_group.reset( new Group(canvas, _node) );
600 _root_group->setSelf(_root_group);
602 // Remove automatically created property listener as we forward them on our
604 _root_group->removeListener();
606 _cull_callback = new CullCallback(canvas);
609 //----------------------------------------------------------------------------
610 void Canvas::setStatusFlags(unsigned int flags, bool set)
617 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
618 _status_msg = "Missing size";
619 else if( _status & MISSING_SIZE_X )
620 _status_msg = "Missing size-x";
621 else if( _status & MISSING_SIZE_Y )
622 _status_msg = "Missing size-y";
623 else if( _status & CREATE_FAILED )
624 _status_msg = "Creating render target failed";
625 else if( _status == STATUS_DIRTY )
626 _status_msg = "Creation pending...";
631 //----------------------------------------------------------------------------
632 Canvas::PlacementFactoryMap Canvas::_placement_factories;
634 } // namespace canvas
635 } // namespace simgear