Tizen 2.0 Release
[profile/ivi/osmesa.git] / src / mesa / state_tracker / st_cb_drawpixels.c
1 /**************************************************************************
2  * 
3  * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
4  * 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
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  * 
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  * 
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21  * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
22  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  * 
26  **************************************************************************/
27
28  /*
29   * Authors:
30   *   Brian Paul
31   */
32
33 #include "main/imports.h"
34 #include "main/image.h"
35 #include "main/bufferobj.h"
36 #include "main/macros.h"
37 #include "main/mfeatures.h"
38 #include "main/mtypes.h"
39 #include "main/pack.h"
40 #include "main/pbo.h"
41 #include "main/texformat.h"
42 #include "main/teximage.h"
43 #include "main/texstore.h"
44 #include "program/program.h"
45 #include "program/prog_print.h"
46 #include "program/prog_instruction.h"
47
48 #include "st_atom.h"
49 #include "st_atom_constbuf.h"
50 #include "st_cb_drawpixels.h"
51 #include "st_cb_readpixels.h"
52 #include "st_cb_fbo.h"
53 #include "st_context.h"
54 #include "st_debug.h"
55 #include "st_format.h"
56 #include "st_program.h"
57 #include "st_texture.h"
58
59 #include "pipe/p_context.h"
60 #include "pipe/p_defines.h"
61 #include "tgsi/tgsi_ureg.h"
62 #include "util/u_draw_quad.h"
63 #include "util/u_format.h"
64 #include "util/u_inlines.h"
65 #include "util/u_math.h"
66 #include "util/u_tile.h"
67 #include "cso_cache/cso_context.h"
68
69
70 #if FEATURE_drawpix
71
72 /**
73  * Check if the given program is:
74  * 0: MOVE result.color, fragment.color;
75  * 1: END;
76  */
77 static GLboolean
78 is_passthrough_program(const struct gl_fragment_program *prog)
79 {
80    if (prog->Base.NumInstructions == 2) {
81       const struct prog_instruction *inst = prog->Base.Instructions;
82       if (inst[0].Opcode == OPCODE_MOV &&
83           inst[1].Opcode == OPCODE_END &&
84           inst[0].DstReg.File == PROGRAM_OUTPUT &&
85           inst[0].DstReg.Index == FRAG_RESULT_COLOR &&
86           inst[0].DstReg.WriteMask == WRITEMASK_XYZW &&
87           inst[0].SrcReg[0].File == PROGRAM_INPUT &&
88           inst[0].SrcReg[0].Index == FRAG_ATTRIB_COL0 &&
89           inst[0].SrcReg[0].Swizzle == SWIZZLE_XYZW) {
90          return GL_TRUE;
91       }
92    }
93    return GL_FALSE;
94 }
95
96
97
98 /**
99  * Make fragment shader for glDraw/CopyPixels.  This shader is made
100  * by combining the pixel transfer shader with the user-defined shader.
101  * \param fpIn  the current/incoming fragment program
102  * \param fpOut  returns the combined fragment program
103  */
104 void
105 st_make_drawpix_fragment_program(struct st_context *st,
106                                  struct gl_fragment_program *fpIn,
107                                  struct gl_fragment_program **fpOut)
108 {
109    struct gl_program *newProg;
110
111    if (is_passthrough_program(fpIn)) {
112       newProg = (struct gl_program *) _mesa_clone_fragment_program(st->ctx,
113                                              &st->pixel_xfer.program->Base);
114    }
115    else {
116 #if 0
117       /* debug */
118       printf("Base program:\n");
119       _mesa_print_program(&fpIn->Base);
120       printf("DrawPix program:\n");
121       _mesa_print_program(&st->pixel_xfer.program->Base.Base);
122 #endif
123       newProg = _mesa_combine_programs(st->ctx,
124                                        &st->pixel_xfer.program->Base.Base,
125                                        &fpIn->Base);
126    }
127
128 #if 0
129    /* debug */
130    printf("Combined DrawPixels program:\n");
131    _mesa_print_program(newProg);
132    printf("InputsRead: 0x%x\n", newProg->InputsRead);
133    printf("OutputsWritten: 0x%x\n", newProg->OutputsWritten);
134    _mesa_print_parameter_list(newProg->Parameters);
135 #endif
136
137    *fpOut = (struct gl_fragment_program *) newProg;
138 }
139
140
141 /**
142  * Create fragment program that does a TEX() instruction to get a Z and/or
143  * stencil value value, then writes to FRAG_RESULT_DEPTH/FRAG_RESULT_STENCIL.
144  * Used for glDrawPixels(GL_DEPTH_COMPONENT / GL_STENCIL_INDEX).
145  * Pass fragment color through as-is.
146  * \return pointer to the gl_fragment program
147  */
148 struct gl_fragment_program *
149 st_make_drawpix_z_stencil_program(struct st_context *st,
150                                   GLboolean write_depth,
151                                   GLboolean write_stencil)
152 {
153    struct gl_context *ctx = st->ctx;
154    struct gl_program *p;
155    struct gl_fragment_program *fp;
156    GLuint ic = 0;
157    const GLuint shaderIndex = write_depth * 2 + write_stencil;
158
159    assert(shaderIndex < Elements(st->drawpix.shaders));
160
161    if (st->drawpix.shaders[shaderIndex]) {
162       /* already have the proper shader */
163       return st->drawpix.shaders[shaderIndex];
164    }
165
166    /*
167     * Create shader now
168     */
169    p = ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
170    if (!p)
171       return NULL;
172
173    p->NumInstructions = write_depth ? 2 : 1;
174    p->NumInstructions += write_stencil ? 1 : 0;
175
176    p->Instructions = _mesa_alloc_instructions(p->NumInstructions);
177    if (!p->Instructions) {
178       ctx->Driver.DeleteProgram(ctx, p);
179       return NULL;
180    }
181    _mesa_init_instructions(p->Instructions, p->NumInstructions);
182
183    if (write_depth) {
184       /* TEX result.depth, fragment.texcoord[0], texture[0], 2D; */
185       p->Instructions[ic].Opcode = OPCODE_TEX;
186       p->Instructions[ic].DstReg.File = PROGRAM_OUTPUT;
187       p->Instructions[ic].DstReg.Index = FRAG_RESULT_DEPTH;
188       p->Instructions[ic].DstReg.WriteMask = WRITEMASK_Z;
189       p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
190       p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
191       p->Instructions[ic].TexSrcUnit = 0;
192       p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
193       ic++;
194    }
195
196    if (write_stencil) {
197       /* TEX result.stencil, fragment.texcoord[0], texture[0], 2D; */
198       p->Instructions[ic].Opcode = OPCODE_TEX;
199       p->Instructions[ic].DstReg.File = PROGRAM_OUTPUT;
200       p->Instructions[ic].DstReg.Index = FRAG_RESULT_STENCIL;
201       p->Instructions[ic].DstReg.WriteMask = WRITEMASK_Y;
202       p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
203       p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
204       p->Instructions[ic].TexSrcUnit = 1;
205       p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
206       ic++;
207    }
208
209    /* END; */
210    p->Instructions[ic++].Opcode = OPCODE_END;
211
212    assert(ic == p->NumInstructions);
213
214    p->InputsRead = FRAG_BIT_TEX0 | FRAG_BIT_COL0;
215    p->OutputsWritten = 0;
216    if (write_depth)
217       p->OutputsWritten |= BITFIELD64_BIT(FRAG_RESULT_DEPTH);
218    if (write_stencil)
219       p->OutputsWritten |= BITFIELD64_BIT(FRAG_RESULT_STENCIL);
220
221    p->SamplersUsed =  0x1;  /* sampler 0 (bit 0) is used */
222    if (write_stencil)
223       p->SamplersUsed |= 1 << 1;
224
225    fp = (struct gl_fragment_program *) p;
226
227    /* save the new shader */
228    st->drawpix.shaders[shaderIndex] = fp;
229
230    return fp;
231 }
232
233
234 /**
235  * Create a simple vertex shader that just passes through the
236  * vertex position and texcoord (and optionally, color).
237  */
238 static void *
239 make_passthrough_vertex_shader(struct st_context *st, 
240                                GLboolean passColor)
241 {
242    if (!st->drawpix.vert_shaders[passColor]) {
243       struct ureg_program *ureg = ureg_create( TGSI_PROCESSOR_VERTEX );
244
245       if (ureg == NULL)
246          return NULL;
247
248       /* MOV result.pos, vertex.pos; */
249       ureg_MOV(ureg, 
250                ureg_DECL_output( ureg, TGSI_SEMANTIC_POSITION, 0 ),
251                ureg_DECL_vs_input( ureg, 0 ));
252       
253       /* MOV result.texcoord0, vertex.attr[1]; */
254       ureg_MOV(ureg, 
255                ureg_DECL_output( ureg, TGSI_SEMANTIC_GENERIC, 0 ),
256                ureg_DECL_vs_input( ureg, 1 ));
257       
258       if (passColor) {
259          /* MOV result.color0, vertex.attr[2]; */
260          ureg_MOV(ureg, 
261                   ureg_DECL_output( ureg, TGSI_SEMANTIC_COLOR, 0 ),
262                   ureg_DECL_vs_input( ureg, 2 ));
263       }
264
265       ureg_END( ureg );
266       
267       st->drawpix.vert_shaders[passColor] = 
268          ureg_create_shader_and_destroy( ureg, st->pipe );
269    }
270
271    return st->drawpix.vert_shaders[passColor];
272 }
273
274
275 /**
276  * Return a texture base format for drawing/copying an image
277  * of the given format.
278  */
279 static GLenum
280 base_format(GLenum format)
281 {
282    switch (format) {
283    case GL_DEPTH_COMPONENT:
284       return GL_DEPTH_COMPONENT;
285    case GL_DEPTH_STENCIL:
286       return GL_DEPTH_STENCIL;
287    case GL_STENCIL_INDEX:
288       return GL_STENCIL_INDEX;
289    default:
290       return GL_RGBA;
291    }
292 }
293
294
295 /**
296  * Return a texture internalFormat for drawing/copying an image
297  * of the given format and type.
298  */
299 static GLenum
300 internal_format(struct gl_context *ctx, GLenum format, GLenum type)
301 {
302    switch (format) {
303    case GL_DEPTH_COMPONENT:
304       return GL_DEPTH_COMPONENT;
305    case GL_DEPTH_STENCIL:
306       return GL_DEPTH_STENCIL;
307    case GL_STENCIL_INDEX:
308       return GL_STENCIL_INDEX;
309    default:
310       if (_mesa_is_integer_format(format)) {
311          switch (type) {
312          case GL_BYTE:
313             return GL_RGBA8I;
314          case GL_UNSIGNED_BYTE:
315             return GL_RGBA8UI;
316          case GL_SHORT:
317             return GL_RGBA16I;
318          case GL_UNSIGNED_SHORT:
319             return GL_RGBA16UI;
320          case GL_INT:
321             return GL_RGBA32I;
322          case GL_UNSIGNED_INT:
323             return GL_RGBA32UI;
324          default:
325             assert(0 && "Unexpected type in internal_format()");
326             return GL_RGBA_INTEGER;
327          }
328       }
329       else {
330          switch (type) {
331          case GL_UNSIGNED_BYTE:
332          case GL_UNSIGNED_INT_8_8_8_8:
333          case GL_UNSIGNED_INT_8_8_8_8_REV:
334          default:
335             return GL_RGBA8;
336
337          case GL_UNSIGNED_BYTE_3_3_2:
338          case GL_UNSIGNED_BYTE_2_3_3_REV:
339          case GL_UNSIGNED_SHORT_4_4_4_4:
340          case GL_UNSIGNED_SHORT_4_4_4_4_REV:
341             return GL_RGBA4;
342
343          case GL_UNSIGNED_SHORT_5_6_5:
344          case GL_UNSIGNED_SHORT_5_6_5_REV:
345          case GL_UNSIGNED_SHORT_5_5_5_1:
346          case GL_UNSIGNED_SHORT_1_5_5_5_REV:
347             return GL_RGB5_A1;
348
349          case GL_UNSIGNED_INT_10_10_10_2:
350          case GL_UNSIGNED_INT_2_10_10_10_REV:
351             return GL_RGB10_A2;
352
353          case GL_UNSIGNED_SHORT:
354          case GL_UNSIGNED_INT:
355             return GL_RGBA16;
356
357          case GL_BYTE:
358             return
359                ctx->Extensions.EXT_texture_snorm ? GL_RGBA8_SNORM : GL_RGBA8;
360
361          case GL_SHORT:
362          case GL_INT:
363             return
364                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
365
366          case GL_HALF_FLOAT_ARB:
367             return
368                ctx->Extensions.ARB_texture_float ? GL_RGBA16F :
369                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
370
371          case GL_FLOAT:
372          case GL_DOUBLE:
373             return
374                ctx->Extensions.ARB_texture_float ? GL_RGBA32F :
375                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
376
377          case GL_UNSIGNED_INT_5_9_9_9_REV:
378             assert(ctx->Extensions.EXT_texture_shared_exponent);
379             return GL_RGB9_E5;
380
381          case GL_UNSIGNED_INT_10F_11F_11F_REV:
382             assert(ctx->Extensions.EXT_packed_float);
383             return GL_R11F_G11F_B10F;
384          }
385       }
386    }
387 }
388
389
390 /**
391  * Create a temporary texture to hold an image of the given size.
392  * If width, height are not POT and the driver only handles POT textures,
393  * allocate the next larger size of texture that is POT.
394  */
395 static struct pipe_resource *
396 alloc_texture(struct st_context *st, GLsizei width, GLsizei height,
397               enum pipe_format texFormat)
398 {
399    struct pipe_resource *pt;
400
401    pt = st_texture_create(st, st->internal_target, texFormat, 0,
402                           width, height, 1, 1, PIPE_BIND_SAMPLER_VIEW);
403
404    return pt;
405 }
406
407
408 /**
409  * Make texture containing an image for glDrawPixels image.
410  * If 'pixels' is NULL, leave the texture image data undefined.
411  */
412 static struct pipe_resource *
413 make_texture(struct st_context *st,
414              GLsizei width, GLsizei height, GLenum format, GLenum type,
415              const struct gl_pixelstore_attrib *unpack,
416              const GLvoid *pixels)
417 {
418    struct gl_context *ctx = st->ctx;
419    struct pipe_context *pipe = st->pipe;
420    gl_format mformat;
421    struct pipe_resource *pt;
422    enum pipe_format pipeFormat;
423    GLenum baseInternalFormat, intFormat;
424
425    intFormat = internal_format(ctx, format, type);
426    baseInternalFormat = _mesa_base_tex_format(ctx, intFormat);
427
428    mformat = st_ChooseTextureFormat_renderable(ctx, intFormat,
429                                                format, type, GL_FALSE);
430    assert(mformat);
431
432    pipeFormat = st_mesa_format_to_pipe_format(mformat);
433    assert(pipeFormat);
434
435    pixels = _mesa_map_pbo_source(ctx, unpack, pixels);
436    if (!pixels)
437       return NULL;
438
439    /* alloc temporary texture */
440    pt = alloc_texture(st, width, height, pipeFormat);
441    if (!pt) {
442       _mesa_unmap_pbo_source(ctx, unpack);
443       return NULL;
444    }
445
446    {
447       struct pipe_transfer *transfer;
448       static const GLuint dstImageOffsets = 0;
449       GLboolean success;
450       GLubyte *dest;
451       const GLbitfield imageTransferStateSave = ctx->_ImageTransferState;
452
453       /* we'll do pixel transfer in a fragment shader */
454       ctx->_ImageTransferState = 0x0;
455
456       transfer = pipe_get_transfer(st->pipe, pt, 0, 0,
457                                    PIPE_TRANSFER_WRITE, 0, 0,
458                                    width, height);
459
460       /* map texture transfer */
461       dest = pipe_transfer_map(pipe, transfer);
462
463
464       /* Put image into texture transfer.
465        * Note that the image is actually going to be upside down in
466        * the texture.  We deal with that with texcoords.
467        */
468       success = _mesa_texstore(ctx, 2,           /* dims */
469                                baseInternalFormat, /* baseInternalFormat */
470                                mformat,          /* gl_format */
471                                dest,             /* dest */
472                                0, 0, 0,          /* dstX/Y/Zoffset */
473                                transfer->stride, /* dstRowStride, bytes */
474                                &dstImageOffsets, /* dstImageOffsets */
475                                width, height, 1, /* size */
476                                format, type,     /* src format/type */
477                                pixels,           /* data source */
478                                unpack);
479
480       /* unmap */
481       pipe_transfer_unmap(pipe, transfer);
482       pipe->transfer_destroy(pipe, transfer);
483
484       assert(success);
485
486       /* restore */
487       ctx->_ImageTransferState = imageTransferStateSave;
488    }
489
490    _mesa_unmap_pbo_source(ctx, unpack);
491
492    return pt;
493 }
494
495
496 /**
497  * Draw quad with texcoords and optional color.
498  * Coords are gallium window coords with y=0=top.
499  * \param color  may be null
500  * \param invertTex  if true, flip texcoords vertically
501  */
502 static void
503 draw_quad(struct gl_context *ctx, GLfloat x0, GLfloat y0, GLfloat z,
504           GLfloat x1, GLfloat y1, const GLfloat *color,
505           GLboolean invertTex, GLfloat maxXcoord, GLfloat maxYcoord)
506 {
507    struct st_context *st = st_context(ctx);
508    struct pipe_context *pipe = st->pipe;
509    GLfloat verts[4][3][4]; /* four verts, three attribs, XYZW */
510
511    /* setup vertex data */
512    {
513       const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
514       const GLfloat fb_width = (GLfloat) fb->Width;
515       const GLfloat fb_height = (GLfloat) fb->Height;
516       const GLfloat clip_x0 = x0 / fb_width * 2.0f - 1.0f;
517       const GLfloat clip_y0 = y0 / fb_height * 2.0f - 1.0f;
518       const GLfloat clip_x1 = x1 / fb_width * 2.0f - 1.0f;
519       const GLfloat clip_y1 = y1 / fb_height * 2.0f - 1.0f;
520       const GLfloat sLeft = 0.0f, sRight = maxXcoord;
521       const GLfloat tTop = invertTex ? maxYcoord : 0.0f;
522       const GLfloat tBot = invertTex ? 0.0f : maxYcoord;
523       GLuint i;
524
525       /* upper-left */
526       verts[0][0][0] = clip_x0;    /* v[0].attr[0].x */
527       verts[0][0][1] = clip_y0;    /* v[0].attr[0].y */
528
529       /* upper-right */
530       verts[1][0][0] = clip_x1;
531       verts[1][0][1] = clip_y0;
532
533       /* lower-right */
534       verts[2][0][0] = clip_x1;
535       verts[2][0][1] = clip_y1;
536
537       /* lower-left */
538       verts[3][0][0] = clip_x0;
539       verts[3][0][1] = clip_y1;
540
541       verts[0][1][0] = sLeft; /* v[0].attr[1].S */
542       verts[0][1][1] = tTop;  /* v[0].attr[1].T */
543       verts[1][1][0] = sRight;
544       verts[1][1][1] = tTop;
545       verts[2][1][0] = sRight;
546       verts[2][1][1] = tBot;
547       verts[3][1][0] = sLeft;
548       verts[3][1][1] = tBot;
549
550       /* same for all verts: */
551       if (color) {
552          for (i = 0; i < 4; i++) {
553             verts[i][0][2] = z;         /* v[i].attr[0].z */
554             verts[i][0][3] = 1.0f;      /* v[i].attr[0].w */
555             verts[i][2][0] = color[0];  /* v[i].attr[2].r */
556             verts[i][2][1] = color[1];  /* v[i].attr[2].g */
557             verts[i][2][2] = color[2];  /* v[i].attr[2].b */
558             verts[i][2][3] = color[3];  /* v[i].attr[2].a */
559             verts[i][1][2] = 0.0f;      /* v[i].attr[1].R */
560             verts[i][1][3] = 1.0f;      /* v[i].attr[1].Q */
561          }
562       }
563       else {
564          for (i = 0; i < 4; i++) {
565             verts[i][0][2] = z;    /*Z*/
566             verts[i][0][3] = 1.0f; /*W*/
567             verts[i][1][2] = 0.0f; /*R*/
568             verts[i][1][3] = 1.0f; /*Q*/
569          }
570       }
571    }
572
573    {
574       struct pipe_resource *buf;
575
576       /* allocate/load buffer object with vertex data */
577       buf = pipe_buffer_create(pipe->screen,
578                                PIPE_BIND_VERTEX_BUFFER,
579                                PIPE_USAGE_STATIC,
580                                sizeof(verts));
581       pipe_buffer_write(st->pipe, buf, 0, sizeof(verts), verts);
582
583       util_draw_vertex_buffer(pipe, st->cso_context, buf, 0,
584                               PIPE_PRIM_QUADS,
585                               4,  /* verts */
586                               3); /* attribs/vert */
587       pipe_resource_reference(&buf, NULL);
588    }
589 }
590
591
592
593 static void
594 draw_textured_quad(struct gl_context *ctx, GLint x, GLint y, GLfloat z,
595                    GLsizei width, GLsizei height,
596                    GLfloat zoomX, GLfloat zoomY,
597                    struct pipe_sampler_view **sv,
598                    int num_sampler_view,
599                    void *driver_vp,
600                    void *driver_fp,
601                    const GLfloat *color,
602                    GLboolean invertTex,
603                    GLboolean write_depth, GLboolean write_stencil)
604 {
605    struct st_context *st = st_context(ctx);
606    struct pipe_context *pipe = st->pipe;
607    struct cso_context *cso = st->cso_context;
608    GLfloat x0, y0, x1, y1;
609    GLsizei maxSize;
610    boolean normalized = sv[0]->texture->target != PIPE_TEXTURE_RECT;
611
612    /* limit checks */
613    /* XXX if DrawPixels image is larger than max texture size, break
614     * it up into chunks.
615     */
616    maxSize = 1 << (pipe->screen->get_param(pipe->screen,
617                                         PIPE_CAP_MAX_TEXTURE_2D_LEVELS) - 1);
618    assert(width <= maxSize);
619    assert(height <= maxSize);
620
621    cso_save_rasterizer(cso);
622    cso_save_viewport(cso);
623    cso_save_samplers(cso);
624    cso_save_fragment_sampler_views(cso);
625    cso_save_fragment_shader(cso);
626    cso_save_vertex_shader(cso);
627    cso_save_vertex_elements(cso);
628    cso_save_vertex_buffers(cso);
629    if (write_stencil) {
630       cso_save_depth_stencil_alpha(cso);
631       cso_save_blend(cso);
632    }
633
634    /* rasterizer state: just scissor */
635    {
636       struct pipe_rasterizer_state rasterizer;
637       memset(&rasterizer, 0, sizeof(rasterizer));
638       rasterizer.clamp_fragment_color = ctx->Color._ClampFragmentColor;
639       rasterizer.gl_rasterization_rules = 1;
640       rasterizer.scissor = ctx->Scissor.Enabled;
641       cso_set_rasterizer(cso, &rasterizer);
642    }
643
644    if (write_stencil) {
645       /* Stencil writing bypasses the normal fragment pipeline to
646        * disable color writing and set stencil test to always pass.
647        */
648       struct pipe_depth_stencil_alpha_state dsa;
649       struct pipe_blend_state blend;
650
651       /* depth/stencil */
652       memset(&dsa, 0, sizeof(dsa));
653       dsa.stencil[0].enabled = 1;
654       dsa.stencil[0].func = PIPE_FUNC_ALWAYS;
655       dsa.stencil[0].writemask = ctx->Stencil.WriteMask[0] & 0xff;
656       dsa.stencil[0].zpass_op = PIPE_STENCIL_OP_REPLACE;
657       if (write_depth) {
658          /* writing depth+stencil: depth test always passes */
659          dsa.depth.enabled = 1;
660          dsa.depth.writemask = ctx->Depth.Mask;
661          dsa.depth.func = PIPE_FUNC_ALWAYS;
662       }
663       cso_set_depth_stencil_alpha(cso, &dsa);
664
665       /* blend (colormask) */
666       memset(&blend, 0, sizeof(blend));
667       cso_set_blend(cso, &blend);
668    }
669
670    /* fragment shader state: TEX lookup program */
671    cso_set_fragment_shader_handle(cso, driver_fp);
672
673    /* vertex shader state: position + texcoord pass-through */
674    cso_set_vertex_shader_handle(cso, driver_vp);
675
676
677    /* texture sampling state: */
678    {
679       struct pipe_sampler_state sampler;
680       memset(&sampler, 0, sizeof(sampler));
681       sampler.wrap_s = PIPE_TEX_WRAP_CLAMP;
682       sampler.wrap_t = PIPE_TEX_WRAP_CLAMP;
683       sampler.wrap_r = PIPE_TEX_WRAP_CLAMP;
684       sampler.min_img_filter = PIPE_TEX_FILTER_NEAREST;
685       sampler.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
686       sampler.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
687       sampler.normalized_coords = normalized;
688
689       cso_single_sampler(cso, 0, &sampler);
690       if (num_sampler_view > 1) {
691          cso_single_sampler(cso, 1, &sampler);
692       }
693       cso_single_sampler_done(cso);
694    }
695
696    /* viewport state: viewport matching window dims */
697    {
698       const float w = (float) ctx->DrawBuffer->Width;
699       const float h = (float) ctx->DrawBuffer->Height;
700       struct pipe_viewport_state vp;
701       vp.scale[0] =  0.5f * w;
702       vp.scale[1] = -0.5f * h;
703       vp.scale[2] = 0.5f;
704       vp.scale[3] = 1.0f;
705       vp.translate[0] = 0.5f * w;
706       vp.translate[1] = 0.5f * h;
707       vp.translate[2] = 0.5f;
708       vp.translate[3] = 0.0f;
709       cso_set_viewport(cso, &vp);
710    }
711
712    cso_set_vertex_elements(cso, 3, st->velems_util_draw);
713
714    /* texture state: */
715    cso_set_fragment_sampler_views(cso, num_sampler_view, sv);
716
717    /* Compute Gallium window coords (y=0=top) with pixel zoom.
718     * Recall that these coords are transformed by the current
719     * vertex shader and viewport transformation.
720     */
721    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_BOTTOM) {
722       y = ctx->DrawBuffer->Height - (int) (y + height * ctx->Pixel.ZoomY);
723       invertTex = !invertTex;
724    }
725
726    x0 = (GLfloat) x;
727    x1 = x + width * ctx->Pixel.ZoomX;
728    y0 = (GLfloat) y;
729    y1 = y + height * ctx->Pixel.ZoomY;
730
731    /* convert Z from [0,1] to [-1,-1] to match viewport Z scale/bias */
732    z = z * 2.0 - 1.0;
733
734    draw_quad(ctx, x0, y0, z, x1, y1, color, invertTex,
735              normalized ? ((GLfloat) width / sv[0]->texture->width0) : (GLfloat)width,
736              normalized ? ((GLfloat) height / sv[0]->texture->height0) : (GLfloat)height);
737
738    /* restore state */
739    cso_restore_rasterizer(cso);
740    cso_restore_viewport(cso);
741    cso_restore_samplers(cso);
742    cso_restore_fragment_sampler_views(cso);
743    cso_restore_fragment_shader(cso);
744    cso_restore_vertex_shader(cso);
745    cso_restore_vertex_elements(cso);
746    cso_restore_vertex_buffers(cso);
747    if (write_stencil) {
748       cso_restore_depth_stencil_alpha(cso);
749       cso_restore_blend(cso);
750    }
751 }
752
753
754 /**
755  * Software fallback to do glDrawPixels(GL_STENCIL_INDEX) when we
756  * can't use a fragment shader to write stencil values.
757  */
758 static void
759 draw_stencil_pixels(struct gl_context *ctx, GLint x, GLint y,
760                     GLsizei width, GLsizei height, GLenum format, GLenum type,
761                     const struct gl_pixelstore_attrib *unpack,
762                     const GLvoid *pixels)
763 {
764    struct st_context *st = st_context(ctx);
765    struct pipe_context *pipe = st->pipe;
766    struct st_renderbuffer *strb;
767    enum pipe_transfer_usage usage;
768    struct pipe_transfer *pt;
769    const GLboolean zoom = ctx->Pixel.ZoomX != 1.0 || ctx->Pixel.ZoomY != 1.0;
770    GLint skipPixels;
771    ubyte *stmap;
772    struct gl_pixelstore_attrib clippedUnpack = *unpack;
773
774    if (!zoom) {
775       if (!_mesa_clip_drawpixels(ctx, &x, &y, &width, &height,
776                                  &clippedUnpack)) {
777          /* totally clipped */
778          return;
779       }
780    }
781
782    strb = st_renderbuffer(ctx->DrawBuffer->
783                           Attachment[BUFFER_STENCIL].Renderbuffer);
784
785    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
786       y = ctx->DrawBuffer->Height - y - height;
787    }
788
789    if(format != GL_DEPTH_STENCIL && 
790       util_format_get_component_bits(strb->format,
791                                      UTIL_FORMAT_COLORSPACE_ZS, 0) != 0)
792       usage = PIPE_TRANSFER_READ_WRITE;
793    else
794       usage = PIPE_TRANSFER_WRITE;
795
796    pt = pipe_get_transfer(pipe, strb->texture,
797                           strb->rtt_level, strb->rtt_face + strb->rtt_slice,
798                           usage, x, y,
799                           width, height);
800
801    stmap = pipe_transfer_map(pipe, pt);
802
803    pixels = _mesa_map_pbo_source(ctx, &clippedUnpack, pixels);
804    assert(pixels);
805
806    /* if width > MAX_WIDTH, have to process image in chunks */
807    skipPixels = 0;
808    while (skipPixels < width) {
809       const GLint spanX = skipPixels;
810       const GLint spanWidth = MIN2(width - skipPixels, MAX_WIDTH);
811       GLint row;
812       for (row = 0; row < height; row++) {
813          GLubyte sValues[MAX_WIDTH];
814          GLuint zValues[MAX_WIDTH];
815          GLenum destType = GL_UNSIGNED_BYTE;
816          const GLvoid *source = _mesa_image_address2d(&clippedUnpack, pixels,
817                                                       width, height,
818                                                       format, type,
819                                                       row, skipPixels);
820          _mesa_unpack_stencil_span(ctx, spanWidth, destType, sValues,
821                                    type, source, &clippedUnpack,
822                                    ctx->_ImageTransferState);
823
824          if (format == GL_DEPTH_STENCIL) {
825             _mesa_unpack_depth_span(ctx, spanWidth, GL_UNSIGNED_INT, zValues,
826                                     (1 << 24) - 1, type, source,
827                                     &clippedUnpack);
828          }
829
830          if (zoom) {
831             _mesa_problem(ctx, "Gallium glDrawPixels(GL_STENCIL) with "
832                           "zoom not complete");
833          }
834
835          {
836             GLint spanY;
837
838             if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
839                spanY = height - row - 1;
840             }
841             else {
842                spanY = row;
843             }
844
845             /* now pack the stencil (and Z) values in the dest format */
846             switch (pt->resource->format) {
847             case PIPE_FORMAT_S8_USCALED:
848                {
849                   ubyte *dest = stmap + spanY * pt->stride + spanX;
850                   assert(usage == PIPE_TRANSFER_WRITE);
851                   memcpy(dest, sValues, spanWidth);
852                }
853                break;
854             case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
855                if (format == GL_DEPTH_STENCIL) {
856                   uint *dest = (uint *) (stmap + spanY * pt->stride + spanX*4);
857                   GLint k;
858                   assert(usage == PIPE_TRANSFER_WRITE);
859                   for (k = 0; k < spanWidth; k++) {
860                      dest[k] = zValues[k] | (sValues[k] << 24);
861                   }
862                }
863                else {
864                   uint *dest = (uint *) (stmap + spanY * pt->stride + spanX*4);
865                   GLint k;
866                   assert(usage == PIPE_TRANSFER_READ_WRITE);
867                   for (k = 0; k < spanWidth; k++) {
868                      dest[k] = (dest[k] & 0xffffff) | (sValues[k] << 24);
869                   }
870                }
871                break;
872             case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
873                if (format == GL_DEPTH_STENCIL) {
874                   uint *dest = (uint *) (stmap + spanY * pt->stride + spanX*4);
875                   GLint k;
876                   assert(usage == PIPE_TRANSFER_WRITE);
877                   for (k = 0; k < spanWidth; k++) {
878                      dest[k] = (zValues[k] << 8) | (sValues[k] & 0xff);
879                   }
880                }
881                else {
882                   uint *dest = (uint *) (stmap + spanY * pt->stride + spanX*4);
883                   GLint k;
884                   assert(usage == PIPE_TRANSFER_READ_WRITE);
885                   for (k = 0; k < spanWidth; k++) {
886                      dest[k] = (dest[k] & 0xffffff00) | (sValues[k] & 0xff);
887                   }
888                }
889                break;
890             default:
891                assert(0);
892             }
893          }
894       }
895       skipPixels += spanWidth;
896    }
897
898    _mesa_unmap_pbo_source(ctx, &clippedUnpack);
899
900    /* unmap the stencil buffer */
901    pipe_transfer_unmap(pipe, pt);
902    pipe->transfer_destroy(pipe, pt);
903 }
904
905
906 /**
907  * Get fragment program variant for a glDrawPixels or glCopyPixels
908  * command for RGBA data.
909  */
910 static struct st_fp_variant *
911 get_color_fp_variant(struct st_context *st)
912 {
913    struct gl_context *ctx = st->ctx;
914    struct st_fp_variant_key key;
915    struct st_fp_variant *fpv;
916
917    memset(&key, 0, sizeof(key));
918
919    key.st = st;
920    key.drawpixels = 1;
921    key.scaleAndBias = (ctx->Pixel.RedBias != 0.0 ||
922                        ctx->Pixel.RedScale != 1.0 ||
923                        ctx->Pixel.GreenBias != 0.0 ||
924                        ctx->Pixel.GreenScale != 1.0 ||
925                        ctx->Pixel.BlueBias != 0.0 ||
926                        ctx->Pixel.BlueScale != 1.0 ||
927                        ctx->Pixel.AlphaBias != 0.0 ||
928                        ctx->Pixel.AlphaScale != 1.0);
929    key.pixelMaps = ctx->Pixel.MapColorFlag;
930
931    fpv = st_get_fp_variant(st, st->fp, &key);
932
933    return fpv;
934 }
935
936
937 /**
938  * Get fragment program variant for a glDrawPixels or glCopyPixels
939  * command for depth/stencil data.
940  */
941 static struct st_fp_variant *
942 get_depth_stencil_fp_variant(struct st_context *st, GLboolean write_depth,
943                              GLboolean write_stencil)
944 {
945    struct st_fp_variant_key key;
946    struct st_fp_variant *fpv;
947
948    memset(&key, 0, sizeof(key));
949
950    key.st = st;
951    key.drawpixels = 1;
952    key.drawpixels_z = write_depth;
953    key.drawpixels_stencil = write_stencil;
954
955    fpv = st_get_fp_variant(st, st->fp, &key);
956
957    return fpv;
958 }
959
960
961 /**
962  * Called via ctx->Driver.DrawPixels()
963  */
964 static void
965 st_DrawPixels(struct gl_context *ctx, GLint x, GLint y,
966               GLsizei width, GLsizei height,
967               GLenum format, GLenum type,
968               const struct gl_pixelstore_attrib *unpack, const GLvoid *pixels)
969 {
970    void *driver_vp, *driver_fp;
971    struct st_context *st = st_context(ctx);
972    const GLfloat *color;
973    struct pipe_context *pipe = st->pipe;
974    GLboolean write_stencil = GL_FALSE, write_depth = GL_FALSE;
975    struct pipe_sampler_view *sv[2];
976    int num_sampler_view = 1;
977    enum pipe_format stencil_format = PIPE_FORMAT_NONE;
978    struct st_fp_variant *fpv;
979
980    if (format == GL_DEPTH_STENCIL)
981       write_stencil = write_depth = GL_TRUE;
982    else if (format == GL_STENCIL_INDEX)
983       write_stencil = GL_TRUE;
984    else if (format == GL_DEPTH_COMPONENT)
985       write_depth = GL_TRUE;
986
987    if (write_stencil) {
988       enum pipe_format tex_format;
989       /* can we write to stencil if not fallback */
990       if (!pipe->screen->get_param(pipe->screen, PIPE_CAP_SHADER_STENCIL_EXPORT))
991          goto stencil_fallback;
992
993       tex_format = st_choose_format(st->pipe->screen, base_format(format),
994                                     GL_NONE, GL_NONE,
995                                     PIPE_TEXTURE_2D,
996                                     0, PIPE_BIND_SAMPLER_VIEW);
997       if (tex_format == PIPE_FORMAT_Z24_UNORM_S8_USCALED)
998          stencil_format = PIPE_FORMAT_X24S8_USCALED;
999       else if (tex_format == PIPE_FORMAT_S8_USCALED_Z24_UNORM)
1000          stencil_format = PIPE_FORMAT_S8X24_USCALED;
1001       else
1002          stencil_format = PIPE_FORMAT_S8_USCALED;
1003       if (stencil_format == PIPE_FORMAT_NONE)
1004          goto stencil_fallback;
1005    }
1006
1007    /* Mesa state should be up to date by now */
1008    assert(ctx->NewState == 0x0);
1009
1010    st_validate_state(st);
1011
1012    /*
1013     * Get vertex/fragment shaders
1014     */
1015    if (write_depth || write_stencil) {
1016       fpv = get_depth_stencil_fp_variant(st, write_depth, write_stencil);
1017
1018       driver_fp = fpv->driver_shader;
1019
1020       driver_vp = make_passthrough_vertex_shader(st, GL_TRUE);
1021
1022       color = ctx->Current.RasterColor;
1023    }
1024    else {
1025       fpv = get_color_fp_variant(st);
1026
1027       driver_fp = fpv->driver_shader;
1028
1029       driver_vp = make_passthrough_vertex_shader(st, GL_FALSE);
1030
1031       color = NULL;
1032       if (st->pixel_xfer.pixelmap_enabled) {
1033           sv[1] = st->pixel_xfer.pixelmap_sampler_view;
1034           num_sampler_view++;
1035       }
1036    }
1037
1038    /* update fragment program constants */
1039    st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
1040
1041    /* draw with textured quad */
1042    {
1043       struct pipe_resource *pt
1044          = make_texture(st, width, height, format, type, unpack, pixels);
1045       if (pt) {
1046          sv[0] = st_create_texture_sampler_view(st->pipe, pt);
1047
1048          if (sv[0]) {
1049             if (write_stencil) {
1050                sv[1] = st_create_texture_sampler_view_format(st->pipe, pt,
1051                                                              stencil_format);
1052                num_sampler_view++;
1053             }
1054
1055             draw_textured_quad(ctx, x, y, ctx->Current.RasterPos[2],
1056                                width, height,
1057                                ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1058                                sv,
1059                                num_sampler_view,
1060                                driver_vp,
1061                                driver_fp,
1062                                color, GL_FALSE, write_depth, write_stencil);
1063             pipe_sampler_view_reference(&sv[0], NULL);
1064             if (num_sampler_view > 1)
1065                pipe_sampler_view_reference(&sv[1], NULL);
1066          }
1067          pipe_resource_reference(&pt, NULL);
1068       }
1069    }
1070    return;
1071
1072 stencil_fallback:
1073    draw_stencil_pixels(ctx, x, y, width, height, format, type,
1074                        unpack, pixels);
1075 }
1076
1077
1078
1079 /**
1080  * Software fallback for glCopyPixels(GL_STENCIL).
1081  */
1082 static void
1083 copy_stencil_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1084                     GLsizei width, GLsizei height,
1085                     GLint dstx, GLint dsty)
1086 {
1087    struct st_renderbuffer *rbDraw;
1088    struct pipe_context *pipe = st_context(ctx)->pipe;
1089    enum pipe_transfer_usage usage;
1090    struct pipe_transfer *ptDraw;
1091    ubyte *drawMap;
1092    ubyte *buffer;
1093    int i;
1094
1095    buffer = malloc(width * height * sizeof(ubyte));
1096    if (!buffer) {
1097       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels(stencil)");
1098       return;
1099    }
1100
1101    /* Get the dest renderbuffer.  If there's a wrapper, use the
1102     * underlying renderbuffer.
1103     */
1104    rbDraw = st_renderbuffer(ctx->DrawBuffer->_StencilBuffer);
1105    if (rbDraw->Base.Wrapped)
1106       rbDraw = st_renderbuffer(rbDraw->Base.Wrapped);
1107
1108    /* this will do stencil pixel transfer ops */
1109    st_read_stencil_pixels(ctx, srcx, srcy, width, height,
1110                           GL_STENCIL_INDEX, GL_UNSIGNED_BYTE,
1111                           &ctx->DefaultPacking, buffer);
1112
1113    if (0) {
1114       /* debug code: dump stencil values */
1115       GLint row, col;
1116       for (row = 0; row < height; row++) {
1117          printf("%3d: ", row);
1118          for (col = 0; col < width; col++) {
1119             printf("%02x ", buffer[col + row * width]);
1120          }
1121          printf("\n");
1122       }
1123    }
1124
1125    if (util_format_get_component_bits(rbDraw->format,
1126                                      UTIL_FORMAT_COLORSPACE_ZS, 0) != 0)
1127       usage = PIPE_TRANSFER_READ_WRITE;
1128    else
1129       usage = PIPE_TRANSFER_WRITE;
1130
1131    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1132       dsty = rbDraw->Base.Height - dsty - height;
1133    }
1134
1135    ptDraw = pipe_get_transfer(pipe,
1136                               rbDraw->texture,
1137                               rbDraw->rtt_level,
1138                               rbDraw->rtt_face + rbDraw->rtt_slice,
1139                               usage, dstx, dsty,
1140                               width, height);
1141
1142    assert(util_format_get_blockwidth(ptDraw->resource->format) == 1);
1143    assert(util_format_get_blockheight(ptDraw->resource->format) == 1);
1144
1145    /* map the stencil buffer */
1146    drawMap = pipe_transfer_map(pipe, ptDraw);
1147
1148    /* draw */
1149    /* XXX PixelZoom not handled yet */
1150    for (i = 0; i < height; i++) {
1151       ubyte *dst;
1152       const ubyte *src;
1153       int y;
1154
1155       y = i;
1156
1157       if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1158          y = height - y - 1;
1159       }
1160
1161       dst = drawMap + y * ptDraw->stride;
1162       src = buffer + i * width;
1163
1164       switch (ptDraw->resource->format) {
1165       case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
1166          {
1167             uint *dst4 = (uint *) dst;
1168             int j;
1169             assert(usage == PIPE_TRANSFER_READ_WRITE);
1170             for (j = 0; j < width; j++) {
1171                *dst4 = (*dst4 & 0xffffff) | (src[j] << 24);
1172                dst4++;
1173             }
1174          }
1175          break;
1176       case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
1177          {
1178             uint *dst4 = (uint *) dst;
1179             int j;
1180             assert(usage == PIPE_TRANSFER_READ_WRITE);
1181             for (j = 0; j < width; j++) {
1182                *dst4 = (*dst4 & 0xffffff00) | (src[j] & 0xff);
1183                dst4++;
1184             }
1185          }
1186          break;
1187       case PIPE_FORMAT_S8_USCALED:
1188          assert(usage == PIPE_TRANSFER_WRITE);
1189          memcpy(dst, src, width);
1190          break;
1191       default:
1192          assert(0);
1193       }
1194    }
1195
1196    free(buffer);
1197
1198    /* unmap the stencil buffer */
1199    pipe_transfer_unmap(pipe, ptDraw);
1200    pipe->transfer_destroy(pipe, ptDraw);
1201 }
1202
1203
1204 /** Do the src/dest regions overlap? */
1205 static GLboolean
1206 regions_overlap(GLint srcX, GLint srcY, GLint dstX, GLint dstY,
1207                 GLsizei width, GLsizei height)
1208 {
1209    if (srcX + width <= dstX ||
1210        dstX + width <= srcX ||
1211        srcY + height <= dstY ||
1212        dstY + height <= srcY)
1213       return GL_FALSE;
1214    else
1215       return GL_TRUE;
1216 }
1217
1218
1219 /**
1220  * Try to do a glCopyPixels for simple cases with a blit by calling
1221  * pipe->resource_copy_region().
1222  *
1223  * We can do this when we're copying color pixels (depth/stencil
1224  * eventually) with no pixel zoom, no pixel transfer ops, no
1225  * per-fragment ops, the src/dest regions don't overlap and the
1226  * src/dest pixel formats are the same.
1227  */
1228 static GLboolean
1229 blit_copy_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1230                  GLsizei width, GLsizei height,
1231                  GLint dstx, GLint dsty, GLenum type)
1232 {
1233    struct st_context *st = st_context(ctx);
1234    struct pipe_context *pipe = st->pipe;
1235    struct gl_pixelstore_attrib pack, unpack;
1236    GLint readX, readY, readW, readH;
1237
1238    if (type == GL_COLOR &&
1239        ctx->Pixel.ZoomX == 1.0 &&
1240        ctx->Pixel.ZoomY == 1.0 &&
1241        ctx->_ImageTransferState == 0x0 &&
1242        !ctx->Color.BlendEnabled &&
1243        !ctx->Color.AlphaEnabled &&
1244        !ctx->Depth.Test &&
1245        !ctx->Fog.Enabled &&
1246        !ctx->Stencil.Enabled &&
1247        !ctx->FragmentProgram.Enabled &&
1248        !ctx->VertexProgram.Enabled &&
1249        !ctx->Shader.CurrentFragmentProgram &&
1250        st_fb_orientation(ctx->ReadBuffer) == st_fb_orientation(ctx->DrawBuffer) &&
1251        ctx->DrawBuffer->_NumColorDrawBuffers == 1 &&
1252        !ctx->Query.CondRenderQuery) {
1253       struct st_renderbuffer *rbRead, *rbDraw;
1254       GLint drawX, drawY;
1255
1256       /*
1257        * Clip the read region against the src buffer bounds.
1258        * We'll still allocate a temporary buffer/texture for the original
1259        * src region size but we'll only read the region which is on-screen.
1260        * This may mean that we draw garbage pixels into the dest region, but
1261        * that's expected.
1262        */
1263       readX = srcx;
1264       readY = srcy;
1265       readW = width;
1266       readH = height;
1267       pack = ctx->DefaultPacking;
1268       if (!_mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack))
1269          return GL_TRUE; /* all done */
1270
1271       /* clip against dest buffer bounds and scissor box */
1272       drawX = dstx + pack.SkipPixels;
1273       drawY = dsty + pack.SkipRows;
1274       unpack = pack;
1275       if (!_mesa_clip_drawpixels(ctx, &drawX, &drawY, &readW, &readH, &unpack))
1276          return GL_TRUE; /* all done */
1277
1278       readX = readX - pack.SkipPixels + unpack.SkipPixels;
1279       readY = readY - pack.SkipRows + unpack.SkipRows;
1280
1281       rbRead = st_get_color_read_renderbuffer(ctx);
1282       rbDraw = st_renderbuffer(ctx->DrawBuffer->_ColorDrawBuffers[0]);
1283
1284       if ((rbRead != rbDraw ||
1285            !regions_overlap(readX, readY, drawX, drawY, readW, readH)) &&
1286           rbRead->Base.Format == rbDraw->Base.Format) {
1287          struct pipe_box srcBox;
1288
1289          /* flip src/dst position if needed */
1290          if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1291             /* both buffers will have the same orientation */
1292             readY = ctx->ReadBuffer->Height - readY - readH;
1293             drawY = ctx->DrawBuffer->Height - drawY - readH;
1294          }
1295
1296          u_box_2d(readX, readY, readW, readH, &srcBox);
1297
1298          pipe->resource_copy_region(pipe,
1299                                     rbDraw->texture,
1300                                     rbDraw->rtt_level, drawX, drawY, 0,
1301                                     rbRead->texture,
1302                                     rbRead->rtt_level, &srcBox);
1303          return GL_TRUE;
1304       }
1305    }
1306
1307    return GL_FALSE;
1308 }
1309
1310
1311 static void
1312 st_CopyPixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1313               GLsizei width, GLsizei height,
1314               GLint dstx, GLint dsty, GLenum type)
1315 {
1316    struct st_context *st = st_context(ctx);
1317    struct pipe_context *pipe = st->pipe;
1318    struct pipe_screen *screen = pipe->screen;
1319    struct st_renderbuffer *rbRead;
1320    void *driver_vp, *driver_fp;
1321    struct pipe_resource *pt;
1322    struct pipe_sampler_view *sv[2];
1323    int num_sampler_view = 1;
1324    GLfloat *color;
1325    enum pipe_format srcFormat, texFormat;
1326    GLboolean invertTex = GL_FALSE;
1327    GLint readX, readY, readW, readH;
1328    GLuint sample_count;
1329    struct gl_pixelstore_attrib pack = ctx->DefaultPacking;
1330    struct st_fp_variant *fpv;
1331
1332    st_validate_state(st);
1333
1334    if (type == GL_STENCIL) {
1335       /* can't use texturing to do stencil */
1336       copy_stencil_pixels(ctx, srcx, srcy, width, height, dstx, dsty);
1337       return;
1338    }
1339
1340    if (blit_copy_pixels(ctx, srcx, srcy, width, height, dstx, dsty, type))
1341       return;
1342
1343    /*
1344     * The subsequent code implements glCopyPixels by copying the source
1345     * pixels into a temporary texture that's then applied to a textured quad.
1346     * When we draw the textured quad, all the usual per-fragment operations
1347     * are handled.
1348     */
1349
1350
1351    /*
1352     * Get vertex/fragment shaders
1353     */
1354    if (type == GL_COLOR) {
1355       rbRead = st_get_color_read_renderbuffer(ctx);
1356       color = NULL;
1357
1358       fpv = get_color_fp_variant(st);
1359       driver_fp = fpv->driver_shader;
1360
1361       driver_vp = make_passthrough_vertex_shader(st, GL_FALSE);
1362
1363       if (st->pixel_xfer.pixelmap_enabled) {
1364           sv[1] = st->pixel_xfer.pixelmap_sampler_view;
1365           num_sampler_view++;
1366       }
1367    }
1368    else {
1369       assert(type == GL_DEPTH);
1370       rbRead = st_renderbuffer(ctx->ReadBuffer->_DepthBuffer);
1371       color = ctx->Current.Attrib[VERT_ATTRIB_COLOR0];
1372
1373       fpv = get_depth_stencil_fp_variant(st, GL_TRUE, GL_FALSE);
1374       driver_fp = fpv->driver_shader;
1375
1376       driver_vp = make_passthrough_vertex_shader(st, GL_TRUE);
1377    }
1378
1379    /* update fragment program constants */
1380    st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
1381
1382
1383    if (rbRead->Base.Wrapped)
1384       rbRead = st_renderbuffer(rbRead->Base.Wrapped);
1385
1386    sample_count = rbRead->texture->nr_samples;
1387    /* I believe this would be legal, presumably would need to do a resolve
1388       for color, and for depth/stencil spec says to just use one of the
1389       depth/stencil samples per pixel? Need some transfer clarifications. */
1390    assert(sample_count < 2);
1391
1392    srcFormat = rbRead->texture->format;
1393
1394    if (screen->is_format_supported(screen, srcFormat, st->internal_target,
1395                                    sample_count,
1396                                    PIPE_BIND_SAMPLER_VIEW)) {
1397       texFormat = srcFormat;
1398    }
1399    else {
1400       /* srcFormat can't be used as a texture format */
1401       if (type == GL_DEPTH) {
1402          texFormat = st_choose_format(screen, GL_DEPTH_COMPONENT,
1403                                       GL_NONE, GL_NONE, st->internal_target,
1404                                       sample_count, PIPE_BIND_DEPTH_STENCIL);
1405          assert(texFormat != PIPE_FORMAT_NONE);
1406       }
1407       else {
1408          /* default color format */
1409          texFormat = st_choose_format(screen, GL_RGBA,
1410                                       GL_NONE, GL_NONE, st->internal_target,
1411                                       sample_count, PIPE_BIND_SAMPLER_VIEW);
1412          assert(texFormat != PIPE_FORMAT_NONE);
1413       }
1414    }
1415
1416    /* Invert src region if needed */
1417    if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1418       srcy = ctx->ReadBuffer->Height - srcy - height;
1419       invertTex = !invertTex;
1420    }
1421
1422    /* Clip the read region against the src buffer bounds.
1423     * We'll still allocate a temporary buffer/texture for the original
1424     * src region size but we'll only read the region which is on-screen.
1425     * This may mean that we draw garbage pixels into the dest region, but
1426     * that's expected.
1427     */
1428    readX = srcx;
1429    readY = srcy;
1430    readW = width;
1431    readH = height;
1432    _mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack);
1433    readW = MAX2(0, readW);
1434    readH = MAX2(0, readH);
1435
1436    /* alloc temporary texture */
1437    pt = alloc_texture(st, width, height, texFormat);
1438    if (!pt)
1439       return;
1440
1441    sv[0] = st_create_texture_sampler_view(st->pipe, pt);
1442    if (!sv[0]) {
1443       pipe_resource_reference(&pt, NULL);
1444       return;
1445    }
1446
1447    /* Make temporary texture which is a copy of the src region.
1448     */
1449    if (srcFormat == texFormat) {
1450       struct pipe_box src_box;
1451       u_box_2d(readX, readY, readW, readH, &src_box);
1452       /* copy source framebuffer surface into mipmap/texture */
1453       pipe->resource_copy_region(pipe,
1454                                  pt,                                /* dest tex */
1455                                  0,                                 /* dest lvl */
1456                                  pack.SkipPixels, pack.SkipRows, 0, /* dest pos */
1457                                  rbRead->texture,                   /* src tex */
1458                                  rbRead->rtt_level,                 /* src lvl */
1459                                  &src_box);
1460
1461    }
1462    else {
1463       /* CPU-based fallback/conversion */
1464       struct pipe_transfer *ptRead =
1465          pipe_get_transfer(st->pipe, rbRead->texture,
1466                            rbRead->rtt_level,
1467                            rbRead->rtt_face + rbRead->rtt_slice,
1468                            PIPE_TRANSFER_READ,
1469                            readX, readY, readW, readH);
1470       struct pipe_transfer *ptTex;
1471       enum pipe_transfer_usage transfer_usage;
1472
1473       if (ST_DEBUG & DEBUG_FALLBACK)
1474          debug_printf("%s: fallback processing\n", __FUNCTION__);
1475
1476       if (type == GL_DEPTH && util_format_is_depth_and_stencil(pt->format))
1477          transfer_usage = PIPE_TRANSFER_READ_WRITE;
1478       else
1479          transfer_usage = PIPE_TRANSFER_WRITE;
1480
1481       ptTex = pipe_get_transfer(st->pipe, pt, 0, 0, transfer_usage,
1482                                 0, 0, width, height);
1483
1484       /* copy image from ptRead surface to ptTex surface */
1485       if (type == GL_COLOR) {
1486          /* alternate path using get/put_tile() */
1487          GLfloat *buf = (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
1488          enum pipe_format readFormat, drawFormat;
1489          readFormat = util_format_linear(rbRead->texture->format);
1490          drawFormat = util_format_linear(pt->format);
1491          pipe_get_tile_rgba_format(pipe, ptRead, 0, 0, readW, readH,
1492                                    readFormat, buf);
1493          pipe_put_tile_rgba_format(pipe, ptTex, pack.SkipPixels, pack.SkipRows,
1494                                    readW, readH, drawFormat, buf);
1495          free(buf);
1496       }
1497       else {
1498          /* GL_DEPTH */
1499          GLuint *buf = (GLuint *) malloc(width * height * sizeof(GLuint));
1500          pipe_get_tile_z(pipe, ptRead, 0, 0, readW, readH, buf);
1501          pipe_put_tile_z(pipe, ptTex, pack.SkipPixels, pack.SkipRows,
1502                          readW, readH, buf);
1503          free(buf);
1504       }
1505
1506       pipe->transfer_destroy(pipe, ptRead);
1507       pipe->transfer_destroy(pipe, ptTex);
1508    }
1509
1510    /* OK, the texture 'pt' contains the src image/pixels.  Now draw a
1511     * textured quad with that texture.
1512     */
1513    draw_textured_quad(ctx, dstx, dsty, ctx->Current.RasterPos[2],
1514                       width, height, ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1515                       sv,
1516                       num_sampler_view,
1517                       driver_vp, 
1518                       driver_fp,
1519                       color, invertTex, GL_FALSE, GL_FALSE);
1520
1521    pipe_resource_reference(&pt, NULL);
1522    pipe_sampler_view_reference(&sv[0], NULL);
1523 }
1524
1525
1526
1527 void st_init_drawpixels_functions(struct dd_function_table *functions)
1528 {
1529    functions->DrawPixels = st_DrawPixels;
1530    functions->CopyPixels = st_CopyPixels;
1531 }
1532
1533
1534 void
1535 st_destroy_drawpix(struct st_context *st)
1536 {
1537    GLuint i;
1538
1539    for (i = 0; i < Elements(st->drawpix.shaders); i++) {
1540       if (st->drawpix.shaders[i])
1541          _mesa_reference_fragprog(st->ctx, &st->drawpix.shaders[i], NULL);
1542    }
1543
1544    st_reference_fragprog(st, &st->pixel_xfer.combined_prog, NULL);
1545    if (st->drawpix.vert_shaders[0])
1546       ureg_free_tokens(st->drawpix.vert_shaders[0]);
1547    if (st->drawpix.vert_shaders[1])
1548       ureg_free_tokens(st->drawpix.vert_shaders[1]);
1549 }
1550
1551 #endif /* FEATURE_drawpix */