]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
Canvas: Add local_pos to mouse event and fix transformation of event positions with...
[simgear.git] / simgear / canvas / elements / CanvasElement.cxx
1 // Interface for 2D Canvas element
2 //
3 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
4 //
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.
9 //
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.
14 //
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
18
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
25 #include <osg/Drawable>
26 #include <osg/Geode>
27 #include <osg/Scissor>
28
29 #include <boost/algorithm/string/predicate.hpp>
30 #include <boost/foreach.hpp>
31 #include <boost/lexical_cast.hpp>
32 #include <boost/make_shared.hpp>
33 #include <boost/tokenizer.hpp>
34
35 #include <cassert>
36 #include <cstring>
37
38 namespace simgear
39 {
40 namespace canvas
41 {
42   const std::string NAME_TRANSFORM = "tf";
43
44   //----------------------------------------------------------------------------
45   void Element::removeListener()
46   {
47     _node->removeChangeListener(this);
48   }
49
50   //----------------------------------------------------------------------------
51   Element::~Element()
52   {
53     removeListener();
54
55     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
56     {
57       parent->removeChild(_transform);
58     }
59   }
60
61   //----------------------------------------------------------------------------
62   ElementWeakPtr Element::getWeakPtr() const
63   {
64     return boost::static_pointer_cast<Element>(_self.lock());
65   }
66
67   //----------------------------------------------------------------------------
68   void Element::update(double dt)
69   {
70     if( !_transform->getNodeMask() )
71       // Don't do anything if element is hidden
72       return;
73
74     if( _transform_dirty )
75     {
76       osg::Matrix m;
77       for( size_t i = 0; i < _transform_types.size(); ++i )
78       {
79         // Skip unused indizes...
80         if( _transform_types[i] == TT_NONE )
81           continue;
82
83         SGPropertyNode* tf_node = _node->getChild("tf", i, true);
84
85         // Build up the matrix representation of the current transform node
86         osg::Matrix tf;
87         switch( _transform_types[i] )
88         {
89           case TT_MATRIX:
90             tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
91                               tf_node->getDoubleValue("m[1]", 0),
92                               0,
93                               tf_node->getDoubleValue("m[6]", 0),
94
95                               tf_node->getDoubleValue("m[2]", 0),
96                               tf_node->getDoubleValue("m[3]", 1),
97                               0,
98                               tf_node->getDoubleValue("m[7]", 0),
99
100                               0,
101                               0,
102                               1,
103                               0,
104
105                               tf_node->getDoubleValue("m[4]", 0),
106                               tf_node->getDoubleValue("m[5]", 0),
107                               0,
108                               tf_node->getDoubleValue("m[8]", 1) );
109             break;
110           case TT_TRANSLATE:
111             tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
112                                           tf_node->getDoubleValue("t[1]", 0),
113                                           0 ) );
114             break;
115           case TT_ROTATE:
116             tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
117             break;
118           case TT_SCALE:
119           {
120             float sx = tf_node->getDoubleValue("s[0]", 1);
121             // sy defaults to sx...
122             tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
123             break;
124           }
125           default:
126             break;
127         }
128         m.postMult( tf );
129       }
130       _transform->setMatrix(m);
131       _transform_dirty = false;
132     }
133
134     // Update bounding box on manual update (manual updates pass zero dt)
135     if( dt == 0 && _drawable )
136       _drawable->getBound();
137   }
138
139   //----------------------------------------------------------------------------
140   naRef Element::addEventListener(const nasal::CallContext& ctx)
141   {
142     const std::string type_str = ctx.requireArg<std::string>(0);
143     naRef code = ctx.requireArg<naRef>(1);
144
145     SG_LOG
146     (
147       SG_NASAL,
148       SG_INFO,
149       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
150     );
151
152     Event::Type type = Event::strToType(type_str);
153     if( type == Event::UNKNOWN )
154       naRuntimeError( ctx.c,
155                       "addEventListener: Unknown event type %s",
156                       type_str.c_str() );
157
158     _listener[ type ].push_back
159     (
160       boost::make_shared<EventListener>( code,
161                                          _canvas.lock()->getSystemAdapter() )
162     );
163
164     return naNil();
165   }
166
167   //----------------------------------------------------------------------------
168   bool Element::accept(EventVisitor& visitor)
169   {
170     return visitor.apply(*this);
171   }
172
173   //----------------------------------------------------------------------------
174   bool Element::ascend(EventVisitor& visitor)
175   {
176     if( _parent )
177       return _parent->accept(visitor);
178     return true;
179   }
180
181   //----------------------------------------------------------------------------
182   bool Element::traverse(EventVisitor& visitor)
183   {
184     return true;
185   }
186
187   //----------------------------------------------------------------------------
188   bool Element::handleEvent(canvas::EventPtr event)
189   {
190     ListenerMap::iterator listeners = _listener.find(event->getType());
191     if( listeners == _listener.end() )
192       return false;
193
194     BOOST_FOREACH(EventListenerPtr listener, listeners->second)
195       listener->call(event);
196
197     return true;
198   }
199
200   //----------------------------------------------------------------------------
201   bool Element::hitBound( const osg::Vec2f& pos,
202                           const osg::Vec2f& local_pos ) const
203   {
204     const osg::Vec3f pos3(pos, 0);
205
206     // Drawables have a bounding box...
207     if( _drawable )
208     {
209       if( !_drawable->getBound().contains(osg::Vec3f(local_pos, 0)) )
210         return false;
211     }
212     // ... for other elements, i.e. groups only a bounding sphere is available
213     else if( !_transform->getBound().contains(osg::Vec3f(pos, 0)) )
214         return false;
215
216     return true;
217   }
218
219   //----------------------------------------------------------------------------
220   bool Element::isVisible() const
221   {
222     return _transform->getNodeMask() != 0;
223   }
224
225   //----------------------------------------------------------------------------
226   osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform()
227   {
228     return _transform;
229   }
230
231   //----------------------------------------------------------------------------
232   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
233   {
234     if(    parent == _node
235         && child->getNameString() == NAME_TRANSFORM )
236     {
237       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
238         _transform_types.resize( child->getIndex() + 1 );
239
240       _transform_types[ child->getIndex() ] = TT_NONE;
241       _transform_dirty = true;
242       return;
243     }
244     else if(    parent->getParent() == _node
245              && parent->getNameString() == NAME_TRANSFORM )
246     {
247       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
248
249       const std::string& name = child->getNameString();
250
251       TransformType& type = _transform_types[parent->getIndex()];
252
253       if(      name == "m" )
254         type = TT_MATRIX;
255       else if( name == "t" )
256         type = TT_TRANSLATE;
257       else if( name == "rot" )
258         type = TT_ROTATE;
259       else if( name == "s" )
260         type = TT_SCALE;
261
262       _transform_dirty = true;
263       return;
264     }
265
266     childAdded(child);
267   }
268
269   //----------------------------------------------------------------------------
270   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
271   {
272     if( parent == _node && child->getNameString() == NAME_TRANSFORM )
273     {
274       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
275       {
276         SG_LOG
277         (
278           SG_GENERAL,
279           SG_WARN,
280           "Element::childRemoved: unknown transform: " << child->getPath()
281         );
282         return;
283       }
284
285       _transform_types[ child->getIndex() ] = TT_NONE;
286
287       while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
288         _transform_types.pop_back();
289
290       _transform_dirty = true;
291       return;
292     }
293
294     childRemoved(child);
295   }
296
297   //----------------------------------------------------------------------------
298   void Element::valueChanged(SGPropertyNode* child)
299   {
300     SGPropertyNode *parent = child->getParent();
301     if( parent == _node )
302     {
303       if( setStyle(child) )
304         return;
305       else if( child->getNameString() == "update" )
306         return update(0);
307       else if( child->getNameString() == "visible" )
308         // TODO check if we need another nodemask
309         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
310     }
311     else if(   parent->getParent() == _node
312             && parent->getNameString() == NAME_TRANSFORM )
313     {
314       _transform_dirty = true;
315       return;
316     }
317
318     childChanged(child);
319   }
320
321   //----------------------------------------------------------------------------
322   bool Element::setStyle(const SGPropertyNode* child)
323   {
324     StyleSetters::const_iterator setter =
325       _style_setters.find(child->getNameString());
326     if( setter == _style_setters.end() )
327       return false;
328
329     const StyleSetter* style_setter = &setter->second.setter;
330     while( style_setter )
331     {
332       if( style_setter->func(*this, child) )
333         return true;
334       style_setter = style_setter->next;
335     }
336     return false;
337   }
338
339   //----------------------------------------------------------------------------
340   void Element::setClip(const std::string& clip)
341   {
342     if( clip.empty() || clip == "auto" )
343     {
344       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
345       return;
346     }
347
348     // TODO generalize CSS property parsing
349     const std::string RECT("rect(");
350     if(    !boost::ends_with(clip, ")")
351         || !boost::starts_with(clip, RECT) )
352     {
353       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
354       return;
355     }
356
357     typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
358     const boost::char_separator<char> del(", \t\npx");
359
360     tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
361     int comp = 0;
362     int values[4];
363     for( tokenizer::const_iterator tok = tokens.begin();
364          tok != tokens.end() && comp < 4;
365          ++tok, ++comp )
366     {
367       values[comp] = boost::lexical_cast<int>(*tok);
368     }
369
370     if( comp < 4 )
371     {
372       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
373       return;
374     }
375
376     float scale_x = 1,
377           scale_y = 1;
378
379     CanvasPtr canvas = _canvas.lock();
380     if( canvas )
381     {
382       // The scissor rectangle isn't affected by any transformation, so we need
383       // to convert to image/canvas coordinates on our selves.
384       scale_x = canvas->getSizeX()
385               / static_cast<float>(canvas->getViewWidth());
386       scale_y = canvas->getSizeY()
387               / static_cast<float>(canvas->getViewHeight());
388     }
389
390     osg::Scissor* scissor = new osg::Scissor();
391     // <top>, <right>, <bottom>, <left>
392     scissor->x() = scale_x * values[3];
393     scissor->y() = scale_y * values[0];
394     scissor->width() = scale_x * (values[1] - values[3]);
395     scissor->height() = scale_y * (values[2] - values[0]);
396
397     if( canvas )
398       // Canvas has y axis upside down
399       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
400
401     getOrCreateStateSet()->setAttributeAndModes(scissor);
402   }
403
404   //----------------------------------------------------------------------------
405   void Element::setBoundingBox(const osg::BoundingBox& bb)
406   {
407     if( _bounding_box.empty() )
408     {
409       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
410       _bounding_box.resize(4);
411       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
412       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
413       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
414       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
415     }
416
417     _bounding_box[0]->setFloatValue(bb._min.x());
418     _bounding_box[1]->setFloatValue(bb._min.y());
419     _bounding_box[2]->setFloatValue(bb._max.x());
420     _bounding_box[3]->setFloatValue(bb._max.y());
421   }
422
423   //----------------------------------------------------------------------------
424   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
425   {
426     if( !_drawable )
427       return osg::BoundingBox();
428
429     osg::BoundingBox transformed;
430     const osg::BoundingBox& bb = _drawable->getBound();
431     for(int i = 0; i < 4; ++i)
432       transformed.expandBy( m * bb.corner(i) );
433
434     return transformed;
435   }
436
437   //----------------------------------------------------------------------------
438   Element::StyleSetters Element::_style_setters;
439
440   //----------------------------------------------------------------------------
441   Element::Element( const CanvasWeakPtr& canvas,
442                     const SGPropertyNode_ptr& node,
443                     const Style& parent_style,
444                     Element* parent ):
445     PropertyBasedElement(node),
446     _canvas( canvas ),
447     _parent( parent ),
448     _attributes_dirty( 0 ),
449     _transform_dirty( false ),
450     _transform( new osg::MatrixTransform ),
451     _style( parent_style ),
452     _drawable( 0 )
453   {
454     SG_LOG
455     (
456       SG_GL,
457       SG_DEBUG,
458       "New canvas element " << node->getPath()
459     );
460
461     if( !isInit<Element>() )
462     {
463       addStyle("clip", "", &Element::setClip);
464     }
465   }
466
467   //----------------------------------------------------------------------------
468   void Element::setDrawable( osg::Drawable* drawable )
469   {
470     _drawable = drawable;
471     assert( _drawable );
472
473     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
474     geode->addDrawable(_drawable);
475     _transform->addChild(geode);
476   }
477
478   //----------------------------------------------------------------------------
479   osg::StateSet* Element::getOrCreateStateSet()
480   {
481     return _drawable ? _drawable->getOrCreateStateSet()
482                      : _transform->getOrCreateStateSet();
483   }
484
485   //----------------------------------------------------------------------------
486   void Element::setupStyle()
487   {
488     BOOST_FOREACH( Style::value_type style, _style )
489       setStyle(style.second);
490   }
491
492 } // namespace canvas
493 } // namespace simgear