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/CanvasEventListener.hxx>
22 #include <simgear/canvas/CanvasEventVisitor.hxx>
23 #include <simgear/canvas/MouseEvent.hxx>
24 #include <simgear/math/SGMisc.hxx>
25 #include <simgear/misc/strutils.hxx>
26 #include <simgear/scene/material/parseBlendFunc.hxx>
28 #include <osg/Drawable>
30 #include <osg/Scissor>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/make_shared.hpp>
43 const std::string NAME_TRANSFORM = "tf";
45 //----------------------------------------------------------------------------
46 Element::OSGUserData::OSGUserData(ElementPtr element):
52 //----------------------------------------------------------------------------
58 //----------------------------------------------------------------------------
59 void Element::setSelf(const PropertyBasedElementPtr& self)
61 PropertyBasedElement::setSelf(self);
63 _transform->setUserData
65 new OSGUserData(boost::static_pointer_cast<Element>(self))
69 //----------------------------------------------------------------------------
70 void Element::onDestroy()
72 if( !_transform.valid() )
75 // The transform node keeps a reference on this element, so ensure it is
77 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
79 parent->removeChild(_transform.get());
83 //----------------------------------------------------------------------------
84 ElementWeakPtr Element::getWeakPtr() const
86 return boost::static_pointer_cast<Element>(_self.lock());
89 //----------------------------------------------------------------------------
90 void Element::update(double dt)
92 if( !_transform->getNodeMask() )
93 // Don't do anything if element is hidden
96 if( _transform_dirty )
99 for( size_t i = 0; i < _transform_types.size(); ++i )
101 // Skip unused indizes...
102 if( _transform_types[i] == TT_NONE )
105 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
107 // Build up the matrix representation of the current transform node
109 switch( _transform_types[i] )
112 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
113 tf_node->getDoubleValue("m[1]", 0),
115 tf_node->getDoubleValue("m[6]", 0),
117 tf_node->getDoubleValue("m[2]", 0),
118 tf_node->getDoubleValue("m[3]", 1),
120 tf_node->getDoubleValue("m[7]", 0),
127 tf_node->getDoubleValue("m[4]", 0),
128 tf_node->getDoubleValue("m[5]", 0),
130 tf_node->getDoubleValue("m[8]", 1) );
133 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
134 tf_node->getDoubleValue("t[1]", 0),
138 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
142 float sx = tf_node->getDoubleValue("s[0]", 1);
143 // sy defaults to sx...
144 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
152 _transform->setMatrix(m);
153 _transform_dirty = false;
156 // Update bounding box on manual update (manual updates pass zero dt)
157 if( dt == 0 && _drawable )
158 _drawable->getBound();
160 if( _attributes_dirty & BLEND_FUNC )
163 _transform->getOrCreateStateSet(),
164 _node->getChild("blend-source"),
165 _node->getChild("blend-destination"),
166 _node->getChild("blend-source-rgb"),
167 _node->getChild("blend-destination-rgb"),
168 _node->getChild("blend-source-alpha"),
169 _node->getChild("blend-destination-alpha")
171 _attributes_dirty &= ~BLEND_FUNC;
175 //----------------------------------------------------------------------------
176 bool Element::addEventListener( const std::string& type_str,
177 const EventListener& cb )
183 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
186 Event::Type type = Event::strToType(type_str);
187 if( type == Event::UNKNOWN )
191 "addEventListener: Unknown event type " << type_str );
195 _listener[ type ].push_back(cb);
200 //----------------------------------------------------------------------------
201 bool Element::addNasalEventListener(const std::string& type, naRef code)
203 SGSharedPtr<NasalEventListener> listener =
204 new NasalEventListener(code, _canvas.lock()->getSystemAdapter());
206 return addEventListener
209 boost::bind(&NasalEventListener::operator(), listener, _1)
213 //----------------------------------------------------------------------------
214 void Element::clearEventListener()
219 //----------------------------------------------------------------------------
220 bool Element::accept(EventVisitor& visitor)
225 return visitor.apply(*this);
228 //----------------------------------------------------------------------------
229 bool Element::ascend(EventVisitor& visitor)
232 return _parent->accept(visitor);
236 //----------------------------------------------------------------------------
237 bool Element::traverse(EventVisitor& visitor)
242 //----------------------------------------------------------------------------
243 bool Element::handleEvent(canvas::EventPtr event)
245 ListenerMap::iterator listeners = _listener.find(event->getType());
246 if( listeners == _listener.end() )
249 BOOST_FOREACH(EventListener const& listener, listeners->second)
255 //----------------------------------------------------------------------------
256 bool Element::hitBound( const osg::Vec2f& pos,
257 const osg::Vec2f& local_pos ) const
259 const osg::Vec3f pos3(pos, 0);
261 // Drawables have a bounding box...
263 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
264 // ... for other elements, i.e. groups only a bounding sphere is available
266 return _transform->getBound().contains(osg::Vec3f(pos, 0));
269 //----------------------------------------------------------------------------
270 bool Element::isVisible() const
272 return _transform.valid() && _transform->getNodeMask() != 0;
275 //----------------------------------------------------------------------------
276 osg::MatrixTransform* Element::getMatrixTransform()
278 return _transform.get();
281 //----------------------------------------------------------------------------
282 osg::MatrixTransform const* Element::getMatrixTransform() const
284 return _transform.get();
287 //----------------------------------------------------------------------------
288 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
291 && child->getNameString() == NAME_TRANSFORM )
293 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
294 _transform_types.resize( child->getIndex() + 1 );
296 _transform_types[ child->getIndex() ] = TT_NONE;
297 _transform_dirty = true;
300 else if( parent->getParent() == _node
301 && parent->getNameString() == NAME_TRANSFORM )
303 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
305 const std::string& name = child->getNameString();
307 TransformType& type = _transform_types[parent->getIndex()];
311 else if( name == "t" )
313 else if( name == "rot" )
315 else if( name == "s" )
318 _transform_dirty = true;
325 //----------------------------------------------------------------------------
326 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
328 if( parent == _node )
330 if( child->getNameString() == NAME_TRANSFORM )
332 if( !_transform.valid() )
335 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
341 "Element::childRemoved: unknown transform: " << child->getPath()
346 _transform_types[ child->getIndex() ] = TT_NONE;
348 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
349 _transform_types.pop_back();
351 _transform_dirty = true;
354 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
356 if( setStyle(getParentStyle(child), style) )
364 //----------------------------------------------------------------------------
365 void Element::valueChanged(SGPropertyNode* child)
367 SGPropertyNode *parent = child->getParent();
368 if( parent == _node )
370 const std::string& name = child->getNameString();
371 if( StyleInfo const* style_info = getStyleInfo(name) )
373 SGPropertyNode const* style = child;
374 if( isStyleEmpty(child) )
377 style = getParentStyle(child);
379 setStyle(style, style_info);
382 else if( name == "update" )
384 else if( name == "visible" )
385 // TODO check if we need another nodemask
386 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
387 else if( boost::starts_with(name, "blend-") )
388 return (void)(_attributes_dirty |= BLEND_FUNC);
390 else if( parent->getParent() == _node
391 && parent->getNameString() == NAME_TRANSFORM )
393 _transform_dirty = true;
400 //----------------------------------------------------------------------------
401 bool Element::setStyle( const SGPropertyNode* child,
402 const StyleInfo* style_info )
404 return canApplyStyle(child) && setStyleImpl(child, style_info);
407 //----------------------------------------------------------------------------
408 void Element::setClip(const std::string& clip)
410 if( clip.empty() || clip == "auto" )
412 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
416 // TODO generalize CSS property parsing
417 const std::string RECT("rect(");
418 if( !boost::ends_with(clip, ")")
419 || !boost::starts_with(clip, RECT) )
421 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
425 const std::string sep(", \t\npx");
429 for(size_t pos = RECT.size(); comp < 4; ++comp)
431 pos = clip.find_first_not_of(sep, pos);
432 if( pos == std::string::npos || pos == clip.size() - 1 )
436 values[comp] = strtod(&clip[pos], &end);
437 if( end == &clip[pos] || !end )
440 pos = end - &clip[0];
445 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
449 float width = values[1] - values[3],
450 height = values[2] - values[0];
452 if( width < 0 || height < 0 )
454 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
461 CanvasPtr canvas = _canvas.lock();
464 // The scissor rectangle isn't affected by any transformation, so we need
465 // to convert to image/canvas coordinates on our selves.
466 scale_x = canvas->getSizeX()
467 / static_cast<float>(canvas->getViewWidth());
468 scale_y = canvas->getSizeY()
469 / static_cast<float>(canvas->getViewHeight());
472 osg::Scissor* scissor = new osg::Scissor();
473 // <top>, <right>, <bottom>, <left>
474 scissor->x() = SGMiscf::roundToInt(scale_x * values[3]);
475 scissor->y() = SGMiscf::roundToInt(scale_y * values[0]);
476 scissor->width() = SGMiscf::roundToInt(scale_x * width);
477 scissor->height() = SGMiscf::roundToInt(scale_y * height);
480 // Canvas has y axis upside down
481 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
483 getOrCreateStateSet()->setAttributeAndModes(scissor);
486 //----------------------------------------------------------------------------
487 void Element::setBoundingBox(const osg::BoundingBox& bb)
489 if( _bounding_box.empty() )
491 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
492 _bounding_box.resize(4);
493 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
494 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
495 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
496 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
499 _bounding_box[0]->setFloatValue(bb._min.x());
500 _bounding_box[1]->setFloatValue(bb._min.y());
501 _bounding_box[2]->setFloatValue(bb._max.x());
502 _bounding_box[3]->setFloatValue(bb._max.y());
505 //----------------------------------------------------------------------------
506 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
509 return osg::BoundingBox();
511 osg::BoundingBox transformed;
512 const osg::BoundingBox& bb = _drawable->getBound();
513 for(int i = 0; i < 4; ++i)
514 transformed.expandBy( bb.corner(i) * m );
519 //----------------------------------------------------------------------------
520 Element::StyleSetters Element::_style_setters;
522 //----------------------------------------------------------------------------
523 Element::Element( const CanvasWeakPtr& canvas,
524 const SGPropertyNode_ptr& node,
525 const Style& parent_style,
527 PropertyBasedElement(node),
530 _attributes_dirty( 0 ),
531 _transform_dirty( false ),
532 _transform( new osg::MatrixTransform ),
533 _style( parent_style ),
542 "New canvas element " << node->getPath()
545 // Ensure elements are drawn in order they appear in the element tree
546 _transform->getOrCreateStateSet()
547 ->setRenderBinDetails
551 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
555 //----------------------------------------------------------------------------
556 void Element::staticInit()
558 if( isInit<Element>() )
561 addStyle("clip", "", &Element::setClip, false);
564 //----------------------------------------------------------------------------
565 bool Element::isStyleEmpty(const SGPropertyNode* child) const
568 || simgear::strutils::strip(child->getStringValue()).empty();
571 //----------------------------------------------------------------------------
572 bool Element::canApplyStyle(const SGPropertyNode* child) const
574 if( _node == child->getParent() )
577 // Parent values do not override if element has own value
578 return isStyleEmpty( _node->getChild(child->getName()) );
581 //----------------------------------------------------------------------------
582 bool Element::setStyleImpl( const SGPropertyNode* child,
583 const StyleInfo* style_info )
585 const StyleSetter* style_setter = style_info
586 ? &style_info->setter
587 : getStyleSetter(child->getNameString());
588 while( style_setter )
590 if( style_setter->func(*this, child) )
592 style_setter = style_setter->next;
597 //----------------------------------------------------------------------------
598 const Element::StyleInfo*
599 Element::getStyleInfo(const std::string& name) const
601 StyleSetters::const_iterator setter = _style_setters.find(name);
602 if( setter == _style_setters.end() )
605 return &setter->second;
608 //----------------------------------------------------------------------------
609 const Element::StyleSetter*
610 Element::getStyleSetter(const std::string& name) const
612 const StyleInfo* info = getStyleInfo(name);
613 return info ? &info->setter : 0;
616 //----------------------------------------------------------------------------
617 const SGPropertyNode*
618 Element::getParentStyle(const SGPropertyNode* child) const
620 // Try to get value from parent...
623 Style::const_iterator style =
624 _parent->_style.find(child->getNameString());
625 if( style != _parent->_style.end() )
626 return style->second;
629 // ...or reset to default if none is available
630 return child; // TODO somehow get default value for each style?
633 //----------------------------------------------------------------------------
634 void Element::setDrawable( osg::Drawable* drawable )
636 _drawable = drawable;
639 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
640 geode->addDrawable(_drawable);
641 _transform->addChild(geode);
644 //----------------------------------------------------------------------------
645 osg::StateSet* Element::getOrCreateStateSet()
647 return _drawable ? _drawable->getOrCreateStateSet()
648 : _transform->getOrCreateStateSet();
651 //----------------------------------------------------------------------------
652 void Element::setupStyle()
654 BOOST_FOREACH( Style::value_type style, _style )
655 setStyle(style.second);
658 } // namespace canvas
659 } // namespace simgear