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