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/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>
42 const std::string NAME_TRANSFORM = "tf";
44 //----------------------------------------------------------------------------
45 Element::OSGUserData::OSGUserData(ElementPtr element):
51 //----------------------------------------------------------------------------
57 //----------------------------------------------------------------------------
58 void Element::setSelf(const PropertyBasedElementPtr& self)
60 PropertyBasedElement::setSelf(self);
62 _transform->setUserData
64 new OSGUserData(boost::static_pointer_cast<Element>(self))
68 //----------------------------------------------------------------------------
69 void Element::onDestroy()
71 if( !_transform.valid() )
74 // The transform node keeps a reference on this element, so ensure it is
76 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
78 parent->removeChild(_transform.get());
82 //----------------------------------------------------------------------------
83 ElementWeakPtr Element::getWeakPtr() const
85 return boost::static_pointer_cast<Element>(_self.lock());
88 //----------------------------------------------------------------------------
89 void Element::update(double dt)
91 if( !_transform->getNodeMask() )
92 // Don't do anything if element is hidden
95 if( _transform_dirty )
98 for( size_t i = 0; i < _transform_types.size(); ++i )
100 // Skip unused indizes...
101 if( _transform_types[i] == TT_NONE )
104 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
106 // Build up the matrix representation of the current transform node
108 switch( _transform_types[i] )
111 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
112 tf_node->getDoubleValue("m[1]", 0),
114 tf_node->getDoubleValue("m[6]", 0),
116 tf_node->getDoubleValue("m[2]", 0),
117 tf_node->getDoubleValue("m[3]", 1),
119 tf_node->getDoubleValue("m[7]", 0),
126 tf_node->getDoubleValue("m[4]", 0),
127 tf_node->getDoubleValue("m[5]", 0),
129 tf_node->getDoubleValue("m[8]", 1) );
132 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
133 tf_node->getDoubleValue("t[1]", 0),
137 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
141 float sx = tf_node->getDoubleValue("s[0]", 1);
142 // sy defaults to sx...
143 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
151 _transform->setMatrix(m);
152 _transform_dirty = false;
155 // Update bounding box on manual update (manual updates pass zero dt)
156 if( dt == 0 && _drawable )
157 _drawable->getBound();
159 if( _attributes_dirty & BLEND_FUNC )
162 _transform->getOrCreateStateSet(),
163 _node->getChild("blend-source"),
164 _node->getChild("blend-destination"),
165 _node->getChild("blend-source-rgb"),
166 _node->getChild("blend-destination-rgb"),
167 _node->getChild("blend-source-alpha"),
168 _node->getChild("blend-destination-alpha")
170 _attributes_dirty &= ~BLEND_FUNC;
174 //----------------------------------------------------------------------------
175 bool Element::addEventListener( const std::string& type_str,
176 const EventListener& cb )
182 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
185 Event::Type type = Event::strToType(type_str);
186 if( type == Event::UNKNOWN )
190 "addEventListener: Unknown event type " << type_str );
194 _listener[ type ].push_back(cb);
199 //----------------------------------------------------------------------------
200 void Element::clearEventListener()
205 //----------------------------------------------------------------------------
206 bool Element::accept(EventVisitor& visitor)
211 return visitor.apply(*this);
214 //----------------------------------------------------------------------------
215 bool Element::ascend(EventVisitor& visitor)
218 return _parent->accept(visitor);
222 //----------------------------------------------------------------------------
223 bool Element::traverse(EventVisitor& visitor)
228 //----------------------------------------------------------------------------
229 bool Element::handleEvent(canvas::EventPtr event)
231 ListenerMap::iterator listeners = _listener.find(event->getType());
232 if( listeners == _listener.end() )
235 BOOST_FOREACH(EventListener const& listener, listeners->second)
241 //----------------------------------------------------------------------------
242 bool Element::hitBound( const osg::Vec2f& pos,
243 const osg::Vec2f& local_pos ) const
245 const osg::Vec3f pos3(pos, 0);
247 // Drawables have a bounding box...
249 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
250 // ... for other elements, i.e. groups only a bounding sphere is available
252 return _transform->getBound().contains(osg::Vec3f(pos, 0));
255 //----------------------------------------------------------------------------
256 bool Element::isVisible() const
258 return _transform.valid() && _transform->getNodeMask() != 0;
261 //----------------------------------------------------------------------------
262 osg::MatrixTransform* Element::getMatrixTransform()
264 return _transform.get();
267 //----------------------------------------------------------------------------
268 osg::MatrixTransform const* Element::getMatrixTransform() const
270 return _transform.get();
273 //----------------------------------------------------------------------------
274 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
277 && child->getNameString() == NAME_TRANSFORM )
279 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
280 _transform_types.resize( child->getIndex() + 1 );
282 _transform_types[ child->getIndex() ] = TT_NONE;
283 _transform_dirty = true;
286 else if( parent->getParent() == _node
287 && parent->getNameString() == NAME_TRANSFORM )
289 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
291 const std::string& name = child->getNameString();
293 TransformType& type = _transform_types[parent->getIndex()];
297 else if( name == "t" )
299 else if( name == "rot" )
301 else if( name == "s" )
304 _transform_dirty = true;
311 //----------------------------------------------------------------------------
312 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
314 if( parent == _node )
316 if( child->getNameString() == NAME_TRANSFORM )
318 if( !_transform.valid() )
321 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
327 "Element::childRemoved: unknown transform: " << child->getPath()
332 _transform_types[ child->getIndex() ] = TT_NONE;
334 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
335 _transform_types.pop_back();
337 _transform_dirty = true;
340 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
342 if( setStyle(getParentStyle(child), style) )
350 //----------------------------------------------------------------------------
351 void Element::valueChanged(SGPropertyNode* child)
353 SGPropertyNode *parent = child->getParent();
354 if( parent == _node )
356 const std::string& name = child->getNameString();
357 if( StyleInfo const* style_info = getStyleInfo(name) )
359 SGPropertyNode const* style = child;
360 if( isStyleEmpty(child) )
363 style = getParentStyle(child);
365 setStyle(style, style_info);
368 else if( name == "update" )
370 else if( name == "visible" )
371 // TODO check if we need another nodemask
372 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
373 else if( boost::starts_with(name, "blend-") )
374 return (void)(_attributes_dirty |= BLEND_FUNC);
376 else if( parent->getParent() == _node
377 && parent->getNameString() == NAME_TRANSFORM )
379 _transform_dirty = true;
386 //----------------------------------------------------------------------------
387 bool Element::setStyle( const SGPropertyNode* child,
388 const StyleInfo* style_info )
390 return canApplyStyle(child) && setStyleImpl(child, style_info);
393 //----------------------------------------------------------------------------
394 void Element::setClip(const std::string& clip)
396 if( clip.empty() || clip == "auto" )
398 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
402 // TODO generalize CSS property parsing
403 const std::string RECT("rect(");
404 if( !boost::ends_with(clip, ")")
405 || !boost::starts_with(clip, RECT) )
407 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
411 const std::string sep(", \t\npx");
415 for(size_t pos = RECT.size(); comp < 4; ++comp)
417 pos = clip.find_first_not_of(sep, pos);
418 if( pos == std::string::npos || pos == clip.size() - 1 )
422 values[comp] = strtod(&clip[pos], &end);
423 if( end == &clip[pos] || !end )
426 pos = end - &clip[0];
431 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
435 float width = values[1] - values[3],
436 height = values[2] - values[0];
438 if( width < 0 || height < 0 )
440 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
447 CanvasPtr canvas = _canvas.lock();
450 // The scissor rectangle isn't affected by any transformation, so we need
451 // to convert to image/canvas coordinates on our selves.
452 scale_x = canvas->getSizeX()
453 / static_cast<float>(canvas->getViewWidth());
454 scale_y = canvas->getSizeY()
455 / static_cast<float>(canvas->getViewHeight());
458 osg::Scissor* scissor = new osg::Scissor();
459 // <top>, <right>, <bottom>, <left>
460 scissor->x() = SGMiscf::roundToInt(scale_x * values[3]);
461 scissor->y() = SGMiscf::roundToInt(scale_y * values[0]);
462 scissor->width() = SGMiscf::roundToInt(scale_x * width);
463 scissor->height() = SGMiscf::roundToInt(scale_y * height);
466 // Canvas has y axis upside down
467 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
469 getOrCreateStateSet()->setAttributeAndModes(scissor);
472 //----------------------------------------------------------------------------
473 void Element::setBoundingBox(const osg::BoundingBox& bb)
475 if( _bounding_box.empty() )
477 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
478 _bounding_box.resize(4);
479 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
480 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
481 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
482 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
485 _bounding_box[0]->setFloatValue(bb._min.x());
486 _bounding_box[1]->setFloatValue(bb._min.y());
487 _bounding_box[2]->setFloatValue(bb._max.x());
488 _bounding_box[3]->setFloatValue(bb._max.y());
491 //----------------------------------------------------------------------------
492 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
495 return osg::BoundingBox();
497 osg::BoundingBox transformed;
498 const osg::BoundingBox& bb = _drawable->getBound();
499 for(int i = 0; i < 4; ++i)
500 transformed.expandBy( bb.corner(i) * m );
505 //----------------------------------------------------------------------------
506 Element::StyleSetters Element::_style_setters;
508 //----------------------------------------------------------------------------
509 Element::Element( const CanvasWeakPtr& canvas,
510 const SGPropertyNode_ptr& node,
511 const Style& parent_style,
513 PropertyBasedElement(node),
516 _attributes_dirty( 0 ),
517 _transform_dirty( false ),
518 _transform( new osg::MatrixTransform ),
519 _style( parent_style ),
528 "New canvas element " << node->getPath()
531 // Ensure elements are drawn in order they appear in the element tree
532 _transform->getOrCreateStateSet()
533 ->setRenderBinDetails
537 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
541 //----------------------------------------------------------------------------
542 void Element::staticInit()
544 if( isInit<Element>() )
547 addStyle("clip", "", &Element::setClip, false);
550 //----------------------------------------------------------------------------
551 bool Element::isStyleEmpty(const SGPropertyNode* child) const
554 || simgear::strutils::strip(child->getStringValue()).empty();
557 //----------------------------------------------------------------------------
558 bool Element::canApplyStyle(const SGPropertyNode* child) const
560 if( _node == child->getParent() )
563 // Parent values do not override if element has own value
564 return isStyleEmpty( _node->getChild(child->getName()) );
567 //----------------------------------------------------------------------------
568 bool Element::setStyleImpl( const SGPropertyNode* child,
569 const StyleInfo* style_info )
571 const StyleSetter* style_setter = style_info
572 ? &style_info->setter
573 : getStyleSetter(child->getNameString());
574 while( style_setter )
576 if( style_setter->func(*this, child) )
578 style_setter = style_setter->next;
583 //----------------------------------------------------------------------------
584 const Element::StyleInfo*
585 Element::getStyleInfo(const std::string& name) const
587 StyleSetters::const_iterator setter = _style_setters.find(name);
588 if( setter == _style_setters.end() )
591 return &setter->second;
594 //----------------------------------------------------------------------------
595 const Element::StyleSetter*
596 Element::getStyleSetter(const std::string& name) const
598 const StyleInfo* info = getStyleInfo(name);
599 return info ? &info->setter : 0;
602 //----------------------------------------------------------------------------
603 const SGPropertyNode*
604 Element::getParentStyle(const SGPropertyNode* child) const
606 // Try to get value from parent...
609 Style::const_iterator style =
610 _parent->_style.find(child->getNameString());
611 if( style != _parent->_style.end() )
612 return style->second;
615 // ...or reset to default if none is available
616 return child; // TODO somehow get default value for each style?
619 //----------------------------------------------------------------------------
620 void Element::setDrawable( osg::Drawable* drawable )
622 _drawable = drawable;
625 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
626 geode->addDrawable(_drawable);
627 _transform->addChild(geode);
630 //----------------------------------------------------------------------------
631 osg::StateSet* Element::getOrCreateStateSet()
633 return _drawable ? _drawable->getOrCreateStateSet()
634 : _transform->getOrCreateStateSet();
637 //----------------------------------------------------------------------------
638 void Element::setupStyle()
640 BOOST_FOREACH( Style::value_type style, _style )
641 setStyle(style.second);
644 } // namespace canvas
645 } // namespace simgear