]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
Canvas: allow also C++ callable entities as event callbacks.
[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/math/SGMisc.hxx>
25 #include <simgear/misc/strutils.hxx>
26 #include <simgear/scene/material/parseBlendFunc.hxx>
27
28 #include <osg/Drawable>
29 #include <osg/Geode>
30 #include <osg/Scissor>
31
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/make_shared.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   Element::OSGUserData::OSGUserData(ElementPtr element):
47     element(element)
48   {
49
50   }
51
52   //----------------------------------------------------------------------------
53   Element::~Element()
54   {
55
56   }
57
58   //----------------------------------------------------------------------------
59   void Element::setSelf(const PropertyBasedElementPtr& self)
60   {
61     PropertyBasedElement::setSelf(self);
62
63     _transform->setUserData
64     (
65       new OSGUserData(boost::static_pointer_cast<Element>(self))
66     );
67   }
68
69   //----------------------------------------------------------------------------
70   void Element::onDestroy()
71   {
72     if( !_transform.valid() )
73       return;
74
75     // The transform node keeps a reference on this element, so ensure it is
76     // deleted.
77     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
78     {
79       parent->removeChild(_transform.get());
80     }
81   }
82
83   //----------------------------------------------------------------------------
84   ElementWeakPtr Element::getWeakPtr() const
85   {
86     return boost::static_pointer_cast<Element>(_self.lock());
87   }
88
89   //----------------------------------------------------------------------------
90   void Element::update(double dt)
91   {
92     if( !_transform->getNodeMask() )
93       // Don't do anything if element is hidden
94       return;
95
96     if( _transform_dirty )
97     {
98       osg::Matrix m;
99       for( size_t i = 0; i < _transform_types.size(); ++i )
100       {
101         // Skip unused indizes...
102         if( _transform_types[i] == TT_NONE )
103           continue;
104
105         SGPropertyNode* tf_node = _node->getChild("tf", i, true);
106
107         // Build up the matrix representation of the current transform node
108         osg::Matrix tf;
109         switch( _transform_types[i] )
110         {
111           case TT_MATRIX:
112             tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
113                               tf_node->getDoubleValue("m[1]", 0),
114                               0,
115                               tf_node->getDoubleValue("m[6]", 0),
116
117                               tf_node->getDoubleValue("m[2]", 0),
118                               tf_node->getDoubleValue("m[3]", 1),
119                               0,
120                               tf_node->getDoubleValue("m[7]", 0),
121
122                               0,
123                               0,
124                               1,
125                               0,
126
127                               tf_node->getDoubleValue("m[4]", 0),
128                               tf_node->getDoubleValue("m[5]", 0),
129                               0,
130                               tf_node->getDoubleValue("m[8]", 1) );
131             break;
132           case TT_TRANSLATE:
133             tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
134                                           tf_node->getDoubleValue("t[1]", 0),
135                                           0 ) );
136             break;
137           case TT_ROTATE:
138             tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
139             break;
140           case TT_SCALE:
141           {
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 );
145             break;
146           }
147           default:
148             break;
149         }
150         m.postMult( tf );
151       }
152       _transform->setMatrix(m);
153       _transform_dirty = false;
154     }
155
156     // Update bounding box on manual update (manual updates pass zero dt)
157     if( dt == 0 && _drawable )
158       _drawable->getBound();
159
160     if( _attributes_dirty & BLEND_FUNC )
161     {
162       parseBlendFunc(
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")
170       );
171       _attributes_dirty &= ~BLEND_FUNC;
172     }
173   }
174
175   //----------------------------------------------------------------------------
176   bool Element::addEventListener( const std::string& type_str,
177                                   const EventListener& cb )
178   {
179     SG_LOG
180     (
181       SG_NASAL,
182       SG_INFO,
183       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
184     );
185
186     Event::Type type = Event::strToType(type_str);
187     if( type == Event::UNKNOWN )
188     {
189       SG_LOG( SG_NASAL,
190               SG_WARN,
191               "addEventListener: Unknown event type " << type_str );
192       return false;
193     }
194
195     _listener[ type ].push_back(cb);
196
197     return true;
198   }
199
200   //----------------------------------------------------------------------------
201   bool Element::addNasalEventListener(const std::string& type, naRef code)
202   {
203     SGSharedPtr<NasalEventListener> listener =
204       new NasalEventListener(code, _canvas.lock()->getSystemAdapter());
205
206     return addEventListener
207     (
208       type,
209       boost::bind(&NasalEventListener::operator(), listener, _1)
210     );
211   }
212
213   //----------------------------------------------------------------------------
214   void Element::clearEventListener()
215   {
216     _listener.clear();
217   }
218
219   //----------------------------------------------------------------------------
220   bool Element::accept(EventVisitor& visitor)
221   {
222     if( !isVisible() )
223       return false;
224
225     return visitor.apply(*this);
226   }
227
228   //----------------------------------------------------------------------------
229   bool Element::ascend(EventVisitor& visitor)
230   {
231     if( _parent )
232       return _parent->accept(visitor);
233     return true;
234   }
235
236   //----------------------------------------------------------------------------
237   bool Element::traverse(EventVisitor& visitor)
238   {
239     return true;
240   }
241
242   //----------------------------------------------------------------------------
243   bool Element::handleEvent(canvas::EventPtr event)
244   {
245     ListenerMap::iterator listeners = _listener.find(event->getType());
246     if( listeners == _listener.end() )
247       return false;
248
249     BOOST_FOREACH(EventListener const& listener, listeners->second)
250       listener(event);
251
252     return true;
253   }
254
255   //----------------------------------------------------------------------------
256   bool Element::hitBound( const osg::Vec2f& pos,
257                           const osg::Vec2f& local_pos ) const
258   {
259     const osg::Vec3f pos3(pos, 0);
260
261     // Drawables have a bounding box...
262     if( _drawable )
263       return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
264     // ... for other elements, i.e. groups only a bounding sphere is available
265     else
266       return _transform->getBound().contains(osg::Vec3f(pos, 0));
267   }
268
269   //----------------------------------------------------------------------------
270   bool Element::isVisible() const
271   {
272     return _transform.valid() && _transform->getNodeMask() != 0;
273   }
274
275   //----------------------------------------------------------------------------
276   osg::MatrixTransform* Element::getMatrixTransform()
277   {
278     return _transform.get();
279   }
280
281   //----------------------------------------------------------------------------
282   osg::MatrixTransform const* Element::getMatrixTransform() const
283   {
284     return _transform.get();
285   }
286
287   //----------------------------------------------------------------------------
288   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
289   {
290     if(    parent == _node
291         && child->getNameString() == NAME_TRANSFORM )
292     {
293       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
294         _transform_types.resize( child->getIndex() + 1 );
295
296       _transform_types[ child->getIndex() ] = TT_NONE;
297       _transform_dirty = true;
298       return;
299     }
300     else if(    parent->getParent() == _node
301              && parent->getNameString() == NAME_TRANSFORM )
302     {
303       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
304
305       const std::string& name = child->getNameString();
306
307       TransformType& type = _transform_types[parent->getIndex()];
308
309       if(      name == "m" )
310         type = TT_MATRIX;
311       else if( name == "t" )
312         type = TT_TRANSLATE;
313       else if( name == "rot" )
314         type = TT_ROTATE;
315       else if( name == "s" )
316         type = TT_SCALE;
317
318       _transform_dirty = true;
319       return;
320     }
321
322     childAdded(child);
323   }
324
325   //----------------------------------------------------------------------------
326   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
327   {
328     if( parent == _node )
329     {
330       if( child->getNameString() == NAME_TRANSFORM )
331       {
332         if( !_transform.valid() )
333           return;
334
335         if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
336         {
337           SG_LOG
338           (
339             SG_GENERAL,
340             SG_WARN,
341             "Element::childRemoved: unknown transform: " << child->getPath()
342           );
343           return;
344         }
345
346         _transform_types[ child->getIndex() ] = TT_NONE;
347
348         while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
349           _transform_types.pop_back();
350
351         _transform_dirty = true;
352         return;
353       }
354       else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
355       {
356         if( setStyle(getParentStyle(child), style) )
357           return;
358       }
359     }
360
361     childRemoved(child);
362   }
363
364   //----------------------------------------------------------------------------
365   void Element::valueChanged(SGPropertyNode* child)
366   {
367     SGPropertyNode *parent = child->getParent();
368     if( parent == _node )
369     {
370       const std::string& name = child->getNameString();
371       if( StyleInfo const* style_info = getStyleInfo(name) )
372       {
373         SGPropertyNode const* style = child;
374         if( isStyleEmpty(child) )
375         {
376           child->clearValue();
377           style = getParentStyle(child);
378         }
379         setStyle(style, style_info);
380         return;
381       }
382       else if( name == "update" )
383         return update(0);
384       else if( name == "visible" )
385         // TODO check if we need another nodemask
386         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
387       else if( boost::starts_with(name, "blend-") )
388         return (void)(_attributes_dirty |= BLEND_FUNC);
389     }
390     else if(   parent->getParent() == _node
391             && parent->getNameString() == NAME_TRANSFORM )
392     {
393       _transform_dirty = true;
394       return;
395     }
396
397     childChanged(child);
398   }
399
400   //----------------------------------------------------------------------------
401   bool Element::setStyle( const SGPropertyNode* child,
402                           const StyleInfo* style_info )
403   {
404     return canApplyStyle(child) && setStyleImpl(child, style_info);
405   }
406
407   //----------------------------------------------------------------------------
408   void Element::setClip(const std::string& clip)
409   {
410     if( clip.empty() || clip == "auto" )
411     {
412       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
413       return;
414     }
415
416     // TODO generalize CSS property parsing
417     const std::string RECT("rect(");
418     if(    !boost::ends_with(clip, ")")
419         || !boost::starts_with(clip, RECT) )
420     {
421       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
422       return;
423     }
424
425     const std::string sep(", \t\npx");
426     int comp = 0;
427     float values[4];
428
429     for(size_t pos = RECT.size(); comp < 4; ++comp)
430     {
431       pos = clip.find_first_not_of(sep, pos);
432       if( pos == std::string::npos || pos == clip.size() - 1 )
433         break;
434
435       char *end = 0;
436       values[comp] = strtod(&clip[pos], &end);
437       if( end == &clip[pos] || !end )
438         break;
439
440       pos = end - &clip[0];
441     }
442
443     if( comp < 4 )
444     {
445       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
446       return;
447     }
448
449     float width = values[1] - values[3],
450           height = values[2] - values[0];
451
452     if( width < 0 || height < 0 )
453     {
454       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
455       return;
456     }
457
458     float scale_x = 1,
459           scale_y = 1;
460
461     CanvasPtr canvas = _canvas.lock();
462     if( canvas )
463     {
464       // The scissor rectangle isn't affected by any transformation, so we need
465       // to convert to image/canvas coordinates on our selves.
466       scale_x = canvas->getSizeX()
467               / static_cast<float>(canvas->getViewWidth());
468       scale_y = canvas->getSizeY()
469               / static_cast<float>(canvas->getViewHeight());
470     }
471
472     osg::Scissor* scissor = new osg::Scissor();
473     // <top>, <right>, <bottom>, <left>
474     scissor->x() = SGMiscf::roundToInt(scale_x * values[3]);
475     scissor->y() = SGMiscf::roundToInt(scale_y * values[0]);
476     scissor->width() = SGMiscf::roundToInt(scale_x * width);
477     scissor->height() = SGMiscf::roundToInt(scale_y * height);
478
479     if( canvas )
480       // Canvas has y axis upside down
481       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
482
483     getOrCreateStateSet()->setAttributeAndModes(scissor);
484   }
485
486   //----------------------------------------------------------------------------
487   void Element::setBoundingBox(const osg::BoundingBox& bb)
488   {
489     if( _bounding_box.empty() )
490     {
491       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
492       _bounding_box.resize(4);
493       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
494       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
495       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
496       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
497     }
498
499     _bounding_box[0]->setFloatValue(bb._min.x());
500     _bounding_box[1]->setFloatValue(bb._min.y());
501     _bounding_box[2]->setFloatValue(bb._max.x());
502     _bounding_box[3]->setFloatValue(bb._max.y());
503   }
504
505   //----------------------------------------------------------------------------
506   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
507   {
508     if( !_drawable )
509       return osg::BoundingBox();
510
511     osg::BoundingBox transformed;
512     const osg::BoundingBox& bb = _drawable->getBound();
513     for(int i = 0; i < 4; ++i)
514       transformed.expandBy( bb.corner(i) * m );
515
516     return transformed;
517   }
518
519   //----------------------------------------------------------------------------
520   Element::StyleSetters Element::_style_setters;
521
522   //----------------------------------------------------------------------------
523   Element::Element( const CanvasWeakPtr& canvas,
524                     const SGPropertyNode_ptr& node,
525                     const Style& parent_style,
526                     Element* parent ):
527     PropertyBasedElement(node),
528     _canvas( canvas ),
529     _parent( parent ),
530     _attributes_dirty( 0 ),
531     _transform_dirty( false ),
532     _transform( new osg::MatrixTransform ),
533     _style( parent_style ),
534     _drawable( 0 )
535   {
536     staticInit();
537
538     SG_LOG
539     (
540       SG_GL,
541       SG_DEBUG,
542       "New canvas element " << node->getPath()
543     );
544
545     // Ensure elements are drawn in order they appear in the element tree
546     _transform->getOrCreateStateSet()
547               ->setRenderBinDetails
548               (
549                 0,
550                 "PreOrderBin",
551                 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
552               );
553   }
554
555   //----------------------------------------------------------------------------
556   void Element::staticInit()
557   {
558     if( isInit<Element>() )
559       return;
560
561     addStyle("clip", "", &Element::setClip, false);
562   }
563
564   //----------------------------------------------------------------------------
565   bool Element::isStyleEmpty(const SGPropertyNode* child) const
566   {
567     return !child
568         || simgear::strutils::strip(child->getStringValue()).empty();
569   }
570
571   //----------------------------------------------------------------------------
572   bool Element::canApplyStyle(const SGPropertyNode* child) const
573   {
574     if( _node == child->getParent() )
575       return true;
576
577     // Parent values do not override if element has own value
578     return isStyleEmpty( _node->getChild(child->getName()) );
579   }
580
581   //----------------------------------------------------------------------------
582   bool Element::setStyleImpl( const SGPropertyNode* child,
583                               const StyleInfo* style_info )
584   {
585     const StyleSetter* style_setter = style_info
586                                     ? &style_info->setter
587                                     : getStyleSetter(child->getNameString());
588     while( style_setter )
589     {
590       if( style_setter->func(*this, child) )
591         return true;
592       style_setter = style_setter->next;
593     }
594     return false;
595   }
596
597   //----------------------------------------------------------------------------
598   const Element::StyleInfo*
599   Element::getStyleInfo(const std::string& name) const
600   {
601     StyleSetters::const_iterator setter = _style_setters.find(name);
602     if( setter == _style_setters.end() )
603       return 0;
604
605     return &setter->second;
606   }
607
608   //----------------------------------------------------------------------------
609   const Element::StyleSetter*
610   Element::getStyleSetter(const std::string& name) const
611   {
612     const StyleInfo* info = getStyleInfo(name);
613     return info ? &info->setter : 0;
614   }
615
616   //----------------------------------------------------------------------------
617   const SGPropertyNode*
618   Element::getParentStyle(const SGPropertyNode* child) const
619   {
620     // Try to get value from parent...
621     if( _parent )
622     {
623       Style::const_iterator style =
624         _parent->_style.find(child->getNameString());
625       if( style != _parent->_style.end() )
626         return style->second;
627     }
628
629     // ...or reset to default if none is available
630     return child; // TODO somehow get default value for each style?
631   }
632
633   //----------------------------------------------------------------------------
634   void Element::setDrawable( osg::Drawable* drawable )
635   {
636     _drawable = drawable;
637     assert( _drawable );
638
639     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
640     geode->addDrawable(_drawable);
641     _transform->addChild(geode);
642   }
643
644   //----------------------------------------------------------------------------
645   osg::StateSet* Element::getOrCreateStateSet()
646   {
647     return _drawable ? _drawable->getOrCreateStateSet()
648                      : _transform->getOrCreateStateSet();
649   }
650
651   //----------------------------------------------------------------------------
652   void Element::setupStyle()
653   {
654     BOOST_FOREACH( Style::value_type style, _style )
655       setStyle(style.second);
656   }
657
658 } // namespace canvas
659 } // namespace simgear