]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasImage.cxx
canvas::Element: print warning instead of crash on removing unknown transform
[simgear.git] / simgear / canvas / elements / CanvasImage.cxx
1 // An image on the Canvas
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 "CanvasImage.hxx"
20
21 #include <simgear/canvas/Canvas.hxx>
22 #include <simgear/canvas/CanvasMgr.hxx>
23 #include <simgear/canvas/CanvasSystemAdapter.hxx>
24 #include <simgear/scene/util/parse_color.hxx>
25 #include <simgear/misc/sg_path.hxx>
26
27 #include <osg/Array>
28 #include <osg/Geometry>
29 #include <osg/PrimitiveSet>
30
31 #include <boost/algorithm/string/predicate.hpp>
32
33 namespace simgear
34 {
35 namespace canvas
36 {
37   /**
38    * Callback to enable/disable rendering of canvas displayed inside windows or
39    * other canvases.
40    */
41   class CullCallback:
42     public osg::Drawable::CullCallback
43   {
44     public:
45       CullCallback(const CanvasWeakPtr& canvas);
46
47     private:
48       CanvasWeakPtr _canvas;
49
50       virtual bool cull( osg::NodeVisitor* nv,
51                          osg::Drawable* drawable,
52                          osg::RenderInfo* renderInfo ) const;
53   };
54
55   //----------------------------------------------------------------------------
56   CullCallback::CullCallback(const CanvasWeakPtr& canvas):
57     _canvas( canvas )
58   {
59
60   }
61
62   //----------------------------------------------------------------------------
63   bool CullCallback::cull( osg::NodeVisitor* nv,
64                            osg::Drawable* drawable,
65                            osg::RenderInfo* renderInfo ) const
66   {
67     if( !_canvas.expired() )
68       _canvas.lock()->enableRendering();
69
70     // TODO check if window/image should be culled
71     return false;
72   }
73
74   //----------------------------------------------------------------------------
75   Image::Image( const CanvasWeakPtr& canvas,
76                 const SGPropertyNode_ptr& node,
77                 const Style& parent_style,
78                 Element* parent ):
79     Element(canvas, node, parent_style, parent),
80     _texture(new osg::Texture2D),
81     _node_src_rect( node->getNode("source", 0, true) )
82   {
83     _geom = new osg::Geometry;
84     _geom->setUseDisplayList(false);
85
86     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
87     stateSet->setTextureAttributeAndModes(0, _texture.get());
88     stateSet->setDataVariance(osg::Object::STATIC);
89
90     // allocate arrays for the image
91     _vertices = new osg::Vec3Array(4);
92     _vertices->setDataVariance(osg::Object::STATIC);
93     _geom->setVertexArray(_vertices);
94
95     _texCoords = new osg::Vec2Array(4);
96     _texCoords->setDataVariance(osg::Object::STATIC);
97     _geom->setTexCoordArray(0, _texCoords);
98
99     _colors = new osg::Vec4Array(4);
100     _colors->setDataVariance(osg::Object::STATIC);
101     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
102     _geom->setColorArray(_colors);
103
104     osg::DrawArrays* prim = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
105     prim->set(osg::PrimitiveSet::QUADS, 0, 4);
106     prim->setDataVariance(osg::Object::STATIC);
107     _geom->addPrimitiveSet(prim);
108
109     setDrawable(_geom);
110
111     addStyle("fill", &Image::setFill, this);
112     setFill("#ffffff"); // TODO how should we handle default values?
113
114     setupStyle();
115   }
116
117   //----------------------------------------------------------------------------
118   Image::~Image()
119   {
120
121   }
122
123   //----------------------------------------------------------------------------
124   void Image::update(double dt)
125   {
126     Element::update(dt);
127
128     if( _attributes_dirty & DEST_SIZE )
129     {
130       (*_vertices)[0].set(_region.l(), _region.t(), 0);
131       (*_vertices)[1].set(_region.r(), _region.t(), 0);
132       (*_vertices)[2].set(_region.r(), _region.b(), 0);
133       (*_vertices)[3].set(_region.l(), _region.b(), 0);
134       _vertices->dirty();
135
136       _attributes_dirty &= ~DEST_SIZE;
137       _geom->dirtyBound();
138       setBoundingBox(_geom->getBound());
139     }
140
141     if( _attributes_dirty & SRC_RECT )
142     {
143       double u0 = _src_rect.l(),
144              u1 = _src_rect.r(),
145              v0 = _src_rect.b(),
146              v1 = _src_rect.t();
147
148       if( !_node_src_rect->getBoolValue("normalized", true) )
149       {
150         const Rect<int>& tex_dim = getTextureDimensions();
151
152         u0 /= tex_dim.width();
153         u1 /= tex_dim.width();
154         v0 /= tex_dim.height();
155         v1 /= tex_dim.height();
156       }
157
158       (*_texCoords)[0].set(u0, v0);
159       (*_texCoords)[1].set(u1, v0);
160       (*_texCoords)[2].set(u1, v1);
161       (*_texCoords)[3].set(u0, v1);
162       _texCoords->dirty();
163
164       _attributes_dirty &= ~SRC_RECT;
165     }
166   }
167
168   //----------------------------------------------------------------------------
169   void Image::setSrcCanvas(CanvasPtr canvas)
170   {
171     if( !_src_canvas.expired() )
172       _src_canvas.lock()->removeDependentCanvas(_canvas);
173
174     _src_canvas = canvas;
175     _geom->getOrCreateStateSet()
176          ->setTextureAttribute(0, canvas ? canvas->getTexture() : 0);
177     _geom->setCullCallback(canvas ? new CullCallback(canvas) : 0);
178
179     if( !_src_canvas.expired() )
180     {
181       setupDefaultDimensions();
182       _src_canvas.lock()->addDependentCanvas(_canvas);
183     }
184   }
185
186   //----------------------------------------------------------------------------
187   CanvasWeakPtr Image::getSrcCanvas() const
188   {
189     return _src_canvas;
190   }
191
192   //----------------------------------------------------------------------------
193   void Image::setImage(osg::Image *img)
194   {
195     // remove canvas...
196     setSrcCanvas( CanvasPtr() );
197
198     _texture->setImage(img);
199     _geom->getOrCreateStateSet()
200          ->setTextureAttributeAndModes(0, _texture);
201
202     if( img )
203       setupDefaultDimensions();
204   }
205
206   //----------------------------------------------------------------------------
207   void Image::setFill(const std::string& fill)
208   {
209     osg::Vec4 color;
210     if( !parseColor(fill, color) )
211       return;
212
213     for( int i = 0; i < 4; ++i )
214       (*_colors)[i] = color;
215     _colors->dirty();
216   }
217
218   //----------------------------------------------------------------------------
219   const Rect<float>& Image::getRegion() const
220   {
221     return _region;
222   }
223
224   //----------------------------------------------------------------------------
225   void Image::childChanged(SGPropertyNode* child)
226   {
227     const std::string& name = child->getNameString();
228
229     if( child->getParent() == _node_src_rect )
230     {
231       _attributes_dirty |= SRC_RECT;
232
233       if(      name == "left" )
234         _src_rect.setLeft( child->getFloatValue() );
235       else if( name == "right" )
236         _src_rect.setRight( child->getFloatValue() );
237       else if( name == "top" )
238         _src_rect.setTop( child->getFloatValue() );
239       else if( name == "bottom" )
240         _src_rect.setBottom( child->getFloatValue() );
241
242       return;
243     }
244     else if( child->getParent() != _node )
245       return;
246
247     if( name == "x" )
248     {
249       _region.setX( child->getFloatValue() );
250       _attributes_dirty |= DEST_SIZE;
251     }
252     else if( name == "y" )
253     {
254       _region.setY( child->getFloatValue() );
255       _attributes_dirty |= DEST_SIZE;
256     }
257     else if( name == "size" )
258     {
259       if( child->getIndex() == 0 )
260         _region.setWidth( child->getFloatValue() );
261       else
262         _region.setHeight( child->getFloatValue() );
263
264       _attributes_dirty |= DEST_SIZE;
265     }
266     else if( name == "file" )
267     {
268       static const std::string CANVAS_PROTOCOL = "canvas://";
269       const std::string& path = child->getStringValue();
270
271       CanvasPtr canvas = _canvas.lock();
272       if( !canvas )
273       {
274         SG_LOG(SG_GL, SG_ALERT, "canvas::Image: No canvas available");
275         return;
276       }
277
278       if( boost::starts_with(path, CANVAS_PROTOCOL) )
279       {
280         CanvasMgr* canvas_mgr = canvas->getCanvasMgr();
281         if( !canvas_mgr )
282         {
283           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: Failed to get CanvasMgr");
284           return;
285         }
286
287         const SGPropertyNode* canvas_node =
288           canvas_mgr->getPropertyRoot()
289                     ->getParent()
290                     ->getNode( path.substr(CANVAS_PROTOCOL.size()) );
291         if( !canvas_node )
292         {
293           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: No such canvas: " << path);
294           return;
295         }
296
297         // TODO add support for other means of addressing canvases (eg. by
298         // name)
299         CanvasPtr src_canvas = canvas_mgr->getCanvas( canvas_node->getIndex() );
300         if( !src_canvas )
301         {
302           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: Invalid canvas: " << path);
303           return;
304         }
305
306         setSrcCanvas(src_canvas);
307       }
308       else
309       {
310         setImage( canvas->getSystemAdapter()->getImage(path) );
311       }
312     }
313   }
314
315   //----------------------------------------------------------------------------
316   void Image::setupDefaultDimensions()
317   {
318     if( !_src_rect.width() || !_src_rect.height() )
319     {
320       const Rect<int>& tex_dim = getTextureDimensions();
321
322       _node_src_rect->setBoolValue("normalized", false);
323       _node_src_rect->setFloatValue("right", tex_dim.width());
324       _node_src_rect->setFloatValue("bottom", tex_dim.height());
325     }
326
327     if( !_region.width() || !_region.height() )
328     {
329       _node->setFloatValue("size[0]", _src_rect.width());
330       _node->setFloatValue("size[1]", _src_rect.height());
331     }
332   }
333
334   //----------------------------------------------------------------------------
335   Rect<int> Image::getTextureDimensions() const
336   {
337     osg::Texture2D *texture = !_src_canvas.expired()
338                             ? _src_canvas.lock()->getTexture()
339                             : _texture.get();
340
341     if( !texture )
342       return Rect<int>();
343
344     return Rect<int>
345     (
346       0,0,
347       texture->getTextureWidth(),
348       texture->getTextureHeight()
349     );
350   }
351
352 } // namespace canvas
353 } // namespace simgear