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>
41 const std::string NAME_TRANSFORM = "tf";
44 * glScissor with coordinates relative to different reference frames.
46 class Element::RelativeScissor:
51 ReferenceFrame _coord_reference;
52 osg::Matrix _parent_inverse;
55 _coord_reference(GLOBAL)
58 virtual void apply(osg::State& state) const
60 const osg::Viewport* vp = state.getCurrentViewport();
61 float w2 = 0.5 * vp->width(),
62 h2 = 0.5 * vp->height();
64 osg::Matrix model_view
71 model_view.preMult(state.getProjectionMatrix());
73 if( _coord_reference != GLOBAL )
75 model_view.preMult(state.getModelViewMatrix());
77 if( _coord_reference == PARENT )
78 model_view.preMult(_parent_inverse);
81 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
82 offset(model_view(3,0), model_view(3,1));
84 // TODO check/warn for rotation?
86 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
87 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
88 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
89 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
96 glScissor(x, y, w, h);
100 //----------------------------------------------------------------------------
101 Element::OSGUserData::OSGUserData(ElementPtr element):
107 //----------------------------------------------------------------------------
113 //----------------------------------------------------------------------------
114 void Element::setSelf(const PropertyBasedElementPtr& self)
116 PropertyBasedElement::setSelf(self);
118 _transform->setUserData
120 new OSGUserData(boost::static_pointer_cast<Element>(self))
124 //----------------------------------------------------------------------------
125 void Element::onDestroy()
127 if( !_transform.valid() )
130 // The transform node keeps a reference on this element, so ensure it is
132 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
134 parent->removeChild(_transform.get());
138 //----------------------------------------------------------------------------
139 ElementWeakPtr Element::getWeakPtr() const
141 return boost::static_pointer_cast<Element>(_self.lock());
144 //----------------------------------------------------------------------------
145 ElementPtr Element::getParent()
147 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
150 //----------------------------------------------------------------------------
151 void Element::update(double dt)
153 if( !_transform->getNodeMask() )
154 // Don't do anything if element is hidden
157 if( _transform_dirty )
160 for( size_t i = 0; i < _transform_types.size(); ++i )
162 // Skip unused indizes...
163 if( _transform_types[i] == TT_NONE )
166 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
168 // Build up the matrix representation of the current transform node
170 switch( _transform_types[i] )
173 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
174 tf_node->getDoubleValue("m[1]", 0),
176 tf_node->getDoubleValue("m[6]", 0),
178 tf_node->getDoubleValue("m[2]", 0),
179 tf_node->getDoubleValue("m[3]", 1),
181 tf_node->getDoubleValue("m[7]", 0),
188 tf_node->getDoubleValue("m[4]", 0),
189 tf_node->getDoubleValue("m[5]", 0),
191 tf_node->getDoubleValue("m[8]", 1) );
194 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
195 tf_node->getDoubleValue("t[1]", 0),
199 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
203 float sx = tf_node->getDoubleValue("s[0]", 1);
204 // sy defaults to sx...
205 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
213 _transform->setMatrix(m);
214 _transform_dirty = false;
215 _attributes_dirty |= SCISSOR_COORDS;
218 if( _attributes_dirty & SCISSOR_COORDS )
220 if( _scissor && _scissor->_coord_reference != GLOBAL )
221 _scissor->_parent_inverse = _transform->getInverseMatrix();
223 _attributes_dirty &= ~SCISSOR_COORDS;
226 // Update bounding box on manual update (manual updates pass zero dt)
227 if( dt == 0 && _drawable )
228 _drawable->getBound();
230 if( _attributes_dirty & BLEND_FUNC )
233 _transform->getOrCreateStateSet(),
234 _node->getChild("blend-source"),
235 _node->getChild("blend-destination"),
236 _node->getChild("blend-source-rgb"),
237 _node->getChild("blend-destination-rgb"),
238 _node->getChild("blend-source-alpha"),
239 _node->getChild("blend-destination-alpha")
241 _attributes_dirty &= ~BLEND_FUNC;
245 //----------------------------------------------------------------------------
246 bool Element::addEventListener( const std::string& type_str,
247 const EventListener& cb )
253 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
256 Event::Type type = Event::strToType(type_str);
257 if( type == Event::UNKNOWN )
261 "addEventListener: Unknown event type " << type_str );
265 _listener[ type ].push_back(cb);
270 //----------------------------------------------------------------------------
271 void Element::clearEventListener()
276 //----------------------------------------------------------------------------
277 bool Element::accept(EventVisitor& visitor)
282 return visitor.apply(*this);
285 //----------------------------------------------------------------------------
286 bool Element::ascend(EventVisitor& visitor)
289 return _parent->accept(visitor);
293 //----------------------------------------------------------------------------
294 bool Element::traverse(EventVisitor& visitor)
299 //----------------------------------------------------------------------------
300 bool Element::handleEvent(canvas::EventPtr event)
302 ListenerMap::iterator listeners = _listener.find(event->getType());
303 if( listeners == _listener.end() )
306 BOOST_FOREACH(EventListener const& listener, listeners->second)
312 //----------------------------------------------------------------------------
313 bool Element::hitBound( const osg::Vec2f& pos,
314 const osg::Vec2f& local_pos ) const
316 const osg::Vec3f pos3(pos, 0);
318 // Drawables have a bounding box...
320 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
321 // ... for other elements, i.e. groups only a bounding sphere is available
323 return _transform->getBound().contains(osg::Vec3f(pos, 0));
326 //----------------------------------------------------------------------------
327 bool Element::isVisible() const
329 return _transform.valid() && _transform->getNodeMask() != 0;
332 //----------------------------------------------------------------------------
333 osg::MatrixTransform* Element::getMatrixTransform()
335 return _transform.get();
338 //----------------------------------------------------------------------------
339 osg::MatrixTransform const* Element::getMatrixTransform() const
341 return _transform.get();
344 //----------------------------------------------------------------------------
345 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
348 && child->getNameString() == NAME_TRANSFORM )
350 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
351 _transform_types.resize( child->getIndex() + 1 );
353 _transform_types[ child->getIndex() ] = TT_NONE;
354 _transform_dirty = true;
357 else if( parent->getParent() == _node
358 && parent->getNameString() == NAME_TRANSFORM )
360 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
362 const std::string& name = child->getNameString();
364 TransformType& type = _transform_types[parent->getIndex()];
368 else if( name == "t" )
370 else if( name == "rot" )
372 else if( name == "s" )
375 _transform_dirty = true;
382 //----------------------------------------------------------------------------
383 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
385 if( parent == _node )
387 if( child->getNameString() == NAME_TRANSFORM )
389 if( !_transform.valid() )
392 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
398 "Element::childRemoved: unknown transform: " << child->getPath()
403 _transform_types[ child->getIndex() ] = TT_NONE;
405 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
406 _transform_types.pop_back();
408 _transform_dirty = true;
411 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
413 if( setStyle(getParentStyle(child), style) )
421 //----------------------------------------------------------------------------
422 void Element::valueChanged(SGPropertyNode* child)
424 SGPropertyNode *parent = child->getParent();
425 if( parent == _node )
427 const std::string& name = child->getNameString();
428 if( StyleInfo const* style_info = getStyleInfo(name) )
430 SGPropertyNode const* style = child;
431 if( isStyleEmpty(child) )
434 style = getParentStyle(child);
436 setStyle(style, style_info);
439 else if( name == "update" )
441 else if( name == "visible" )
442 // TODO check if we need another nodemask
443 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
444 else if( boost::starts_with(name, "blend-") )
445 return (void)(_attributes_dirty |= BLEND_FUNC);
447 else if( parent->getParent() == _node
448 && parent->getNameString() == NAME_TRANSFORM )
450 _transform_dirty = true;
457 //----------------------------------------------------------------------------
458 bool Element::setStyle( const SGPropertyNode* child,
459 const StyleInfo* style_info )
461 return canApplyStyle(child) && setStyleImpl(child, style_info);
464 //----------------------------------------------------------------------------
465 void Element::setClip(const std::string& clip)
467 if( clip.empty() || clip == "auto" )
469 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
474 // TODO generalize CSS property parsing
475 const std::string RECT("rect(");
476 if( !boost::ends_with(clip, ")")
477 || !boost::starts_with(clip, RECT) )
479 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
483 const std::string sep(", \t\npx");
487 for(size_t pos = RECT.size(); comp < 4; ++comp)
489 pos = clip.find_first_not_of(sep, pos);
490 if( pos == std::string::npos || pos == clip.size() - 1 )
494 values[comp] = strtod(&clip[pos], &end);
495 if( end == &clip[pos] || !end )
498 pos = end - &clip[0];
503 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
507 float width = values[1] - values[3],
508 height = values[2] - values[0];
510 if( width < 0 || height < 0 )
512 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
516 _scissor = new RelativeScissor();
517 // <top>, <right>, <bottom>, <left>
518 _scissor->x() = SGMiscf::roundToInt(values[3]);
519 _scissor->y() = SGMiscf::roundToInt(values[0]);
520 _scissor->width() = SGMiscf::roundToInt(width);
521 _scissor->height() = SGMiscf::roundToInt(height);
523 getOrCreateStateSet()->setAttributeAndModes(_scissor);
525 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
527 valueChanged(clip_frame);
530 //----------------------------------------------------------------------------
531 void Element::setClipFrame(ReferenceFrame rf)
535 _scissor->_coord_reference = rf;
536 _attributes_dirty |= SCISSOR_COORDS;
540 //----------------------------------------------------------------------------
541 void Element::setBoundingBox(const osg::BoundingBox& bb)
543 if( _bounding_box.empty() )
545 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
546 _bounding_box.resize(4);
547 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
548 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
549 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
550 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
553 _bounding_box[0]->setFloatValue(bb._min.x());
554 _bounding_box[1]->setFloatValue(bb._min.y());
555 _bounding_box[2]->setFloatValue(bb._max.x());
556 _bounding_box[3]->setFloatValue(bb._max.y());
559 //----------------------------------------------------------------------------
560 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
563 return osg::BoundingBox();
565 osg::BoundingBox transformed;
566 const osg::BoundingBox& bb = _drawable->getBound();
567 for(int i = 0; i < 4; ++i)
568 transformed.expandBy( bb.corner(i) * m );
573 //----------------------------------------------------------------------------
574 Element::StyleSetters Element::_style_setters;
576 //----------------------------------------------------------------------------
577 Element::Element( const CanvasWeakPtr& canvas,
578 const SGPropertyNode_ptr& node,
579 const Style& parent_style,
581 PropertyBasedElement(node),
584 _attributes_dirty( 0 ),
585 _transform_dirty( false ),
586 _transform( new osg::MatrixTransform ),
587 _style( parent_style ),
597 "New canvas element " << node->getPath()
600 // Ensure elements are drawn in order they appear in the element tree
601 _transform->getOrCreateStateSet()
602 ->setRenderBinDetails
606 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
610 //----------------------------------------------------------------------------
611 void Element::staticInit()
613 if( isInit<Element>() )
616 addStyle("clip", "", &Element::setClip, false);
617 addStyle("clip-frame", "", &Element::setClipFrame, false);
620 //----------------------------------------------------------------------------
621 bool Element::isStyleEmpty(const SGPropertyNode* child) const
624 || simgear::strutils::strip(child->getStringValue()).empty();
627 //----------------------------------------------------------------------------
628 bool Element::canApplyStyle(const SGPropertyNode* child) const
630 if( _node == child->getParent() )
633 // Parent values do not override if element has own value
634 return isStyleEmpty( _node->getChild(child->getName()) );
637 //----------------------------------------------------------------------------
638 bool Element::setStyleImpl( const SGPropertyNode* child,
639 const StyleInfo* style_info )
641 const StyleSetter* style_setter = style_info
642 ? &style_info->setter
643 : getStyleSetter(child->getNameString());
644 while( style_setter )
646 if( style_setter->func(*this, child) )
648 style_setter = style_setter->next;
653 //----------------------------------------------------------------------------
654 const Element::StyleInfo*
655 Element::getStyleInfo(const std::string& name) const
657 StyleSetters::const_iterator setter = _style_setters.find(name);
658 if( setter == _style_setters.end() )
661 return &setter->second;
664 //----------------------------------------------------------------------------
665 const Element::StyleSetter*
666 Element::getStyleSetter(const std::string& name) const
668 const StyleInfo* info = getStyleInfo(name);
669 return info ? &info->setter : 0;
672 //----------------------------------------------------------------------------
673 const SGPropertyNode*
674 Element::getParentStyle(const SGPropertyNode* child) const
676 // Try to get value from parent...
679 Style::const_iterator style =
680 _parent->_style.find(child->getNameString());
681 if( style != _parent->_style.end() )
682 return style->second;
685 // ...or reset to default if none is available
686 return child; // TODO somehow get default value for each style?
689 //----------------------------------------------------------------------------
690 void Element::setDrawable( osg::Drawable* drawable )
692 _drawable = drawable;
695 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
696 geode->addDrawable(_drawable);
697 _transform->addChild(geode);
700 //----------------------------------------------------------------------------
701 osg::StateSet* Element::getOrCreateStateSet()
703 return _drawable ? _drawable->getOrCreateStateSet()
704 : _transform->getOrCreateStateSet();
707 //----------------------------------------------------------------------------
708 void Element::setupStyle()
710 BOOST_FOREACH( Style::value_type style, _style )
711 setStyle(style.second);
714 } // namespace canvas
715 } // namespace simgear