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/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/lexical_cast.hpp>
34 #include <boost/make_shared.hpp>
35 #include <boost/tokenizer.hpp>
44 const std::string NAME_TRANSFORM = "tf";
46 //----------------------------------------------------------------------------
47 Element::OSGUserData::OSGUserData(ElementPtr element):
53 //----------------------------------------------------------------------------
59 //----------------------------------------------------------------------------
60 void Element::setSelf(const PropertyBasedElementPtr& self)
62 PropertyBasedElement::setSelf(self);
64 _transform->setUserData
66 new OSGUserData(boost::static_pointer_cast<Element>(self))
70 //----------------------------------------------------------------------------
71 void Element::onDestroy()
73 if( !_transform.valid() )
76 // The transform node keeps a reference on this element, so ensure it is
78 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
80 parent->removeChild(_transform.get());
84 //----------------------------------------------------------------------------
85 ElementWeakPtr Element::getWeakPtr() const
87 return boost::static_pointer_cast<Element>(_self.lock());
90 //----------------------------------------------------------------------------
91 void Element::update(double dt)
93 if( !_transform->getNodeMask() )
94 // Don't do anything if element is hidden
97 if( _transform_dirty )
100 for( size_t i = 0; i < _transform_types.size(); ++i )
102 // Skip unused indizes...
103 if( _transform_types[i] == TT_NONE )
106 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
108 // Build up the matrix representation of the current transform node
110 switch( _transform_types[i] )
113 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
114 tf_node->getDoubleValue("m[1]", 0),
116 tf_node->getDoubleValue("m[6]", 0),
118 tf_node->getDoubleValue("m[2]", 0),
119 tf_node->getDoubleValue("m[3]", 1),
121 tf_node->getDoubleValue("m[7]", 0),
128 tf_node->getDoubleValue("m[4]", 0),
129 tf_node->getDoubleValue("m[5]", 0),
131 tf_node->getDoubleValue("m[8]", 1) );
134 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
135 tf_node->getDoubleValue("t[1]", 0),
139 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
143 float sx = tf_node->getDoubleValue("s[0]", 1);
144 // sy defaults to sx...
145 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
153 _transform->setMatrix(m);
154 _transform_dirty = false;
157 // Update bounding box on manual update (manual updates pass zero dt)
158 if( dt == 0 && _drawable )
159 _drawable->getBound();
161 if( _attributes_dirty & BLEND_FUNC )
164 _transform->getOrCreateStateSet(),
165 _node->getChild("blend-source"),
166 _node->getChild("blend-destination"),
167 _node->getChild("blend-source-rgb"),
168 _node->getChild("blend-destination-rgb"),
169 _node->getChild("blend-source-alpha"),
170 _node->getChild("blend-destination-alpha")
172 _attributes_dirty &= ~BLEND_FUNC;
176 //----------------------------------------------------------------------------
177 naRef Element::addEventListener(const nasal::CallContext& ctx)
179 const std::string type_str = ctx.requireArg<std::string>(0);
180 naRef code = ctx.requireArg<naRef>(1);
186 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
189 Event::Type type = Event::strToType(type_str);
190 if( type == Event::UNKNOWN )
191 naRuntimeError( ctx.c,
192 "addEventListener: Unknown event type %s",
195 _listener[ type ].push_back
197 boost::make_shared<EventListener>( code,
198 _canvas.lock()->getSystemAdapter() )
204 //----------------------------------------------------------------------------
205 void Element::clearEventListener()
210 //----------------------------------------------------------------------------
211 bool Element::accept(EventVisitor& visitor)
216 return visitor.apply(*this);
219 //----------------------------------------------------------------------------
220 bool Element::ascend(EventVisitor& visitor)
223 return _parent->accept(visitor);
227 //----------------------------------------------------------------------------
228 bool Element::traverse(EventVisitor& visitor)
233 //----------------------------------------------------------------------------
234 bool Element::handleEvent(canvas::EventPtr event)
236 ListenerMap::iterator listeners = _listener.find(event->getType());
237 if( listeners == _listener.end() )
240 BOOST_FOREACH(EventListenerPtr listener, listeners->second)
241 listener->call(event);
246 //----------------------------------------------------------------------------
247 bool Element::hitBound( const osg::Vec2f& pos,
248 const osg::Vec2f& local_pos ) const
250 const osg::Vec3f pos3(pos, 0);
252 // Drawables have a bounding box...
254 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
255 // ... for other elements, i.e. groups only a bounding sphere is available
257 return _transform->getBound().contains(osg::Vec3f(pos, 0));
260 //----------------------------------------------------------------------------
261 bool Element::isVisible() const
263 return _transform.valid() && _transform->getNodeMask() != 0;
266 //----------------------------------------------------------------------------
267 osg::MatrixTransform* Element::getMatrixTransform()
269 return _transform.get();
272 //----------------------------------------------------------------------------
273 osg::MatrixTransform const* Element::getMatrixTransform() const
275 return _transform.get();
278 //----------------------------------------------------------------------------
279 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
282 && child->getNameString() == NAME_TRANSFORM )
284 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
285 _transform_types.resize( child->getIndex() + 1 );
287 _transform_types[ child->getIndex() ] = TT_NONE;
288 _transform_dirty = true;
291 else if( parent->getParent() == _node
292 && parent->getNameString() == NAME_TRANSFORM )
294 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
296 const std::string& name = child->getNameString();
298 TransformType& type = _transform_types[parent->getIndex()];
302 else if( name == "t" )
304 else if( name == "rot" )
306 else if( name == "s" )
309 _transform_dirty = true;
316 //----------------------------------------------------------------------------
317 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
319 if( parent == _node )
321 if( child->getNameString() == NAME_TRANSFORM )
323 if( !_transform.valid() )
326 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
332 "Element::childRemoved: unknown transform: " << child->getPath()
337 _transform_types[ child->getIndex() ] = TT_NONE;
339 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
340 _transform_types.pop_back();
342 _transform_dirty = true;
345 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
347 if( setStyle(getParentStyle(child), style) )
355 //----------------------------------------------------------------------------
356 void Element::valueChanged(SGPropertyNode* child)
358 SGPropertyNode *parent = child->getParent();
359 if( parent == _node )
361 const std::string& name = child->getNameString();
362 if( StyleInfo const* style_info = getStyleInfo(name) )
364 SGPropertyNode const* style = child;
365 if( isStyleEmpty(child) )
368 style = getParentStyle(child);
370 setStyle(style, style_info);
373 else if( name == "update" )
375 else if( name == "visible" )
376 // TODO check if we need another nodemask
377 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
378 else if( boost::starts_with(name, "blend-") )
379 return (void)(_attributes_dirty |= BLEND_FUNC);
381 else if( parent->getParent() == _node
382 && parent->getNameString() == NAME_TRANSFORM )
384 _transform_dirty = true;
391 //----------------------------------------------------------------------------
392 bool Element::setStyle( const SGPropertyNode* child,
393 const StyleInfo* style_info )
395 return canApplyStyle(child) && setStyleImpl(child, style_info);
398 //----------------------------------------------------------------------------
399 void Element::setClip(const std::string& clip)
401 if( clip.empty() || clip == "auto" )
403 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
407 // TODO generalize CSS property parsing
408 const std::string RECT("rect(");
409 if( !boost::ends_with(clip, ")")
410 || !boost::starts_with(clip, RECT) )
412 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
416 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
417 const boost::char_separator<char> del(", \t\npx");
419 tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
422 for( tokenizer::const_iterator tok = tokens.begin();
423 tok != tokens.end() && comp < 4;
426 values[comp] = boost::lexical_cast<int>(*tok);
431 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
438 CanvasPtr canvas = _canvas.lock();
441 // The scissor rectangle isn't affected by any transformation, so we need
442 // to convert to image/canvas coordinates on our selves.
443 scale_x = canvas->getSizeX()
444 / static_cast<float>(canvas->getViewWidth());
445 scale_y = canvas->getSizeY()
446 / static_cast<float>(canvas->getViewHeight());
449 osg::Scissor* scissor = new osg::Scissor();
450 // <top>, <right>, <bottom>, <left>
451 scissor->x() = scale_x * values[3];
452 scissor->y() = scale_y * values[0];
453 scissor->width() = scale_x * (values[1] - values[3]);
454 scissor->height() = scale_y * (values[2] - values[0]);
457 // Canvas has y axis upside down
458 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
460 getOrCreateStateSet()->setAttributeAndModes(scissor);
463 //----------------------------------------------------------------------------
464 void Element::setBoundingBox(const osg::BoundingBox& bb)
466 if( _bounding_box.empty() )
468 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
469 _bounding_box.resize(4);
470 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
471 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
472 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
473 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
476 _bounding_box[0]->setFloatValue(bb._min.x());
477 _bounding_box[1]->setFloatValue(bb._min.y());
478 _bounding_box[2]->setFloatValue(bb._max.x());
479 _bounding_box[3]->setFloatValue(bb._max.y());
482 //----------------------------------------------------------------------------
483 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
486 return osg::BoundingBox();
488 osg::BoundingBox transformed;
489 const osg::BoundingBox& bb = _drawable->getBound();
490 for(int i = 0; i < 4; ++i)
491 transformed.expandBy( m * bb.corner(i) );
496 //----------------------------------------------------------------------------
497 Element::StyleSetters Element::_style_setters;
499 //----------------------------------------------------------------------------
500 Element::Element( const CanvasWeakPtr& canvas,
501 const SGPropertyNode_ptr& node,
502 const Style& parent_style,
504 PropertyBasedElement(node),
507 _attributes_dirty( 0 ),
508 _transform_dirty( false ),
509 _transform( new osg::MatrixTransform ),
510 _style( parent_style ),
517 "New canvas element " << node->getPath()
520 if( !isInit<Element>() )
522 addStyle("clip", "", &Element::setClip, false);
526 //----------------------------------------------------------------------------
527 bool Element::isStyleEmpty(const SGPropertyNode* child) const
530 || simgear::strutils::strip(child->getStringValue()).empty();
533 //----------------------------------------------------------------------------
534 bool Element::canApplyStyle(const SGPropertyNode* child) const
536 if( _node == child->getParent() )
539 // Parent values do not override if element has own value
540 return isStyleEmpty( _node->getChild(child->getName()) );
543 //----------------------------------------------------------------------------
544 bool Element::setStyleImpl( const SGPropertyNode* child,
545 const StyleInfo* style_info )
547 const StyleSetter* style_setter = style_info
548 ? &style_info->setter
549 : getStyleSetter(child->getNameString());
550 while( style_setter )
552 if( style_setter->func(*this, child) )
554 style_setter = style_setter->next;
559 //----------------------------------------------------------------------------
560 const Element::StyleInfo*
561 Element::getStyleInfo(const std::string& name) const
563 StyleSetters::const_iterator setter = _style_setters.find(name);
564 if( setter == _style_setters.end() )
567 return &setter->second;
570 //----------------------------------------------------------------------------
571 const Element::StyleSetter*
572 Element::getStyleSetter(const std::string& name) const
574 const StyleInfo* info = getStyleInfo(name);
575 return info ? &info->setter : 0;
578 //----------------------------------------------------------------------------
579 const SGPropertyNode*
580 Element::getParentStyle(const SGPropertyNode* child) const
582 // Try to get value from parent...
585 Style::const_iterator style =
586 _parent->_style.find(child->getNameString());
587 if( style != _parent->_style.end() )
588 return style->second;
591 // ...or reset to default if none is available
592 return child; // TODO somehow get default value for each style?
595 //----------------------------------------------------------------------------
596 void Element::setDrawable( osg::Drawable* drawable )
598 _drawable = drawable;
601 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
602 geode->addDrawable(_drawable);
603 _transform->addChild(geode);
606 //----------------------------------------------------------------------------
607 osg::StateSet* Element::getOrCreateStateSet()
609 return _drawable ? _drawable->getOrCreateStateSet()
610 : _transform->getOrCreateStateSet();
613 //----------------------------------------------------------------------------
614 void Element::setupStyle()
616 BOOST_FOREACH( Style::value_type style, _style )
617 setStyle(style.second);
620 } // namespace canvas
621 } // namespace simgear