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