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