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