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/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 naRef Element::addEventListener(const nasal::CallContext& ctx)
177 const std::string type_str = ctx.requireArg<std::string>(0);
178 naRef code = ctx.requireArg<naRef>(1);
184 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
187 Event::Type type = Event::strToType(type_str);
188 if( type == Event::UNKNOWN )
189 naRuntimeError( ctx.c,
190 "addEventListener: Unknown event type %s",
193 _listener[ type ].push_back
195 boost::make_shared<EventListener>( code,
196 _canvas.lock()->getSystemAdapter() )
202 //----------------------------------------------------------------------------
203 void Element::clearEventListener()
208 //----------------------------------------------------------------------------
209 bool Element::accept(EventVisitor& visitor)
214 return visitor.apply(*this);
217 //----------------------------------------------------------------------------
218 bool Element::ascend(EventVisitor& visitor)
221 return _parent->accept(visitor);
225 //----------------------------------------------------------------------------
226 bool Element::traverse(EventVisitor& visitor)
231 //----------------------------------------------------------------------------
232 bool Element::handleEvent(canvas::EventPtr event)
234 ListenerMap::iterator listeners = _listener.find(event->getType());
235 if( listeners == _listener.end() )
238 BOOST_FOREACH(EventListenerPtr listener, listeners->second)
239 listener->call(event);
244 //----------------------------------------------------------------------------
245 bool Element::hitBound( const osg::Vec2f& pos,
246 const osg::Vec2f& local_pos ) const
248 const osg::Vec3f pos3(pos, 0);
250 // Drawables have a bounding box...
252 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
253 // ... for other elements, i.e. groups only a bounding sphere is available
255 return _transform->getBound().contains(osg::Vec3f(pos, 0));
258 //----------------------------------------------------------------------------
259 bool Element::isVisible() const
261 return _transform.valid() && _transform->getNodeMask() != 0;
264 //----------------------------------------------------------------------------
265 osg::MatrixTransform* Element::getMatrixTransform()
267 return _transform.get();
270 //----------------------------------------------------------------------------
271 osg::MatrixTransform const* Element::getMatrixTransform() const
273 return _transform.get();
276 //----------------------------------------------------------------------------
277 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
280 && child->getNameString() == NAME_TRANSFORM )
282 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
283 _transform_types.resize( child->getIndex() + 1 );
285 _transform_types[ child->getIndex() ] = TT_NONE;
286 _transform_dirty = true;
289 else if( parent->getParent() == _node
290 && parent->getNameString() == NAME_TRANSFORM )
292 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
294 const std::string& name = child->getNameString();
296 TransformType& type = _transform_types[parent->getIndex()];
300 else if( name == "t" )
302 else if( name == "rot" )
304 else if( name == "s" )
307 _transform_dirty = true;
314 //----------------------------------------------------------------------------
315 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
317 if( parent == _node )
319 if( child->getNameString() == NAME_TRANSFORM )
321 if( !_transform.valid() )
324 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
330 "Element::childRemoved: unknown transform: " << child->getPath()
335 _transform_types[ child->getIndex() ] = TT_NONE;
337 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
338 _transform_types.pop_back();
340 _transform_dirty = true;
343 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
345 if( setStyle(getParentStyle(child), style) )
353 //----------------------------------------------------------------------------
354 void Element::valueChanged(SGPropertyNode* child)
356 SGPropertyNode *parent = child->getParent();
357 if( parent == _node )
359 const std::string& name = child->getNameString();
360 if( StyleInfo const* style_info = getStyleInfo(name) )
362 SGPropertyNode const* style = child;
363 if( isStyleEmpty(child) )
366 style = getParentStyle(child);
368 setStyle(style, style_info);
371 else if( name == "update" )
373 else if( name == "visible" )
374 // TODO check if we need another nodemask
375 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
376 else if( boost::starts_with(name, "blend-") )
377 return (void)(_attributes_dirty |= BLEND_FUNC);
379 else if( parent->getParent() == _node
380 && parent->getNameString() == NAME_TRANSFORM )
382 _transform_dirty = true;
389 //----------------------------------------------------------------------------
390 bool Element::setStyle( const SGPropertyNode* child,
391 const StyleInfo* style_info )
393 return canApplyStyle(child) && setStyleImpl(child, style_info);
396 //----------------------------------------------------------------------------
397 void Element::setClip(const std::string& clip)
399 if( clip.empty() || clip == "auto" )
401 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
405 // TODO generalize CSS property parsing
406 const std::string RECT("rect(");
407 if( !boost::ends_with(clip, ")")
408 || !boost::starts_with(clip, RECT) )
410 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
414 const std::string sep(", \t\npx");
418 for(size_t pos = RECT.size(); comp < 4; ++comp)
420 pos = clip.find_first_not_of(sep, pos);
421 if( pos == std::string::npos || pos == clip.size() - 1 )
425 values[comp] = strtod(&clip[pos], &end);
426 if( end == &clip[pos] || !end )
429 pos = end - &clip[0];
434 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
441 CanvasPtr canvas = _canvas.lock();
444 // The scissor rectangle isn't affected by any transformation, so we need
445 // to convert to image/canvas coordinates on our selves.
446 scale_x = canvas->getSizeX()
447 / static_cast<float>(canvas->getViewWidth());
448 scale_y = canvas->getSizeY()
449 / static_cast<float>(canvas->getViewHeight());
452 osg::Scissor* scissor = new osg::Scissor();
453 // <top>, <right>, <bottom>, <left>
454 scissor->x() = scale_x * values[3];
455 scissor->y() = scale_y * values[0];
456 scissor->width() = scale_x * (values[1] - values[3]);
457 scissor->height() = scale_y * (values[2] - values[0]);
460 // Canvas has y axis upside down
461 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
463 getOrCreateStateSet()->setAttributeAndModes(scissor);
466 //----------------------------------------------------------------------------
467 void Element::setBoundingBox(const osg::BoundingBox& bb)
469 if( _bounding_box.empty() )
471 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
472 _bounding_box.resize(4);
473 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
474 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
475 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
476 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
479 _bounding_box[0]->setFloatValue(bb._min.x());
480 _bounding_box[1]->setFloatValue(bb._min.y());
481 _bounding_box[2]->setFloatValue(bb._max.x());
482 _bounding_box[3]->setFloatValue(bb._max.y());
485 //----------------------------------------------------------------------------
486 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
489 return osg::BoundingBox();
491 osg::BoundingBox transformed;
492 const osg::BoundingBox& bb = _drawable->getBound();
493 for(int i = 0; i < 4; ++i)
494 transformed.expandBy( bb.corner(i) * m );
499 //----------------------------------------------------------------------------
500 Element::StyleSetters Element::_style_setters;
502 //----------------------------------------------------------------------------
503 Element::Element( const CanvasWeakPtr& canvas,
504 const SGPropertyNode_ptr& node,
505 const Style& parent_style,
507 PropertyBasedElement(node),
510 _attributes_dirty( 0 ),
511 _transform_dirty( false ),
512 _transform( new osg::MatrixTransform ),
513 _style( parent_style ),
520 "New canvas element " << node->getPath()
523 if( !isInit<Element>() )
525 addStyle("clip", "", &Element::setClip, false);
528 // Ensure elements are drawn in order they appear in the element tree
529 _transform->getOrCreateStateSet()
530 ->setRenderBinDetails
534 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
538 //----------------------------------------------------------------------------
539 bool Element::isStyleEmpty(const SGPropertyNode* child) const
542 || simgear::strutils::strip(child->getStringValue()).empty();
545 //----------------------------------------------------------------------------
546 bool Element::canApplyStyle(const SGPropertyNode* child) const
548 if( _node == child->getParent() )
551 // Parent values do not override if element has own value
552 return isStyleEmpty( _node->getChild(child->getName()) );
555 //----------------------------------------------------------------------------
556 bool Element::setStyleImpl( const SGPropertyNode* child,
557 const StyleInfo* style_info )
559 const StyleSetter* style_setter = style_info
560 ? &style_info->setter
561 : getStyleSetter(child->getNameString());
562 while( style_setter )
564 if( style_setter->func(*this, child) )
566 style_setter = style_setter->next;
571 //----------------------------------------------------------------------------
572 const Element::StyleInfo*
573 Element::getStyleInfo(const std::string& name) const
575 StyleSetters::const_iterator setter = _style_setters.find(name);
576 if( setter == _style_setters.end() )
579 return &setter->second;
582 //----------------------------------------------------------------------------
583 const Element::StyleSetter*
584 Element::getStyleSetter(const std::string& name) const
586 const StyleInfo* info = getStyleInfo(name);
587 return info ? &info->setter : 0;
590 //----------------------------------------------------------------------------
591 const SGPropertyNode*
592 Element::getParentStyle(const SGPropertyNode* child) const
594 // Try to get value from parent...
597 Style::const_iterator style =
598 _parent->_style.find(child->getNameString());
599 if( style != _parent->_style.end() )
600 return style->second;
603 // ...or reset to default if none is available
604 return child; // TODO somehow get default value for each style?
607 //----------------------------------------------------------------------------
608 void Element::setDrawable( osg::Drawable* drawable )
610 _drawable = drawable;
613 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
614 geode->addDrawable(_drawable);
615 _transform->addChild(geode);
618 //----------------------------------------------------------------------------
619 osg::StateSet* Element::getOrCreateStateSet()
621 return _drawable ? _drawable->getOrCreateStateSet()
622 : _transform->getOrCreateStateSet();
625 //----------------------------------------------------------------------------
626 void Element::setupStyle()
628 BOOST_FOREACH( Style::value_type style, _style )
629 setStyle(style.second);
632 } // namespace canvas
633 } // namespace simgear