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

Revision 10600, 17.9 kB (checked in by robert, 5 years ago)

Introduced new BufferObject? design + implementation in preperation of implementing a pool system for buffer objects

  • 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        // we don't have a applyTexImage1D_subload yet so can't reuse.. so just generate a new texture object.
215        textureObject = generateTextureObject(this, contextID,GL_TEXTURE_RECTANGLE);
216       
217        textureObject->bind();
218
219        applyTexParameters(GL_TEXTURE_RECTANGLE, state);
220     
221        applyTexImage_load(GL_TEXTURE_RECTANGLE, _image.get(), state, _textureWidth, _textureHeight);
222
223        textureObject->setAllocated(1,_internalFormat,_textureWidth,_textureHeight,1,0);
224       
225        _textureObjectBuffer[contextID] = textureObject;
226
227        if (_unrefImageDataAfterApply && areAllTextureObjectsLoaded() && _image->getDataVariance()==STATIC)
228        {
229            TextureRectangle* non_const_this = const_cast<TextureRectangle*>(this);
230            non_const_this->_image = 0;
231        }
232
233
234    }
235    else if ( (_textureWidth!=0) && (_textureHeight!=0) && (_internalFormat!=0) )
236    {
237        _textureObjectBuffer[contextID] = textureObject = generateTextureObject(
238                this, contextID,GL_TEXTURE_RECTANGLE,0,_internalFormat,_textureWidth,_textureHeight,1,0);
239       
240        textureObject->bind();
241
242        applyTexParameters(GL_TEXTURE_RECTANGLE,state);
243
244        // no image present, but dimensions at set so lets create the texture
245        glTexImage2D( GL_TEXTURE_RECTANGLE, 0, _internalFormat,
246                     _textureWidth, _textureHeight, _borderWidth,
247                     _sourceFormat ? _sourceFormat : _internalFormat,
248                     _sourceType ? _sourceType : GL_UNSIGNED_BYTE,
249                     0);               
250                     
251        if (_readPBuffer.valid())
252        {
253            _readPBuffer->bindPBufferToTexture(GL_FRONT);
254        }
255       
256    }
257    else
258    {
259        glBindTexture(GL_TEXTURE_RECTANGLE, 0);
260    }
261}
262
263void TextureRectangle::applyTexImage_load(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const
264{
265    // if we don't have a valid image we can't create a texture!
266    if (!image || !image->data())
267        return;
268
269    // get the contextID (user defined ID of 0 upwards) for the
270    // current OpenGL context.
271    const unsigned int contextID = state.getContextID();
272    const Extensions* extensions = getExtensions(contextID,true);
273
274    // update the modified count to show that it is upto date.
275    getModifiedCount(contextID) = image->getModifiedCount();
276
277    // compute the internal texture format, sets _internalFormat.
278    computeInternalFormat();
279
280    glPixelStorei(GL_UNPACK_ALIGNMENT, image->getPacking());
281
282    bool useClientStorage = extensions->isClientStorageSupported() && getClientStorageHint();
283    if (useClientStorage)
284    {
285        glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE,GL_TRUE);
286        glTexParameterf(target,GL_TEXTURE_PRIORITY,0.0f);
287       
288        #ifdef GL_TEXTURE_STORAGE_HINT_APPLE   
289            glTexParameteri(target, GL_TEXTURE_STORAGE_HINT_APPLE , GL_STORAGE_CACHED_APPLE);
290        #endif
291    }
292
293    const unsigned char* dataPtr = image->data();
294    GLBufferObject* pbo = image->getOrCreateGLBufferObject(contextID);
295    if (pbo)
296    {
297        state.bindPixelBufferObject(pbo);
298        dataPtr = reinterpret_cast<unsigned char*>(pbo->getOffset(image->getBufferIndex()));
299    }
300
301    if(isCompressedInternalFormat(_internalFormat) && extensions->isCompressedTexImage2DSupported())
302    {
303        extensions->glCompressedTexImage2D(target, 0, _internalFormat,
304          image->s(), image->t(), 0,
305          image->getImageSizeInBytes(),
306          dataPtr);
307    }
308    else
309    {
310        glTexImage2D(target, 0, _internalFormat,
311          image->s(), image->t(), 0,
312          (GLenum)image->getPixelFormat(),
313          (GLenum)image->getDataType(),
314          dataPtr );
315    }
316   
317
318    if (pbo)
319    {
320        state.unbindPixelBufferObject();
321    }
322
323    inwidth = image->s();
324    inheight = image->t();
325
326    if (useClientStorage)
327    {
328        glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE,GL_FALSE);
329    }
330}
331
332void TextureRectangle::applyTexImage_subload(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight, GLint& inInternalFormat) const
333{
334    // if we don't have a valid image we can't create a texture!
335    if (!image || !image->data())
336        return;
337
338    if (image->s()!=inwidth || image->t()!=inheight || image->getInternalTextureFormat()!=inInternalFormat)
339    {
340        applyTexImage_load(target, image, state, inwidth, inheight);
341        return;
342    }
343
344
345    // get the contextID (user defined ID of 0 upwards) for the
346    // current OpenGL context.
347    const unsigned int contextID = state.getContextID();
348    const Extensions* extensions = getExtensions(contextID,true);
349
350
351    // update the modified count to show that it is upto date.
352    getModifiedCount(contextID) = image->getModifiedCount();
353
354    // compute the internal texture format, sets _internalFormat.
355    computeInternalFormat();
356
357    glPixelStorei(GL_UNPACK_ALIGNMENT, image->getPacking());
358
359#ifdef DO_TIMING
360    osg::Timer_t start_tick = osg::Timer::instance()->tick();
361    osg::notify(osg::NOTICE)<<"TextureRectangle::apply pixelFormat = "<<std::hex<<image->getPixelFormat()<<std::dec<<std::endl;
362#endif
363    const unsigned char* dataPtr = image->data();
364    GLBufferObject* pbo = image->getOrCreateGLBufferObject(contextID);
365    if (pbo)
366    {
367        state.bindPixelBufferObject(pbo);
368        dataPtr = reinterpret_cast<unsigned char*>(pbo->getOffset(image->getBufferIndex()));
369#ifdef DO_TIMING
370        osg::notify(osg::NOTICE)<<"after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
371#endif
372    }
373    else
374    {
375        osg::notify(osg::NOTICE)<<"    no PixelBufferObject "<<image->getBufferObject()<<", "<<image->getPixelBufferObject()<<" pbo="<<pbo<<std::endl;
376    }
377   
378
379    if(isCompressedInternalFormat(_internalFormat) && extensions->isCompressedTexSubImage2DSupported())
380    {
381        extensions->glCompressedTexSubImage2D(target, 0,
382          0,0,
383          image->s(), image->t(),
384          (GLenum)image->getPixelFormat(),
385          (GLenum)image->getDataType(),
386          dataPtr);
387    }
388    else
389    {
390        glTexSubImage2D(target, 0,
391          0,0,
392          image->s(), image->t(),
393          (GLenum)image->getPixelFormat(),
394          (GLenum)image->getDataType(),
395          dataPtr);
396    }
397
398    if (pbo)
399    {
400        state.unbindPixelBufferObject();
401    }
402
403#ifdef DO_TIMING
404    osg::notify(osg::NOTICE)<<"glTexSubImage2D "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
405#endif
406}
407
408void TextureRectangle::computeInternalFormat() const
409{
410    if (_image.valid()) computeInternalFormatWithImage(*_image);
411    else computeInternalFormatType();
412}
413
414void TextureRectangle::copyTexImage2D(State& state, int x, int y, int width, int height )
415{
416    const unsigned int contextID = state.getContextID();
417   
418    if (_internalFormat==0) _internalFormat=GL_RGBA;
419
420    // get the globj for the current contextID.
421    TextureObject* textureObject = getTextureObject(contextID);
422   
423    if (textureObject)
424    {
425        if (width==(int)_textureWidth && height==(int)_textureHeight)
426        {
427            // we have a valid texture object which is the right size
428            // so lets play clever and use copyTexSubImage2D instead.
429            // this allows use to reuse the texture object and avoid
430            // expensive memory allocations.
431            copyTexSubImage2D(state,0 ,0, x, y, width, height);
432            return;
433        }
434        // the relevent texture object is not of the right size so
435        // needs to been deleted   
436        // remove previously bound textures.
437        dirtyTextureObject();
438        // note, dirtyTextureObject() dirties all the texture objects for
439        // this texture, is this right?  Perhaps we should dirty just the
440        // one for this context.  Note sure yet will leave till later.
441        // RO July 2001.
442    }
443   
444   
445    // remove any previously assigned images as these are nolonger valid.
446    _image = NULL;
447
448    // switch off mip-mapping.
449    //
450    _textureObjectBuffer[contextID] = textureObject = generateTextureObject(this, contextID,GL_TEXTURE_RECTANGLE);
451
452    textureObject->bind();
453   
454    applyTexParameters(GL_TEXTURE_RECTANGLE,state);
455
456
457/*    bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
458    bool hardwareMipMapOn = false;
459    if (needHardwareMipMap)
460    {
461        const Extensions* extensions = getExtensions(contextID,true);
462        bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
463
464        hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
465       
466        if (!hardwareMipMapOn)
467        {
468            // have to swtich off mip mapping
469            notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
470            _min_filter = LINEAR;
471        }
472    }
473*/   
474//    if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
475
476    glCopyTexImage2D( GL_TEXTURE_RECTANGLE, 0, _internalFormat, x, y, width, height, 0 );
477
478//    if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
479
480
481    _textureWidth = width;
482    _textureHeight = height;
483//    _numMipmapLevels = 1;
484   
485    textureObject->setAllocated(1,_internalFormat,_textureWidth,_textureHeight,1,0);
486
487
488    // inform state that this texture is the current one bound.
489    state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this);
490}
491
492void TextureRectangle::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
493{
494    const unsigned int contextID = state.getContextID();
495
496    if (_internalFormat==0) _internalFormat=GL_RGBA;
497
498    // get the texture object for the current contextID.
499    TextureObject* textureObject = getTextureObject(contextID);
500   
501    if (textureObject)
502    {
503        // we have a valid image
504        textureObject->bind();
505       
506        applyTexParameters(GL_TEXTURE_RECTANGLE,state);
507
508/*        bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
509        bool hardwareMipMapOn = false;
510        if (needHardwareMipMap)
511        {
512            const Extensions* extensions = getExtensions(contextID,true);
513            bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
514
515            hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
516
517            if (!hardwareMipMapOn)
518            {
519                // have to swtich off mip mapping
520                notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
521                _min_filter = LINEAR;
522            }
523        }
524*/
525//        if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
526
527        glCopyTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, xoffset, yoffset, x, y, width, height);
528
529//        if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
530
531        // inform state that this texture is the current one bound.
532        state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this);
533
534    }
535    else
536    {
537        // no texture object already exsits for this context so need to
538        // create it upfront - simply call copyTexImage2D.
539        copyTexImage2D(state,x,y,width,height);
540    }
541}
542
543void TextureRectangle::allocateMipmap(State&) const
544{
545    osg::notify(osg::NOTICE)<<"Warning: TextureRectangle::allocateMipmap(State&) called eroneously, GL_TEXTURE_RECTANGLE does not support mipmapping."<<std::endl;
546}
Note: See TracBrowser for help on using the browser.