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