]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
CanvasImage: Use image/canvas size rather than texture size
[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
135   //----------------------------------------------------------------------------
136   naRef Element::addEventListener(const nasal::CallContext& ctx)
137   {
138     const std::string type_str = ctx.requireArg<std::string>(0);
139     naRef code = ctx.requireArg<naRef>(1);
140
141     SG_LOG
142     (
143       SG_NASAL,
144       SG_INFO,
145       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
146     );
147
148     Event::Type type = Event::strToType(type_str);
149     if( type == Event::UNKNOWN )
150       naRuntimeError( ctx.c,
151                       "addEventListener: Unknown event type %s",
152                       type_str.c_str() );
153
154     _listener[ type ].push_back
155     (
156       boost::make_shared<EventListener>( code,
157                                          _canvas.lock()->getSystemAdapter() )
158     );
159
160     return naNil();
161   }
162
163   //----------------------------------------------------------------------------
164   bool Element::accept(EventVisitor& visitor)
165   {
166     return visitor.apply(*this);
167   }
168
169   //----------------------------------------------------------------------------
170   bool Element::ascend(EventVisitor& visitor)
171   {
172     if( _parent )
173       return _parent->accept(visitor);
174     return true;
175   }
176
177   //----------------------------------------------------------------------------
178   bool Element::traverse(EventVisitor& visitor)
179   {
180     return true;
181   }
182
183   //----------------------------------------------------------------------------
184   void Element::callListeners(const canvas::EventPtr& event)
185   {
186     ListenerMap::iterator listeners = _listener.find(event->getType());
187     if( listeners == _listener.end() )
188       return;
189
190     BOOST_FOREACH(EventListenerPtr listener, listeners->second)
191       listener->call(event);
192   }
193
194   //----------------------------------------------------------------------------
195   bool Element::hitBound( const osg::Vec2f& pos,
196                           const osg::Vec2f& local_pos ) const
197   {
198     const osg::Vec3f pos3(pos, 0);
199
200     // Drawables have a bounding box...
201     if( _drawable )
202     {
203       if( !_drawable->getBound().contains(osg::Vec3f(local_pos, 0)) )
204         return false;
205     }
206     // ... for other elements, i.e. groups only a bounding sphere is available
207     else if( !_transform->getBound().contains(osg::Vec3f(pos, 0)) )
208         return false;
209
210     return true;
211   }
212
213   //----------------------------------------------------------------------------
214   bool Element::isVisible() const
215   {
216     return _transform->getNodeMask() != 0;
217   }
218
219   //----------------------------------------------------------------------------
220   osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform()
221   {
222     return _transform;
223   }
224
225   //----------------------------------------------------------------------------
226   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
227   {
228     if(    parent == _node
229         && child->getNameString() == NAME_TRANSFORM )
230     {
231       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
232         _transform_types.resize( child->getIndex() + 1 );
233
234       _transform_types[ child->getIndex() ] = TT_NONE;
235       _transform_dirty = true;
236       return;
237     }
238     else if(    parent->getParent() == _node
239              && parent->getNameString() == NAME_TRANSFORM )
240     {
241       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
242
243       const std::string& name = child->getNameString();
244
245       TransformType& type = _transform_types[parent->getIndex()];
246
247       if(      name == "m" )
248         type = TT_MATRIX;
249       else if( name == "t" )
250         type = TT_TRANSLATE;
251       else if( name == "rot" )
252         type = TT_ROTATE;
253       else if( name == "s" )
254         type = TT_SCALE;
255
256       _transform_dirty = true;
257       return;
258     }
259
260     childAdded(child);
261   }
262
263   //----------------------------------------------------------------------------
264   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
265   {
266     if( parent == _node && child->getNameString() == NAME_TRANSFORM )
267     {
268       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
269       {
270         SG_LOG
271         (
272           SG_GENERAL,
273           SG_WARN,
274           "Element::childRemoved: unknown transform: " << child->getPath()
275         );
276         return;
277       }
278
279       _transform_types[ child->getIndex() ] = TT_NONE;
280
281       while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
282         _transform_types.pop_back();
283
284       _transform_dirty = true;
285       return;
286     }
287
288     childRemoved(child);
289   }
290
291   //----------------------------------------------------------------------------
292   void Element::valueChanged(SGPropertyNode* child)
293   {
294     SGPropertyNode *parent = child->getParent();
295     if( parent == _node )
296     {
297       if( setStyle(child) )
298         return;
299       else if( child->getNameString() == "update" )
300         return update(0);
301       else if( child->getNameString() == "visible" )
302         // TODO check if we need another nodemask
303         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
304     }
305     else if(   parent->getParent() == _node
306             && parent->getNameString() == NAME_TRANSFORM )
307     {
308       _transform_dirty = true;
309       return;
310     }
311
312     childChanged(child);
313   }
314
315   //----------------------------------------------------------------------------
316   bool Element::setStyle(const SGPropertyNode* child)
317   {
318     StyleSetters::const_iterator setter =
319       _style_setters.find(child->getNameString());
320     if( setter == _style_setters.end() )
321       return false;
322
323     setter->second(child);
324     return true;
325   }
326
327   //----------------------------------------------------------------------------
328   void Element::setClip(const std::string& clip)
329   {
330     if( clip.empty() || clip == "auto" )
331     {
332       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
333       return;
334     }
335
336     // TODO generalize CSS property parsing
337     const std::string RECT("rect(");
338     if(    !boost::ends_with(clip, ")")
339         || !boost::starts_with(clip, RECT) )
340     {
341       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
342       return;
343     }
344
345     typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
346     const boost::char_separator<char> del(", \t\npx");
347
348     tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
349     int comp = 0;
350     int values[4];
351     for( tokenizer::const_iterator tok = tokens.begin();
352          tok != tokens.end() && comp < 4;
353          ++tok, ++comp )
354     {
355       values[comp] = boost::lexical_cast<int>(*tok);
356     }
357
358     if( comp < 4 )
359     {
360       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
361       return;
362     }
363
364     float scale_x = 1,
365           scale_y = 1;
366
367     CanvasPtr canvas = _canvas.lock();
368     if( canvas )
369     {
370       // The scissor rectangle isn't affected by any transformation, so we need
371       // to convert to image/canvas coordinates on our selves.
372       scale_x = canvas->getSizeX()
373               / static_cast<float>(canvas->getViewWidth());
374       scale_y = canvas->getSizeY()
375               / static_cast<float>(canvas->getViewHeight());
376     }
377
378     osg::Scissor* scissor = new osg::Scissor();
379     // <top>, <right>, <bottom>, <left>
380     scissor->x() = scale_x * values[3];
381     scissor->y() = scale_y * values[0];
382     scissor->width() = scale_x * (values[1] - values[3]);
383     scissor->height() = scale_y * (values[2] - values[0]);
384
385     if( canvas )
386       // Canvas has y axis upside down
387       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
388
389     getOrCreateStateSet()->setAttributeAndModes(scissor);
390   }
391
392   //----------------------------------------------------------------------------
393   void Element::setBoundingBox(const osg::BoundingBox& bb)
394   {
395     if( _bounding_box.empty() )
396     {
397       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
398       _bounding_box.resize(4);
399       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
400       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
401       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
402       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
403     }
404
405     _bounding_box[0]->setFloatValue(bb._min.x());
406     _bounding_box[1]->setFloatValue(bb._min.y());
407     _bounding_box[2]->setFloatValue(bb._max.x());
408     _bounding_box[3]->setFloatValue(bb._max.y());
409   }
410
411   //----------------------------------------------------------------------------
412   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
413   {
414     if( !_drawable )
415       return osg::BoundingBox();
416
417     osg::BoundingBox transformed;
418     const osg::BoundingBox& bb = _drawable->getBound();
419     for(int i = 0; i < 4; ++i)
420       transformed.expandBy( m * bb.corner(i) );
421
422     return transformed;
423   }
424
425   //----------------------------------------------------------------------------
426   Element::Element( const CanvasWeakPtr& canvas,
427                     const SGPropertyNode_ptr& node,
428                     const Style& parent_style,
429                     Element* parent ):
430     PropertyBasedElement(node),
431     _canvas( canvas ),
432     _parent( parent ),
433     _transform_dirty( false ),
434     _transform( new osg::MatrixTransform ),
435     _style( parent_style ),
436     _drawable( 0 )
437   {
438     SG_LOG
439     (
440       SG_GL,
441       SG_DEBUG,
442       "New canvas element " << node->getPath()
443     );
444
445     addStyle("clip", &Element::setClip, this);
446   }
447
448   //----------------------------------------------------------------------------
449   void Element::setDrawable( osg::Drawable* drawable )
450   {
451     _drawable = drawable;
452     assert( _drawable );
453
454     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
455     geode->addDrawable(_drawable);
456     _transform->addChild(geode);
457   }
458
459   //----------------------------------------------------------------------------
460   osg::StateSet* Element::getOrCreateStateSet()
461   {
462     return _drawable ? _drawable->getOrCreateStateSet()
463                      : _transform->getOrCreateStateSet();
464   }
465
466   //----------------------------------------------------------------------------
467   void Element::setupStyle()
468   {
469     BOOST_FOREACH( Style::value_type style, _style )
470       setStyle(style.second);
471   }
472
473 } // namespace canvas
474 } // namespace simgear