source: OGRE/trunk/ogrenew/RenderSystems/GL/src/OgreGLHardwarePixelBuffer.cpp @ 692

Revision 692, 30.7 KB checked in by mattausch, 19 years ago (diff)

adding ogre 1.2 and dependencies

Line 
1/*
2-----------------------------------------------------------------------------
3This source file is part of OGRE
4    (Object-oriented Graphics Rendering Engine)
5For the latest info, see http://www.ogre3d.org/
6
7Copyright (c) 2000-2005 The OGRE Team
8Also see acknowledgements in Readme.html
9
10This program is free software; you can redistribute it and/or modify it under
11the terms of the GNU Lesser General Public License as published by the Free Software
12Foundation; either version 2 of the License, or (at your option) any later
13version.
14
15This program is distributed in the hope that it will be useful, but WITHOUT
16ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
18
19You should have received a copy of the GNU Lesser General Public License along with
20this program; if not, write to the Free Software Foundation, Inc., 59 Temple
21Place - Suite 330, Boston, MA 02111-1307, USA, or go to
22http://www.gnu.org/copyleft/lesser.txt.
23-----------------------------------------------------------------------------
24*/
25#include "OgreGLHardwarePixelBuffer.h"
26#include "OgreGLTexture.h"
27#include "OgreGLSupport.h"
28#include "OgreGLPixelFormat.h"
29#include "OgreException.h"
30#include "OgreLogManager.h"
31#include "OgreStringConverter.h"
32#include "OgreBitwise.h"
33#include "OgreGLFBORenderTexture.h"
34#include "OgreRoot.h"
35
36namespace Ogre {
37//-----------------------------------------------------------------------------
38GLHardwarePixelBuffer::GLHardwarePixelBuffer(size_t mWidth, size_t mHeight, size_t mDepth,
39                PixelFormat mFormat,
40                HardwareBuffer::Usage usage):
41      HardwarePixelBuffer(mWidth, mHeight, mDepth, mFormat, usage, false, false),
42      mBuffer(mWidth, mHeight, mDepth, mFormat),
43      mGLInternalFormat(GL_NONE)
44{
45}
46
47//----------------------------------------------------------------------------- 
48GLHardwarePixelBuffer::~GLHardwarePixelBuffer()
49{
50        // Force free buffer
51        delete [] (uint8*)mBuffer.data;
52}
53//----------------------------------------------------------------------------- 
54void GLHardwarePixelBuffer::allocateBuffer()
55{
56        if(mBuffer.data)
57                // Already allocated
58                return;
59        mBuffer.data = new uint8[mSizeInBytes];
60        // TODO: use PBO if we're HBU_DYNAMIC
61}
62//----------------------------------------------------------------------------- 
63void GLHardwarePixelBuffer::freeBuffer()
64{
65        // Free buffer if we're STATIC to save memory
66        if(mUsage & HBU_STATIC)
67        {
68                delete [] (uint8*)mBuffer.data;
69                mBuffer.data = 0;
70        }
71}
72//----------------------------------------------------------------------------- 
73PixelBox GLHardwarePixelBuffer::lockImpl(const Image::Box lockBox,  LockOptions options)
74{
75        allocateBuffer();
76        //if(!(mUsage & HBU_WRITEONLY) && options!=HBU_DISCARD)
77        if(options == HBL_READ_ONLY)
78                // Download the old contents of the texture
79                download(mBuffer);
80        return mBuffer.getSubVolume(lockBox);
81}
82//----------------------------------------------------------------------------- 
83void GLHardwarePixelBuffer::unlockImpl(void)
84{
85        // From buffer to card
86        upload(mCurrentLock);
87       
88        freeBuffer();
89}
90
91//----------------------------------------------------------------------------- 
92void GLHardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Image::Box &dstBox)
93{
94        if(!mBuffer.contains(dstBox))
95                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "destination box out of range",
96                 "GLHardwarePixelBuffer::blitFromMemory");
97        PixelBox scaled;
98       
99        if(src.getWidth() != dstBox.getWidth() ||
100                src.getHeight() != dstBox.getHeight() ||
101                src.getDepth() != dstBox.getDepth())
102        {
103                // Scale to destination size. Use DevIL and not iluScale because ILU screws up for
104                // floating point textures and cannot cope with 3D images.
105                // This also does pixel format conversion if needed
106                allocateBuffer();
107                scaled = mBuffer.getSubVolume(dstBox);
108                Image::scale(src, scaled, Image::FILTER_BILINEAR);
109        }
110        else if(GLPixelUtil::getGLOriginFormat(src.format) == 0)
111        {
112                // Extents match, but format is not accepted as valid source format for GL
113                // do conversion in temporary buffer
114                allocateBuffer();
115                scaled = mBuffer.getSubVolume(dstBox);
116                PixelUtil::bulkPixelConversion(src, scaled);
117        }
118        else
119        {
120                // No scaling or conversion needed
121                scaled = src;
122                // Set extents for upload
123                scaled.left = dstBox.left;
124                scaled.right = dstBox.right;
125                scaled.top = dstBox.top;
126                scaled.bottom = dstBox.bottom;
127                scaled.front = dstBox.front;
128                scaled.back = dstBox.back;
129        }
130       
131        upload(scaled);
132        freeBuffer();
133}
134//----------------------------------------------------------------------------- 
135void GLHardwarePixelBuffer::blitToMemory(const Image::Box &srcBox, const PixelBox &dst)
136{
137        if(!mBuffer.contains(srcBox))
138                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "source box out of range",
139                 "GLHardwarePixelBuffer::blitToMemory");
140        if(srcBox.left == 0 && srcBox.right == getWidth() &&
141           srcBox.top == 0 && srcBox.bottom == getHeight() &&
142           srcBox.front == 0 && srcBox.back == getDepth() &&
143           dst.getWidth() == getWidth() &&
144           dst.getHeight() == getHeight() &&
145           dst.getDepth() == getDepth() &&
146           GLPixelUtil::getGLOriginFormat(dst.format) != 0)
147        {
148                // The direct case: the user wants the entire texture in a format supported by GL
149                // so we don't need an intermediate buffer
150                download(dst);
151        }
152        else
153        {
154                // Use buffer for intermediate copy
155                allocateBuffer();
156                // Download entire buffer
157                download(mBuffer);
158                if(srcBox.getWidth() != dst.getWidth() ||
159                        srcBox.getHeight() != dst.getHeight() ||
160                        srcBox.getDepth() != dst.getDepth())
161                {
162                        // We need scaling
163                        Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR);
164                }
165                else
166                {
167                        // Just copy the bit that we need
168                        PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst);
169                }
170                freeBuffer();
171        }
172}
173//-----------------------------------------------------------------------------
174void GLHardwarePixelBuffer::upload(const PixelBox &data)
175{
176    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
177                "Upload not possible for this pixelbuffer type",
178        "GLHardwarePixelBuffer::upload");
179}
180//----------------------------------------------------------------------------- 
181void GLHardwarePixelBuffer::download(const PixelBox &data)
182{
183    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Download not possible for this pixelbuffer type",
184        "GLHardwarePixelBuffer::download");
185}
186//----------------------------------------------------------------------------- 
187void GLHardwarePixelBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
188{
189    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Framebuffer bind not possible for this pixelbuffer type",
190        "GLHardwarePixelBuffer::bindToFramebuffer");
191}
192//********* GLTextureBuffer
193GLTextureBuffer::GLTextureBuffer(const String &baseName, GLenum target, GLuint id, GLint face, GLint level, Usage usage, bool crappyCard):
194        GLHardwarePixelBuffer(0, 0, 0, PF_UNKNOWN, usage),
195        mTarget(target), mTextureID(id), mFace(face), mLevel(level), mSoftwareMipmap(crappyCard)
196{
197        // devise mWidth, mHeight and mDepth and mFormat
198        GLint value;
199       
200        glBindTexture( mTarget, mTextureID );
201       
202        // Get face identifier
203        mFaceTarget = mTarget;
204        if(mTarget == GL_TEXTURE_CUBE_MAP)
205                mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
206       
207        // Get width
208        glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_WIDTH, &value);
209        mWidth = value;
210       
211        // Get height
212        if(target == GL_TEXTURE_1D)
213                value = 1;      // Height always 1 for 1D textures
214        else
215                glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_HEIGHT, &value);
216        mHeight = value;
217       
218        // Get depth
219        if(target != GL_TEXTURE_3D)
220                value = 1; // Depth always 1 for non-3D textures
221        else
222                glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_DEPTH, &value);
223        mDepth = value;
224
225        // Get format
226        glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_INTERNAL_FORMAT, &value);
227        mGLInternalFormat = value;
228        mFormat = GLPixelUtil::getClosestOGREFormat(value);
229       
230        // Default
231        mRowPitch = mWidth;
232        mSlicePitch = mHeight*mWidth;
233        mSizeInBytes = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
234       
235        // Log a message
236        /*
237        std::stringstream str;
238        str << "GLHardwarePixelBuffer constructed for texture " << mTextureID
239                << " face " << mFace << " level " << mLevel << ": "
240                << "width=" << mWidth << " height="<< mHeight << " depth=" << mDepth
241                << "format=" << PixelUtil::getFormatName(mFormat) << "(internal 0x"
242                << std::hex << value << ")";
243        LogManager::getSingleton().logMessage(
244                LML_NORMAL, str.str());
245        */
246        // Set up pixel box
247        mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat);
248       
249    if(mWidth==0 || mHeight==0 || mDepth==0)
250        /// We are invalid, do not allocate a buffer
251        return;
252        // Allocate buffer
253        //if(mUsage & HBU_STATIC)
254        //      allocateBuffer();
255    // Is this a render target?
256    if(mUsage & TU_RENDERTARGET)
257    {
258        // Create render target for each slice
259        mSliceTRT.reserve(mDepth);
260        for(size_t zoffset=0; zoffset<mDepth; ++zoffset)
261        {
262            String name;
263            name = baseName+
264                "/"+Ogre::StringConverter::toString(face)+
265                "/"+Ogre::StringConverter::toString(level)+
266                "/"+Ogre::StringConverter::toString(zoffset);
267            GLSurfaceDesc target;
268            target.buffer = this;
269            target.zoffset = zoffset;
270            RenderTexture *trt = GLRTTManager::getSingleton().createRenderTexture(name, target);
271            mSliceTRT.push_back(trt);
272            Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[zoffset]);
273        }
274        }
275}
276GLTextureBuffer::~GLTextureBuffer()
277{
278    if(mUsage & TU_RENDERTARGET)
279    {
280        // Delete all render targets that are not yet deleted via _clearSliceRTT because the rendertarget
281        // was deleted by the user.
282        for(size_t zoffset=0; zoffset<mDepth; ++zoffset)
283        {
284            if(mSliceTRT[zoffset])
285                Root::getSingleton().getRenderSystem()->destroyRenderTarget(mSliceTRT[zoffset]->getName());
286        }
287        }
288}
289//-----------------------------------------------------------------------------
290void GLTextureBuffer::upload(const PixelBox &data)
291{
292        glBindTexture( mTarget, mTextureID );
293        if(PixelUtil::isCompressed(data.format))
294        {
295                if(data.format != mFormat || !data.isConsecutive())
296                        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
297                        "Compressed images must be consecutive, in the source format",
298                        "GLHardwarePixelBuffer::upload");
299                GLenum format = GLPixelUtil::getClosestGLInternalFormat(mFormat);
300                // Data must be consecutive and at beginning of buffer as PixelStorei not allowed
301                // for compressed formats
302                switch(mTarget) {
303                        case GL_TEXTURE_1D:
304                                glCompressedTexSubImage1DARB(GL_TEXTURE_1D, mLevel,
305                                        data.left,
306                                        data.getWidth(),
307                                        format, data.getConsecutiveSize(),
308                                        data.data);
309                                break;
310                        case GL_TEXTURE_2D:
311                        case GL_TEXTURE_CUBE_MAP:
312                                glCompressedTexSubImage2DARB(mFaceTarget, mLevel,
313                                        data.left, data.top,
314                                        data.getWidth(), data.getHeight(),
315                                        format, data.getConsecutiveSize(),
316                                        data.data);
317                                break;
318                        case GL_TEXTURE_3D:
319                                glCompressedTexSubImage3DARB(GL_TEXTURE_3D, mLevel,
320                                        data.left, data.top, data.front,
321                                        data.getWidth(), data.getHeight(), data.getDepth(),
322                                        format, data.getConsecutiveSize(),
323                                        data.data);
324                                break;
325                }
326               
327        }
328        else if(mSoftwareMipmap)
329        {
330                GLint internalFormat;
331                glGetTexLevelParameteriv(mTarget, mLevel, GL_TEXTURE_INTERNAL_FORMAT, &internalFormat);
332                if(data.getWidth() != data.rowPitch)
333                        glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch);
334                if(data.getHeight()*data.getWidth() != data.slicePitch)
335                        glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
336                glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
337               
338                switch(mTarget)
339                {
340                case GL_TEXTURE_1D:
341                        gluBuild1DMipmaps(
342                                GL_TEXTURE_1D, internalFormat,
343                                data.getWidth(),
344                                GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
345                                data.data);
346                        break;
347                case GL_TEXTURE_2D:
348                case GL_TEXTURE_CUBE_MAP:
349                        gluBuild2DMipmaps(
350                                mFaceTarget,
351                                internalFormat, data.getWidth(), data.getHeight(),
352                                GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
353                                data.data);
354                        break;         
355                case GL_TEXTURE_3D:
356                        /* Requires GLU 1.3 which is harder to come by than cards doing hardware mipmapping
357                                Most 3D textures don't need mipmaps?
358                        gluBuild3DMipmaps(
359                                GL_TEXTURE_3D, internalFormat,
360                                data.getWidth(), data.getHeight(), data.getDepth(),
361                                GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
362                                data.data);
363                        */
364                        glTexImage3D(
365                                GL_TEXTURE_3D, 0, internalFormat,
366                                data.getWidth(), data.getHeight(), data.getDepth(), 0,
367                                GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
368                                data.data );
369                        break;
370                }
371        }
372        else
373        {
374                if(data.getWidth() != data.rowPitch)
375                        glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch);
376                if(data.getHeight()*data.getWidth() != data.slicePitch)
377                        glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
378                if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
379                        // Standard alignment of 4 is not right
380                        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
381                }
382                switch(mTarget) {
383                        case GL_TEXTURE_1D:
384                                glTexSubImage1D(GL_TEXTURE_1D, mLevel,
385                                        data.left,
386                                        data.getWidth(),
387                                        GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
388                                        data.data);
389                                break;
390                        case GL_TEXTURE_2D:
391                        case GL_TEXTURE_CUBE_MAP:
392                                glTexSubImage2D(mFaceTarget, mLevel,
393                                        data.left, data.top,
394                                        data.getWidth(), data.getHeight(),
395                                        GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
396                                        data.data);
397                                break;
398                        case GL_TEXTURE_3D:
399                                glTexSubImage3D(
400                                        GL_TEXTURE_3D, mLevel,
401                                        data.left, data.top, data.front,
402                                        data.getWidth(), data.getHeight(), data.getDepth(),
403                                        GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
404                                        data.data);
405                                break;
406                }       
407        }
408        // Restore defaults
409        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
410        glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
411        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
412}
413//----------------------------------------------------------------------------- 
414void GLTextureBuffer::download(const PixelBox &data)
415{
416        if(data.getWidth() != getWidth() ||
417                data.getHeight() != getHeight() ||
418                data.getDepth() != getDepth())
419                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "only download of entire buffer is supported by GL",
420                        "GLHardwarePixelBuffer::download");
421        glBindTexture( mTarget, mTextureID );
422        if(PixelUtil::isCompressed(data.format))
423        {
424                if(data.format != mFormat || !data.isConsecutive())
425                        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
426                        "Compressed images must be consecutive, in the source format",
427                        "GLHardwarePixelBuffer::upload");
428                // Data must be consecutive and at beginning of buffer as PixelStorei not allowed
429                // for compressed formate
430                glGetCompressedTexImageARB(mFaceTarget, mLevel, data.data);
431        }
432        else
433        {
434                if(data.getWidth() != data.rowPitch)
435                        glPixelStorei(GL_PACK_ROW_LENGTH, data.rowPitch);
436                if(data.getHeight()*data.getWidth() != data.slicePitch)
437                        glPixelStorei(GL_PACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
438                if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
439                        // Standard alignment of 4 is not right
440                        glPixelStorei(GL_PACK_ALIGNMENT, 1);
441                }
442                // We can only get the entire texture
443                glGetTexImage(mFaceTarget, mLevel,
444                        GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
445                        data.data);
446                // Restore defaults
447                glPixelStorei(GL_PACK_ROW_LENGTH, 0);
448                glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
449                glPixelStorei(GL_PACK_ALIGNMENT, 4);
450        }
451}
452//----------------------------------------------------------------------------- 
453void GLTextureBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
454{
455    assert(zoffset < mDepth);
456    switch(mTarget)
457    {
458    case GL_TEXTURE_1D:
459        glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, attachment,
460                            mFaceTarget, mTextureID, mLevel);
461        break;
462    case GL_TEXTURE_2D:
463    case GL_TEXTURE_CUBE_MAP:
464        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
465                            mFaceTarget, mTextureID, mLevel);
466        break;
467    case GL_TEXTURE_3D:
468        glFramebufferTexture3DEXT(GL_FRAMEBUFFER_EXT, attachment,
469                            mFaceTarget, mTextureID, mLevel, zoffset);
470        break;
471    }
472}
473//-----------------------------------------------------------------------------
474void GLTextureBuffer::copyFromFramebuffer(size_t zoffset)
475{
476    glBindTexture(mTarget, mTextureID);
477    switch(mTarget)
478    {
479    case GL_TEXTURE_1D:
480        glCopyTexSubImage1D(mFaceTarget, mLevel, 0, 0, 0, mWidth);
481        break;
482    case GL_TEXTURE_2D:
483    case GL_TEXTURE_CUBE_MAP:
484        glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight);
485        break;
486    case GL_TEXTURE_3D:
487        glCopyTexSubImage3D(mFaceTarget, mLevel, 0, 0, zoffset, 0, 0, mWidth, mHeight);
488        break;
489    }
490}
491//----------------------------------------------------------------------------- 
492void GLTextureBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Image::Box &srcBox, const Image::Box &dstBox)
493{
494    GLTextureBuffer *srct = static_cast<GLTextureBuffer *>(src.getPointer());
495    /// Check for FBO support first
496    /// Destination texture must be 1D, 2D, 3D, or Cube
497    /// Source texture must be 1D, 2D or 3D
498    if(GLEW_EXT_framebuffer_object &&
499        (srct->mTarget==GL_TEXTURE_1D||srct->mTarget==GL_TEXTURE_2D||srct->mTarget==GL_TEXTURE_3D))
500    {
501        blitFromTexture(srct, srcBox, dstBox);
502    }
503    else
504    {
505        GLHardwarePixelBuffer::blit(src, srcBox, dstBox);
506    }
507}
508
509//----------------------------------------------------------------------------- 
510/// Very fast texture-to-texture blitter and hardware bi/trilinear scaling implementation using FBO
511/// Destination texture must be 1D, 2D, 3D, or Cube
512/// Source texture must be 1D, 2D or 3D
513/// Supports compressed formats as both source and destination format, it will use the hardware DXT compressor
514/// if available.
515/// @author W.J. van der Laan
516void GLTextureBuffer::blitFromTexture(GLTextureBuffer *src, const Image::Box &srcBox, const Image::Box &dstBox)
517{
518    //std::cerr << "GLTextureBuffer::blitFromTexture " <<
519    //src->mTextureID << ":" << srcBox.left << "," << srcBox.top << "," << srcBox.right << "," << srcBox.bottom << " " <<
520    //mTextureID << ":" << dstBox.left << "," << dstBox.top << "," << dstBox.right << "," << dstBox.bottom << std::endl;
521    /// Store reference to FBO manager
522    GLFBOManager *fboMan = static_cast<GLFBOManager *>(GLRTTManager::getSingletonPtr());
523   
524    /// Save and clear GL state for rendering
525    glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT |
526        GL_FOG_BIT | GL_LIGHTING_BIT | GL_POLYGON_BIT | GL_SCISSOR_BIT | GL_STENCIL_BUFFER_BIT |
527        GL_TEXTURE_BIT | GL_VIEWPORT_BIT);
528
529    /// Disable alpha, depth and scissor testing, disable blending,
530    /// disable culling, disble lighting, disable fog and reset foreground
531    /// colour.
532    glDisable(GL_ALPHA_TEST);
533    glDisable(GL_DEPTH_TEST);
534    glDisable(GL_SCISSOR_TEST);
535    glDisable(GL_BLEND);
536    glDisable(GL_CULL_FACE);
537    glDisable(GL_LIGHTING);
538    glDisable(GL_FOG);
539    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
540   
541    /// Save and reset matrices
542    glMatrixMode(GL_MODELVIEW);
543    glPushMatrix();
544    glLoadIdentity();
545    glMatrixMode(GL_PROJECTION);
546    glPushMatrix();
547    glLoadIdentity();
548    glMatrixMode(GL_TEXTURE);
549    glPushMatrix();
550    glLoadIdentity();
551   
552    /// Set up source texture
553    glBindTexture(src->mTarget, src->mTextureID);
554   
555    /// Set filtering modes depending on the dimensions and source
556    if(srcBox.getWidth()==dstBox.getWidth() &&
557        srcBox.getHeight()==dstBox.getHeight() &&
558        srcBox.getDepth()==dstBox.getDepth())
559    {
560        /// Dimensions match -- use nearest filtering (fastest and pixel correct)
561        glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
562        glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
563    }
564    else
565    {
566        /// Dimensions don't match -- use bi or trilinear filtering depending on the
567        /// source texture.
568        if(src->mUsage & TU_AUTOMIPMAP)
569        {
570            /// Automatic mipmaps, we can safely use trilinear filter which
571            /// brings greatly imporoved quality for minimisation.
572            glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
573            glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);   
574        }
575        else
576        {
577            /// Manual mipmaps, stay safe with bilinear filtering so that no
578            /// intermipmap leakage occurs.
579            glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
580            glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
581        }
582    }
583    /// Clamp to edge (fastest)
584    glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
585    glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
586    glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
587   
588    /// Set origin base level mipmap to make sure we source from the right mip
589    /// level.
590    glTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, src->mLevel);
591   
592    /// Store old binding so it can be restored later
593    GLint oldfb;
594    glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb);
595   
596    /// Set up temporary FBO
597    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboMan->getTemporaryFBO());
598   
599    GLuint tempTex = 0;
600    if(!fboMan->checkFormat(mFormat))
601    {
602        /// If target format not directly supported, create intermediate texture
603        GLenum tempFormat = GLPixelUtil::getClosestGLInternalFormat(fboMan->getSupportedAlternative(mFormat));
604        glGenTextures(1, &tempTex);
605        glBindTexture(GL_TEXTURE_2D, tempTex);
606        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
607        /// Allocate temporary texture of the size of the destination area
608        glTexImage2D(GL_TEXTURE_2D, 0, tempFormat,
609            GLPixelUtil::optionalPO2(dstBox.getWidth()), GLPixelUtil::optionalPO2(dstBox.getHeight()),
610            0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
611        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
612            GL_TEXTURE_2D, tempTex, 0);
613        /// Set viewport to size of destination slice
614        glViewport(0, 0, dstBox.getWidth(), dstBox.getHeight());
615    }
616    else
617    {
618        /// We are going to bind directly, so set viewport to size and position of destination slice
619        glViewport(dstBox.left, dstBox.top, dstBox.getWidth(), dstBox.getHeight());
620    }
621   
622    /// Process each destination slice
623    for(size_t slice=dstBox.front; slice<dstBox.back; ++slice)
624    {
625        if(!tempTex)
626        {
627            /// Bind directly
628            bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, slice);
629        }
630        /// Calculate source texture coordinates
631        float u1 = (float)srcBox.left / (float)src->mWidth;
632        float v1 = (float)srcBox.top / (float)src->mHeight;
633        float u2 = (float)srcBox.right / (float)src->mWidth;
634        float v2 = (float)srcBox.bottom / (float)src->mHeight;
635        /// Calculate source slice for this destination slice
636        float w = (float)(slice - dstBox.front) / (float)dstBox.getDepth();
637        /// Get slice # in source
638        w = w * (float)srcBox.getDepth() + srcBox.front;
639        /// Normalise to texture coordinate in 0.0 .. 1.0
640        w = (w+0.5f) / (float)src->mDepth;
641       
642        /// Finally we're ready to rumble
643        glBindTexture(src->mTarget, src->mTextureID);
644        glEnable(src->mTarget);
645        glBegin(GL_QUADS);
646        glTexCoord3f(u1, v1, w);
647        glVertex2f(-1.0f, -1.0f);
648        glTexCoord3f(u2, v1, w);
649        glVertex2f(1.0f, -1.0f);
650        glTexCoord3f(u2, v2, w);
651        glVertex2f(1.0f, 1.0f);
652        glTexCoord3f(u1, v2, w);
653        glVertex2f(-1.0f, 1.0f);
654        glEnd();
655        glDisable(src->mTarget);
656       
657        if(tempTex)
658        {
659            /// Copy temporary texture
660            glBindTexture(mTarget, mTextureID);
661            switch(mTarget)
662            {
663            case GL_TEXTURE_1D:
664                glCopyTexSubImage1D(mFaceTarget, mLevel,
665                    dstBox.left,
666                    0, 0, dstBox.getWidth());
667                break;
668            case GL_TEXTURE_2D:
669            case GL_TEXTURE_CUBE_MAP:
670                glCopyTexSubImage2D(mFaceTarget, mLevel,
671                    dstBox.left, dstBox.top,
672                    0, 0, dstBox.getWidth(), dstBox.getHeight());
673                break;
674            case GL_TEXTURE_3D:
675                glCopyTexSubImage3D(mFaceTarget, mLevel,
676                    dstBox.left, dstBox.top, slice,
677                    0, 0, dstBox.getWidth(), dstBox.getHeight());
678                break;
679            }
680        }
681    }
682    /// Finish up
683    if(!tempTex)
684    {
685        /// Generate mipmaps
686        if(mUsage & TU_AUTOMIPMAP)
687        {
688            glBindTexture(mTarget, mTextureID);
689            glGenerateMipmapEXT(mTarget);
690        }
691    }
692
693    /// Reset source texture to sane state
694    glBindTexture(src->mTarget, src->mTextureID);
695    glTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, 0);
696   
697    /// Detach texture from temporary framebuffer
698    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
699                    GL_RENDERBUFFER_EXT, 0);
700    /// Restore old framebuffer
701    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, oldfb);
702    /// Restore matrix stacks and render state
703    glMatrixMode(GL_TEXTURE);
704    glPopMatrix();
705    glMatrixMode(GL_PROJECTION);
706    glPopMatrix();
707    glMatrixMode(GL_MODELVIEW);
708    glPopMatrix();
709    glPopAttrib();
710    glDeleteTextures(1, &tempTex);
711}
712//----------------------------------------------------------------------------- 
713/// blitFromMemory doing hardware trilinear scaling
714void GLTextureBuffer::blitFromMemory(const PixelBox &src_orig, const Image::Box &dstBox)
715{
716    /// Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case
717    /// - FBO is not supported
718    /// - the source dimensions match the destination ones, in which case no scaling is needed
719    if(!GLEW_EXT_framebuffer_object ||
720        (src_orig.getWidth() == dstBox.getWidth() &&
721        src_orig.getHeight() == dstBox.getHeight() &&
722        src_orig.getDepth() == dstBox.getDepth()))
723    {
724        GLHardwarePixelBuffer::blitFromMemory(src_orig, dstBox);
725        return;
726    }
727    if(!mBuffer.contains(dstBox))
728        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "destination box out of range",
729                    "GLHardwarePixelBuffer::blitFromMemory");
730    /// For scoped deletion of conversion buffer
731    MemoryDataStreamPtr buf;
732    PixelBox src;
733   
734    /// First, convert the srcbox to a OpenGL compatible pixel format
735    if(GLPixelUtil::getGLOriginFormat(src_orig.format) == 0)
736    {
737        /// Convert to buffer internal format
738        buf.bind(new MemoryDataStream(
739                PixelUtil::getMemorySize(src_orig.getWidth(), src_orig.getHeight(), src_orig.getDepth(),
740                                         mFormat)));
741        src = PixelBox(src_orig.getWidth(), src_orig.getHeight(), src_orig.getDepth(), mFormat, buf->getPtr());
742        PixelUtil::bulkPixelConversion(src_orig, src);
743    }
744    else
745    {
746        /// No conversion needed
747        src = src_orig;
748    }
749   
750    /// Create temporary texture to store source data
751    GLuint id;
752    GLenum target = (src.getDepth()!=1)?GL_TEXTURE_3D:GL_TEXTURE_2D;
753    GLsizei width = GLPixelUtil::optionalPO2(src.getWidth());
754    GLsizei height = GLPixelUtil::optionalPO2(src.getHeight());
755    GLsizei depth = GLPixelUtil::optionalPO2(src.getDepth());
756    GLenum format = GLPixelUtil::getClosestGLInternalFormat(src.format);
757   
758    /// Generate texture name
759    glGenTextures(1, &id);
760   
761    /// Set texture type
762    glBindTexture(target, id);
763   
764    /// Set automatic mipmap generation; nice for minimisation
765    glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 1000 );
766    glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE );
767   
768    /// Allocate texture memory
769    if(target == GL_TEXTURE_3D)
770        glTexImage3D(target, 0, format, width, height, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
771    else
772        glTexImage2D(target, 0, format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
773
774    /// GL texture buffer
775    GLTextureBuffer tex("", target, id, 0, 0, (Usage)(TU_AUTOMIPMAP|HBU_STATIC_WRITE_ONLY), false);
776   
777    /// Upload data to 0,0,0 in temporary texture
778    PixelBox tempTarget(src.getWidth(), src.getHeight(), src.getDepth(), src.format, src.data);
779    tex.upload(tempTarget);
780   
781    /// Blit
782    blitFromTexture(&tex, tempTarget, dstBox);
783   
784    /// Delete temp texture
785    glDeleteTextures(1, &id);
786}
787//-----------------------------------------------------------------------------   
788
789RenderTexture *GLTextureBuffer::getRenderTarget(size_t zoffset)
790{
791    assert(mUsage & TU_RENDERTARGET);
792    assert(zoffset < mDepth);
793    return mSliceTRT[zoffset];
794}
795//********* GLRenderBuffer
796//-----------------------------------------------------------------------------
797GLRenderBuffer::GLRenderBuffer(GLenum format, size_t width, size_t height):
798    GLHardwarePixelBuffer(width, height, 1, GLPixelUtil::getClosestOGREFormat(format),HBU_WRITE_ONLY)
799{
800    mGLInternalFormat = format;
801    /// Generate renderbuffer
802    glGenRenderbuffersEXT(1, &mRenderbufferID);
803    /// Bind it to FBO
804    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRenderbufferID);
805   
806    /// Allocate storage for depth buffer
807    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, format,
808                        width, height);
809}
810//-----------------------------------------------------------------------------
811GLRenderBuffer::~GLRenderBuffer()
812{
813    /// Generate renderbuffer
814    glDeleteRenderbuffersEXT(1, &mRenderbufferID);
815}
816//----------------------------------------------------------------------------- 
817void GLRenderBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
818{
819    assert(zoffset < mDepth);
820    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, attachment,
821                        GL_RENDERBUFFER_EXT, mRenderbufferID);
822}
823
824};
Note: See TracBrowser for help on using the repository browser.