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

Revision 13041, 19.2 kB (checked in by robert, 3 years ago)

Ran script to remove trailing spaces and tabs

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