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/CanvasEventVisitor.hxx>
21 #include <simgear/canvas/MouseEvent.hxx>
22 #include <simgear/math/SGMisc.hxx>
23 #include <simgear/misc/strutils.hxx>
24 #include <simgear/scene/material/parseBlendFunc.hxx>
26 #include <osg/Drawable>
28 #include <osg/Scissor>
30 #include <boost/algorithm/string/predicate.hpp>
31 #include <boost/foreach.hpp>
32 #include <boost/make_shared.hpp>
42 const std::string NAME_TRANSFORM = "tf";
45 * glScissor with coordinates relative to different reference frames.
47 class Element::RelativeScissor:
52 ReferenceFrame _coord_reference;
53 osg::Matrix _parent_inverse;
56 _coord_reference(GLOBAL)
59 bool contains(const osg::Vec2f& pos) const
61 return _x <= pos.x() && pos.x() <= _x + _width
62 && _y <= pos.y() && pos.y() <= _y + _height;
65 bool contains( const osg::Vec2f& global_pos,
66 const osg::Vec2f& parent_pos,
67 const osg::Vec2f& local_pos ) const
69 switch( _coord_reference )
71 case GLOBAL: return contains(global_pos);
72 case PARENT: return contains(parent_pos);
73 case LOCAL: return contains(local_pos);
79 virtual void apply(osg::State& state) const
81 const osg::Viewport* vp = state.getCurrentViewport();
82 float w2 = 0.5 * vp->width(),
83 h2 = 0.5 * vp->height();
85 osg::Matrix model_view
92 model_view.preMult(state.getProjectionMatrix());
94 if( _coord_reference != GLOBAL )
96 model_view.preMult(state.getModelViewMatrix());
98 if( _coord_reference == PARENT )
99 model_view.preMult(_parent_inverse);
102 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
103 offset(model_view(3,0), model_view(3,1));
105 // TODO check/warn for rotation?
107 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
108 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
109 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
110 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
117 glScissor(x, y, w, h);
121 //----------------------------------------------------------------------------
122 Element::OSGUserData::OSGUserData(ElementPtr element):
128 //----------------------------------------------------------------------------
131 if( !_transform.valid() )
134 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
137 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
140 // Ensure parent is cleared to prevent accessing released memory if an
141 // element somehow survives longer than his parent.
142 ud->element->_parent = 0;
146 //----------------------------------------------------------------------------
147 void Element::setSelf(const PropertyBasedElementPtr& self)
149 PropertyBasedElement::setSelf(self);
151 _transform->setUserData
153 new OSGUserData(boost::static_pointer_cast<Element>(self))
157 //----------------------------------------------------------------------------
158 void Element::onDestroy()
160 if( !_transform.valid() )
163 // The transform node keeps a reference on this element, so ensure it is
165 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
167 parent->removeChild(_transform.get());
171 //----------------------------------------------------------------------------
172 ElementWeakPtr Element::getWeakPtr() const
174 return boost::static_pointer_cast<Element>(_self.lock());
177 //----------------------------------------------------------------------------
178 ElementPtr Element::getParent()
180 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
183 //----------------------------------------------------------------------------
184 void Element::update(double dt)
189 // Trigger matrix update
192 if( _attributes_dirty & SCISSOR_COORDS )
194 if( _scissor && _scissor->_coord_reference != GLOBAL )
195 _scissor->_parent_inverse = _transform->getInverseMatrix();
197 _attributes_dirty &= ~SCISSOR_COORDS;
200 // Update bounding box on manual update (manual updates pass zero dt)
201 if( dt == 0 && _drawable )
202 _drawable->getBound();
204 if( _attributes_dirty & BLEND_FUNC )
207 _transform->getOrCreateStateSet(),
208 _node->getChild("blend-source"),
209 _node->getChild("blend-destination"),
210 _node->getChild("blend-source-rgb"),
211 _node->getChild("blend-destination-rgb"),
212 _node->getChild("blend-source-alpha"),
213 _node->getChild("blend-destination-alpha")
215 _attributes_dirty &= ~BLEND_FUNC;
219 //----------------------------------------------------------------------------
220 bool Element::addEventListener( const std::string& type_str,
221 const EventListener& cb )
227 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
230 Event::Type type = Event::strToType(type_str);
231 if( type == Event::UNKNOWN )
235 "addEventListener: Unknown event type " << type_str );
239 _listener[ type ].push_back(cb);
244 //----------------------------------------------------------------------------
245 void Element::clearEventListener()
250 //----------------------------------------------------------------------------
251 bool Element::accept(EventVisitor& visitor)
256 return visitor.apply(*this);
259 //----------------------------------------------------------------------------
260 bool Element::ascend(EventVisitor& visitor)
263 return _parent->accept(visitor);
267 //----------------------------------------------------------------------------
268 bool Element::traverse(EventVisitor& visitor)
273 //----------------------------------------------------------------------------
274 bool Element::handleEvent(canvas::EventPtr event)
276 ListenerMap::iterator listeners = _listener.find(event->getType());
277 if( listeners == _listener.end() )
280 BOOST_FOREACH(EventListener const& listener, listeners->second)
286 //----------------------------------------------------------------------------
287 bool Element::hitBound( const osg::Vec2f& global_pos,
288 const osg::Vec2f& parent_pos,
289 const osg::Vec2f& local_pos ) const
291 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
294 const osg::Vec3f pos3(parent_pos, 0);
296 // Drawables have a bounding box...
298 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
300 // ... for other elements, i.e. groups only a bounding sphere is available
301 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
305 //----------------------------------------------------------------------------
306 void Element::setVisible(bool visible)
308 if( _transform.valid() )
309 // TODO check if we need another nodemask
310 _transform->setNodeMask(visible ? 0xffffffff : 0);
313 //----------------------------------------------------------------------------
314 bool Element::isVisible() const
316 return _transform.valid() && _transform->getNodeMask() != 0;
319 //----------------------------------------------------------------------------
320 osg::MatrixTransform* Element::getMatrixTransform()
322 return _transform.get();
325 //----------------------------------------------------------------------------
326 osg::MatrixTransform const* Element::getMatrixTransform() const
328 return _transform.get();
331 //----------------------------------------------------------------------------
332 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
335 const osg::Matrix& m = _transform->getInverseMatrix();
338 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
339 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
343 //----------------------------------------------------------------------------
344 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
347 && child->getNameString() == NAME_TRANSFORM )
349 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
350 _transform_types.resize( child->getIndex() + 1 );
352 _transform_types[ child->getIndex() ] = TT_NONE;
353 _attributes_dirty |= TRANSFORM;
356 else if( parent->getParent() == _node
357 && parent->getNameString() == NAME_TRANSFORM )
359 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
361 const std::string& name = child->getNameString();
363 TransformType& type = _transform_types[parent->getIndex()];
367 else if( name == "t" )
369 else if( name == "rot" )
371 else if( name == "s" )
374 _attributes_dirty |= TRANSFORM;
381 //----------------------------------------------------------------------------
382 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
384 if( parent == _node )
386 if( child->getNameString() == NAME_TRANSFORM )
388 if( !_transform.valid() )
391 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
397 "Element::childRemoved: unknown transform: " << child->getPath()
402 _transform_types[ child->getIndex() ] = TT_NONE;
404 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
405 _transform_types.pop_back();
407 _attributes_dirty |= TRANSFORM;
410 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
412 if( setStyle(getParentStyle(child), style) )
420 //----------------------------------------------------------------------------
421 void Element::valueChanged(SGPropertyNode* child)
423 SGPropertyNode *parent = child->getParent();
424 if( parent == _node )
426 const std::string& name = child->getNameString();
427 if( StyleInfo const* style_info = getStyleInfo(name) )
429 SGPropertyNode const* style = child;
430 if( isStyleEmpty(child) )
433 style = getParentStyle(child);
435 setStyle(style, style_info);
438 else if( name == "update" )
440 else if( boost::starts_with(name, "blend-") )
441 return (void)(_attributes_dirty |= BLEND_FUNC);
443 else if( parent->getParent() == _node
444 && parent->getNameString() == NAME_TRANSFORM )
446 _attributes_dirty |= TRANSFORM;
453 //----------------------------------------------------------------------------
454 bool Element::setStyle( const SGPropertyNode* child,
455 const StyleInfo* style_info )
457 return canApplyStyle(child) && setStyleImpl(child, style_info);
460 //----------------------------------------------------------------------------
461 void Element::setClip(const std::string& clip)
463 if( clip.empty() || clip == "auto" )
465 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
470 // TODO generalize CSS property parsing
471 const std::string RECT("rect(");
472 if( !boost::ends_with(clip, ")")
473 || !boost::starts_with(clip, RECT) )
475 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
479 const std::string sep(", \t\npx");
483 for(size_t pos = RECT.size(); comp < 4; ++comp)
485 pos = clip.find_first_not_of(sep, pos);
486 if( pos == std::string::npos || pos == clip.size() - 1 )
490 values[comp] = strtod(&clip[pos], &end);
491 if( end == &clip[pos] || !end )
494 pos = end - &clip[0];
499 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
503 float width = values[1] - values[3],
504 height = values[2] - values[0];
506 if( width < 0 || height < 0 )
508 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
512 _scissor = new RelativeScissor();
513 // <top>, <right>, <bottom>, <left>
514 _scissor->x() = SGMiscf::roundToInt(values[3]);
515 _scissor->y() = SGMiscf::roundToInt(values[0]);
516 _scissor->width() = SGMiscf::roundToInt(width);
517 _scissor->height() = SGMiscf::roundToInt(height);
519 getOrCreateStateSet()->setAttributeAndModes(_scissor);
521 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
523 valueChanged(clip_frame);
526 //----------------------------------------------------------------------------
527 void Element::setClipFrame(ReferenceFrame rf)
531 _scissor->_coord_reference = rf;
532 _attributes_dirty |= SCISSOR_COORDS;
536 //----------------------------------------------------------------------------
537 void Element::setBoundingBox(const osg::BoundingBox& bb)
539 if( _bounding_box.empty() )
541 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
542 _bounding_box.resize(4);
543 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
544 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
545 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
546 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
549 _bounding_box[0]->setFloatValue(bb._min.x());
550 _bounding_box[1]->setFloatValue(bb._min.y());
551 _bounding_box[2]->setFloatValue(bb._max.x());
552 _bounding_box[3]->setFloatValue(bb._max.y());
555 //----------------------------------------------------------------------------
556 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
559 return osg::BoundingBox();
561 osg::BoundingBox transformed;
562 const osg::BoundingBox& bb = _drawable->getBound();
563 for(int i = 0; i < 4; ++i)
564 transformed.expandBy( bb.corner(i) * m );
569 //----------------------------------------------------------------------------
570 osg::Matrix Element::getMatrix() const
572 if( !(_attributes_dirty & TRANSFORM) )
573 return _transform->getMatrix();
576 for( size_t i = 0; i < _transform_types.size(); ++i )
578 // Skip unused indizes...
579 if( _transform_types[i] == TT_NONE )
582 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
584 // Build up the matrix representation of the current transform node
586 switch( _transform_types[i] )
589 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
590 tf_node->getDoubleValue("m[1]", 0),
592 tf_node->getDoubleValue("m[6]", 0),
594 tf_node->getDoubleValue("m[2]", 0),
595 tf_node->getDoubleValue("m[3]", 1),
597 tf_node->getDoubleValue("m[7]", 0),
604 tf_node->getDoubleValue("m[4]", 0),
605 tf_node->getDoubleValue("m[5]", 0),
607 tf_node->getDoubleValue("m[8]", 1) );
610 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
611 tf_node->getDoubleValue("t[1]", 0),
615 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
619 float sx = tf_node->getDoubleValue("s[0]", 1);
620 // sy defaults to sx...
621 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
629 _transform->setMatrix(m);
630 _attributes_dirty &= ~TRANSFORM;
631 _attributes_dirty |= SCISSOR_COORDS;
636 //----------------------------------------------------------------------------
637 Element::StyleSetters Element::_style_setters;
639 //----------------------------------------------------------------------------
640 Element::Element( const CanvasWeakPtr& canvas,
641 const SGPropertyNode_ptr& node,
642 const Style& parent_style,
644 PropertyBasedElement(node),
647 _attributes_dirty( 0 ),
648 _transform( new osg::MatrixTransform ),
649 _style( parent_style ),
659 "New canvas element " << node->getPath()
662 // Ensure elements are drawn in order they appear in the element tree
663 _transform->getOrCreateStateSet()
664 ->setRenderBinDetails
668 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
672 //----------------------------------------------------------------------------
673 void Element::staticInit()
675 if( isInit<Element>() )
678 addStyle("clip", "", &Element::setClip, false);
679 addStyle("clip-frame", "", &Element::setClipFrame, false);
680 addStyle("visible", "", &Element::setVisible, false);
683 //----------------------------------------------------------------------------
684 bool Element::isStyleEmpty(const SGPropertyNode* child) const
687 || simgear::strutils::strip(child->getStringValue()).empty();
690 //----------------------------------------------------------------------------
691 bool Element::canApplyStyle(const SGPropertyNode* child) const
693 if( _node == child->getParent() )
696 // Parent values do not override if element has own value
697 return isStyleEmpty( _node->getChild(child->getName()) );
700 //----------------------------------------------------------------------------
701 bool Element::setStyleImpl( const SGPropertyNode* child,
702 const StyleInfo* style_info )
704 const StyleSetter* style_setter = style_info
705 ? &style_info->setter
706 : getStyleSetter(child->getNameString());
707 while( style_setter )
709 if( style_setter->func(*this, child) )
711 style_setter = style_setter->next;
716 //----------------------------------------------------------------------------
717 const Element::StyleInfo*
718 Element::getStyleInfo(const std::string& name) const
720 StyleSetters::const_iterator setter = _style_setters.find(name);
721 if( setter == _style_setters.end() )
724 return &setter->second;
727 //----------------------------------------------------------------------------
728 const Element::StyleSetter*
729 Element::getStyleSetter(const std::string& name) const
731 const StyleInfo* info = getStyleInfo(name);
732 return info ? &info->setter : 0;
735 //----------------------------------------------------------------------------
736 const SGPropertyNode*
737 Element::getParentStyle(const SGPropertyNode* child) const
739 // Try to get value from parent...
742 Style::const_iterator style =
743 _parent->_style.find(child->getNameString());
744 if( style != _parent->_style.end() )
745 return style->second;
748 // ...or reset to default if none is available
749 return child; // TODO somehow get default value for each style?
752 //----------------------------------------------------------------------------
753 void Element::setDrawable( osg::Drawable* drawable )
755 _drawable = drawable;
758 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
759 geode->addDrawable(_drawable);
760 _transform->addChild(geode);
763 //----------------------------------------------------------------------------
764 osg::StateSet* Element::getOrCreateStateSet()
766 return _drawable ? _drawable->getOrCreateStateSet()
767 : _transform->getOrCreateStateSet();
770 //----------------------------------------------------------------------------
771 void Element::setupStyle()
773 BOOST_FOREACH( Style::value_type style, _style )
774 setStyle(style.second);
777 } // namespace canvas
778 } // namespace simgear