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