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/Scissor>
31 #include <boost/algorithm/string/predicate.hpp>
32 #include <boost/foreach.hpp>
33 #include <boost/make_shared.hpp>
43 const std::string NAME_TRANSFORM = "tf";
46 * glScissor with coordinates relative to different reference frames.
48 class Element::RelativeScissor:
53 ReferenceFrame _coord_reference;
54 osg::observer_ptr<osg::Node> _node;
56 RelativeScissor(osg::Node* node = NULL):
57 _coord_reference(GLOBAL),
64 /** Copy constructor using CopyOp to manage deep vs shallow copy. */
65 RelativeScissor( const RelativeScissor& vp,
66 const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ):
68 _coord_reference(vp._coord_reference),
72 META_StateAttribute(simgear, RelativeScissor, SCISSOR);
74 /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
75 virtual int compare(const StateAttribute& sa) const
77 // check the types are equal and then create the rhs variable
78 // used by the COMPARE_StateAttribute_Parameter macros below.
79 COMPARE_StateAttribute_Types(RelativeScissor,sa)
81 // compare each parameter in turn against the rhs.
82 COMPARE_StateAttribute_Parameter(_x)
83 COMPARE_StateAttribute_Parameter(_y)
84 COMPARE_StateAttribute_Parameter(_width)
85 COMPARE_StateAttribute_Parameter(_height)
86 COMPARE_StateAttribute_Parameter(_coord_reference)
87 COMPARE_StateAttribute_Parameter(_node)
89 return 0; // passed all the above comparison macros, must be equal.
92 virtual void apply(osg::State& state) const
94 if( _width <= 0 || _height <= 0 )
97 const osg::Viewport* vp = state.getCurrentViewport();
98 float w2 = 0.5 * vp->width(),
99 h2 = 0.5 * vp->height();
101 osg::Matrix model_view
108 model_view.preMult(state.getProjectionMatrix());
110 if( _coord_reference != GLOBAL )
112 osg::Node* ref_obj = _node.get();
114 if( _coord_reference == PARENT )
116 if( _node->getNumParents() < 1 )
118 SG_LOG(SG_GL, SG_WARN, "RelativeScissor: missing parent.");
122 ref_obj = _node->getParent(0);
125 osg::MatrixList const& parent_matrices = ref_obj->getWorldMatrices();
126 assert( !parent_matrices.empty() );
127 model_view.preMult(parent_matrices.front());
130 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
131 offset(model_view(3,0), model_view(3,1));
133 // TODO check/warn for rotation?
134 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
135 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
136 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
137 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
144 glScissor(x, y, w, h);
147 bool contains(const osg::Vec2f& pos) const
149 return _x <= pos.x() && pos.x() <= _x + _width
150 && _y <= pos.y() && pos.y() <= _y + _height;
153 bool contains( const osg::Vec2f& global_pos,
154 const osg::Vec2f& parent_pos,
155 const osg::Vec2f& local_pos ) const
157 switch( _coord_reference )
159 case GLOBAL: return contains(global_pos);
160 case PARENT: return contains(parent_pos);
161 case LOCAL: return contains(local_pos);
168 //----------------------------------------------------------------------------
169 Element::OSGUserData::OSGUserData(ElementPtr element):
175 //----------------------------------------------------------------------------
178 if( !_transform.valid() )
181 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
184 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
187 // Ensure parent is cleared to prevent accessing released memory if an
188 // element somehow survives longer than his parent.
189 ud->element->_parent = 0;
193 //----------------------------------------------------------------------------
194 void Element::onDestroy()
196 if( !_transform.valid() )
199 // The transform node keeps a reference on this element, so ensure it is
201 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
203 parent->removeChild(_transform.get());
207 //----------------------------------------------------------------------------
208 ElementPtr Element::getParent() const
213 //----------------------------------------------------------------------------
214 CanvasWeakPtr Element::getCanvas() const
219 //----------------------------------------------------------------------------
220 void Element::update(double dt)
225 // Trigger matrix update
228 // Update bounding box on manual update (manual updates pass zero dt)
229 if( dt == 0 && _drawable )
230 _drawable->getBound();
232 if( _attributes_dirty & BLEND_FUNC )
235 _transform->getOrCreateStateSet(),
236 _node->getChild("blend-source"),
237 _node->getChild("blend-destination"),
238 _node->getChild("blend-source-rgb"),
239 _node->getChild("blend-destination-rgb"),
240 _node->getChild("blend-source-alpha"),
241 _node->getChild("blend-destination-alpha")
243 _attributes_dirty &= ~BLEND_FUNC;
247 //----------------------------------------------------------------------------
248 bool Element::addEventListener( const std::string& type_str,
249 const EventListener& cb )
255 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
258 _listener[ Event::getOrRegisterType(type_str) ].push_back(cb);
262 //----------------------------------------------------------------------------
263 void Element::clearEventListener()
268 //----------------------------------------------------------------------------
269 bool Element::accept(EventVisitor& visitor)
274 return visitor.apply(*this);
277 //----------------------------------------------------------------------------
278 bool Element::ascend(EventVisitor& visitor)
281 return _parent->accept(visitor);
285 //----------------------------------------------------------------------------
286 bool Element::traverse(EventVisitor& visitor)
291 //----------------------------------------------------------------------------
292 bool Element::handleEvent(const EventPtr& event)
294 ListenerMap::iterator listeners = _listener.find(event->getType());
295 if( listeners == _listener.end() )
298 BOOST_FOREACH(EventListener const& listener, listeners->second)
303 catch( std::exception const& ex )
308 "canvas::Element: event handler error: '" << ex.what() << "'"
315 //----------------------------------------------------------------------------
316 bool Element::dispatchEvent(const EventPtr& event)
318 EventPropagationPath path;
319 path.push_back( EventTarget(this) );
321 for( Element* parent = _parent;
323 parent = parent->_parent )
324 path.push_front( EventTarget(parent) );
326 CanvasPtr canvas = _canvas.lock();
330 return canvas->propagateEvent(event, path);
333 //----------------------------------------------------------------------------
334 bool Element::hitBound( const osg::Vec2f& global_pos,
335 const osg::Vec2f& parent_pos,
336 const osg::Vec2f& local_pos ) const
338 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
341 const osg::Vec3f pos3(parent_pos, 0);
343 // Drawables have a bounding box...
345 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
346 else if( _transform.valid() )
347 // ... for other elements, i.e. groups only a bounding sphere is available
348 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
354 //----------------------------------------------------------------------------
355 void Element::setVisible(bool visible)
357 if( _transform.valid() )
358 // TODO check if we need another nodemask
359 _transform->setNodeMask(visible ? 0xffffffff : 0);
362 //----------------------------------------------------------------------------
363 bool Element::isVisible() const
365 return _transform.valid() && _transform->getNodeMask() != 0;
368 //----------------------------------------------------------------------------
369 osg::MatrixTransform* Element::getMatrixTransform()
371 return _transform.get();
374 //----------------------------------------------------------------------------
375 osg::MatrixTransform const* Element::getMatrixTransform() const
377 return _transform.get();
380 //----------------------------------------------------------------------------
381 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
384 const osg::Matrix& m = _transform->getInverseMatrix();
387 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
388 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
392 //----------------------------------------------------------------------------
393 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
396 && child->getNameString() == NAME_TRANSFORM )
398 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
399 _transform_types.resize( child->getIndex() + 1 );
401 _transform_types[ child->getIndex() ] = TT_NONE;
402 _attributes_dirty |= TRANSFORM;
405 else if( parent->getParent() == _node
406 && parent->getNameString() == NAME_TRANSFORM )
408 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
410 const std::string& name = child->getNameString();
412 TransformType& type = _transform_types[parent->getIndex()];
416 else if( name == "t" )
418 else if( name == "rot" )
420 else if( name == "s" )
423 _attributes_dirty |= TRANSFORM;
430 //----------------------------------------------------------------------------
431 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
433 if( parent == _node )
435 if( child->getNameString() == NAME_TRANSFORM )
437 if( !_transform.valid() )
440 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
446 "Element::childRemoved: unknown transform: " << child->getPath()
451 _transform_types[ child->getIndex() ] = TT_NONE;
453 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
454 _transform_types.pop_back();
456 _attributes_dirty |= TRANSFORM;
459 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
461 if( setStyle(getParentStyle(child), style) )
469 //----------------------------------------------------------------------------
470 void Element::valueChanged(SGPropertyNode* child)
472 SGPropertyNode *parent = child->getParent();
473 if( parent == _node )
475 const std::string& name = child->getNameString();
476 if( boost::starts_with(name, "data-") )
478 else if( StyleInfo const* style_info = getStyleInfo(name) )
480 SGPropertyNode const* style = child;
481 if( isStyleEmpty(child) )
484 style = getParentStyle(child);
486 setStyle(style, style_info);
489 else if( name == "update" )
491 else if( boost::starts_with(name, "blend-") )
492 return (void)(_attributes_dirty |= BLEND_FUNC);
495 && parent->getParent() == _node
496 && parent->getNameString() == NAME_TRANSFORM )
498 _attributes_dirty |= TRANSFORM;
505 //----------------------------------------------------------------------------
506 bool Element::setStyle( const SGPropertyNode* child,
507 const StyleInfo* style_info )
509 return canApplyStyle(child) && setStyleImpl(child, style_info);
512 //----------------------------------------------------------------------------
513 void Element::setClip(const std::string& clip)
515 if( clip.empty() || clip == "auto" )
517 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
522 // TODO generalize CSS property parsing
523 const std::string RECT("rect(");
524 if( !boost::ends_with(clip, ")")
525 || !boost::starts_with(clip, RECT) )
527 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
531 const std::string sep(", \t\npx");
535 for(size_t pos = RECT.size(); comp < 4; ++comp)
537 pos = clip.find_first_not_of(sep, pos);
538 if( pos == std::string::npos || pos == clip.size() - 1 )
542 values[comp] = strtod(&clip[pos], &end);
543 if( end == &clip[pos] || !end )
546 pos = end - &clip[0];
551 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
555 float width = values[1] - values[3],
556 height = values[2] - values[0];
558 if( width < 0 || height < 0 )
560 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
565 _scissor = new RelativeScissor(_transform.get());
567 // <top>, <right>, <bottom>, <left>
568 _scissor->x() = SGMiscf::roundToInt(values[3]);
569 _scissor->y() = SGMiscf::roundToInt(values[0]);
570 _scissor->width() = SGMiscf::roundToInt(width);
571 _scissor->height() = SGMiscf::roundToInt(height);
573 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
575 valueChanged(clip_frame);
577 _scissor->_coord_reference = GLOBAL;
579 getOrCreateStateSet()->setAttributeAndModes(_scissor);
582 //----------------------------------------------------------------------------
583 void Element::setClipFrame(ReferenceFrame rf)
586 _scissor->_coord_reference = rf;
589 //----------------------------------------------------------------------------
590 osg::BoundingBox Element::getBoundingBox() const
593 return _drawable->getBound();
597 if( _transform.valid() )
598 bb.expandBy(_transform->getBound());
603 //----------------------------------------------------------------------------
604 osg::BoundingBox Element::getTightBoundingBox() const
606 return getTransformedBounds(getMatrix());
609 //----------------------------------------------------------------------------
610 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
613 return osg::BoundingBox();
615 osg::BoundingBox transformed;
616 const osg::BoundingBox& bb = _drawable->getBound();
617 for(int i = 0; i < 4; ++i)
618 transformed.expandBy( bb.corner(i) * m );
623 //----------------------------------------------------------------------------
624 osg::Matrix Element::getMatrix() const
627 return osg::Matrix::identity();
629 if( !(_attributes_dirty & TRANSFORM) )
630 return _transform->getMatrix();
633 for( size_t i = 0; i < _transform_types.size(); ++i )
635 // Skip unused indizes...
636 if( _transform_types[i] == TT_NONE )
639 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
641 // Build up the matrix representation of the current transform node
643 switch( _transform_types[i] )
646 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
647 tf_node->getDoubleValue("m[1]", 0),
649 tf_node->getDoubleValue("m[6]", 0),
651 tf_node->getDoubleValue("m[2]", 0),
652 tf_node->getDoubleValue("m[3]", 1),
654 tf_node->getDoubleValue("m[7]", 0),
661 tf_node->getDoubleValue("m[4]", 0),
662 tf_node->getDoubleValue("m[5]", 0),
664 tf_node->getDoubleValue("m[8]", 1) );
667 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
668 tf_node->getDoubleValue("t[1]", 0),
672 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
676 float sx = tf_node->getDoubleValue("s[0]", 1);
677 // sy defaults to sx...
678 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
686 _transform->setMatrix(m);
687 _attributes_dirty &= ~TRANSFORM;
692 //----------------------------------------------------------------------------
693 Element::StyleSetters Element::_style_setters;
695 //----------------------------------------------------------------------------
696 Element::Element( const CanvasWeakPtr& canvas,
697 const SGPropertyNode_ptr& node,
698 const Style& parent_style,
700 PropertyBasedElement(node),
703 _attributes_dirty( 0 ),
704 _transform( new osg::MatrixTransform ),
705 _style( parent_style ),
715 "New canvas element " << node->getPath()
718 // Ensure elements are drawn in order they appear in the element tree
719 _transform->getOrCreateStateSet()
720 ->setRenderBinDetails
724 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
727 _transform->setUserData( new OSGUserData(this) );
730 //----------------------------------------------------------------------------
731 void Element::staticInit()
733 if( isInit<Element>() )
736 addStyle("clip", "", &Element::setClip, false);
737 addStyle("clip-frame", "", &Element::setClipFrame, false);
738 addStyle("visible", "", &Element::setVisible, false);
741 //----------------------------------------------------------------------------
742 bool Element::isStyleEmpty(const SGPropertyNode* child) const
745 || simgear::strutils::strip(child->getStringValue()).empty();
748 //----------------------------------------------------------------------------
749 bool Element::canApplyStyle(const SGPropertyNode* child) const
751 if( _node == child->getParent() )
754 // Parent values do not override if element has own value
755 return isStyleEmpty( _node->getChild(child->getName()) );
758 //----------------------------------------------------------------------------
759 bool Element::setStyleImpl( const SGPropertyNode* child,
760 const StyleInfo* style_info )
762 const StyleSetter* style_setter = style_info
763 ? &style_info->setter
764 : getStyleSetter(child->getNameString());
765 while( style_setter )
767 if( style_setter->func(*this, child) )
769 style_setter = style_setter->next;
774 //----------------------------------------------------------------------------
775 const Element::StyleInfo*
776 Element::getStyleInfo(const std::string& name) const
778 StyleSetters::const_iterator setter = _style_setters.find(name);
779 if( setter == _style_setters.end() )
782 return &setter->second;
785 //----------------------------------------------------------------------------
786 const Element::StyleSetter*
787 Element::getStyleSetter(const std::string& name) const
789 const StyleInfo* info = getStyleInfo(name);
790 return info ? &info->setter : 0;
793 //----------------------------------------------------------------------------
794 const SGPropertyNode*
795 Element::getParentStyle(const SGPropertyNode* child) const
797 // Try to get value from parent...
800 Style::const_iterator style =
801 _parent->_style.find(child->getNameString());
802 if( style != _parent->_style.end() )
803 return style->second;
806 // ...or reset to default if none is available
807 return child; // TODO somehow get default value for each style?
810 //----------------------------------------------------------------------------
811 void Element::setDrawable( osg::Drawable* drawable )
813 _drawable = drawable;
816 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
817 geode->addDrawable(_drawable);
818 _transform->addChild(geode);
821 //----------------------------------------------------------------------------
822 osg::StateSet* Element::getOrCreateStateSet()
824 return _drawable ? _drawable->getOrCreateStateSet()
825 : _transform->getOrCreateStateSet();
828 //----------------------------------------------------------------------------
829 void Element::setupStyle()
831 BOOST_FOREACH( Style::value_type style, _style )
832 setStyle(style.second);
835 } // namespace canvas
836 } // namespace simgear