OSDN Git Service

meta: clear_state structure cleanup
[android-x86/external-mesa.git] / src / mesa / drivers / common / meta.c
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 2009  VMware, Inc.  All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  */
24
25 /**
26  * Meta operations.  Some GL operations can be expressed in terms of
27  * other GL operations.  For example, glBlitFramebuffer() can be done
28  * with texture mapping and glClear() can be done with polygon rendering.
29  *
30  * \author Brian Paul
31  */
32
33
34 #include "main/glheader.h"
35 #include "main/mtypes.h"
36 #include "main/imports.h"
37 #include "main/arbprogram.h"
38 #include "main/arrayobj.h"
39 #include "main/blend.h"
40 #include "main/blit.h"
41 #include "main/bufferobj.h"
42 #include "main/buffers.h"
43 #include "main/clear.h"
44 #include "main/condrender.h"
45 #include "main/depth.h"
46 #include "main/enable.h"
47 #include "main/fbobject.h"
48 #include "main/feedback.h"
49 #include "main/formats.h"
50 #include "main/format_unpack.h"
51 #include "main/glformats.h"
52 #include "main/image.h"
53 #include "main/macros.h"
54 #include "main/matrix.h"
55 #include "main/mipmap.h"
56 #include "main/multisample.h"
57 #include "main/objectlabel.h"
58 #include "main/pipelineobj.h"
59 #include "main/pixel.h"
60 #include "main/pbo.h"
61 #include "main/polygon.h"
62 #include "main/queryobj.h"
63 #include "main/readpix.h"
64 #include "main/scissor.h"
65 #include "main/shaderapi.h"
66 #include "main/shaderobj.h"
67 #include "main/state.h"
68 #include "main/stencil.h"
69 #include "main/texobj.h"
70 #include "main/texenv.h"
71 #include "main/texgetimage.h"
72 #include "main/teximage.h"
73 #include "main/texparam.h"
74 #include "main/texstate.h"
75 #include "main/texstore.h"
76 #include "main/transformfeedback.h"
77 #include "main/uniforms.h"
78 #include "main/varray.h"
79 #include "main/viewport.h"
80 #include "main/samplerobj.h"
81 #include "program/program.h"
82 #include "swrast/swrast.h"
83 #include "drivers/common/meta.h"
84 #include "main/enums.h"
85 #include "main/glformats.h"
86 #include "util/ralloc.h"
87
88 /** Return offset in bytes of the field within a vertex struct */
89 #define OFFSET(FIELD) ((void *) offsetof(struct vertex, FIELD))
90
91 static void
92 meta_clear(struct gl_context *ctx, GLbitfield buffers, bool glsl);
93
94 static struct blit_shader *
95 choose_blit_shader(GLenum target, struct blit_shader_table *table);
96
97 static void cleanup_temp_texture(struct temp_texture *tex);
98 static void meta_glsl_clear_cleanup(struct gl_context *ctx,
99                                     struct clear_state *clear);
100 static void meta_decompress_cleanup(struct gl_context *ctx,
101                                     struct decompress_state *decompress);
102 static void meta_drawpix_cleanup(struct gl_context *ctx,
103                                  struct drawpix_state *drawpix);
104
105 void
106 _mesa_meta_bind_fbo_image(GLenum fboTarget, GLenum attachment,
107                           struct gl_texture_image *texImage, GLuint layer)
108 {
109    struct gl_texture_object *texObj = texImage->TexObject;
110    int level = texImage->Level;
111    GLenum texTarget = texObj->Target;
112
113    switch (texTarget) {
114    case GL_TEXTURE_1D:
115       _mesa_FramebufferTexture1D(fboTarget,
116                                  attachment,
117                                  texTarget,
118                                  texObj->Name,
119                                  level);
120       break;
121    case GL_TEXTURE_1D_ARRAY:
122    case GL_TEXTURE_2D_ARRAY:
123    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
124    case GL_TEXTURE_CUBE_MAP_ARRAY:
125    case GL_TEXTURE_3D:
126       _mesa_FramebufferTextureLayer(fboTarget,
127                                     attachment,
128                                     texObj->Name,
129                                     level,
130                                     layer);
131       break;
132    default: /* 2D / cube */
133       if (texTarget == GL_TEXTURE_CUBE_MAP)
134          texTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + texImage->Face;
135
136       _mesa_FramebufferTexture2D(fboTarget,
137                                  attachment,
138                                  texTarget,
139                                  texObj->Name,
140                                  level);
141    }
142 }
143
144 GLuint
145 _mesa_meta_compile_shader_with_debug(struct gl_context *ctx, GLenum target,
146                                      const GLcharARB *source)
147 {
148    GLuint shader;
149    GLint ok, size;
150    GLchar *info;
151
152    shader = _mesa_CreateShader(target);
153    _mesa_ShaderSource(shader, 1, &source, NULL);
154    _mesa_CompileShader(shader);
155
156    _mesa_GetShaderiv(shader, GL_COMPILE_STATUS, &ok);
157    if (ok)
158       return shader;
159
160    _mesa_GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
161    if (size == 0) {
162       _mesa_DeleteShader(shader);
163       return 0;
164    }
165
166    info = malloc(size);
167    if (!info) {
168       _mesa_DeleteShader(shader);
169       return 0;
170    }
171
172    _mesa_GetShaderInfoLog(shader, size, NULL, info);
173    _mesa_problem(ctx,
174                  "meta program compile failed:\n%s\n"
175                  "source:\n%s\n",
176                  info, source);
177
178    free(info);
179    _mesa_DeleteShader(shader);
180
181    return 0;
182 }
183
184 GLuint
185 _mesa_meta_link_program_with_debug(struct gl_context *ctx, GLuint program)
186 {
187    GLint ok, size;
188    GLchar *info;
189
190    _mesa_LinkProgram(program);
191
192    _mesa_GetProgramiv(program, GL_LINK_STATUS, &ok);
193    if (ok)
194       return program;
195
196    _mesa_GetProgramiv(program, GL_INFO_LOG_LENGTH, &size);
197    if (size == 0)
198       return 0;
199
200    info = malloc(size);
201    if (!info)
202       return 0;
203
204    _mesa_GetProgramInfoLog(program, size, NULL, info);
205    _mesa_problem(ctx, "meta program link failed:\n%s", info);
206
207    free(info);
208
209    return 0;
210 }
211
212 void
213 _mesa_meta_compile_and_link_program(struct gl_context *ctx,
214                                     const char *vs_source,
215                                     const char *fs_source,
216                                     const char *name,
217                                     GLuint *program)
218 {
219    GLuint vs = _mesa_meta_compile_shader_with_debug(ctx, GL_VERTEX_SHADER,
220                                                     vs_source);
221    GLuint fs = _mesa_meta_compile_shader_with_debug(ctx, GL_FRAGMENT_SHADER,
222                                                     fs_source);
223
224    *program = _mesa_CreateProgram();
225    _mesa_ObjectLabel(GL_PROGRAM, *program, -1, name);
226    _mesa_AttachShader(*program, fs);
227    _mesa_DeleteShader(fs);
228    _mesa_AttachShader(*program, vs);
229    _mesa_DeleteShader(vs);
230    _mesa_BindAttribLocation(*program, 0, "position");
231    _mesa_BindAttribLocation(*program, 1, "texcoords");
232    _mesa_meta_link_program_with_debug(ctx, *program);
233
234    _mesa_UseProgram(*program);
235 }
236
237 /**
238  * Generate a generic shader to blit from a texture to a framebuffer
239  *
240  * \param ctx       Current GL context
241  * \param texTarget Texture target that will be the source of the blit
242  *
243  * \returns a handle to a shader program on success or zero on failure.
244  */
245 void
246 _mesa_meta_setup_blit_shader(struct gl_context *ctx,
247                              GLenum target,
248                              bool do_depth,
249                              struct blit_shader_table *table)
250 {
251    char *vs_source, *fs_source;
252    struct blit_shader *shader = choose_blit_shader(target, table);
253    const char *vs_input, *vs_output, *fs_input, *vs_preprocess, *fs_preprocess;
254    void *mem_ctx;
255
256    if (ctx->Const.GLSLVersion < 130) {
257       vs_preprocess = "";
258       vs_input = "attribute";
259       vs_output = "varying";
260       fs_preprocess = "#extension GL_EXT_texture_array : enable";
261       fs_input = "varying";
262    } else {
263       vs_preprocess = "#version 130";
264       vs_input = "in";
265       vs_output = "out";
266       fs_preprocess = "#version 130";
267       fs_input = "in";
268       shader->func = "texture";
269    }
270
271    assert(shader != NULL);
272
273    if (shader->shader_prog != 0) {
274       _mesa_UseProgram(shader->shader_prog);
275       return;
276    }
277
278    mem_ctx = ralloc_context(NULL);
279
280    vs_source = ralloc_asprintf(mem_ctx,
281                 "%s\n"
282                 "%s vec2 position;\n"
283                 "%s vec4 textureCoords;\n"
284                 "%s vec4 texCoords;\n"
285                 "void main()\n"
286                 "{\n"
287                 "   texCoords = textureCoords;\n"
288                 "   gl_Position = vec4(position, 0.0, 1.0);\n"
289                 "}\n",
290                 vs_preprocess, vs_input, vs_input, vs_output);
291
292    fs_source = ralloc_asprintf(mem_ctx,
293                 "%s\n"
294                 "#extension GL_ARB_texture_cube_map_array: enable\n"
295                 "uniform %s texSampler;\n"
296                 "%s vec4 texCoords;\n"
297                 "void main()\n"
298                 "{\n"
299                 "   gl_FragColor = %s(texSampler, %s);\n"
300                 "%s"
301                 "}\n",
302                 fs_preprocess, shader->type, fs_input,
303                 shader->func, shader->texcoords,
304                 do_depth ?  "   gl_FragDepth = gl_FragColor.x;\n" : "");
305
306    _mesa_meta_compile_and_link_program(ctx, vs_source, fs_source,
307                                        ralloc_asprintf(mem_ctx, "%s blit",
308                                                        shader->type),
309                                        &shader->shader_prog);
310    ralloc_free(mem_ctx);
311 }
312
313 /**
314  * Configure vertex buffer and vertex array objects for tests
315  *
316  * Regardless of whether a new VAO is created, the object referenced by \c VAO
317  * will be bound into the GL state vector when this function terminates.  The
318  * object referenced by \c VBO will \b not be bound.
319  *
320  * \param VAO       Storage for vertex array object handle.  If 0, a new VAO
321  *                  will be created.
322  * \param buf_obj   Storage for vertex buffer object pointer.  If \c NULL, a new VBO
323  *                  will be created.  The new VBO will have storage for 4
324  *                  \c vertex structures.
325  * \param use_generic_attributes  Should generic attributes 0 and 1 be used,
326  *                  or should traditional, fixed-function color and texture
327  *                  coordinate be used?
328  * \param vertex_size  Number of components for attribute 0 / vertex.
329  * \param texcoord_size  Number of components for attribute 1 / texture
330  *                  coordinate.  If this is 0, attribute 1 will not be set or
331  *                  enabled.
332  * \param color_size  Number of components for attribute 1 / primary color.
333  *                  If this is 0, attribute 1 will not be set or enabled.
334  *
335  * \note If \c use_generic_attributes is \c true, \c color_size must be zero.
336  * Use \c texcoord_size instead.
337  */
338 void
339 _mesa_meta_setup_vertex_objects(struct gl_context *ctx,
340                                 GLuint *VAO, struct gl_buffer_object **buf_obj,
341                                 bool use_generic_attributes,
342                                 unsigned vertex_size, unsigned texcoord_size,
343                                 unsigned color_size)
344 {
345    if (*VAO == 0) {
346       struct gl_vertex_array_object *array_obj;
347       assert(*buf_obj == NULL);
348
349       /* create vertex array object */
350       _mesa_GenVertexArrays(1, VAO);
351       _mesa_BindVertexArray(*VAO);
352
353       array_obj = _mesa_lookup_vao(ctx, *VAO);
354       assert(array_obj != NULL);
355
356       /* create vertex array buffer */
357       *buf_obj = ctx->Driver.NewBufferObject(ctx, 0xDEADBEEF);
358       if (*buf_obj == NULL)
359          return;
360
361       _mesa_buffer_data(ctx, *buf_obj, GL_NONE, 4 * sizeof(struct vertex), NULL,
362                         GL_DYNAMIC_DRAW, __func__);
363
364       /* setup vertex arrays */
365       if (use_generic_attributes) {
366          assert(color_size == 0);
367
368          _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_GENERIC(0),
369                                    vertex_size, GL_FLOAT, GL_RGBA, GL_FALSE,
370                                    GL_FALSE, GL_FALSE,
371                                    offsetof(struct vertex, x), true);
372          _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_GENERIC(0),
373                                   *buf_obj, 0, sizeof(struct vertex));
374          _mesa_enable_vertex_array_attrib(ctx, array_obj,
375                                           VERT_ATTRIB_GENERIC(0));
376          if (texcoord_size > 0) {
377             _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_GENERIC(1),
378                                       texcoord_size, GL_FLOAT, GL_RGBA,
379                                       GL_FALSE, GL_FALSE, GL_FALSE,
380                                       offsetof(struct vertex, tex), false);
381             _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_GENERIC(1),
382                                      *buf_obj, 0, sizeof(struct vertex));
383             _mesa_enable_vertex_array_attrib(ctx, array_obj,
384                                              VERT_ATTRIB_GENERIC(1));
385          }
386       } else {
387          _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_POS,
388                                    vertex_size, GL_FLOAT, GL_RGBA, GL_FALSE,
389                                    GL_FALSE, GL_FALSE,
390                                    offsetof(struct vertex, x), true);
391          _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_POS,
392                                   *buf_obj, 0, sizeof(struct vertex));
393          _mesa_enable_vertex_array_attrib(ctx, array_obj, VERT_ATTRIB_POS);
394
395          if (texcoord_size > 0) {
396             _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_TEX(0),
397                                       vertex_size, GL_FLOAT, GL_RGBA, GL_FALSE,
398                                       GL_FALSE, GL_FALSE,
399                                       offsetof(struct vertex, tex), false);
400             _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_TEX(0),
401                                      *buf_obj, 0, sizeof(struct vertex));
402             _mesa_enable_vertex_array_attrib(ctx, array_obj, VERT_ATTRIB_TEX(0));
403          }
404
405          if (color_size > 0) {
406             _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_COLOR0,
407                                       vertex_size, GL_FLOAT, GL_RGBA, GL_FALSE,
408                                       GL_FALSE, GL_FALSE,
409                                       offsetof(struct vertex, r), false);
410             _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_COLOR0,
411                                      *buf_obj, 0, sizeof(struct vertex));
412             _mesa_enable_vertex_array_attrib(ctx, array_obj, VERT_ATTRIB_COLOR0);
413          }
414       }
415    } else {
416       _mesa_BindVertexArray(*VAO);
417    }
418 }
419
420 /**
421  * Initialize meta-ops for a context.
422  * To be called once during context creation.
423  */
424 void
425 _mesa_meta_init(struct gl_context *ctx)
426 {
427    assert(!ctx->Meta);
428
429    ctx->Meta = CALLOC_STRUCT(gl_meta_state);
430 }
431
432 /**
433  * Free context meta-op state.
434  * To be called once during context destruction.
435  */
436 void
437 _mesa_meta_free(struct gl_context *ctx)
438 {
439    GET_CURRENT_CONTEXT(old_context);
440    _mesa_make_current(ctx, NULL, NULL);
441    _mesa_meta_glsl_blit_cleanup(ctx, &ctx->Meta->Blit);
442    meta_glsl_clear_cleanup(ctx, &ctx->Meta->Clear);
443    _mesa_meta_glsl_generate_mipmap_cleanup(ctx, &ctx->Meta->Mipmap);
444    cleanup_temp_texture(&ctx->Meta->TempTex);
445    meta_decompress_cleanup(ctx, &ctx->Meta->Decompress);
446    meta_drawpix_cleanup(ctx, &ctx->Meta->DrawPix);
447    if (old_context)
448       _mesa_make_current(old_context, old_context->WinSysDrawBuffer, old_context->WinSysReadBuffer);
449    else
450       _mesa_make_current(NULL, NULL, NULL);
451    free(ctx->Meta);
452    ctx->Meta = NULL;
453 }
454
455
456 /**
457  * Enter meta state.  This is like a light-weight version of glPushAttrib
458  * but it also resets most GL state back to default values.
459  *
460  * \param state  bitmask of MESA_META_* flags indicating which attribute groups
461  *               to save and reset to their defaults
462  */
463 void
464 _mesa_meta_begin(struct gl_context *ctx, GLbitfield state)
465 {
466    struct save_state *save;
467
468    /* hope MAX_META_OPS_DEPTH is large enough */
469    assert(ctx->Meta->SaveStackDepth < MAX_META_OPS_DEPTH);
470
471    save = &ctx->Meta->Save[ctx->Meta->SaveStackDepth++];
472    memset(save, 0, sizeof(*save));
473    save->SavedState = state;
474
475    /* We always push into desktop GL mode and pop out at the end.  No sense in
476     * writing our shaders varying based on the user's context choice, when
477     * Mesa can handle either.
478     */
479    save->API = ctx->API;
480    ctx->API = API_OPENGL_COMPAT;
481
482    /* Mesa's extension helper functions use the current context's API to look up
483     * the version required by an extension as a step in determining whether or
484     * not it has been advertised. Since meta aims to only be restricted by the
485     * driver capability (and not by whether or not an extension has been
486     * advertised), set the helper functions' Version variable to a value that
487     * will make the checks on the context API and version unconditionally pass.
488     */
489    save->ExtensionsVersion = ctx->Extensions.Version;
490    ctx->Extensions.Version = ~0;
491
492    /* Pausing transform feedback needs to be done early, or else we won't be
493     * able to change other state.
494     */
495    save->TransformFeedbackNeedsResume =
496       _mesa_is_xfb_active_and_unpaused(ctx);
497    if (save->TransformFeedbackNeedsResume)
498       _mesa_PauseTransformFeedback();
499
500    /* After saving the current occlusion object, call EndQuery so that no
501     * occlusion querying will be active during the meta-operation.
502     */
503    if (state & MESA_META_OCCLUSION_QUERY) {
504       save->CurrentOcclusionObject = ctx->Query.CurrentOcclusionObject;
505       if (save->CurrentOcclusionObject)
506          _mesa_EndQuery(save->CurrentOcclusionObject->Target);
507    }
508
509    if (state & MESA_META_ALPHA_TEST) {
510       save->AlphaEnabled = ctx->Color.AlphaEnabled;
511       save->AlphaFunc = ctx->Color.AlphaFunc;
512       save->AlphaRef = ctx->Color.AlphaRef;
513       if (ctx->Color.AlphaEnabled)
514          _mesa_set_enable(ctx, GL_ALPHA_TEST, GL_FALSE);
515    }
516
517    if (state & MESA_META_BLEND) {
518       save->BlendEnabled = ctx->Color.BlendEnabled;
519       if (ctx->Color.BlendEnabled) {
520          if (ctx->Extensions.EXT_draw_buffers2) {
521             GLuint i;
522             for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
523                _mesa_set_enablei(ctx, GL_BLEND, i, GL_FALSE);
524             }
525          }
526          else {
527             _mesa_set_enable(ctx, GL_BLEND, GL_FALSE);
528          }
529       }
530       save->ColorLogicOpEnabled = ctx->Color.ColorLogicOpEnabled;
531       if (ctx->Color.ColorLogicOpEnabled)
532          _mesa_set_enable(ctx, GL_COLOR_LOGIC_OP, GL_FALSE);
533    }
534
535    if (state & MESA_META_DITHER) {
536       save->DitherFlag = ctx->Color.DitherFlag;
537       _mesa_set_enable(ctx, GL_DITHER, GL_TRUE);
538    }
539
540    if (state & MESA_META_COLOR_MASK) {
541       memcpy(save->ColorMask, ctx->Color.ColorMask,
542              sizeof(ctx->Color.ColorMask));
543       if (!ctx->Color.ColorMask[0][0] ||
544           !ctx->Color.ColorMask[0][1] ||
545           !ctx->Color.ColorMask[0][2] ||
546           !ctx->Color.ColorMask[0][3])
547          _mesa_ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
548    }
549
550    if (state & MESA_META_DEPTH_TEST) {
551       save->Depth = ctx->Depth; /* struct copy */
552       if (ctx->Depth.Test)
553          _mesa_set_enable(ctx, GL_DEPTH_TEST, GL_FALSE);
554    }
555
556    if (state & MESA_META_FOG) {
557       save->Fog = ctx->Fog.Enabled;
558       if (ctx->Fog.Enabled)
559          _mesa_set_enable(ctx, GL_FOG, GL_FALSE);
560    }
561
562    if (state & MESA_META_PIXEL_STORE) {
563       save->Pack = ctx->Pack;
564       save->Unpack = ctx->Unpack;
565       ctx->Pack = ctx->DefaultPacking;
566       ctx->Unpack = ctx->DefaultPacking;
567    }
568
569    if (state & MESA_META_PIXEL_TRANSFER) {
570       save->RedScale = ctx->Pixel.RedScale;
571       save->RedBias = ctx->Pixel.RedBias;
572       save->GreenScale = ctx->Pixel.GreenScale;
573       save->GreenBias = ctx->Pixel.GreenBias;
574       save->BlueScale = ctx->Pixel.BlueScale;
575       save->BlueBias = ctx->Pixel.BlueBias;
576       save->AlphaScale = ctx->Pixel.AlphaScale;
577       save->AlphaBias = ctx->Pixel.AlphaBias;
578       save->MapColorFlag = ctx->Pixel.MapColorFlag;
579       ctx->Pixel.RedScale = 1.0F;
580       ctx->Pixel.RedBias = 0.0F;
581       ctx->Pixel.GreenScale = 1.0F;
582       ctx->Pixel.GreenBias = 0.0F;
583       ctx->Pixel.BlueScale = 1.0F;
584       ctx->Pixel.BlueBias = 0.0F;
585       ctx->Pixel.AlphaScale = 1.0F;
586       ctx->Pixel.AlphaBias = 0.0F;
587       ctx->Pixel.MapColorFlag = GL_FALSE;
588       /* XXX more state */
589       ctx->NewState |=_NEW_PIXEL;
590    }
591
592    if (state & MESA_META_RASTERIZATION) {
593       save->FrontPolygonMode = ctx->Polygon.FrontMode;
594       save->BackPolygonMode = ctx->Polygon.BackMode;
595       save->PolygonOffset = ctx->Polygon.OffsetFill;
596       save->PolygonSmooth = ctx->Polygon.SmoothFlag;
597       save->PolygonStipple = ctx->Polygon.StippleFlag;
598       save->PolygonCull = ctx->Polygon.CullFlag;
599       _mesa_PolygonMode(GL_FRONT_AND_BACK, GL_FILL);
600       _mesa_set_enable(ctx, GL_POLYGON_OFFSET_FILL, GL_FALSE);
601       _mesa_set_enable(ctx, GL_POLYGON_SMOOTH, GL_FALSE);
602       _mesa_set_enable(ctx, GL_POLYGON_STIPPLE, GL_FALSE);
603       _mesa_set_enable(ctx, GL_CULL_FACE, GL_FALSE);
604    }
605
606    if (state & MESA_META_SCISSOR) {
607       save->Scissor = ctx->Scissor; /* struct copy */
608       _mesa_set_enable(ctx, GL_SCISSOR_TEST, GL_FALSE);
609    }
610
611    if (state & MESA_META_SHADER) {
612       int i;
613
614       if (ctx->Extensions.ARB_vertex_program) {
615          save->VertexProgramEnabled = ctx->VertexProgram.Enabled;
616          _mesa_reference_vertprog(ctx, &save->VertexProgram,
617                                   ctx->VertexProgram.Current);
618          _mesa_set_enable(ctx, GL_VERTEX_PROGRAM_ARB, GL_FALSE);
619       }
620
621       if (ctx->Extensions.ARB_fragment_program) {
622          save->FragmentProgramEnabled = ctx->FragmentProgram.Enabled;
623          _mesa_reference_fragprog(ctx, &save->FragmentProgram,
624                                   ctx->FragmentProgram.Current);
625          _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB, GL_FALSE);
626       }
627
628       if (ctx->Extensions.ATI_fragment_shader) {
629          save->ATIFragmentShaderEnabled = ctx->ATIFragmentShader.Enabled;
630          _mesa_set_enable(ctx, GL_FRAGMENT_SHADER_ATI, GL_FALSE);
631       }
632
633       if (ctx->Pipeline.Current) {
634          _mesa_reference_pipeline_object(ctx, &save->Pipeline,
635                                          ctx->Pipeline.Current);
636          _mesa_BindProgramPipeline(0);
637       }
638
639       /* Save the shader state from ctx->Shader (instead of ctx->_Shader) so
640        * that we don't have to worry about the current pipeline state.
641        */
642       for (i = 0; i < MESA_SHADER_STAGES; i++) {
643          _mesa_reference_shader_program(ctx, &save->Shader[i],
644                                         ctx->Shader.CurrentProgram[i]);
645       }
646       _mesa_reference_shader_program(ctx, &save->ActiveShader,
647                                      ctx->Shader.ActiveProgram);
648
649       _mesa_UseProgram(0);
650    }
651
652    if (state & MESA_META_STENCIL_TEST) {
653       save->Stencil = ctx->Stencil; /* struct copy */
654       if (ctx->Stencil.Enabled)
655          _mesa_set_enable(ctx, GL_STENCIL_TEST, GL_FALSE);
656       /* NOTE: other stencil state not reset */
657    }
658
659    if (state & MESA_META_TEXTURE) {
660       GLuint u, tgt;
661
662       save->ActiveUnit = ctx->Texture.CurrentUnit;
663       save->EnvMode = ctx->Texture.Unit[0].EnvMode;
664
665       /* Disable all texture units */
666       for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
667          save->TexEnabled[u] = ctx->Texture.Unit[u].Enabled;
668          save->TexGenEnabled[u] = ctx->Texture.Unit[u].TexGenEnabled;
669          if (ctx->Texture.Unit[u].Enabled ||
670              ctx->Texture.Unit[u].TexGenEnabled) {
671             _mesa_ActiveTexture(GL_TEXTURE0 + u);
672             _mesa_set_enable(ctx, GL_TEXTURE_2D, GL_FALSE);
673             if (ctx->Extensions.ARB_texture_cube_map)
674                _mesa_set_enable(ctx, GL_TEXTURE_CUBE_MAP, GL_FALSE);
675
676             _mesa_set_enable(ctx, GL_TEXTURE_1D, GL_FALSE);
677             _mesa_set_enable(ctx, GL_TEXTURE_3D, GL_FALSE);
678             if (ctx->Extensions.NV_texture_rectangle)
679                _mesa_set_enable(ctx, GL_TEXTURE_RECTANGLE, GL_FALSE);
680             _mesa_set_enable(ctx, GL_TEXTURE_GEN_S, GL_FALSE);
681             _mesa_set_enable(ctx, GL_TEXTURE_GEN_T, GL_FALSE);
682             _mesa_set_enable(ctx, GL_TEXTURE_GEN_R, GL_FALSE);
683             _mesa_set_enable(ctx, GL_TEXTURE_GEN_Q, GL_FALSE);
684          }
685       }
686
687       /* save current texture objects for unit[0] only */
688       for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
689          _mesa_reference_texobj(&save->CurrentTexture[tgt],
690                                 ctx->Texture.Unit[0].CurrentTex[tgt]);
691       }
692
693       /* set defaults for unit[0] */
694       _mesa_ActiveTexture(GL_TEXTURE0);
695       _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
696    }
697
698    if (state & MESA_META_TRANSFORM) {
699       GLuint activeTexture = ctx->Texture.CurrentUnit;
700       memcpy(save->ModelviewMatrix, ctx->ModelviewMatrixStack.Top->m,
701              16 * sizeof(GLfloat));
702       memcpy(save->ProjectionMatrix, ctx->ProjectionMatrixStack.Top->m,
703              16 * sizeof(GLfloat));
704       memcpy(save->TextureMatrix, ctx->TextureMatrixStack[0].Top->m,
705              16 * sizeof(GLfloat));
706       save->MatrixMode = ctx->Transform.MatrixMode;
707       /* set 1:1 vertex:pixel coordinate transform */
708       _mesa_ActiveTexture(GL_TEXTURE0);
709       _mesa_MatrixMode(GL_TEXTURE);
710       _mesa_LoadIdentity();
711       _mesa_ActiveTexture(GL_TEXTURE0 + activeTexture);
712       _mesa_MatrixMode(GL_MODELVIEW);
713       _mesa_LoadIdentity();
714       _mesa_MatrixMode(GL_PROJECTION);
715       _mesa_LoadIdentity();
716
717       /* glOrtho with width = 0 or height = 0 generates GL_INVALID_VALUE.
718        * This can occur when there is no draw buffer.
719        */
720       if (ctx->DrawBuffer->Width != 0 && ctx->DrawBuffer->Height != 0)
721          _mesa_Ortho(0.0, ctx->DrawBuffer->Width,
722                      0.0, ctx->DrawBuffer->Height,
723                      -1.0, 1.0);
724
725       if (ctx->Extensions.ARB_clip_control) {
726          save->ClipOrigin = ctx->Transform.ClipOrigin;
727          save->ClipDepthMode = ctx->Transform.ClipDepthMode;
728          _mesa_ClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
729       }
730    }
731
732    if (state & MESA_META_CLIP) {
733       save->ClipPlanesEnabled = ctx->Transform.ClipPlanesEnabled;
734       if (ctx->Transform.ClipPlanesEnabled) {
735          GLuint i;
736          for (i = 0; i < ctx->Const.MaxClipPlanes; i++) {
737             _mesa_set_enable(ctx, GL_CLIP_PLANE0 + i, GL_FALSE);
738          }
739       }
740    }
741
742    if (state & MESA_META_VERTEX) {
743       /* save vertex array object state */
744       _mesa_reference_vao(ctx, &save->VAO,
745                                    ctx->Array.VAO);
746       /* set some default state? */
747    }
748
749    if (state & MESA_META_VIEWPORT) {
750       /* save viewport state */
751       save->ViewportX = ctx->ViewportArray[0].X;
752       save->ViewportY = ctx->ViewportArray[0].Y;
753       save->ViewportW = ctx->ViewportArray[0].Width;
754       save->ViewportH = ctx->ViewportArray[0].Height;
755       /* set viewport to match window size */
756       if (ctx->ViewportArray[0].X != 0 ||
757           ctx->ViewportArray[0].Y != 0 ||
758           ctx->ViewportArray[0].Width != (float) ctx->DrawBuffer->Width ||
759           ctx->ViewportArray[0].Height != (float) ctx->DrawBuffer->Height) {
760          _mesa_set_viewport(ctx, 0, 0, 0,
761                             ctx->DrawBuffer->Width, ctx->DrawBuffer->Height);
762       }
763       /* save depth range state */
764       save->DepthNear = ctx->ViewportArray[0].Near;
765       save->DepthFar = ctx->ViewportArray[0].Far;
766       /* set depth range to default */
767       _mesa_set_depth_range(ctx, 0, 0.0, 1.0);
768    }
769
770    if (state & MESA_META_CLAMP_FRAGMENT_COLOR) {
771       save->ClampFragmentColor = ctx->Color.ClampFragmentColor;
772
773       /* Generally in here we want to do clamping according to whether
774        * it's for the pixel path (ClampFragmentColor is GL_TRUE),
775        * regardless of the internal implementation of the metaops.
776        */
777       if (ctx->Color.ClampFragmentColor != GL_TRUE &&
778           ctx->Extensions.ARB_color_buffer_float)
779          _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
780    }
781
782    if (state & MESA_META_CLAMP_VERTEX_COLOR) {
783       save->ClampVertexColor = ctx->Light.ClampVertexColor;
784
785       /* Generally in here we never want vertex color clamping --
786        * result clamping is only dependent on fragment clamping.
787        */
788       if (ctx->Extensions.ARB_color_buffer_float)
789          _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
790    }
791
792    if (state & MESA_META_CONDITIONAL_RENDER) {
793       save->CondRenderQuery = ctx->Query.CondRenderQuery;
794       save->CondRenderMode = ctx->Query.CondRenderMode;
795
796       if (ctx->Query.CondRenderQuery)
797          _mesa_EndConditionalRender();
798    }
799
800    if (state & MESA_META_SELECT_FEEDBACK) {
801       save->RenderMode = ctx->RenderMode;
802       if (ctx->RenderMode == GL_SELECT) {
803          save->Select = ctx->Select; /* struct copy */
804          _mesa_RenderMode(GL_RENDER);
805       } else if (ctx->RenderMode == GL_FEEDBACK) {
806          save->Feedback = ctx->Feedback; /* struct copy */
807          _mesa_RenderMode(GL_RENDER);
808       }
809    }
810
811    if (state & MESA_META_MULTISAMPLE) {
812       save->Multisample = ctx->Multisample; /* struct copy */
813
814       if (ctx->Multisample.Enabled)
815          _mesa_set_multisample(ctx, GL_FALSE);
816       if (ctx->Multisample.SampleCoverage)
817          _mesa_set_enable(ctx, GL_SAMPLE_COVERAGE, GL_FALSE);
818       if (ctx->Multisample.SampleAlphaToCoverage)
819          _mesa_set_enable(ctx, GL_SAMPLE_ALPHA_TO_COVERAGE, GL_FALSE);
820       if (ctx->Multisample.SampleAlphaToOne)
821          _mesa_set_enable(ctx, GL_SAMPLE_ALPHA_TO_ONE, GL_FALSE);
822       if (ctx->Multisample.SampleShading)
823          _mesa_set_enable(ctx, GL_SAMPLE_SHADING, GL_FALSE);
824       if (ctx->Multisample.SampleMask)
825          _mesa_set_enable(ctx, GL_SAMPLE_MASK, GL_FALSE);
826    }
827
828    if (state & MESA_META_FRAMEBUFFER_SRGB) {
829       save->sRGBEnabled = ctx->Color.sRGBEnabled;
830       if (ctx->Color.sRGBEnabled)
831          _mesa_set_framebuffer_srgb(ctx, GL_FALSE);
832    }
833
834    if (state & MESA_META_DRAW_BUFFERS) {
835       struct gl_framebuffer *fb = ctx->DrawBuffer;
836       memcpy(save->ColorDrawBuffers, fb->ColorDrawBuffer,
837              sizeof(save->ColorDrawBuffers));
838    }
839
840    /* misc */
841    {
842       save->Lighting = ctx->Light.Enabled;
843       if (ctx->Light.Enabled)
844          _mesa_set_enable(ctx, GL_LIGHTING, GL_FALSE);
845       save->RasterDiscard = ctx->RasterDiscard;
846       if (ctx->RasterDiscard)
847          _mesa_set_enable(ctx, GL_RASTERIZER_DISCARD, GL_FALSE);
848
849       save->DrawBufferName = ctx->DrawBuffer->Name;
850       save->ReadBufferName = ctx->ReadBuffer->Name;
851       save->RenderbufferName = (ctx->CurrentRenderbuffer ?
852                                 ctx->CurrentRenderbuffer->Name : 0);
853    }
854 }
855
856
857 /**
858  * Leave meta state.  This is like a light-weight version of glPopAttrib().
859  */
860 void
861 _mesa_meta_end(struct gl_context *ctx)
862 {
863    assert(ctx->Meta->SaveStackDepth > 0);
864
865    struct save_state *save = &ctx->Meta->Save[ctx->Meta->SaveStackDepth - 1];
866    const GLbitfield state = save->SavedState;
867    int i;
868
869    /* Grab the result of the old occlusion query before starting it again. The
870     * old result is added to the result of the new query so the driver will
871     * continue adding where it left off. */
872    if (state & MESA_META_OCCLUSION_QUERY) {
873       if (save->CurrentOcclusionObject) {
874          struct gl_query_object *q = save->CurrentOcclusionObject;
875          GLuint64EXT result;
876          if (!q->Ready)
877             ctx->Driver.WaitQuery(ctx, q);
878          result = q->Result;
879          _mesa_BeginQuery(q->Target, q->Id);
880          ctx->Query.CurrentOcclusionObject->Result += result;
881       }
882    }
883
884    if (state & MESA_META_ALPHA_TEST) {
885       if (ctx->Color.AlphaEnabled != save->AlphaEnabled)
886          _mesa_set_enable(ctx, GL_ALPHA_TEST, save->AlphaEnabled);
887       _mesa_AlphaFunc(save->AlphaFunc, save->AlphaRef);
888    }
889
890    if (state & MESA_META_BLEND) {
891       if (ctx->Color.BlendEnabled != save->BlendEnabled) {
892          if (ctx->Extensions.EXT_draw_buffers2) {
893             GLuint i;
894             for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
895                _mesa_set_enablei(ctx, GL_BLEND, i, (save->BlendEnabled >> i) & 1);
896             }
897          }
898          else {
899             _mesa_set_enable(ctx, GL_BLEND, (save->BlendEnabled & 1));
900          }
901       }
902       if (ctx->Color.ColorLogicOpEnabled != save->ColorLogicOpEnabled)
903          _mesa_set_enable(ctx, GL_COLOR_LOGIC_OP, save->ColorLogicOpEnabled);
904    }
905
906    if (state & MESA_META_DITHER)
907       _mesa_set_enable(ctx, GL_DITHER, save->DitherFlag);
908
909    if (state & MESA_META_COLOR_MASK) {
910       GLuint i;
911       for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
912          if (!TEST_EQ_4V(ctx->Color.ColorMask[i], save->ColorMask[i])) {
913             if (i == 0) {
914                _mesa_ColorMask(save->ColorMask[i][0], save->ColorMask[i][1],
915                                save->ColorMask[i][2], save->ColorMask[i][3]);
916             }
917             else {
918                _mesa_ColorMaski(i,
919                                       save->ColorMask[i][0],
920                                       save->ColorMask[i][1],
921                                       save->ColorMask[i][2],
922                                       save->ColorMask[i][3]);
923             }
924          }
925       }
926    }
927
928    if (state & MESA_META_DEPTH_TEST) {
929       if (ctx->Depth.Test != save->Depth.Test)
930          _mesa_set_enable(ctx, GL_DEPTH_TEST, save->Depth.Test);
931       _mesa_DepthFunc(save->Depth.Func);
932       _mesa_DepthMask(save->Depth.Mask);
933    }
934
935    if (state & MESA_META_FOG) {
936       _mesa_set_enable(ctx, GL_FOG, save->Fog);
937    }
938
939    if (state & MESA_META_PIXEL_STORE) {
940       ctx->Pack = save->Pack;
941       ctx->Unpack = save->Unpack;
942    }
943
944    if (state & MESA_META_PIXEL_TRANSFER) {
945       ctx->Pixel.RedScale = save->RedScale;
946       ctx->Pixel.RedBias = save->RedBias;
947       ctx->Pixel.GreenScale = save->GreenScale;
948       ctx->Pixel.GreenBias = save->GreenBias;
949       ctx->Pixel.BlueScale = save->BlueScale;
950       ctx->Pixel.BlueBias = save->BlueBias;
951       ctx->Pixel.AlphaScale = save->AlphaScale;
952       ctx->Pixel.AlphaBias = save->AlphaBias;
953       ctx->Pixel.MapColorFlag = save->MapColorFlag;
954       /* XXX more state */
955       ctx->NewState |=_NEW_PIXEL;
956    }
957
958    if (state & MESA_META_RASTERIZATION) {
959       _mesa_PolygonMode(GL_FRONT, save->FrontPolygonMode);
960       _mesa_PolygonMode(GL_BACK, save->BackPolygonMode);
961       _mesa_set_enable(ctx, GL_POLYGON_STIPPLE, save->PolygonStipple);
962       _mesa_set_enable(ctx, GL_POLYGON_SMOOTH, save->PolygonSmooth);
963       _mesa_set_enable(ctx, GL_POLYGON_OFFSET_FILL, save->PolygonOffset);
964       _mesa_set_enable(ctx, GL_CULL_FACE, save->PolygonCull);
965    }
966
967    if (state & MESA_META_SCISSOR) {
968       unsigned i;
969
970       for (i = 0; i < ctx->Const.MaxViewports; i++) {
971          _mesa_set_scissor(ctx, i,
972                            save->Scissor.ScissorArray[i].X,
973                            save->Scissor.ScissorArray[i].Y,
974                            save->Scissor.ScissorArray[i].Width,
975                            save->Scissor.ScissorArray[i].Height);
976          _mesa_set_enablei(ctx, GL_SCISSOR_TEST, i,
977                            (save->Scissor.EnableFlags >> i) & 1);
978       }
979    }
980
981    if (state & MESA_META_SHADER) {
982       static const GLenum targets[] = {
983          GL_VERTEX_SHADER,
984          GL_TESS_CONTROL_SHADER,
985          GL_TESS_EVALUATION_SHADER,
986          GL_GEOMETRY_SHADER,
987          GL_FRAGMENT_SHADER,
988          GL_COMPUTE_SHADER,
989       };
990       STATIC_ASSERT(MESA_SHADER_STAGES == ARRAY_SIZE(targets));
991
992       bool any_shader;
993
994       if (ctx->Extensions.ARB_vertex_program) {
995          _mesa_set_enable(ctx, GL_VERTEX_PROGRAM_ARB,
996                           save->VertexProgramEnabled);
997          _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, 
998                                   save->VertexProgram);
999          _mesa_reference_vertprog(ctx, &save->VertexProgram, NULL);
1000       }
1001
1002       if (ctx->Extensions.ARB_fragment_program) {
1003          _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB,
1004                           save->FragmentProgramEnabled);
1005          _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
1006                                   save->FragmentProgram);
1007          _mesa_reference_fragprog(ctx, &save->FragmentProgram, NULL);
1008       }
1009
1010       if (ctx->Extensions.ATI_fragment_shader) {
1011          _mesa_set_enable(ctx, GL_FRAGMENT_SHADER_ATI,
1012                           save->ATIFragmentShaderEnabled);
1013       }
1014
1015       any_shader = false;
1016       for (i = 0; i < MESA_SHADER_STAGES; i++) {
1017          /* It is safe to call _mesa_use_shader_program even if the extension
1018           * necessary for that program state is not supported.  In that case,
1019           * the saved program object must be NULL and the currently bound
1020           * program object must be NULL.  _mesa_use_shader_program is a no-op
1021           * in that case.
1022           */
1023          _mesa_use_shader_program(ctx, targets[i],
1024                                   save->Shader[i],
1025                                   &ctx->Shader);
1026
1027          /* Do this *before* killing the reference. :)
1028           */
1029          if (save->Shader[i] != NULL)
1030             any_shader = true;
1031
1032          _mesa_reference_shader_program(ctx, &save->Shader[i], NULL);
1033       }
1034
1035       _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram,
1036                                      save->ActiveShader);
1037       _mesa_reference_shader_program(ctx, &save->ActiveShader, NULL);
1038
1039       /* If there were any stages set with programs, use ctx->Shader as the
1040        * current shader state.  Otherwise, use Pipeline.Default.  The pipeline
1041        * hasn't been restored yet, and that may modify ctx->_Shader further.
1042        */
1043       if (any_shader)
1044          _mesa_reference_pipeline_object(ctx, &ctx->_Shader,
1045                                          &ctx->Shader);
1046       else
1047          _mesa_reference_pipeline_object(ctx, &ctx->_Shader,
1048                                          ctx->Pipeline.Default);
1049
1050       if (save->Pipeline) {
1051          _mesa_bind_pipeline(ctx, save->Pipeline);
1052
1053          _mesa_reference_pipeline_object(ctx, &save->Pipeline, NULL);
1054       }
1055    }
1056
1057    if (state & MESA_META_STENCIL_TEST) {
1058       const struct gl_stencil_attrib *stencil = &save->Stencil;
1059
1060       _mesa_set_enable(ctx, GL_STENCIL_TEST, stencil->Enabled);
1061       _mesa_ClearStencil(stencil->Clear);
1062       if (ctx->Extensions.EXT_stencil_two_side) {
1063          _mesa_set_enable(ctx, GL_STENCIL_TEST_TWO_SIDE_EXT,
1064                           stencil->TestTwoSide);
1065          _mesa_ActiveStencilFaceEXT(stencil->ActiveFace
1066                                     ? GL_BACK : GL_FRONT);
1067       }
1068       /* front state */
1069       _mesa_StencilFuncSeparate(GL_FRONT,
1070                                 stencil->Function[0],
1071                                 stencil->Ref[0],
1072                                 stencil->ValueMask[0]);
1073       _mesa_StencilMaskSeparate(GL_FRONT, stencil->WriteMask[0]);
1074       _mesa_StencilOpSeparate(GL_FRONT, stencil->FailFunc[0],
1075                               stencil->ZFailFunc[0],
1076                               stencil->ZPassFunc[0]);
1077       /* back state */
1078       _mesa_StencilFuncSeparate(GL_BACK,
1079                                 stencil->Function[1],
1080                                 stencil->Ref[1],
1081                                 stencil->ValueMask[1]);
1082       _mesa_StencilMaskSeparate(GL_BACK, stencil->WriteMask[1]);
1083       _mesa_StencilOpSeparate(GL_BACK, stencil->FailFunc[1],
1084                               stencil->ZFailFunc[1],
1085                               stencil->ZPassFunc[1]);
1086    }
1087
1088    if (state & MESA_META_TEXTURE) {
1089       GLuint u, tgt;
1090
1091       assert(ctx->Texture.CurrentUnit == 0);
1092
1093       /* restore texenv for unit[0] */
1094       _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, save->EnvMode);
1095
1096       /* restore texture objects for unit[0] only */
1097       for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
1098          if (ctx->Texture.Unit[0].CurrentTex[tgt] != save->CurrentTexture[tgt]) {
1099             FLUSH_VERTICES(ctx, _NEW_TEXTURE);
1100             _mesa_reference_texobj(&ctx->Texture.Unit[0].CurrentTex[tgt],
1101                                    save->CurrentTexture[tgt]);
1102          }
1103          _mesa_reference_texobj(&save->CurrentTexture[tgt], NULL);
1104       }
1105
1106       /* Restore fixed function texture enables, texgen */
1107       for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
1108          if (ctx->Texture.Unit[u].Enabled != save->TexEnabled[u]) {
1109             FLUSH_VERTICES(ctx, _NEW_TEXTURE);
1110             ctx->Texture.Unit[u].Enabled = save->TexEnabled[u];
1111          }
1112
1113          if (ctx->Texture.Unit[u].TexGenEnabled != save->TexGenEnabled[u]) {
1114             FLUSH_VERTICES(ctx, _NEW_TEXTURE);
1115             ctx->Texture.Unit[u].TexGenEnabled = save->TexGenEnabled[u];
1116          }
1117       }
1118
1119       /* restore current unit state */
1120       _mesa_ActiveTexture(GL_TEXTURE0 + save->ActiveUnit);
1121    }
1122
1123    if (state & MESA_META_TRANSFORM) {
1124       GLuint activeTexture = ctx->Texture.CurrentUnit;
1125       _mesa_ActiveTexture(GL_TEXTURE0);
1126       _mesa_MatrixMode(GL_TEXTURE);
1127       _mesa_LoadMatrixf(save->TextureMatrix);
1128       _mesa_ActiveTexture(GL_TEXTURE0 + activeTexture);
1129
1130       _mesa_MatrixMode(GL_MODELVIEW);
1131       _mesa_LoadMatrixf(save->ModelviewMatrix);
1132
1133       _mesa_MatrixMode(GL_PROJECTION);
1134       _mesa_LoadMatrixf(save->ProjectionMatrix);
1135
1136       _mesa_MatrixMode(save->MatrixMode);
1137
1138       if (ctx->Extensions.ARB_clip_control)
1139          _mesa_ClipControl(save->ClipOrigin, save->ClipDepthMode);
1140    }
1141
1142    if (state & MESA_META_CLIP) {
1143       if (save->ClipPlanesEnabled) {
1144          GLuint i;
1145          for (i = 0; i < ctx->Const.MaxClipPlanes; i++) {
1146             if (save->ClipPlanesEnabled & (1 << i)) {
1147                _mesa_set_enable(ctx, GL_CLIP_PLANE0 + i, GL_TRUE);
1148             }
1149          }
1150       }
1151    }
1152
1153    if (state & MESA_META_VERTEX) {
1154       /* restore vertex array object */
1155       _mesa_BindVertexArray(save->VAO->Name);
1156       _mesa_reference_vao(ctx, &save->VAO, NULL);
1157    }
1158
1159    if (state & MESA_META_VIEWPORT) {
1160       if (save->ViewportX != ctx->ViewportArray[0].X ||
1161           save->ViewportY != ctx->ViewportArray[0].Y ||
1162           save->ViewportW != ctx->ViewportArray[0].Width ||
1163           save->ViewportH != ctx->ViewportArray[0].Height) {
1164          _mesa_set_viewport(ctx, 0, save->ViewportX, save->ViewportY,
1165                             save->ViewportW, save->ViewportH);
1166       }
1167       _mesa_set_depth_range(ctx, 0, save->DepthNear, save->DepthFar);
1168    }
1169
1170    if (state & MESA_META_CLAMP_FRAGMENT_COLOR &&
1171        ctx->Extensions.ARB_color_buffer_float) {
1172       _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, save->ClampFragmentColor);
1173    }
1174
1175    if (state & MESA_META_CLAMP_VERTEX_COLOR &&
1176        ctx->Extensions.ARB_color_buffer_float) {
1177       _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR, save->ClampVertexColor);
1178    }
1179
1180    if (state & MESA_META_CONDITIONAL_RENDER) {
1181       if (save->CondRenderQuery)
1182          _mesa_BeginConditionalRender(save->CondRenderQuery->Id,
1183                                       save->CondRenderMode);
1184    }
1185
1186    if (state & MESA_META_SELECT_FEEDBACK) {
1187       if (save->RenderMode == GL_SELECT) {
1188          _mesa_RenderMode(GL_SELECT);
1189          ctx->Select = save->Select;
1190       } else if (save->RenderMode == GL_FEEDBACK) {
1191          _mesa_RenderMode(GL_FEEDBACK);
1192          ctx->Feedback = save->Feedback;
1193       }
1194    }
1195
1196    if (state & MESA_META_MULTISAMPLE) {
1197       struct gl_multisample_attrib *ctx_ms = &ctx->Multisample;
1198       struct gl_multisample_attrib *save_ms = &save->Multisample;
1199
1200       if (ctx_ms->Enabled != save_ms->Enabled)
1201          _mesa_set_multisample(ctx, save_ms->Enabled);
1202       if (ctx_ms->SampleCoverage != save_ms->SampleCoverage)
1203          _mesa_set_enable(ctx, GL_SAMPLE_COVERAGE, save_ms->SampleCoverage);
1204       if (ctx_ms->SampleAlphaToCoverage != save_ms->SampleAlphaToCoverage)
1205          _mesa_set_enable(ctx, GL_SAMPLE_ALPHA_TO_COVERAGE, save_ms->SampleAlphaToCoverage);
1206       if (ctx_ms->SampleAlphaToOne != save_ms->SampleAlphaToOne)
1207          _mesa_set_enable(ctx, GL_SAMPLE_ALPHA_TO_ONE, save_ms->SampleAlphaToOne);
1208       if (ctx_ms->SampleCoverageValue != save_ms->SampleCoverageValue ||
1209           ctx_ms->SampleCoverageInvert != save_ms->SampleCoverageInvert) {
1210          _mesa_SampleCoverage(save_ms->SampleCoverageValue,
1211                               save_ms->SampleCoverageInvert);
1212       }
1213       if (ctx_ms->SampleShading != save_ms->SampleShading)
1214          _mesa_set_enable(ctx, GL_SAMPLE_SHADING, save_ms->SampleShading);
1215       if (ctx_ms->SampleMask != save_ms->SampleMask)
1216          _mesa_set_enable(ctx, GL_SAMPLE_MASK, save_ms->SampleMask);
1217       if (ctx_ms->SampleMaskValue != save_ms->SampleMaskValue)
1218          _mesa_SampleMaski(0, save_ms->SampleMaskValue);
1219       if (ctx_ms->MinSampleShadingValue != save_ms->MinSampleShadingValue)
1220          _mesa_MinSampleShading(save_ms->MinSampleShadingValue);
1221    }
1222
1223    if (state & MESA_META_FRAMEBUFFER_SRGB) {
1224       if (ctx->Color.sRGBEnabled != save->sRGBEnabled)
1225          _mesa_set_framebuffer_srgb(ctx, save->sRGBEnabled);
1226    }
1227
1228    /* misc */
1229    if (save->Lighting) {
1230       _mesa_set_enable(ctx, GL_LIGHTING, GL_TRUE);
1231    }
1232    if (save->RasterDiscard) {
1233       _mesa_set_enable(ctx, GL_RASTERIZER_DISCARD, GL_TRUE);
1234    }
1235    if (save->TransformFeedbackNeedsResume)
1236       _mesa_ResumeTransformFeedback();
1237
1238    if (ctx->DrawBuffer->Name != save->DrawBufferName)
1239       _mesa_BindFramebuffer(GL_DRAW_FRAMEBUFFER, save->DrawBufferName);
1240
1241    if (ctx->ReadBuffer->Name != save->ReadBufferName)
1242       _mesa_BindFramebuffer(GL_READ_FRAMEBUFFER, save->ReadBufferName);
1243
1244    if (!ctx->CurrentRenderbuffer ||
1245        ctx->CurrentRenderbuffer->Name != save->RenderbufferName)
1246       _mesa_BindRenderbuffer(GL_RENDERBUFFER, save->RenderbufferName);
1247
1248    if (state & MESA_META_DRAW_BUFFERS) {
1249       _mesa_drawbuffers(ctx, ctx->DrawBuffer, ctx->Const.MaxDrawBuffers,
1250                         save->ColorDrawBuffers, NULL);
1251    }
1252
1253    ctx->Meta->SaveStackDepth--;
1254
1255    ctx->API = save->API;
1256    ctx->Extensions.Version = save->ExtensionsVersion;
1257 }
1258
1259
1260 /**
1261  * Convert Z from a normalized value in the range [0, 1] to an object-space
1262  * Z coordinate in [-1, +1] so that drawing at the new Z position with the
1263  * default/identity ortho projection results in the original Z value.
1264  * Used by the meta-Clear, Draw/CopyPixels and Bitmap functions where the Z
1265  * value comes from the clear value or raster position.
1266  */
1267 static inline GLfloat
1268 invert_z(GLfloat normZ)
1269 {
1270    GLfloat objZ = 1.0f - 2.0f * normZ;
1271    return objZ;
1272 }
1273
1274
1275 /**
1276  * One-time init for a temp_texture object.
1277  * Choose tex target, compute max tex size, etc.
1278  */
1279 static void
1280 init_temp_texture(struct gl_context *ctx, struct temp_texture *tex)
1281 {
1282    /* prefer texture rectangle */
1283    if (_mesa_is_desktop_gl(ctx) && ctx->Extensions.NV_texture_rectangle) {
1284       tex->Target = GL_TEXTURE_RECTANGLE;
1285       tex->MaxSize = ctx->Const.MaxTextureRectSize;
1286       tex->NPOT = GL_TRUE;
1287    }
1288    else {
1289       /* use 2D texture, NPOT if possible */
1290       tex->Target = GL_TEXTURE_2D;
1291       tex->MaxSize = 1 << (ctx->Const.MaxTextureLevels - 1);
1292       tex->NPOT = ctx->Extensions.ARB_texture_non_power_of_two;
1293    }
1294    tex->MinSize = 16;  /* 16 x 16 at least */
1295    assert(tex->MaxSize > 0);
1296
1297    _mesa_GenTextures(1, &tex->TexObj);
1298 }
1299
1300 static void
1301 cleanup_temp_texture(struct temp_texture *tex)
1302 {
1303    if (!tex->TexObj)
1304      return;
1305    _mesa_DeleteTextures(1, &tex->TexObj);
1306    tex->TexObj = 0;
1307 }
1308
1309
1310 /**
1311  * Return pointer to temp_texture info for non-bitmap ops.
1312  * This does some one-time init if needed.
1313  */
1314 struct temp_texture *
1315 _mesa_meta_get_temp_texture(struct gl_context *ctx)
1316 {
1317    struct temp_texture *tex = &ctx->Meta->TempTex;
1318
1319    if (!tex->TexObj) {
1320       init_temp_texture(ctx, tex);
1321    }
1322
1323    return tex;
1324 }
1325
1326
1327 /**
1328  * Return pointer to temp_texture info for _mesa_meta_bitmap().
1329  * We use a separate texture for bitmaps to reduce texture
1330  * allocation/deallocation.
1331  */
1332 static struct temp_texture *
1333 get_bitmap_temp_texture(struct gl_context *ctx)
1334 {
1335    struct temp_texture *tex = &ctx->Meta->Bitmap.Tex;
1336
1337    if (!tex->TexObj) {
1338       init_temp_texture(ctx, tex);
1339    }
1340
1341    return tex;
1342 }
1343
1344 /**
1345  * Return pointer to depth temp_texture.
1346  * This does some one-time init if needed.
1347  */
1348 struct temp_texture *
1349 _mesa_meta_get_temp_depth_texture(struct gl_context *ctx)
1350 {
1351    struct temp_texture *tex = &ctx->Meta->Blit.depthTex;
1352
1353    if (!tex->TexObj) {
1354       init_temp_texture(ctx, tex);
1355    }
1356
1357    return tex;
1358 }
1359
1360 /**
1361  * Compute the width/height of texture needed to draw an image of the
1362  * given size.  Return a flag indicating whether the current texture
1363  * can be re-used (glTexSubImage2D) or if a new texture needs to be
1364  * allocated (glTexImage2D).
1365  * Also, compute s/t texcoords for drawing.
1366  *
1367  * \return GL_TRUE if new texture is needed, GL_FALSE otherwise
1368  */
1369 GLboolean
1370 _mesa_meta_alloc_texture(struct temp_texture *tex,
1371                          GLsizei width, GLsizei height, GLenum intFormat)
1372 {
1373    GLboolean newTex = GL_FALSE;
1374
1375    assert(width <= tex->MaxSize);
1376    assert(height <= tex->MaxSize);
1377
1378    if (width > tex->Width ||
1379        height > tex->Height ||
1380        intFormat != tex->IntFormat) {
1381       /* alloc new texture (larger or different format) */
1382
1383       if (tex->NPOT) {
1384          /* use non-power of two size */
1385          tex->Width = MAX2(tex->MinSize, width);
1386          tex->Height = MAX2(tex->MinSize, height);
1387       }
1388       else {
1389          /* find power of two size */
1390          GLsizei w, h;
1391          w = h = tex->MinSize;
1392          while (w < width)
1393             w *= 2;
1394          while (h < height)
1395             h *= 2;
1396          tex->Width = w;
1397          tex->Height = h;
1398       }
1399
1400       tex->IntFormat = intFormat;
1401
1402       newTex = GL_TRUE;
1403    }
1404
1405    /* compute texcoords */
1406    if (tex->Target == GL_TEXTURE_RECTANGLE) {
1407       tex->Sright = (GLfloat) width;
1408       tex->Ttop = (GLfloat) height;
1409    }
1410    else {
1411       tex->Sright = (GLfloat) width / tex->Width;
1412       tex->Ttop = (GLfloat) height / tex->Height;
1413    }
1414
1415    return newTex;
1416 }
1417
1418
1419 /**
1420  * Setup/load texture for glCopyPixels or glBlitFramebuffer.
1421  */
1422 void
1423 _mesa_meta_setup_copypix_texture(struct gl_context *ctx,
1424                                  struct temp_texture *tex,
1425                                  GLint srcX, GLint srcY,
1426                                  GLsizei width, GLsizei height,
1427                                  GLenum intFormat,
1428                                  GLenum filter)
1429 {
1430    bool newTex;
1431
1432    _mesa_BindTexture(tex->Target, tex->TexObj);
1433    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MIN_FILTER, filter);
1434    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MAG_FILTER, filter);
1435    _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1436
1437    newTex = _mesa_meta_alloc_texture(tex, width, height, intFormat);
1438
1439    /* copy framebuffer image to texture */
1440    if (newTex) {
1441       /* create new tex image */
1442       if (tex->Width == width && tex->Height == height) {
1443          /* create new tex with framebuffer data */
1444          _mesa_CopyTexImage2D(tex->Target, 0, tex->IntFormat,
1445                               srcX, srcY, width, height, 0);
1446       }
1447       else {
1448          /* create empty texture */
1449          _mesa_TexImage2D(tex->Target, 0, tex->IntFormat,
1450                           tex->Width, tex->Height, 0,
1451                           intFormat, GL_UNSIGNED_BYTE, NULL);
1452          /* load image */
1453          _mesa_CopyTexSubImage2D(tex->Target, 0,
1454                                  0, 0, srcX, srcY, width, height);
1455       }
1456    }
1457    else {
1458       /* replace existing tex image */
1459       _mesa_CopyTexSubImage2D(tex->Target, 0,
1460                               0, 0, srcX, srcY, width, height);
1461    }
1462 }
1463
1464
1465 /**
1466  * Setup/load texture for glDrawPixels.
1467  */
1468 void
1469 _mesa_meta_setup_drawpix_texture(struct gl_context *ctx,
1470                                  struct temp_texture *tex,
1471                                  GLboolean newTex,
1472                                  GLsizei width, GLsizei height,
1473                                  GLenum format, GLenum type,
1474                                  const GLvoid *pixels)
1475 {
1476    _mesa_BindTexture(tex->Target, tex->TexObj);
1477    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1478    _mesa_TexParameteri(tex->Target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1479    _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1480
1481    /* copy pixel data to texture */
1482    if (newTex) {
1483       /* create new tex image */
1484       if (tex->Width == width && tex->Height == height) {
1485          /* create new tex and load image data */
1486          _mesa_TexImage2D(tex->Target, 0, tex->IntFormat,
1487                           tex->Width, tex->Height, 0, format, type, pixels);
1488       }
1489       else {
1490          struct gl_buffer_object *save_unpack_obj = NULL;
1491
1492          _mesa_reference_buffer_object(ctx, &save_unpack_obj,
1493                                        ctx->Unpack.BufferObj);
1494          _mesa_BindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
1495          /* create empty texture */
1496          _mesa_TexImage2D(tex->Target, 0, tex->IntFormat,
1497                           tex->Width, tex->Height, 0, format, type, NULL);
1498          if (save_unpack_obj != NULL)
1499             _mesa_BindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB,
1500                                 save_unpack_obj->Name);
1501          /* load image */
1502          _mesa_TexSubImage2D(tex->Target, 0,
1503                              0, 0, width, height, format, type, pixels);
1504       }
1505    }
1506    else {
1507       /* replace existing tex image */
1508       _mesa_TexSubImage2D(tex->Target, 0,
1509                           0, 0, width, height, format, type, pixels);
1510    }
1511 }
1512
1513 void
1514 _mesa_meta_setup_ff_tnl_for_blit(struct gl_context *ctx,
1515                                  GLuint *VAO, struct gl_buffer_object **buf_obj,
1516                                  unsigned texcoord_size)
1517 {
1518    _mesa_meta_setup_vertex_objects(ctx, VAO, buf_obj, false, 2, texcoord_size,
1519                                    0);
1520
1521    /* setup projection matrix */
1522    _mesa_MatrixMode(GL_PROJECTION);
1523    _mesa_LoadIdentity();
1524 }
1525
1526 /**
1527  * Meta implementation of ctx->Driver.Clear() in terms of polygon rendering.
1528  */
1529 void
1530 _mesa_meta_Clear(struct gl_context *ctx, GLbitfield buffers)
1531 {
1532    meta_clear(ctx, buffers, false);
1533 }
1534
1535 void
1536 _mesa_meta_glsl_Clear(struct gl_context *ctx, GLbitfield buffers)
1537 {
1538    meta_clear(ctx, buffers, true);
1539 }
1540
1541 static void
1542 meta_glsl_clear_init(struct gl_context *ctx, struct clear_state *clear)
1543 {
1544    const char *vs_source =
1545       "#extension GL_AMD_vertex_shader_layer : enable\n"
1546       "#extension GL_ARB_draw_instanced : enable\n"
1547       "#extension GL_ARB_explicit_attrib_location :enable\n"
1548       "layout(location = 0) in vec4 position;\n"
1549       "void main()\n"
1550       "{\n"
1551       "#ifdef GL_AMD_vertex_shader_layer\n"
1552       "   gl_Layer = gl_InstanceID;\n"
1553       "#endif\n"
1554       "   gl_Position = position;\n"
1555       "}\n";
1556    const char *fs_source =
1557       "#extension GL_ARB_explicit_attrib_location :enable\n"
1558       "#extension GL_ARB_explicit_uniform_location :enable\n"
1559       "layout(location = 0) uniform vec4 color;\n"
1560       "void main()\n"
1561       "{\n"
1562       "   gl_FragColor = color;\n"
1563       "}\n";
1564    GLuint vs, fs;
1565    bool has_integer_textures;
1566
1567    _mesa_meta_setup_vertex_objects(ctx, &clear->VAO, &clear->buf_obj, true,
1568                                    3, 0, 0);
1569
1570    if (clear->ShaderProg != 0)
1571       return;
1572
1573    vs = _mesa_CreateShader(GL_VERTEX_SHADER);
1574    _mesa_ShaderSource(vs, 1, &vs_source, NULL);
1575    _mesa_CompileShader(vs);
1576
1577    fs = _mesa_CreateShader(GL_FRAGMENT_SHADER);
1578    _mesa_ShaderSource(fs, 1, &fs_source, NULL);
1579    _mesa_CompileShader(fs);
1580
1581    clear->ShaderProg = _mesa_CreateProgram();
1582    _mesa_AttachShader(clear->ShaderProg, fs);
1583    _mesa_DeleteShader(fs);
1584    _mesa_AttachShader(clear->ShaderProg, vs);
1585    _mesa_DeleteShader(vs);
1586    _mesa_ObjectLabel(GL_PROGRAM, clear->ShaderProg, -1, "meta clear");
1587    _mesa_LinkProgram(clear->ShaderProg);
1588
1589    has_integer_textures = _mesa_is_gles3(ctx) ||
1590       (_mesa_is_desktop_gl(ctx) && ctx->Const.GLSLVersion >= 130);
1591
1592    if (has_integer_textures) {
1593       void *shader_source_mem_ctx = ralloc_context(NULL);
1594       const char *vs_int_source =
1595          ralloc_asprintf(shader_source_mem_ctx,
1596                          "#version 130\n"
1597                          "#extension GL_AMD_vertex_shader_layer : enable\n"
1598                          "#extension GL_ARB_draw_instanced : enable\n"
1599                          "#extension GL_ARB_explicit_attrib_location :enable\n"
1600                          "layout(location = 0) in vec4 position;\n"
1601                          "void main()\n"
1602                          "{\n"
1603                          "#ifdef GL_AMD_vertex_shader_layer\n"
1604                          "   gl_Layer = gl_InstanceID;\n"
1605                          "#endif\n"
1606                          "   gl_Position = position;\n"
1607                          "}\n");
1608       const char *fs_int_source =
1609          ralloc_asprintf(shader_source_mem_ctx,
1610                          "#version 130\n"
1611                          "#extension GL_ARB_explicit_attrib_location :enable\n"
1612                          "#extension GL_ARB_explicit_uniform_location :enable\n"
1613                          "layout(location = 0) uniform ivec4 color;\n"
1614                          "out ivec4 out_color;\n"
1615                          "\n"
1616                          "void main()\n"
1617                          "{\n"
1618                          "   out_color = color;\n"
1619                          "}\n");
1620
1621       vs = _mesa_meta_compile_shader_with_debug(ctx, GL_VERTEX_SHADER,
1622                                                 vs_int_source);
1623       fs = _mesa_meta_compile_shader_with_debug(ctx, GL_FRAGMENT_SHADER,
1624                                                 fs_int_source);
1625       ralloc_free(shader_source_mem_ctx);
1626
1627       clear->IntegerShaderProg = _mesa_CreateProgram();
1628       _mesa_AttachShader(clear->IntegerShaderProg, fs);
1629       _mesa_DeleteShader(fs);
1630       _mesa_AttachShader(clear->IntegerShaderProg, vs);
1631       _mesa_DeleteShader(vs);
1632
1633       /* Note that user-defined out attributes get automatically assigned
1634        * locations starting from 0, so we don't need to explicitly
1635        * BindFragDataLocation to 0.
1636        */
1637
1638       _mesa_ObjectLabel(GL_PROGRAM, clear->IntegerShaderProg, -1,
1639                         "integer clear");
1640       _mesa_meta_link_program_with_debug(ctx, clear->IntegerShaderProg);
1641    }
1642 }
1643
1644 static void
1645 meta_glsl_clear_cleanup(struct gl_context *ctx, struct clear_state *clear)
1646 {
1647    if (clear->VAO == 0)
1648       return;
1649    _mesa_DeleteVertexArrays(1, &clear->VAO);
1650    clear->VAO = 0;
1651    _mesa_reference_buffer_object(ctx, &clear->buf_obj, NULL);
1652    _mesa_DeleteProgram(clear->ShaderProg);
1653    clear->ShaderProg = 0;
1654
1655    if (clear->IntegerShaderProg) {
1656       _mesa_DeleteProgram(clear->IntegerShaderProg);
1657       clear->IntegerShaderProg = 0;
1658    }
1659 }
1660
1661 /**
1662  * Given a bitfield of BUFFER_BIT_x draw buffers, call glDrawBuffers to
1663  * set GL to only draw to those buffers.
1664  *
1665  * Since the bitfield has no associated order, the assignment of draw buffer
1666  * indices to color attachment indices is rather arbitrary.
1667  */
1668 void
1669 _mesa_meta_drawbuffers_from_bitfield(GLbitfield bits)
1670 {
1671    GLenum enums[MAX_DRAW_BUFFERS];
1672    int i = 0;
1673    int n;
1674
1675    /* This function is only legal for color buffer bitfields. */
1676    assert((bits & ~BUFFER_BITS_COLOR) == 0);
1677
1678    /* Make sure we don't overflow any arrays. */
1679    assert(_mesa_bitcount(bits) <= MAX_DRAW_BUFFERS);
1680
1681    enums[0] = GL_NONE;
1682
1683    if (bits & BUFFER_BIT_FRONT_LEFT)
1684       enums[i++] = GL_FRONT_LEFT;
1685
1686    if (bits & BUFFER_BIT_FRONT_RIGHT)
1687       enums[i++] = GL_FRONT_RIGHT;
1688
1689    if (bits & BUFFER_BIT_BACK_LEFT)
1690       enums[i++] = GL_BACK_LEFT;
1691
1692    if (bits & BUFFER_BIT_BACK_RIGHT)
1693       enums[i++] = GL_BACK_RIGHT;
1694
1695    for (n = 0; n < MAX_COLOR_ATTACHMENTS; n++) {
1696       if (bits & (1 << (BUFFER_COLOR0 + n)))
1697          enums[i++] = GL_COLOR_ATTACHMENT0 + n;
1698    }
1699
1700    _mesa_DrawBuffers(i, enums);
1701 }
1702
1703 /**
1704  * Meta implementation of ctx->Driver.Clear() in terms of polygon rendering.
1705  */
1706 static void
1707 meta_clear(struct gl_context *ctx, GLbitfield buffers, bool glsl)
1708 {
1709    struct clear_state *clear = &ctx->Meta->Clear;
1710    GLbitfield metaSave;
1711    const GLuint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
1712    struct gl_framebuffer *fb = ctx->DrawBuffer;
1713    float x0, y0, x1, y1, z;
1714    struct vertex verts[4];
1715    int i;
1716
1717    metaSave = (MESA_META_ALPHA_TEST |
1718                MESA_META_BLEND |
1719                MESA_META_DEPTH_TEST |
1720                MESA_META_RASTERIZATION |
1721                MESA_META_SHADER |
1722                MESA_META_STENCIL_TEST |
1723                MESA_META_VERTEX |
1724                MESA_META_VIEWPORT |
1725                MESA_META_CLIP |
1726                MESA_META_CLAMP_FRAGMENT_COLOR |
1727                MESA_META_MULTISAMPLE |
1728                MESA_META_OCCLUSION_QUERY);
1729
1730    if (!glsl) {
1731       metaSave |= MESA_META_FOG |
1732                   MESA_META_PIXEL_TRANSFER |
1733                   MESA_META_TRANSFORM |
1734                   MESA_META_TEXTURE |
1735                   MESA_META_CLAMP_VERTEX_COLOR |
1736                   MESA_META_SELECT_FEEDBACK;
1737    }
1738
1739    if (buffers & BUFFER_BITS_COLOR) {
1740       metaSave |= MESA_META_DRAW_BUFFERS;
1741    } else {
1742       /* We'll use colormask to disable color writes.  Otherwise,
1743        * respect color mask
1744        */
1745       metaSave |= MESA_META_COLOR_MASK;
1746    }
1747
1748    _mesa_meta_begin(ctx, metaSave);
1749
1750    if (glsl) {
1751       meta_glsl_clear_init(ctx, clear);
1752
1753       x0 = ((float) fb->_Xmin / fb->Width)  * 2.0f - 1.0f;
1754       y0 = ((float) fb->_Ymin / fb->Height) * 2.0f - 1.0f;
1755       x1 = ((float) fb->_Xmax / fb->Width)  * 2.0f - 1.0f;
1756       y1 = ((float) fb->_Ymax / fb->Height) * 2.0f - 1.0f;
1757       z = -invert_z(ctx->Depth.Clear);
1758    } else {
1759       _mesa_meta_setup_vertex_objects(ctx, &clear->VAO, &clear->buf_obj, false,
1760                                       3, 0, 4);
1761
1762       x0 = (float) fb->_Xmin;
1763       y0 = (float) fb->_Ymin;
1764       x1 = (float) fb->_Xmax;
1765       y1 = (float) fb->_Ymax;
1766       z = invert_z(ctx->Depth.Clear);
1767    }
1768
1769    if (fb->_IntegerColor) {
1770       assert(glsl);
1771       _mesa_UseProgram(clear->IntegerShaderProg);
1772       _mesa_Uniform4iv(0, 1, ctx->Color.ClearColor.i);
1773    } else if (glsl) {
1774       _mesa_UseProgram(clear->ShaderProg);
1775       _mesa_Uniform4fv(0, 1, ctx->Color.ClearColor.f);
1776    }
1777
1778    /* GL_COLOR_BUFFER_BIT */
1779    if (buffers & BUFFER_BITS_COLOR) {
1780       /* Only draw to the buffers we were asked to clear. */
1781       _mesa_meta_drawbuffers_from_bitfield(buffers & BUFFER_BITS_COLOR);
1782
1783       /* leave colormask state as-is */
1784
1785       /* Clears never have the color clamped. */
1786       if (ctx->Extensions.ARB_color_buffer_float)
1787          _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
1788    }
1789    else {
1790       assert(metaSave & MESA_META_COLOR_MASK);
1791       _mesa_ColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1792    }
1793
1794    /* GL_DEPTH_BUFFER_BIT */
1795    if (buffers & BUFFER_BIT_DEPTH) {
1796       _mesa_set_enable(ctx, GL_DEPTH_TEST, GL_TRUE);
1797       _mesa_DepthFunc(GL_ALWAYS);
1798       _mesa_DepthMask(GL_TRUE);
1799    }
1800    else {
1801       assert(!ctx->Depth.Test);
1802    }
1803
1804    /* GL_STENCIL_BUFFER_BIT */
1805    if (buffers & BUFFER_BIT_STENCIL) {
1806       _mesa_set_enable(ctx, GL_STENCIL_TEST, GL_TRUE);
1807       _mesa_StencilOpSeparate(GL_FRONT_AND_BACK,
1808                               GL_REPLACE, GL_REPLACE, GL_REPLACE);
1809       _mesa_StencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS,
1810                                 ctx->Stencil.Clear & stencilMax,
1811                                 ctx->Stencil.WriteMask[0]);
1812    }
1813    else {
1814       assert(!ctx->Stencil.Enabled);
1815    }
1816
1817    /* vertex positions */
1818    verts[0].x = x0;
1819    verts[0].y = y0;
1820    verts[0].z = z;
1821    verts[1].x = x1;
1822    verts[1].y = y0;
1823    verts[1].z = z;
1824    verts[2].x = x1;
1825    verts[2].y = y1;
1826    verts[2].z = z;
1827    verts[3].x = x0;
1828    verts[3].y = y1;
1829    verts[3].z = z;
1830
1831    if (!glsl) {
1832       for (i = 0; i < 4; i++) {
1833          verts[i].r = ctx->Color.ClearColor.f[0];
1834          verts[i].g = ctx->Color.ClearColor.f[1];
1835          verts[i].b = ctx->Color.ClearColor.f[2];
1836          verts[i].a = ctx->Color.ClearColor.f[3];
1837       }
1838    }
1839
1840    /* upload new vertex data */
1841    _mesa_buffer_data(ctx, clear->buf_obj, GL_NONE, sizeof(verts), verts,
1842                      GL_DYNAMIC_DRAW, __func__);
1843
1844    /* draw quad(s) */
1845    if (fb->MaxNumLayers > 0) {
1846       _mesa_DrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, fb->MaxNumLayers);
1847    } else {
1848       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
1849    }
1850
1851    _mesa_meta_end(ctx);
1852 }
1853
1854 /**
1855  * Meta implementation of ctx->Driver.CopyPixels() in terms
1856  * of texture mapping and polygon rendering and GLSL shaders.
1857  */
1858 void
1859 _mesa_meta_CopyPixels(struct gl_context *ctx, GLint srcX, GLint srcY,
1860                       GLsizei width, GLsizei height,
1861                       GLint dstX, GLint dstY, GLenum type)
1862 {
1863    struct copypix_state *copypix = &ctx->Meta->CopyPix;
1864    struct temp_texture *tex = _mesa_meta_get_temp_texture(ctx);
1865    struct vertex verts[4];
1866
1867    if (type != GL_COLOR ||
1868        ctx->_ImageTransferState ||
1869        ctx->Fog.Enabled ||
1870        width > tex->MaxSize ||
1871        height > tex->MaxSize) {
1872       /* XXX avoid this fallback */
1873       _swrast_CopyPixels(ctx, srcX, srcY, width, height, dstX, dstY, type);
1874       return;
1875    }
1876
1877    /* Most GL state applies to glCopyPixels, but a there's a few things
1878     * we need to override:
1879     */
1880    _mesa_meta_begin(ctx, (MESA_META_RASTERIZATION |
1881                           MESA_META_SHADER |
1882                           MESA_META_TEXTURE |
1883                           MESA_META_TRANSFORM |
1884                           MESA_META_CLIP |
1885                           MESA_META_VERTEX |
1886                           MESA_META_VIEWPORT));
1887
1888    _mesa_meta_setup_vertex_objects(ctx, &copypix->VAO, &copypix->buf_obj, false,
1889                                    3, 2, 0);
1890
1891    /* Silence valgrind warnings about reading uninitialized stack. */
1892    memset(verts, 0, sizeof(verts));
1893
1894    /* Alloc/setup texture */
1895    _mesa_meta_setup_copypix_texture(ctx, tex, srcX, srcY, width, height,
1896                                     GL_RGBA, GL_NEAREST);
1897
1898    /* vertex positions, texcoords (after texture allocation!) */
1899    {
1900       const GLfloat dstX0 = (GLfloat) dstX;
1901       const GLfloat dstY0 = (GLfloat) dstY;
1902       const GLfloat dstX1 = dstX + width * ctx->Pixel.ZoomX;
1903       const GLfloat dstY1 = dstY + height * ctx->Pixel.ZoomY;
1904       const GLfloat z = invert_z(ctx->Current.RasterPos[2]);
1905
1906       verts[0].x = dstX0;
1907       verts[0].y = dstY0;
1908       verts[0].z = z;
1909       verts[0].tex[0] = 0.0F;
1910       verts[0].tex[1] = 0.0F;
1911       verts[1].x = dstX1;
1912       verts[1].y = dstY0;
1913       verts[1].z = z;
1914       verts[1].tex[0] = tex->Sright;
1915       verts[1].tex[1] = 0.0F;
1916       verts[2].x = dstX1;
1917       verts[2].y = dstY1;
1918       verts[2].z = z;
1919       verts[2].tex[0] = tex->Sright;
1920       verts[2].tex[1] = tex->Ttop;
1921       verts[3].x = dstX0;
1922       verts[3].y = dstY1;
1923       verts[3].z = z;
1924       verts[3].tex[0] = 0.0F;
1925       verts[3].tex[1] = tex->Ttop;
1926
1927       /* upload new vertex data */
1928       _mesa_buffer_sub_data(ctx, copypix->buf_obj, 0, sizeof(verts), verts,
1929                             __func__);
1930    }
1931
1932    _mesa_set_enable(ctx, tex->Target, GL_TRUE);
1933
1934    /* draw textured quad */
1935    _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
1936
1937    _mesa_set_enable(ctx, tex->Target, GL_FALSE);
1938
1939    _mesa_meta_end(ctx);
1940 }
1941
1942 static void
1943 meta_drawpix_cleanup(struct gl_context *ctx, struct drawpix_state *drawpix)
1944 {
1945    if (drawpix->VAO != 0) {
1946       _mesa_DeleteVertexArrays(1, &drawpix->VAO);
1947       drawpix->VAO = 0;
1948
1949       _mesa_reference_buffer_object(ctx, &drawpix->buf_obj, NULL);
1950    }
1951
1952    if (drawpix->StencilFP != 0) {
1953       _mesa_DeleteProgramsARB(1, &drawpix->StencilFP);
1954       drawpix->StencilFP = 0;
1955    }
1956
1957    if (drawpix->DepthFP != 0) {
1958       _mesa_DeleteProgramsARB(1, &drawpix->DepthFP);
1959       drawpix->DepthFP = 0;
1960    }
1961 }
1962
1963 /**
1964  * When the glDrawPixels() image size is greater than the max rectangle
1965  * texture size we use this function to break the glDrawPixels() image
1966  * into tiles which fit into the max texture size.
1967  */
1968 static void
1969 tiled_draw_pixels(struct gl_context *ctx,
1970                   GLint tileSize,
1971                   GLint x, GLint y, GLsizei width, GLsizei height,
1972                   GLenum format, GLenum type,
1973                   const struct gl_pixelstore_attrib *unpack,
1974                   const GLvoid *pixels)
1975 {
1976    struct gl_pixelstore_attrib tileUnpack = *unpack;
1977    GLint i, j;
1978
1979    if (tileUnpack.RowLength == 0)
1980       tileUnpack.RowLength = width;
1981
1982    for (i = 0; i < width; i += tileSize) {
1983       const GLint tileWidth = MIN2(tileSize, width - i);
1984       const GLint tileX = (GLint) (x + i * ctx->Pixel.ZoomX);
1985
1986       tileUnpack.SkipPixels = unpack->SkipPixels + i;
1987
1988       for (j = 0; j < height; j += tileSize) {
1989          const GLint tileHeight = MIN2(tileSize, height - j);
1990          const GLint tileY = (GLint) (y + j * ctx->Pixel.ZoomY);
1991
1992          tileUnpack.SkipRows = unpack->SkipRows + j;
1993
1994          _mesa_meta_DrawPixels(ctx, tileX, tileY, tileWidth, tileHeight,
1995                                format, type, &tileUnpack, pixels);
1996       }
1997    }
1998 }
1999
2000
2001 /**
2002  * One-time init for drawing stencil pixels.
2003  */
2004 static void
2005 init_draw_stencil_pixels(struct gl_context *ctx)
2006 {
2007    /* This program is run eight times, once for each stencil bit.
2008     * The stencil values to draw are found in an 8-bit alpha texture.
2009     * We read the texture/stencil value and test if bit 'b' is set.
2010     * If the bit is not set, use KIL to kill the fragment.
2011     * Finally, we use the stencil test to update the stencil buffer.
2012     *
2013     * The basic algorithm for checking if a bit is set is:
2014     *   if (is_odd(value / (1 << bit)))
2015     *      result is one (or non-zero).
2016     *   else
2017     *      result is zero.
2018     * The program parameter contains three values:
2019     *   parm.x = 255 / (1 << bit)
2020     *   parm.y = 0.5
2021     *   parm.z = 0.0
2022     */
2023    static const char *program =
2024       "!!ARBfp1.0\n"
2025       "PARAM parm = program.local[0]; \n"
2026       "TEMP t; \n"
2027       "TEX t, fragment.texcoord[0], texture[0], %s; \n"   /* NOTE %s here! */
2028       "# t = t * 255 / bit \n"
2029       "MUL t.x, t.a, parm.x; \n"
2030       "# t = (int) t \n"
2031       "FRC t.y, t.x; \n"
2032       "SUB t.x, t.x, t.y; \n"
2033       "# t = t * 0.5 \n"
2034       "MUL t.x, t.x, parm.y; \n"
2035       "# t = fract(t.x) \n"
2036       "FRC t.x, t.x; # if t.x != 0, then the bit is set \n"
2037       "# t.x = (t.x == 0 ? 1 : 0) \n"
2038       "SGE t.x, -t.x, parm.z; \n"
2039       "KIL -t.x; \n"
2040       "# for debug only \n"
2041       "#MOV result.color, t.x; \n"
2042       "END \n";
2043    char program2[1000];
2044    struct drawpix_state *drawpix = &ctx->Meta->DrawPix;
2045    struct temp_texture *tex = _mesa_meta_get_temp_texture(ctx);
2046    const char *texTarget;
2047
2048    assert(drawpix->StencilFP == 0);
2049
2050    /* replace %s with "RECT" or "2D" */
2051    assert(strlen(program) + 4 < sizeof(program2));
2052    if (tex->Target == GL_TEXTURE_RECTANGLE)
2053       texTarget = "RECT";
2054    else
2055       texTarget = "2D";
2056    _mesa_snprintf(program2, sizeof(program2), program, texTarget);
2057
2058    _mesa_GenProgramsARB(1, &drawpix->StencilFP);
2059    _mesa_BindProgramARB(GL_FRAGMENT_PROGRAM_ARB, drawpix->StencilFP);
2060    _mesa_ProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2061                           strlen(program2), (const GLubyte *) program2);
2062 }
2063
2064
2065 /**
2066  * One-time init for drawing depth pixels.
2067  */
2068 static void
2069 init_draw_depth_pixels(struct gl_context *ctx)
2070 {
2071    static const char *program =
2072       "!!ARBfp1.0\n"
2073       "PARAM color = program.local[0]; \n"
2074       "TEX result.depth, fragment.texcoord[0], texture[0], %s; \n"
2075       "MOV result.color, color; \n"
2076       "END \n";
2077    char program2[200];
2078    struct drawpix_state *drawpix = &ctx->Meta->DrawPix;
2079    struct temp_texture *tex = _mesa_meta_get_temp_texture(ctx);
2080    const char *texTarget;
2081
2082    assert(drawpix->DepthFP == 0);
2083
2084    /* replace %s with "RECT" or "2D" */
2085    assert(strlen(program) + 4 < sizeof(program2));
2086    if (tex->Target == GL_TEXTURE_RECTANGLE)
2087       texTarget = "RECT";
2088    else
2089       texTarget = "2D";
2090    _mesa_snprintf(program2, sizeof(program2), program, texTarget);
2091
2092    _mesa_GenProgramsARB(1, &drawpix->DepthFP);
2093    _mesa_BindProgramARB(GL_FRAGMENT_PROGRAM_ARB, drawpix->DepthFP);
2094    _mesa_ProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2095                           strlen(program2), (const GLubyte *) program2);
2096 }
2097
2098
2099 /**
2100  * Meta implementation of ctx->Driver.DrawPixels() in terms
2101  * of texture mapping and polygon rendering.
2102  */
2103 void
2104 _mesa_meta_DrawPixels(struct gl_context *ctx,
2105                       GLint x, GLint y, GLsizei width, GLsizei height,
2106                       GLenum format, GLenum type,
2107                       const struct gl_pixelstore_attrib *unpack,
2108                       const GLvoid *pixels)
2109 {
2110    struct drawpix_state *drawpix = &ctx->Meta->DrawPix;
2111    struct temp_texture *tex = _mesa_meta_get_temp_texture(ctx);
2112    const struct gl_pixelstore_attrib unpackSave = ctx->Unpack;
2113    const GLuint origStencilMask = ctx->Stencil.WriteMask[0];
2114    struct vertex verts[4];
2115    GLenum texIntFormat;
2116    GLboolean fallback, newTex;
2117    GLbitfield metaExtraSave = 0x0;
2118
2119    /*
2120     * Determine if we can do the glDrawPixels with texture mapping.
2121     */
2122    fallback = GL_FALSE;
2123    if (ctx->Fog.Enabled) {
2124       fallback = GL_TRUE;
2125    }
2126
2127    if (_mesa_is_color_format(format)) {
2128       /* use more compact format when possible */
2129       /* XXX disable special case for GL_LUMINANCE for now to work around
2130        * apparent i965 driver bug (see bug #23670).
2131        */
2132       if (/*format == GL_LUMINANCE ||*/ format == GL_LUMINANCE_ALPHA)
2133          texIntFormat = format;
2134       else
2135          texIntFormat = GL_RGBA;
2136
2137       /* If we're not supposed to clamp the resulting color, then just
2138        * promote our texture to fully float.  We could do better by
2139        * just going for the matching set of channels, in floating
2140        * point.
2141        */
2142       if (ctx->Color.ClampFragmentColor != GL_TRUE &&
2143           ctx->Extensions.ARB_texture_float)
2144          texIntFormat = GL_RGBA32F;
2145    }
2146    else if (_mesa_is_stencil_format(format)) {
2147       if (ctx->Extensions.ARB_fragment_program &&
2148           ctx->Pixel.IndexShift == 0 &&
2149           ctx->Pixel.IndexOffset == 0 &&
2150           type == GL_UNSIGNED_BYTE) {
2151          /* We'll store stencil as alpha.  This only works for GLubyte
2152           * image data because of how incoming values are mapped to alpha
2153           * in [0,1].
2154           */
2155          texIntFormat = GL_ALPHA;
2156          metaExtraSave = (MESA_META_COLOR_MASK |
2157                           MESA_META_DEPTH_TEST |
2158                           MESA_META_PIXEL_TRANSFER |
2159                           MESA_META_SHADER |
2160                           MESA_META_STENCIL_TEST);
2161       }
2162       else {
2163          fallback = GL_TRUE;
2164       }
2165    }
2166    else if (_mesa_is_depth_format(format)) {
2167       if (ctx->Extensions.ARB_depth_texture &&
2168           ctx->Extensions.ARB_fragment_program) {
2169          texIntFormat = GL_DEPTH_COMPONENT;
2170          metaExtraSave = (MESA_META_SHADER);
2171       }
2172       else {
2173          fallback = GL_TRUE;
2174       }
2175    }
2176    else {
2177       fallback = GL_TRUE;
2178    }
2179
2180    if (fallback) {
2181       _swrast_DrawPixels(ctx, x, y, width, height,
2182                          format, type, unpack, pixels);
2183       return;
2184    }
2185
2186    /*
2187     * Check image size against max texture size, draw as tiles if needed.
2188     */
2189    if (width > tex->MaxSize || height > tex->MaxSize) {
2190       tiled_draw_pixels(ctx, tex->MaxSize, x, y, width, height,
2191                         format, type, unpack, pixels);
2192       return;
2193    }
2194
2195    /* Most GL state applies to glDrawPixels (like blending, stencil, etc),
2196     * but a there's a few things we need to override:
2197     */
2198    _mesa_meta_begin(ctx, (MESA_META_RASTERIZATION |
2199                           MESA_META_SHADER |
2200                           MESA_META_TEXTURE |
2201                           MESA_META_TRANSFORM |
2202                           MESA_META_CLIP |
2203                           MESA_META_VERTEX |
2204                           MESA_META_VIEWPORT |
2205                           metaExtraSave));
2206
2207    newTex = _mesa_meta_alloc_texture(tex, width, height, texIntFormat);
2208
2209    _mesa_meta_setup_vertex_objects(ctx, &drawpix->VAO, &drawpix->buf_obj, false,
2210                                    3, 2, 0);
2211
2212    /* Silence valgrind warnings about reading uninitialized stack. */
2213    memset(verts, 0, sizeof(verts));
2214
2215    /* vertex positions, texcoords (after texture allocation!) */
2216    {
2217       const GLfloat x0 = (GLfloat) x;
2218       const GLfloat y0 = (GLfloat) y;
2219       const GLfloat x1 = x + width * ctx->Pixel.ZoomX;
2220       const GLfloat y1 = y + height * ctx->Pixel.ZoomY;
2221       const GLfloat z = invert_z(ctx->Current.RasterPos[2]);
2222
2223       verts[0].x = x0;
2224       verts[0].y = y0;
2225       verts[0].z = z;
2226       verts[0].tex[0] = 0.0F;
2227       verts[0].tex[1] = 0.0F;
2228       verts[1].x = x1;
2229       verts[1].y = y0;
2230       verts[1].z = z;
2231       verts[1].tex[0] = tex->Sright;
2232       verts[1].tex[1] = 0.0F;
2233       verts[2].x = x1;
2234       verts[2].y = y1;
2235       verts[2].z = z;
2236       verts[2].tex[0] = tex->Sright;
2237       verts[2].tex[1] = tex->Ttop;
2238       verts[3].x = x0;
2239       verts[3].y = y1;
2240       verts[3].z = z;
2241       verts[3].tex[0] = 0.0F;
2242       verts[3].tex[1] = tex->Ttop;
2243    }
2244
2245    /* upload new vertex data */
2246    _mesa_buffer_data(ctx, drawpix->buf_obj, GL_NONE, sizeof(verts), verts,
2247                      GL_DYNAMIC_DRAW, __func__);
2248
2249    /* set given unpack params */
2250    ctx->Unpack = *unpack;
2251
2252    _mesa_set_enable(ctx, tex->Target, GL_TRUE);
2253
2254    if (_mesa_is_stencil_format(format)) {
2255       /* Drawing stencil */
2256       GLint bit;
2257
2258       if (!drawpix->StencilFP)
2259          init_draw_stencil_pixels(ctx);
2260
2261       _mesa_meta_setup_drawpix_texture(ctx, tex, newTex, width, height,
2262                                        GL_ALPHA, type, pixels);
2263
2264       _mesa_ColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2265
2266       _mesa_set_enable(ctx, GL_STENCIL_TEST, GL_TRUE);
2267
2268       /* set all stencil bits to 0 */
2269       _mesa_StencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
2270       _mesa_StencilFunc(GL_ALWAYS, 0, 255);
2271       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
2272   
2273       /* set stencil bits to 1 where needed */
2274       _mesa_StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
2275
2276       _mesa_BindProgramARB(GL_FRAGMENT_PROGRAM_ARB, drawpix->StencilFP);
2277       _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB, GL_TRUE);
2278
2279       for (bit = 0; bit < ctx->DrawBuffer->Visual.stencilBits; bit++) {
2280          const GLuint mask = 1 << bit;
2281          if (mask & origStencilMask) {
2282             _mesa_StencilFunc(GL_ALWAYS, mask, mask);
2283             _mesa_StencilMask(mask);
2284
2285             _mesa_ProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0,
2286                                              255.0f / mask, 0.5f, 0.0f, 0.0f);
2287
2288             _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
2289          }
2290       }
2291    }
2292    else if (_mesa_is_depth_format(format)) {
2293       /* Drawing depth */
2294       if (!drawpix->DepthFP)
2295          init_draw_depth_pixels(ctx);
2296
2297       _mesa_BindProgramARB(GL_FRAGMENT_PROGRAM_ARB, drawpix->DepthFP);
2298       _mesa_set_enable(ctx, GL_FRAGMENT_PROGRAM_ARB, GL_TRUE);
2299
2300       /* polygon color = current raster color */
2301       _mesa_ProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0,
2302                                         ctx->Current.RasterColor);
2303
2304       _mesa_meta_setup_drawpix_texture(ctx, tex, newTex, width, height,
2305                                        format, type, pixels);
2306
2307       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
2308    }
2309    else {
2310       /* Drawing RGBA */
2311       _mesa_meta_setup_drawpix_texture(ctx, tex, newTex, width, height,
2312                                        format, type, pixels);
2313       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
2314    }
2315
2316    _mesa_set_enable(ctx, tex->Target, GL_FALSE);
2317
2318    /* restore unpack params */
2319    ctx->Unpack = unpackSave;
2320
2321    _mesa_meta_end(ctx);
2322 }
2323
2324 static GLboolean
2325 alpha_test_raster_color(struct gl_context *ctx)
2326 {
2327    GLfloat alpha = ctx->Current.RasterColor[ACOMP];
2328    GLfloat ref = ctx->Color.AlphaRef;
2329
2330    switch (ctx->Color.AlphaFunc) {
2331       case GL_NEVER:
2332          return GL_FALSE;
2333       case GL_LESS:
2334          return alpha < ref;
2335       case GL_EQUAL:
2336          return alpha == ref;
2337       case GL_LEQUAL:
2338          return alpha <= ref;
2339       case GL_GREATER:
2340          return alpha > ref;
2341       case GL_NOTEQUAL:
2342          return alpha != ref;
2343       case GL_GEQUAL:
2344          return alpha >= ref;
2345       case GL_ALWAYS:
2346          return GL_TRUE;
2347       default:
2348          assert(0);
2349          return GL_FALSE;
2350    }
2351 }
2352
2353 /**
2354  * Do glBitmap with a alpha texture quad.  Use the alpha test to cull
2355  * the 'off' bits.  A bitmap cache as in the gallium/mesa state
2356  * tracker would improve performance a lot.
2357  */
2358 void
2359 _mesa_meta_Bitmap(struct gl_context *ctx,
2360                   GLint x, GLint y, GLsizei width, GLsizei height,
2361                   const struct gl_pixelstore_attrib *unpack,
2362                   const GLubyte *bitmap1)
2363 {
2364    struct bitmap_state *bitmap = &ctx->Meta->Bitmap;
2365    struct temp_texture *tex = get_bitmap_temp_texture(ctx);
2366    const GLenum texIntFormat = GL_ALPHA;
2367    const struct gl_pixelstore_attrib unpackSave = *unpack;
2368    GLubyte fg, bg;
2369    struct vertex verts[4];
2370    GLboolean newTex;
2371    GLubyte *bitmap8;
2372
2373    /*
2374     * Check if swrast fallback is needed.
2375     */
2376    if (ctx->_ImageTransferState ||
2377        ctx->FragmentProgram._Enabled ||
2378        ctx->Fog.Enabled ||
2379        ctx->Texture._MaxEnabledTexImageUnit != -1 ||
2380        width > tex->MaxSize ||
2381        height > tex->MaxSize) {
2382       _swrast_Bitmap(ctx, x, y, width, height, unpack, bitmap1);
2383       return;
2384    }
2385
2386    if (ctx->Color.AlphaEnabled && !alpha_test_raster_color(ctx))
2387       return;
2388
2389    /* Most GL state applies to glBitmap (like blending, stencil, etc),
2390     * but a there's a few things we need to override:
2391     */
2392    _mesa_meta_begin(ctx, (MESA_META_ALPHA_TEST |
2393                           MESA_META_PIXEL_STORE |
2394                           MESA_META_RASTERIZATION |
2395                           MESA_META_SHADER |
2396                           MESA_META_TEXTURE |
2397                           MESA_META_TRANSFORM |
2398                           MESA_META_CLIP |
2399                           MESA_META_VERTEX |
2400                           MESA_META_VIEWPORT));
2401
2402    _mesa_meta_setup_vertex_objects(ctx, &bitmap->VAO, &bitmap->buf_obj, false,
2403                                    3, 2, 4);
2404
2405    newTex = _mesa_meta_alloc_texture(tex, width, height, texIntFormat);
2406
2407    /* Silence valgrind warnings about reading uninitialized stack. */
2408    memset(verts, 0, sizeof(verts));
2409
2410    /* vertex positions, texcoords, colors (after texture allocation!) */
2411    {
2412       const GLfloat x0 = (GLfloat) x;
2413       const GLfloat y0 = (GLfloat) y;
2414       const GLfloat x1 = (GLfloat) (x + width);
2415       const GLfloat y1 = (GLfloat) (y + height);
2416       const GLfloat z = invert_z(ctx->Current.RasterPos[2]);
2417       GLuint i;
2418
2419       verts[0].x = x0;
2420       verts[0].y = y0;
2421       verts[0].z = z;
2422       verts[0].tex[0] = 0.0F;
2423       verts[0].tex[1] = 0.0F;
2424       verts[1].x = x1;
2425       verts[1].y = y0;
2426       verts[1].z = z;
2427       verts[1].tex[0] = tex->Sright;
2428       verts[1].tex[1] = 0.0F;
2429       verts[2].x = x1;
2430       verts[2].y = y1;
2431       verts[2].z = z;
2432       verts[2].tex[0] = tex->Sright;
2433       verts[2].tex[1] = tex->Ttop;
2434       verts[3].x = x0;
2435       verts[3].y = y1;
2436       verts[3].z = z;
2437       verts[3].tex[0] = 0.0F;
2438       verts[3].tex[1] = tex->Ttop;
2439
2440       for (i = 0; i < 4; i++) {
2441          verts[i].r = ctx->Current.RasterColor[0];
2442          verts[i].g = ctx->Current.RasterColor[1];
2443          verts[i].b = ctx->Current.RasterColor[2];
2444          verts[i].a = ctx->Current.RasterColor[3];
2445       }
2446
2447       /* upload new vertex data */
2448       _mesa_buffer_sub_data(ctx, bitmap->buf_obj, 0, sizeof(verts), verts,
2449                             __func__);
2450    }
2451
2452    /* choose different foreground/background alpha values */
2453    CLAMPED_FLOAT_TO_UBYTE(fg, ctx->Current.RasterColor[ACOMP]);
2454    bg = (fg > 127 ? 0 : 255);
2455
2456    bitmap1 = _mesa_map_pbo_source(ctx, &unpackSave, bitmap1);
2457    if (!bitmap1) {
2458       _mesa_meta_end(ctx);
2459       return;
2460    }
2461
2462    bitmap8 = malloc(width * height);
2463    if (bitmap8) {
2464       memset(bitmap8, bg, width * height);
2465       _mesa_expand_bitmap(width, height, &unpackSave, bitmap1,
2466                           bitmap8, width, fg);
2467
2468       _mesa_set_enable(ctx, tex->Target, GL_TRUE);
2469
2470       _mesa_set_enable(ctx, GL_ALPHA_TEST, GL_TRUE);
2471       _mesa_AlphaFunc(GL_NOTEQUAL, UBYTE_TO_FLOAT(bg));
2472
2473       _mesa_meta_setup_drawpix_texture(ctx, tex, newTex, width, height,
2474                                        GL_ALPHA, GL_UNSIGNED_BYTE, bitmap8);
2475
2476       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
2477
2478       _mesa_set_enable(ctx, tex->Target, GL_FALSE);
2479
2480       free(bitmap8);
2481    }
2482
2483    _mesa_unmap_pbo_source(ctx, &unpackSave);
2484
2485    _mesa_meta_end(ctx);
2486 }
2487
2488 /**
2489  * Compute the texture coordinates for the four vertices of a quad for
2490  * drawing a 2D texture image or slice of a cube/3D texture.  The offset
2491  * and width, height specify a sub-region of the 2D image.
2492  *
2493  * \param faceTarget  GL_TEXTURE_1D/2D/3D or cube face name
2494  * \param slice  slice of a 1D/2D array texture or 3D texture
2495  * \param xoffset  X position of sub texture
2496  * \param yoffset  Y position of sub texture
2497  * \param width  width of the sub texture image
2498  * \param height  height of the sub texture image
2499  * \param total_width  total width of the texture image
2500  * \param total_height  total height of the texture image
2501  * \param total_depth  total depth of the texture image
2502  * \param coords0/1/2/3  returns the computed texcoords
2503  */
2504 void
2505 _mesa_meta_setup_texture_coords(GLenum faceTarget,
2506                                 GLint slice,
2507                                 GLint xoffset,
2508                                 GLint yoffset,
2509                                 GLint width,
2510                                 GLint height,
2511                                 GLint total_width,
2512                                 GLint total_height,
2513                                 GLint total_depth,
2514                                 GLfloat coords0[4],
2515                                 GLfloat coords1[4],
2516                                 GLfloat coords2[4],
2517                                 GLfloat coords3[4])
2518 {
2519    float st[4][2];
2520    GLuint i;
2521    const float s0 = (float) xoffset / (float) total_width;
2522    const float s1 = (float) (xoffset + width) / (float) total_width;
2523    const float t0 = (float) yoffset / (float) total_height;
2524    const float t1 = (float) (yoffset + height) / (float) total_height;
2525    GLfloat r;
2526
2527    /* setup the reference texcoords */
2528    st[0][0] = s0;
2529    st[0][1] = t0;
2530    st[1][0] = s1;
2531    st[1][1] = t0;
2532    st[2][0] = s1;
2533    st[2][1] = t1;
2534    st[3][0] = s0;
2535    st[3][1] = t1;
2536
2537    if (faceTarget == GL_TEXTURE_CUBE_MAP_ARRAY)
2538       faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice % 6;
2539
2540    /* Currently all texture targets want the W component to be 1.0.
2541     */
2542    coords0[3] = 1.0F;
2543    coords1[3] = 1.0F;
2544    coords2[3] = 1.0F;
2545    coords3[3] = 1.0F;
2546
2547    switch (faceTarget) {
2548    case GL_TEXTURE_1D:
2549    case GL_TEXTURE_2D:
2550    case GL_TEXTURE_3D:
2551    case GL_TEXTURE_2D_ARRAY:
2552       if (faceTarget == GL_TEXTURE_3D) {
2553          assert(slice < total_depth);
2554          assert(total_depth >= 1);
2555          r = (slice + 0.5f) / total_depth;
2556       }
2557       else if (faceTarget == GL_TEXTURE_2D_ARRAY)
2558          r = (float) slice;
2559       else
2560          r = 0.0F;
2561       coords0[0] = st[0][0]; /* s */
2562       coords0[1] = st[0][1]; /* t */
2563       coords0[2] = r; /* r */
2564       coords1[0] = st[1][0];
2565       coords1[1] = st[1][1];
2566       coords1[2] = r;
2567       coords2[0] = st[2][0];
2568       coords2[1] = st[2][1];
2569       coords2[2] = r;
2570       coords3[0] = st[3][0];
2571       coords3[1] = st[3][1];
2572       coords3[2] = r;
2573       break;
2574    case GL_TEXTURE_RECTANGLE_ARB:
2575       coords0[0] = (float) xoffset; /* s */
2576       coords0[1] = (float) yoffset; /* t */
2577       coords0[2] = 0.0F; /* r */
2578       coords1[0] = (float) (xoffset + width);
2579       coords1[1] = (float) yoffset;
2580       coords1[2] = 0.0F;
2581       coords2[0] = (float) (xoffset + width);
2582       coords2[1] = (float) (yoffset + height);
2583       coords2[2] = 0.0F;
2584       coords3[0] = (float) xoffset;
2585       coords3[1] = (float) (yoffset + height);
2586       coords3[2] = 0.0F;
2587       break;
2588    case GL_TEXTURE_1D_ARRAY:
2589       coords0[0] = st[0][0]; /* s */
2590       coords0[1] = (float) slice; /* t */
2591       coords0[2] = 0.0F; /* r */
2592       coords1[0] = st[1][0];
2593       coords1[1] = (float) slice;
2594       coords1[2] = 0.0F;
2595       coords2[0] = st[2][0];
2596       coords2[1] = (float) slice;
2597       coords2[2] = 0.0F;
2598       coords3[0] = st[3][0];
2599       coords3[1] = (float) slice;
2600       coords3[2] = 0.0F;
2601       break;
2602
2603    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
2604    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
2605    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
2606    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
2607    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
2608    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
2609       /* loop over quad verts */
2610       for (i = 0; i < 4; i++) {
2611          /* Compute sc = +/-scale and tc = +/-scale.
2612           * Not +/-1 to avoid cube face selection ambiguity near the edges,
2613           * though that can still sometimes happen with this scale factor...
2614           */
2615          const GLfloat scale = 0.9999f;
2616          const GLfloat sc = (2.0f * st[i][0] - 1.0f) * scale;
2617          const GLfloat tc = (2.0f * st[i][1] - 1.0f) * scale;
2618          GLfloat *coord;
2619
2620          switch (i) {
2621          case 0:
2622             coord = coords0;
2623             break;
2624          case 1:
2625             coord = coords1;
2626             break;
2627          case 2:
2628             coord = coords2;
2629             break;
2630          case 3:
2631             coord = coords3;
2632             break;
2633          default:
2634             unreachable("not reached");
2635          }
2636
2637          coord[3] = (float) (slice / 6);
2638
2639          switch (faceTarget) {
2640          case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
2641             coord[0] = 1.0f;
2642             coord[1] = -tc;
2643             coord[2] = -sc;
2644             break;
2645          case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
2646             coord[0] = -1.0f;
2647             coord[1] = -tc;
2648             coord[2] = sc;
2649             break;
2650          case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
2651             coord[0] = sc;
2652             coord[1] = 1.0f;
2653             coord[2] = tc;
2654             break;
2655          case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
2656             coord[0] = sc;
2657             coord[1] = -1.0f;
2658             coord[2] = -tc;
2659             break;
2660          case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
2661             coord[0] = sc;
2662             coord[1] = -tc;
2663             coord[2] = 1.0f;
2664             break;
2665          case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
2666             coord[0] = -sc;
2667             coord[1] = -tc;
2668             coord[2] = -1.0f;
2669             break;
2670          default:
2671             assert(0);
2672          }
2673       }
2674       break;
2675    default:
2676       assert(!"unexpected target in _mesa_meta_setup_texture_coords()");
2677    }
2678 }
2679
2680 static struct blit_shader *
2681 choose_blit_shader(GLenum target, struct blit_shader_table *table)
2682 {
2683    switch(target) {
2684    case GL_TEXTURE_1D:
2685       table->sampler_1d.type = "sampler1D";
2686       table->sampler_1d.func = "texture1D";
2687       table->sampler_1d.texcoords = "texCoords.x";
2688       return &table->sampler_1d;
2689    case GL_TEXTURE_2D:
2690       table->sampler_2d.type = "sampler2D";
2691       table->sampler_2d.func = "texture2D";
2692       table->sampler_2d.texcoords = "texCoords.xy";
2693       return &table->sampler_2d;
2694    case GL_TEXTURE_RECTANGLE:
2695       table->sampler_rect.type = "sampler2DRect";
2696       table->sampler_rect.func = "texture2DRect";
2697       table->sampler_rect.texcoords = "texCoords.xy";
2698       return &table->sampler_rect;
2699    case GL_TEXTURE_3D:
2700       /* Code for mipmap generation with 3D textures is not used yet.
2701        * It's a sw fallback.
2702        */
2703       table->sampler_3d.type = "sampler3D";
2704       table->sampler_3d.func = "texture3D";
2705       table->sampler_3d.texcoords = "texCoords.xyz";
2706       return &table->sampler_3d;
2707    case GL_TEXTURE_CUBE_MAP:
2708       table->sampler_cubemap.type = "samplerCube";
2709       table->sampler_cubemap.func = "textureCube";
2710       table->sampler_cubemap.texcoords = "texCoords.xyz";
2711       return &table->sampler_cubemap;
2712    case GL_TEXTURE_1D_ARRAY:
2713       table->sampler_1d_array.type = "sampler1DArray";
2714       table->sampler_1d_array.func = "texture1DArray";
2715       table->sampler_1d_array.texcoords = "texCoords.xy";
2716       return &table->sampler_1d_array;
2717    case GL_TEXTURE_2D_ARRAY:
2718       table->sampler_2d_array.type = "sampler2DArray";
2719       table->sampler_2d_array.func = "texture2DArray";
2720       table->sampler_2d_array.texcoords = "texCoords.xyz";
2721       return &table->sampler_2d_array;
2722    case GL_TEXTURE_CUBE_MAP_ARRAY:
2723       table->sampler_cubemap_array.type = "samplerCubeArray";
2724       table->sampler_cubemap_array.func = "textureCubeArray";
2725       table->sampler_cubemap_array.texcoords = "texCoords.xyzw";
2726       return &table->sampler_cubemap_array;
2727    default:
2728       _mesa_problem(NULL, "Unexpected texture target 0x%x in"
2729                     " setup_texture_sampler()\n", target);
2730       return NULL;
2731    }
2732 }
2733
2734 void
2735 _mesa_meta_blit_shader_table_cleanup(struct blit_shader_table *table)
2736 {
2737    _mesa_DeleteProgram(table->sampler_1d.shader_prog);
2738    _mesa_DeleteProgram(table->sampler_2d.shader_prog);
2739    _mesa_DeleteProgram(table->sampler_3d.shader_prog);
2740    _mesa_DeleteProgram(table->sampler_rect.shader_prog);
2741    _mesa_DeleteProgram(table->sampler_cubemap.shader_prog);
2742    _mesa_DeleteProgram(table->sampler_1d_array.shader_prog);
2743    _mesa_DeleteProgram(table->sampler_2d_array.shader_prog);
2744    _mesa_DeleteProgram(table->sampler_cubemap_array.shader_prog);
2745
2746    table->sampler_1d.shader_prog = 0;
2747    table->sampler_2d.shader_prog = 0;
2748    table->sampler_3d.shader_prog = 0;
2749    table->sampler_rect.shader_prog = 0;
2750    table->sampler_cubemap.shader_prog = 0;
2751    table->sampler_1d_array.shader_prog = 0;
2752    table->sampler_2d_array.shader_prog = 0;
2753    table->sampler_cubemap_array.shader_prog = 0;
2754 }
2755
2756 /**
2757  * Determine the GL data type to use for the temporary image read with
2758  * ReadPixels() and passed to Tex[Sub]Image().
2759  */
2760 static GLenum
2761 get_temp_image_type(struct gl_context *ctx, mesa_format format)
2762 {
2763    const GLenum baseFormat = _mesa_get_format_base_format(format);
2764    const GLenum datatype = _mesa_get_format_datatype(format);
2765    const GLint format_red_bits = _mesa_get_format_bits(format, GL_RED_BITS);
2766
2767    switch (baseFormat) {
2768    case GL_RGBA:
2769    case GL_RGB:
2770    case GL_RG:
2771    case GL_RED:
2772    case GL_ALPHA:
2773    case GL_LUMINANCE:
2774    case GL_LUMINANCE_ALPHA:
2775    case GL_INTENSITY:
2776       if (datatype == GL_INT || datatype == GL_UNSIGNED_INT) {
2777          return datatype;
2778       } else if (format_red_bits <= 8) {
2779          return GL_UNSIGNED_BYTE;
2780       } else if (format_red_bits <= 16) {
2781          return GL_UNSIGNED_SHORT;
2782       }
2783       return GL_FLOAT;
2784    case GL_DEPTH_COMPONENT:
2785       if (datatype == GL_FLOAT)
2786          return GL_FLOAT;
2787       else
2788          return GL_UNSIGNED_INT;
2789    case GL_DEPTH_STENCIL:
2790       if (datatype == GL_FLOAT)
2791          return GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
2792       else
2793          return GL_UNSIGNED_INT_24_8;
2794    default:
2795       _mesa_problem(ctx, "Unexpected format %d in get_temp_image_type()",
2796                     baseFormat);
2797       return 0;
2798    }
2799 }
2800
2801 /**
2802  * Attempts to wrap the destination texture in an FBO and use
2803  * glBlitFramebuffer() to implement glCopyTexSubImage().
2804  */
2805 static bool
2806 copytexsubimage_using_blit_framebuffer(struct gl_context *ctx, GLuint dims,
2807                                        struct gl_texture_image *texImage,
2808                                        GLint xoffset,
2809                                        GLint yoffset,
2810                                        GLint zoffset,
2811                                        struct gl_renderbuffer *rb,
2812                                        GLint x, GLint y,
2813                                        GLsizei width, GLsizei height)
2814 {
2815    GLuint fbo;
2816    bool success = false;
2817    GLbitfield mask;
2818    GLenum status;
2819
2820    if (!ctx->Extensions.ARB_framebuffer_object)
2821       return false;
2822
2823    _mesa_meta_begin(ctx, MESA_META_ALL & ~MESA_META_DRAW_BUFFERS);
2824
2825    _mesa_GenFramebuffers(1, &fbo);
2826    _mesa_BindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
2827
2828    if (rb->_BaseFormat == GL_DEPTH_STENCIL ||
2829        rb->_BaseFormat == GL_DEPTH_COMPONENT) {
2830       _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
2831                                 texImage, zoffset);
2832       mask = GL_DEPTH_BUFFER_BIT;
2833
2834       if (rb->_BaseFormat == GL_DEPTH_STENCIL &&
2835           texImage->_BaseFormat == GL_DEPTH_STENCIL) {
2836          _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
2837                                    texImage, zoffset);
2838          mask |= GL_STENCIL_BUFFER_BIT;
2839       }
2840       _mesa_DrawBuffer(GL_NONE);
2841    } else {
2842       _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2843                                 texImage, zoffset);
2844       mask = GL_COLOR_BUFFER_BIT;
2845       _mesa_DrawBuffer(GL_COLOR_ATTACHMENT0);
2846    }
2847
2848    status = _mesa_CheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
2849    if (status != GL_FRAMEBUFFER_COMPLETE)
2850       goto out;
2851
2852    ctx->Meta->Blit.no_ctsi_fallback = true;
2853
2854    /* Since we've bound a new draw framebuffer, we need to update
2855     * its derived state -- _Xmin, etc -- for BlitFramebuffer's clipping to
2856     * be correct.
2857     */
2858    _mesa_update_state(ctx);
2859
2860    /* We skip the core BlitFramebuffer checks for format consistency, which
2861     * are too strict for CopyTexImage.  We know meta will be fine with format
2862     * changes.
2863     */
2864    mask = _mesa_meta_BlitFramebuffer(ctx, ctx->ReadBuffer, ctx->DrawBuffer,
2865                                      x, y,
2866                                      x + width, y + height,
2867                                      xoffset, yoffset,
2868                                      xoffset + width, yoffset + height,
2869                                      mask, GL_NEAREST);
2870    ctx->Meta->Blit.no_ctsi_fallback = false;
2871    success = mask == 0x0;
2872
2873  out:
2874    _mesa_DeleteFramebuffers(1, &fbo);
2875    _mesa_meta_end(ctx);
2876    return success;
2877 }
2878
2879 /**
2880  * Helper for _mesa_meta_CopyTexSubImage1/2/3D() functions.
2881  * Have to be careful with locking and meta state for pixel transfer.
2882  */
2883 void
2884 _mesa_meta_CopyTexSubImage(struct gl_context *ctx, GLuint dims,
2885                            struct gl_texture_image *texImage,
2886                            GLint xoffset, GLint yoffset, GLint zoffset,
2887                            struct gl_renderbuffer *rb,
2888                            GLint x, GLint y,
2889                            GLsizei width, GLsizei height)
2890 {
2891    GLenum format, type;
2892    GLint bpp;
2893    void *buf;
2894
2895    if (copytexsubimage_using_blit_framebuffer(ctx, dims,
2896                                               texImage,
2897                                               xoffset, yoffset, zoffset,
2898                                               rb,
2899                                               x, y,
2900                                               width, height)) {
2901       return;
2902    }
2903
2904    /* Choose format/type for temporary image buffer */
2905    format = _mesa_get_format_base_format(texImage->TexFormat);
2906    if (format == GL_LUMINANCE ||
2907        format == GL_LUMINANCE_ALPHA ||
2908        format == GL_INTENSITY) {
2909       /* We don't want to use GL_LUMINANCE, GL_INTENSITY, etc. for the
2910        * temp image buffer because glReadPixels will do L=R+G+B which is
2911        * not what we want (should be L=R).
2912        */
2913       format = GL_RGBA;
2914    }
2915
2916    type = get_temp_image_type(ctx, texImage->TexFormat);
2917    if (_mesa_is_format_integer_color(texImage->TexFormat)) {
2918       format = _mesa_base_format_to_integer_format(format);
2919    }
2920    bpp = _mesa_bytes_per_pixel(format, type);
2921    if (bpp <= 0) {
2922       _mesa_problem(ctx, "Bad bpp in _mesa_meta_CopyTexSubImage()");
2923       return;
2924    }
2925
2926    /*
2927     * Alloc image buffer (XXX could use a PBO)
2928     */
2929    buf = malloc(width * height * bpp);
2930    if (!buf) {
2931       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyTexSubImage%uD", dims);
2932       return;
2933    }
2934
2935    /*
2936     * Read image from framebuffer (disable pixel transfer ops)
2937     */
2938    _mesa_meta_begin(ctx, MESA_META_PIXEL_STORE | MESA_META_PIXEL_TRANSFER);
2939    ctx->Driver.ReadPixels(ctx, x, y, width, height,
2940                           format, type, &ctx->Pack, buf);
2941    _mesa_meta_end(ctx);
2942
2943    _mesa_update_state(ctx); /* to update pixel transfer state */
2944
2945    /*
2946     * Store texture data (with pixel transfer ops)
2947     */
2948    _mesa_meta_begin(ctx, MESA_META_PIXEL_STORE);
2949
2950    if (texImage->TexObject->Target == GL_TEXTURE_1D_ARRAY) {
2951       assert(yoffset == 0);
2952       ctx->Driver.TexSubImage(ctx, dims, texImage,
2953                               xoffset, zoffset, 0, width, 1, 1,
2954                               format, type, buf, &ctx->Unpack);
2955    } else {
2956       ctx->Driver.TexSubImage(ctx, dims, texImage,
2957                               xoffset, yoffset, zoffset, width, height, 1,
2958                               format, type, buf, &ctx->Unpack);
2959    }
2960
2961    _mesa_meta_end(ctx);
2962
2963    free(buf);
2964 }
2965
2966 static void
2967 meta_decompress_fbo_cleanup(struct decompress_fbo_state *decompress_fbo)
2968 {
2969    if (decompress_fbo->FBO != 0) {
2970       _mesa_DeleteFramebuffers(1, &decompress_fbo->FBO);
2971       _mesa_DeleteRenderbuffers(1, &decompress_fbo->RBO);
2972    }
2973
2974    memset(decompress_fbo, 0, sizeof(*decompress_fbo));
2975 }
2976
2977 static void
2978 meta_decompress_cleanup(struct gl_context *ctx,
2979                         struct decompress_state *decompress)
2980 {
2981    meta_decompress_fbo_cleanup(&decompress->byteFBO);
2982    meta_decompress_fbo_cleanup(&decompress->floatFBO);
2983
2984    if (decompress->VAO != 0) {
2985       _mesa_DeleteVertexArrays(1, &decompress->VAO);
2986       _mesa_reference_buffer_object(ctx, &decompress->buf_obj, NULL);
2987    }
2988
2989    if (decompress->Sampler != 0)
2990       _mesa_DeleteSamplers(1, &decompress->Sampler);
2991
2992    memset(decompress, 0, sizeof(*decompress));
2993 }
2994
2995 /**
2996  * Decompress a texture image by drawing a quad with the compressed
2997  * texture and reading the pixels out of the color buffer.
2998  * \param slice  which slice of a 3D texture or layer of a 1D/2D texture
2999  * \param destFormat  format, ala glReadPixels
3000  * \param destType  type, ala glReadPixels
3001  * \param dest  destination buffer
3002  * \param destRowLength  dest image rowLength (ala GL_PACK_ROW_LENGTH)
3003  */
3004 static bool
3005 decompress_texture_image(struct gl_context *ctx,
3006                          struct gl_texture_image *texImage,
3007                          GLuint slice,
3008                          GLint xoffset, GLint yoffset,
3009                          GLsizei width, GLsizei height,
3010                          GLenum destFormat, GLenum destType,
3011                          GLvoid *dest)
3012 {
3013    struct decompress_state *decompress = &ctx->Meta->Decompress;
3014    struct decompress_fbo_state *decompress_fbo;
3015    struct gl_texture_object *texObj = texImage->TexObject;
3016    const GLenum target = texObj->Target;
3017    GLenum rbFormat;
3018    GLenum faceTarget;
3019    struct vertex verts[4];
3020    GLuint samplerSave;
3021    GLenum status;
3022    const bool use_glsl_version = ctx->Extensions.ARB_vertex_shader &&
3023                                       ctx->Extensions.ARB_fragment_shader;
3024
3025    switch (_mesa_get_format_datatype(texImage->TexFormat)) {
3026    case GL_FLOAT:
3027       decompress_fbo = &decompress->floatFBO;
3028       rbFormat = GL_RGBA32F;
3029       break;
3030    case GL_UNSIGNED_NORMALIZED:
3031       decompress_fbo = &decompress->byteFBO;
3032       rbFormat = GL_RGBA;
3033       break;
3034    default:
3035       return false;
3036    }
3037
3038    if (slice > 0) {
3039       assert(target == GL_TEXTURE_3D ||
3040              target == GL_TEXTURE_2D_ARRAY ||
3041              target == GL_TEXTURE_CUBE_MAP_ARRAY);
3042    }
3043
3044    switch (target) {
3045    case GL_TEXTURE_1D:
3046    case GL_TEXTURE_1D_ARRAY:
3047       assert(!"No compressed 1D textures.");
3048       return false;
3049
3050    case GL_TEXTURE_3D:
3051       assert(!"No compressed 3D textures.");
3052       return false;
3053
3054    case GL_TEXTURE_CUBE_MAP_ARRAY:
3055       faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + (slice % 6);
3056       break;
3057
3058    case GL_TEXTURE_CUBE_MAP:
3059       faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + texImage->Face;
3060       break;
3061
3062    default:
3063       faceTarget = target;
3064       break;
3065    }
3066
3067    _mesa_meta_begin(ctx, MESA_META_ALL & ~(MESA_META_PIXEL_STORE |
3068                                            MESA_META_DRAW_BUFFERS));
3069
3070    samplerSave = ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler ?
3071          ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler->Name : 0;
3072
3073    /* Create/bind FBO/renderbuffer */
3074    if (decompress_fbo->FBO == 0) {
3075       _mesa_GenFramebuffers(1, &decompress_fbo->FBO);
3076       _mesa_GenRenderbuffers(1, &decompress_fbo->RBO);
3077       _mesa_BindFramebuffer(GL_FRAMEBUFFER_EXT, decompress_fbo->FBO);
3078       _mesa_BindRenderbuffer(GL_RENDERBUFFER_EXT, decompress_fbo->RBO);
3079       _mesa_FramebufferRenderbuffer(GL_FRAMEBUFFER_EXT,
3080                                        GL_COLOR_ATTACHMENT0_EXT,
3081                                        GL_RENDERBUFFER_EXT,
3082                                        decompress_fbo->RBO);
3083    }
3084    else {
3085       _mesa_BindFramebuffer(GL_FRAMEBUFFER_EXT, decompress_fbo->FBO);
3086    }
3087
3088    /* alloc dest surface */
3089    if (width > decompress_fbo->Width || height > decompress_fbo->Height) {
3090       _mesa_BindRenderbuffer(GL_RENDERBUFFER_EXT, decompress_fbo->RBO);
3091       _mesa_RenderbufferStorage(GL_RENDERBUFFER_EXT, rbFormat,
3092                                 width, height);
3093       status = _mesa_CheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
3094       if (status != GL_FRAMEBUFFER_COMPLETE) {
3095          /* If the framebuffer isn't complete then we'll leave
3096           * decompress_fbo->Width as zero so that it will fail again next time
3097           * too */
3098          _mesa_meta_end(ctx);
3099          return false;
3100       }
3101       decompress_fbo->Width = width;
3102       decompress_fbo->Height = height;
3103    }
3104
3105    if (use_glsl_version) {
3106       _mesa_meta_setup_vertex_objects(ctx, &decompress->VAO,
3107                                       &decompress->buf_obj, true,
3108                                       2, 4, 0);
3109
3110       _mesa_meta_setup_blit_shader(ctx, target, false, &decompress->shaders);
3111    } else {
3112       _mesa_meta_setup_ff_tnl_for_blit(ctx, &decompress->VAO,
3113                                        &decompress->buf_obj, 3);
3114    }
3115
3116    if (!decompress->Sampler) {
3117       _mesa_GenSamplers(1, &decompress->Sampler);
3118       _mesa_BindSampler(ctx->Texture.CurrentUnit, decompress->Sampler);
3119       /* nearest filtering */
3120       _mesa_SamplerParameteri(decompress->Sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3121       _mesa_SamplerParameteri(decompress->Sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3122       /* No sRGB decode or encode.*/
3123       if (ctx->Extensions.EXT_texture_sRGB_decode) {
3124          _mesa_SamplerParameteri(decompress->Sampler, GL_TEXTURE_SRGB_DECODE_EXT,
3125                              GL_SKIP_DECODE_EXT);
3126       }
3127
3128    } else {
3129       _mesa_BindSampler(ctx->Texture.CurrentUnit, decompress->Sampler);
3130    }
3131
3132    /* Silence valgrind warnings about reading uninitialized stack. */
3133    memset(verts, 0, sizeof(verts));
3134
3135    _mesa_meta_setup_texture_coords(faceTarget, slice,
3136                                    xoffset, yoffset, width, height,
3137                                    texImage->Width, texImage->Height,
3138                                    texImage->Depth,
3139                                    verts[0].tex,
3140                                    verts[1].tex,
3141                                    verts[2].tex,
3142                                    verts[3].tex);
3143
3144    /* setup vertex positions */
3145    verts[0].x = -1.0F;
3146    verts[0].y = -1.0F;
3147    verts[1].x =  1.0F;
3148    verts[1].y = -1.0F;
3149    verts[2].x =  1.0F;
3150    verts[2].y =  1.0F;
3151    verts[3].x = -1.0F;
3152    verts[3].y =  1.0F;
3153
3154    _mesa_set_viewport(ctx, 0, 0, 0, width, height);
3155
3156    /* upload new vertex data */
3157    _mesa_buffer_sub_data(ctx, decompress->buf_obj, 0, sizeof(verts), verts,
3158                          __func__);
3159
3160    /* setup texture state */
3161    _mesa_BindTexture(target, texObj->Name);
3162
3163    if (!use_glsl_version)
3164       _mesa_set_enable(ctx, target, GL_TRUE);
3165
3166    {
3167       /* save texture object state */
3168       const GLint baseLevelSave = texObj->BaseLevel;
3169       const GLint maxLevelSave = texObj->MaxLevel;
3170
3171       /* restrict sampling to the texture level of interest */
3172       if (target != GL_TEXTURE_RECTANGLE_ARB) {
3173          _mesa_TexParameteri(target, GL_TEXTURE_BASE_LEVEL, texImage->Level);
3174          _mesa_TexParameteri(target, GL_TEXTURE_MAX_LEVEL, texImage->Level);
3175       }
3176
3177       /* render quad w/ texture into renderbuffer */
3178       _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
3179       
3180       /* Restore texture object state, the texture binding will
3181        * be restored by _mesa_meta_end().
3182        */
3183       if (target != GL_TEXTURE_RECTANGLE_ARB) {
3184          _mesa_TexParameteri(target, GL_TEXTURE_BASE_LEVEL, baseLevelSave);
3185          _mesa_TexParameteri(target, GL_TEXTURE_MAX_LEVEL, maxLevelSave);
3186       }
3187
3188    }
3189
3190    /* read pixels from renderbuffer */
3191    {
3192       GLenum baseTexFormat = texImage->_BaseFormat;
3193       GLenum destBaseFormat = _mesa_unpack_format_to_base_format(destFormat);
3194
3195       /* The pixel transfer state will be set to default values at this point
3196        * (see MESA_META_PIXEL_TRANSFER) so pixel transfer ops are effectively
3197        * turned off (as required by glGetTexImage) but we need to handle some
3198        * special cases.  In particular, single-channel texture values are
3199        * returned as red and two-channel texture values are returned as
3200        * red/alpha.
3201        */
3202       if (_mesa_need_luminance_to_rgb_conversion(baseTexFormat,
3203                                                  destBaseFormat) ||
3204           /* If we're reading back an RGB(A) texture (using glGetTexImage) as
3205            * luminance then we need to return L=tex(R).
3206            */
3207           _mesa_need_rgb_to_luminance_conversion(baseTexFormat,
3208                                                  destBaseFormat)) {
3209          /* Green and blue must be zero */
3210          _mesa_PixelTransferf(GL_GREEN_SCALE, 0.0f);
3211          _mesa_PixelTransferf(GL_BLUE_SCALE, 0.0f);
3212       }
3213
3214       _mesa_ReadPixels(0, 0, width, height, destFormat, destType, dest);
3215    }
3216
3217    /* disable texture unit */
3218    if (!use_glsl_version)
3219       _mesa_set_enable(ctx, target, GL_FALSE);
3220
3221    _mesa_BindSampler(ctx->Texture.CurrentUnit, samplerSave);
3222
3223    _mesa_meta_end(ctx);
3224
3225    return true;
3226 }
3227
3228
3229 /**
3230  * This is just a wrapper around _mesa_get_tex_image() and
3231  * decompress_texture_image().  Meta functions should not be directly called
3232  * from core Mesa.
3233  */
3234 void
3235 _mesa_meta_GetTexSubImage(struct gl_context *ctx,
3236                           GLint xoffset, GLint yoffset, GLint zoffset,
3237                           GLsizei width, GLsizei height, GLsizei depth,
3238                           GLenum format, GLenum type, GLvoid *pixels,
3239                           struct gl_texture_image *texImage)
3240 {
3241    if (_mesa_is_format_compressed(texImage->TexFormat)) {
3242       GLuint slice;
3243       bool result = true;
3244
3245       for (slice = 0; slice < depth; slice++) {
3246          void *dst;
3247          if (texImage->TexObject->Target == GL_TEXTURE_2D_ARRAY
3248              || texImage->TexObject->Target == GL_TEXTURE_CUBE_MAP_ARRAY) {
3249             /* Setup pixel packing.  SkipPixels and SkipRows will be applied
3250              * in the decompress_texture_image() function's call to
3251              * glReadPixels but we need to compute the dest slice's address
3252              * here (according to SkipImages and ImageHeight).
3253              */
3254             struct gl_pixelstore_attrib packing = ctx->Pack;
3255             packing.SkipPixels = 0;
3256             packing.SkipRows = 0;
3257             dst = _mesa_image_address3d(&packing, pixels, width, height,
3258                                         format, type, slice, 0, 0);
3259          }
3260          else {
3261             dst = pixels;
3262          }
3263          result = decompress_texture_image(ctx, texImage, slice,
3264                                            xoffset, yoffset, width, height,
3265                                            format, type, dst);
3266          if (!result)
3267             break;
3268       }
3269
3270       if (result)
3271          return;
3272    }
3273
3274    _mesa_GetTexSubImage_sw(ctx, xoffset, yoffset, zoffset,
3275                            width, height, depth, format, type, pixels, texImage);
3276 }
3277
3278
3279 /**
3280  * Meta implementation of ctx->Driver.DrawTex() in terms
3281  * of polygon rendering.
3282  */
3283 void
3284 _mesa_meta_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
3285                    GLfloat width, GLfloat height)
3286 {
3287    struct drawtex_state *drawtex = &ctx->Meta->DrawTex;
3288    struct vertex {
3289       GLfloat x, y, z, st[MAX_TEXTURE_UNITS][2];
3290    };
3291    struct vertex verts[4];
3292    GLuint i;
3293
3294    _mesa_meta_begin(ctx, (MESA_META_RASTERIZATION |
3295                           MESA_META_SHADER |
3296                           MESA_META_TRANSFORM |
3297                           MESA_META_VERTEX |
3298                           MESA_META_VIEWPORT));
3299
3300    if (drawtex->VAO == 0) {
3301       /* one-time setup */
3302       struct gl_vertex_array_object *array_obj;
3303
3304       /* create vertex array object */
3305       _mesa_GenVertexArrays(1, &drawtex->VAO);
3306       _mesa_BindVertexArray(drawtex->VAO);
3307
3308       array_obj = _mesa_lookup_vao(ctx, drawtex->VAO);
3309       assert(array_obj != NULL);
3310
3311       /* create vertex array buffer */
3312       drawtex->buf_obj = ctx->Driver.NewBufferObject(ctx, 0xDEADBEEF);
3313       if (drawtex->buf_obj == NULL)
3314          return;
3315
3316       _mesa_buffer_data(ctx, drawtex->buf_obj, GL_NONE, sizeof(verts), verts,
3317                         GL_DYNAMIC_DRAW, __func__);
3318
3319       /* setup vertex arrays */
3320       _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_POS,
3321                                 3, GL_FLOAT, GL_RGBA, GL_FALSE,
3322                                 GL_FALSE, GL_FALSE,
3323                                 offsetof(struct vertex, x), true);
3324       _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_POS,
3325                                drawtex->buf_obj, 0, sizeof(struct vertex));
3326       _mesa_enable_vertex_array_attrib(ctx, array_obj, VERT_ATTRIB_POS);
3327
3328
3329       for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
3330          _mesa_update_array_format(ctx, array_obj, VERT_ATTRIB_TEX(i),
3331                                    2, GL_FLOAT, GL_RGBA, GL_FALSE,
3332                                    GL_FALSE, GL_FALSE,
3333                                    offsetof(struct vertex, st[i]), true);
3334          _mesa_bind_vertex_buffer(ctx, array_obj, VERT_ATTRIB_TEX(i),
3335                                   drawtex->buf_obj, 0, sizeof(struct vertex));
3336          _mesa_enable_vertex_array_attrib(ctx, array_obj, VERT_ATTRIB_TEX(i));
3337       }
3338    }
3339    else {
3340       _mesa_BindVertexArray(drawtex->VAO);
3341    }
3342
3343    /* vertex positions, texcoords */
3344    {
3345       const GLfloat x1 = x + width;
3346       const GLfloat y1 = y + height;
3347
3348       z = CLAMP(z, 0.0f, 1.0f);
3349       z = invert_z(z);
3350
3351       verts[0].x = x;
3352       verts[0].y = y;
3353       verts[0].z = z;
3354
3355       verts[1].x = x1;
3356       verts[1].y = y;
3357       verts[1].z = z;
3358
3359       verts[2].x = x1;
3360       verts[2].y = y1;
3361       verts[2].z = z;
3362
3363       verts[3].x = x;
3364       verts[3].y = y1;
3365       verts[3].z = z;
3366
3367       for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
3368          const struct gl_texture_object *texObj;
3369          const struct gl_texture_image *texImage;
3370          GLfloat s, t, s1, t1;
3371          GLuint tw, th;
3372
3373          if (!ctx->Texture.Unit[i]._Current) {
3374             GLuint j;
3375             for (j = 0; j < 4; j++) {
3376                verts[j].st[i][0] = 0.0f;
3377                verts[j].st[i][1] = 0.0f;
3378             }
3379             continue;
3380          }
3381
3382          texObj = ctx->Texture.Unit[i]._Current;
3383          texImage = texObj->Image[0][texObj->BaseLevel];
3384          tw = texImage->Width2;
3385          th = texImage->Height2;
3386
3387          s = (GLfloat) texObj->CropRect[0] / tw;
3388          t = (GLfloat) texObj->CropRect[1] / th;
3389          s1 = (GLfloat) (texObj->CropRect[0] + texObj->CropRect[2]) / tw;
3390          t1 = (GLfloat) (texObj->CropRect[1] + texObj->CropRect[3]) / th;
3391
3392          verts[0].st[i][0] = s;
3393          verts[0].st[i][1] = t;
3394
3395          verts[1].st[i][0] = s1;
3396          verts[1].st[i][1] = t;
3397
3398          verts[2].st[i][0] = s1;
3399          verts[2].st[i][1] = t1;
3400
3401          verts[3].st[i][0] = s;
3402          verts[3].st[i][1] = t1;
3403       }
3404
3405       _mesa_buffer_sub_data(ctx, drawtex->buf_obj, 0, sizeof(verts), verts,
3406                             __func__);
3407    }
3408
3409    _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
3410
3411    _mesa_meta_end(ctx);
3412 }
3413
3414 static bool
3415 cleartexsubimage_color(struct gl_context *ctx,
3416                        struct gl_texture_image *texImage,
3417                        const GLvoid *clearValue,
3418                        GLint zoffset)
3419 {
3420    mesa_format format;
3421    union gl_color_union colorValue;
3422    GLenum datatype;
3423    GLenum status;
3424
3425    _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
3426                              texImage, zoffset);
3427
3428    status = _mesa_CheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
3429    if (status != GL_FRAMEBUFFER_COMPLETE)
3430       return false;
3431
3432    /* We don't want to apply an sRGB conversion so override the format */
3433    format = _mesa_get_srgb_format_linear(texImage->TexFormat);
3434    datatype = _mesa_get_format_datatype(format);
3435
3436    switch (datatype) {
3437    case GL_UNSIGNED_INT:
3438    case GL_INT:
3439       if (clearValue)
3440          _mesa_unpack_uint_rgba_row(format, 1, clearValue,
3441                                     (GLuint (*)[4]) colorValue.ui);
3442       else
3443          memset(&colorValue, 0, sizeof colorValue);
3444       if (datatype == GL_INT)
3445          _mesa_ClearBufferiv(GL_COLOR, 0, colorValue.i);
3446       else
3447          _mesa_ClearBufferuiv(GL_COLOR, 0, colorValue.ui);
3448       break;
3449    default:
3450       if (clearValue)
3451          _mesa_unpack_rgba_row(format, 1, clearValue,
3452                                (GLfloat (*)[4]) colorValue.f);
3453       else
3454          memset(&colorValue, 0, sizeof colorValue);
3455       _mesa_ClearBufferfv(GL_COLOR, 0, colorValue.f);
3456       break;
3457    }
3458
3459    return true;
3460 }
3461
3462 static bool
3463 cleartexsubimage_depth_stencil(struct gl_context *ctx,
3464                                struct gl_texture_image *texImage,
3465                                const GLvoid *clearValue,
3466                                GLint zoffset)
3467 {
3468    GLint stencilValue;
3469    GLfloat depthValue;
3470    GLenum status;
3471
3472    _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
3473                              texImage, zoffset);
3474
3475    if (texImage->_BaseFormat == GL_DEPTH_STENCIL)
3476       _mesa_meta_bind_fbo_image(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
3477                                 texImage, zoffset);
3478
3479    status = _mesa_CheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
3480    if (status != GL_FRAMEBUFFER_COMPLETE)
3481       return false;
3482
3483    if (clearValue) {
3484       GLuint depthStencilValue[2];
3485
3486       /* Convert the clearValue from whatever format it's in to a floating
3487        * point value for the depth and an integer value for the stencil index
3488        */
3489       _mesa_unpack_float_32_uint_24_8_depth_stencil_row(texImage->TexFormat,
3490                                                         1, /* n */
3491                                                         clearValue,
3492                                                         depthStencilValue);
3493       /* We need a memcpy here instead of a cast because we need to
3494        * reinterpret the bytes as a float rather than converting it
3495        */
3496       memcpy(&depthValue, depthStencilValue, sizeof depthValue);
3497       stencilValue = depthStencilValue[1] & 0xff;
3498    } else {
3499       depthValue = 0.0f;
3500       stencilValue = 0;
3501    }
3502
3503    if (texImage->_BaseFormat == GL_DEPTH_STENCIL)
3504       _mesa_ClearBufferfi(GL_DEPTH_STENCIL, 0, depthValue, stencilValue);
3505    else
3506       _mesa_ClearBufferfv(GL_DEPTH, 0, &depthValue);
3507
3508    return true;
3509 }
3510
3511 static bool
3512 cleartexsubimage_for_zoffset(struct gl_context *ctx,
3513                              struct gl_texture_image *texImage,
3514                              GLint zoffset,
3515                              const GLvoid *clearValue)
3516 {
3517    GLuint fbo;
3518    bool success;
3519
3520    _mesa_GenFramebuffers(1, &fbo);
3521    _mesa_BindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
3522
3523    switch(texImage->_BaseFormat) {
3524    case GL_DEPTH_STENCIL:
3525    case GL_DEPTH_COMPONENT:
3526       success = cleartexsubimage_depth_stencil(ctx, texImage,
3527                                                clearValue, zoffset);
3528       break;
3529    default:
3530       success = cleartexsubimage_color(ctx, texImage, clearValue, zoffset);
3531       break;
3532    }
3533
3534    _mesa_DeleteFramebuffers(1, &fbo);
3535
3536    return success;
3537 }
3538
3539 static bool
3540 cleartexsubimage_using_fbo(struct gl_context *ctx,
3541                            struct gl_texture_image *texImage,
3542                            GLint xoffset, GLint yoffset, GLint zoffset,
3543                            GLsizei width, GLsizei height, GLsizei depth,
3544                            const GLvoid *clearValue)
3545 {
3546    bool success = true;
3547    GLint z;
3548
3549    _mesa_meta_begin(ctx,
3550                     MESA_META_SCISSOR |
3551                     MESA_META_COLOR_MASK |
3552                     MESA_META_DITHER |
3553                     MESA_META_FRAMEBUFFER_SRGB);
3554
3555    _mesa_set_enable(ctx, GL_DITHER, GL_FALSE);
3556
3557    _mesa_set_enable(ctx, GL_SCISSOR_TEST, GL_TRUE);
3558    _mesa_Scissor(xoffset, yoffset, width, height);
3559
3560    for (z = zoffset; z < zoffset + depth; z++) {
3561       if (!cleartexsubimage_for_zoffset(ctx, texImage, z, clearValue)) {
3562          success = false;
3563          break;
3564       }
3565    }
3566
3567    _mesa_meta_end(ctx);
3568
3569    return success;
3570 }
3571
3572 extern void
3573 _mesa_meta_ClearTexSubImage(struct gl_context *ctx,
3574                             struct gl_texture_image *texImage,
3575                             GLint xoffset, GLint yoffset, GLint zoffset,
3576                             GLsizei width, GLsizei height, GLsizei depth,
3577                             const GLvoid *clearValue)
3578 {
3579    bool res;
3580
3581    res = cleartexsubimage_using_fbo(ctx, texImage,
3582                                     xoffset, yoffset, zoffset,
3583                                     width, height, depth,
3584                                     clearValue);
3585
3586    if (res)
3587       return;
3588
3589    _mesa_warning(ctx,
3590                  "Falling back to mapping the texture in "
3591                  "glClearTexSubImage\n");
3592
3593    _mesa_store_cleartexsubimage(ctx, texImage,
3594                                 xoffset, yoffset, zoffset,
3595                                 width, height, depth,
3596                                 clearValue);
3597 }