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