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::setSystemAdapter(const SystemAdapterPtr& system_adapter)
86 _system_adapter = system_adapter;
87 _texture.setSystemAdapter(system_adapter);
90 //----------------------------------------------------------------------------
91 SystemAdapterPtr Canvas::getSystemAdapter() const
93 return _system_adapter;
96 //----------------------------------------------------------------------------
97 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
99 _canvas_mgr = canvas_mgr;
102 //----------------------------------------------------------------------------
103 CanvasMgr* Canvas::getCanvasMgr() const
108 //----------------------------------------------------------------------------
109 bool Canvas::isInit() const
111 return _texture.serviceable();
114 //----------------------------------------------------------------------------
115 void Canvas::destroy()
117 // TODO check if really not in use anymore
118 getProps()->getParent()
119 ->removeChild( getProps()->getName(),
120 getProps()->getIndex(),
124 //----------------------------------------------------------------------------
125 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
127 if( canvas.expired() )
133 "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
138 _parent_canvases.insert(canvas);
141 //----------------------------------------------------------------------------
142 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
144 if( canvas.expired() )
150 "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
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 boost::dynamic_pointer_cast<Group>
175 _root_group->createChild("group", name)
179 //----------------------------------------------------------------------------
180 GroupPtr Canvas::getGroup(const std::string& name)
182 return boost::dynamic_pointer_cast<Group>
184 _root_group->getChild(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 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 // Ensure objects are drawn in order of traversal
235 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
237 if( _texture.serviceable() )
239 setStatusFlags(STATUS_OK);
240 setStatusFlags(STATUS_DIRTY, false);
241 _render_dirty = true;
245 setStatusFlags(CREATE_FAILED);
250 if( _visible || _render_always )
252 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
254 // TODO should we check if the image the child canvas is displayed
255 // within is really visible?
256 if( !canvas.expired() )
257 canvas.lock()->_visible = true;
262 // Also mark all canvases this canvas is displayed within as dirty
263 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
265 if( !canvas.expired() )
266 canvas.lock()->_render_dirty = true;
270 _texture.setRender(_render_dirty);
272 _render_dirty = false;
276 _texture.setRender(false);
278 _root_group->update(delta_time_sec);
280 if( _sampling_dirty )
282 _texture.setSampling(
283 _node->getBoolValue("mipmapping"),
284 _node->getIntValue("coverage-samples"),
285 _node->getIntValue("color-samples")
287 _sampling_dirty = false;
288 _render_dirty = true;
291 while( !_dirty_placements.empty() )
293 SGPropertyNode *node = _dirty_placements.back();
294 _dirty_placements.pop_back();
296 if( node->getIndex() >= static_cast<int>(_placements.size()) )
298 _placements.resize(node->getIndex() + 1);
300 // Remove possibly existing placements
301 _placements[ node->getIndex() ].clear();
303 // Get new placements
304 PlacementFactoryMap::const_iterator placement_factory =
305 _placement_factories.find( node->getStringValue("type", "object") );
306 if( placement_factory != _placement_factories.end() )
308 Placements& placements = _placements[ node->getIndex() ] =
309 placement_factory->second
312 boost::static_pointer_cast<Canvas>(_self.lock())
317 placements.empty() ? "No match" : "Ok"
321 node->setStringValue("status-msg", "Unknown placement type");
325 //----------------------------------------------------------------------------
326 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
328 if( !_root_group.get() )
329 naRuntimeError(ctx.c, "Canvas: No root group!");
331 return _root_group->addEventListener(ctx);
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")
465 || node->getParent()->getNameString() == "bounding-box" )
467 _render_dirty = true;
470 if( node->getParent()->getParent() == _node
471 && node->getParent()->getNameString() == "placement" )
473 bool placement_dirty = false;
474 BOOST_FOREACH(Placements& placements, _placements)
476 BOOST_FOREACH(PlacementPtr& placement, placements)
478 // check if change can be directly handled by placement
479 if( placement->getProps() == node->getParent()
480 && !placement->childChanged(node) )
481 placement_dirty = true;
485 if( !placement_dirty )
488 // prevent double updates...
489 for( size_t i = 0; i < _dirty_placements.size(); ++i )
491 if( node->getParent() == _dirty_placements[i] )
495 _dirty_placements.push_back(node->getParent());
497 else if( node->getParent() == _node )
499 if( node->getNameString() == "background" )
502 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
504 _texture.getCamera()->setClearColor(color);
505 _render_dirty = true;
508 else if( node->getNameString() == "mipmapping"
509 || node->getNameString() == "coverage-samples"
510 || node->getNameString() == "color-samples" )
512 _sampling_dirty = true;
514 else if( node->getNameString() == "additive-blend" )
516 _texture.useAdditiveBlend( node->getBoolValue() );
518 else if( node->getNameString() == "render-always" )
520 _render_always = node->getBoolValue();
522 else if( node->getNameString() == "size" )
524 if( node->getIndex() == 0 )
525 setSizeX( node->getIntValue() );
526 else if( node->getIndex() == 1 )
527 setSizeY( node->getIntValue() );
529 else if( node->getNameString() == "view" )
531 if( node->getIndex() == 0 )
532 setViewWidth( node->getIntValue() );
533 else if( node->getIndex() == 1 )
534 setViewHeight( node->getIntValue() );
536 else if( node->getNameString() == "freeze" )
537 _texture.setRender( node->getBoolValue() );
544 if( !handled && _root_group.get() )
545 _root_group->valueChanged(node);
548 //----------------------------------------------------------------------------
549 osg::Texture2D* Canvas::getTexture() const
551 return _texture.getTexture();
554 //----------------------------------------------------------------------------
555 Canvas::CullCallbackPtr Canvas::getCullCallback() const
557 return _cull_callback;
560 //----------------------------------------------------------------------------
561 void Canvas::reloadPlacements(const std::string& type)
563 for(size_t i = 0; i < _placements.size(); ++i)
565 if( _placements[i].empty() )
568 SGPropertyNode* child = _placements[i].front()->getProps();
570 // reload if type matches or no type specified
571 || child->getStringValue("type", type.c_str()) == type )
573 _dirty_placements.push_back(child);
578 //----------------------------------------------------------------------------
579 void Canvas::addPlacementFactory( const std::string& type,
580 PlacementFactory factory )
582 if( _placement_factories.find(type) != _placement_factories.end() )
587 "Canvas::addPlacementFactory: replace existing factor for type " << type
590 _placement_factories[type] = factory;
593 //----------------------------------------------------------------------------
594 void Canvas::setSelf(const PropertyBasedElementPtr& self)
596 PropertyBasedElement::setSelf(self);
598 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
600 _root_group.reset( new Group(canvas, _node) );
601 _root_group->setSelf(_root_group);
603 // Remove automatically created property listener as we forward them on our
605 _root_group->removeListener();
607 _cull_callback = new CullCallback(canvas);
610 //----------------------------------------------------------------------------
611 void Canvas::setStatusFlags(unsigned int flags, bool set)
618 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
619 _status_msg = "Missing size";
620 else if( _status & MISSING_SIZE_X )
621 _status_msg = "Missing size-x";
622 else if( _status & MISSING_SIZE_Y )
623 _status_msg = "Missing size-y";
624 else if( _status & CREATE_FAILED )
625 _status_msg = "Creating render target failed";
626 else if( _status == STATUS_DIRTY )
627 _status_msg = "Creation pending...";
632 //----------------------------------------------------------------------------
633 Canvas::PlacementFactoryMap Canvas::_placement_factories;
635 } // namespace canvas
636 } // namespace simgear