]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
CanvasGroup: Fix handling z-index while moving child to front.
[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/Canvas.hxx>
21 #include <simgear/canvas/CanvasEventListener.hxx>
22 #include <simgear/canvas/CanvasEventVisitor.hxx>
23 #include <simgear/canvas/MouseEvent.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/lexical_cast.hpp>
33 #include <boost/make_shared.hpp>
34 #include <boost/tokenizer.hpp>
35
36 #include <cassert>
37 #include <cstring>
38
39 namespace simgear
40 {
41 namespace canvas
42 {
43   const std::string NAME_TRANSFORM = "tf";
44
45   //----------------------------------------------------------------------------
46   void Element::removeListener()
47   {
48     _node->removeChangeListener(this);
49   }
50
51   //----------------------------------------------------------------------------
52   Element::~Element()
53   {
54     removeListener();
55
56     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
57     {
58       parent->removeChild(_transform);
59     }
60   }
61
62   //----------------------------------------------------------------------------
63   ElementWeakPtr Element::getWeakPtr() const
64   {
65     return boost::static_pointer_cast<Element>(_self.lock());
66   }
67
68   //----------------------------------------------------------------------------
69   void Element::update(double dt)
70   {
71     if( !_transform->getNodeMask() )
72       // Don't do anything if element is hidden
73       return;
74
75     if( _transform_dirty )
76     {
77       osg::Matrix m;
78       for( size_t i = 0; i < _transform_types.size(); ++i )
79       {
80         // Skip unused indizes...
81         if( _transform_types[i] == TT_NONE )
82           continue;
83
84         SGPropertyNode* tf_node = _node->getChild("tf", i, true);
85
86         // Build up the matrix representation of the current transform node
87         osg::Matrix tf;
88         switch( _transform_types[i] )
89         {
90           case TT_MATRIX:
91             tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
92                               tf_node->getDoubleValue("m[1]", 0),
93                               0,
94                               tf_node->getDoubleValue("m[6]", 0),
95
96                               tf_node->getDoubleValue("m[2]", 0),
97                               tf_node->getDoubleValue("m[3]", 1),
98                               0,
99                               tf_node->getDoubleValue("m[7]", 0),
100
101                               0,
102                               0,
103                               1,
104                               0,
105
106                               tf_node->getDoubleValue("m[4]", 0),
107                               tf_node->getDoubleValue("m[5]", 0),
108                               0,
109                               tf_node->getDoubleValue("m[8]", 1) );
110             break;
111           case TT_TRANSLATE:
112             tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
113                                           tf_node->getDoubleValue("t[1]", 0),
114                                           0 ) );
115             break;
116           case TT_ROTATE:
117             tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
118             break;
119           case TT_SCALE:
120           {
121             float sx = tf_node->getDoubleValue("s[0]", 1);
122             // sy defaults to sx...
123             tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
124             break;
125           }
126           default:
127             break;
128         }
129         m.postMult( tf );
130       }
131       _transform->setMatrix(m);
132       _transform_dirty = false;
133     }
134
135     // Update bounding box on manual update (manual updates pass zero dt)
136     if( dt == 0 && _drawable )
137       _drawable->getBound();
138
139     if( _attributes_dirty & BLEND_FUNC )
140     {
141       parseBlendFunc(
142         _transform->getOrCreateStateSet(),
143         _node->getChild("blend-source"),
144         _node->getChild("blend-destination"),
145         _node->getChild("blend-source-rgb"),
146         _node->getChild("blend-destination-rgb"),
147         _node->getChild("blend-source-alpha"),
148         _node->getChild("blend-destination-alpha")
149       );
150       _attributes_dirty &= ~BLEND_FUNC;
151     }
152   }
153
154   //----------------------------------------------------------------------------
155   naRef Element::addEventListener(const nasal::CallContext& ctx)
156   {
157     const std::string type_str = ctx.requireArg<std::string>(0);
158     naRef code = ctx.requireArg<naRef>(1);
159
160     SG_LOG
161     (
162       SG_NASAL,
163       SG_INFO,
164       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
165     );
166
167     Event::Type type = Event::strToType(type_str);
168     if( type == Event::UNKNOWN )
169       naRuntimeError( ctx.c,
170                       "addEventListener: Unknown event type %s",
171                       type_str.c_str() );
172
173     _listener[ type ].push_back
174     (
175       boost::make_shared<EventListener>( code,
176                                          _canvas.lock()->getSystemAdapter() )
177     );
178
179     return naNil();
180   }
181
182   //----------------------------------------------------------------------------
183   void Element::clearEventListener()
184   {
185     _listener.clear();
186   }
187
188   //----------------------------------------------------------------------------
189   bool Element::accept(EventVisitor& visitor)
190   {
191     return visitor.apply(*this);
192   }
193
194   //----------------------------------------------------------------------------
195   bool Element::ascend(EventVisitor& visitor)
196   {
197     if( _parent )
198       return _parent->accept(visitor);
199     return true;
200   }
201
202   //----------------------------------------------------------------------------
203   bool Element::traverse(EventVisitor& visitor)
204   {
205     return true;
206   }
207
208   //----------------------------------------------------------------------------
209   bool Element::handleEvent(canvas::EventPtr event)
210   {
211     ListenerMap::iterator listeners = _listener.find(event->getType());
212     if( listeners == _listener.end() )
213       return false;
214
215     BOOST_FOREACH(EventListenerPtr listener, listeners->second)
216       listener->call(event);
217
218     return true;
219   }
220
221   //----------------------------------------------------------------------------
222   bool Element::hitBound( const osg::Vec2f& pos,
223                           const osg::Vec2f& local_pos ) const
224   {
225     const osg::Vec3f pos3(pos, 0);
226
227     // Drawables have a bounding box...
228     if( _drawable )
229       return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
230     // ... for other elements, i.e. groups only a bounding sphere is available
231     else
232       return _transform->getBound().contains(osg::Vec3f(pos, 0));
233   }
234
235   //----------------------------------------------------------------------------
236   bool Element::isVisible() const
237   {
238     return _transform->getNodeMask() != 0;
239   }
240
241   //----------------------------------------------------------------------------
242   osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform()
243   {
244     return _transform;
245   }
246
247   osg::ref_ptr<osg::MatrixTransform const> Element::getMatrixTransform() const
248   {
249     return _transform;
250   }
251
252   //----------------------------------------------------------------------------
253   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
254   {
255     if(    parent == _node
256         && child->getNameString() == NAME_TRANSFORM )
257     {
258       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
259         _transform_types.resize( child->getIndex() + 1 );
260
261       _transform_types[ child->getIndex() ] = TT_NONE;
262       _transform_dirty = true;
263       return;
264     }
265     else if(    parent->getParent() == _node
266              && parent->getNameString() == NAME_TRANSFORM )
267     {
268       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
269
270       const std::string& name = child->getNameString();
271
272       TransformType& type = _transform_types[parent->getIndex()];
273
274       if(      name == "m" )
275         type = TT_MATRIX;
276       else if( name == "t" )
277         type = TT_TRANSLATE;
278       else if( name == "rot" )
279         type = TT_ROTATE;
280       else if( name == "s" )
281         type = TT_SCALE;
282
283       _transform_dirty = true;
284       return;
285     }
286
287     childAdded(child);
288   }
289
290   //----------------------------------------------------------------------------
291   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
292   {
293     if( parent == _node && child->getNameString() == NAME_TRANSFORM )
294     {
295       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
296       {
297         SG_LOG
298         (
299           SG_GENERAL,
300           SG_WARN,
301           "Element::childRemoved: unknown transform: " << child->getPath()
302         );
303         return;
304       }
305
306       _transform_types[ child->getIndex() ] = TT_NONE;
307
308       while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
309         _transform_types.pop_back();
310
311       _transform_dirty = true;
312       return;
313     }
314
315     childRemoved(child);
316   }
317
318   //----------------------------------------------------------------------------
319   void Element::valueChanged(SGPropertyNode* child)
320   {
321     SGPropertyNode *parent = child->getParent();
322     if( parent == _node )
323     {
324       const std::string& name = child->getNameString();
325       if( setStyle(child) )
326         return;
327       else if( name == "update" )
328         return update(0);
329       else if( name == "visible" )
330         // TODO check if we need another nodemask
331         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
332       else if( boost::starts_with(name, "blend-") )
333         return (void)(_attributes_dirty |= BLEND_FUNC);
334     }
335     else if(   parent->getParent() == _node
336             && parent->getNameString() == NAME_TRANSFORM )
337     {
338       _transform_dirty = true;
339       return;
340     }
341
342     childChanged(child);
343   }
344
345   //----------------------------------------------------------------------------
346   bool Element::setStyle(const SGPropertyNode* child)
347   {
348     StyleSetters::const_iterator setter =
349       _style_setters.find(child->getNameString());
350     if( setter == _style_setters.end() )
351       return false;
352
353     const StyleSetter* style_setter = &setter->second.setter;
354     while( style_setter )
355     {
356       if( style_setter->func(*this, child) )
357         return true;
358       style_setter = style_setter->next;
359     }
360     return false;
361   }
362
363   //----------------------------------------------------------------------------
364   void Element::setClip(const std::string& clip)
365   {
366     if( clip.empty() || clip == "auto" )
367     {
368       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
369       return;
370     }
371
372     // TODO generalize CSS property parsing
373     const std::string RECT("rect(");
374     if(    !boost::ends_with(clip, ")")
375         || !boost::starts_with(clip, RECT) )
376     {
377       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
378       return;
379     }
380
381     typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
382     const boost::char_separator<char> del(", \t\npx");
383
384     tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
385     int comp = 0;
386     int values[4];
387     for( tokenizer::const_iterator tok = tokens.begin();
388          tok != tokens.end() && comp < 4;
389          ++tok, ++comp )
390     {
391       values[comp] = boost::lexical_cast<int>(*tok);
392     }
393
394     if( comp < 4 )
395     {
396       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
397       return;
398     }
399
400     float scale_x = 1,
401           scale_y = 1;
402
403     CanvasPtr canvas = _canvas.lock();
404     if( canvas )
405     {
406       // The scissor rectangle isn't affected by any transformation, so we need
407       // to convert to image/canvas coordinates on our selves.
408       scale_x = canvas->getSizeX()
409               / static_cast<float>(canvas->getViewWidth());
410       scale_y = canvas->getSizeY()
411               / static_cast<float>(canvas->getViewHeight());
412     }
413
414     osg::Scissor* scissor = new osg::Scissor();
415     // <top>, <right>, <bottom>, <left>
416     scissor->x() = scale_x * values[3];
417     scissor->y() = scale_y * values[0];
418     scissor->width() = scale_x * (values[1] - values[3]);
419     scissor->height() = scale_y * (values[2] - values[0]);
420
421     if( canvas )
422       // Canvas has y axis upside down
423       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
424
425     getOrCreateStateSet()->setAttributeAndModes(scissor);
426   }
427
428   //----------------------------------------------------------------------------
429   void Element::setBoundingBox(const osg::BoundingBox& bb)
430   {
431     if( _bounding_box.empty() )
432     {
433       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
434       _bounding_box.resize(4);
435       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
436       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
437       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
438       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
439     }
440
441     _bounding_box[0]->setFloatValue(bb._min.x());
442     _bounding_box[1]->setFloatValue(bb._min.y());
443     _bounding_box[2]->setFloatValue(bb._max.x());
444     _bounding_box[3]->setFloatValue(bb._max.y());
445   }
446
447   //----------------------------------------------------------------------------
448   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
449   {
450     if( !_drawable )
451       return osg::BoundingBox();
452
453     osg::BoundingBox transformed;
454     const osg::BoundingBox& bb = _drawable->getBound();
455     for(int i = 0; i < 4; ++i)
456       transformed.expandBy( m * bb.corner(i) );
457
458     return transformed;
459   }
460
461   //----------------------------------------------------------------------------
462   Element::StyleSetters Element::_style_setters;
463
464   //----------------------------------------------------------------------------
465   Element::Element( const CanvasWeakPtr& canvas,
466                     const SGPropertyNode_ptr& node,
467                     const Style& parent_style,
468                     Element* parent ):
469     PropertyBasedElement(node),
470     _canvas( canvas ),
471     _parent( parent ),
472     _attributes_dirty( 0 ),
473     _transform_dirty( false ),
474     _transform( new osg::MatrixTransform ),
475     _style( parent_style ),
476     _drawable( 0 )
477   {
478     SG_LOG
479     (
480       SG_GL,
481       SG_DEBUG,
482       "New canvas element " << node->getPath()
483     );
484
485     if( !isInit<Element>() )
486     {
487       addStyle("clip", "", &Element::setClip);
488     }
489   }
490
491   //----------------------------------------------------------------------------
492   void Element::setDrawable( osg::Drawable* drawable )
493   {
494     _drawable = drawable;
495     assert( _drawable );
496
497     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
498     geode->addDrawable(_drawable);
499     _transform->addChild(geode);
500   }
501
502   //----------------------------------------------------------------------------
503   osg::StateSet* Element::getOrCreateStateSet()
504   {
505     return _drawable ? _drawable->getOrCreateStateSet()
506                      : _transform->getOrCreateStateSet();
507   }
508
509   //----------------------------------------------------------------------------
510   void Element::setupStyle()
511   {
512     BOOST_FOREACH( Style::value_type style, _style )
513       setStyle(style.second);
514   }
515
516 } // namespace canvas
517 } // namespace simgear