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 virtual void apply(osg::State& state) const
61 const osg::Viewport* vp = state.getCurrentViewport();
62 float w2 = 0.5 * vp->width(),
63 h2 = 0.5 * vp->height();
65 osg::Matrix model_view
72 model_view.preMult(state.getProjectionMatrix());
74 if( _coord_reference != GLOBAL )
76 model_view.preMult(state.getModelViewMatrix());
78 if( _coord_reference == PARENT )
79 model_view.preMult(_parent_inverse);
82 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
83 offset(model_view(3,0), model_view(3,1));
85 // TODO check/warn for rotation?
87 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
88 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
89 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
90 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
97 glScissor(x, y, w, h);
101 //----------------------------------------------------------------------------
102 Element::OSGUserData::OSGUserData(ElementPtr element):
108 //----------------------------------------------------------------------------
114 //----------------------------------------------------------------------------
115 void Element::setSelf(const PropertyBasedElementPtr& self)
117 PropertyBasedElement::setSelf(self);
119 _transform->setUserData
121 new OSGUserData(boost::static_pointer_cast<Element>(self))
125 //----------------------------------------------------------------------------
126 void Element::onDestroy()
128 if( !_transform.valid() )
131 // The transform node keeps a reference on this element, so ensure it is
133 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
135 parent->removeChild(_transform.get());
139 //----------------------------------------------------------------------------
140 ElementWeakPtr Element::getWeakPtr() const
142 return boost::static_pointer_cast<Element>(_self.lock());
145 //----------------------------------------------------------------------------
146 ElementPtr Element::getParent()
148 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
151 //----------------------------------------------------------------------------
152 void Element::update(double dt)
154 if( !_transform->getNodeMask() )
155 // Don't do anything if element is hidden
158 if( _transform_dirty )
161 for( size_t i = 0; i < _transform_types.size(); ++i )
163 // Skip unused indizes...
164 if( _transform_types[i] == TT_NONE )
167 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
169 // Build up the matrix representation of the current transform node
171 switch( _transform_types[i] )
174 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
175 tf_node->getDoubleValue("m[1]", 0),
177 tf_node->getDoubleValue("m[6]", 0),
179 tf_node->getDoubleValue("m[2]", 0),
180 tf_node->getDoubleValue("m[3]", 1),
182 tf_node->getDoubleValue("m[7]", 0),
189 tf_node->getDoubleValue("m[4]", 0),
190 tf_node->getDoubleValue("m[5]", 0),
192 tf_node->getDoubleValue("m[8]", 1) );
195 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
196 tf_node->getDoubleValue("t[1]", 0),
200 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
204 float sx = tf_node->getDoubleValue("s[0]", 1);
205 // sy defaults to sx...
206 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
214 _transform->setMatrix(m);
215 _transform_dirty = false;
216 _attributes_dirty |= SCISSOR_COORDS;
219 if( _attributes_dirty & SCISSOR_COORDS )
221 if( _scissor && _scissor->_coord_reference != GLOBAL )
222 _scissor->_parent_inverse = _transform->getInverseMatrix();
224 _attributes_dirty &= ~SCISSOR_COORDS;
227 // Update bounding box on manual update (manual updates pass zero dt)
228 if( dt == 0 && _drawable )
229 _drawable->getBound();
231 if( _attributes_dirty & BLEND_FUNC )
234 _transform->getOrCreateStateSet(),
235 _node->getChild("blend-source"),
236 _node->getChild("blend-destination"),
237 _node->getChild("blend-source-rgb"),
238 _node->getChild("blend-destination-rgb"),
239 _node->getChild("blend-source-alpha"),
240 _node->getChild("blend-destination-alpha")
242 _attributes_dirty &= ~BLEND_FUNC;
246 //----------------------------------------------------------------------------
247 bool Element::addEventListener( const std::string& type_str,
248 const EventListener& cb )
254 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
257 Event::Type type = Event::strToType(type_str);
258 if( type == Event::UNKNOWN )
262 "addEventListener: Unknown event type " << type_str );
266 _listener[ type ].push_back(cb);
271 //----------------------------------------------------------------------------
272 void Element::clearEventListener()
277 //----------------------------------------------------------------------------
278 bool Element::accept(EventVisitor& visitor)
283 return visitor.apply(*this);
286 //----------------------------------------------------------------------------
287 bool Element::ascend(EventVisitor& visitor)
290 return _parent->accept(visitor);
294 //----------------------------------------------------------------------------
295 bool Element::traverse(EventVisitor& visitor)
300 //----------------------------------------------------------------------------
301 bool Element::handleEvent(canvas::EventPtr event)
303 ListenerMap::iterator listeners = _listener.find(event->getType());
304 if( listeners == _listener.end() )
307 BOOST_FOREACH(EventListener const& listener, listeners->second)
313 //----------------------------------------------------------------------------
314 bool Element::hitBound( const osg::Vec2f& pos,
315 const osg::Vec2f& local_pos ) const
317 const osg::Vec3f pos3(pos, 0);
319 // Drawables have a bounding box...
321 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
322 // ... for other elements, i.e. groups only a bounding sphere is available
324 return _transform->getBound().contains(osg::Vec3f(pos, 0));
327 //----------------------------------------------------------------------------
328 bool Element::isVisible() const
330 return _transform.valid() && _transform->getNodeMask() != 0;
333 //----------------------------------------------------------------------------
334 osg::MatrixTransform* Element::getMatrixTransform()
336 return _transform.get();
339 //----------------------------------------------------------------------------
340 osg::MatrixTransform const* Element::getMatrixTransform() const
342 return _transform.get();
345 //----------------------------------------------------------------------------
346 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
349 && child->getNameString() == NAME_TRANSFORM )
351 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
352 _transform_types.resize( child->getIndex() + 1 );
354 _transform_types[ child->getIndex() ] = TT_NONE;
355 _transform_dirty = true;
358 else if( parent->getParent() == _node
359 && parent->getNameString() == NAME_TRANSFORM )
361 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
363 const std::string& name = child->getNameString();
365 TransformType& type = _transform_types[parent->getIndex()];
369 else if( name == "t" )
371 else if( name == "rot" )
373 else if( name == "s" )
376 _transform_dirty = true;
383 //----------------------------------------------------------------------------
384 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
386 if( parent == _node )
388 if( child->getNameString() == NAME_TRANSFORM )
390 if( !_transform.valid() )
393 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
399 "Element::childRemoved: unknown transform: " << child->getPath()
404 _transform_types[ child->getIndex() ] = TT_NONE;
406 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
407 _transform_types.pop_back();
409 _transform_dirty = true;
412 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
414 if( setStyle(getParentStyle(child), style) )
422 //----------------------------------------------------------------------------
423 void Element::valueChanged(SGPropertyNode* child)
425 SGPropertyNode *parent = child->getParent();
426 if( parent == _node )
428 const std::string& name = child->getNameString();
429 if( StyleInfo const* style_info = getStyleInfo(name) )
431 SGPropertyNode const* style = child;
432 if( isStyleEmpty(child) )
435 style = getParentStyle(child);
437 setStyle(style, style_info);
440 else if( name == "update" )
442 else if( name == "visible" )
443 // TODO check if we need another nodemask
444 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
445 else if( boost::starts_with(name, "blend-") )
446 return (void)(_attributes_dirty |= BLEND_FUNC);
448 else if( parent->getParent() == _node
449 && parent->getNameString() == NAME_TRANSFORM )
451 _transform_dirty = true;
458 //----------------------------------------------------------------------------
459 bool Element::setStyle( const SGPropertyNode* child,
460 const StyleInfo* style_info )
462 return canApplyStyle(child) && setStyleImpl(child, style_info);
465 //----------------------------------------------------------------------------
466 void Element::setClip(const std::string& clip)
468 if( clip.empty() || clip == "auto" )
470 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
475 // TODO generalize CSS property parsing
476 const std::string RECT("rect(");
477 if( !boost::ends_with(clip, ")")
478 || !boost::starts_with(clip, RECT) )
480 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
484 const std::string sep(", \t\npx");
488 for(size_t pos = RECT.size(); comp < 4; ++comp)
490 pos = clip.find_first_not_of(sep, pos);
491 if( pos == std::string::npos || pos == clip.size() - 1 )
495 values[comp] = strtod(&clip[pos], &end);
496 if( end == &clip[pos] || !end )
499 pos = end - &clip[0];
504 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
508 float width = values[1] - values[3],
509 height = values[2] - values[0];
511 if( width < 0 || height < 0 )
513 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
517 _scissor = new RelativeScissor();
518 // <top>, <right>, <bottom>, <left>
519 _scissor->x() = SGMiscf::roundToInt(values[3]);
520 _scissor->y() = SGMiscf::roundToInt(values[0]);
521 _scissor->width() = SGMiscf::roundToInt(width);
522 _scissor->height() = SGMiscf::roundToInt(height);
524 getOrCreateStateSet()->setAttributeAndModes(_scissor);
526 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
528 valueChanged(clip_frame);
531 //----------------------------------------------------------------------------
532 void Element::setClipFrame(ReferenceFrame rf)
536 _scissor->_coord_reference = rf;
537 _attributes_dirty |= SCISSOR_COORDS;
541 //----------------------------------------------------------------------------
542 void Element::setBoundingBox(const osg::BoundingBox& bb)
544 if( _bounding_box.empty() )
546 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
547 _bounding_box.resize(4);
548 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
549 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
550 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
551 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
554 _bounding_box[0]->setFloatValue(bb._min.x());
555 _bounding_box[1]->setFloatValue(bb._min.y());
556 _bounding_box[2]->setFloatValue(bb._max.x());
557 _bounding_box[3]->setFloatValue(bb._max.y());
560 //----------------------------------------------------------------------------
561 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
564 return osg::BoundingBox();
566 osg::BoundingBox transformed;
567 const osg::BoundingBox& bb = _drawable->getBound();
568 for(int i = 0; i < 4; ++i)
569 transformed.expandBy( bb.corner(i) * m );
574 //----------------------------------------------------------------------------
575 Element::StyleSetters Element::_style_setters;
577 //----------------------------------------------------------------------------
578 Element::Element( const CanvasWeakPtr& canvas,
579 const SGPropertyNode_ptr& node,
580 const Style& parent_style,
582 PropertyBasedElement(node),
585 _attributes_dirty( 0 ),
586 _transform_dirty( false ),
587 _transform( new osg::MatrixTransform ),
588 _style( parent_style ),
598 "New canvas element " << node->getPath()
601 // Ensure elements are drawn in order they appear in the element tree
602 _transform->getOrCreateStateSet()
603 ->setRenderBinDetails
607 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
611 //----------------------------------------------------------------------------
612 void Element::staticInit()
614 if( isInit<Element>() )
617 addStyle("clip", "", &Element::setClip, false);
618 addStyle("clip-frame", "", &Element::setClipFrame, false);
621 //----------------------------------------------------------------------------
622 bool Element::isStyleEmpty(const SGPropertyNode* child) const
625 || simgear::strutils::strip(child->getStringValue()).empty();
628 //----------------------------------------------------------------------------
629 bool Element::canApplyStyle(const SGPropertyNode* child) const
631 if( _node == child->getParent() )
634 // Parent values do not override if element has own value
635 return isStyleEmpty( _node->getChild(child->getName()) );
638 //----------------------------------------------------------------------------
639 bool Element::setStyleImpl( const SGPropertyNode* child,
640 const StyleInfo* style_info )
642 const StyleSetter* style_setter = style_info
643 ? &style_info->setter
644 : getStyleSetter(child->getNameString());
645 while( style_setter )
647 if( style_setter->func(*this, child) )
649 style_setter = style_setter->next;
654 //----------------------------------------------------------------------------
655 const Element::StyleInfo*
656 Element::getStyleInfo(const std::string& name) const
658 StyleSetters::const_iterator setter = _style_setters.find(name);
659 if( setter == _style_setters.end() )
662 return &setter->second;
665 //----------------------------------------------------------------------------
666 const Element::StyleSetter*
667 Element::getStyleSetter(const std::string& name) const
669 const StyleInfo* info = getStyleInfo(name);
670 return info ? &info->setter : 0;
673 //----------------------------------------------------------------------------
674 const SGPropertyNode*
675 Element::getParentStyle(const SGPropertyNode* child) const
677 // Try to get value from parent...
680 Style::const_iterator style =
681 _parent->_style.find(child->getNameString());
682 if( style != _parent->_style.end() )
683 return style->second;
686 // ...or reset to default if none is available
687 return child; // TODO somehow get default value for each style?
690 //----------------------------------------------------------------------------
691 void Element::setDrawable( osg::Drawable* drawable )
693 _drawable = drawable;
696 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
697 geode->addDrawable(_drawable);
698 _transform->addChild(geode);
701 //----------------------------------------------------------------------------
702 osg::StateSet* Element::getOrCreateStateSet()
704 return _drawable ? _drawable->getOrCreateStateSet()
705 : _transform->getOrCreateStateSet();
708 //----------------------------------------------------------------------------
709 void Element::setupStyle()
711 BOOST_FOREACH( Style::value_type style, _style )
712 setStyle(style.second);
715 } // namespace canvas
716 } // namespace simgear