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()
118 _root_group->clearEventListener();
120 // TODO check if really not in use anymore
121 getProps()->getParent()
122 ->removeChild( getProps()->getName(),
123 getProps()->getIndex(),
127 //----------------------------------------------------------------------------
128 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
130 if( canvas.expired() )
136 "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
141 _parent_canvases.insert(canvas);
144 //----------------------------------------------------------------------------
145 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
147 if( canvas.expired() )
153 "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
158 _child_canvases.insert(canvas);
161 //----------------------------------------------------------------------------
162 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
164 _parent_canvases.erase(canvas);
167 //----------------------------------------------------------------------------
168 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
170 _child_canvases.erase(canvas);
173 //----------------------------------------------------------------------------
174 GroupPtr Canvas::createGroup(const std::string& name)
176 return boost::dynamic_pointer_cast<Group>
178 _root_group->createChild("group", name)
182 //----------------------------------------------------------------------------
183 GroupPtr Canvas::getGroup(const std::string& name)
185 return boost::dynamic_pointer_cast<Group>
187 _root_group->getChild(name)
191 //----------------------------------------------------------------------------
192 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
194 GroupPtr group = getGroup(name);
198 return createGroup(name);
201 //----------------------------------------------------------------------------
202 GroupPtr Canvas::getRootGroup()
207 //----------------------------------------------------------------------------
208 void Canvas::enableRendering(bool force)
212 _render_dirty = true;
215 //----------------------------------------------------------------------------
216 void Canvas::update(double delta_time_sec)
218 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
219 || (_status & CREATE_FAILED) )
222 if( _status == STATUS_DIRTY )
224 _texture.setSize(_size_x, _size_y);
226 if( !_texture.serviceable() )
228 _texture.useImageCoords(true);
229 _texture.useStencil(true);
230 _texture.allocRT(/*_camera_callback*/);
234 // Resizing causes a new texture to be created so we need to reapply all
235 // existing placements
239 osg::Camera* camera = _texture.getCamera();
241 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
242 parseColor(_node->getStringValue("background"), clear_color);
243 camera->setClearColor(clear_color);
245 camera->addChild(_root_group->getMatrixTransform());
247 // Ensure objects are drawn in order of traversal
248 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
250 if( _texture.serviceable() )
252 setStatusFlags(STATUS_OK);
253 setStatusFlags(STATUS_DIRTY, false);
254 _render_dirty = true;
258 setStatusFlags(CREATE_FAILED);
263 if( _visible || _render_always )
265 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
267 // TODO should we check if the image the child canvas is displayed
268 // within is really visible?
269 if( !canvas.expired() )
270 canvas.lock()->_visible = true;
275 // Also mark all canvases this canvas is displayed within as dirty
276 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
278 if( !canvas.expired() )
279 canvas.lock()->_render_dirty = true;
283 _texture.setRender(_render_dirty);
285 _render_dirty = false;
289 _texture.setRender(false);
291 _root_group->update(delta_time_sec);
293 if( _sampling_dirty )
295 _texture.setSampling(
296 _node->getBoolValue("mipmapping"),
297 _node->getIntValue("coverage-samples"),
298 _node->getIntValue("color-samples")
300 _sampling_dirty = false;
301 _render_dirty = true;
304 while( !_dirty_placements.empty() )
306 SGPropertyNode *node = _dirty_placements.back();
307 _dirty_placements.pop_back();
309 if( node->getIndex() >= static_cast<int>(_placements.size()) )
311 _placements.resize(node->getIndex() + 1);
313 // Remove possibly existing placements
314 _placements[ node->getIndex() ].clear();
316 // Get new placements
317 PlacementFactoryMap::const_iterator placement_factory =
318 _placement_factories.find( node->getStringValue("type", "object") );
319 if( placement_factory != _placement_factories.end() )
321 Placements& placements = _placements[ node->getIndex() ] =
322 placement_factory->second
325 boost::static_pointer_cast<Canvas>(_self.lock())
330 placements.empty() ? "No match" : "Ok"
334 node->setStringValue("status-msg", "Unknown placement type");
338 //----------------------------------------------------------------------------
339 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
341 if( !_root_group.get() )
342 naRuntimeError(ctx.c, "Canvas: No root group!");
344 return _root_group->addEventListener(ctx);
347 //----------------------------------------------------------------------------
348 void Canvas::setSizeX(int sx)
353 setStatusFlags(STATUS_DIRTY);
356 setStatusFlags(MISSING_SIZE_X);
358 setStatusFlags(MISSING_SIZE_X, false);
360 // reset flag to allow creation with new size
361 setStatusFlags(CREATE_FAILED, false);
364 //----------------------------------------------------------------------------
365 void Canvas::setSizeY(int sy)
370 setStatusFlags(STATUS_DIRTY);
373 setStatusFlags(MISSING_SIZE_Y);
375 setStatusFlags(MISSING_SIZE_Y, false);
377 // reset flag to allow creation with new size
378 setStatusFlags(CREATE_FAILED, false);
381 //----------------------------------------------------------------------------
382 int Canvas::getSizeX() const
387 //----------------------------------------------------------------------------
388 int Canvas::getSizeY() const
393 //----------------------------------------------------------------------------
394 void Canvas::setViewWidth(int w)
396 if( _view_width == w )
400 _texture.setViewSize(_view_width, _view_height);
403 //----------------------------------------------------------------------------
404 void Canvas::setViewHeight(int h)
406 if( _view_height == h )
410 _texture.setViewSize(_view_width, _view_height);
413 //----------------------------------------------------------------------------
414 int Canvas::getViewWidth() const
416 return _texture.getViewSize().x();
419 //----------------------------------------------------------------------------
420 int Canvas::getViewHeight() const
422 return _texture.getViewSize().y();
425 //----------------------------------------------------------------------------
426 SGRect<int> Canvas::getViewport() const
428 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
431 //----------------------------------------------------------------------------
432 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
434 if( !_root_group.get() )
437 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
438 event->getClientPos(),
440 if( !_root_group->accept(visitor) )
443 return _event_manager->handleEvent(event, visitor.getPropagationPath());
446 //----------------------------------------------------------------------------
447 void Canvas::childAdded( SGPropertyNode * parent,
448 SGPropertyNode * child )
450 if( parent != _node )
453 if( child->getNameString() == "placement" )
454 _dirty_placements.push_back(child);
455 else if( _root_group.get() )
456 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
459 //----------------------------------------------------------------------------
460 void Canvas::childRemoved( SGPropertyNode * parent,
461 SGPropertyNode * child )
463 _render_dirty = true;
465 if( parent != _node )
468 if( child->getNameString() == "placement" )
469 _placements[ child->getIndex() ].clear();
470 else if( _root_group.get() )
471 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
474 //----------------------------------------------------------------------------
475 void Canvas::valueChanged(SGPropertyNode* node)
477 if( boost::starts_with(node->getNameString(), "status")
478 || node->getParent()->getNameString() == "bounding-box" )
480 _render_dirty = true;
483 if( node->getParent()->getParent() == _node
484 && node->getParent()->getNameString() == "placement" )
486 bool placement_dirty = false;
487 BOOST_FOREACH(Placements& placements, _placements)
489 BOOST_FOREACH(PlacementPtr& placement, placements)
491 // check if change can be directly handled by placement
492 if( placement->getProps() == node->getParent()
493 && !placement->childChanged(node) )
494 placement_dirty = true;
498 if( !placement_dirty )
501 // prevent double updates...
502 for( size_t i = 0; i < _dirty_placements.size(); ++i )
504 if( node->getParent() == _dirty_placements[i] )
508 _dirty_placements.push_back(node->getParent());
510 else if( node->getParent() == _node )
512 if( node->getNameString() == "background" )
515 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
517 _texture.getCamera()->setClearColor(color);
518 _render_dirty = true;
521 else if( node->getNameString() == "mipmapping"
522 || node->getNameString() == "coverage-samples"
523 || node->getNameString() == "color-samples" )
525 _sampling_dirty = true;
527 else if( node->getNameString() == "additive-blend" )
529 _texture.useAdditiveBlend( node->getBoolValue() );
531 else if( node->getNameString() == "render-always" )
533 _render_always = node->getBoolValue();
535 else if( node->getNameString() == "size" )
537 if( node->getIndex() == 0 )
538 setSizeX( node->getIntValue() );
539 else if( node->getIndex() == 1 )
540 setSizeY( node->getIntValue() );
542 else if( node->getNameString() == "view" )
544 if( node->getIndex() == 0 )
545 setViewWidth( node->getIntValue() );
546 else if( node->getIndex() == 1 )
547 setViewHeight( node->getIntValue() );
549 else if( node->getNameString() == "freeze" )
550 _texture.setRender( node->getBoolValue() );
557 if( !handled && _root_group.get() )
558 _root_group->valueChanged(node);
561 //----------------------------------------------------------------------------
562 osg::Texture2D* Canvas::getTexture() const
564 return _texture.getTexture();
567 //----------------------------------------------------------------------------
568 Canvas::CullCallbackPtr Canvas::getCullCallback() const
570 return _cull_callback;
573 //----------------------------------------------------------------------------
574 void Canvas::reloadPlacements(const std::string& type)
576 for(size_t i = 0; i < _placements.size(); ++i)
578 if( _placements[i].empty() )
581 SGPropertyNode* child = _placements[i].front()->getProps();
583 // reload if type matches or no type specified
584 || child->getStringValue("type", type.c_str()) == type )
586 _dirty_placements.push_back(child);
591 //----------------------------------------------------------------------------
592 void Canvas::addPlacementFactory( const std::string& type,
593 PlacementFactory factory )
595 if( _placement_factories.find(type) != _placement_factories.end() )
600 "Canvas::addPlacementFactory: replace existing factor for type " << type
603 _placement_factories[type] = factory;
606 //----------------------------------------------------------------------------
607 void Canvas::setSelf(const PropertyBasedElementPtr& self)
609 PropertyBasedElement::setSelf(self);
611 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
613 _root_group.reset( new Group(canvas, _node) );
614 _root_group->setSelf(_root_group);
616 // Remove automatically created property listener as we forward them on our
618 _root_group->removeListener();
620 _cull_callback = new CullCallback(canvas);
623 //----------------------------------------------------------------------------
624 void Canvas::setStatusFlags(unsigned int flags, bool set)
631 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
632 _status_msg = "Missing size";
633 else if( _status & MISSING_SIZE_X )
634 _status_msg = "Missing size-x";
635 else if( _status & MISSING_SIZE_Y )
636 _status_msg = "Missing size-y";
637 else if( _status & CREATE_FAILED )
638 _status_msg = "Creating render target failed";
639 else if( _status == STATUS_DIRTY )
640 _status_msg = "Creation pending...";
645 //----------------------------------------------------------------------------
646 Canvas::PlacementFactoryMap Canvas::_placement_factories;
648 } // namespace canvas
649 } // namespace simgear