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