meta: Fold the glUseProgram() into the blit program generator.
[mesa.git] / src / mesa / drivers / common / meta.c
index 08bd899f861ee704d98c53171a95ac69bd0c2488..f0cd5a0a8eb9bc946665611757642584c13891d3 100644 (file)
@@ -1,6 +1,5 @@
 /*
  * Mesa 3-D graphics library
- * Version:  7.6
  *
  * Copyright (C) 2009  VMware, Inc.  All Rights Reserved.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
- * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
  */
 
 /**
@@ -54,6 +54,7 @@
 #include "main/pixel.h"
 #include "main/pbo.h"
 #include "main/polygon.h"
+#include "main/queryobj.h"
 #include "main/readpix.h"
 #include "main/scissor.h"
 #include "main/shaderapi.h"
@@ -89,6 +90,9 @@ struct save_state
 {
    GLbitfield SavedState;  /**< bitmask of MESA_META_* flags */
 
+   /** MESA_META_CLEAR (and others?) */
+   struct gl_query_object *CurrentOcclusionObject;
+
    /** MESA_META_ALPHA_TEST */
    GLboolean AlphaEnabled;
    GLenum AlphaFunc;
@@ -133,9 +137,8 @@ struct save_state
    struct gl_vertex_program *VertexProgram;
    GLboolean FragmentProgramEnabled;
    struct gl_fragment_program *FragmentProgram;
-   struct gl_shader_program *VertexShader;
-   struct gl_shader_program *GeometryShader;
-   struct gl_shader_program *FragmentShader;
+   GLboolean ATIFragmentShaderEnabled;
+   struct gl_shader_program *Shader[MESA_SHADER_STAGES];
    struct gl_shader_program *ActiveShader;
 
    /** MESA_META_STENCIL_TEST */
@@ -161,11 +164,11 @@ struct save_state
    GLuint EnvMode;  /* unit[0] only */
 
    /** MESA_META_VERTEX */
-   struct gl_array_object *ArrayObj;
+   struct gl_vertex_array_object *VAO;
    struct gl_buffer_object *ArrayBufferObj;
 
    /** MESA_META_VIEWPORT */
-   GLint ViewportX, ViewportY, ViewportW, ViewportH;
+   GLfloat ViewportX, ViewportY, ViewportW, ViewportH;
    GLclampd DepthNear, DepthFar;
 
    /** MESA_META_CLAMP_FRAGMENT_COLOR */
@@ -212,15 +215,41 @@ struct temp_texture
    GLfloat Sright, Ttop;  /**< right, top texcoords */
 };
 
+/**
+ * State for GLSL texture sampler which is used to generate fragment
+ * shader in _mesa_meta_generate_mipmap().
+ */
+struct glsl_sampler {
+   const char *type;
+   const char *func;
+   const char *texcoords;
+   GLuint shader_prog;
+};
+
+/**
+ * Table of all sampler types and shaders for accessing them.
+ */
+struct sampler_table {
+   struct glsl_sampler sampler_1d;
+   struct glsl_sampler sampler_2d;
+   struct glsl_sampler sampler_3d;
+   struct glsl_sampler sampler_rect;
+   struct glsl_sampler sampler_cubemap;
+   struct glsl_sampler sampler_1d_array;
+   struct glsl_sampler sampler_2d_array;
+   struct glsl_sampler sampler_cubemap_array;
+};
 
 /**
  * State for glBlitFramebufer()
  */
 struct blit_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
    GLuint DepthFP;
+   struct sampler_table samplers;
+   struct temp_texture depthTex;
 };
 
 
@@ -229,13 +258,15 @@ struct blit_state
  */
 struct clear_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
    GLuint ShaderProg;
    GLint ColorLocation;
+   GLint LayerLocation;
 
    GLuint IntegerShaderProg;
    GLint IntegerColorLocation;
+   GLint IntegerLayerLocation;
 };
 
 
@@ -244,7 +275,7 @@ struct clear_state
  */
 struct copypix_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
 };
 
@@ -254,7 +285,8 @@ struct copypix_state
  */
 struct drawpix_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
+   GLuint VBO;
 
    GLuint StencilFP;  /**< Fragment program for drawing stencil images */
    GLuint DepthFP;  /**< Fragment program for drawing depth images */
@@ -266,38 +298,22 @@ struct drawpix_state
  */
 struct bitmap_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
    struct temp_texture Tex;  /**< separate texture from other meta ops */
 };
 
-/**
- * State for GLSL texture sampler which is used to generate fragment
- * shader in _mesa_meta_generate_mipmap().
- */
-struct glsl_sampler {
-   const char *type;
-   const char *func;
-   const char *texcoords;
-   GLuint shader_prog;
-};
-
 /**
  * State for _mesa_meta_generate_mipmap()
  */
 struct gen_mipmap_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
    GLuint FBO;
    GLuint Sampler;
-   GLuint ShaderProg;
-   struct glsl_sampler sampler_1d;
-   struct glsl_sampler sampler_2d;
-   struct glsl_sampler sampler_3d;
-   struct glsl_sampler sampler_cubemap;
-   struct glsl_sampler sampler_1d_array;
-   struct glsl_sampler sampler_2d_array;
+
+   struct sampler_table samplers;
 };
 
 /**
@@ -305,9 +321,11 @@ struct gen_mipmap_state
  */
 struct decompress_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO, FBO, RBO, Sampler;
    GLint Width, Height;
+
+   struct sampler_table samplers;
 };
 
 /**
@@ -315,7 +333,7 @@ struct decompress_state
  */
 struct drawtex_state
 {
-   GLuint ArrayObj;
+   GLuint VAO;
    GLuint VBO;
 };
 
@@ -342,11 +360,21 @@ struct gl_meta_state
    struct drawtex_state DrawTex;  /**< For _mesa_meta_DrawTex() */
 };
 
-static void meta_glsl_blit_cleanup(struct gl_context *ctx, struct blit_state *blit);
-static void cleanup_temp_texture(struct gl_context *ctx, struct temp_texture *tex);
-static void meta_glsl_clear_cleanup(struct gl_context *ctx, struct clear_state *clear);
-static void meta_glsl_generate_mipmap_cleanup(struct gl_context *ctx,
-                                              struct gen_mipmap_state *mipmap);
+struct vertex {
+   GLfloat x, y, z, tex[4];
+   GLfloat r, g, b, a;
+};
+
+static struct glsl_sampler *
+setup_texture_sampler(GLenum target, struct sampler_table *table);
+
+static void meta_glsl_blit_cleanup(struct blit_state *blit);
+static void cleanup_temp_texture(struct temp_texture *tex);
+static void meta_glsl_clear_cleanup(struct clear_state *clear);
+static void meta_glsl_generate_mipmap_cleanup(struct gen_mipmap_state *mipmap);
+static void meta_decompress_cleanup(struct decompress_state *decompress);
+static void meta_drawpix_cleanup(struct drawpix_state *drawpix);
+static void sampler_table_cleanup(struct sampler_table *table);
 
 static GLuint
 compile_shader_with_debug(struct gl_context *ctx, GLenum target, const GLcharARB *source)
@@ -375,7 +403,7 @@ compile_shader_with_debug(struct gl_context *ctx, GLenum target, const GLcharARB
       return 0;
    }
 
-   _mesa_GetProgramInfoLog(shader, size, NULL, info);
+   _mesa_GetShaderInfoLog(shader, size, NULL, info);
    _mesa_problem(ctx,
                 "meta program compile failed:\n%s\n"
                 "source:\n%s\n",
@@ -415,6 +443,192 @@ link_program_with_debug(struct gl_context *ctx, GLuint program)
    return 0;
 }
 
+/**
+ * Generate a generic shader to blit from a texture to a framebuffer
+ *
+ * \param ctx       Current GL context
+ * \param texTarget Texture target that will be the source of the blit
+ *
+ * \returns a handle to a shader program on success or zero on failure.
+ */
+static void
+setup_blit_shader(struct gl_context *ctx,
+                  GLenum target,
+                  struct sampler_table *table)
+{
+   const char *vs_source;
+   char *fs_source;
+   GLuint vs, fs;
+   void *const mem_ctx = ralloc_context(NULL);
+   struct glsl_sampler *sampler =
+      setup_texture_sampler(target, table);
+
+   assert(sampler != NULL);
+
+   if (sampler->shader_prog != 0) {
+      _mesa_UseProgram(sampler->shader_prog);
+      return;
+   }
+
+   /* The version check is a little tricky.  API is set to API_OPENGLES2 even
+    * for OpenGL ES 3.0 contexts, and GLSLVersion may be set to 140, for
+    * example, in an OpenGL ES 2.0 context.
+    */
+   if ((ctx->API == API_OPENGLES2 && ctx->Version < 30)
+       || ctx->Const.GLSLVersion < 130) {
+      vs_source =
+         "attribute vec2 position;\n"
+         "attribute vec3 textureCoords;\n"
+         "varying vec4 texCoords;\n"
+         "void main()\n"
+         "{\n"
+         "   texCoords = textureCoords;\n"
+         "   gl_Position = vec4(position, 0.0, 1.0);\n"
+         "}\n";
+
+      fs_source = ralloc_asprintf(mem_ctx,
+                                  "#extension GL_EXT_texture_array : enable\n"
+                                  "#extension GL_ARB_texture_cube_map_array: enable\n"
+                                  "#ifdef GL_ES\n"
+                                  "precision highp float;\n"
+                                  "#endif\n"
+                                  "uniform %s texSampler;\n"
+                                  "varying vec4 texCoords;\n"
+                                  "void main()\n"
+                                  "{\n"
+                                  "   gl_FragColor = %s(texSampler, %s);\n"
+                                  "   gl_FragDepth = gl_FragColor.x;\n"
+                                  "}\n",
+                                  sampler->type,
+                                  sampler->func, sampler->texcoords);
+   }
+   else {
+      vs_source = ralloc_asprintf(mem_ctx,
+                                  "#version %s\n"
+                                  "in vec2 position;\n"
+                                  "in vec4 textureCoords;\n"
+                                  "out vec4 texCoords;\n"
+                                  "void main()\n"
+                                  "{\n"
+                                  "   texCoords = textureCoords;\n"
+                                  "   gl_Position = vec4(position, 0.0, 1.0);\n"
+                                  "}\n",
+                                  _mesa_is_desktop_gl(ctx) ? "130" : "300 es");
+      fs_source = ralloc_asprintf(mem_ctx,
+                                  "#version %s\n"
+                                  "#extension GL_ARB_texture_cube_map_array: enable\n"
+                                  "#ifdef GL_ES\n"
+                                  "precision highp float;\n"
+                                  "#endif\n"
+                                  "uniform %s texSampler;\n"
+                                  "in vec4 texCoords;\n"
+                                  "out vec4 out_color;\n"
+                                  "\n"
+                                  "void main()\n"
+                                  "{\n"
+                                  "   out_color = texture(texSampler, %s);\n"
+                                  "   gl_FragDepth = out_color.x;\n"
+                                  "}\n",
+                                  _mesa_is_desktop_gl(ctx) ? "130" : "300 es",
+                                  sampler->type,
+                                  sampler->texcoords);
+   }
+
+   vs = compile_shader_with_debug(ctx, GL_VERTEX_SHADER, vs_source);
+   fs = compile_shader_with_debug(ctx, GL_FRAGMENT_SHADER, fs_source);
+
+   sampler->shader_prog = _mesa_CreateProgramObjectARB();
+   _mesa_AttachShader(sampler->shader_prog, fs);
+   _mesa_DeleteObjectARB(fs);
+   _mesa_AttachShader(sampler->shader_prog, vs);
+   _mesa_DeleteObjectARB(vs);
+   _mesa_BindAttribLocation(sampler->shader_prog, 0, "position");
+   _mesa_BindAttribLocation(sampler->shader_prog, 1, "texcoords");
+   link_program_with_debug(ctx, sampler->shader_prog);
+   ralloc_free(mem_ctx);
+
+   _mesa_UseProgram(sampler->shader_prog);
+}
+
+/**
+ * Configure vertex buffer and vertex array objects for tests
+ *
+ * Regardless of whether a new VAO and new VBO are created, the objects
+ * referenced by \c VAO and \c VBO will be bound into the GL state vector
+ * when this function terminates.
+ *
+ * \param VAO       Storage for vertex array object handle.  If 0, a new VAO
+ *                  will be created.
+ * \param VBO       Storage for vertex buffer object handle.  If 0, a new VBO
+ *                  will be created.  The new VBO will have storage for 4
+ *                  \c vertex structures.
+ * \param use_generic_attributes  Should generic attributes 0 and 1 be used,
+ *                  or should traditional, fixed-function color and texture
+ *                  coordinate be used?
+ * \param vertex_size  Number of components for attribute 0 / vertex.
+ * \param texcoord_size  Number of components for attribute 1 / texture
+ *                  coordinate.  If this is 0, attribute 1 will not be set or
+ *                  enabled.
+ * \param color_size  Number of components for attribute 1 / primary color.
+ *                  If this is 0, attribute 1 will not be set or enabled.
+ *
+ * \note If \c use_generic_attributes is \c true, \c color_size must be zero.
+ * Use \c texcoord_size instead.
+ */
+static void
+setup_vertex_objects(GLuint *VAO, GLuint *VBO, bool use_generic_attributes,
+                     unsigned vertex_size, unsigned texcoord_size,
+                     unsigned color_size)
+{
+   if (*VAO == 0) {
+      assert(*VBO == 0);
+
+      /* create vertex array object */
+      _mesa_GenVertexArrays(1, VAO);
+      _mesa_BindVertexArray(*VAO);
+
+      /* create vertex array buffer */
+      _mesa_GenBuffers(1, VBO);
+      _mesa_BindBuffer(GL_ARRAY_BUFFER, *VBO);
+      _mesa_BufferData(GL_ARRAY_BUFFER, 4 * sizeof(struct vertex), NULL,
+                       GL_DYNAMIC_DRAW);
+
+      /* setup vertex arrays */
+      if (use_generic_attributes) {
+         assert(color_size == 0);
+
+         _mesa_VertexAttribPointer(0, vertex_size, GL_FLOAT, GL_FALSE,
+                                   sizeof(struct vertex), OFFSET(x));
+         _mesa_EnableVertexAttribArray(0);
+
+         if (texcoord_size > 0) {
+            _mesa_VertexAttribPointer(1, texcoord_size, GL_FLOAT, GL_FALSE,
+                                      sizeof(struct vertex), OFFSET(tex));
+            _mesa_EnableVertexAttribArray(1);
+         }
+      } else {
+         _mesa_VertexPointer(vertex_size, GL_FLOAT, sizeof(struct vertex),
+                             OFFSET(x));
+         _mesa_EnableClientState(GL_VERTEX_ARRAY);
+
+         if (texcoord_size > 0) {
+            _mesa_TexCoordPointer(texcoord_size, GL_FLOAT,
+                                  sizeof(struct vertex), OFFSET(tex));
+            _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
+         }
+
+         if (color_size > 0) {
+            _mesa_ColorPointer(color_size, GL_FLOAT,
+                               sizeof(struct vertex), OFFSET(r));
+            _mesa_EnableClientState(GL_COLOR_ARRAY);
+         }
+      }
+   } else {
+      _mesa_BindVertexArray(*VAO);
+      _mesa_BindBuffer(GL_ARRAY_BUFFER, *VBO);
+   }
+}
+
 /**
  * Initialize meta-ops for a context.
  * To be called once during context creation.
@@ -437,10 +651,12 @@ _mesa_meta_free(struct gl_context *ctx)
 {
    GET_CURRENT_CONTEXT(old_context);
    _mesa_make_current(ctx, NULL, NULL);
-   meta_glsl_blit_cleanup(ctx, &ctx->Meta->Blit);
-   meta_glsl_clear_cleanup(ctx, &ctx->Meta->Clear);
-   meta_glsl_generate_mipmap_cleanup(ctx, &ctx->Meta->Mipmap);
-   cleanup_temp_texture(ctx, &ctx->Meta->TempTex);
+   meta_glsl_blit_cleanup(&ctx->Meta->Blit);
+   meta_glsl_clear_cleanup(&ctx->Meta->Clear);
+   meta_glsl_generate_mipmap_cleanup(&ctx->Meta->Mipmap);
+   cleanup_temp_texture(&ctx->Meta->TempTex);
+   meta_decompress_cleanup(&ctx->Meta->Decompress);
+   meta_drawpix_cleanup(&ctx->Meta->DrawPix);
    if (old_context)
       _mesa_make_current(old_context, old_context->WinSysDrawBuffer, old_context->WinSysReadBuffer);
    else
@@ -473,11 +689,19 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
     * able to change other state.
     */
    save->TransformFeedbackNeedsResume =
-      ctx->TransformFeedback.CurrentObject->Active &&
-      !ctx->TransformFeedback.CurrentObject->Paused;
+      _mesa_is_xfb_active_and_unpaused(ctx);
    if (save->TransformFeedbackNeedsResume)
       _mesa_PauseTransformFeedback();
 
+   /* After saving the current occlusion object, call EndQuery so that no
+    * occlusion querying will be active during the meta-operation.
+    */
+   if (state & MESA_META_OCCLUSION_QUERY) {
+      save->CurrentOcclusionObject = ctx->Query.CurrentOcclusionObject;
+      if (save->CurrentOcclusionObject)
+         _mesa_EndQuery(save->CurrentOcclusionObject->Target);
+   }
+
    if (state & MESA_META_ALPHA_TEST) {
       save->AlphaEnabled = ctx->Color.AlphaEnabled;
       save->AlphaFunc = ctx->Color.AlphaFunc;
@@ -580,6 +804,8 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
    }
 
    if (state & MESA_META_SHADER) {
+      int i;
+
       if (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.ARB_vertex_program) {
          save->VertexProgramEnabled = ctx->VertexProgram.Enabled;
          _mesa_reference_vertprog(ctx, &save->VertexProgram,
@@ -594,18 +820,19 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
          _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB, GL_FALSE);
       }
 
-      if (ctx->Extensions.ARB_shader_objects) {
-        _mesa_reference_shader_program(ctx, &save->VertexShader,
-                                       ctx->Shader.CurrentVertexProgram);
-        _mesa_reference_shader_program(ctx, &save->GeometryShader,
-                                       ctx->Shader.CurrentGeometryProgram);
-        _mesa_reference_shader_program(ctx, &save->FragmentShader,
-                                       ctx->Shader.CurrentFragmentProgram);
-        _mesa_reference_shader_program(ctx, &save->ActiveShader,
-                                       ctx->Shader.ActiveProgram);
+      if (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.ATI_fragment_shader) {
+         save->ATIFragmentShaderEnabled = ctx->ATIFragmentShader.Enabled;
+         _mesa_set_enable(ctx, GL_FRAGMENT_SHADER_ATI, GL_FALSE);
+      }
 
-         _mesa_UseProgram(0);
+      for (i = 0; i < MESA_SHADER_STAGES; i++) {
+         _mesa_reference_shader_program(ctx, &save->Shader[i],
+                                     ctx->Shader.CurrentProgram[i]);
       }
+      _mesa_reference_shader_program(ctx, &save->ActiveShader,
+                                     ctx->Shader.ActiveProgram);
+
+      _mesa_UseProgram(0);
    }
 
    if (state & MESA_META_STENCIL_TEST) {
@@ -633,7 +860,8 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
                _mesa_set_enable(ctx, GL_TEXTURE_2D, GL_FALSE);
                if (ctx->Extensions.ARB_texture_cube_map)
                   _mesa_set_enable(ctx, GL_TEXTURE_CUBE_MAP, GL_FALSE);
-               if (ctx->Extensions.OES_EGL_image_external)
+               if (_mesa_is_gles(ctx) &&
+                   ctx->Extensions.OES_EGL_image_external)
                   _mesa_set_enable(ctx, GL_TEXTURE_EXTERNAL_OES, GL_FALSE);
 
                if (ctx->API == API_OPENGL_COMPAT) {
@@ -684,9 +912,14 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
       _mesa_LoadIdentity();
       _mesa_MatrixMode(GL_PROJECTION);
       _mesa_LoadIdentity();
-      _mesa_Ortho(0.0, ctx->DrawBuffer->Width,
-                  0.0, ctx->DrawBuffer->Height,
-                  -1.0, 1.0);
+
+      /* glOrtho with width = 0 or height = 0 generates GL_INVALID_VALUE.
+       * This can occur when there is no draw buffer.
+       */
+      if (ctx->DrawBuffer->Width != 0 && ctx->DrawBuffer->Height != 0)
+         _mesa_Ortho(0.0, ctx->DrawBuffer->Width,
+                     0.0, ctx->DrawBuffer->Height,
+                     -1.0, 1.0);
    }
 
    if (state & MESA_META_CLIP) {
@@ -701,8 +934,8 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
 
    if (state & MESA_META_VERTEX) {
       /* save vertex array object state */
-      _mesa_reference_array_object(ctx, &save->ArrayObj,
-                                   ctx->Array.ArrayObj);
+      _mesa_reference_vao(ctx, &save->VAO,
+                                   ctx->Array.VAO);
       _mesa_reference_buffer_object(ctx, &save->ArrayBufferObj,
                                     ctx->Array.ArrayBufferObj);
       /* set some default state? */
@@ -710,21 +943,21 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
 
    if (state & MESA_META_VIEWPORT) {
       /* save viewport state */
-      save->ViewportX = ctx->Viewport.X;
-      save->ViewportY = ctx->Viewport.Y;
-      save->ViewportW = ctx->Viewport.Width;
-      save->ViewportH = ctx->Viewport.Height;
+      save->ViewportX = ctx->ViewportArray[0].X;
+      save->ViewportY = ctx->ViewportArray[0].Y;
+      save->ViewportW = ctx->ViewportArray[0].Width;
+      save->ViewportH = ctx->ViewportArray[0].Height;
       /* set viewport to match window size */
-      if (ctx->Viewport.X != 0 ||
-          ctx->Viewport.Y != 0 ||
-          ctx->Viewport.Width != ctx->DrawBuffer->Width ||
-          ctx->Viewport.Height != ctx->DrawBuffer->Height) {
-         _mesa_set_viewport(ctx, 0, 0,
+      if (ctx->ViewportArray[0].X != 0 ||
+          ctx->ViewportArray[0].Y != 0 ||
+          ctx->ViewportArray[0].Width != (float) ctx->DrawBuffer->Width ||
+          ctx->ViewportArray[0].Height != (float) ctx->DrawBuffer->Height) {
+         _mesa_set_viewport(ctx, 0, 0, 0,
                             ctx->DrawBuffer->Width, ctx->DrawBuffer->Height);
       }
       /* save depth range state */
-      save->DepthNear = ctx->Viewport.Near;
-      save->DepthFar = ctx->Viewport.Far;
+      save->DepthNear = ctx->ViewportArray[0].Near;
+      save->DepthFar = ctx->ViewportArray[0].Far;
       /* set depth range to default */
       _mesa_DepthRange(0.0, 1.0);
    }
@@ -736,7 +969,8 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
        * it's for the pixel path (ClampFragmentColor is GL_TRUE),
        * regardless of the internal implementation of the metaops.
        */
-      if (ctx->Color.ClampFragmentColor != GL_TRUE)
+      if (ctx->Color.ClampFragmentColor != GL_TRUE &&
+          ctx->Extensions.ARB_color_buffer_float)
         _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
    }
 
@@ -746,7 +980,8 @@ _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
       /* Generally in here we never want vertex color clamping --
        * result clamping is only dependent on fragment clamping.
        */
-      _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
+      if (ctx->Extensions.ARB_color_buffer_float)
+         _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
    }
 
    if (state & MESA_META_CONDITIONAL_RENDER) {
@@ -800,6 +1035,19 @@ _mesa_meta_end(struct gl_context *ctx)
 {
    struct save_state *save = &ctx->Meta->Save[ctx->Meta->SaveStackDepth - 1];
    const GLbitfield state = save->SavedState;
+   int i;
+
+   /* After starting a new occlusion query, initialize the results to the
+    * values saved previously. The driver will then continue to increment
+    * these values.
+    */
+   if (state & MESA_META_OCCLUSION_QUERY) {
+      if (save->CurrentOcclusionObject) {
+         _mesa_BeginQuery(save->CurrentOcclusionObject->Target,
+                          save->CurrentOcclusionObject->Id);
+         ctx->Query.CurrentOcclusionObject->Result = save->CurrentOcclusionObject->Result;
+      }
+   }
 
    if (state & MESA_META_ALPHA_TEST) {
       if (ctx->Color.AlphaEnabled != save->AlphaEnabled)
@@ -892,9 +1140,17 @@ _mesa_meta_end(struct gl_context *ctx)
    }
 
    if (state & MESA_META_SCISSOR) {
-      _mesa_set_enable(ctx, GL_SCISSOR_TEST, save->Scissor.Enabled);
-      _mesa_Scissor(save->Scissor.X, save->Scissor.Y,
-                    save->Scissor.Width, save->Scissor.Height);
+      unsigned i;
+
+      for (i = 0; i < ctx->Const.MaxViewports; i++) {
+         _mesa_set_scissor(ctx, i,
+                           save->Scissor.ScissorArray[i].X,
+                           save->Scissor.ScissorArray[i].Y,
+                           save->Scissor.ScissorArray[i].Width,
+                           save->Scissor.ScissorArray[i].Height);
+         _mesa_set_enablei(ctx, GL_SCISSOR_TEST, i,
+                           (save->Scissor.EnableFlags >> i) & 1);
+      }
    }
 
    if (state & MESA_META_SHADER) {
@@ -914,23 +1170,29 @@ _mesa_meta_end(struct gl_context *ctx)
         _mesa_reference_fragprog(ctx, &save->FragmentProgram, NULL);
       }
 
-      if (ctx->Extensions.ARB_vertex_shader)
-        _mesa_use_shader_program(ctx, GL_VERTEX_SHADER, save->VertexShader);
+      if (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.ATI_fragment_shader) {
+         _mesa_set_enable(ctx, GL_FRAGMENT_SHADER_ATI,
+                          save->ATIFragmentShaderEnabled);
+      }
+
+      if (ctx->Extensions.ARB_vertex_shader) {
+        _mesa_use_shader_program(ctx, GL_VERTEX_SHADER,
+                                  save->Shader[MESA_SHADER_VERTEX]);
+      }
 
-      if (ctx->Extensions.ARB_geometry_shader4)
+      if (_mesa_has_geometry_shaders(ctx))
         _mesa_use_shader_program(ctx, GL_GEOMETRY_SHADER_ARB,
-                                 save->GeometryShader);
+                                 save->Shader[MESA_SHADER_GEOMETRY]);
 
       if (ctx->Extensions.ARB_fragment_shader)
         _mesa_use_shader_program(ctx, GL_FRAGMENT_SHADER,
-                                 save->FragmentShader);
+                                 save->Shader[MESA_SHADER_FRAGMENT]);
 
       _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram,
                                     save->ActiveShader);
 
-      _mesa_reference_shader_program(ctx, &save->VertexShader, NULL);
-      _mesa_reference_shader_program(ctx, &save->GeometryShader, NULL);
-      _mesa_reference_shader_program(ctx, &save->FragmentShader, NULL);
+      for (i = 0; i < MESA_SHADER_STAGES; i++)
+         _mesa_reference_shader_program(ctx, &save->Shader[i], NULL);
       _mesa_reference_shader_program(ctx, &save->ActiveShader, NULL);
    }
 
@@ -1038,26 +1300,28 @@ _mesa_meta_end(struct gl_context *ctx)
       _mesa_reference_buffer_object(ctx, &save->ArrayBufferObj, NULL);
 
       /* restore vertex array object */
-      _mesa_BindVertexArray(save->ArrayObj->Name);
-      _mesa_reference_array_object(ctx, &save->ArrayObj, NULL);
+      _mesa_BindVertexArray(save->VAO->Name);
+      _mesa_reference_vao(ctx, &save->VAO, NULL);
    }
 
    if (state & MESA_META_VIEWPORT) {
-      if (save->ViewportX != ctx->Viewport.X ||
-          save->ViewportY != ctx->Viewport.Y ||
-          save->ViewportW != ctx->Viewport.Width ||
-          save->ViewportH != ctx->Viewport.Height) {
-         _mesa_set_viewport(ctx, save->ViewportX, save->ViewportY,
+      if (save->ViewportX != ctx->ViewportArray[0].X ||
+          save->ViewportY != ctx->ViewportArray[0].Y ||
+          save->ViewportW != ctx->ViewportArray[0].Width ||
+          save->ViewportH != ctx->ViewportArray[0].Height) {
+         _mesa_set_viewport(ctx, 0, save->ViewportX, save->ViewportY,
                             save->ViewportW, save->ViewportH);
       }
       _mesa_DepthRange(save->DepthNear, save->DepthFar);
    }
 
-   if (state & MESA_META_CLAMP_FRAGMENT_COLOR) {
+   if (state & MESA_META_CLAMP_FRAGMENT_COLOR &&
+       ctx->Extensions.ARB_color_buffer_float) {
       _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, save->ClampFragmentColor);
    }
 
-   if (state & MESA_META_CLAMP_VERTEX_COLOR) {
+   if (state & MESA_META_CLAMP_VERTEX_COLOR &&
+       ctx->Extensions.ARB_color_buffer_float) {
       _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR, save->ClampVertexColor);
    }
 
@@ -1134,7 +1398,7 @@ static void
 init_temp_texture(struct gl_context *ctx, struct temp_texture *tex)
 {
    /* prefer texture rectangle */
-   if (ctx->Extensions.NV_texture_rectangle) {
+   if (_mesa_is_desktop_gl(ctx) && ctx->Extensions.NV_texture_rectangle) {
       tex->Target = GL_TEXTURE_RECTANGLE;
       tex->MaxSize = ctx->Const.MaxTextureRectSize;
       tex->NPOT = GL_TRUE;
@@ -1152,7 +1416,7 @@ init_temp_texture(struct gl_context *ctx, struct temp_texture *tex)
 }
 
 static void
-cleanup_temp_texture(struct gl_context *ctx, struct temp_texture *tex)
+cleanup_temp_texture(struct temp_texture *tex)
 {
    if (!tex->TexObj)
      return;
@@ -1195,6 +1459,21 @@ get_bitmap_temp_texture(struct gl_context *ctx)
    return tex;
 }
 
+/**
+ * Return pointer to depth temp_texture.
+ * This does some one-time init if needed.
+ */
+static struct temp_texture *
+get_temp_depth_texture(struct gl_context *ctx)
+{
+   struct temp_texture *tex = &ctx->Meta->Blit.depthTex;
+
+   if (!tex->TexObj) {
+      init_temp_texture(ctx, tex);
+   }
+
+   return tex;
+}
 
 /**
  * Compute the width/height of texture needed to draw an image of the
@@ -1259,7 +1538,8 @@ alloc_texture(struct temp_texture *tex,
  * Setup/load texture for glCopyPixels or glBlitFramebuffer.
  */
 static void
-setup_copypix_texture(struct temp_texture *tex,
+setup_copypix_texture(struct gl_context *ctx,
+                      struct temp_texture *tex,
                       GLboolean newTex,
                       GLint srcX, GLint srcY,
                       GLsizei width, GLsizei height, GLenum intFormat,
@@ -1268,7 +1548,8 @@ setup_copypix_texture(struct temp_texture *tex,
    _mesa_BindTexture(tex->Target, tex->TexObj);
    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MIN_FILTER, filter);
    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MAG_FILTER, filter);
-   _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+   if (ctx->API == API_OPENGL_COMPAT || ctx->API == API_OPENGLES)
+      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
 
    /* copy framebuffer image to texture */
    if (newTex) {
@@ -1303,7 +1584,6 @@ static void
 setup_drawpix_texture(struct gl_context *ctx,
                      struct temp_texture *tex,
                       GLboolean newTex,
-                      GLenum texIntFormat,
                       GLsizei width, GLsizei height,
                       GLenum format, GLenum type,
                       const GLvoid *pixels)
@@ -1311,7 +1591,8 @@ setup_drawpix_texture(struct gl_context *ctx,
    _mesa_BindTexture(tex->Target, tex->TexObj);
    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-   _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+   if (ctx->API == API_OPENGL_COMPAT || ctx->API == API_OPENGLES)
+      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
 
    /* copy pixel data to texture */
    if (newTex) {
@@ -1378,6 +1659,28 @@ init_blit_depth_pixels(struct gl_context *ctx)
                           strlen(program2), (const GLubyte *) program2);
 }
 
+static void
+setup_ff_tnl_for_blit(GLuint *VAO, GLuint *VBO, unsigned texcoord_size)
+{
+   setup_vertex_objects(VAO, VBO, false, 2, texcoord_size, 0);
+
+   /* setup projection matrix */
+   _mesa_MatrixMode(GL_PROJECTION);
+   _mesa_LoadIdentity();
+}
+
+static void
+setup_glsl_blit_framebuffer(struct gl_context *ctx,
+                            struct blit_state *blit,
+                            GLenum target)
+{
+   /* target = GL_TEXTURE_RECTANGLE is not supported in GLES 3.0 */
+   assert(_mesa_is_desktop_gl(ctx) || target == GL_TEXTURE_2D);
+
+   setup_vertex_objects(&blit->VAO, &blit->VBO, true, 2, 2, 0);
+
+   setup_blit_shader(ctx, target, &blit->samplers);
+}
 
 /**
  * Try to do a glBlitFramebuffer using no-copy texturing.
@@ -1391,17 +1694,22 @@ static GLbitfield
 blitframebuffer_texture(struct gl_context *ctx,
                         GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
                         GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
-                        GLbitfield mask, GLenum filter)
+                        GLbitfield mask, GLenum filter, GLint flipX,
+                        GLint flipY, GLboolean glsl_version)
 {
    if (mask & GL_COLOR_BUFFER_BIT) {
       const struct gl_framebuffer *drawFb = ctx->DrawBuffer;
       const struct gl_framebuffer *readFb = ctx->ReadBuffer;
-      const struct gl_renderbuffer_attachment *drawAtt =
-         &drawFb->Attachment[drawFb->_ColorDrawBufferIndexes[0]];
+      const struct gl_renderbuffer_attachment *drawAtt;
       const struct gl_renderbuffer_attachment *readAtt =
          &readFb->Attachment[readFb->_ColorReadBufferIndex];
 
       if (readAtt && readAtt->Texture) {
+         struct blit_state *blit = &ctx->Meta->Blit;
+         const GLint dstX = MIN2(dstX0, dstX1);
+         const GLint dstY = MIN2(dstY0, dstY1);
+         const GLint dstW = abs(dstX1 - dstX0);
+         const GLint dstH = abs(dstY1 - dstY0);
          const struct gl_texture_object *texObj = readAtt->Texture;
          const GLuint srcLevel = readAtt->TextureLevel;
          const GLint baseLevelSave = texObj->BaseLevel;
@@ -1410,13 +1718,22 @@ blitframebuffer_texture(struct gl_context *ctx,
          GLuint sampler, samplerSave =
             ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler ?
             ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler->Name : 0;
-
-         if (drawAtt->Texture == readAtt->Texture) {
-            /* Can't use same texture as both the source and dest.  We need
-             * to handle overlapping blits and besides, some hw may not
-             * support this.
-             */
-            return mask;
+         int i;
+
+         /* Iterate through all draw buffers */
+         for (i = 0; i < ctx->DrawBuffer->_NumColorDrawBuffers; i++) {
+            int idx = ctx->DrawBuffer->_ColorDrawBufferIndexes[i];
+            if (idx == -1)
+               continue;
+            drawAtt = &drawFb->Attachment[idx];
+
+            if (drawAtt->Texture == readAtt->Texture) {
+               /* Can't use same texture as both the source and dest.  We need
+                * to handle overlapping blits and besides, some hw may not
+                * support this.
+                */
+               return mask;
+            }
          }
 
          if (target != GL_TEXTURE_2D && target != GL_TEXTURE_RECTANGLE_ARB) {
@@ -1424,6 +1741,18 @@ blitframebuffer_texture(struct gl_context *ctx,
             return mask;
          }
 
+         /* Choose between glsl version and fixed function version of
+          * BlitFramebuffer function.
+          */
+         if (glsl_version) {
+            setup_glsl_blit_framebuffer(ctx, blit, target);
+         }
+         else {
+            setup_ff_tnl_for_blit(&ctx->Meta->Blit.VAO,
+                                  &ctx->Meta->Blit.VBO,
+                                  2);
+         }
+
          _mesa_GenSamplers(1, &sampler);
          _mesa_BindSampler(ctx->Texture.CurrentUnit, sampler);
 
@@ -1453,14 +1782,13 @@ blitframebuffer_texture(struct gl_context *ctx,
                                GL_SKIP_DECODE_EXT);
         }
 
-         _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-         _mesa_set_enable(ctx, target, GL_TRUE);
+         if (ctx->API == API_OPENGL_COMPAT || ctx->API == API_OPENGLES) {
+            _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+            _mesa_set_enable(ctx, target, GL_TRUE);
+        }
 
          /* Prepare vertex data (the VBO was previously created and bound) */
          {
-            struct vertex {
-               GLfloat x, y, s, t;
-            };
             struct vertex verts[4];
             GLfloat s0, t0, s1, t1;
 
@@ -1474,33 +1802,41 @@ blitframebuffer_texture(struct gl_context *ctx,
             }
             else {
                assert(target == GL_TEXTURE_RECTANGLE_ARB);
-               s0 = srcX0;
-               s1 = srcX1;
-               t0 = srcY0;
-               t1 = srcY1;
+               s0 = (float) srcX0;
+               s1 = (float) srcX1;
+               t0 = (float) srcY0;
+               t1 = (float) srcY1;
             }
 
-            verts[0].x = (GLfloat) dstX0;
-            verts[0].y = (GLfloat) dstY0;
-            verts[1].x = (GLfloat) dstX1;
-            verts[1].y = (GLfloat) dstY0;
-            verts[2].x = (GLfloat) dstX1;
-            verts[2].y = (GLfloat) dstY1;
-            verts[3].x = (GLfloat) dstX0;
-            verts[3].y = (GLfloat) dstY1;
-
-            verts[0].s = s0;
-            verts[0].t = t0;
-            verts[1].s = s1;
-            verts[1].t = t0;
-            verts[2].s = s1;
-            verts[2].t = t1;
-            verts[3].s = s0;
-            verts[3].t = t1;
+            /* Silence valgrind warnings about reading uninitialized stack. */
+            memset(verts, 0, sizeof(verts));
+
+            /* setup vertex positions */
+            verts[0].x = -1.0F * flipX;
+            verts[0].y = -1.0F * flipY;
+            verts[1].x =  1.0F * flipX;
+            verts[1].y = -1.0F * flipY;
+            verts[2].x =  1.0F * flipX;
+            verts[2].y =  1.0F * flipY;
+            verts[3].x = -1.0F * flipX;
+            verts[3].y =  1.0F * flipY;
+
+            verts[0].tex[0] = s0;
+            verts[0].tex[1] = t0;
+            verts[1].tex[0] = s1;
+            verts[1].tex[1] = t0;
+            verts[2].tex[0] = s1;
+            verts[2].tex[1] = t1;
+            verts[3].tex[0] = s0;
+            verts[3].tex[1] = t1;
 
             _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
          }
 
+         /* setup viewport */
+         _mesa_set_viewport(ctx, 0, dstX, dstY, dstW, dstH);
+         _mesa_ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+         _mesa_DepthMask(GL_FALSE);
          _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
 
          /* Restore texture object state, the texture binding will
@@ -1535,18 +1871,28 @@ _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
 {
    struct blit_state *blit = &ctx->Meta->Blit;
    struct temp_texture *tex = get_temp_texture(ctx);
+   struct temp_texture *depthTex = get_temp_depth_texture(ctx);
    const GLsizei maxTexSize = tex->MaxSize;
    const GLint srcX = MIN2(srcX0, srcX1);
    const GLint srcY = MIN2(srcY0, srcY1);
    const GLint srcW = abs(srcX1 - srcX0);
    const GLint srcH = abs(srcY1 - srcY0);
-   const GLboolean srcFlipX = srcX1 < srcX0;
-   const GLboolean srcFlipY = srcY1 < srcY0;
-   struct vertex {
-      GLfloat x, y, s, t;
-   };
+   const GLint dstX = MIN2(dstX0, dstX1);
+   const GLint dstY = MIN2(dstY0, dstY1);
+   const GLint dstW = abs(dstX1 - dstX0);
+   const GLint dstH = abs(dstY1 - dstY0);
+   const GLint srcFlipX = (srcX1 - srcX0) / srcW;
+   const GLint srcFlipY = (srcY1 - srcY0) / srcH;
+   const GLint dstFlipX = (dstX1 - dstX0) / dstW;
+   const GLint dstFlipY = (dstY1 - dstY0) / dstH;
+   const GLint flipX = srcFlipX * dstFlipX;
+   const GLint flipY = srcFlipY * dstFlipY;
+
    struct vertex verts[4];
    GLboolean newTex;
+   const GLboolean use_glsl_version = ctx->Extensions.ARB_vertex_shader &&
+                                      ctx->Extensions.ARB_fragment_shader &&
+                                      (ctx->API != API_OPENGLES);
 
    /* In addition to falling back if the blit size is larger than the maximum
     * texture size, fallback if the source is multisampled.  This fallback can
@@ -1560,106 +1906,123 @@ _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
       return;
    }
 
-   if (srcFlipX) {
-      GLint tmp = dstX0;
-      dstX0 = dstX1;
-      dstX1 = tmp;
-   }
-
-   if (srcFlipY) {
-      GLint tmp = dstY0;
-      dstY0 = dstY1;
-      dstY1 = tmp;
-   }
-
    /* only scissor effects blit so save/clear all other relevant state */
    _mesa_meta_begin(ctx, ~MESA_META_SCISSOR);
 
-   if (blit->ArrayObj == 0) {
-      /* one-time setup */
-
-      /* create vertex array object */
-      _mesa_GenVertexArrays(1, &blit->ArrayObj);
-      _mesa_BindVertexArray(blit->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &blit->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, blit->VBO);
-      _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts),
-                          NULL, GL_DYNAMIC_DRAW_ARB);
-
-      /* setup vertex arrays */
-      _mesa_VertexPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_TexCoordPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(s));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-   }
-   else {
-      _mesa_BindVertexArray(blit->ArrayObj);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, blit->VBO);
-   }
-
    /* Try faster, direct texture approach first */
    mask = blitframebuffer_texture(ctx, srcX0, srcY0, srcX1, srcY1,
-                                  dstX0, dstY0, dstX1, dstY1, mask, filter);
+                                  dstX0, dstY0, dstX1, dstY1, mask, filter,
+                                  dstFlipX, dstFlipY, use_glsl_version);
    if (mask == 0x0) {
       _mesa_meta_end(ctx);
       return;
    }
 
-   /* Continue with "normal" approach which involves copying the src rect
-    * into a temporary texture and is "blitted" by drawing a textured quad.
+   /* Choose between glsl version and fixed function version of
+    * BlitFramebuffer function.
     */
+   if (use_glsl_version) {
+      setup_glsl_blit_framebuffer(ctx, blit, tex->Target);
+   }
+   else {
+      setup_ff_tnl_for_blit(&blit->VAO, &blit->VBO, 2);
+   }
 
-   newTex = alloc_texture(tex, srcW, srcH, GL_RGBA);
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
 
-   /* vertex positions/texcoords (after texture allocation!) */
+   /* Continue with "normal" approach which involves copying the src rect
+    * into a temporary texture and is "blitted" by drawing a textured quad.
+    */
    {
-      verts[0].x = (GLfloat) dstX0;
-      verts[0].y = (GLfloat) dstY0;
-      verts[1].x = (GLfloat) dstX1;
-      verts[1].y = (GLfloat) dstY0;
-      verts[2].x = (GLfloat) dstX1;
-      verts[2].y = (GLfloat) dstY1;
-      verts[3].x = (GLfloat) dstX0;
-      verts[3].y = (GLfloat) dstY1;
-
-      verts[0].s = 0.0F;
-      verts[0].t = 0.0F;
-      verts[1].s = tex->Sright;
-      verts[1].t = 0.0F;
-      verts[2].s = tex->Sright;
-      verts[2].t = tex->Ttop;
-      verts[3].s = 0.0F;
-      verts[3].t = tex->Ttop;
+      /* setup vertex positions */
+      verts[0].x = -1.0F * flipX;
+      verts[0].y = -1.0F * flipY;
+      verts[1].x =  1.0F * flipX;
+      verts[1].y = -1.0F * flipY;
+      verts[2].x =  1.0F * flipX;
+      verts[2].y =  1.0F * flipY;
+      verts[3].x = -1.0F * flipX;
+      verts[3].y =  1.0F * flipY;
 
-      /* upload new vertex data */
-      _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
    }
 
-   _mesa_set_enable(ctx, tex->Target, GL_TRUE);
+   /* glEnable() in gles2 and gles3 doesn't allow GL_TEXTURE_{1D, 2D, etc.}
+    * tokens.
+    */
+   if (_mesa_is_desktop_gl(ctx) || ctx->API == API_OPENGLES)
+      _mesa_set_enable(ctx, tex->Target, GL_TRUE);
 
    if (mask & GL_COLOR_BUFFER_BIT) {
-      setup_copypix_texture(tex, newTex, srcX, srcY, srcW, srcH,
-                            GL_RGBA, filter);
+      const struct gl_framebuffer *readFb = ctx->ReadBuffer;
+      const struct gl_renderbuffer *colorReadRb = readFb->_ColorReadBuffer;
+      const GLenum rb_base_format =
+         _mesa_base_tex_format(ctx, colorReadRb->InternalFormat);
+
+      /* Using  the exact source rectangle to create the texture does incorrect
+       * linear filtering along the edges. So, allocate the texture extended along
+       * edges by one pixel in x, y directions.
+       */
+      newTex = alloc_texture(tex, srcW + 2, srcH + 2, rb_base_format);
+      setup_copypix_texture(ctx, tex, newTex,
+                            srcX - 1, srcY - 1, srcW + 2, srcH + 2,
+                            rb_base_format, filter);
+      /* texcoords (after texture allocation!) */
+      {
+         verts[0].tex[0] = 1.0F;
+         verts[0].tex[1] = 1.0F;
+         verts[1].tex[0] = tex->Sright - 1.0F;
+         verts[1].tex[1] = 1.0F;
+         verts[2].tex[0] = tex->Sright - 1.0F;
+         verts[2].tex[1] = tex->Ttop - 1.0F;
+         verts[3].tex[0] = 1.0F;
+         verts[3].tex[1] = tex->Ttop - 1.0F;
+
+         /* upload new vertex data */
+         _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
+      }
+
+      _mesa_set_viewport(ctx, 0, dstX, dstY, dstW, dstH);
+      _mesa_ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+      _mesa_set_enable(ctx, GL_DEPTH_TEST, GL_FALSE);
+      _mesa_DepthMask(GL_FALSE);
       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
       mask &= ~GL_COLOR_BUFFER_BIT;
    }
 
-   if (mask & GL_DEPTH_BUFFER_BIT) {
+   if ((mask & GL_DEPTH_BUFFER_BIT) &&
+       _mesa_is_desktop_gl(ctx) &&
+       ctx->Extensions.ARB_depth_texture &&
+       ctx->Extensions.ARB_fragment_program) {
+
       GLuint *tmp = malloc(srcW * srcH * sizeof(GLuint));
+
       if (tmp) {
-         if (!blit->DepthFP)
-            init_blit_depth_pixels(ctx);
 
-         /* maybe change tex format here */
-         newTex = alloc_texture(tex, srcW, srcH, GL_DEPTH_COMPONENT);
+         newTex = alloc_texture(depthTex, srcW, srcH, GL_DEPTH_COMPONENT);
+         _mesa_ReadPixels(srcX, srcY, srcW, srcH, GL_DEPTH_COMPONENT,
+                          GL_UNSIGNED_INT, tmp);
+         setup_drawpix_texture(ctx, depthTex, newTex,
+                               srcW, srcH, GL_DEPTH_COMPONENT,
+                               GL_UNSIGNED_INT, tmp);
 
-         _mesa_ReadPixels(srcX, srcY, srcW, srcH,
-                          GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, tmp);
+         /* texcoords (after texture allocation!) */
+         {
+            verts[0].tex[0] = 0.0F;
+            verts[0].tex[1] = 0.0F;
+            verts[1].tex[0] = depthTex->Sright;
+            verts[1].tex[1] = 0.0F;
+            verts[2].tex[0] = depthTex->Sright;
+            verts[2].tex[1] = depthTex->Ttop;
+            verts[3].tex[0] = 0.0F;
+            verts[3].tex[1] = depthTex->Ttop;
+
+            /* upload new vertex data */
+            _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
+         }
 
-         setup_drawpix_texture(ctx, tex, newTex, GL_DEPTH_COMPONENT, srcW, srcH,
-                               GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, tmp);
+         if (!blit->DepthFP)
+            init_blit_depth_pixels(ctx);
 
          _mesa_BindProgramARB(GL_FRAGMENT_PROGRAM_ARB, blit->DepthFP);
          _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB, GL_TRUE);
@@ -1668,6 +2031,8 @@ _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
          _mesa_DepthFunc(GL_ALWAYS);
          _mesa_DepthMask(GL_TRUE);
 
+         _mesa_set_viewport(ctx, 0, dstX, dstY, dstW, dstH);
+         _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
          _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
          mask &= ~GL_DEPTH_BUFFER_BIT;
 
@@ -1679,7 +2044,8 @@ _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
       /* XXX can't easily do stencil */
    }
 
-   _mesa_set_enable(ctx, tex->Target, GL_FALSE);
+   if (_mesa_is_desktop_gl(ctx) || ctx->API == API_OPENGLES)
+      _mesa_set_enable(ctx, tex->Target, GL_FALSE);
 
    _mesa_meta_end(ctx);
 
@@ -1690,11 +2056,11 @@ _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
 }
 
 static void
-meta_glsl_blit_cleanup(struct gl_context *ctx, struct blit_state *blit)
+meta_glsl_blit_cleanup(struct blit_state *blit)
 {
-   if (blit->ArrayObj) {
-      _mesa_DeleteVertexArrays(1, &blit->ArrayObj);
-      blit->ArrayObj = 0;
+   if (blit->VAO) {
+      _mesa_DeleteVertexArrays(1, &blit->VAO);
+      blit->VAO = 0;
       _mesa_DeleteBuffers(1, &blit->VBO);
       blit->VBO = 0;
    }
@@ -1702,6 +2068,11 @@ meta_glsl_blit_cleanup(struct gl_context *ctx, struct blit_state *blit)
       _mesa_DeleteProgramsARB(1, &blit->DepthFP);
       blit->DepthFP = 0;
    }
+
+   sampler_table_cleanup(&blit->samplers);
+
+   _mesa_DeleteTextures(1, &blit->depthTex.TexObj);
+   blit->depthTex.TexObj = 0;
 }
 
 
@@ -1712,9 +2083,6 @@ void
 _mesa_meta_Clear(struct gl_context *ctx, GLbitfield buffers)
 {
    struct clear_state *clear = &ctx->Meta->Clear;
-   struct vertex {
-      GLfloat x, y, z, r, g, b, a;
-   };
    struct vertex verts[4];
    /* save all state but scissor, pixel pack/unpack */
    GLbitfield metaSave = (MESA_META_ALL -
@@ -1731,34 +2099,15 @@ _mesa_meta_Clear(struct gl_context *ctx, GLbitfield buffers)
 
    _mesa_meta_begin(ctx, metaSave);
 
-   if (clear->ArrayObj == 0) {
-      /* one-time setup */
-
-      /* create vertex array object */
-      _mesa_GenVertexArrays(1, &clear->ArrayObj);
-      _mesa_BindVertexArray(clear->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &clear->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, clear->VBO);
-
-      /* setup vertex arrays */
-      _mesa_VertexPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_ColorPointer(4, GL_FLOAT, sizeof(struct vertex), OFFSET(r));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_COLOR_ARRAY);
-   }
-   else {
-      _mesa_BindVertexArray(clear->ArrayObj);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, clear->VBO);
-   }
+   setup_vertex_objects(&clear->VAO, &clear->VBO, false, 3, 0, 4);
 
    /* GL_COLOR_BUFFER_BIT */
    if (buffers & BUFFER_BITS_COLOR) {
       /* leave colormask, glDrawBuffer state as-is */
 
       /* Clears never have the color clamped. */
-      _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
+      if (ctx->Extensions.ARB_color_buffer_float)
+         _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
    }
    else {
       ASSERT(metaSave & MESA_META_COLOR_MASK);
@@ -1838,49 +2187,46 @@ meta_glsl_clear_init(struct gl_context *ctx, struct clear_state *clear)
       "{\n"
       "   gl_Position = position;\n"
       "}\n";
-   const char *fs_source =
-      "uniform vec4 color;\n"
-      "void main()\n"
-      "{\n"
-      "   gl_FragColor = color;\n"
-      "}\n";
-   const char *vs_int_source =
-      "#version 130\n"
-      "in vec4 position;\n"
+   const char *gs_source =
+      "#version 150\n"
+      "layout(triangles) in;\n"
+      "layout(triangle_strip, max_vertices = 4) out;\n"
+      "uniform int layer;\n"
       "void main()\n"
       "{\n"
-      "   gl_Position = position;\n"
+      "  for (int i = 0; i < 3; i++) {\n"
+      "    gl_Layer = layer;\n"
+      "    gl_Position = gl_in[i].gl_Position;\n"
+      "    EmitVertex();\n"
+      "  }\n"
       "}\n";
-   const char *fs_int_source =
-      "#version 130\n"
-      "uniform ivec4 color;\n"
-      "out ivec4 out_color;\n"
-      "\n"
+   const char *fs_source =
+      "#ifdef GL_ES\n"
+      "precision highp float;\n"
+      "#endif\n"
+      "uniform vec4 color;\n"
       "void main()\n"
       "{\n"
-      "   out_color = color;\n"
+      "   gl_FragColor = color;\n"
       "}\n";
-   GLuint vs, fs;
+   GLuint vs, gs = 0, fs;
+   bool has_integer_textures;
 
-   if (clear->ArrayObj != 0)
-      return;
-
-   /* create vertex array object */
-   _mesa_GenVertexArrays(1, &clear->ArrayObj);
-   _mesa_BindVertexArray(clear->ArrayObj);
+   setup_vertex_objects(&clear->VAO, &clear->VBO, true, 3, 0, 0);
 
-   /* create vertex array buffer */
-   _mesa_GenBuffers(1, &clear->VBO);
-   _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, clear->VBO);
-
-   /* setup vertex arrays */
-   _mesa_VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
-   _mesa_EnableVertexAttribArray(0);
+   if (clear->ShaderProg != 0)
+      return;
 
    vs = _mesa_CreateShaderObjectARB(GL_VERTEX_SHADER);
    _mesa_ShaderSource(vs, 1, &vs_source, NULL);
    _mesa_CompileShader(vs);
 
+   if (_mesa_has_geometry_shaders(ctx)) {
+      gs = _mesa_CreateShaderObjectARB(GL_GEOMETRY_SHADER);
+      _mesa_ShaderSource(gs, 1, &gs_source, NULL);
+      _mesa_CompileShader(gs);
+   }
+
    fs = _mesa_CreateShaderObjectARB(GL_FRAGMENT_SHADER);
    _mesa_ShaderSource(fs, 1, &fs_source, NULL);
    _mesa_CompileShader(fs);
@@ -1888,6 +2234,8 @@ meta_glsl_clear_init(struct gl_context *ctx, struct clear_state *clear)
    clear->ShaderProg = _mesa_CreateProgramObjectARB();
    _mesa_AttachShader(clear->ShaderProg, fs);
    _mesa_DeleteObjectARB(fs);
+   if (gs != 0)
+      _mesa_AttachShader(clear->ShaderProg, gs);
    _mesa_AttachShader(clear->ShaderProg, vs);
    _mesa_DeleteObjectARB(vs);
    _mesa_BindAttribLocation(clear->ShaderProg, 0, "position");
@@ -1895,14 +2243,49 @@ meta_glsl_clear_init(struct gl_context *ctx, struct clear_state *clear)
 
    clear->ColorLocation = _mesa_GetUniformLocation(clear->ShaderProg,
                                                      "color");
+   if (gs != 0) {
+      clear->LayerLocation = _mesa_GetUniformLocation(clear->ShaderProg,
+                                                     "layer");
+   }
+
+   has_integer_textures = _mesa_is_gles3(ctx) ||
+      (_mesa_is_desktop_gl(ctx) && ctx->Const.GLSLVersion >= 130);
+
+   if (has_integer_textures) {
+      void *shader_source_mem_ctx = ralloc_context(NULL);
+      const char *vs_int_source =
+         ralloc_asprintf(shader_source_mem_ctx,
+                         "#version %s\n"
+                         "in vec4 position;\n"
+                         "void main()\n"
+                         "{\n"
+                         "   gl_Position = position;\n"
+                         "}\n",
+                         _mesa_is_desktop_gl(ctx) ? "130" : "300 es");
+      const char *fs_int_source =
+         ralloc_asprintf(shader_source_mem_ctx,
+                         "#version %s\n"
+                         "#ifdef GL_ES\n"
+                         "precision highp float;\n"
+                         "#endif\n"
+                         "uniform ivec4 color;\n"
+                         "out ivec4 out_color;\n"
+                         "\n"
+                         "void main()\n"
+                         "{\n"
+                         "   out_color = color;\n"
+                         "}\n",
+                         _mesa_is_desktop_gl(ctx) ? "130" : "300 es");
 
-   if (_mesa_is_desktop_gl(ctx) && ctx->Const.GLSLVersion >= 130) {
       vs = compile_shader_with_debug(ctx, GL_VERTEX_SHADER, vs_int_source);
       fs = compile_shader_with_debug(ctx, GL_FRAGMENT_SHADER, fs_int_source);
+      ralloc_free(shader_source_mem_ctx);
 
       clear->IntegerShaderProg = _mesa_CreateProgramObjectARB();
       _mesa_AttachShader(clear->IntegerShaderProg, fs);
       _mesa_DeleteObjectARB(fs);
+      if (gs != 0)
+         _mesa_AttachShader(clear->IntegerShaderProg, gs);
       _mesa_AttachShader(clear->IntegerShaderProg, vs);
       _mesa_DeleteObjectARB(vs);
       _mesa_BindAttribLocation(clear->IntegerShaderProg, 0, "position");
@@ -1916,16 +2299,22 @@ meta_glsl_clear_init(struct gl_context *ctx, struct clear_state *clear)
 
       clear->IntegerColorLocation =
         _mesa_GetUniformLocation(clear->IntegerShaderProg, "color");
+      if (gs != 0) {
+         clear->IntegerLayerLocation =
+            _mesa_GetUniformLocation(clear->IntegerShaderProg, "layer");
+      }
    }
+   if (gs != 0)
+      _mesa_DeleteObjectARB(gs);
 }
 
 static void
-meta_glsl_clear_cleanup(struct gl_context *ctx, struct clear_state *clear)
+meta_glsl_clear_cleanup(struct clear_state *clear)
 {
-   if (clear->ArrayObj == 0)
+   if (clear->VAO == 0)
       return;
-   _mesa_DeleteVertexArrays(1, &clear->ArrayObj);
-   clear->ArrayObj = 0;
+   _mesa_DeleteVertexArrays(1, &clear->VAO);
+   clear->VAO = 0;
    _mesa_DeleteBuffers(1, &clear->VBO);
    clear->VBO = 0;
    _mesa_DeleteObjectARB(clear->ShaderProg);
@@ -1952,9 +2341,7 @@ _mesa_meta_glsl_Clear(struct gl_context *ctx, GLbitfield buffers)
    const float x1 = ((float)fb->_Xmax / fb->Width)  * 2.0f - 1.0f;
    const float y1 = ((float)fb->_Ymax / fb->Height) * 2.0f - 1.0f;
    const float z = -invert_z(ctx->Depth.Clear);
-   struct vertex {
-      GLfloat x, y, z;
-   } verts[4];
+   struct vertex verts[4];
 
    metaSave = (MESA_META_ALPHA_TEST |
               MESA_META_BLEND |
@@ -1966,7 +2353,8 @@ _mesa_meta_glsl_Clear(struct gl_context *ctx, GLbitfield buffers)
               MESA_META_VIEWPORT |
               MESA_META_CLIP |
               MESA_META_CLAMP_FRAGMENT_COLOR |
-               MESA_META_MULTISAMPLE);
+               MESA_META_MULTISAMPLE |
+               MESA_META_OCCLUSION_QUERY);
 
    if (!(buffers & BUFFER_BITS_COLOR)) {
       /* We'll use colormask to disable color writes.  Otherwise,
@@ -1989,15 +2377,13 @@ _mesa_meta_glsl_Clear(struct gl_context *ctx, GLbitfield buffers)
                          ctx->Color.ClearColor.f);
    }
 
-   _mesa_BindVertexArray(clear->ArrayObj);
-   _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, clear->VBO);
-
    /* GL_COLOR_BUFFER_BIT */
    if (buffers & BUFFER_BITS_COLOR) {
       /* leave colormask, glDrawBuffer state as-is */
 
       /* Clears never have the color clamped. */
-      _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
+      if (ctx->Extensions.ARB_color_buffer_float)
+         _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
    }
    else {
       ASSERT(metaSave & MESA_META_COLOR_MASK);
@@ -2045,8 +2431,19 @@ _mesa_meta_glsl_Clear(struct gl_context *ctx, GLbitfield buffers)
    _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts), verts,
                       GL_DYNAMIC_DRAW_ARB);
 
-   /* draw quad */
-   _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
+   /* draw quad(s) */
+   if (fb->MaxNumLayers > 0) {
+      unsigned layer;
+      for (layer = 0; layer < fb->MaxNumLayers; layer++) {
+         if (fb->_IntegerColor)
+            _mesa_Uniform1i(clear->IntegerLayerLocation, layer);
+         else
+            _mesa_Uniform1i(clear->LayerLocation, layer);
+         _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
+      }
+   } else {
+      _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
+   }
 
    _mesa_meta_end(ctx);
 }
@@ -2062,9 +2459,6 @@ _mesa_meta_CopyPixels(struct gl_context *ctx, GLint srcX, GLint srcY,
 {
    struct copypix_state *copypix = &ctx->Meta->CopyPix;
    struct temp_texture *tex = get_temp_texture(ctx);
-   struct vertex {
-      GLfloat x, y, z, s, t;
-   };
    struct vertex verts[4];
    GLboolean newTex;
    GLenum intFormat = GL_RGBA;
@@ -2090,32 +2484,13 @@ _mesa_meta_CopyPixels(struct gl_context *ctx, GLint srcX, GLint srcY,
                           MESA_META_VERTEX |
                           MESA_META_VIEWPORT));
 
-   if (copypix->ArrayObj == 0) {
-      /* one-time setup */
-
-      /* create vertex array object */
-      _mesa_GenVertexArrays(1, &copypix->ArrayObj);
-      _mesa_BindVertexArray(copypix->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &copypix->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, copypix->VBO);
-      _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts),
-                          NULL, GL_DYNAMIC_DRAW_ARB);
-
-      /* setup vertex arrays */
-      _mesa_VertexPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_TexCoordPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(s));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-   }
-   else {
-      _mesa_BindVertexArray(copypix->ArrayObj);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, copypix->VBO);
-   }
+   setup_vertex_objects(&copypix->VAO, &copypix->VBO, false, 3, 2, 0);
 
    newTex = alloc_texture(tex, width, height, intFormat);
 
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
+
    /* vertex positions, texcoords (after texture allocation!) */
    {
       const GLfloat dstX0 = (GLfloat) dstX;
@@ -2127,30 +2502,30 @@ _mesa_meta_CopyPixels(struct gl_context *ctx, GLint srcX, GLint srcY,
       verts[0].x = dstX0;
       verts[0].y = dstY0;
       verts[0].z = z;
-      verts[0].s = 0.0F;
-      verts[0].t = 0.0F;
+      verts[0].tex[0] = 0.0F;
+      verts[0].tex[1] = 0.0F;
       verts[1].x = dstX1;
       verts[1].y = dstY0;
       verts[1].z = z;
-      verts[1].s = tex->Sright;
-      verts[1].t = 0.0F;
+      verts[1].tex[0] = tex->Sright;
+      verts[1].tex[1] = 0.0F;
       verts[2].x = dstX1;
       verts[2].y = dstY1;
       verts[2].z = z;
-      verts[2].s = tex->Sright;
-      verts[2].t = tex->Ttop;
+      verts[2].tex[0] = tex->Sright;
+      verts[2].tex[1] = tex->Ttop;
       verts[3].x = dstX0;
       verts[3].y = dstY1;
       verts[3].z = z;
-      verts[3].s = 0.0F;
-      verts[3].t = tex->Ttop;
+      verts[3].tex[0] = 0.0F;
+      verts[3].tex[1] = tex->Ttop;
 
       /* upload new vertex data */
       _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
    }
 
    /* Alloc/setup texture */
-   setup_copypix_texture(tex, newTex, srcX, srcY, width, height,
+   setup_copypix_texture(ctx, tex, newTex, srcX, srcY, width, height,
                          GL_RGBA, GL_NEAREST);
 
    _mesa_set_enable(ctx, tex->Target, GL_TRUE);
@@ -2163,7 +2538,27 @@ _mesa_meta_CopyPixels(struct gl_context *ctx, GLint srcX, GLint srcY,
    _mesa_meta_end(ctx);
 }
 
+static void
+meta_drawpix_cleanup(struct drawpix_state *drawpix)
+{
+   if (drawpix->VAO != 0) {
+      _mesa_DeleteVertexArrays(1, &drawpix->VAO);
+      drawpix->VAO = 0;
 
+      _mesa_DeleteBuffers(1, &drawpix->VBO);
+      drawpix->VBO = 0;
+   }
+
+   if (drawpix->StencilFP != 0) {
+      _mesa_DeleteProgramsARB(1, &drawpix->StencilFP);
+      drawpix->StencilFP = 0;
+   }
+
+   if (drawpix->DepthFP != 0) {
+      _mesa_DeleteProgramsARB(1, &drawpix->DepthFP);
+      drawpix->DepthFP = 0;
+   }
+}
 
 /**
  * When the glDrawPixels() image size is greater than the max rectangle
@@ -2316,14 +2711,10 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
    struct temp_texture *tex = get_temp_texture(ctx);
    const struct gl_pixelstore_attrib unpackSave = ctx->Unpack;
    const GLuint origStencilMask = ctx->Stencil.WriteMask[0];
-   struct vertex {
-      GLfloat x, y, z, s, t;
-   };
    struct vertex verts[4];
    GLenum texIntFormat;
    GLboolean fallback, newTex;
    GLbitfield metaExtraSave = 0x0;
-   GLuint vbo;
 
    /*
     * Determine if we can do the glDrawPixels with texture mapping.
@@ -2415,6 +2806,11 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
 
    newTex = alloc_texture(tex, width, height, texIntFormat);
 
+   setup_vertex_objects(&drawpix->VAO, &drawpix->VBO, false, 3, 2, 0);
+
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
+
    /* vertex positions, texcoords (after texture allocation!) */
    {
       const GLfloat x0 = (GLfloat) x;
@@ -2426,43 +2822,29 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
       verts[0].x = x0;
       verts[0].y = y0;
       verts[0].z = z;
-      verts[0].s = 0.0F;
-      verts[0].t = 0.0F;
+      verts[0].tex[0] = 0.0F;
+      verts[0].tex[1] = 0.0F;
       verts[1].x = x1;
       verts[1].y = y0;
       verts[1].z = z;
-      verts[1].s = tex->Sright;
-      verts[1].t = 0.0F;
+      verts[1].tex[0] = tex->Sright;
+      verts[1].tex[1] = 0.0F;
       verts[2].x = x1;
       verts[2].y = y1;
       verts[2].z = z;
-      verts[2].s = tex->Sright;
-      verts[2].t = tex->Ttop;
+      verts[2].tex[0] = tex->Sright;
+      verts[2].tex[1] = tex->Ttop;
       verts[3].x = x0;
       verts[3].y = y1;
       verts[3].z = z;
-      verts[3].s = 0.0F;
-      verts[3].t = tex->Ttop;
-   }
-
-   if (drawpix->ArrayObj == 0) {
-      /* one-time setup: create vertex array object */
-      _mesa_GenVertexArrays(1, &drawpix->ArrayObj);
+      verts[3].tex[0] = 0.0F;
+      verts[3].tex[1] = tex->Ttop;
    }
-   _mesa_BindVertexArray(drawpix->ArrayObj);
 
-   /* create vertex array buffer */
-   _mesa_GenBuffers(1, &vbo);
-   _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, vbo);
+   /* upload new vertex data */
    _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts),
                        verts, GL_DYNAMIC_DRAW_ARB);
 
-   /* setup vertex arrays */
-   _mesa_VertexPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-   _mesa_TexCoordPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(s));
-   _mesa_EnableClientState(GL_VERTEX_ARRAY);
-   _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-
    /* set given unpack params */
    ctx->Unpack = *unpack;
 
@@ -2475,7 +2857,7 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
       if (!drawpix->StencilFP)
          init_draw_stencil_pixels(ctx);
 
-      setup_drawpix_texture(ctx, tex, newTex, texIntFormat, width, height,
+      setup_drawpix_texture(ctx, tex, newTex, width, height,
                             GL_ALPHA, type, pixels);
 
       _mesa_ColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
@@ -2500,7 +2882,7 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
             _mesa_StencilMask(mask);
 
             _mesa_ProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0,
-                                             255.0 / mask, 0.5, 0.0, 0.0);
+                                             255.0f / mask, 0.5f, 0.0f, 0.0f);
 
             _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
          }
@@ -2518,22 +2900,20 @@ _mesa_meta_DrawPixels(struct gl_context *ctx,
       _mesa_ProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0,
                                         ctx->Current.RasterColor);
 
-      setup_drawpix_texture(ctx, tex, newTex, texIntFormat, width, height,
+      setup_drawpix_texture(ctx, tex, newTex, width, height,
                             format, type, pixels);
 
       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
    else {
       /* Drawing RGBA */
-      setup_drawpix_texture(ctx, tex, newTex, texIntFormat, width, height,
+      setup_drawpix_texture(ctx, tex, newTex, width, height,
                             format, type, pixels);
       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
 
    _mesa_set_enable(ctx, tex->Target, GL_FALSE);
 
-   _mesa_DeleteBuffers(1, &vbo);
-
    /* restore unpack params */
    ctx->Unpack = unpackSave;
 
@@ -2585,9 +2965,6 @@ _mesa_meta_Bitmap(struct gl_context *ctx,
    const GLenum texIntFormat = GL_ALPHA;
    const struct gl_pixelstore_attrib unpackSave = *unpack;
    GLubyte fg, bg;
-   struct vertex {
-      GLfloat x, y, z, s, t, r, g, b, a;
-   };
    struct vertex verts[4];
    GLboolean newTex;
    GLubyte *bitmap8;
@@ -2621,34 +2998,13 @@ _mesa_meta_Bitmap(struct gl_context *ctx,
                           MESA_META_VERTEX |
                           MESA_META_VIEWPORT));
 
-   if (bitmap->ArrayObj == 0) {
-      /* one-time setup */
-
-      /* create vertex array object */
-      _mesa_GenVertexArraysAPPLE(1, &bitmap->ArrayObj);
-      _mesa_BindVertexArrayAPPLE(bitmap->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &bitmap->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, bitmap->VBO);
-      _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts),
-                          NULL, GL_DYNAMIC_DRAW_ARB);
-
-      /* setup vertex arrays */
-      _mesa_VertexPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_TexCoordPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(s));
-      _mesa_ColorPointer(4, GL_FLOAT, sizeof(struct vertex), OFFSET(r));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-      _mesa_EnableClientState(GL_COLOR_ARRAY);
-   }
-   else {
-      _mesa_BindVertexArray(bitmap->ArrayObj);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, bitmap->VBO);
-   }
+   setup_vertex_objects(&bitmap->VAO, &bitmap->VBO, false, 3, 2, 4);
 
    newTex = alloc_texture(tex, width, height, texIntFormat);
 
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
+
    /* vertex positions, texcoords, colors (after texture allocation!) */
    {
       const GLfloat x0 = (GLfloat) x;
@@ -2661,23 +3017,23 @@ _mesa_meta_Bitmap(struct gl_context *ctx,
       verts[0].x = x0;
       verts[0].y = y0;
       verts[0].z = z;
-      verts[0].s = 0.0F;
-      verts[0].t = 0.0F;
+      verts[0].tex[0] = 0.0F;
+      verts[0].tex[1] = 0.0F;
       verts[1].x = x1;
       verts[1].y = y0;
       verts[1].z = z;
-      verts[1].s = tex->Sright;
-      verts[1].t = 0.0F;
+      verts[1].tex[0] = tex->Sright;
+      verts[1].tex[1] = 0.0F;
       verts[2].x = x1;
       verts[2].y = y1;
       verts[2].z = z;
-      verts[2].s = tex->Sright;
-      verts[2].t = tex->Ttop;
+      verts[2].tex[0] = tex->Sright;
+      verts[2].tex[1] = tex->Ttop;
       verts[3].x = x0;
       verts[3].y = y1;
       verts[3].z = z;
-      verts[3].s = 0.0F;
-      verts[3].t = tex->Ttop;
+      verts[3].tex[0] = 0.0F;
+      verts[3].tex[1] = tex->Ttop;
 
       for (i = 0; i < 4; i++) {
          verts[i].r = ctx->Current.RasterColor[0];
@@ -2711,7 +3067,7 @@ _mesa_meta_Bitmap(struct gl_context *ctx,
       _mesa_set_enable(ctx, GL_ALPHA_TEST, GL_TRUE);
       _mesa_AlphaFunc(GL_NOTEQUAL, UBYTE_TO_FLOAT(bg));
 
-      setup_drawpix_texture(ctx, tex, newTex, texIntFormat, width, height,
+      setup_drawpix_texture(ctx, tex, newTex, width, height,
                             GL_ALPHA, GL_UNSIGNED_BYTE, bitmap8);
 
       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
@@ -2744,16 +3100,27 @@ _mesa_meta_check_generate_mipmap_fallback(struct gl_context *ctx, GLenum target,
    GLenum status;
 
    /* check for fallbacks */
-   if (!ctx->Extensions.EXT_framebuffer_object ||
-       target == GL_TEXTURE_3D ||
+   if (target == GL_TEXTURE_3D ||
        target == GL_TEXTURE_1D_ARRAY ||
        target == GL_TEXTURE_2D_ARRAY) {
+      _mesa_perf_debug(ctx, MESA_DEBUG_SEVERITY_HIGH,
+                       "glGenerateMipmap() to %s target\n",
+                       _mesa_lookup_enum_by_nr(target));
       return GL_TRUE;
    }
 
    srcLevel = texObj->BaseLevel;
    baseImage = _mesa_select_tex_image(ctx, texObj, target, srcLevel);
-   if (!baseImage || _mesa_is_format_compressed(baseImage->TexFormat)) {
+   if (!baseImage) {
+      _mesa_perf_debug(ctx, MESA_DEBUG_SEVERITY_HIGH,
+                       "glGenerateMipmap() couldn't find base teximage\n");
+      return GL_TRUE;
+   }
+
+   if (_mesa_is_format_compressed(baseImage->TexFormat)) {
+      _mesa_perf_debug(ctx, MESA_DEBUG_SEVERITY_HIGH,
+                       "glGenerateMipmap() with %s format\n",
+                       _mesa_get_format_name(baseImage->TexFormat));
       return GL_TRUE;
    }
 
@@ -2763,6 +3130,9 @@ _mesa_meta_check_generate_mipmap_fallback(struct gl_context *ctx, GLenum target,
        * texture sample conversion.  So we won't be able to generate the
        * right colors when rendering.  Need to use a fallback.
        */
+      _mesa_perf_debug(ctx, MESA_DEBUG_SEVERITY_HIGH,
+                       "glGenerateMipmap() of sRGB texture without "
+                       "sRGB decode\n");
       return GL_TRUE;
    }
 
@@ -2799,6 +3169,8 @@ _mesa_meta_check_generate_mipmap_fallback(struct gl_context *ctx, GLenum target,
    _mesa_BindFramebuffer(GL_FRAMEBUFFER_EXT, fboSave);
 
    if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
+      _mesa_perf_debug(ctx, MESA_DEBUG_SEVERITY_HIGH,
+                       "glGenerateMipmap() got incomplete FBO\n");
       return GL_TRUE;
    }
 
@@ -2820,10 +3192,11 @@ setup_texture_coords(GLenum faceTarget,
                      GLint slice,
                      GLint width,
                      GLint height,
-                     GLfloat coords0[3],
-                     GLfloat coords1[3],
-                     GLfloat coords2[3],
-                     GLfloat coords3[3])
+                     GLint depth,
+                     GLfloat coords0[4],
+                     GLfloat coords1[4],
+                     GLfloat coords2[4],
+                     GLfloat coords3[4])
 {
    static const GLfloat st[4][2] = {
       {0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}
@@ -2831,15 +3204,25 @@ setup_texture_coords(GLenum faceTarget,
    GLuint i;
    GLfloat r;
 
+   /* Currently all texture targets want the W component to be 1.0.
+    */
+   coords0[3] = 1.0F;
+   coords1[3] = 1.0F;
+   coords2[3] = 1.0F;
+   coords3[3] = 1.0F;
+
    switch (faceTarget) {
    case GL_TEXTURE_1D:
    case GL_TEXTURE_2D:
    case GL_TEXTURE_3D:
    case GL_TEXTURE_2D_ARRAY:
-      if (faceTarget == GL_TEXTURE_3D)
-         r = 1.0F / slice;
+      if (faceTarget == GL_TEXTURE_3D) {
+         assert(slice < depth);
+         assert(depth >= 1);
+         r = (slice + 0.5f) / depth;
+      }
       else if (faceTarget == GL_TEXTURE_2D_ARRAY)
-         r = slice;
+         r = (float) slice;
       else
          r = 0.0F;
       coords0[0] = 0.0F; /* s */
@@ -2859,28 +3242,28 @@ setup_texture_coords(GLenum faceTarget,
       coords0[0] = 0.0F; /* s */
       coords0[1] = 0.0F; /* t */
       coords0[2] = 0.0F; /* r */
-      coords1[0] = width;
+      coords1[0] = (float) width;
       coords1[1] = 0.0F;
       coords1[2] = 0.0F;
-      coords2[0] = width;
-      coords2[1] = height;
+      coords2[0] = (float) width;
+      coords2[1] = (float) height;
       coords2[2] = 0.0F;
       coords3[0] = 0.0F;
-      coords3[1] = height;
+      coords3[1] = (float) height;
       coords3[2] = 0.0F;
       break;
    case GL_TEXTURE_1D_ARRAY:
       coords0[0] = 0.0F; /* s */
-      coords0[1] = slice; /* t */
+      coords0[1] = (float) slice; /* t */
       coords0[2] = 0.0F; /* r */
       coords1[0] = 1.0f;
-      coords1[1] = slice;
+      coords1[1] = (float) slice;
       coords1[2] = 0.0F;
       coords2[0] = 1.0F;
-      coords2[1] = slice;
+      coords2[1] = (float) slice;
       coords2[2] = 0.0F;
       coords3[0] = 0.0F;
-      coords3[1] = slice;
+      coords3[1] = (float) slice;
       coords3[2] = 0.0F;
       break;
 
@@ -2918,6 +3301,8 @@ setup_texture_coords(GLenum faceTarget,
             assert(0);
          }
 
+         coord[3] = (float) (slice / 6);
+
          switch (faceTarget) {
          case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
             coord[0] = 1.0f;
@@ -2959,75 +3344,53 @@ setup_texture_coords(GLenum faceTarget,
    }
 }
 
-
-static void
-setup_ff_generate_mipmap(struct gl_context *ctx,
-                         struct gen_mipmap_state *mipmap)
-{
-   struct vertex {
-      GLfloat x, y, tex[3];
-   };
-
-   if (mipmap->ArrayObj == 0) {
-      /* one-time setup */
-      /* create vertex array object */
-      _mesa_GenVertexArraysAPPLE(1, &mipmap->ArrayObj);
-      _mesa_BindVertexArrayAPPLE(mipmap->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &mipmap->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, mipmap->VBO);
-      /* setup vertex arrays */
-      _mesa_VertexPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_TexCoordPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(tex));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-   }
-
-   /* setup projection matrix */
-   _mesa_MatrixMode(GL_PROJECTION);
-   _mesa_LoadIdentity();
-   _mesa_Ortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
-}
-
-
 static struct glsl_sampler *
-setup_texture_sampler(GLenum target, struct gen_mipmap_state *mipmap)
+setup_texture_sampler(GLenum target, struct sampler_table *table)
 {
    switch(target) {
    case GL_TEXTURE_1D:
-      mipmap->sampler_1d.type = "sampler1D";
-      mipmap->sampler_1d.func = "texture1D";
-      mipmap->sampler_1d.texcoords = "texCoords.x";
-      return &mipmap->sampler_1d;
+      table->sampler_1d.type = "sampler1D";
+      table->sampler_1d.func = "texture1D";
+      table->sampler_1d.texcoords = "texCoords.x";
+      return &table->sampler_1d;
    case GL_TEXTURE_2D:
-      mipmap->sampler_2d.type = "sampler2D";
-      mipmap->sampler_2d.func = "texture2D";
-      mipmap->sampler_2d.texcoords = "texCoords.xy";
-      return &mipmap->sampler_2d;
+      table->sampler_2d.type = "sampler2D";
+      table->sampler_2d.func = "texture2D";
+      table->sampler_2d.texcoords = "texCoords.xy";
+      return &table->sampler_2d;
+   case GL_TEXTURE_RECTANGLE:
+      table->sampler_rect.type = "sampler2DRect";
+      table->sampler_rect.func = "texture2DRect";
+      table->sampler_rect.texcoords = "texCoords.xy";
+      return &table->sampler_rect;
    case GL_TEXTURE_3D:
       /* Code for mipmap generation with 3D textures is not used yet.
        * It's a sw fallback.
        */
-      mipmap->sampler_3d.type = "sampler3D";
-      mipmap->sampler_3d.func = "texture3D";
-      mipmap->sampler_3d.texcoords = "texCoords";
-      return &mipmap->sampler_3d;
+      table->sampler_3d.type = "sampler3D";
+      table->sampler_3d.func = "texture3D";
+      table->sampler_3d.texcoords = "texCoords.xyz";
+      return &table->sampler_3d;
    case GL_TEXTURE_CUBE_MAP:
-      mipmap->sampler_cubemap.type = "samplerCube";
-      mipmap->sampler_cubemap.func = "textureCube";
-      mipmap->sampler_cubemap.texcoords = "texCoords";
-      return &mipmap->sampler_cubemap;
+      table->sampler_cubemap.type = "samplerCube";
+      table->sampler_cubemap.func = "textureCube";
+      table->sampler_cubemap.texcoords = "texCoords.xyz";
+      return &table->sampler_cubemap;
    case GL_TEXTURE_1D_ARRAY:
-      mipmap->sampler_1d_array.type = "sampler1DArray";
-      mipmap->sampler_1d_array.func = "texture1DArray";
-      mipmap->sampler_1d_array.texcoords = "texCoords.xy";
-      return &mipmap->sampler_1d_array;
+      table->sampler_1d_array.type = "sampler1DArray";
+      table->sampler_1d_array.func = "texture1DArray";
+      table->sampler_1d_array.texcoords = "texCoords.xy";
+      return &table->sampler_1d_array;
    case GL_TEXTURE_2D_ARRAY:
-      mipmap->sampler_2d_array.type = "sampler2DArray";
-      mipmap->sampler_2d_array.func = "texture2DArray";
-      mipmap->sampler_2d_array.texcoords = "texCoords";
-      return &mipmap->sampler_2d_array;
+      table->sampler_2d_array.type = "sampler2DArray";
+      table->sampler_2d_array.func = "texture2DArray";
+      table->sampler_2d_array.texcoords = "texCoords.xyz";
+      return &table->sampler_2d_array;
+   case GL_TEXTURE_CUBE_MAP_ARRAY:
+      table->sampler_cubemap_array.type = "samplerCubeArray";
+      table->sampler_cubemap_array.func = "textureCubeArray";
+      table->sampler_cubemap_array.texcoords = "texCoords.xyzw";
+      return &table->sampler_cubemap_array;
    default:
       _mesa_problem(NULL, "Unexpected texture target 0x%x in"
                     " setup_texture_sampler()\n", target);
@@ -3035,138 +3398,50 @@ setup_texture_sampler(GLenum target, struct gen_mipmap_state *mipmap)
    }
 }
 
+static void
+sampler_table_cleanup(struct sampler_table *table)
+{
+   _mesa_DeleteObjectARB(table->sampler_1d.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_2d.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_3d.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_rect.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_cubemap.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_1d_array.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_2d_array.shader_prog);
+   _mesa_DeleteObjectARB(table->sampler_cubemap_array.shader_prog);
+
+   table->sampler_1d.shader_prog = 0;
+   table->sampler_2d.shader_prog = 0;
+   table->sampler_3d.shader_prog = 0;
+   table->sampler_rect.shader_prog = 0;
+   table->sampler_cubemap.shader_prog = 0;
+   table->sampler_1d_array.shader_prog = 0;
+   table->sampler_2d_array.shader_prog = 0;
+   table->sampler_cubemap_array.shader_prog = 0;
+}
 
 static void
 setup_glsl_generate_mipmap(struct gl_context *ctx,
                            struct gen_mipmap_state *mipmap,
                            GLenum target)
 {
-   struct vertex {
-      GLfloat x, y, tex[3];
-   };
-   struct glsl_sampler *sampler;
-   const char *vs_source;
-   char *fs_source;
-   GLuint vs, fs;
-   void *mem_ctx;
-
-   /* Check if already initialized */
-   if (mipmap->ArrayObj == 0) {
-
-      /* create vertex array object */
-      _mesa_GenVertexArrays(1, &mipmap->ArrayObj);
-      _mesa_BindVertexArray(mipmap->ArrayObj);
+   setup_vertex_objects(&mipmap->VAO, &mipmap->VBO, true, 2, 3, 0);
 
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &mipmap->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, mipmap->VBO);
-
-      /* setup vertex arrays */
-      _mesa_VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE,
-                                   sizeof(struct vertex), OFFSET(x));
-      _mesa_VertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
-                                   sizeof(struct vertex), OFFSET(tex));
-   }
-
-   /* Generate a fragment shader program appropriate for the texture target */
-   sampler = setup_texture_sampler(target, mipmap);
-   assert(sampler != NULL);
-   if (sampler->shader_prog != 0) {
-      mipmap->ShaderProg = sampler->shader_prog;
-      return;
-   }
-
-   mem_ctx = ralloc_context(NULL);
-
-   if (ctx->API == API_OPENGLES2 || ctx->Const.GLSLVersion < 130) {
-      vs_source =
-         "attribute vec2 position;\n"
-         "attribute vec3 textureCoords;\n"
-         "varying vec3 texCoords;\n"
-         "void main()\n"
-         "{\n"
-         "   texCoords = textureCoords;\n"
-         "   gl_Position = vec4(position, 0.0, 1.0);\n"
-         "}\n";
-
-      fs_source = ralloc_asprintf(mem_ctx,
-                                  "#extension GL_EXT_texture_array : enable\n"
-                                  "uniform %s texSampler;\n"
-                                  "varying vec3 texCoords;\n"
-                                  "void main()\n"
-                                  "{\n"
-                                  "   gl_FragColor = %s(texSampler, %s);\n"
-                                  "}\n",
-                                  sampler->type,
-                                  sampler->func, sampler->texcoords);
-   }
-   else {
-      vs_source =
-         "#version 130\n"
-         "in vec2 position;\n"
-         "in vec3 textureCoords;\n"
-         "out vec3 texCoords;\n"
-         "void main()\n"
-         "{\n"
-         "   texCoords = textureCoords;\n"
-         "   gl_Position = vec4(position, 0.0, 1.0);\n"
-         "}\n";
-      fs_source = ralloc_asprintf(mem_ctx,
-                                  "#version 130\n"
-                                  "uniform %s texSampler;\n"
-                                  "in vec3 texCoords;\n"
-                                  "out vec4 out_color;\n"
-                                  "\n"
-                                  "void main()\n"
-                                  "{\n"
-                                  "   out_color = texture(texSampler, %s);\n"
-                                  "}\n",
-                                  sampler->type,
-                                  sampler->texcoords);
-   }
-
-   vs = compile_shader_with_debug(ctx, GL_VERTEX_SHADER, vs_source);
-   fs = compile_shader_with_debug(ctx, GL_FRAGMENT_SHADER, fs_source);
-
-   mipmap->ShaderProg = _mesa_CreateProgramObjectARB();
-   _mesa_AttachShader(mipmap->ShaderProg, fs);
-   _mesa_DeleteObjectARB(fs);
-   _mesa_AttachShader(mipmap->ShaderProg, vs);
-   _mesa_DeleteObjectARB(vs);
-   _mesa_BindAttribLocation(mipmap->ShaderProg, 0, "position");
-   _mesa_BindAttribLocation(mipmap->ShaderProg, 1, "texcoords");
-   _mesa_EnableVertexAttribArray(0);
-   _mesa_EnableVertexAttribArray(1);
-   link_program_with_debug(ctx, mipmap->ShaderProg);
-   sampler->shader_prog = mipmap->ShaderProg;
-   ralloc_free(mem_ctx);
+   setup_blit_shader(ctx, target, &mipmap->samplers);
 }
 
 
 static void
-meta_glsl_generate_mipmap_cleanup(struct gl_context *ctx,
-                                 struct gen_mipmap_state *mipmap)
+meta_glsl_generate_mipmap_cleanup(struct gen_mipmap_state *mipmap)
 {
-   if (mipmap->ArrayObj == 0)
+   if (mipmap->VAO == 0)
       return;
-   _mesa_DeleteVertexArrays(1, &mipmap->ArrayObj);
-   mipmap->ArrayObj = 0;
+   _mesa_DeleteVertexArrays(1, &mipmap->VAO);
+   mipmap->VAO = 0;
    _mesa_DeleteBuffers(1, &mipmap->VBO);
    mipmap->VBO = 0;
 
-   _mesa_DeleteObjectARB(mipmap->sampler_1d.shader_prog);
-   _mesa_DeleteObjectARB(mipmap->sampler_2d.shader_prog);
-   _mesa_DeleteObjectARB(mipmap->sampler_3d.shader_prog);
-   _mesa_DeleteObjectARB(mipmap->sampler_cubemap.shader_prog);
-   _mesa_DeleteObjectARB(mipmap->sampler_1d_array.shader_prog);
-   _mesa_DeleteObjectARB(mipmap->sampler_2d_array.shader_prog);
-
-   mipmap->sampler_1d.shader_prog = 0;
-   mipmap->sampler_2d.shader_prog = 0;
-   mipmap->sampler_3d.shader_prog = 0;
-   mipmap->sampler_cubemap.shader_prog = 0;
-   mipmap->sampler_1d_array.shader_prog = 0;
-   mipmap->sampler_2d_array.shader_prog = 0;
+   sampler_table_cleanup(&mipmap->samplers);
 }
 
 
@@ -3180,9 +3455,6 @@ _mesa_meta_GenerateMipmap(struct gl_context *ctx, GLenum target,
                           struct gl_texture_object *texObj)
 {
    struct gen_mipmap_state *mipmap = &ctx->Meta->Mipmap;
-   struct vertex {
-      GLfloat x, y, tex[3];
-   };
    struct vertex verts[4];
    const GLuint baseLevel = texObj->BaseLevel;
    const GLuint maxLevel = texObj->MaxLevel;
@@ -3219,16 +3491,12 @@ _mesa_meta_GenerateMipmap(struct gl_context *ctx, GLenum target,
     */
    if (use_glsl_version) {
       setup_glsl_generate_mipmap(ctx, mipmap, target);
-      _mesa_UseProgram(mipmap->ShaderProg);
    }
    else {
-      setup_ff_generate_mipmap(ctx, mipmap);
+      setup_ff_tnl_for_blit(&mipmap->VAO, &mipmap->VBO, 3);
       _mesa_set_enable(ctx, target, GL_TRUE);
    }
 
-   _mesa_BindVertexArray(mipmap->ArrayObj);
-   _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, mipmap->VBO);
-
    samplerSave = ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler ?
       ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler->Name : 0;
 
@@ -3271,10 +3539,13 @@ _mesa_meta_GenerateMipmap(struct gl_context *ctx, GLenum target,
    else
       assert(!genMipmapSave);
 
-  /* Setup texture coordinates */
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
+
+   /* Setup texture coordinates */
    setup_texture_coords(faceTarget,
                         slice,
-                        0, 0, /* width, height never used here */
+                        0, 0, 1, /* width, height never used here */
                         verts[0].tex,
                         verts[1].tex,
                         verts[2].tex,
@@ -3382,7 +3653,7 @@ _mesa_meta_GenerateMipmap(struct gl_context *ctx, GLenum target,
       assert(dstHeight == ctx->DrawBuffer->Height);
 
       /* setup viewport */
-      _mesa_set_viewport(ctx, 0, 0, dstWidth, dstHeight);
+      _mesa_set_viewport(ctx, 0, 0, 0, dstWidth, dstHeight);
 
       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
@@ -3406,7 +3677,7 @@ _mesa_meta_GenerateMipmap(struct gl_context *ctx, GLenum target,
  * ReadPixels() and passed to Tex[Sub]Image().
  */
 static GLenum
-get_temp_image_type(struct gl_context *ctx, gl_format format)
+get_temp_image_type(struct gl_context *ctx, mesa_format format)
 {
    GLenum baseFormat;
 
@@ -3431,10 +3702,20 @@ get_temp_image_type(struct gl_context *ctx, gl_format format)
             return datatype;
          return GL_FLOAT;
       }
-   case GL_DEPTH_COMPONENT:
-      return GL_UNSIGNED_INT;
-   case GL_DEPTH_STENCIL:
-      return GL_UNSIGNED_INT_24_8;
+   case GL_DEPTH_COMPONENT: {
+      GLenum datatype = _mesa_get_format_datatype(format);
+      if (datatype == GL_FLOAT)
+         return GL_FLOAT;
+      else
+         return GL_UNSIGNED_INT;
+   }
+   case GL_DEPTH_STENCIL: {
+      GLenum datatype = _mesa_get_format_datatype(format);
+      if (datatype == GL_FLOAT)
+         return GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
+      else
+         return GL_UNSIGNED_INT_24_8;
+   }
    default:
       _mesa_problem(ctx, "Unexpected format %d in get_temp_image_type()",
                    baseFormat);
@@ -3460,6 +3741,12 @@ _mesa_meta_CopyTexSubImage(struct gl_context *ctx, GLuint dims,
    GLint bpp;
    void *buf;
 
+   /* The gl_renderbuffer is part of the interface for
+    * dd_function_table::CopyTexSubImage, but this implementation does not use
+    * it.
+    */
+   (void) rb;
+
    /* Choose format/type for temporary image buffer */
    format = _mesa_get_format_base_format(texImage->TexFormat);
    if (format == GL_LUMINANCE ||
@@ -3508,9 +3795,16 @@ _mesa_meta_CopyTexSubImage(struct gl_context *ctx, GLuint dims,
     */
    _mesa_meta_begin(ctx, MESA_META_PIXEL_STORE);
 
-   ctx->Driver.TexSubImage(ctx, dims, texImage,
-                           xoffset, yoffset, zoffset, width, height, 1,
-                           format, type, buf, &ctx->Unpack);
+   if (texImage->TexObject->Target == GL_TEXTURE_1D_ARRAY) {
+      assert(yoffset == 0);
+      ctx->Driver.TexSubImage(ctx, dims, texImage,
+                              xoffset, zoffset, 0, width, 1, 1,
+                              format, type, buf, &ctx->Unpack);
+   } else {
+      ctx->Driver.TexSubImage(ctx, dims, texImage,
+                              xoffset, yoffset, zoffset, width, height, 1,
+                              format, type, buf, &ctx->Unpack);
+   }
 
    _mesa_meta_end(ctx);
 
@@ -3520,6 +3814,25 @@ _mesa_meta_CopyTexSubImage(struct gl_context *ctx, GLuint dims,
 }
 
 
+static void
+meta_decompress_cleanup(struct decompress_state *decompress)
+{
+   if (decompress->FBO != 0) {
+      _mesa_DeleteFramebuffers(1, &decompress->FBO);
+      _mesa_DeleteRenderbuffers(1, &decompress->RBO);
+   }
+
+   if (decompress->VAO != 0) {
+      _mesa_DeleteVertexArrays(1, &decompress->VAO);
+      _mesa_DeleteBuffers(1, &decompress->VBO);
+   }
+
+   if (decompress->Sampler != 0)
+      _mesa_DeleteSamplers(1, &decompress->Sampler);
+
+   memset(decompress, 0, sizeof(*decompress));
+}
+
 /**
  * Decompress a texture image by drawing a quad with the compressed
  * texture and reading the pixels out of the color buffer.
@@ -3540,26 +3853,44 @@ decompress_texture_image(struct gl_context *ctx,
    struct gl_texture_object *texObj = texImage->TexObject;
    const GLint width = texImage->Width;
    const GLint height = texImage->Height;
+   const GLint depth = texImage->Height;
    const GLenum target = texObj->Target;
    GLenum faceTarget;
-   struct vertex {
-      GLfloat x, y, tex[3];
-   };
    struct vertex verts[4];
    GLuint fboDrawSave, fboReadSave;
    GLuint rbSave;
    GLuint samplerSave;
+   const bool use_glsl_version = ctx->Extensions.ARB_vertex_shader &&
+                                      ctx->Extensions.ARB_fragment_shader &&
+                                      (ctx->API != API_OPENGLES);
 
    if (slice > 0) {
       assert(target == GL_TEXTURE_3D ||
-             target == GL_TEXTURE_2D_ARRAY);
+             target == GL_TEXTURE_2D_ARRAY ||
+             target == GL_TEXTURE_CUBE_MAP_ARRAY);
    }
 
-   if (target == GL_TEXTURE_CUBE_MAP) {
+   switch (target) {
+   case GL_TEXTURE_1D:
+   case GL_TEXTURE_1D_ARRAY:
+      assert(!"No compressed 1D textures.");
+      return;
+
+   case GL_TEXTURE_3D:
+      assert(!"No compressed 3D textures.");
+      return;
+
+   case GL_TEXTURE_CUBE_MAP_ARRAY:
+      faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + (slice % 6);
+      break;
+
+   case GL_TEXTURE_CUBE_MAP:
       faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + texImage->Face;
-   }
-   else {
+      break;
+
+   default:
       faceTarget = target;
+      break;
    }
 
    /* save fbo bindings (not saved by _mesa_meta_begin()) */
@@ -3596,27 +3927,13 @@ decompress_texture_image(struct gl_context *ctx,
       decompress->Height = height;
    }
 
-   /* setup VBO data */
-   if (decompress->ArrayObj == 0) {
-      /* create vertex array object */
-      _mesa_GenVertexArrays(1, &decompress->ArrayObj);
-      _mesa_BindVertexArray(decompress->ArrayObj);
-
-      /* create vertex array buffer */
-      _mesa_GenBuffers(1, &decompress->VBO);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, decompress->VBO);
-      _mesa_BufferData(GL_ARRAY_BUFFER_ARB, sizeof(verts),
-                          NULL, GL_DYNAMIC_DRAW_ARB);
+   if (use_glsl_version) {
+      setup_vertex_objects(&decompress->VAO, &decompress->VBO, true,
+                           2, 4, 0);
 
-      /* setup vertex arrays */
-      _mesa_VertexPointer(2, GL_FLOAT, sizeof(struct vertex), OFFSET(x));
-      _mesa_TexCoordPointer(3, GL_FLOAT, sizeof(struct vertex), OFFSET(tex));
-      _mesa_EnableClientState(GL_VERTEX_ARRAY);
-      _mesa_EnableClientState(GL_TEXTURE_COORD_ARRAY);
-   }
-   else {
-      _mesa_BindVertexArray(decompress->ArrayObj);
-      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, decompress->VBO);
+      setup_blit_shader(ctx, target, &decompress->samplers);
+   } else {
+      setup_ff_tnl_for_blit(&decompress->VAO, &decompress->VBO, 3);
    }
 
    if (!decompress->Sampler) {
@@ -3635,28 +3952,35 @@ decompress_texture_image(struct gl_context *ctx,
       _mesa_BindSampler(ctx->Texture.CurrentUnit, decompress->Sampler);
    }
 
-   setup_texture_coords(faceTarget, slice, width, height,
+   /* Silence valgrind warnings about reading uninitialized stack. */
+   memset(verts, 0, sizeof(verts));
+
+   setup_texture_coords(faceTarget, slice, width, height, depth,
                         verts[0].tex,
                         verts[1].tex,
                         verts[2].tex,
                         verts[3].tex);
 
    /* setup vertex positions */
-   verts[0].x = 0.0F;
-   verts[0].y = 0.0F;
-   verts[1].x = width;
-   verts[1].y = 0.0F;
-   verts[2].x = width;
-   verts[2].y = height;
-   verts[3].x = 0.0F;
-   verts[3].y = height;
+   verts[0].x = -1.0F;
+   verts[0].y = -1.0F;
+   verts[1].x =  1.0F;
+   verts[1].y = -1.0F;
+   verts[2].x =  1.0F;
+   verts[2].y =  1.0F;
+   verts[3].x = -1.0F;
+   verts[3].y =  1.0F;
+
+   _mesa_set_viewport(ctx, 0, 0, 0, width, height);
 
    /* upload new vertex data */
    _mesa_BufferSubData(GL_ARRAY_BUFFER_ARB, 0, sizeof(verts), verts);
 
    /* setup texture state */
    _mesa_BindTexture(target, texObj->Name);
-   _mesa_set_enable(ctx, target, GL_TRUE);
+
+   if (!use_glsl_version)
+      _mesa_set_enable(ctx, target, GL_TRUE);
 
    {
       /* save texture object state */
@@ -3685,6 +4009,7 @@ decompress_texture_image(struct gl_context *ctx,
    /* read pixels from renderbuffer */
    {
       GLenum baseTexFormat = texImage->_BaseFormat;
+      GLenum destBaseFormat = _mesa_base_tex_format(ctx, destFormat);
 
       /* The pixel transfer state will be set to default values at this point
        * (see MESA_META_PIXEL_TRANSFER) so pixel transfer ops are effectively
@@ -3693,9 +4018,19 @@ decompress_texture_image(struct gl_context *ctx,
        * returned as red and two-channel texture values are returned as
        * red/alpha.
        */
-      if (baseTexFormat == GL_LUMINANCE ||
-          baseTexFormat == GL_LUMINANCE_ALPHA ||
-          baseTexFormat == GL_INTENSITY) {
+      if ((baseTexFormat == GL_LUMINANCE ||
+           baseTexFormat == GL_LUMINANCE_ALPHA ||
+           baseTexFormat == GL_INTENSITY) ||
+          /* If we're reading back an RGB(A) texture (using glGetTexImage) as
+          * luminance then we need to return L=tex(R).
+          */
+          ((baseTexFormat == GL_RGBA ||
+            baseTexFormat == GL_RGB  ||
+            baseTexFormat == GL_RG) &&
+          (destBaseFormat == GL_LUMINANCE ||
+           destBaseFormat == GL_LUMINANCE_ALPHA ||
+           destBaseFormat == GL_LUMINANCE_INTEGER_EXT ||
+           destBaseFormat == GL_LUMINANCE_ALPHA_INTEGER_EXT))) {
          /* Green and blue must be zero */
          _mesa_PixelTransferf(GL_GREEN_SCALE, 0.0f);
          _mesa_PixelTransferf(GL_BLUE_SCALE, 0.0f);
@@ -3705,7 +4040,8 @@ decompress_texture_image(struct gl_context *ctx,
    }
 
    /* disable texture unit */
-   _mesa_set_enable(ctx, target, GL_FALSE);
+   if (!use_glsl_version)
+      _mesa_set_enable(ctx, target, GL_FALSE);
 
    _mesa_BindSampler(ctx->Texture.CurrentUnit, samplerSave);
 
@@ -3741,10 +4077,30 @@ _mesa_meta_GetTexImage(struct gl_context *ctx,
        _mesa_get_format_datatype(texImage->TexFormat)
        == GL_UNSIGNED_NORMALIZED) {
       struct gl_texture_object *texObj = texImage->TexObject;
-      const GLuint slice = 0; /* only 2D compressed textures for now */
+      GLuint slice;
       /* Need to unlock the texture here to prevent deadlock... */
       _mesa_unlock_texture(ctx, texObj);
-      decompress_texture_image(ctx, texImage, slice, format, type, pixels);
+      for (slice = 0; slice < texImage->Depth; slice++) {
+         void *dst;
+         if (texImage->TexObject->Target == GL_TEXTURE_2D_ARRAY
+             || texImage->TexObject->Target == GL_TEXTURE_CUBE_MAP_ARRAY) {
+            /* Setup pixel packing.  SkipPixels and SkipRows will be applied
+             * in the decompress_texture_image() function's call to
+             * glReadPixels but we need to compute the dest slice's address
+             * here (according to SkipImages and ImageHeight).
+             */
+            struct gl_pixelstore_attrib packing = ctx->Pack;
+            packing.SkipPixels = 0;
+            packing.SkipRows = 0;
+            dst = _mesa_image_address3d(&packing, pixels, texImage->Width,
+                                        texImage->Height, format, type,
+                                        slice, 0, 0);
+         }
+         else {
+            dst = pixels;
+         }
+         decompress_texture_image(ctx, texImage, slice, format, type, dst);
+      }
       /* ... and relock it */
       _mesa_lock_texture(ctx, texObj);
    }
@@ -3775,13 +4131,13 @@ _mesa_meta_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
                           MESA_META_VERTEX |
                           MESA_META_VIEWPORT));
 
-   if (drawtex->ArrayObj == 0) {
+   if (drawtex->VAO == 0) {
       /* one-time setup */
       GLint active_texture;
 
       /* create vertex array object */
-      _mesa_GenVertexArrays(1, &drawtex->ArrayObj);
-      _mesa_BindVertexArray(drawtex->ArrayObj);
+      _mesa_GenVertexArrays(1, &drawtex->VAO);
+      _mesa_BindVertexArray(drawtex->VAO);
 
       /* create vertex array buffer */
       _mesa_GenBuffers(1, &drawtex->VBO);
@@ -3805,7 +4161,7 @@ _mesa_meta_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
       _mesa_ClientActiveTexture(GL_TEXTURE0 + active_texture);
    }
    else {
-      _mesa_BindVertexArray(drawtex->ArrayObj);
+      _mesa_BindVertexArray(drawtex->VAO);
       _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB, drawtex->VBO);
    }
 
@@ -3814,7 +4170,7 @@ _mesa_meta_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
       const GLfloat x1 = x + width;
       const GLfloat y1 = y + height;
 
-      z = CLAMP(z, 0.0, 1.0);
+      z = CLAMP(z, 0.0f, 1.0f);
       z = invert_z(z);
 
       verts[0].x = x;