root/OpenSceneGraph/trunk/src/osg/TextureRectangle.cpp @ 10710

Revision 10710, 18.5 kB (checked in by robert, 5 years ago)

From Paul Martz, changes for compiling against OpenGL 3.x

  • 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#include <osg/GLExtensions>
15#include <osg/TextureRectangle>
16#include <osg/ImageSequence>
17#include <osg/State>
18#include <osg/GLU>
19#include <osg/Notify>
20
21#include <osg/Timer>
22
23#ifndef GL_UNPACK_CLIENT_STORAGE_APPLE
24#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2
25#endif
26
27#ifndef GL_APPLE_vertex_array_range
28#define GL_VERTEX_ARRAY_RANGE_APPLE       0x851D
29#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
30#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
31#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
32#define GL_STORAGE_CACHED_APPLE           0x85BE
33#define GL_STORAGE_SHARED_APPLE           0x85BF
34#endif
35
36// #define DO_TIMING
37
38using namespace osg;
39
40TextureRectangle::TextureRectangle():
41    _textureWidth(0),
42    _textureHeight(0)
43{
44    setWrap(WRAP_S, CLAMP);
45    setWrap(WRAP_T, CLAMP);
46
47    setFilter(MIN_FILTER, LINEAR);
48    setFilter(MAG_FILTER, LINEAR);
49}
50
51TextureRectangle::TextureRectangle(Image* image):
52            _textureWidth(0),
53            _textureHeight(0)
54{
55    setWrap(WRAP_S, CLAMP);
56    setWrap(WRAP_T, CLAMP);
57
58    setFilter(MIN_FILTER, LINEAR);
59    setFilter(MAG_FILTER, LINEAR);
60   
61    setImage(image);
62}
63
64TextureRectangle::TextureRectangle(const TextureRectangle& text,const CopyOp& copyop):
65    Texture(text,copyop),
66    _image(copyop(text._image.get())),
67    _textureWidth(text._textureWidth),
68    _textureHeight(text._textureHeight),
69    _subloadCallback(text._subloadCallback)
70{
71}
72
73TextureRectangle::~TextureRectangle()
74{
75}
76
77int TextureRectangle::compare(const StateAttribute& sa) const
78{
79    // check the types are equal and then create the rhs variable
80    // used by the COMPARE_StateAttribute_Parameter macro's below.
81    COMPARE_StateAttribute_Types(TextureRectangle,sa)
82
83    if (_image!=rhs._image) // smart pointer comparison.
84    {
85        if (_image.valid())
86        {
87            if (rhs._image.valid())
88            {
89                int result = _image->compare(*rhs._image);
90                if (result!=0) return result;
91            }
92            else
93            {
94                return 1; // valid lhs._image is greater than null.
95            }
96        }
97        else if (rhs._image.valid())
98        {
99            return -1; // valid rhs._image is greater than null.
100        }
101    }
102
103    if (!_image && !rhs._image)
104    {
105        // no image attached to either Texture2D
106        // but could these textures already be downloaded?
107        // check the _textureObjectBuffer to see if they have been
108        // downloaded
109
110        int result = compareTextureObjects(rhs);
111        if (result!=0) return result;
112    }
113
114    int result = compareTexture(rhs);
115    if (result!=0) return result;
116
117    // compare each parameter in turn against the rhs.
118    COMPARE_StateAttribute_Parameter(_textureWidth)
119    COMPARE_StateAttribute_Parameter(_textureHeight)
120    COMPARE_StateAttribute_Parameter(_subloadCallback)
121
122    return 0; // passed all the above comparison macro's, must be equal.
123}
124
125void TextureRectangle::setImage(Image* image)
126{
127    if (_image == image) return;
128
129    if (dynamic_cast<osg::ImageSequence*>(_image.get()))
130    {
131        setUpdateCallback(0);
132        setDataVariance(osg::Object::STATIC);
133    }
134
135    // delete old texture objects.
136    dirtyTextureObject();
137
138    _image = image;
139   
140    if (dynamic_cast<osg::ImageSequence*>(_image.get()))
141    {
142        setUpdateCallback(new ImageSequence::UpdateCallback());
143        setDataVariance(osg::Object::DYNAMIC);
144    }
145}
146
147
148void TextureRectangle::apply(State& state) const
149{
150    static bool s_rectangleSupported = isGLExtensionSupported(state.getContextID(),"GL_ARB_texture_rectangle")
151            || isGLExtensionSupported(state.getContextID(),"GL_EXT_texture_rectangle")
152            || isGLExtensionSupported(state.getContextID(),"GL_NV_texture_rectangle");
153
154    if (!s_rectangleSupported)
155    {
156        notify(WARN)<<"Warning: TextureRectangle::apply(..) failed, texture rectangle is not support by your OpenGL drivers."<<std::endl;
157        return;
158    }
159
160    // get the contextID (user defined ID of 0 upwards) for the
161    // current OpenGL context.
162    const unsigned int contextID = state.getContextID();
163
164    Texture::TextureObjectManager* tom = Texture::getTextureObjectManager(contextID);
165    ElapsedTime elapsedTime(&(tom->getApplyTime()));
166    tom->getNumberApplied()++;
167
168
169    // get the texture object for the current contextID.
170    TextureObject* textureObject = getTextureObject(contextID);
171   
172   
173    if (textureObject != 0)
174    {
175
176        textureObject->bind();
177        if (getTextureParameterDirty(state.getContextID()))
178            applyTexParameters(GL_TEXTURE_RECTANGLE, state);
179
180        if (_subloadCallback.valid())
181        {
182            _subloadCallback->subload(*this, state);
183        }
184        else if (_image.valid() && getModifiedCount(contextID) != _image->getModifiedCount())
185        {
186            applyTexImage_subload(GL_TEXTURE_RECTANGLE, _image.get(), state, _textureWidth, _textureHeight, _internalFormat);
187 
188            // update the modified count to show that it is upto date.
189            getModifiedCount(contextID) = _image->getModifiedCount();
190        }
191    }
192    else if (_subloadCallback.valid())
193    {
194        // we don't have a applyTexImage1D_subload yet so can't reuse.. so just generate a new texture object.       
195        _textureObjectBuffer[contextID] = textureObject = generateTextureObject(this, contextID,GL_TEXTURE_RECTANGLE);
196
197        textureObject->bind();
198
199        applyTexParameters(GL_TEXTURE_RECTANGLE, state);
200
201        _subloadCallback->load(*this, state);
202
203        textureObject->setAllocated(1,_internalFormat,_textureWidth,_textureHeight,1,0);
204
205        // in theory the following line is redundant, but in practice
206        // have found that the first frame drawn doesn't apply the textures
207        // unless a second bind is called?!!
208        // perhaps it is the first glBind which is not required...
209        //glBindTexture(GL_TEXTURE_RECTANGLE, handle);
210    }
211    else if (_image.valid() && _image->data())
212    {
213
214
215        // keep the image around at least till we go out of scope.
216        osg::ref_ptr<osg::Image> image = _image;
217
218        // compute the internal texture format, this set the _internalFormat to an appropriate value.
219        computeInternalFormat();
220
221        _textureWidth = image->s();
222        _textureHeight = image->t();
223
224        _textureObjectBuffer[contextID] = textureObject = generateTextureObject(
225                this, contextID,GL_TEXTURE_RECTANGLE,1,_internalFormat,_textureWidth,_textureHeight,1,0);
226
227        textureObject->bind();
228
229        applyTexParameters(GL_TEXTURE_RECTANGLE, state);
230
231        if (textureObject->isAllocated())
232        {
233            applyTexImage_subload(GL_TEXTURE_RECTANGLE, _image.get(), state, _textureWidth, _textureHeight, _internalFormat);
234        }
235        else
236        {
237            applyTexImage_load(GL_TEXTURE_RECTANGLE, _image.get(), state, _textureWidth, _textureHeight);
238            textureObject->setAllocated(true);
239        }
240
241        if (state.getMaxTexturePoolSize()==0 && _unrefImageDataAfterApply && areAllTextureObjectsLoaded() && _image->getDataVariance()==STATIC)
242        {
243            TextureRectangle* non_const_this = const_cast<TextureRectangle*>(this);
244            non_const_this->_image = 0;
245        }
246
247    }
248    else if ( (_textureWidth!=0) && (_textureHeight!=0) && (_internalFormat!=0) )
249    {
250        _textureObjectBuffer[contextID] = textureObject = generateTextureObject(
251                this, contextID,GL_TEXTURE_RECTANGLE,0,_internalFormat,_textureWidth,_textureHeight,1,0);
252       
253        textureObject->bind();
254
255        applyTexParameters(GL_TEXTURE_RECTANGLE,state);
256
257        // no image present, but dimensions at set so lets create the texture
258        glTexImage2D( GL_TEXTURE_RECTANGLE, 0, _internalFormat,
259                     _textureWidth, _textureHeight, _borderWidth,
260                     _sourceFormat ? _sourceFormat : _internalFormat,
261                     _sourceType ? _sourceType : GL_UNSIGNED_BYTE,
262                     0);               
263                     
264        if (_readPBuffer.valid())
265        {
266            _readPBuffer->bindPBufferToTexture(GL_FRONT);
267        }
268       
269    }
270    else
271    {
272        glBindTexture(GL_TEXTURE_RECTANGLE, 0);
273    }
274}
275
276void TextureRectangle::applyTexImage_load(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const
277{
278    // if we don't have a valid image we can't create a texture!
279    if (!image || !image->data())
280        return;
281
282    // get the contextID (user defined ID of 0 upwards) for the
283    // current OpenGL context.
284    const unsigned int contextID = state.getContextID();
285    const Extensions* extensions = getExtensions(contextID,true);
286
287    // update the modified count to show that it is upto date.
288    getModifiedCount(contextID) = image->getModifiedCount();
289
290    // compute the internal texture format, sets _internalFormat.
291    computeInternalFormat();
292
293    glPixelStorei(GL_UNPACK_ALIGNMENT, image->getPacking());
294
295    bool useClientStorage = extensions->isClientStorageSupported() && getClientStorageHint();
296    if (useClientStorage)
297    {
298        glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE,GL_TRUE);
299
300        #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)
301            glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_PRIORITY,0.0f);
302        #endif
303
304        #ifdef GL_TEXTURE_STORAGE_HINT_APPLE
305            glTexParameteri(target, GL_TEXTURE_STORAGE_HINT_APPLE , GL_STORAGE_CACHED_APPLE);
306        #endif
307    }
308
309    const unsigned char* dataPtr = image->data();
310    GLBufferObject* pbo = image->getOrCreateGLBufferObject(contextID);
311    if (pbo)
312    {
313        state.bindPixelBufferObject(pbo);
314        dataPtr = reinterpret_cast<unsigned char*>(pbo->getOffset(image->getBufferIndex()));
315    }
316
317    if(isCompressedInternalFormat(_internalFormat) && extensions->isCompressedTexImage2DSupported())
318    {
319        extensions->glCompressedTexImage2D(target, 0, _internalFormat,
320          image->s(), image->t(), 0,
321          image->getImageSizeInBytes(),
322          dataPtr);
323    }
324    else
325    {
326        glTexImage2D(target, 0, _internalFormat,
327          image->s(), image->t(), 0,
328          (GLenum)image->getPixelFormat(),
329          (GLenum)image->getDataType(),
330          dataPtr );
331    }
332   
333
334    if (pbo)
335    {
336        state.unbindPixelBufferObject();
337    }
338
339    inwidth = image->s();
340    inheight = image->t();
341
342    if (useClientStorage)
343    {
344        glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE,GL_FALSE);
345    }
346}
347
348void TextureRectangle::applyTexImage_subload(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight, GLint& inInternalFormat) const
349{
350    // if we don't have a valid image we can't create a texture!
351    if (!image || !image->data())
352        return;
353
354    if (image->s()!=inwidth || image->t()!=inheight || image->getInternalTextureFormat()!=inInternalFormat)
355    {
356        applyTexImage_load(target, image, state, inwidth, inheight);
357        return;
358    }
359
360
361    // get the contextID (user defined ID of 0 upwards) for the
362    // current OpenGL context.
363    const unsigned int contextID = state.getContextID();
364    const Extensions* extensions = getExtensions(contextID,true);
365
366
367    // update the modified count to show that it is upto date.
368    getModifiedCount(contextID) = image->getModifiedCount();
369
370    // compute the internal texture format, sets _internalFormat.
371    computeInternalFormat();
372
373    glPixelStorei(GL_UNPACK_ALIGNMENT, image->getPacking());
374
375#ifdef DO_TIMING
376    osg::Timer_t start_tick = osg::Timer::instance()->tick();
377    osg::notify(osg::NOTICE)<<"TextureRectangle::apply pixelFormat = "<<std::hex<<image->getPixelFormat()<<std::dec<<std::endl;
378#endif
379    const unsigned char* dataPtr = image->data();
380    GLBufferObject* pbo = image->getOrCreateGLBufferObject(contextID);
381    if (pbo)
382    {
383        state.bindPixelBufferObject(pbo);
384        dataPtr = reinterpret_cast<unsigned char*>(pbo->getOffset(image->getBufferIndex()));
385#ifdef DO_TIMING
386        osg::notify(osg::NOTICE)<<"after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
387#endif
388    }
389    else
390    {
391        osg::notify(osg::NOTICE)<<"    no PixelBufferObject "<<image->getBufferObject()<<", "<<image->getPixelBufferObject()<<" pbo="<<pbo<<std::endl;
392    }
393   
394
395    if(isCompressedInternalFormat(_internalFormat) && extensions->isCompressedTexSubImage2DSupported())
396    {
397        extensions->glCompressedTexSubImage2D(target, 0,
398          0,0,
399          image->s(), image->t(),
400          (GLenum)image->getPixelFormat(),
401          (GLenum)image->getDataType(),
402          dataPtr);
403    }
404    else
405    {
406        glTexSubImage2D(target, 0,
407          0,0,
408          image->s(), image->t(),
409          (GLenum)image->getPixelFormat(),
410          (GLenum)image->getDataType(),
411          dataPtr);
412    }
413
414    if (pbo)
415    {
416        state.unbindPixelBufferObject();
417    }
418
419#ifdef DO_TIMING
420    osg::notify(osg::NOTICE)<<"glTexSubImage2D "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
421#endif
422}
423
424void TextureRectangle::computeInternalFormat() const
425{
426    if (_image.valid()) computeInternalFormatWithImage(*_image);
427    else computeInternalFormatType();
428}
429
430void TextureRectangle::copyTexImage2D(State& state, int x, int y, int width, int height )
431{
432    const unsigned int contextID = state.getContextID();
433   
434    if (_internalFormat==0) _internalFormat=GL_RGBA;
435
436    // get the globj for the current contextID.
437    TextureObject* textureObject = getTextureObject(contextID);
438   
439    if (textureObject)
440    {
441        if (width==(int)_textureWidth && height==(int)_textureHeight)
442        {
443            // we have a valid texture object which is the right size
444            // so lets play clever and use copyTexSubImage2D instead.
445            // this allows use to reuse the texture object and avoid
446            // expensive memory allocations.
447            copyTexSubImage2D(state,0 ,0, x, y, width, height);
448            return;
449        }
450        // the relevent texture object is not of the right size so
451        // needs to been deleted   
452        // remove previously bound textures.
453        dirtyTextureObject();
454        // note, dirtyTextureObject() dirties all the texture objects for
455        // this texture, is this right?  Perhaps we should dirty just the
456        // one for this context.  Note sure yet will leave till later.
457        // RO July 2001.
458    }
459   
460   
461    // remove any previously assigned images as these are nolonger valid.
462    _image = NULL;
463
464    // switch off mip-mapping.
465    //
466    _textureObjectBuffer[contextID] = textureObject = generateTextureObject(this, contextID,GL_TEXTURE_RECTANGLE);
467
468    textureObject->bind();
469   
470    applyTexParameters(GL_TEXTURE_RECTANGLE,state);
471
472
473/*    bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
474    bool hardwareMipMapOn = false;
475    if (needHardwareMipMap)
476    {
477        const Extensions* extensions = getExtensions(contextID,true);
478        bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
479
480        hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
481       
482        if (!hardwareMipMapOn)
483        {
484            // have to swtich off mip mapping
485            notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
486            _min_filter = LINEAR;
487        }
488    }
489*/   
490//    if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
491
492    glCopyTexImage2D( GL_TEXTURE_RECTANGLE, 0, _internalFormat, x, y, width, height, 0 );
493
494//    if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
495
496
497    _textureWidth = width;
498    _textureHeight = height;
499//    _numMipmapLevels = 1;
500   
501    textureObject->setAllocated(1,_internalFormat,_textureWidth,_textureHeight,1,0);
502
503
504    // inform state that this texture is the current one bound.
505    state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this);
506}
507
508void TextureRectangle::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
509{
510    const unsigned int contextID = state.getContextID();
511
512    if (_internalFormat==0) _internalFormat=GL_RGBA;
513
514    // get the texture object for the current contextID.
515    TextureObject* textureObject = getTextureObject(contextID);
516   
517    if (textureObject)
518    {
519        // we have a valid image
520        textureObject->bind();
521       
522        applyTexParameters(GL_TEXTURE_RECTANGLE,state);
523
524/*        bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
525        bool hardwareMipMapOn = false;
526        if (needHardwareMipMap)
527        {
528            const Extensions* extensions = getExtensions(contextID,true);
529            bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
530
531            hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
532
533            if (!hardwareMipMapOn)
534            {
535                // have to swtich off mip mapping
536                notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
537                _min_filter = LINEAR;
538            }
539        }
540*/
541//        if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
542
543        glCopyTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, xoffset, yoffset, x, y, width, height);
544
545//        if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
546
547        // inform state that this texture is the current one bound.
548        state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this);
549
550    }
551    else
552    {
553        // no texture object already exsits for this context so need to
554        // create it upfront - simply call copyTexImage2D.
555        copyTexImage2D(state,x,y,width,height);
556    }
557}
558
559void TextureRectangle::allocateMipmap(State&) const
560{
561    osg::notify(osg::NOTICE)<<"Warning: TextureRectangle::allocateMipmap(State&) called eroneously, GL_TEXTURE_RECTANGLE does not support mipmapping."<<std::endl;
562}
Note: See TracBrowser for help on using the browser.