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/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/lexical_cast.hpp>
33 #include <boost/make_shared.hpp>
34 #include <boost/tokenizer.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 naRef Element::addEventListener(const nasal::CallContext& ctx)
178 const std::string type_str = ctx.requireArg<std::string>(0);
179 naRef code = ctx.requireArg<naRef>(1);
185 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
188 Event::Type type = Event::strToType(type_str);
189 if( type == Event::UNKNOWN )
190 naRuntimeError( ctx.c,
191 "addEventListener: Unknown event type %s",
194 _listener[ type ].push_back
196 boost::make_shared<EventListener>( code,
197 _canvas.lock()->getSystemAdapter() )
203 //----------------------------------------------------------------------------
204 void Element::clearEventListener()
209 //----------------------------------------------------------------------------
210 bool Element::accept(EventVisitor& visitor)
215 return visitor.apply(*this);
218 //----------------------------------------------------------------------------
219 bool Element::ascend(EventVisitor& visitor)
222 return _parent->accept(visitor);
226 //----------------------------------------------------------------------------
227 bool Element::traverse(EventVisitor& visitor)
232 //----------------------------------------------------------------------------
233 bool Element::handleEvent(canvas::EventPtr event)
235 ListenerMap::iterator listeners = _listener.find(event->getType());
236 if( listeners == _listener.end() )
239 BOOST_FOREACH(EventListenerPtr listener, listeners->second)
240 listener->call(event);
245 //----------------------------------------------------------------------------
246 bool Element::hitBound( const osg::Vec2f& pos,
247 const osg::Vec2f& local_pos ) const
249 const osg::Vec3f pos3(pos, 0);
251 // Drawables have a bounding box...
253 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
254 // ... for other elements, i.e. groups only a bounding sphere is available
256 return _transform->getBound().contains(osg::Vec3f(pos, 0));
259 //----------------------------------------------------------------------------
260 bool Element::isVisible() const
262 return _transform.valid() && _transform->getNodeMask() != 0;
265 //----------------------------------------------------------------------------
266 osg::MatrixTransform* Element::getMatrixTransform()
268 return _transform.get();
271 //----------------------------------------------------------------------------
272 osg::MatrixTransform const* Element::getMatrixTransform() const
274 return _transform.get();
277 //----------------------------------------------------------------------------
278 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
281 && child->getNameString() == NAME_TRANSFORM )
283 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
284 _transform_types.resize( child->getIndex() + 1 );
286 _transform_types[ child->getIndex() ] = TT_NONE;
287 _transform_dirty = true;
290 else if( parent->getParent() == _node
291 && parent->getNameString() == NAME_TRANSFORM )
293 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
295 const std::string& name = child->getNameString();
297 TransformType& type = _transform_types[parent->getIndex()];
301 else if( name == "t" )
303 else if( name == "rot" )
305 else if( name == "s" )
308 _transform_dirty = true;
315 //----------------------------------------------------------------------------
316 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
318 if( parent == _node && child->getNameString() == NAME_TRANSFORM )
320 if( !_transform.valid() )
323 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
329 "Element::childRemoved: unknown transform: " << child->getPath()
334 _transform_types[ child->getIndex() ] = TT_NONE;
336 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
337 _transform_types.pop_back();
339 _transform_dirty = true;
346 //----------------------------------------------------------------------------
347 void Element::valueChanged(SGPropertyNode* child)
349 SGPropertyNode *parent = child->getParent();
350 if( parent == _node )
352 const std::string& name = child->getNameString();
353 if( setStyle(child) )
355 else if( name == "update" )
357 else if( name == "visible" )
358 // TODO check if we need another nodemask
359 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
360 else if( boost::starts_with(name, "blend-") )
361 return (void)(_attributes_dirty |= BLEND_FUNC);
363 else if( parent->getParent() == _node
364 && parent->getNameString() == NAME_TRANSFORM )
366 _transform_dirty = true;
373 //----------------------------------------------------------------------------
374 bool Element::setStyle(const SGPropertyNode* child)
376 StyleSetters::const_iterator setter =
377 _style_setters.find(child->getNameString());
378 if( setter == _style_setters.end() )
381 const StyleSetter* style_setter = &setter->second.setter;
382 while( style_setter )
384 if( style_setter->func(*this, child) )
386 style_setter = style_setter->next;
391 //----------------------------------------------------------------------------
392 void Element::setClip(const std::string& clip)
394 if( clip.empty() || clip == "auto" )
396 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
400 // TODO generalize CSS property parsing
401 const std::string RECT("rect(");
402 if( !boost::ends_with(clip, ")")
403 || !boost::starts_with(clip, RECT) )
405 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
409 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
410 const boost::char_separator<char> del(", \t\npx");
412 tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
415 for( tokenizer::const_iterator tok = tokens.begin();
416 tok != tokens.end() && comp < 4;
419 values[comp] = boost::lexical_cast<int>(*tok);
424 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
431 CanvasPtr canvas = _canvas.lock();
434 // The scissor rectangle isn't affected by any transformation, so we need
435 // to convert to image/canvas coordinates on our selves.
436 scale_x = canvas->getSizeX()
437 / static_cast<float>(canvas->getViewWidth());
438 scale_y = canvas->getSizeY()
439 / static_cast<float>(canvas->getViewHeight());
442 osg::Scissor* scissor = new osg::Scissor();
443 // <top>, <right>, <bottom>, <left>
444 scissor->x() = scale_x * values[3];
445 scissor->y() = scale_y * values[0];
446 scissor->width() = scale_x * (values[1] - values[3]);
447 scissor->height() = scale_y * (values[2] - values[0]);
450 // Canvas has y axis upside down
451 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
453 getOrCreateStateSet()->setAttributeAndModes(scissor);
456 //----------------------------------------------------------------------------
457 void Element::setBoundingBox(const osg::BoundingBox& bb)
459 if( _bounding_box.empty() )
461 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
462 _bounding_box.resize(4);
463 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
464 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
465 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
466 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
469 _bounding_box[0]->setFloatValue(bb._min.x());
470 _bounding_box[1]->setFloatValue(bb._min.y());
471 _bounding_box[2]->setFloatValue(bb._max.x());
472 _bounding_box[3]->setFloatValue(bb._max.y());
475 //----------------------------------------------------------------------------
476 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
479 return osg::BoundingBox();
481 osg::BoundingBox transformed;
482 const osg::BoundingBox& bb = _drawable->getBound();
483 for(int i = 0; i < 4; ++i)
484 transformed.expandBy( m * bb.corner(i) );
489 //----------------------------------------------------------------------------
490 Element::StyleSetters Element::_style_setters;
492 //----------------------------------------------------------------------------
493 Element::Element( const CanvasWeakPtr& canvas,
494 const SGPropertyNode_ptr& node,
495 const Style& parent_style,
497 PropertyBasedElement(node),
500 _attributes_dirty( 0 ),
501 _transform_dirty( false ),
502 _transform( new osg::MatrixTransform ),
503 _style( parent_style ),
510 "New canvas element " << node->getPath()
513 if( !isInit<Element>() )
515 addStyle("clip", "", &Element::setClip);
519 //----------------------------------------------------------------------------
520 void Element::setDrawable( osg::Drawable* drawable )
522 _drawable = drawable;
525 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
526 geode->addDrawable(_drawable);
527 _transform->addChild(geode);
530 //----------------------------------------------------------------------------
531 osg::StateSet* Element::getOrCreateStateSet()
533 return _drawable ? _drawable->getOrCreateStateSet()
534 : _transform->getOrCreateStateSet();
537 //----------------------------------------------------------------------------
538 void Element::setupStyle()
540 BOOST_FOREACH( Style::value_type style, _style )
541 setStyle(style.second);
544 } // namespace canvas
545 } // namespace simgear