Home | History | Annotate | Download | only in main
      1 /*
      2  * Mesa 3-D graphics library
      3  *
      4  * Copyright (C) 1999-2008  Brian Paul   All Rights Reserved.
      5  *
      6  * Permission is hereby granted, free of charge, to any person obtaining a
      7  * copy of this software and associated documentation files (the "Software"),
      8  * to deal in the Software without restriction, including without limitation
      9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     10  * and/or sell copies of the Software, and to permit persons to whom the
     11  * Software is furnished to do so, subject to the following conditions:
     12  *
     13  * The above copyright notice and this permission notice shall be included
     14  * in all copies or substantial portions of the Software.
     15  *
     16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
     17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
     20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
     21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     22  * OTHER DEALINGS IN THE SOFTWARE.
     23  */
     24 
     25 
     26 /**
     27  * Functions for allocating/managing framebuffers and renderbuffers.
     28  * Also, routines for reading/writing renderbuffer data as ubytes,
     29  * ushorts, uints, etc.
     30  */
     31 
     32 #include <stdio.h>
     33 #include "glheader.h"
     34 #include "imports.h"
     35 #include "blend.h"
     36 #include "buffers.h"
     37 #include "context.h"
     38 #include "enums.h"
     39 #include "formats.h"
     40 #include "macros.h"
     41 #include "mtypes.h"
     42 #include "fbobject.h"
     43 #include "framebuffer.h"
     44 #include "renderbuffer.h"
     45 #include "texobj.h"
     46 #include "glformats.h"
     47 
     48 
     49 
     50 /**
     51  * Compute/set the _DepthMax field for the given framebuffer.
     52  * This value depends on the Z buffer resolution.
     53  */
     54 static void
     55 compute_depth_max(struct gl_framebuffer *fb)
     56 {
     57    if (fb->Visual.depthBits == 0) {
     58       /* Special case.  Even if we don't have a depth buffer we need
     59        * good values for DepthMax for Z vertex transformation purposes
     60        * and for per-fragment fog computation.
     61        */
     62       fb->_DepthMax = (1 << 16) - 1;
     63    }
     64    else if (fb->Visual.depthBits < 32) {
     65       fb->_DepthMax = (1 << fb->Visual.depthBits) - 1;
     66    }
     67    else {
     68       /* Special case since shift values greater than or equal to the
     69        * number of bits in the left hand expression's type are undefined.
     70        */
     71       fb->_DepthMax = 0xffffffff;
     72    }
     73    fb->_DepthMaxF = (GLfloat) fb->_DepthMax;
     74 
     75    /* Minimum resolvable depth value, for polygon offset */
     76    fb->_MRD = (GLfloat)1.0 / fb->_DepthMaxF;
     77 }
     78 
     79 /**
     80  * Create and initialize a gl_framebuffer object.
     81  * This is intended for creating _window_system_ framebuffers, not generic
     82  * framebuffer objects ala GL_EXT_framebuffer_object.
     83  *
     84  * \sa _mesa_new_framebuffer
     85  */
     86 struct gl_framebuffer *
     87 _mesa_create_framebuffer(const struct gl_config *visual)
     88 {
     89    struct gl_framebuffer *fb = CALLOC_STRUCT(gl_framebuffer);
     90    assert(visual);
     91    if (fb) {
     92       _mesa_initialize_window_framebuffer(fb, visual);
     93    }
     94    return fb;
     95 }
     96 
     97 
     98 /**
     99  * Allocate a new gl_framebuffer object.
    100  * This is the default function for ctx->Driver.NewFramebuffer().
    101  * This is for allocating user-created framebuffers, not window-system
    102  * framebuffers!
    103  * \sa _mesa_create_framebuffer
    104  */
    105 struct gl_framebuffer *
    106 _mesa_new_framebuffer(struct gl_context *ctx, GLuint name)
    107 {
    108    struct gl_framebuffer *fb;
    109    (void) ctx;
    110    assert(name != 0);
    111    fb = CALLOC_STRUCT(gl_framebuffer);
    112    if (fb) {
    113       _mesa_initialize_user_framebuffer(fb, name);
    114    }
    115    return fb;
    116 }
    117 
    118 
    119 /**
    120  * Initialize a gl_framebuffer object.  Typically used to initialize
    121  * window system-created framebuffers, not user-created framebuffers.
    122  * \sa _mesa_initialize_user_framebuffer
    123  */
    124 void
    125 _mesa_initialize_window_framebuffer(struct gl_framebuffer *fb,
    126 				     const struct gl_config *visual)
    127 {
    128    assert(fb);
    129    assert(visual);
    130 
    131    memset(fb, 0, sizeof(struct gl_framebuffer));
    132 
    133    mtx_init(&fb->Mutex, mtx_plain);
    134 
    135    fb->RefCount = 1;
    136 
    137    /* save the visual */
    138    fb->Visual = *visual;
    139 
    140    /* Init read/draw renderbuffer state */
    141    if (visual->doubleBufferMode) {
    142       fb->_NumColorDrawBuffers = 1;
    143       fb->ColorDrawBuffer[0] = GL_BACK;
    144       fb->_ColorDrawBufferIndexes[0] = BUFFER_BACK_LEFT;
    145       fb->ColorReadBuffer = GL_BACK;
    146       fb->_ColorReadBufferIndex = BUFFER_BACK_LEFT;
    147    }
    148    else {
    149       fb->_NumColorDrawBuffers = 1;
    150       fb->ColorDrawBuffer[0] = GL_FRONT;
    151       fb->_ColorDrawBufferIndexes[0] = BUFFER_FRONT_LEFT;
    152       fb->ColorReadBuffer = GL_FRONT;
    153       fb->_ColorReadBufferIndex = BUFFER_FRONT_LEFT;
    154    }
    155 
    156    fb->Delete = _mesa_destroy_framebuffer;
    157    fb->_Status = GL_FRAMEBUFFER_COMPLETE_EXT;
    158    fb->_AllColorBuffersFixedPoint = !visual->floatMode;
    159    fb->_HasSNormOrFloatColorBuffer = visual->floatMode;
    160    fb->_HasAttachments = true;
    161 
    162    compute_depth_max(fb);
    163 }
    164 
    165 
    166 /**
    167  * Initialize a user-created gl_framebuffer object.
    168  * \sa _mesa_initialize_window_framebuffer
    169  */
    170 void
    171 _mesa_initialize_user_framebuffer(struct gl_framebuffer *fb, GLuint name)
    172 {
    173    assert(fb);
    174    assert(name);
    175 
    176    memset(fb, 0, sizeof(struct gl_framebuffer));
    177 
    178    fb->Name = name;
    179    fb->RefCount = 1;
    180    fb->_NumColorDrawBuffers = 1;
    181    fb->ColorDrawBuffer[0] = GL_COLOR_ATTACHMENT0_EXT;
    182    fb->_ColorDrawBufferIndexes[0] = BUFFER_COLOR0;
    183    fb->ColorReadBuffer = GL_COLOR_ATTACHMENT0_EXT;
    184    fb->_ColorReadBufferIndex = BUFFER_COLOR0;
    185    fb->Delete = _mesa_destroy_framebuffer;
    186    mtx_init(&fb->Mutex, mtx_plain);
    187 }
    188 
    189 
    190 /**
    191  * Deallocate buffer and everything attached to it.
    192  * Typically called via the gl_framebuffer->Delete() method.
    193  */
    194 void
    195 _mesa_destroy_framebuffer(struct gl_framebuffer *fb)
    196 {
    197    if (fb) {
    198       _mesa_free_framebuffer_data(fb);
    199       free(fb->Label);
    200       free(fb);
    201    }
    202 }
    203 
    204 
    205 /**
    206  * Free all the data hanging off the given gl_framebuffer, but don't free
    207  * the gl_framebuffer object itself.
    208  */
    209 void
    210 _mesa_free_framebuffer_data(struct gl_framebuffer *fb)
    211 {
    212    GLuint i;
    213 
    214    assert(fb);
    215    assert(fb->RefCount == 0);
    216 
    217    mtx_destroy(&fb->Mutex);
    218 
    219    for (i = 0; i < BUFFER_COUNT; i++) {
    220       struct gl_renderbuffer_attachment *att = &fb->Attachment[i];
    221       if (att->Renderbuffer) {
    222          _mesa_reference_renderbuffer(&att->Renderbuffer, NULL);
    223       }
    224       if (att->Texture) {
    225          _mesa_reference_texobj(&att->Texture, NULL);
    226       }
    227       assert(!att->Renderbuffer);
    228       assert(!att->Texture);
    229       att->Type = GL_NONE;
    230    }
    231 }
    232 
    233 
    234 /**
    235  * Set *ptr to point to fb, with refcounting and locking.
    236  * This is normally only called from the _mesa_reference_framebuffer() macro
    237  * when there's a real pointer change.
    238  */
    239 void
    240 _mesa_reference_framebuffer_(struct gl_framebuffer **ptr,
    241                              struct gl_framebuffer *fb)
    242 {
    243    if (*ptr) {
    244       /* unreference old renderbuffer */
    245       GLboolean deleteFlag = GL_FALSE;
    246       struct gl_framebuffer *oldFb = *ptr;
    247 
    248       mtx_lock(&oldFb->Mutex);
    249       assert(oldFb->RefCount > 0);
    250       oldFb->RefCount--;
    251       deleteFlag = (oldFb->RefCount == 0);
    252       mtx_unlock(&oldFb->Mutex);
    253 
    254       if (deleteFlag)
    255          oldFb->Delete(oldFb);
    256 
    257       *ptr = NULL;
    258    }
    259 
    260    if (fb) {
    261       mtx_lock(&fb->Mutex);
    262       fb->RefCount++;
    263       mtx_unlock(&fb->Mutex);
    264       *ptr = fb;
    265    }
    266 }
    267 
    268 
    269 /**
    270  * Resize the given framebuffer's renderbuffers to the new width and height.
    271  * This should only be used for window-system framebuffers, not
    272  * user-created renderbuffers (i.e. made with GL_EXT_framebuffer_object).
    273  * This will typically be called directly from a device driver.
    274  *
    275  * \note it's possible for ctx to be null since a window can be resized
    276  * without a currently bound rendering context.
    277  */
    278 void
    279 _mesa_resize_framebuffer(struct gl_context *ctx, struct gl_framebuffer *fb,
    280                          GLuint width, GLuint height)
    281 {
    282    GLuint i;
    283 
    284    /* XXX I think we could check if the size is not changing
    285     * and return early.
    286     */
    287 
    288    /* Can only resize win-sys framebuffer objects */
    289    assert(_mesa_is_winsys_fbo(fb));
    290 
    291    for (i = 0; i < BUFFER_COUNT; i++) {
    292       struct gl_renderbuffer_attachment *att = &fb->Attachment[i];
    293       if (att->Type == GL_RENDERBUFFER_EXT && att->Renderbuffer) {
    294          struct gl_renderbuffer *rb = att->Renderbuffer;
    295          /* only resize if size is changing */
    296          if (rb->Width != width || rb->Height != height) {
    297             if (rb->AllocStorage(ctx, rb, rb->InternalFormat, width, height)) {
    298                assert(rb->Width == width);
    299                assert(rb->Height == height);
    300             }
    301             else {
    302                _mesa_error(ctx, GL_OUT_OF_MEMORY, "Resizing framebuffer");
    303                /* no return */
    304             }
    305          }
    306       }
    307    }
    308 
    309    fb->Width = width;
    310    fb->Height = height;
    311 
    312    if (ctx) {
    313       /* update scissor / window bounds */
    314       _mesa_update_draw_buffer_bounds(ctx, ctx->DrawBuffer);
    315       /* Signal new buffer state so that swrast will update its clipping
    316        * info (the CLIP_BIT flag).
    317        */
    318       ctx->NewState |= _NEW_BUFFERS;
    319    }
    320 }
    321 
    322 /**
    323  * Examine all the framebuffer's renderbuffers to update the Width/Height
    324  * fields of the framebuffer.  If we have renderbuffers with different
    325  * sizes, set the framebuffer's width and height to the min size.
    326  * Note: this is only intended for user-created framebuffers, not
    327  * window-system framebuffes.
    328  */
    329 static void
    330 update_framebuffer_size(struct gl_context *ctx, struct gl_framebuffer *fb)
    331 {
    332    GLuint minWidth = ~0, minHeight = ~0;
    333    GLuint i;
    334 
    335    /* user-created framebuffers only */
    336    assert(_mesa_is_user_fbo(fb));
    337 
    338    for (i = 0; i < BUFFER_COUNT; i++) {
    339       struct gl_renderbuffer_attachment *att = &fb->Attachment[i];
    340       const struct gl_renderbuffer *rb = att->Renderbuffer;
    341       if (rb) {
    342          minWidth = MIN2(minWidth, rb->Width);
    343          minHeight = MIN2(minHeight, rb->Height);
    344       }
    345    }
    346 
    347    if (minWidth != ~0U) {
    348       fb->Width = minWidth;
    349       fb->Height = minHeight;
    350    }
    351    else {
    352       fb->Width = 0;
    353       fb->Height = 0;
    354    }
    355 }
    356 
    357 
    358 
    359 /**
    360  * Given a bounding box, intersect the bounding box with the scissor of
    361  * a specified vieport.
    362  *
    363  * \param ctx     GL context.
    364  * \param idx     Index of the desired viewport
    365  * \param bbox    Bounding box for the scissored viewport.  Stored as xmin,
    366  *                xmax, ymin, ymax.
    367  */
    368 void
    369 _mesa_intersect_scissor_bounding_box(const struct gl_context *ctx,
    370                                      unsigned idx, int *bbox)
    371 {
    372    if (ctx->Scissor.EnableFlags & (1u << idx)) {
    373       if (ctx->Scissor.ScissorArray[idx].X > bbox[0]) {
    374          bbox[0] = ctx->Scissor.ScissorArray[idx].X;
    375       }
    376       if (ctx->Scissor.ScissorArray[idx].Y > bbox[2]) {
    377          bbox[2] = ctx->Scissor.ScissorArray[idx].Y;
    378       }
    379       if (ctx->Scissor.ScissorArray[idx].X + ctx->Scissor.ScissorArray[idx].Width < bbox[1]) {
    380          bbox[1] = ctx->Scissor.ScissorArray[idx].X + ctx->Scissor.ScissorArray[idx].Width;
    381       }
    382       if (ctx->Scissor.ScissorArray[idx].Y + ctx->Scissor.ScissorArray[idx].Height < bbox[3]) {
    383          bbox[3] = ctx->Scissor.ScissorArray[idx].Y + ctx->Scissor.ScissorArray[idx].Height;
    384       }
    385       /* finally, check for empty region */
    386       if (bbox[0] > bbox[1]) {
    387          bbox[0] = bbox[1];
    388       }
    389       if (bbox[2] > bbox[3]) {
    390          bbox[2] = bbox[3];
    391       }
    392    }
    393 }
    394 
    395 /**
    396  * Calculate the inclusive bounding box for the scissor of a specific viewport
    397  *
    398  * \param ctx     GL context.
    399  * \param buffer  Framebuffer to be checked against
    400  * \param idx     Index of the desired viewport
    401  * \param bbox    Bounding box for the scissored viewport.  Stored as xmin,
    402  *                xmax, ymin, ymax.
    403  *
    404  * \warning This function assumes that the framebuffer dimensions are up to
    405  * date (e.g., update_framebuffer_size has been recently called on \c buffer).
    406  *
    407  * \sa _mesa_clip_to_region
    408  */
    409 void
    410 _mesa_scissor_bounding_box(const struct gl_context *ctx,
    411                            const struct gl_framebuffer *buffer,
    412                            unsigned idx, int *bbox)
    413 {
    414    bbox[0] = 0;
    415    bbox[2] = 0;
    416    bbox[1] = buffer->Width;
    417    bbox[3] = buffer->Height;
    418 
    419    _mesa_intersect_scissor_bounding_box(ctx, idx, bbox);
    420 
    421    assert(bbox[0] <= bbox[1]);
    422    assert(bbox[2] <= bbox[3]);
    423 }
    424 
    425 /**
    426  * Update the context's current drawing buffer's Xmin, Xmax, Ymin, Ymax fields.
    427  * These values are computed from the buffer's width and height and
    428  * the scissor box, if it's enabled.
    429  * \param ctx  the GL context.
    430  */
    431 void
    432 _mesa_update_draw_buffer_bounds(struct gl_context *ctx,
    433                                 struct gl_framebuffer *buffer)
    434 {
    435    int bbox[4];
    436 
    437    if (!buffer)
    438       return;
    439 
    440    if (_mesa_is_user_fbo(buffer)) {
    441       /* user-created framebuffer size depends on the renderbuffers */
    442       update_framebuffer_size(ctx, buffer);
    443    }
    444 
    445    /* Default to the first scissor as that's always valid */
    446    _mesa_scissor_bounding_box(ctx, buffer, 0, bbox);
    447    buffer->_Xmin = bbox[0];
    448    buffer->_Ymin = bbox[2];
    449    buffer->_Xmax = bbox[1];
    450    buffer->_Ymax = bbox[3];
    451 }
    452 
    453 
    454 /**
    455  * The glGet queries of the framebuffer red/green/blue size, stencil size,
    456  * etc. are satisfied by the fields of ctx->DrawBuffer->Visual.  These can
    457  * change depending on the renderbuffer bindings.  This function updates
    458  * the given framebuffer's Visual from the current renderbuffer bindings.
    459  *
    460  * This may apply to user-created framebuffers or window system framebuffers.
    461  *
    462  * Also note: ctx->DrawBuffer->Visual.depthBits might not equal
    463  * ctx->DrawBuffer->Attachment[BUFFER_DEPTH].Renderbuffer.DepthBits.
    464  * The former one is used to convert floating point depth values into
    465  * integer Z values.
    466  */
    467 void
    468 _mesa_update_framebuffer_visual(struct gl_context *ctx,
    469 				struct gl_framebuffer *fb)
    470 {
    471    GLuint i;
    472 
    473    memset(&fb->Visual, 0, sizeof(fb->Visual));
    474    fb->Visual.rgbMode = GL_TRUE; /* assume this */
    475 
    476 #if 0 /* this _might_ be needed */
    477    if (fb->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
    478       /* leave visual fields zero'd */
    479       return;
    480    }
    481 #endif
    482 
    483    /* find first RGB renderbuffer */
    484    for (i = 0; i < BUFFER_COUNT; i++) {
    485       if (fb->Attachment[i].Renderbuffer) {
    486          const struct gl_renderbuffer *rb = fb->Attachment[i].Renderbuffer;
    487          const GLenum baseFormat = _mesa_get_format_base_format(rb->Format);
    488          const mesa_format fmt = rb->Format;
    489 
    490          /* Grab samples and sampleBuffers from any attachment point (assuming
    491           * the framebuffer is complete, we'll get the same answer from all
    492           * attachments).
    493           */
    494          fb->Visual.samples = rb->NumSamples;
    495          fb->Visual.sampleBuffers = rb->NumSamples > 0 ? 1 : 0;
    496 
    497          if (_mesa_is_legal_color_format(ctx, baseFormat)) {
    498             fb->Visual.redBits = _mesa_get_format_bits(fmt, GL_RED_BITS);
    499             fb->Visual.greenBits = _mesa_get_format_bits(fmt, GL_GREEN_BITS);
    500             fb->Visual.blueBits = _mesa_get_format_bits(fmt, GL_BLUE_BITS);
    501             fb->Visual.alphaBits = _mesa_get_format_bits(fmt, GL_ALPHA_BITS);
    502             fb->Visual.rgbBits = fb->Visual.redBits
    503                + fb->Visual.greenBits + fb->Visual.blueBits;
    504             if (_mesa_get_format_color_encoding(fmt) == GL_SRGB)
    505                 fb->Visual.sRGBCapable = ctx->Extensions.EXT_framebuffer_sRGB;
    506             break;
    507          }
    508       }
    509    }
    510 
    511    fb->Visual.floatMode = GL_FALSE;
    512    for (i = 0; i < BUFFER_COUNT; i++) {
    513       if (fb->Attachment[i].Renderbuffer) {
    514          const struct gl_renderbuffer *rb = fb->Attachment[i].Renderbuffer;
    515          const mesa_format fmt = rb->Format;
    516 
    517          if (_mesa_get_format_datatype(fmt) == GL_FLOAT) {
    518             fb->Visual.floatMode = GL_TRUE;
    519             break;
    520          }
    521       }
    522    }
    523 
    524    if (fb->Attachment[BUFFER_DEPTH].Renderbuffer) {
    525       const struct gl_renderbuffer *rb =
    526          fb->Attachment[BUFFER_DEPTH].Renderbuffer;
    527       const mesa_format fmt = rb->Format;
    528       fb->Visual.haveDepthBuffer = GL_TRUE;
    529       fb->Visual.depthBits = _mesa_get_format_bits(fmt, GL_DEPTH_BITS);
    530    }
    531 
    532    if (fb->Attachment[BUFFER_STENCIL].Renderbuffer) {
    533       const struct gl_renderbuffer *rb =
    534          fb->Attachment[BUFFER_STENCIL].Renderbuffer;
    535       const mesa_format fmt = rb->Format;
    536       fb->Visual.haveStencilBuffer = GL_TRUE;
    537       fb->Visual.stencilBits = _mesa_get_format_bits(fmt, GL_STENCIL_BITS);
    538    }
    539 
    540    if (fb->Attachment[BUFFER_ACCUM].Renderbuffer) {
    541       const struct gl_renderbuffer *rb =
    542          fb->Attachment[BUFFER_ACCUM].Renderbuffer;
    543       const mesa_format fmt = rb->Format;
    544       fb->Visual.haveAccumBuffer = GL_TRUE;
    545       fb->Visual.accumRedBits = _mesa_get_format_bits(fmt, GL_RED_BITS);
    546       fb->Visual.accumGreenBits = _mesa_get_format_bits(fmt, GL_GREEN_BITS);
    547       fb->Visual.accumBlueBits = _mesa_get_format_bits(fmt, GL_BLUE_BITS);
    548       fb->Visual.accumAlphaBits = _mesa_get_format_bits(fmt, GL_ALPHA_BITS);
    549    }
    550 
    551    compute_depth_max(fb);
    552 }
    553 
    554 
    555 /*
    556  * Example DrawBuffers scenarios:
    557  *
    558  * 1. glDrawBuffer(GL_FRONT_AND_BACK), fixed-func or shader writes to
    559  * "gl_FragColor" or program writes to the "result.color" register:
    560  *
    561  *   fragment color output   renderbuffer
    562  *   ---------------------   ---------------
    563  *   color[0]                Front, Back
    564  *
    565  *
    566  * 2. glDrawBuffers(3, [GL_FRONT, GL_AUX0, GL_AUX1]), shader writes to
    567  * gl_FragData[i] or program writes to result.color[i] registers:
    568  *
    569  *   fragment color output   renderbuffer
    570  *   ---------------------   ---------------
    571  *   color[0]                Front
    572  *   color[1]                Aux0
    573  *   color[3]                Aux1
    574  *
    575  *
    576  * 3. glDrawBuffers(3, [GL_FRONT, GL_AUX0, GL_AUX1]) and shader writes to
    577  * gl_FragColor, or fixed function:
    578  *
    579  *   fragment color output   renderbuffer
    580  *   ---------------------   ---------------
    581  *   color[0]                Front, Aux0, Aux1
    582  *
    583  *
    584  * In either case, the list of renderbuffers is stored in the
    585  * framebuffer->_ColorDrawBuffers[] array and
    586  * framebuffer->_NumColorDrawBuffers indicates the number of buffers.
    587  * The renderer (like swrast) has to look at the current fragment shader
    588  * to see if it writes to gl_FragColor vs. gl_FragData[i] to determine
    589  * how to map color outputs to renderbuffers.
    590  *
    591  * Note that these two calls are equivalent (for fixed function fragment
    592  * shading anyway):
    593  *   a)  glDrawBuffer(GL_FRONT_AND_BACK);  (assuming non-stereo framebuffer)
    594  *   b)  glDrawBuffers(2, [GL_FRONT_LEFT, GL_BACK_LEFT]);
    595  */
    596 
    597 
    598 
    599 
    600 /**
    601  * Update the (derived) list of color drawing renderbuffer pointers.
    602  * Later, when we're rendering we'll loop from 0 to _NumColorDrawBuffers
    603  * writing colors.
    604  */
    605 static void
    606 update_color_draw_buffers(struct gl_context *ctx, struct gl_framebuffer *fb)
    607 {
    608    GLuint output;
    609 
    610    /* set 0th buffer to NULL now in case _NumColorDrawBuffers is zero */
    611    fb->_ColorDrawBuffers[0] = NULL;
    612 
    613    for (output = 0; output < fb->_NumColorDrawBuffers; output++) {
    614       GLint buf = fb->_ColorDrawBufferIndexes[output];
    615       if (buf >= 0) {
    616          fb->_ColorDrawBuffers[output] = fb->Attachment[buf].Renderbuffer;
    617       }
    618       else {
    619          fb->_ColorDrawBuffers[output] = NULL;
    620       }
    621    }
    622 }
    623 
    624 
    625 /**
    626  * Update the (derived) color read renderbuffer pointer.
    627  * Unlike the DrawBuffer, we can only read from one (or zero) color buffers.
    628  */
    629 static void
    630 update_color_read_buffer(struct gl_context *ctx, struct gl_framebuffer *fb)
    631 {
    632    (void) ctx;
    633    if (fb->_ColorReadBufferIndex == -1 ||
    634        fb->DeletePending ||
    635        fb->Width == 0 ||
    636        fb->Height == 0) {
    637       fb->_ColorReadBuffer = NULL; /* legal! */
    638    }
    639    else {
    640       assert(fb->_ColorReadBufferIndex >= 0);
    641       assert(fb->_ColorReadBufferIndex < BUFFER_COUNT);
    642       fb->_ColorReadBuffer
    643          = fb->Attachment[fb->_ColorReadBufferIndex].Renderbuffer;
    644    }
    645 }
    646 
    647 
    648 /**
    649  * Update a gl_framebuffer's derived state.
    650  *
    651  * Specifically, update these framebuffer fields:
    652  *    _ColorDrawBuffers
    653  *    _NumColorDrawBuffers
    654  *    _ColorReadBuffer
    655  *
    656  * If the framebuffer is user-created, make sure it's complete.
    657  *
    658  * The following functions (at least) can effect framebuffer state:
    659  * glReadBuffer, glDrawBuffer, glDrawBuffersARB, glFramebufferRenderbufferEXT,
    660  * glRenderbufferStorageEXT.
    661  */
    662 static void
    663 update_framebuffer(struct gl_context *ctx, struct gl_framebuffer *fb)
    664 {
    665    if (_mesa_is_winsys_fbo(fb)) {
    666       /* This is a window-system framebuffer */
    667       /* Need to update the FB's GL_DRAW_BUFFER state to match the
    668        * context state (GL_READ_BUFFER too).
    669        */
    670       if (fb->ColorDrawBuffer[0] != ctx->Color.DrawBuffer[0]) {
    671          _mesa_drawbuffers(ctx, fb, ctx->Const.MaxDrawBuffers,
    672                            ctx->Color.DrawBuffer, NULL);
    673       }
    674    }
    675    else {
    676       /* This is a user-created framebuffer.
    677        * Completeness only matters for user-created framebuffers.
    678        */
    679       if (fb->_Status != GL_FRAMEBUFFER_COMPLETE) {
    680          _mesa_test_framebuffer_completeness(ctx, fb);
    681       }
    682    }
    683 
    684    /* Strictly speaking, we don't need to update the draw-state
    685     * if this FB is bound as ctx->ReadBuffer (and conversely, the
    686     * read-state if this FB is bound as ctx->DrawBuffer), but no
    687     * harm.
    688     */
    689    update_color_draw_buffers(ctx, fb);
    690    update_color_read_buffer(ctx, fb);
    691 
    692    compute_depth_max(fb);
    693 }
    694 
    695 
    696 /**
    697  * Update state related to the draw/read framebuffers.
    698  */
    699 void
    700 _mesa_update_framebuffer(struct gl_context *ctx,
    701                          struct gl_framebuffer *readFb,
    702                          struct gl_framebuffer *drawFb)
    703 {
    704    assert(ctx);
    705 
    706    update_framebuffer(ctx, drawFb);
    707    if (readFb != drawFb)
    708       update_framebuffer(ctx, readFb);
    709 
    710    _mesa_update_clamp_vertex_color(ctx, drawFb);
    711    _mesa_update_clamp_fragment_color(ctx, drawFb);
    712 }
    713 
    714 
    715 /**
    716  * Check if the renderbuffer for a read/draw operation exists.
    717  * \param format  a basic image format such as GL_RGB, GL_RGBA, GL_ALPHA,
    718  *                GL_DEPTH_COMPONENT, etc. or GL_COLOR, GL_DEPTH, GL_STENCIL.
    719  * \param reading  if TRUE, we're going to read from the buffer,
    720                    if FALSE, we're going to write to the buffer.
    721  * \return GL_TRUE if buffer exists, GL_FALSE otherwise
    722  */
    723 static GLboolean
    724 renderbuffer_exists(struct gl_context *ctx,
    725                     struct gl_framebuffer *fb,
    726                     GLenum format,
    727                     GLboolean reading)
    728 {
    729    const struct gl_renderbuffer_attachment *att = fb->Attachment;
    730 
    731    /* If we don't know the framebuffer status, update it now */
    732    if (fb->_Status == 0) {
    733       _mesa_test_framebuffer_completeness(ctx, fb);
    734    }
    735 
    736    if (fb->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
    737       return GL_FALSE;
    738    }
    739 
    740    switch (format) {
    741    case GL_COLOR:
    742    case GL_RED:
    743    case GL_GREEN:
    744    case GL_BLUE:
    745    case GL_ALPHA:
    746    case GL_LUMINANCE:
    747    case GL_LUMINANCE_ALPHA:
    748    case GL_INTENSITY:
    749    case GL_RG:
    750    case GL_RGB:
    751    case GL_BGR:
    752    case GL_RGBA:
    753    case GL_BGRA:
    754    case GL_ABGR_EXT:
    755    case GL_RED_INTEGER_EXT:
    756    case GL_RG_INTEGER:
    757    case GL_GREEN_INTEGER_EXT:
    758    case GL_BLUE_INTEGER_EXT:
    759    case GL_ALPHA_INTEGER_EXT:
    760    case GL_RGB_INTEGER_EXT:
    761    case GL_RGBA_INTEGER_EXT:
    762    case GL_BGR_INTEGER_EXT:
    763    case GL_BGRA_INTEGER_EXT:
    764    case GL_LUMINANCE_INTEGER_EXT:
    765    case GL_LUMINANCE_ALPHA_INTEGER_EXT:
    766       if (reading) {
    767          /* about to read from a color buffer */
    768          const struct gl_renderbuffer *readBuf = fb->_ColorReadBuffer;
    769          if (!readBuf) {
    770             return GL_FALSE;
    771          }
    772          assert(_mesa_get_format_bits(readBuf->Format, GL_RED_BITS) > 0 ||
    773                 _mesa_get_format_bits(readBuf->Format, GL_ALPHA_BITS) > 0 ||
    774                 _mesa_get_format_bits(readBuf->Format, GL_TEXTURE_LUMINANCE_SIZE) > 0 ||
    775                 _mesa_get_format_bits(readBuf->Format, GL_TEXTURE_INTENSITY_SIZE) > 0 ||
    776                 _mesa_get_format_bits(readBuf->Format, GL_INDEX_BITS) > 0);
    777       }
    778       else {
    779          /* about to draw to zero or more color buffers (none is OK) */
    780          return GL_TRUE;
    781       }
    782       break;
    783    case GL_DEPTH:
    784    case GL_DEPTH_COMPONENT:
    785       if (att[BUFFER_DEPTH].Type == GL_NONE) {
    786          return GL_FALSE;
    787       }
    788       break;
    789    case GL_STENCIL:
    790    case GL_STENCIL_INDEX:
    791       if (att[BUFFER_STENCIL].Type == GL_NONE) {
    792          return GL_FALSE;
    793       }
    794       break;
    795    case GL_DEPTH_STENCIL_EXT:
    796       if (att[BUFFER_DEPTH].Type == GL_NONE ||
    797           att[BUFFER_STENCIL].Type == GL_NONE) {
    798          return GL_FALSE;
    799       }
    800       break;
    801    default:
    802       _mesa_problem(ctx,
    803                     "Unexpected format 0x%x in renderbuffer_exists",
    804                     format);
    805       return GL_FALSE;
    806    }
    807 
    808    /* OK */
    809    return GL_TRUE;
    810 }
    811 
    812 
    813 /**
    814  * Check if the renderbuffer for a read operation (glReadPixels, glCopyPixels,
    815  * glCopyTex[Sub]Image, etc) exists.
    816  * \param format  a basic image format such as GL_RGB, GL_RGBA, GL_ALPHA,
    817  *                GL_DEPTH_COMPONENT, etc. or GL_COLOR, GL_DEPTH, GL_STENCIL.
    818  * \return GL_TRUE if buffer exists, GL_FALSE otherwise
    819  */
    820 GLboolean
    821 _mesa_source_buffer_exists(struct gl_context *ctx, GLenum format)
    822 {
    823    return renderbuffer_exists(ctx, ctx->ReadBuffer, format, GL_TRUE);
    824 }
    825 
    826 
    827 /**
    828  * As above, but for drawing operations.
    829  */
    830 GLboolean
    831 _mesa_dest_buffer_exists(struct gl_context *ctx, GLenum format)
    832 {
    833    return renderbuffer_exists(ctx, ctx->DrawBuffer, format, GL_FALSE);
    834 }
    835 
    836 
    837 /**
    838  * Used to answer the GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES query.
    839  */
    840 GLenum
    841 _mesa_get_color_read_format(struct gl_context *ctx)
    842 {
    843    if (!ctx->ReadBuffer || !ctx->ReadBuffer->_ColorReadBuffer) {
    844       /* The spec is unclear how to handle this case, but NVIDIA's
    845        * driver generates GL_INVALID_OPERATION.
    846        */
    847       _mesa_error(ctx, GL_INVALID_OPERATION,
    848                   "glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT: "
    849                   "no GL_READ_BUFFER)");
    850       return GL_NONE;
    851    }
    852    else {
    853       const mesa_format format = ctx->ReadBuffer->_ColorReadBuffer->Format;
    854       const GLenum data_type = _mesa_get_format_datatype(format);
    855 
    856       if (format == MESA_FORMAT_B8G8R8A8_UNORM)
    857          return GL_BGRA;
    858       else if (format == MESA_FORMAT_B5G6R5_UNORM)
    859          return GL_RGB;
    860       else if (format == MESA_FORMAT_R_UNORM8)
    861          return GL_RED;
    862 
    863       switch (data_type) {
    864       case GL_UNSIGNED_INT:
    865       case GL_INT:
    866          return GL_RGBA_INTEGER;
    867       default:
    868          return GL_RGBA;
    869       }
    870    }
    871 }
    872 
    873 
    874 /**
    875  * Used to answer the GL_IMPLEMENTATION_COLOR_READ_TYPE_OES query.
    876  */
    877 GLenum
    878 _mesa_get_color_read_type(struct gl_context *ctx)
    879 {
    880    if (!ctx->ReadBuffer || !ctx->ReadBuffer->_ColorReadBuffer) {
    881       /* The spec is unclear how to handle this case, but NVIDIA's
    882        * driver generates GL_INVALID_OPERATION.
    883        */
    884       _mesa_error(ctx, GL_INVALID_OPERATION,
    885                   "glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE: "
    886                   "no GL_READ_BUFFER)");
    887       return GL_NONE;
    888    }
    889    else {
    890       const GLenum format = ctx->ReadBuffer->_ColorReadBuffer->Format;
    891       const GLenum data_type = _mesa_get_format_datatype(format);
    892 
    893       if (format == MESA_FORMAT_B5G6R5_UNORM)
    894          return GL_UNSIGNED_SHORT_5_6_5;
    895 
    896       switch (data_type) {
    897       case GL_SIGNED_NORMALIZED:
    898          return GL_BYTE;
    899       case GL_UNSIGNED_INT:
    900       case GL_INT:
    901       case GL_FLOAT:
    902          return data_type;
    903       case GL_UNSIGNED_NORMALIZED:
    904       default:
    905          return GL_UNSIGNED_BYTE;
    906       }
    907    }
    908 }
    909 
    910 
    911 /**
    912  * Returns the read renderbuffer for the specified format.
    913  */
    914 struct gl_renderbuffer *
    915 _mesa_get_read_renderbuffer_for_format(const struct gl_context *ctx,
    916                                        GLenum format)
    917 {
    918    const struct gl_framebuffer *rfb = ctx->ReadBuffer;
    919 
    920    if (_mesa_is_color_format(format)) {
    921       return rfb->Attachment[rfb->_ColorReadBufferIndex].Renderbuffer;
    922    } else if (_mesa_is_depth_format(format) ||
    923               _mesa_is_depthstencil_format(format)) {
    924       return rfb->Attachment[BUFFER_DEPTH].Renderbuffer;
    925    } else {
    926       return rfb->Attachment[BUFFER_STENCIL].Renderbuffer;
    927    }
    928 }
    929 
    930 
    931 /**
    932  * Print framebuffer info to stderr, for debugging.
    933  */
    934 void
    935 _mesa_print_framebuffer(const struct gl_framebuffer *fb)
    936 {
    937    GLuint i;
    938 
    939    fprintf(stderr, "Mesa Framebuffer %u at %p\n", fb->Name, (void *) fb);
    940    fprintf(stderr, "  Size: %u x %u  Status: %s\n", fb->Width, fb->Height,
    941            _mesa_enum_to_string(fb->_Status));
    942    fprintf(stderr, "  Attachments:\n");
    943 
    944    for (i = 0; i < BUFFER_COUNT; i++) {
    945       const struct gl_renderbuffer_attachment *att = &fb->Attachment[i];
    946       if (att->Type == GL_TEXTURE) {
    947          const struct gl_texture_image *texImage = att->Renderbuffer->TexImage;
    948          fprintf(stderr,
    949                  "  %2d: Texture %u, level %u, face %u, slice %u, complete %d\n",
    950                  i, att->Texture->Name, att->TextureLevel, att->CubeMapFace,
    951                  att->Zoffset, att->Complete);
    952          fprintf(stderr, "       Size: %u x %u x %u  Format %s\n",
    953                  texImage->Width, texImage->Height, texImage->Depth,
    954                  _mesa_get_format_name(texImage->TexFormat));
    955       }
    956       else if (att->Type == GL_RENDERBUFFER) {
    957          fprintf(stderr, "  %2d: Renderbuffer %u, complete %d\n",
    958                  i, att->Renderbuffer->Name, att->Complete);
    959          fprintf(stderr, "       Size: %u x %u  Format %s\n",
    960                  att->Renderbuffer->Width, att->Renderbuffer->Height,
    961                  _mesa_get_format_name(att->Renderbuffer->Format));
    962       }
    963       else {
    964          fprintf(stderr, "  %2d: none\n", i);
    965       }
    966    }
    967 }
    968 
    969 bool
    970 _mesa_is_front_buffer_reading(const struct gl_framebuffer *fb)
    971 {
    972    if (!fb || _mesa_is_user_fbo(fb))
    973       return false;
    974 
    975    return fb->_ColorReadBufferIndex == BUFFER_FRONT_LEFT;
    976 }
    977 
    978 bool
    979 _mesa_is_front_buffer_drawing(const struct gl_framebuffer *fb)
    980 {
    981    if (!fb || _mesa_is_user_fbo(fb))
    982       return false;
    983 
    984    return (fb->_NumColorDrawBuffers >= 1 &&
    985            fb->_ColorDrawBufferIndexes[0] == BUFFER_FRONT_LEFT);
    986 }
    987 
    988 static inline GLuint
    989 _mesa_geometric_nonvalidated_samples(const struct gl_framebuffer *buffer)
    990 {
    991    return buffer->_HasAttachments ?
    992       buffer->Visual.samples :
    993       buffer->DefaultGeometry.NumSamples;
    994 }
    995 
    996 bool
    997 _mesa_is_multisample_enabled(const struct gl_context *ctx)
    998 {
    999    /* The sample count may not be validated by the driver, but when it is set,
   1000     * we know that is in a valid range and no driver should ever validate a
   1001     * multisampled framebuffer to non-multisampled and vice-versa.
   1002     */
   1003    return ctx->Multisample.Enabled &&
   1004           ctx->DrawBuffer &&
   1005           _mesa_geometric_nonvalidated_samples(ctx->DrawBuffer) >= 1;
   1006 }
   1007 
   1008 /**
   1009  * Is alpha testing enabled and applicable to the currently bound
   1010  * framebuffer?
   1011  */
   1012 bool
   1013 _mesa_is_alpha_test_enabled(const struct gl_context *ctx)
   1014 {
   1015    bool buffer0_is_integer = ctx->DrawBuffer->_IntegerBuffers & 0x1;
   1016    return (ctx->Color.AlphaEnabled && !buffer0_is_integer);
   1017 }
   1018 
   1019 /**
   1020  * Is alpha to coverage enabled and applicable to the currently bound
   1021  * framebuffer?
   1022  */
   1023 bool
   1024 _mesa_is_alpha_to_coverage_enabled(const struct gl_context *ctx)
   1025 {
   1026    bool buffer0_is_integer = ctx->DrawBuffer->_IntegerBuffers & 0x1;
   1027    return (ctx->Multisample.SampleAlphaToCoverage &&
   1028            _mesa_is_multisample_enabled(ctx) &&
   1029            !buffer0_is_integer);
   1030 }
   1031