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