]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
canvas::Element: Fix bounding box calculation of groups
[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( StyleInfo const* style = getStyleInfo(child->getNameString()) )
346       {
347         if( setStyle(getParentStyle(child), style) )
348           return;
349       }
350     }
351
352     childRemoved(child);
353   }
354
355   //----------------------------------------------------------------------------
356   void Element::valueChanged(SGPropertyNode* child)
357   {
358     SGPropertyNode *parent = child->getParent();
359     if( parent == _node )
360     {
361       const std::string& name = child->getNameString();
362       if( StyleInfo const* style_info = getStyleInfo(name) )
363       {
364         SGPropertyNode const* style = child;
365         if( isStyleEmpty(child) )
366         {
367           child->clearValue();
368           style = getParentStyle(child);
369         }
370         setStyle(style, style_info);
371         return;
372       }
373       else if( name == "update" )
374         return update(0);
375       else if( name == "visible" )
376         // TODO check if we need another nodemask
377         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
378       else if( boost::starts_with(name, "blend-") )
379         return (void)(_attributes_dirty |= BLEND_FUNC);
380     }
381     else if(   parent->getParent() == _node
382             && parent->getNameString() == NAME_TRANSFORM )
383     {
384       _transform_dirty = true;
385       return;
386     }
387
388     childChanged(child);
389   }
390
391   //----------------------------------------------------------------------------
392   bool Element::setStyle( const SGPropertyNode* child,
393                           const StyleInfo* style_info )
394   {
395     return canApplyStyle(child) && setStyleImpl(child, style_info);
396   }
397
398   //----------------------------------------------------------------------------
399   void Element::setClip(const std::string& clip)
400   {
401     if( clip.empty() || clip == "auto" )
402     {
403       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
404       return;
405     }
406
407     // TODO generalize CSS property parsing
408     const std::string RECT("rect(");
409     if(    !boost::ends_with(clip, ")")
410         || !boost::starts_with(clip, RECT) )
411     {
412       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
413       return;
414     }
415
416     typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
417     const boost::char_separator<char> del(", \t\npx");
418
419     tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
420     int comp = 0;
421     int values[4];
422     for( tokenizer::const_iterator tok = tokens.begin();
423          tok != tokens.end() && comp < 4;
424          ++tok, ++comp )
425     {
426       values[comp] = boost::lexical_cast<int>(*tok);
427     }
428
429     if( comp < 4 )
430     {
431       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
432       return;
433     }
434
435     float scale_x = 1,
436           scale_y = 1;
437
438     CanvasPtr canvas = _canvas.lock();
439     if( canvas )
440     {
441       // The scissor rectangle isn't affected by any transformation, so we need
442       // to convert to image/canvas coordinates on our selves.
443       scale_x = canvas->getSizeX()
444               / static_cast<float>(canvas->getViewWidth());
445       scale_y = canvas->getSizeY()
446               / static_cast<float>(canvas->getViewHeight());
447     }
448
449     osg::Scissor* scissor = new osg::Scissor();
450     // <top>, <right>, <bottom>, <left>
451     scissor->x() = scale_x * values[3];
452     scissor->y() = scale_y * values[0];
453     scissor->width() = scale_x * (values[1] - values[3]);
454     scissor->height() = scale_y * (values[2] - values[0]);
455
456     if( canvas )
457       // Canvas has y axis upside down
458       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
459
460     getOrCreateStateSet()->setAttributeAndModes(scissor);
461   }
462
463   //----------------------------------------------------------------------------
464   void Element::setBoundingBox(const osg::BoundingBox& bb)
465   {
466     if( _bounding_box.empty() )
467     {
468       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
469       _bounding_box.resize(4);
470       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
471       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
472       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
473       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
474     }
475
476     _bounding_box[0]->setFloatValue(bb._min.x());
477     _bounding_box[1]->setFloatValue(bb._min.y());
478     _bounding_box[2]->setFloatValue(bb._max.x());
479     _bounding_box[3]->setFloatValue(bb._max.y());
480   }
481
482   //----------------------------------------------------------------------------
483   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
484   {
485     if( !_drawable )
486       return osg::BoundingBox();
487
488     osg::BoundingBox transformed;
489     const osg::BoundingBox& bb = _drawable->getBound();
490     for(int i = 0; i < 4; ++i)
491       transformed.expandBy( bb.corner(i) * m );
492
493     return transformed;
494   }
495
496   //----------------------------------------------------------------------------
497   Element::StyleSetters Element::_style_setters;
498
499   //----------------------------------------------------------------------------
500   Element::Element( const CanvasWeakPtr& canvas,
501                     const SGPropertyNode_ptr& node,
502                     const Style& parent_style,
503                     Element* parent ):
504     PropertyBasedElement(node),
505     _canvas( canvas ),
506     _parent( parent ),
507     _attributes_dirty( 0 ),
508     _transform_dirty( false ),
509     _transform( new osg::MatrixTransform ),
510     _style( parent_style ),
511     _drawable( 0 )
512   {
513     SG_LOG
514     (
515       SG_GL,
516       SG_DEBUG,
517       "New canvas element " << node->getPath()
518     );
519
520     if( !isInit<Element>() )
521     {
522       addStyle("clip", "", &Element::setClip, false);
523     }
524
525     // Ensure elements are drawn in order they appear in the element tree
526     _transform->getOrCreateStateSet()
527               ->setRenderBinDetails
528               (
529                 0,
530                 "PreOrderBin",
531                 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
532               );
533   }
534
535   //----------------------------------------------------------------------------
536   bool Element::isStyleEmpty(const SGPropertyNode* child) const
537   {
538     return !child
539         || simgear::strutils::strip(child->getStringValue()).empty();
540   }
541
542   //----------------------------------------------------------------------------
543   bool Element::canApplyStyle(const SGPropertyNode* child) const
544   {
545     if( _node == child->getParent() )
546       return true;
547
548     // Parent values do not override if element has own value
549     return isStyleEmpty( _node->getChild(child->getName()) );
550   }
551
552   //----------------------------------------------------------------------------
553   bool Element::setStyleImpl( const SGPropertyNode* child,
554                               const StyleInfo* style_info )
555   {
556     const StyleSetter* style_setter = style_info
557                                     ? &style_info->setter
558                                     : getStyleSetter(child->getNameString());
559     while( style_setter )
560     {
561       if( style_setter->func(*this, child) )
562         return true;
563       style_setter = style_setter->next;
564     }
565     return false;
566   }
567
568   //----------------------------------------------------------------------------
569   const Element::StyleInfo*
570   Element::getStyleInfo(const std::string& name) const
571   {
572     StyleSetters::const_iterator setter = _style_setters.find(name);
573     if( setter == _style_setters.end() )
574       return 0;
575
576     return &setter->second;
577   }
578
579   //----------------------------------------------------------------------------
580   const Element::StyleSetter*
581   Element::getStyleSetter(const std::string& name) const
582   {
583     const StyleInfo* info = getStyleInfo(name);
584     return info ? &info->setter : 0;
585   }
586
587   //----------------------------------------------------------------------------
588   const SGPropertyNode*
589   Element::getParentStyle(const SGPropertyNode* child) const
590   {
591     // Try to get value from parent...
592     if( _parent )
593     {
594       Style::const_iterator style =
595         _parent->_style.find(child->getNameString());
596       if( style != _parent->_style.end() )
597         return style->second;
598     }
599
600     // ...or reset to default if none is available
601     return child; // TODO somehow get default value for each style?
602   }
603
604   //----------------------------------------------------------------------------
605   void Element::setDrawable( osg::Drawable* drawable )
606   {
607     _drawable = drawable;
608     assert( _drawable );
609
610     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
611     geode->addDrawable(_drawable);
612     _transform->addChild(geode);
613   }
614
615   //----------------------------------------------------------------------------
616   osg::StateSet* Element::getOrCreateStateSet()
617   {
618     return _drawable ? _drawable->getOrCreateStateSet()
619                      : _transform->getOrCreateStateSet();
620   }
621
622   //----------------------------------------------------------------------------
623   void Element::setupStyle()
624   {
625     BOOST_FOREACH( Style::value_type style, _style )
626       setStyle(style.second);
627   }
628
629 } // namespace canvas
630 } // namespace simgear