1 // Interface for 2D Canvas element
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
19 #include "CanvasElement.hxx"
20 #include <simgear/canvas/Canvas.hxx>
21 #include <simgear/canvas/CanvasEventVisitor.hxx>
22 #include <simgear/canvas/events/MouseEvent.hxx>
23 #include <simgear/math/SGMisc.hxx>
24 #include <simgear/misc/strutils.hxx>
25 #include <simgear/scene/material/parseBlendFunc.hxx>
27 #include <osg/Drawable>
29 #include <osg/StateAttribute>
30 #include <osg/Version>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/make_shared.hpp>
44 const std::string NAME_TRANSFORM = "tf";
47 * glScissor with coordinates relative to different reference frames.
49 class Element::RelativeScissor:
50 public osg::StateAttribute
54 ReferenceFrame _coord_reference;
55 osg::observer_ptr<osg::Node> _node;
57 explicit RelativeScissor(osg::Node* node = NULL):
58 _coord_reference(GLOBAL),
68 /** Copy constructor using CopyOp to manage deep vs shallow copy. */
69 RelativeScissor( const RelativeScissor& vp,
70 const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ):
71 StateAttribute(vp, copyop),
72 _coord_reference(vp._coord_reference),
80 META_StateAttribute(simgear, RelativeScissor, SCISSOR);
82 /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
83 virtual int compare(const StateAttribute& sa) const
85 // check the types are equal and then create the rhs variable
86 // used by the COMPARE_StateAttribute_Parameter macros below.
87 COMPARE_StateAttribute_Types(RelativeScissor,sa)
89 // compare each parameter in turn against the rhs.
90 COMPARE_StateAttribute_Parameter(_x)
91 COMPARE_StateAttribute_Parameter(_y)
92 COMPARE_StateAttribute_Parameter(_width)
93 COMPARE_StateAttribute_Parameter(_height)
94 COMPARE_StateAttribute_Parameter(_coord_reference)
95 COMPARE_StateAttribute_Parameter(_node)
97 return 0; // passed all the above comparison macros, must be equal.
100 virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
102 usage.usesMode(GL_SCISSOR_TEST);
106 inline float& x() { return _x; }
107 inline float x() const { return _x; }
109 inline float& y() { return _y; }
110 inline float y() const { return _y; }
112 inline float& width() { return _width; }
113 inline float width() const { return _width; }
115 inline float& height() { return _height; }
116 inline float height() const { return _height; }
118 virtual void apply(osg::State& state) const
120 if( _width <= 0 || _height <= 0 )
123 const osg::Viewport* vp = state.getCurrentViewport();
124 float w2 = 0.5 * vp->width(),
125 h2 = 0.5 * vp->height();
127 osg::Matrix model_view
134 model_view.preMult(state.getProjectionMatrix());
136 if( _coord_reference != GLOBAL )
138 osg::Node* ref_obj = _node.get();
140 if( _coord_reference == PARENT )
142 if( _node->getNumParents() < 1 )
144 SG_LOG(SG_GL, SG_WARN, "RelativeScissor: missing parent.");
148 ref_obj = _node->getParent(0);
151 osg::MatrixList const& parent_matrices = ref_obj->getWorldMatrices();
152 assert( !parent_matrices.empty() );
153 model_view.preMult(parent_matrices.front());
156 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
157 offset(model_view(3,0), model_view(3,1));
159 // TODO check/warn for rotation?
160 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
161 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
162 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
163 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
170 glScissor(x, y, w, h);
173 bool contains(const osg::Vec2f& pos) const
175 return _x <= pos.x() && pos.x() <= _x + _width
176 && _y <= pos.y() && pos.y() <= _y + _height;
179 bool contains( const osg::Vec2f& global_pos,
180 const osg::Vec2f& parent_pos,
181 const osg::Vec2f& local_pos ) const
183 switch( _coord_reference )
185 case GLOBAL: return contains(global_pos);
186 case PARENT: return contains(parent_pos);
187 case LOCAL: return contains(local_pos);
200 //----------------------------------------------------------------------------
201 Element::OSGUserData::OSGUserData(ElementPtr element):
207 //----------------------------------------------------------------------------
210 if( !_transform.valid() )
213 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
216 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
219 // Ensure parent is cleared to prevent accessing released memory if an
220 // element somehow survives longer than his parent.
221 ud->element->_parent = 0;
225 //----------------------------------------------------------------------------
226 void Element::onDestroy()
228 if( !_transform.valid() )
231 // The transform node keeps a reference on this element, so ensure it is
233 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
235 parent->removeChild(_transform.get());
238 // Hide in case someone still holds a reference
246 //----------------------------------------------------------------------------
247 ElementPtr Element::getParent() const
252 //----------------------------------------------------------------------------
253 CanvasWeakPtr Element::getCanvas() const
258 //----------------------------------------------------------------------------
259 void Element::update(double dt)
264 // Trigger matrix update
267 // Update bounding box on manual update (manual updates pass zero dt)
268 if( dt == 0 && _drawable )
269 _drawable->getBound();
271 if( (_attributes_dirty & BLEND_FUNC) && _transform.valid() )
274 _transform->getOrCreateStateSet(),
275 _node->getChild("blend-source"),
276 _node->getChild("blend-destination"),
277 _node->getChild("blend-source-rgb"),
278 _node->getChild("blend-destination-rgb"),
279 _node->getChild("blend-source-alpha"),
280 _node->getChild("blend-destination-alpha")
282 _attributes_dirty &= ~BLEND_FUNC;
286 //----------------------------------------------------------------------------
287 bool Element::addEventListener( const std::string& type_str,
288 const EventListener& cb )
294 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
297 _listener[ Event::getOrRegisterType(type_str) ].push_back(cb);
301 //----------------------------------------------------------------------------
302 void Element::clearEventListener()
307 //----------------------------------------------------------------------------
308 void Element::setFocus()
310 CanvasPtr canvas = _canvas.lock();
312 canvas->setFocusElement(this);
315 //----------------------------------------------------------------------------
316 bool Element::accept(EventVisitor& visitor)
321 return visitor.apply(*this);
324 //----------------------------------------------------------------------------
325 bool Element::ascend(EventVisitor& visitor)
328 return _parent->accept(visitor);
332 //----------------------------------------------------------------------------
333 bool Element::traverse(EventVisitor& visitor)
338 //----------------------------------------------------------------------------
339 size_t Element::numEventHandler(int type) const
341 ListenerMap::const_iterator listeners = _listener.find(type);
342 if( listeners != _listener.end() )
343 return listeners->second.size();
347 //----------------------------------------------------------------------------
348 bool Element::handleEvent(const EventPtr& event)
350 ListenerMap::iterator listeners = _listener.find(event->getType());
351 if( listeners == _listener.end() )
354 BOOST_FOREACH(EventListener const& listener, listeners->second)
359 catch( std::exception const& ex )
364 "canvas::Element: event handler error: '" << ex.what() << "'"
371 //----------------------------------------------------------------------------
372 bool Element::dispatchEvent(const EventPtr& event)
374 EventPropagationPath path;
375 path.push_back( EventTarget(this) );
377 for( Element* parent = _parent;
379 parent = parent->_parent )
380 path.push_front( EventTarget(parent) );
382 CanvasPtr canvas = _canvas.lock();
386 return canvas->propagateEvent(event, path);
389 //----------------------------------------------------------------------------
390 bool Element::hitBound( const osg::Vec2f& global_pos,
391 const osg::Vec2f& parent_pos,
392 const osg::Vec2f& local_pos ) const
394 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
397 const osg::Vec3f pos3(parent_pos, 0);
399 // Drawables have a bounding box...
402 #if OSG_VERSION_LESS_THAN(3,3,2)
407 .contains(osg::Vec3f(local_pos, 0));
408 else if( _transform.valid() )
409 // ... for other elements, i.e. groups only a bounding sphere is available
410 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
416 //----------------------------------------------------------------------------
417 void Element::setVisible(bool visible)
419 if( _transform.valid() )
420 // TODO check if we need another nodemask
421 _transform->setNodeMask(visible ? 0xffffffff : 0);
424 //----------------------------------------------------------------------------
425 bool Element::isVisible() const
427 return _transform.valid() && _transform->getNodeMask() != 0;
430 //----------------------------------------------------------------------------
431 osg::MatrixTransform* Element::getMatrixTransform()
433 return _transform.get();
436 //----------------------------------------------------------------------------
437 osg::MatrixTransform const* Element::getMatrixTransform() const
439 return _transform.get();
442 //----------------------------------------------------------------------------
443 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
446 const osg::Matrix& m = _transform->getInverseMatrix();
449 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
450 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
454 //----------------------------------------------------------------------------
455 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
458 && child->getNameString() == NAME_TRANSFORM )
460 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
461 _transform_types.resize( child->getIndex() + 1 );
463 _transform_types[ child->getIndex() ] = TT_NONE;
464 _attributes_dirty |= TRANSFORM;
467 else if( parent->getParent() == _node
468 && parent->getNameString() == NAME_TRANSFORM )
470 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
472 const std::string& name = child->getNameString();
474 TransformType& type = _transform_types[parent->getIndex()];
478 else if( name == "t" )
480 else if( name == "rot" )
482 else if( name == "s" )
485 _attributes_dirty |= TRANSFORM;
492 //----------------------------------------------------------------------------
493 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
495 if( parent == _node )
497 if( child->getNameString() == NAME_TRANSFORM )
499 if( !_transform.valid() )
502 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
508 "Element::childRemoved: unknown transform: " << child->getPath()
513 _transform_types[ child->getIndex() ] = TT_NONE;
515 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
516 _transform_types.pop_back();
518 _attributes_dirty |= TRANSFORM;
521 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
523 if( setStyle(getParentStyle(child), style) )
531 //----------------------------------------------------------------------------
532 void Element::valueChanged(SGPropertyNode* child)
534 SGPropertyNode *parent = child->getParent();
535 if( parent == _node )
537 const std::string& name = child->getNameString();
538 if( boost::starts_with(name, "data-") )
540 else if( StyleInfo const* style_info = getStyleInfo(name) )
542 SGPropertyNode const* style = child;
543 if( isStyleEmpty(child) )
546 style = getParentStyle(child);
548 setStyle(style, style_info);
551 else if( name == "update" )
553 else if( boost::starts_with(name, "blend-") )
554 return (void)(_attributes_dirty |= BLEND_FUNC);
557 && parent->getParent() == _node
558 && parent->getNameString() == NAME_TRANSFORM )
560 _attributes_dirty |= TRANSFORM;
567 //----------------------------------------------------------------------------
568 bool Element::setStyle( const SGPropertyNode* child,
569 const StyleInfo* style_info )
571 return canApplyStyle(child) && setStyleImpl(child, style_info);
574 //----------------------------------------------------------------------------
575 void Element::setClip(const std::string& clip)
577 osg::StateSet* ss = getOrCreateStateSet();
581 if( clip.empty() || clip == "auto" )
583 ss->removeAttribute(osg::StateAttribute::SCISSOR);
588 // TODO generalize CSS property parsing
589 const std::string RECT("rect(");
590 if( !boost::ends_with(clip, ")")
591 || !boost::starts_with(clip, RECT) )
593 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
597 const std::string sep(", \t\npx");
601 for(size_t pos = RECT.size(); comp < 4; ++comp)
603 pos = clip.find_first_not_of(sep, pos);
604 if( pos == std::string::npos || pos == clip.size() - 1 )
608 values[comp] = strtod(&clip[pos], &end);
609 if( end == &clip[pos] || !end )
612 pos = end - &clip[0];
617 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
621 float width = values[1] - values[3],
622 height = values[2] - values[0];
624 if( width < 0 || height < 0 )
626 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
631 _scissor = new RelativeScissor(_transform.get());
633 // <top>, <right>, <bottom>, <left>
634 _scissor->x() = values[3];
635 _scissor->y() = values[0];
636 _scissor->width() = width;
637 _scissor->height() = height;
639 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
641 valueChanged(clip_frame);
643 _scissor->_coord_reference = GLOBAL;
645 ss->setAttributeAndModes(_scissor);
648 //----------------------------------------------------------------------------
649 void Element::setClipFrame(ReferenceFrame rf)
652 _scissor->_coord_reference = rf;
655 //----------------------------------------------------------------------------
656 osg::BoundingBox Element::getBoundingBox() const
659 #if OSG_VERSION_LESS_THAN(3,3,2)
660 return _drawable->getBound();
662 return _drawable->getBoundingBox();
667 if( _transform.valid() )
668 bb.expandBy(_transform->getBound());
673 //----------------------------------------------------------------------------
674 osg::BoundingBox Element::getTightBoundingBox() const
676 return getTransformedBounds(getMatrix());
679 //----------------------------------------------------------------------------
680 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
683 return osg::BoundingBox();
685 osg::BoundingBox transformed;
686 const osg::BoundingBox& bb =
687 #if OSG_VERSION_LESS_THAN(3,3,2)
688 _drawable->getBound();
690 _drawable->getBoundingBox();
693 for(int i = 0; i < 4; ++i)
694 transformed.expandBy( bb.corner(i) * m );
699 //----------------------------------------------------------------------------
700 osg::Matrix Element::getMatrix() const
703 return osg::Matrix::identity();
705 if( !(_attributes_dirty & TRANSFORM) )
706 return _transform->getMatrix();
709 for( size_t i = 0; i < _transform_types.size(); ++i )
711 // Skip unused indizes...
712 if( _transform_types[i] == TT_NONE )
715 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
717 // Build up the matrix representation of the current transform node
719 switch( _transform_types[i] )
722 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
723 tf_node->getDoubleValue("m[1]", 0),
725 tf_node->getDoubleValue("m[6]", 0),
727 tf_node->getDoubleValue("m[2]", 0),
728 tf_node->getDoubleValue("m[3]", 1),
730 tf_node->getDoubleValue("m[7]", 0),
737 tf_node->getDoubleValue("m[4]", 0),
738 tf_node->getDoubleValue("m[5]", 0),
740 tf_node->getDoubleValue("m[8]", 1) );
743 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
744 tf_node->getDoubleValue("t[1]", 0),
748 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
752 float sx = tf_node->getDoubleValue("s[0]", 1);
753 // sy defaults to sx...
754 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
762 _transform->setMatrix(m);
763 _attributes_dirty &= ~TRANSFORM;
768 //----------------------------------------------------------------------------
769 Element::StyleSetters Element::_style_setters;
771 //----------------------------------------------------------------------------
772 Element::Element( const CanvasWeakPtr& canvas,
773 const SGPropertyNode_ptr& node,
774 const Style& parent_style,
776 PropertyBasedElement(node),
779 _attributes_dirty( 0 ),
780 _transform( new osg::MatrixTransform ),
781 _style( parent_style ),
791 "New canvas element " << node->getPath()
794 // Ensure elements are drawn in order they appear in the element tree
795 _transform->getOrCreateStateSet()
796 ->setRenderBinDetails
800 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
803 _transform->setUserData( new OSGUserData(this) );
806 //----------------------------------------------------------------------------
807 void Element::staticInit()
809 if( isInit<Element>() )
812 addStyle("clip", "", &Element::setClip, false);
813 addStyle("clip-frame", "", &Element::setClipFrame, false);
814 addStyle("visible", "", &Element::setVisible, false);
817 //----------------------------------------------------------------------------
818 bool Element::isStyleEmpty(const SGPropertyNode* child) const
821 || simgear::strutils::strip(child->getStringValue()).empty();
824 //----------------------------------------------------------------------------
825 bool Element::canApplyStyle(const SGPropertyNode* child) const
827 if( _node == child->getParent() )
830 // Parent values do not override if element has own value
831 return isStyleEmpty( _node->getChild(child->getName()) );
834 //----------------------------------------------------------------------------
835 bool Element::setStyleImpl( const SGPropertyNode* child,
836 const StyleInfo* style_info )
838 const StyleSetter* style_setter = style_info
839 ? &style_info->setter
840 : getStyleSetter(child->getNameString());
841 while( style_setter )
843 if( style_setter->func(*this, child) )
845 style_setter = style_setter->next;
850 //----------------------------------------------------------------------------
851 const Element::StyleInfo*
852 Element::getStyleInfo(const std::string& name) const
854 StyleSetters::const_iterator setter = _style_setters.find(name);
855 if( setter == _style_setters.end() )
858 return &setter->second;
861 //----------------------------------------------------------------------------
862 const Element::StyleSetter*
863 Element::getStyleSetter(const std::string& name) const
865 const StyleInfo* info = getStyleInfo(name);
866 return info ? &info->setter : 0;
869 //----------------------------------------------------------------------------
870 const SGPropertyNode*
871 Element::getParentStyle(const SGPropertyNode* child) const
873 // Try to get value from parent...
876 Style::const_iterator style =
877 _parent->_style.find(child->getNameString());
878 if( style != _parent->_style.end() )
879 return style->second;
882 // ...or reset to default if none is available
883 return child; // TODO somehow get default value for each style?
886 //----------------------------------------------------------------------------
887 void Element::setDrawable( osg::Drawable* drawable )
889 _drawable = drawable;
892 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
893 geode->addDrawable(_drawable);
894 _transform->addChild(geode);
897 //----------------------------------------------------------------------------
898 osg::StateSet* Element::getOrCreateStateSet()
900 if( _drawable.valid() )
901 return _drawable->getOrCreateStateSet();
902 if( _transform.valid() )
903 return _transform->getOrCreateStateSet();
908 //----------------------------------------------------------------------------
909 void Element::setupStyle()
911 BOOST_FOREACH( Style::value_type style, _style )
912 setStyle(style.second);
915 } // namespace canvas
916 } // namespace simgear