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 void Element::removeListener()
48 _node->removeChangeListener(this);
51 //----------------------------------------------------------------------------
56 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
58 parent->removeChild(_transform);
62 //----------------------------------------------------------------------------
63 ElementWeakPtr Element::getWeakPtr() const
65 return boost::static_pointer_cast<Element>(_self.lock());
68 //----------------------------------------------------------------------------
69 void Element::update(double dt)
71 if( !_transform->getNodeMask() )
72 // Don't do anything if element is hidden
75 if( _transform_dirty )
78 for( size_t i = 0; i < _transform_types.size(); ++i )
80 // Skip unused indizes...
81 if( _transform_types[i] == TT_NONE )
84 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
86 // Build up the matrix representation of the current transform node
88 switch( _transform_types[i] )
91 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
92 tf_node->getDoubleValue("m[1]", 0),
94 tf_node->getDoubleValue("m[6]", 0),
96 tf_node->getDoubleValue("m[2]", 0),
97 tf_node->getDoubleValue("m[3]", 1),
99 tf_node->getDoubleValue("m[7]", 0),
106 tf_node->getDoubleValue("m[4]", 0),
107 tf_node->getDoubleValue("m[5]", 0),
109 tf_node->getDoubleValue("m[8]", 1) );
112 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
113 tf_node->getDoubleValue("t[1]", 0),
117 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
121 float sx = tf_node->getDoubleValue("s[0]", 1);
122 // sy defaults to sx...
123 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
131 _transform->setMatrix(m);
132 _transform_dirty = false;
135 // Update bounding box on manual update (manual updates pass zero dt)
136 if( dt == 0 && _drawable )
137 _drawable->getBound();
139 if( _attributes_dirty & BLEND_FUNC )
142 _transform->getOrCreateStateSet(),
143 _node->getChild("blend-source"),
144 _node->getChild("blend-destination"),
145 _node->getChild("blend-source-rgb"),
146 _node->getChild("blend-destination-rgb"),
147 _node->getChild("blend-source-alpha"),
148 _node->getChild("blend-destination-alpha")
150 _attributes_dirty &= ~BLEND_FUNC;
154 //----------------------------------------------------------------------------
155 naRef Element::addEventListener(const nasal::CallContext& ctx)
157 const std::string type_str = ctx.requireArg<std::string>(0);
158 naRef code = ctx.requireArg<naRef>(1);
164 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
167 Event::Type type = Event::strToType(type_str);
168 if( type == Event::UNKNOWN )
169 naRuntimeError( ctx.c,
170 "addEventListener: Unknown event type %s",
173 _listener[ type ].push_back
175 boost::make_shared<EventListener>( code,
176 _canvas.lock()->getSystemAdapter() )
182 //----------------------------------------------------------------------------
183 void Element::clearEventListener()
188 //----------------------------------------------------------------------------
189 bool Element::accept(EventVisitor& visitor)
191 return visitor.apply(*this);
194 //----------------------------------------------------------------------------
195 bool Element::ascend(EventVisitor& visitor)
198 return _parent->accept(visitor);
202 //----------------------------------------------------------------------------
203 bool Element::traverse(EventVisitor& visitor)
208 //----------------------------------------------------------------------------
209 bool Element::handleEvent(canvas::EventPtr event)
211 ListenerMap::iterator listeners = _listener.find(event->getType());
212 if( listeners == _listener.end() )
215 BOOST_FOREACH(EventListenerPtr listener, listeners->second)
216 listener->call(event);
221 //----------------------------------------------------------------------------
222 bool Element::hitBound( const osg::Vec2f& pos,
223 const osg::Vec2f& local_pos ) const
225 const osg::Vec3f pos3(pos, 0);
227 // Drawables have a bounding box...
229 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
230 // ... for other elements, i.e. groups only a bounding sphere is available
232 return _transform->getBound().contains(osg::Vec3f(pos, 0));
235 //----------------------------------------------------------------------------
236 bool Element::isVisible() const
238 return _transform->getNodeMask() != 0;
241 //----------------------------------------------------------------------------
242 osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform()
247 osg::ref_ptr<osg::MatrixTransform const> Element::getMatrixTransform() const
252 //----------------------------------------------------------------------------
253 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
256 && child->getNameString() == NAME_TRANSFORM )
258 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
259 _transform_types.resize( child->getIndex() + 1 );
261 _transform_types[ child->getIndex() ] = TT_NONE;
262 _transform_dirty = true;
265 else if( parent->getParent() == _node
266 && parent->getNameString() == NAME_TRANSFORM )
268 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
270 const std::string& name = child->getNameString();
272 TransformType& type = _transform_types[parent->getIndex()];
276 else if( name == "t" )
278 else if( name == "rot" )
280 else if( name == "s" )
283 _transform_dirty = true;
290 //----------------------------------------------------------------------------
291 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
293 if( parent == _node && child->getNameString() == NAME_TRANSFORM )
295 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
301 "Element::childRemoved: unknown transform: " << child->getPath()
306 _transform_types[ child->getIndex() ] = TT_NONE;
308 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
309 _transform_types.pop_back();
311 _transform_dirty = true;
318 //----------------------------------------------------------------------------
319 void Element::valueChanged(SGPropertyNode* child)
321 SGPropertyNode *parent = child->getParent();
322 if( parent == _node )
324 const std::string& name = child->getNameString();
325 if( setStyle(child) )
327 else if( name == "update" )
329 else if( name == "visible" )
330 // TODO check if we need another nodemask
331 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
332 else if( boost::starts_with(name, "blend-") )
333 return (void)(_attributes_dirty |= BLEND_FUNC);
335 else if( parent->getParent() == _node
336 && parent->getNameString() == NAME_TRANSFORM )
338 _transform_dirty = true;
345 //----------------------------------------------------------------------------
346 bool Element::setStyle(const SGPropertyNode* child)
348 StyleSetters::const_iterator setter =
349 _style_setters.find(child->getNameString());
350 if( setter == _style_setters.end() )
353 const StyleSetter* style_setter = &setter->second.setter;
354 while( style_setter )
356 if( style_setter->func(*this, child) )
358 style_setter = style_setter->next;
363 //----------------------------------------------------------------------------
364 void Element::setClip(const std::string& clip)
366 if( clip.empty() || clip == "auto" )
368 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
372 // TODO generalize CSS property parsing
373 const std::string RECT("rect(");
374 if( !boost::ends_with(clip, ")")
375 || !boost::starts_with(clip, RECT) )
377 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
381 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
382 const boost::char_separator<char> del(", \t\npx");
384 tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
387 for( tokenizer::const_iterator tok = tokens.begin();
388 tok != tokens.end() && comp < 4;
391 values[comp] = boost::lexical_cast<int>(*tok);
396 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
403 CanvasPtr canvas = _canvas.lock();
406 // The scissor rectangle isn't affected by any transformation, so we need
407 // to convert to image/canvas coordinates on our selves.
408 scale_x = canvas->getSizeX()
409 / static_cast<float>(canvas->getViewWidth());
410 scale_y = canvas->getSizeY()
411 / static_cast<float>(canvas->getViewHeight());
414 osg::Scissor* scissor = new osg::Scissor();
415 // <top>, <right>, <bottom>, <left>
416 scissor->x() = scale_x * values[3];
417 scissor->y() = scale_y * values[0];
418 scissor->width() = scale_x * (values[1] - values[3]);
419 scissor->height() = scale_y * (values[2] - values[0]);
422 // Canvas has y axis upside down
423 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
425 getOrCreateStateSet()->setAttributeAndModes(scissor);
428 //----------------------------------------------------------------------------
429 void Element::setBoundingBox(const osg::BoundingBox& bb)
431 if( _bounding_box.empty() )
433 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
434 _bounding_box.resize(4);
435 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
436 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
437 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
438 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
441 _bounding_box[0]->setFloatValue(bb._min.x());
442 _bounding_box[1]->setFloatValue(bb._min.y());
443 _bounding_box[2]->setFloatValue(bb._max.x());
444 _bounding_box[3]->setFloatValue(bb._max.y());
447 //----------------------------------------------------------------------------
448 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
451 return osg::BoundingBox();
453 osg::BoundingBox transformed;
454 const osg::BoundingBox& bb = _drawable->getBound();
455 for(int i = 0; i < 4; ++i)
456 transformed.expandBy( m * bb.corner(i) );
461 //----------------------------------------------------------------------------
462 Element::StyleSetters Element::_style_setters;
464 //----------------------------------------------------------------------------
465 Element::Element( const CanvasWeakPtr& canvas,
466 const SGPropertyNode_ptr& node,
467 const Style& parent_style,
469 PropertyBasedElement(node),
472 _attributes_dirty( 0 ),
473 _transform_dirty( false ),
474 _transform( new osg::MatrixTransform ),
475 _style( parent_style ),
482 "New canvas element " << node->getPath()
485 if( !isInit<Element>() )
487 addStyle("clip", "", &Element::setClip);
491 //----------------------------------------------------------------------------
492 void Element::setDrawable( osg::Drawable* drawable )
494 _drawable = drawable;
497 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
498 geode->addDrawable(_drawable);
499 _transform->addChild(geode);
502 //----------------------------------------------------------------------------
503 osg::StateSet* Element::getOrCreateStateSet()
505 return _drawable ? _drawable->getOrCreateStateSet()
506 : _transform->getOrCreateStateSet();
509 //----------------------------------------------------------------------------
510 void Element::setupStyle()
512 BOOST_FOREACH( Style::value_type style, _style )
513 setStyle(style.second);
516 } // namespace canvas
517 } // namespace simgear