root/OpenSceneGraph/trunk/include/osg/Image @ 12842

Revision 12842, 17.7 kB (checked in by robert, 3 years ago)

Added flipDepth() method

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under 
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#ifndef OSG_IMAGE
15#define OSG_IMAGE 1
16
17#include <osg/BufferObject>
18#include <osg/Vec2>
19#include <osg/Vec3>
20#include <osg/Vec4>
21#include <osg/FrameStamp>
22#include <osg/StateAttribute>
23
24#include <string>
25#include <vector>
26
27#ifndef GL_VERSION_1_2
28    // 1.2 definitions...
29    #define GL_BGR                          0x80E0
30    #define GL_BGRA                         0x80E1
31    #define GL_UNSIGNED_BYTE_3_3_2          0x8032
32    #define GL_UNSIGNED_BYTE_2_3_3_REV      0x8362
33    #define GL_UNSIGNED_SHORT_5_6_5         0x8363
34    #define GL_UNSIGNED_SHORT_5_6_5_REV     0x8364
35    #define GL_UNSIGNED_SHORT_4_4_4_4       0x8033
36    #define GL_UNSIGNED_SHORT_4_4_4_4_REV   0x8365
37    #define GL_UNSIGNED_SHORT_5_5_5_1       0x8034
38    #define GL_UNSIGNED_SHORT_1_5_5_5_REV   0x8366
39    #define GL_UNSIGNED_INT_8_8_8_8         0x8035
40    #define GL_UNSIGNED_INT_8_8_8_8_REV     0x8367
41    #define GL_UNSIGNED_INT_10_10_10_2      0x8036
42    #define GL_UNSIGNED_INT_2_10_10_10_REV  0x8368
43#endif
44
45#ifndef GL_COMPRESSED_ALPHA
46    #define GL_COMPRESSED_ALPHA             0x84E9
47    #define GL_COMPRESSED_LUMINANCE         0x84EA
48    #define GL_COMPRESSED_LUMINANCE_ALPHA   0x84EB
49    #define GL_COMPRESSED_INTENSITY         0x84EC
50    #define GL_COMPRESSED_RGB               0x84ED
51    #define GL_COMPRESSED_RGBA              0x84EE
52#endif
53
54
55#ifndef GL_ABGR_EXT
56#define GL_ABGR_EXT                         0x8000
57#endif
58
59#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE)
60    #define GL_RED                  0x1903
61    #define GL_GREEN                0x1904
62    #define GL_BLUE                 0x1905
63    #define GL_DEPTH_COMPONENT      0x1902
64    #define GL_STENCIL_INDEX        0x1901
65#endif
66
67#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) || defined(OSG_GL3_AVAILABLE)
68    #define GL_BITMAP               0x1A00
69    #define GL_COLOR_INDEX          0x1900
70    #define GL_INTENSITY12          0x804C
71    #define GL_INTENSITY16          0x804D
72    #define GL_INTENSITY4           0x804A
73    #define GL_INTENSITY8           0x804B
74    #define GL_LUMINANCE12          0x8041
75    #define GL_LUMINANCE12_ALPHA4   0x8046
76    #define GL_LUMINANCE12_ALPHA12  0x8047
77    #define GL_LUMINANCE16          0x8042
78    #define GL_LUMINANCE16_ALPHA16  0x8048
79    #define GL_LUMINANCE4           0x803F
80    #define GL_LUMINANCE4_ALPHA4    0x8043
81    #define GL_LUMINANCE6_ALPHA2    0x8044
82    #define GL_LUMINANCE8           0x8040
83    #define GL_LUMINANCE8_ALPHA8    0x8045
84    #define GL_RGBA8                0x8058
85    #define GL_PACK_ROW_LENGTH      0x0D02
86#endif
87
88#ifndef GL_PACK_SKIP_IMAGES
89    #define GL_PACK_SKIP_IMAGES     0x806B
90    #define GL_PACK_IMAGE_HEIGHT    0x806C
91    #define GL_UNPACK_SKIP_IMAGES   0x806D
92    #define GL_UNPACK_IMAGE_HEIGHT  0x806E
93#endif
94
95namespace osg {
96
97// forward declare
98class NodeVisitor;
99
100/** Image class for encapsulating the storage texture image data. */
101class OSG_EXPORT Image : public BufferData
102{
103
104    public :
105
106        Image();
107       
108        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
109        Image(const Image& image,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
110
111        virtual Object* cloneType() const { return new Image(); }
112        virtual Object* clone(const CopyOp& copyop) const { return new Image(*this,copyop); }
113        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Image*>(obj)!=0; }
114        virtual const char* libraryName() const { return "osg"; }
115        virtual const char* className() const { return "Image"; }
116
117        virtual const GLvoid*   getDataPointer() const { return data(); }
118        virtual unsigned int    getTotalDataSize() const { return getTotalSizeInBytesIncludingMipmaps(); }
119
120        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
121        virtual int compare(const Image& rhs) const;
122
123        void setFileName(const std::string& fileName);
124        inline const std::string& getFileName() const { return _fileName; }
125       
126        enum WriteHint {
127            NO_PREFERENCE,
128            STORE_INLINE,
129            EXTERNAL_FILE
130        };
131       
132        void setWriteHint(WriteHint writeHint) { _writeHint = writeHint; }
133        WriteHint getWriteHint() const { return _writeHint; }
134       
135        enum AllocationMode {
136            NO_DELETE,
137            USE_NEW_DELETE,
138            USE_MALLOC_FREE
139        };
140       
141        /** Set the method used for deleting data once it goes out of scope. */
142        void setAllocationMode(AllocationMode mode) { _allocationMode = mode; }
143
144        /** Get the method used for deleting data once it goes out of scope. */
145        AllocationMode getAllocationMode() const { return _allocationMode; }
146
147
148        /** Allocate a pixel block of specified size and type. */
149        virtual void allocateImage(int s,int t,int r,
150                           GLenum pixelFormat,GLenum type,
151                           int packing=1);
152       
153       
154        /** Set the image dimensions, format and data. */
155        virtual void setImage(int s,int t,int r,
156                      GLint internalTextureformat,
157                      GLenum pixelFormat,GLenum type,
158                      unsigned char* data,
159                      AllocationMode mode,
160                      int packing=1);
161           
162        /** Read pixels from current frame buffer at specified position and size, using glReadPixels.
163          * Create memory for storage if required, reuse existing pixel coords if possible.
164        */
165        virtual void readPixels(int x,int y,int width,int height,
166                        GLenum pixelFormat,GLenum type);
167           
168
169        /** Read the contents of the current bound texture, handling compressed pixelFormats if present.
170          * Create memory for storage if required, reuse existing pixel coords if possible.
171        */
172        virtual void readImageFromCurrentTexture(unsigned int contextID, bool copyMipMapsIfAvailable, GLenum type = GL_UNSIGNED_BYTE);
173
174
175        /** Scale image to specified size. */
176        void scaleImage(int s,int t,int r) { scaleImage(s,t,r, getDataType()); }
177
178        /** Scale image to specified size and with specified data type. */
179        virtual void scaleImage(int s,int t,int r, GLenum newDataType);
180
181        /** Copy a source Image into a subpart of this Image at specified position.
182          * Typically used to copy to an already allocated image, such as creating
183          * a 3D image from a stack 2D images.
184          * If this Image is empty then image data is created to
185          * accomodate the source image in its offset position.
186          * If source is NULL then no operation happens, this Image is left unchanged.
187        */
188        virtual void copySubImage(int s_offset, int t_offset, int r_offset, const osg::Image* source);
189
190
191        enum Origin
192        {
193            BOTTOM_LEFT,
194            TOP_LEFT
195        };
196       
197        /** Set the origin of the image.
198          * The default value is BOTTOM_LEFT and is consistent with OpenGL.
199          * TOP_LEFT is used for imagery that follows standard Imagery convention, such as movies,
200          * and hasn't been flipped yet.  For such images one much flip the t axis of the tex coords.
201          * to handle this origin position. */
202        void setOrigin(Origin origin) { _origin = origin; }
203       
204        /** Get the origin of the image.*/
205        Origin getOrigin() const { return _origin; }
206       
207
208        /** Width of image. */
209        inline int s() const { return _s; }
210
211        /** Height of image. */
212        inline int t() const { return _t; }
213       
214        /** Depth of image. */
215        inline int r() const { return _r; }
216       
217        void setInternalTextureFormat(GLint internalFormat);
218        inline GLint getInternalTextureFormat() const { return _internalTextureFormat; }
219       
220        void setPixelFormat(GLenum pixelFormat);
221        inline GLenum getPixelFormat() const { return _pixelFormat; }
222       
223        void setDataType(GLenum dataType);
224        inline GLenum getDataType() const { return _dataType; }       
225       
226        void setPacking(unsigned int packing) { _packing = packing; }
227        inline unsigned int getPacking() const { return _packing; }
228
229        /** return true of the pixel format is an OpenGL compressed pixel format.*/
230        bool isCompressed() const;
231
232        /** Set the pixel aspect ratio, defined as the pixel width divided by the pixel height.*/
233        inline void setPixelAspectRatio(float pixelAspectRatio) { _pixelAspectRatio = pixelAspectRatio; }
234
235        /** Get the pixel aspect ratio.*/
236        inline float getPixelAspectRatio() const { return _pixelAspectRatio; }
237       
238        /** Return the number of bits required for each pixel. */
239        inline unsigned int getPixelSizeInBits() const { return computePixelSizeInBits(_pixelFormat,_dataType); }
240
241        /** Return the number of bytes each row of pixels occupies once it has been packed. */
242        inline unsigned int getRowSizeInBytes() const { return computeRowWidthInBytes(_s,_pixelFormat,_dataType,_packing); }
243
244        /** Return the number of bytes each image (_s*_t) of pixels occupies. */
245        inline unsigned int getImageSizeInBytes() const { return getRowSizeInBytes()*_t; }
246       
247        /** Return the number of bytes the whole row/image/volume of pixels occupies. */
248        inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; }
249
250        /** Return the number of bytes the whole row/image/volume of pixels occupies, including all mip maps if included. */
251        unsigned int getTotalSizeInBytesIncludingMipmaps() const;
252
253        /** Return true if the Image represent a valid and usable imagery.*/
254        bool valid() const { return _s!=0 && _t!=0 && _r!=0 && _data!=0 && _dataType!=0; }
255
256        /** Raw image data. */
257        inline unsigned char* data() { return _data; }
258       
259        /** Raw const image data. */
260        inline const unsigned char* data() const { return _data; }
261
262
263        inline unsigned char* data(int column, int row=0,int image=0)
264        {
265            if (!_data) return NULL;
266            return _data+(column*getPixelSizeInBits())/8+row*getRowSizeInBytes()+image*getImageSizeInBytes();
267        }
268       
269        inline const unsigned char* data(int column, int row=0,int image=0) const
270        {
271            if (!_data) return NULL;
272            return _data+(column*getPixelSizeInBits())/8+row*getRowSizeInBytes()+image*getImageSizeInBytes();
273        }
274
275        /** Get the color value for specified texcoord.*/
276        Vec4 getColor(unsigned int s,unsigned t=0,unsigned r=0) const;
277
278        /** Get the color value for specified texcoord.*/
279        Vec4 getColor(const Vec2& texcoord) const { return getColor(Vec3(texcoord.x(),texcoord.y(),0.0f)); }
280
281        /** Get the color value for specified texcoord.*/
282        Vec4 getColor(const Vec3& texcoord) const;
283
284
285        /** Flip the image horizontally, around s dimension. */
286        void flipHorizontal();
287       
288        /** Flip the image vertically, around t dimension. */
289        void flipVertical();
290
291        /** Flip the image around the r dimension. Only relevent for 3D textures. */
292        void flipDepth();
293
294        /** Ensure image dimensions are a power of two.
295          * Mipmapped textures require the image dimensions to be
296          * power of two and are within the maxiumum texture size for
297          * the host machine.
298        */
299        void ensureValidSizeForTexturing(GLint maxTextureSize);
300
301        static bool isPackedType(GLenum type);
302        static GLenum computePixelFormat(GLenum pixelFormat);
303        static GLenum computeFormatDataType(GLenum pixelFormat);
304        static unsigned int computeNumComponents(GLenum pixelFormat);
305        static unsigned int computePixelSizeInBits(GLenum pixelFormat,GLenum type);
306        static unsigned int computeRowWidthInBytes(int width,GLenum pixelFormat,GLenum type,int packing);
307        static int computeNearestPowerOfTwo(int s,float bias=0.5f);
308        static int computeNumberOfMipmapLevels(int s,int t = 1, int r = 1);
309
310        /** Precomputed mipmaps stuff. */
311        typedef std::vector< unsigned int > MipmapDataType;
312
313        inline bool isMipmap() const {return !_mipmapData.empty();};
314
315        unsigned int getNumMipmapLevels() const
316        {
317            return static_cast<unsigned int>(_mipmapData.size())+1;
318        };
319
320        /** Send offsets into data. It is assumed that first mipmap offset (index 0) is 0.*/
321        inline void setMipmapLevels(const MipmapDataType& mipmapDataVector) { _mipmapData = mipmapDataVector; }
322       
323        inline const MipmapDataType& getMipmapLevels() const { return _mipmapData; }
324
325        inline unsigned int getMipmapOffset(unsigned int mipmapLevel) const
326        {
327            if(mipmapLevel == 0)
328                return 0;
329            else if (mipmapLevel < getNumMipmapLevels())
330               return _mipmapData[mipmapLevel-1];
331            return 0;
332        };
333       
334        inline unsigned char* getMipmapData(unsigned int mipmapLevel)
335        {
336           return _data+getMipmapOffset(mipmapLevel);
337        }
338
339        inline const unsigned char* getMipmapData(unsigned int mipmapLevel) const
340        {
341           return _data+getMipmapOffset(mipmapLevel);
342        }
343
344        /*inline const unsigned char* getMipmapData(unsigned int row, unsigned int column, unsigned int mipmapLevel) const
345        {
346           if (!_data) return NULL;
347           return getMipmapData(mipmapLevel) + (column*getPixelSizeInBits())/8+row*getRowSizeInBytes();
348        }*/
349
350        /** Return true if this image is translucent - i.e. it has alpha values that are less 1.0 (when normalized). */
351        virtual bool isImageTranslucent() const;
352
353        /** Set the optional PixelBufferObject used to map the image memory efficiently to graphics memory. */
354        void setPixelBufferObject(PixelBufferObject* buffer) { setBufferObject(buffer); }
355
356        /** Get the PixelBufferObject.*/
357        PixelBufferObject* getPixelBufferObject() { return dynamic_cast<PixelBufferObject*>(_bufferObject.get()); }
358
359        /** Get the const PixelBufferObject.*/
360        const PixelBufferObject* getPixelBufferObject() const { return dynamic_cast<const PixelBufferObject*>(_bufferObject.get()); }
361
362        /** return whether the update(NodeVisitor* nv) should be required on each frame to enable proper working of osg::Image.*/
363        virtual bool requiresUpdateCall() const { return false; }
364
365        /** update method for osg::Image subclasses that update themselves during the update traversal.*/
366        virtual void update(NodeVisitor* /*nv*/) {}
367
368        /** convience update callback class that can be attached to StateAttribute (such as Textures) to ensure
369          * that the Image::update(NodeVisitor*) method is called during the update traversal.  This callback
370          * is automatically attached when Image::requiresUpdateCall() is true (it's false by default.)
371          */
372        struct OSG_EXPORT UpdateCallback : public osg::StateAttributeCallback
373        {
374            virtual void operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv);
375        };
376
377        /** method for hinting whether to enable or disable focus to images acting as front ends to interactive surfaces such as a vnc or browser window.  Return true if handled. */
378        virtual bool sendFocusHint(bool /*focus*/) { return false; }
379
380        /** method for sending pointer events to images that are acting as front ends to interactive surfaces such as a vnc or browser window.  Return true if handled. */
381        virtual bool sendPointerEvent(int /*x*/, int /*y*/, int /*buttonMask*/) { return false; }
382
383        /** method for sending key events to images that are acting as front ends to interactive surfaces such as a vnc or browser window.  Return true if handled.*/
384        virtual bool sendKeyEvent(int /*key*/, bool /*keyDown*/) { return false; }
385
386        /** method for passing frame information to the custom Image classes, to be called only when objects associated with imagery are not culled.*/
387        virtual void setFrameLastRendered(const osg::FrameStamp* /*frameStamp*/) {}
388
389    protected :
390
391        virtual ~Image();
392
393        Image& operator = (const Image&) { return *this; }
394
395        std::string _fileName;
396        WriteHint   _writeHint;
397
398
399        Origin _origin;
400
401        int _s, _t, _r;
402        GLint _internalTextureFormat;
403        GLenum _pixelFormat;
404        GLenum _dataType;
405        unsigned int _packing;
406        float _pixelAspectRatio;
407
408        AllocationMode _allocationMode;
409        unsigned char* _data;
410       
411        void deallocateData();
412       
413        void setData(unsigned char* data,AllocationMode allocationMode);
414
415        MipmapDataType _mipmapData;
416       
417        ref_ptr<PixelBufferObject> _bufferObject;
418};
419
420class Geode;
421
422/** Convenience function to be used by image loaders to generate a valid geode
423  * to return for readNode().
424  * Use the image's s and t values to scale the dimensions of the image.
425*/
426extern OSG_EXPORT Geode* createGeodeForImage(Image* image);
427/** Convenience function to be used by image loaders to generate a valid geode
428  * to return for readNode().
429  * Use the specified s and t values to scale the dimensions of the image.
430*/
431extern OSG_EXPORT Geode* createGeodeForImage(Image* image,float s,float t);
432
433}
434
435#endif                                            // __SG_IMAGE_H
Note: See TracBrowser for help on using the browser.