st_cb_texture.c revision 45dac0d82a5a69166e86dce77c2550f7512c541e
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#include "main/mfeatures.h"
29#include "main/bufferobj.h"
30#if FEATURE_convolve
31#include "main/convolve.h"
32#endif
33#include "main/enums.h"
34#include "main/fbobject.h"
35#include "main/formats.h"
36#include "main/image.h"
37#include "main/imports.h"
38#include "main/macros.h"
39#include "main/mipmap.h"
40#include "main/texcompress.h"
41#include "main/texfetch.h"
42#include "main/texgetimage.h"
43#include "main/teximage.h"
44#include "main/texobj.h"
45#include "main/texstore.h"
46
47#include "state_tracker/st_debug.h"
48#include "state_tracker/st_context.h"
49#include "state_tracker/st_cb_fbo.h"
50#include "state_tracker/st_cb_texture.h"
51#include "state_tracker/st_format.h"
52#include "state_tracker/st_public.h"
53#include "state_tracker/st_texture.h"
54#include "state_tracker/st_gen_mipmap.h"
55#include "state_tracker/st_inlines.h"
56#include "state_tracker/st_atom.h"
57
58#include "pipe/p_context.h"
59#include "pipe/p_defines.h"
60#include "util/u_inlines.h"
61#include "pipe/p_shader_tokens.h"
62#include "util/u_tile.h"
63#include "util/u_blit.h"
64#include "util/u_format.h"
65#include "util/u_surface.h"
66#include "util/u_math.h"
67
68
69#define DBG if (0) printf
70
71
72static enum pipe_texture_target
73gl_target_to_pipe(GLenum target)
74{
75   switch (target) {
76   case GL_TEXTURE_1D:
77      return PIPE_TEXTURE_1D;
78
79   case GL_TEXTURE_2D:
80   case GL_TEXTURE_RECTANGLE_NV:
81      return PIPE_TEXTURE_2D;
82
83   case GL_TEXTURE_3D:
84      return PIPE_TEXTURE_3D;
85
86   case GL_TEXTURE_CUBE_MAP_ARB:
87      return PIPE_TEXTURE_CUBE;
88
89   default:
90      assert(0);
91      return 0;
92   }
93}
94
95
96/** called via ctx->Driver.NewTextureImage() */
97static struct gl_texture_image *
98st_NewTextureImage(GLcontext * ctx)
99{
100   DBG("%s\n", __FUNCTION__);
101   (void) ctx;
102   return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
103}
104
105
106/** called via ctx->Driver.NewTextureObject() */
107static struct gl_texture_object *
108st_NewTextureObject(GLcontext * ctx, GLuint name, GLenum target)
109{
110   struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
111
112   DBG("%s\n", __FUNCTION__);
113   _mesa_initialize_texture_object(&obj->base, name, target);
114
115   return &obj->base;
116}
117
118/** called via ctx->Driver.DeleteTextureImage() */
119static void
120st_DeleteTextureObject(GLcontext *ctx,
121                       struct gl_texture_object *texObj)
122{
123   struct st_texture_object *stObj = st_texture_object(texObj);
124   if (stObj->pt)
125      pipe_texture_reference(&stObj->pt, NULL);
126
127   _mesa_delete_texture_object(ctx, texObj);
128}
129
130
131/** called via ctx->Driver.FreeTexImageData() */
132static void
133st_FreeTextureImageData(GLcontext * ctx, struct gl_texture_image *texImage)
134{
135   struct st_texture_image *stImage = st_texture_image(texImage);
136
137   DBG("%s\n", __FUNCTION__);
138
139   if (stImage->pt) {
140      pipe_texture_reference(&stImage->pt, NULL);
141   }
142
143   if (texImage->Data) {
144      _mesa_align_free(texImage->Data);
145      texImage->Data = NULL;
146   }
147}
148
149
150/**
151 * From linux kernel i386 header files, copes with odd sizes better
152 * than COPY_DWORDS would:
153 * XXX Put this in src/mesa/main/imports.h ???
154 */
155#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
156static INLINE void *
157__memcpy(void *to, const void *from, size_t n)
158{
159   int d0, d1, d2;
160   __asm__ __volatile__("rep ; movsl\n\t"
161                        "testb $2,%b4\n\t"
162                        "je 1f\n\t"
163                        "movsw\n"
164                        "1:\ttestb $1,%b4\n\t"
165                        "je 2f\n\t"
166                        "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
167                        :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
168                        :"memory");
169   return (to);
170}
171#else
172#define __memcpy(a,b,c) memcpy(a,b,c)
173#endif
174
175
176/**
177 * The system memcpy (at least on ubuntu 5.10) has problems copying
178 * to agp (writecombined) memory from a source which isn't 64-byte
179 * aligned - there is a 4x performance falloff.
180 *
181 * The x86 __memcpy is immune to this but is slightly slower
182 * (10%-ish) than the system memcpy.
183 *
184 * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
185 * isn't much faster than x86_memcpy for agp copies.
186 *
187 * TODO: switch dynamically.
188 */
189static void *
190do_memcpy(void *dest, const void *src, size_t n)
191{
192   if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
193      return __memcpy(dest, src, n);
194   }
195   else
196      return memcpy(dest, src, n);
197}
198
199
200/**
201 * Return default texture usage bitmask for the given texture format.
202 */
203static GLuint
204default_usage(enum pipe_format fmt)
205{
206   GLuint usage = PIPE_TEXTURE_USAGE_SAMPLER;
207   if (util_format_is_depth_or_stencil(fmt))
208      usage |= PIPE_TEXTURE_USAGE_DEPTH_STENCIL;
209   else
210      usage |= PIPE_TEXTURE_USAGE_RENDER_TARGET;
211   return usage;
212}
213
214
215/**
216 * Allocate a pipe_texture object for the given st_texture_object using
217 * the given st_texture_image to guess the mipmap size/levels.
218 *
219 * [comments...]
220 * Otherwise, store it in memory if (Border != 0) or (any dimension ==
221 * 1).
222 *
223 * Otherwise, if max_level >= level >= min_level, create texture with
224 * space for images from min_level down to max_level.
225 *
226 * Otherwise, create texture with space for images from (level 0)..(1x1).
227 * Consider pruning this texture at a validation if the saving is worth it.
228 */
229static void
230guess_and_alloc_texture(struct st_context *st,
231			struct st_texture_object *stObj,
232			const struct st_texture_image *stImage)
233{
234   GLuint firstLevel;
235   GLuint lastLevel;
236   GLuint width = stImage->base.Width2;  /* size w/out border */
237   GLuint height = stImage->base.Height2;
238   GLuint depth = stImage->base.Depth2;
239   GLuint i, usage;
240   enum pipe_format fmt;
241
242   DBG("%s\n", __FUNCTION__);
243
244   assert(!stObj->pt);
245
246   if (stObj->pt &&
247       (GLint) stImage->level > stObj->base.BaseLevel &&
248       (stImage->base.Width == 1 ||
249        (stObj->base.Target != GL_TEXTURE_1D &&
250         stImage->base.Height == 1) ||
251        (stObj->base.Target == GL_TEXTURE_3D &&
252         stImage->base.Depth == 1)))
253      return;
254
255   /* If this image disrespects BaseLevel, allocate from level zero.
256    * Usually BaseLevel == 0, so it's unlikely to happen.
257    */
258   if ((GLint) stImage->level < stObj->base.BaseLevel)
259      firstLevel = 0;
260   else
261      firstLevel = stObj->base.BaseLevel;
262
263
264   /* Figure out image dimensions at start level.
265    */
266   for (i = stImage->level; i > firstLevel; i--) {
267      if (width != 1)
268         width <<= 1;
269      if (height != 1)
270         height <<= 1;
271      if (depth != 1)
272         depth <<= 1;
273   }
274
275   if (width == 0 || height == 0 || depth == 0) {
276      /* no texture needed */
277      return;
278   }
279
280   /* Guess a reasonable value for lastLevel.  This is probably going
281    * to be wrong fairly often and might mean that we have to look at
282    * resizable buffers, or require that buffers implement lazy
283    * pagetable arrangements.
284    */
285   if ((stObj->base.MinFilter == GL_NEAREST ||
286        stObj->base.MinFilter == GL_LINEAR ||
287        stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
288        stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
289       !stObj->base.GenerateMipmap &&
290       stImage->level == firstLevel) {
291      /* only alloc space for a single mipmap level */
292      lastLevel = firstLevel;
293   }
294   else {
295      /* alloc space for a full mipmap */
296      GLuint l2width = util_logbase2(width);
297      GLuint l2height = util_logbase2(height);
298      GLuint l2depth = util_logbase2(depth);
299      lastLevel = firstLevel + MAX2(MAX2(l2width, l2height), l2depth);
300   }
301
302   fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
303
304   usage = default_usage(fmt);
305
306   stObj->pt = st_texture_create(st,
307                                 gl_target_to_pipe(stObj->base.Target),
308                                 fmt,
309                                 lastLevel,
310                                 width,
311                                 height,
312                                 depth,
313                                 usage);
314
315   DBG("%s - success\n", __FUNCTION__);
316}
317
318
319/**
320 * Adjust pixel unpack params and image dimensions to strip off the
321 * texture border.
322 * Gallium doesn't support texture borders.  They've seldem been used
323 * and seldom been implemented correctly anyway.
324 * \param unpackNew  returns the new pixel unpack parameters
325 */
326static void
327strip_texture_border(GLint border,
328                     GLint *width, GLint *height, GLint *depth,
329                     const struct gl_pixelstore_attrib *unpack,
330                     struct gl_pixelstore_attrib *unpackNew)
331{
332   assert(border > 0);  /* sanity check */
333
334   *unpackNew = *unpack;
335
336   if (unpackNew->RowLength == 0)
337      unpackNew->RowLength = *width;
338
339   if (depth && unpackNew->ImageHeight == 0)
340      unpackNew->ImageHeight = *height;
341
342   unpackNew->SkipPixels += border;
343   if (height)
344      unpackNew->SkipRows += border;
345   if (depth)
346      unpackNew->SkipImages += border;
347
348   assert(*width >= 3);
349   *width = *width - 2 * border;
350   if (height && *height >= 3)
351      *height = *height - 2 * border;
352   if (depth && *depth >= 3)
353      *depth = *depth - 2 * border;
354}
355
356
357/**
358 * Try to do texture compression via rendering.  If the Gallium driver
359 * can render into a compressed surface this will allow us to do texture
360 * compression.
361 * \return GL_TRUE for success, GL_FALSE for failure
362 */
363static GLboolean
364compress_with_blit(GLcontext * ctx,
365                   GLenum target, GLint level,
366                   GLint xoffset, GLint yoffset, GLint zoffset,
367                   GLint width, GLint height, GLint depth,
368                   GLenum format, GLenum type, const void *pixels,
369                   const struct gl_pixelstore_attrib *unpack,
370                   struct gl_texture_image *texImage)
371{
372   const GLuint dstImageOffsets[1] = {0};
373   struct st_texture_image *stImage = st_texture_image(texImage);
374   struct pipe_screen *screen = ctx->st->pipe->screen;
375   gl_format mesa_format;
376   struct pipe_texture templ;
377   struct pipe_texture *src_tex;
378   struct pipe_surface *dst_surface;
379   struct pipe_transfer *tex_xfer;
380   void *map;
381
382   if (!stImage->pt) {
383      /* XXX: Can this happen? Should we assert? */
384      return GL_FALSE;
385   }
386
387   /* get destination surface (in the compressed texture) */
388   dst_surface = screen->get_tex_surface(screen, stImage->pt,
389                                         stImage->face, stImage->level, 0,
390                                         PIPE_BUFFER_USAGE_GPU_WRITE);
391   if (!dst_surface) {
392      /* can't render into this format (or other problem) */
393      return GL_FALSE;
394   }
395
396   /* Choose format for the temporary RGBA texture image.
397    */
398   mesa_format = st_ChooseTextureFormat(ctx, GL_RGBA, format, type);
399   assert(mesa_format);
400   if (!mesa_format)
401      return GL_FALSE;
402
403   /* Create the temporary source texture
404    */
405   memset(&templ, 0, sizeof(templ));
406   templ.target = PIPE_TEXTURE_2D;
407   templ.format = st_mesa_format_to_pipe_format(mesa_format);
408   templ.width0 = width;
409   templ.height0 = height;
410   templ.depth0 = 1;
411   templ.last_level = 0;
412   templ.tex_usage = PIPE_TEXTURE_USAGE_SAMPLER;
413   src_tex = screen->texture_create(screen, &templ);
414
415   if (!src_tex)
416      return GL_FALSE;
417
418   /* Put user's tex data into the temporary texture
419    */
420   tex_xfer = st_cond_flush_get_tex_transfer(st_context(ctx), src_tex,
421					     0, 0, 0, /* face, level are zero */
422					     PIPE_TRANSFER_WRITE,
423					     0, 0, width, height); /* x, y, w, h */
424   map = screen->transfer_map(screen, tex_xfer);
425
426   _mesa_texstore(ctx, 2, GL_RGBA, mesa_format,
427                  map,              /* dest ptr */
428                  0, 0, 0,          /* dest x/y/z offset */
429                  tex_xfer->stride, /* dest row stride (bytes) */
430                  dstImageOffsets,  /* image offsets (for 3D only) */
431                  width, height, 1, /* size */
432                  format, type,     /* source format/type */
433                  pixels,           /* source data */
434                  unpack);          /* source data packing */
435
436   screen->transfer_unmap(screen, tex_xfer);
437   screen->tex_transfer_destroy(tex_xfer);
438
439   /* copy / compress image */
440   util_blit_pixels_tex(ctx->st->blit,
441                        src_tex,          /* pipe_texture (src) */
442                        0, 0,             /* src x0, y0 */
443                        width, height,    /* src x1, y1 */
444                        dst_surface,      /* pipe_surface (dst) */
445                        xoffset, yoffset, /* dst x0, y0 */
446                        xoffset + width,  /* dst x1 */
447                        yoffset + height, /* dst y1 */
448                        0.0,              /* z */
449                        PIPE_TEX_MIPFILTER_NEAREST);
450
451   pipe_surface_reference(&dst_surface, NULL);
452   pipe_texture_reference(&src_tex, NULL);
453
454   return GL_TRUE;
455}
456
457
458/**
459 * Do glTexImage1/2/3D().
460 */
461static void
462st_TexImage(GLcontext * ctx,
463            GLint dims,
464            GLenum target, GLint level,
465            GLint internalFormat,
466            GLint width, GLint height, GLint depth,
467            GLint border,
468            GLenum format, GLenum type, const void *pixels,
469            const struct gl_pixelstore_attrib *unpack,
470            struct gl_texture_object *texObj,
471            struct gl_texture_image *texImage,
472            GLsizei imageSize, GLboolean compressed_src)
473{
474   struct pipe_screen *screen = ctx->st->pipe->screen;
475   struct st_texture_object *stObj = st_texture_object(texObj);
476   struct st_texture_image *stImage = st_texture_image(texImage);
477   GLint postConvWidth, postConvHeight;
478   GLint texelBytes, sizeInBytes;
479   GLuint dstRowStride = 0;
480   struct gl_pixelstore_attrib unpackNB;
481   enum pipe_transfer_usage transfer_usage = 0;
482
483   DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
484       _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
485
486   /* switch to "normal" */
487   if (stObj->surface_based) {
488      _mesa_clear_texture_object(ctx, texObj);
489      stObj->surface_based = GL_FALSE;
490   }
491
492   /* gallium does not support texture borders, strip it off */
493   if (border) {
494      strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
495      unpack = &unpackNB;
496      texImage->Width = width;
497      texImage->Height = height;
498      texImage->Depth = depth;
499      texImage->Border = 0;
500      border = 0;
501   }
502
503   postConvWidth = width;
504   postConvHeight = height;
505
506   stImage->face = _mesa_tex_target_to_face(target);
507   stImage->level = level;
508
509#if FEATURE_convolve
510   if (ctx->_ImageTransferState & IMAGE_CONVOLUTION_BIT) {
511      _mesa_adjust_image_for_convolution(ctx, dims, &postConvWidth,
512                                         &postConvHeight);
513   }
514#endif
515
516   _mesa_set_fetch_functions(texImage, dims);
517
518   if (_mesa_is_format_compressed(texImage->TexFormat)) {
519      /* must be a compressed format */
520      texelBytes = 0;
521   }
522   else {
523      texelBytes = _mesa_get_format_bytes(texImage->TexFormat);
524
525      /* Minimum pitch of 32 bytes */
526      if (postConvWidth * texelBytes < 32) {
527	 postConvWidth = 32 / texelBytes;
528	 texImage->RowStride = postConvWidth;
529      }
530
531      /* we'll set RowStride elsewhere when the texture is a "mapped" state */
532      /*assert(texImage->RowStride == postConvWidth);*/
533   }
534
535   /* Release the reference to a potentially orphaned buffer.
536    * Release any old malloced memory.
537    */
538   if (stImage->pt) {
539      pipe_texture_reference(&stImage->pt, NULL);
540      assert(!texImage->Data);
541   }
542   else if (texImage->Data) {
543      _mesa_align_free(texImage->Data);
544   }
545
546   /*
547    * See if the new image is somehow incompatible with the existing
548    * mipmap.  If so, free the old mipmap.
549    */
550   if (stObj->pt) {
551      if (stObj->teximage_realloc ||
552          level > (GLint) stObj->pt->last_level ||
553          !st_texture_match_image(stObj->pt, &stImage->base,
554                                  stImage->face, stImage->level)) {
555         DBG("release it\n");
556         pipe_texture_reference(&stObj->pt, NULL);
557         assert(!stObj->pt);
558         stObj->teximage_realloc = FALSE;
559      }
560   }
561
562   if (width == 0 || height == 0 || depth == 0) {
563      /* stop after freeing old image */
564      return;
565   }
566
567   if (!stObj->pt) {
568      guess_and_alloc_texture(ctx->st, stObj, stImage);
569      if (!stObj->pt) {
570         /* Probably out of memory.
571          * Try flushing any pending rendering, then retry.
572          */
573         st_finish(ctx->st);
574         guess_and_alloc_texture(ctx->st, stObj, stImage);
575         if (!stObj->pt) {
576            _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
577            return;
578         }
579      }
580   }
581
582   assert(!stImage->pt);
583
584   if (stObj->pt &&
585       st_texture_match_image(stObj->pt, &stImage->base,
586                                 stImage->face, stImage->level)) {
587
588      pipe_texture_reference(&stImage->pt, stObj->pt);
589      assert(stImage->pt);
590   }
591
592   if (!stImage->pt)
593      DBG("XXX: Image did not fit into texture - storing in local memory!\n");
594
595   /* st_CopyTexImage calls this function with pixels == NULL, with
596    * the expectation that the texture will be set up but nothing
597    * more will be done.  This is where those calls return:
598    */
599   if (compressed_src) {
600      pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
601						      unpack,
602						      "glCompressedTexImage");
603   }
604   else {
605      pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
606					   format, type,
607					   pixels, unpack, "glTexImage");
608   }
609
610   /* Note: we can't check for pixels==NULL until after we've allocated
611    * memory for the texture.
612    */
613
614   /* See if we can do texture compression with a blit/render.
615    */
616   if (!compressed_src &&
617       !ctx->Mesa_DXTn &&
618       _mesa_is_format_compressed(texImage->TexFormat) &&
619       screen->is_format_supported(screen,
620                                   stImage->pt->format,
621                                   stImage->pt->target,
622                                   PIPE_TEXTURE_USAGE_RENDER_TARGET, 0)) {
623      if (!pixels)
624         goto done;
625
626      if (compress_with_blit(ctx, target, level, 0, 0, 0, width, height, depth,
627                             format, type, pixels, unpack, texImage)) {
628         goto done;
629      }
630   }
631
632   if (stImage->pt) {
633      if (format == GL_DEPTH_COMPONENT &&
634          util_format_is_depth_and_stencil(stImage->pt->format))
635         transfer_usage = PIPE_TRANSFER_READ_WRITE;
636      else
637         transfer_usage = PIPE_TRANSFER_WRITE;
638
639      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
640                                            transfer_usage, 0, 0,
641                                            stImage->base.Width,
642                                            stImage->base.Height);
643      if(stImage->transfer)
644         dstRowStride = stImage->transfer->stride;
645   }
646   else {
647      /* Allocate regular memory and store the image there temporarily.   */
648      if (_mesa_is_format_compressed(texImage->TexFormat)) {
649         sizeInBytes = _mesa_format_image_size(texImage->TexFormat,
650                                               texImage->Width,
651                                               texImage->Height,
652                                               texImage->Depth);
653         dstRowStride = _mesa_format_row_stride(texImage->TexFormat, width);
654         assert(dims != 3);
655      }
656      else {
657         dstRowStride = postConvWidth * texelBytes;
658         sizeInBytes = depth * dstRowStride * postConvHeight;
659      }
660
661      texImage->Data = _mesa_align_malloc(sizeInBytes, 16);
662   }
663
664   if (!texImage->Data) {
665      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
666      return;
667   }
668
669   if (!pixels)
670      goto done;
671
672   DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
673       width, height, depth, width * texelBytes, dstRowStride);
674
675   /* Copy data.  Would like to know when it's ok for us to eg. use
676    * the blitter to copy.  Or, use the hardware to do the format
677    * conversion and copy:
678    */
679   if (compressed_src) {
680      const GLuint srcImageStride = _mesa_format_row_stride(texImage->TexFormat, width);
681      if(dstRowStride == srcImageStride)
682         memcpy(texImage->Data, pixels, imageSize);
683      else
684      {
685         char *dst = texImage->Data;
686         const char *src = pixels;
687         GLuint i, bw, bh, lines;
688         _mesa_get_format_block_size(texImage->TexFormat, &bw, &bh);
689         lines = (height + bh - 1) / bh;
690
691         for(i = 0; i < lines; ++i)
692         {
693            memcpy(dst, src, srcImageStride);
694            dst += dstRowStride;
695            src += srcImageStride;
696         }
697      }
698   }
699   else {
700      const GLuint srcImageStride =
701         _mesa_image_image_stride(unpack, width, height, format, type);
702      GLint i;
703      const GLubyte *src = (const GLubyte *) pixels;
704
705      for (i = 0; i < depth; i++) {
706	 if (!_mesa_texstore(ctx, dims,
707                             texImage->_BaseFormat,
708                             texImage->TexFormat,
709                             texImage->Data,
710                             0, 0, 0, /* dstX/Y/Zoffset */
711                             dstRowStride,
712                             texImage->ImageOffsets,
713                             width, height, 1,
714                             format, type, src, unpack)) {
715	    _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
716	 }
717
718	 if (stImage->pt && i + 1 < depth) {
719            /* unmap this slice */
720	    st_texture_image_unmap(ctx->st, stImage);
721            /* map next slice of 3D texture */
722	    texImage->Data = st_texture_image_map(ctx->st, stImage, i + 1,
723                                                  transfer_usage, 0, 0,
724                                                  stImage->base.Width,
725                                                  stImage->base.Height);
726	    src += srcImageStride;
727	 }
728      }
729   }
730
731done:
732   _mesa_unmap_teximage_pbo(ctx, unpack);
733
734   if (stImage->pt && texImage->Data) {
735      st_texture_image_unmap(ctx->st, stImage);
736      texImage->Data = NULL;
737   }
738}
739
740
741static void
742st_TexImage3D(GLcontext * ctx,
743              GLenum target, GLint level,
744              GLint internalFormat,
745              GLint width, GLint height, GLint depth,
746              GLint border,
747              GLenum format, GLenum type, const void *pixels,
748              const struct gl_pixelstore_attrib *unpack,
749              struct gl_texture_object *texObj,
750              struct gl_texture_image *texImage)
751{
752   st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
753               border, format, type, pixels, unpack, texObj, texImage,
754               0, GL_FALSE);
755}
756
757
758static void
759st_TexImage2D(GLcontext * ctx,
760              GLenum target, GLint level,
761              GLint internalFormat,
762              GLint width, GLint height, GLint border,
763              GLenum format, GLenum type, const void *pixels,
764              const struct gl_pixelstore_attrib *unpack,
765              struct gl_texture_object *texObj,
766              struct gl_texture_image *texImage)
767{
768   st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
769               format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
770}
771
772
773static void
774st_TexImage1D(GLcontext * ctx,
775              GLenum target, GLint level,
776              GLint internalFormat,
777              GLint width, GLint border,
778              GLenum format, GLenum type, const void *pixels,
779              const struct gl_pixelstore_attrib *unpack,
780              struct gl_texture_object *texObj,
781              struct gl_texture_image *texImage)
782{
783   st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
784               format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
785}
786
787
788static void
789st_CompressedTexImage2D(GLcontext *ctx, GLenum target, GLint level,
790                        GLint internalFormat,
791                        GLint width, GLint height, GLint border,
792                        GLsizei imageSize, const GLvoid *data,
793                        struct gl_texture_object *texObj,
794                        struct gl_texture_image *texImage)
795{
796   st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
797               0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
798}
799
800
801
802/**
803 * glGetTexImage() helper: decompress a compressed texture by rendering
804 * a textured quad.  Store the results in the user's buffer.
805 */
806static void
807decompress_with_blit(GLcontext * ctx, GLenum target, GLint level,
808                     GLenum format, GLenum type, GLvoid *pixels,
809                     struct gl_texture_object *texObj,
810                     struct gl_texture_image *texImage)
811{
812   struct pipe_screen *screen = ctx->st->pipe->screen;
813   struct st_texture_image *stImage = st_texture_image(texImage);
814   const GLuint width = texImage->Width;
815   const GLuint height = texImage->Height;
816   struct pipe_surface *dst_surface;
817   struct pipe_texture *dst_texture;
818   struct pipe_transfer *tex_xfer;
819
820   /* create temp / dest surface */
821   if (!util_create_rgba_surface(screen, width, height,
822                                 &dst_texture, &dst_surface)) {
823      _mesa_problem(ctx, "util_create_rgba_surface() failed "
824                    "in decompress_with_blit()");
825      return;
826   }
827
828   /* blit/render/decompress */
829   util_blit_pixels_tex(ctx->st->blit,
830                        stImage->pt,      /* pipe_texture (src) */
831                        0, 0,             /* src x0, y0 */
832                        width, height,    /* src x1, y1 */
833                        dst_surface,      /* pipe_surface (dst) */
834                        0, 0,             /* dst x0, y0 */
835                        width, height,    /* dst x1, y1 */
836                        0.0,              /* z */
837                        PIPE_TEX_MIPFILTER_NEAREST);
838
839   /* map the dst_surface so we can read from it */
840   tex_xfer = st_cond_flush_get_tex_transfer(st_context(ctx),
841					     dst_texture, 0, 0, 0,
842					     PIPE_TRANSFER_READ,
843					     0, 0, width, height);
844
845   pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
846
847   /* copy/pack data into user buffer */
848   if (st_equal_formats(stImage->pt->format, format, type)) {
849      /* memcpy */
850      const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
851      ubyte *map = screen->transfer_map(screen, tex_xfer);
852      GLuint row;
853      for (row = 0; row < height; row++) {
854         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
855                                              height, format, type, row, 0);
856         memcpy(dest, map, bytesPerRow);
857         map += tex_xfer->stride;
858      }
859      screen->transfer_unmap(screen, tex_xfer);
860   }
861   else {
862      /* format translation via floats */
863      GLuint row;
864      for (row = 0; row < height; row++) {
865         const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
866         GLfloat rgba[4 * MAX_WIDTH];
867         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
868                                              height, format, type, row, 0);
869
870         if (ST_DEBUG & DEBUG_FALLBACK)
871            debug_printf("%s: fallback format translation\n", __FUNCTION__);
872
873         /* get float[4] rgba row from surface */
874         pipe_get_tile_rgba(tex_xfer, 0, row, width, 1, rgba);
875
876         _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
877                                    type, dest, &ctx->Pack, transferOps);
878      }
879   }
880
881   _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
882
883   /* destroy the temp / dest surface */
884   util_destroy_rgba_surface(dst_texture, dst_surface);
885}
886
887
888
889/**
890 * Need to map texture image into memory before copying image data,
891 * then unmap it.
892 */
893static void
894st_get_tex_image(GLcontext * ctx, GLenum target, GLint level,
895                 GLenum format, GLenum type, GLvoid * pixels,
896                 struct gl_texture_object *texObj,
897                 struct gl_texture_image *texImage, GLboolean compressed_dst)
898{
899   struct st_texture_image *stImage = st_texture_image(texImage);
900   const GLuint dstImageStride =
901      _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
902                               format, type);
903   GLuint depth, i;
904   GLubyte *dest;
905
906   if (stImage->pt &&
907       util_format_is_compressed(stImage->pt->format) &&
908       !compressed_dst) {
909      /* Need to decompress the texture.
910       * We'll do this by rendering a textured quad.
911       * Note that we only expect RGBA formats (no Z/depth formats).
912       */
913      decompress_with_blit(ctx, target, level, format, type, pixels,
914                           texObj, texImage);
915      return;
916   }
917
918   /* Map */
919   if (stImage->pt) {
920      /* Image is stored in hardware format in a buffer managed by the
921       * kernel.  Need to explicitly map and unmap it.
922       */
923      unsigned face = _mesa_tex_target_to_face(target);
924
925      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
926				   PIPE_TRANSFER_READ);
927
928      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
929                                            PIPE_TRANSFER_READ, 0, 0,
930                                            stImage->base.Width,
931                                            stImage->base.Height);
932      texImage->RowStride = stImage->transfer->stride / util_format_get_blocksize(stImage->pt->format);
933   }
934   else {
935      /* Otherwise, the image should actually be stored in
936       * texImage->Data.  This is pretty confusing for
937       * everybody, I'd much prefer to separate the two functions of
938       * texImage->Data - storage for texture images in main memory
939       * and access (ie mappings) of images.  In other words, we'd
940       * create a new texImage->Map field and leave Data simply for
941       * storage.
942       */
943      assert(texImage->Data);
944   }
945
946   depth = texImage->Depth;
947   texImage->Depth = 1;
948
949   dest = (GLubyte *) pixels;
950
951   for (i = 0; i < depth; i++) {
952      if (compressed_dst) {
953	 _mesa_get_compressed_teximage(ctx, target, level, dest,
954				       texObj, texImage);
955      }
956      else {
957	 _mesa_get_teximage(ctx, target, level, format, type, dest,
958			    texObj, texImage);
959      }
960
961      if (stImage->pt && i + 1 < depth) {
962         /* unmap this slice */
963	 st_texture_image_unmap(ctx->st, stImage);
964         /* map next slice of 3D texture */
965	 texImage->Data = st_texture_image_map(ctx->st, stImage, i + 1,
966                                               PIPE_TRANSFER_READ, 0, 0,
967                                               stImage->base.Width,
968                                               stImage->base.Height);
969	 dest += dstImageStride;
970      }
971   }
972
973   texImage->Depth = depth;
974
975   /* Unmap */
976   if (stImage->pt) {
977      st_texture_image_unmap(ctx->st, stImage);
978      texImage->Data = NULL;
979   }
980}
981
982
983static void
984st_GetTexImage(GLcontext * ctx, GLenum target, GLint level,
985               GLenum format, GLenum type, GLvoid * pixels,
986               struct gl_texture_object *texObj,
987               struct gl_texture_image *texImage)
988{
989   st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
990                    GL_FALSE);
991}
992
993
994static void
995st_GetCompressedTexImage(GLcontext *ctx, GLenum target, GLint level,
996                         GLvoid *pixels,
997                         struct gl_texture_object *texObj,
998                         struct gl_texture_image *texImage)
999{
1000   st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
1001                    GL_TRUE);
1002}
1003
1004
1005
1006static void
1007st_TexSubimage(GLcontext *ctx, GLint dims, GLenum target, GLint level,
1008               GLint xoffset, GLint yoffset, GLint zoffset,
1009               GLint width, GLint height, GLint depth,
1010               GLenum format, GLenum type, const void *pixels,
1011               const struct gl_pixelstore_attrib *packing,
1012               struct gl_texture_object *texObj,
1013               struct gl_texture_image *texImage)
1014{
1015   struct pipe_screen *screen = ctx->st->pipe->screen;
1016   struct st_texture_image *stImage = st_texture_image(texImage);
1017   GLuint dstRowStride;
1018   const GLuint srcImageStride =
1019      _mesa_image_image_stride(packing, width, height, format, type);
1020   GLint i;
1021   const GLubyte *src;
1022   /* init to silence warning only: */
1023   enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
1024
1025   DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
1026       _mesa_lookup_enum_by_nr(target),
1027       level, xoffset, yoffset, width, height);
1028
1029   pixels =
1030      _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
1031                                  type, pixels, packing, "glTexSubImage2D");
1032   if (!pixels)
1033      return;
1034
1035   /* See if we can do texture compression with a blit/render.
1036    */
1037   if (!ctx->Mesa_DXTn &&
1038       _mesa_is_format_compressed(texImage->TexFormat) &&
1039       screen->is_format_supported(screen,
1040                                   stImage->pt->format,
1041                                   stImage->pt->target,
1042                                   PIPE_TEXTURE_USAGE_RENDER_TARGET, 0)) {
1043      if (compress_with_blit(ctx, target, level,
1044                             xoffset, yoffset, zoffset,
1045                             width, height, depth,
1046                             format, type, pixels, packing, texImage)) {
1047         goto done;
1048      }
1049   }
1050
1051   /* Map buffer if necessary.  Need to lock to prevent other contexts
1052    * from uploading the buffer under us.
1053    */
1054   if (stImage->pt) {
1055      unsigned face = _mesa_tex_target_to_face(target);
1056
1057      if (format == GL_DEPTH_COMPONENT &&
1058          util_format_is_depth_and_stencil(stImage->pt->format))
1059         transfer_usage = PIPE_TRANSFER_READ_WRITE;
1060      else
1061         transfer_usage = PIPE_TRANSFER_WRITE;
1062
1063      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
1064				   transfer_usage);
1065      texImage->Data = st_texture_image_map(ctx->st, stImage, zoffset,
1066                                            transfer_usage,
1067                                            xoffset, yoffset,
1068                                            width, height);
1069   }
1070
1071   if (!texImage->Data) {
1072      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1073      goto done;
1074   }
1075
1076   src = (const GLubyte *) pixels;
1077   dstRowStride = stImage->transfer->stride;
1078
1079   for (i = 0; i < depth; i++) {
1080      if (!_mesa_texstore(ctx, dims, texImage->_BaseFormat,
1081                          texImage->TexFormat,
1082                          texImage->Data,
1083                          0, 0, 0,
1084                          dstRowStride,
1085                          texImage->ImageOffsets,
1086                          width, height, 1,
1087                          format, type, src, packing)) {
1088	 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1089      }
1090
1091      if (stImage->pt && i + 1 < depth) {
1092         /* unmap this slice */
1093	 st_texture_image_unmap(ctx->st, stImage);
1094         /* map next slice of 3D texture */
1095	 texImage->Data = st_texture_image_map(ctx->st, stImage,
1096                                               zoffset + i + 1,
1097                                               transfer_usage,
1098                                               xoffset, yoffset,
1099                                               width, height);
1100	 src += srcImageStride;
1101      }
1102   }
1103
1104done:
1105   _mesa_unmap_teximage_pbo(ctx, packing);
1106
1107   if (stImage->pt && texImage->Data) {
1108      st_texture_image_unmap(ctx->st, stImage);
1109      texImage->Data = NULL;
1110   }
1111}
1112
1113
1114
1115static void
1116st_TexSubImage3D(GLcontext *ctx, GLenum target, GLint level,
1117                 GLint xoffset, GLint yoffset, GLint zoffset,
1118                 GLsizei width, GLsizei height, GLsizei depth,
1119                 GLenum format, GLenum type, const GLvoid *pixels,
1120                 const struct gl_pixelstore_attrib *packing,
1121                 struct gl_texture_object *texObj,
1122                 struct gl_texture_image *texImage)
1123{
1124   st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
1125                  width, height, depth, format, type,
1126                  pixels, packing, texObj, texImage);
1127}
1128
1129
1130static void
1131st_TexSubImage2D(GLcontext *ctx, GLenum target, GLint level,
1132                 GLint xoffset, GLint yoffset,
1133                 GLsizei width, GLsizei height,
1134                 GLenum format, GLenum type, const GLvoid * pixels,
1135                 const struct gl_pixelstore_attrib *packing,
1136                 struct gl_texture_object *texObj,
1137                 struct gl_texture_image *texImage)
1138{
1139   st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
1140                  width, height, 1, format, type,
1141                  pixels, packing, texObj, texImage);
1142}
1143
1144
1145static void
1146st_TexSubImage1D(GLcontext *ctx, GLenum target, GLint level,
1147                 GLint xoffset, GLsizei width, GLenum format, GLenum type,
1148                 const GLvoid * pixels,
1149                 const struct gl_pixelstore_attrib *packing,
1150                 struct gl_texture_object *texObj,
1151                 struct gl_texture_image *texImage)
1152{
1153   st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
1154                  format, type, pixels, packing, texObj, texImage);
1155}
1156
1157
1158static void
1159st_CompressedTexSubImage1D(GLcontext *ctx, GLenum target, GLint level,
1160                           GLint xoffset, GLsizei width,
1161                           GLenum format,
1162                           GLsizei imageSize, const GLvoid *data,
1163                           struct gl_texture_object *texObj,
1164                           struct gl_texture_image *texImage)
1165{
1166   assert(0);
1167}
1168
1169
1170static void
1171st_CompressedTexSubImage2D(GLcontext *ctx, GLenum target, GLint level,
1172                           GLint xoffset, GLint yoffset,
1173                           GLsizei width, GLint height,
1174                           GLenum format,
1175                           GLsizei imageSize, const GLvoid *data,
1176                           struct gl_texture_object *texObj,
1177                           struct gl_texture_image *texImage)
1178{
1179   struct st_texture_image *stImage = st_texture_image(texImage);
1180   int srcBlockStride;
1181   int dstBlockStride;
1182   int y;
1183   enum pipe_format pformat= stImage->pt->format;
1184
1185   if (stImage->pt) {
1186      unsigned face = _mesa_tex_target_to_face(target);
1187
1188      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
1189				   PIPE_TRANSFER_WRITE);
1190      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
1191                                            PIPE_TRANSFER_WRITE,
1192                                            xoffset, yoffset,
1193                                            width, height);
1194
1195      srcBlockStride = util_format_get_stride(pformat, width);
1196      dstBlockStride = stImage->transfer->stride;
1197   } else {
1198      assert(stImage->pt);
1199      /* TODO find good values for block and strides */
1200      /* TODO also adjust texImage->data for yoffset/xoffset */
1201      return;
1202   }
1203
1204   if (!texImage->Data) {
1205      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
1206      return;
1207   }
1208
1209   assert(xoffset % util_format_get_blockwidth(pformat) == 0);
1210   assert(yoffset % util_format_get_blockheight(pformat) == 0);
1211   assert(width % util_format_get_blockwidth(pformat) == 0);
1212   assert(height % util_format_get_blockheight(pformat) == 0);
1213
1214   for (y = 0; y < height; y += util_format_get_blockheight(pformat)) {
1215      /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
1216      const char *src = (const char*)data + srcBlockStride * util_format_get_nblocksy(pformat, y);
1217      char *dst = (char*)texImage->Data + dstBlockStride * util_format_get_nblocksy(pformat, y);
1218      memcpy(dst, src, util_format_get_stride(pformat, width));
1219   }
1220
1221   if (stImage->pt) {
1222      st_texture_image_unmap(ctx->st, stImage);
1223      texImage->Data = NULL;
1224   }
1225}
1226
1227
1228static void
1229st_CompressedTexSubImage3D(GLcontext *ctx, GLenum target, GLint level,
1230                           GLint xoffset, GLint yoffset, GLint zoffset,
1231                           GLsizei width, GLint height, GLint depth,
1232                           GLenum format,
1233                           GLsizei imageSize, const GLvoid *data,
1234                           struct gl_texture_object *texObj,
1235                           struct gl_texture_image *texImage)
1236{
1237   assert(0);
1238}
1239
1240
1241
1242/**
1243 * Do a CopyTexSubImage operation using a read transfer from the source,
1244 * a write transfer to the destination and get_tile()/put_tile() to access
1245 * the pixels/texels.
1246 *
1247 * Note: srcY=0=TOP of renderbuffer
1248 */
1249static void
1250fallback_copy_texsubimage(GLcontext *ctx, GLenum target, GLint level,
1251                          struct st_renderbuffer *strb,
1252                          struct st_texture_image *stImage,
1253                          GLenum baseFormat,
1254                          GLint destX, GLint destY, GLint destZ,
1255                          GLint srcX, GLint srcY,
1256                          GLsizei width, GLsizei height)
1257{
1258   struct pipe_context *pipe = ctx->st->pipe;
1259   struct pipe_screen *screen = pipe->screen;
1260   struct pipe_transfer *src_trans;
1261   GLvoid *texDest;
1262   enum pipe_transfer_usage transfer_usage;
1263
1264   if (ST_DEBUG & DEBUG_FALLBACK)
1265      debug_printf("%s: fallback processing\n", __FUNCTION__);
1266
1267   assert(width <= MAX_WIDTH);
1268
1269   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1270      srcY = strb->Base.Height - srcY - height;
1271   }
1272
1273   src_trans = st_cond_flush_get_tex_transfer( st_context(ctx),
1274					       strb->texture,
1275					       0, 0, 0,
1276					       PIPE_TRANSFER_READ,
1277					       srcX, srcY,
1278					       width, height);
1279
1280   if ((baseFormat == GL_DEPTH_COMPONENT ||
1281        baseFormat == GL_DEPTH_STENCIL) &&
1282       util_format_is_depth_and_stencil(stImage->pt->format))
1283      transfer_usage = PIPE_TRANSFER_READ_WRITE;
1284   else
1285      transfer_usage = PIPE_TRANSFER_WRITE;
1286
1287   st_teximage_flush_before_map(ctx->st, stImage->pt, 0, 0,
1288				transfer_usage);
1289
1290   texDest = st_texture_image_map(ctx->st, stImage, 0, transfer_usage,
1291                                  destX, destY, width, height);
1292
1293   if (baseFormat == GL_DEPTH_COMPONENT ||
1294       baseFormat == GL_DEPTH_STENCIL) {
1295      const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
1296                                     ctx->Pixel.DepthBias != 0.0F);
1297      GLint row, yStep;
1298
1299      /* determine bottom-to-top vs. top-to-bottom order for src buffer */
1300      if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1301         srcY = height - 1;
1302         yStep = -1;
1303      }
1304      else {
1305         srcY = 0;
1306         yStep = 1;
1307      }
1308
1309      /* To avoid a large temp memory allocation, do copy row by row */
1310      for (row = 0; row < height; row++, srcY += yStep) {
1311         uint data[MAX_WIDTH];
1312         pipe_get_tile_z(src_trans, 0, srcY, width, 1, data);
1313         if (scaleOrBias) {
1314            _mesa_scale_and_bias_depth_uint(ctx, width, data);
1315         }
1316         pipe_put_tile_z(stImage->transfer, 0, row, width, 1, data);
1317      }
1318   }
1319   else {
1320      /* RGBA format */
1321      GLfloat *tempSrc =
1322         (GLfloat *) _mesa_malloc(width * height * 4 * sizeof(GLfloat));
1323
1324      if (tempSrc && texDest) {
1325         const GLint dims = 2;
1326         const GLint dstRowStride = stImage->transfer->stride;
1327         struct gl_texture_image *texImage = &stImage->base;
1328         struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
1329
1330         if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1331            unpack.Invert = GL_TRUE;
1332         }
1333
1334         /* get float/RGBA image from framebuffer */
1335         /* XXX this usually involves a lot of int/float conversion.
1336          * try to avoid that someday.
1337          */
1338         pipe_get_tile_rgba(src_trans, 0, 0, width, height, tempSrc);
1339
1340         /* Store into texture memory.
1341          * Note that this does some special things such as pixel transfer
1342          * ops and format conversion.  In particular, if the dest tex format
1343          * is actually RGBA but the user created the texture as GL_RGB we
1344          * need to fill-in/override the alpha channel with 1.0.
1345          */
1346         _mesa_texstore(ctx, dims,
1347                        texImage->_BaseFormat,
1348                        texImage->TexFormat,
1349                        texDest,
1350                        0, 0, 0,
1351                        dstRowStride,
1352                        texImage->ImageOffsets,
1353                        width, height, 1,
1354                        GL_RGBA, GL_FLOAT, tempSrc, /* src */
1355                        &unpack);
1356      }
1357      else {
1358         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1359      }
1360
1361      if (tempSrc)
1362         _mesa_free(tempSrc);
1363   }
1364
1365   st_texture_image_unmap(ctx->st, stImage);
1366   screen->tex_transfer_destroy(src_trans);
1367}
1368
1369
1370
1371/**
1372 * If the format of the src renderbuffer and the format of the dest
1373 * texture are compatible (in terms of blitting), return a TGSI writemask
1374 * to be used during the blit.
1375 * If the src/dest are incompatible, return 0.
1376 */
1377static unsigned
1378compatible_src_dst_formats(GLcontext *ctx,
1379                           const struct gl_renderbuffer *src,
1380                           const struct gl_texture_image *dst)
1381{
1382   /* Get logical base formats for the src and dest.
1383    * That is, use the user-requested formats and not the actual, device-
1384    * chosen formats.
1385    * For example, the user may have requested an A8 texture but the
1386    * driver may actually be using an RGBA texture format.  When we
1387    * copy/blit to that texture, we only want to copy the Alpha channel
1388    * and not the RGB channels.
1389    *
1390    * Similarly, when the src FBO was created an RGB format may have been
1391    * requested but the driver actually chose an RGBA format.  In that case,
1392    * we don't want to copy the undefined Alpha channel to the dest texture
1393    * (it should be 1.0).
1394    */
1395   const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
1396   const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
1397
1398   /**
1399    * XXX when we have red-only and red/green renderbuffers we'll need
1400    * to add more cases here (or implement a general-purpose routine that
1401    * queries the existance of the R,G,B,A channels in the src and dest).
1402    */
1403   if (srcFormat == dstFormat) {
1404      /* This is the same as matching_base_formats, which should
1405       * always pass, as it did previously.
1406       */
1407      return TGSI_WRITEMASK_XYZW;
1408   }
1409   else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
1410      /* Make sure that A in the dest is 1.  The actual src format
1411       * may be RGBA and have undefined A values.
1412       */
1413      return TGSI_WRITEMASK_XYZ;
1414   }
1415   else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
1416      /* Make sure that A in the dest is 1.  The actual dst format
1417       * may be RGBA and will need A=1 to provide proper alpha values
1418       * when sampled later.
1419       */
1420      return TGSI_WRITEMASK_XYZ;
1421   }
1422   else {
1423      if (ST_DEBUG & DEBUG_FALLBACK)
1424         debug_printf("%s failed for src %s, dst %s\n",
1425                      __FUNCTION__,
1426                      _mesa_lookup_enum_by_nr(srcFormat),
1427                      _mesa_lookup_enum_by_nr(dstFormat));
1428
1429      /* Otherwise fail.
1430       */
1431      return 0;
1432   }
1433}
1434
1435
1436
1437/**
1438 * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
1439 * Note that the region to copy has already been clipped so we know we
1440 * won't read from outside the source renderbuffer's bounds.
1441 *
1442 * Note: srcY=0=Bottom of renderbuffer (GL convention)
1443 */
1444static void
1445st_copy_texsubimage(GLcontext *ctx,
1446                    GLenum target, GLint level,
1447                    GLint destX, GLint destY, GLint destZ,
1448                    GLint srcX, GLint srcY,
1449                    GLsizei width, GLsizei height)
1450{
1451   struct gl_texture_unit *texUnit =
1452      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1453   struct gl_texture_object *texObj =
1454      _mesa_select_tex_object(ctx, texUnit, target);
1455   struct gl_texture_image *texImage =
1456      _mesa_select_tex_image(ctx, texObj, target, level);
1457   struct st_texture_image *stImage = st_texture_image(texImage);
1458   const GLenum texBaseFormat = texImage->_BaseFormat;
1459   struct gl_framebuffer *fb = ctx->ReadBuffer;
1460   struct st_renderbuffer *strb;
1461   struct pipe_context *pipe = ctx->st->pipe;
1462   struct pipe_screen *screen = pipe->screen;
1463   enum pipe_format dest_format, src_format;
1464   GLboolean use_fallback = GL_TRUE;
1465   GLboolean matching_base_formats;
1466   GLuint format_writemask;
1467   struct pipe_surface *dest_surface = NULL;
1468   GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
1469
1470   /* any rendering in progress must flushed before we grab the fb image */
1471   st_flush(ctx->st, PIPE_FLUSH_RENDER_CACHE, NULL);
1472
1473   /* make sure finalize_textures has been called?
1474    */
1475   if (0) st_validate_state(ctx->st);
1476
1477   /* determine if copying depth or color data */
1478   if (texBaseFormat == GL_DEPTH_COMPONENT ||
1479       texBaseFormat == GL_DEPTH_STENCIL) {
1480      strb = st_renderbuffer(fb->_DepthBuffer);
1481   }
1482   else {
1483      /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
1484      strb = st_renderbuffer(fb->_ColorReadBuffer);
1485   }
1486
1487   if (!strb || !strb->surface || !stImage->pt) {
1488      debug_printf("%s: null strb or stImage\n", __FUNCTION__);
1489      return;
1490   }
1491
1492   if (srcX < 0) {
1493      width -= -srcX;
1494      destX += -srcX;
1495      srcX = 0;
1496   }
1497
1498   if (srcY < 0) {
1499      height -= -srcY;
1500      destY += -srcY;
1501      srcY = 0;
1502   }
1503
1504   if (destX < 0) {
1505      width -= -destX;
1506      srcX += -destX;
1507      destX = 0;
1508   }
1509
1510   if (destY < 0) {
1511      height -= -destY;
1512      srcY += -destY;
1513      destY = 0;
1514   }
1515
1516   if (width < 0 || height < 0)
1517      return;
1518
1519
1520   assert(strb);
1521   assert(strb->surface);
1522   assert(stImage->pt);
1523
1524   src_format = strb->surface->format;
1525   dest_format = stImage->pt->format;
1526
1527   /*
1528    * Determine if the src framebuffer and dest texture have the same
1529    * base format.  We need this to detect a case such as the framebuffer
1530    * being GL_RGBA but the texture being GL_RGB.  If the actual hardware
1531    * texture format stores RGBA we need to set A=1 (overriding the
1532    * framebuffer's alpha values).  We can't do that with the blit or
1533    * textured-quad paths.
1534    */
1535   matching_base_formats =
1536      (_mesa_get_format_base_format(strb->Base.Format) ==
1537       _mesa_get_format_base_format(texImage->TexFormat));
1538   format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
1539
1540   if (ctx->_ImageTransferState == 0x0) {
1541
1542      if (pipe->surface_copy &&
1543          matching_base_formats &&
1544          src_format == dest_format &&
1545          !do_flip)
1546      {
1547         /* use surface_copy() / blit */
1548
1549         dest_surface = screen->get_tex_surface(screen, stImage->pt,
1550                                                stImage->face, stImage->level,
1551                                                destZ,
1552                                                PIPE_BUFFER_USAGE_GPU_WRITE);
1553
1554         /* for surface_copy(), y=0=top, always */
1555         pipe->surface_copy(pipe,
1556                            /* dest */
1557                            dest_surface,
1558                            destX, destY,
1559                            /* src */
1560                            strb->surface,
1561                            srcX, srcY,
1562                            /* size */
1563                            width, height);
1564         use_fallback = GL_FALSE;
1565      }
1566      else if (format_writemask &&
1567               texBaseFormat != GL_DEPTH_COMPONENT &&
1568               texBaseFormat != GL_DEPTH_STENCIL &&
1569               screen->is_format_supported(screen, src_format,
1570                                           PIPE_TEXTURE_2D,
1571                                           PIPE_TEXTURE_USAGE_SAMPLER,
1572                                           0) &&
1573               screen->is_format_supported(screen, dest_format,
1574                                           PIPE_TEXTURE_2D,
1575                                           PIPE_TEXTURE_USAGE_RENDER_TARGET,
1576                                           0)) {
1577         /* draw textured quad to do the copy */
1578         GLint srcY0, srcY1;
1579
1580         dest_surface = screen->get_tex_surface(screen, stImage->pt,
1581                                                stImage->face, stImage->level,
1582                                                destZ,
1583                                                PIPE_BUFFER_USAGE_GPU_WRITE);
1584
1585         if (do_flip) {
1586            srcY1 = strb->Base.Height - srcY - height;
1587            srcY0 = srcY1 + height;
1588         }
1589         else {
1590            srcY0 = srcY;
1591            srcY1 = srcY0 + height;
1592         }
1593         util_blit_pixels_writemask(ctx->st->blit,
1594                                    strb->surface,
1595                                    srcX, srcY0,
1596                                    srcX + width, srcY1,
1597                                    dest_surface,
1598                                    destX, destY,
1599                                    destX + width, destY + height,
1600                                    0.0, PIPE_TEX_MIPFILTER_NEAREST,
1601                                    format_writemask);
1602         use_fallback = GL_FALSE;
1603      }
1604
1605      if (dest_surface)
1606         pipe_surface_reference(&dest_surface, NULL);
1607   }
1608
1609   if (use_fallback) {
1610      /* software fallback */
1611      fallback_copy_texsubimage(ctx, target, level,
1612                                strb, stImage, texBaseFormat,
1613                                destX, destY, destZ,
1614                                srcX, srcY, width, height);
1615   }
1616}
1617
1618
1619
1620static void
1621st_CopyTexImage1D(GLcontext * ctx, GLenum target, GLint level,
1622                  GLenum internalFormat,
1623                  GLint x, GLint y, GLsizei width, GLint border)
1624{
1625   struct gl_texture_unit *texUnit =
1626      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1627   struct gl_texture_object *texObj =
1628      _mesa_select_tex_object(ctx, texUnit, target);
1629   struct gl_texture_image *texImage =
1630      _mesa_select_tex_image(ctx, texObj, target, level);
1631
1632   /* Setup or redefine the texture object, texture and texture
1633    * image.  Don't populate yet.
1634    */
1635   ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
1636                          width, border,
1637                          GL_RGBA, CHAN_TYPE, NULL,
1638                          &ctx->DefaultPacking, texObj, texImage);
1639
1640   st_copy_texsubimage(ctx, target, level,
1641                       0, 0, 0,  /* destX,Y,Z */
1642                       x, y, width, 1);  /* src X, Y, size */
1643}
1644
1645
1646static void
1647st_CopyTexImage2D(GLcontext * ctx, GLenum target, GLint level,
1648                  GLenum internalFormat,
1649                  GLint x, GLint y, GLsizei width, GLsizei height,
1650                  GLint border)
1651{
1652   struct gl_texture_unit *texUnit =
1653      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1654   struct gl_texture_object *texObj =
1655      _mesa_select_tex_object(ctx, texUnit, target);
1656   struct gl_texture_image *texImage =
1657      _mesa_select_tex_image(ctx, texObj, target, level);
1658
1659   /* Setup or redefine the texture object, texture and texture
1660    * image.  Don't populate yet.
1661    */
1662   ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
1663                          width, height, border,
1664                          GL_RGBA, CHAN_TYPE, NULL,
1665                          &ctx->DefaultPacking, texObj, texImage);
1666
1667   st_copy_texsubimage(ctx, target, level,
1668                       0, 0, 0,  /* destX,Y,Z */
1669                       x, y, width, height);  /* src X, Y, size */
1670}
1671
1672
1673static void
1674st_CopyTexSubImage1D(GLcontext * ctx, GLenum target, GLint level,
1675                     GLint xoffset, GLint x, GLint y, GLsizei width)
1676{
1677   const GLint yoffset = 0, zoffset = 0;
1678   const GLsizei height = 1;
1679   st_copy_texsubimage(ctx, target, level,
1680                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1681                       x, y, width, height);  /* src X, Y, size */
1682}
1683
1684
1685static void
1686st_CopyTexSubImage2D(GLcontext * ctx, GLenum target, GLint level,
1687                     GLint xoffset, GLint yoffset,
1688                     GLint x, GLint y, GLsizei width, GLsizei height)
1689{
1690   const GLint zoffset = 0;
1691   st_copy_texsubimage(ctx, target, level,
1692                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1693                       x, y, width, height);  /* src X, Y, size */
1694}
1695
1696
1697static void
1698st_CopyTexSubImage3D(GLcontext * ctx, GLenum target, GLint level,
1699                     GLint xoffset, GLint yoffset, GLint zoffset,
1700                     GLint x, GLint y, GLsizei width, GLsizei height)
1701{
1702   st_copy_texsubimage(ctx, target, level,
1703                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1704                       x, y, width, height);  /* src X, Y, size */
1705}
1706
1707
1708static void
1709copy_image_data_to_texture(struct st_context *st,
1710			   struct st_texture_object *stObj,
1711                           GLuint dstLevel,
1712			   struct st_texture_image *stImage)
1713{
1714   if (stImage->pt) {
1715      /* Copy potentially with the blitter:
1716       */
1717      st_texture_image_copy(st->pipe,
1718                            stObj->pt, dstLevel,  /* dest texture, level */
1719                            stImage->pt, /* src texture */
1720                            stImage->face
1721                            );
1722
1723      pipe_texture_reference(&stImage->pt, NULL);
1724   }
1725   else if (stImage->base.Data) {
1726      /* More straightforward upload.
1727       */
1728
1729      st_teximage_flush_before_map(st, stObj->pt, stImage->face, dstLevel,
1730				   PIPE_TRANSFER_WRITE);
1731
1732
1733      st_texture_image_data(st,
1734                            stObj->pt,
1735                            stImage->face,
1736                            dstLevel,
1737                            stImage->base.Data,
1738                            stImage->base.RowStride *
1739                            util_format_get_blocksize(stObj->pt->format),
1740                            stImage->base.RowStride *
1741                            stImage->base.Height *
1742                            util_format_get_blocksize(stObj->pt->format));
1743      _mesa_align_free(stImage->base.Data);
1744      stImage->base.Data = NULL;
1745   }
1746
1747   pipe_texture_reference(&stImage->pt, stObj->pt);
1748}
1749
1750
1751/**
1752 * Called during state validation.  When this function is finished,
1753 * the texture object should be ready for rendering.
1754 * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
1755 */
1756GLboolean
1757st_finalize_texture(GLcontext *ctx,
1758		    struct pipe_context *pipe,
1759		    struct gl_texture_object *tObj,
1760		    GLboolean *needFlush)
1761{
1762   struct st_texture_object *stObj = st_texture_object(tObj);
1763   const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
1764   GLuint blockSize, face;
1765   struct st_texture_image *firstImage;
1766
1767   *needFlush = GL_FALSE;
1768
1769   if (stObj->base._Complete) {
1770      /* The texture is complete and we know exactly how many mipmap levels
1771       * are present/needed.  This is conditional because we may be called
1772       * from the st_generate_mipmap() function when the texture object is
1773       * incomplete.  In that case, we'll have set stObj->lastLevel before
1774       * we get here.
1775       */
1776      if (stObj->base.MinFilter == GL_LINEAR ||
1777          stObj->base.MinFilter == GL_NEAREST)
1778         stObj->lastLevel = stObj->base.BaseLevel;
1779      else
1780         stObj->lastLevel = stObj->base._MaxLevel - stObj->base.BaseLevel;
1781   }
1782
1783   firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
1784
1785   /* If both firstImage and stObj point to a texture which can contain
1786    * all active images, favour firstImage.  Note that because of the
1787    * completeness requirement, we know that the image dimensions
1788    * will match.
1789    */
1790   if (firstImage->pt &&
1791       firstImage->pt != stObj->pt &&
1792       firstImage->pt->last_level >= stObj->lastLevel) {
1793      pipe_texture_reference(&stObj->pt, firstImage->pt);
1794   }
1795
1796   /* bytes per pixel block (blocks are usually 1x1) */
1797   blockSize = _mesa_get_format_bytes(firstImage->base.TexFormat);
1798
1799   /* If we already have a gallium texture, check that it matches the texture
1800    * object's format, target, size, num_levels, etc.
1801    */
1802   if (stObj->pt) {
1803      const enum pipe_format fmt =
1804         st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
1805      if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
1806          stObj->pt->format != fmt ||
1807          stObj->pt->last_level < stObj->lastLevel ||
1808          stObj->pt->width0 != firstImage->base.Width2 ||
1809          stObj->pt->height0 != firstImage->base.Height2 ||
1810          stObj->pt->depth0 != firstImage->base.Depth2)
1811      {
1812         pipe_texture_reference(&stObj->pt, NULL);
1813         ctx->st->dirty.st |= ST_NEW_FRAMEBUFFER;
1814      }
1815   }
1816
1817   /* May need to create a new gallium texture:
1818    */
1819   if (!stObj->pt) {
1820      const enum pipe_format fmt =
1821         st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
1822      GLuint usage = default_usage(fmt);
1823
1824      stObj->pt = st_texture_create(ctx->st,
1825                                    gl_target_to_pipe(stObj->base.Target),
1826                                    fmt,
1827                                    stObj->lastLevel,
1828                                    firstImage->base.Width2,
1829                                    firstImage->base.Height2,
1830                                    firstImage->base.Depth2,
1831                                    usage);
1832
1833      if (!stObj->pt) {
1834         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
1835         return GL_FALSE;
1836      }
1837   }
1838
1839   /* Pull in any images not in the object's texture:
1840    */
1841   for (face = 0; face < nr_faces; face++) {
1842      GLuint level;
1843      for (level = 0; level <= stObj->lastLevel; level++) {
1844         struct st_texture_image *stImage =
1845            st_texture_image(stObj->base.Image[face][stObj->base.BaseLevel + level]);
1846
1847         /* Need to import images in main memory or held in other textures.
1848          */
1849         if (stImage && stObj->pt != stImage->pt) {
1850            copy_image_data_to_texture(ctx->st, stObj, level, stImage);
1851	    *needFlush = GL_TRUE;
1852         }
1853      }
1854   }
1855
1856   return GL_TRUE;
1857}
1858
1859
1860/**
1861 * Returns pointer to a default/dummy texture.
1862 * This is typically used when the current shader has tex/sample instructions
1863 * but the user has not provided a (any) texture(s).
1864 */
1865struct gl_texture_object *
1866st_get_default_texture(struct st_context *st)
1867{
1868   if (!st->default_texture) {
1869      static const GLenum target = GL_TEXTURE_2D;
1870      GLubyte pixels[16][16][4];
1871      struct gl_texture_object *texObj;
1872      struct gl_texture_image *texImg;
1873      GLuint i, j;
1874
1875      /* The ARB_fragment_program spec says (0,0,0,1) should be returned
1876       * when attempting to sample incomplete textures.
1877       */
1878      for (i = 0; i < 16; i++) {
1879         for (j = 0; j < 16; j++) {
1880            pixels[i][j][0] = 0;
1881            pixels[i][j][1] = 0;
1882            pixels[i][j][2] = 0;
1883            pixels[i][j][3] = 255;
1884         }
1885      }
1886
1887      texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
1888
1889      texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
1890
1891      _mesa_init_teximage_fields(st->ctx, target, texImg,
1892                                 16, 16, 1, 0,  /* w, h, d, border */
1893                                 GL_RGBA);
1894
1895      st_TexImage(st->ctx, 2, target,
1896                  0, GL_RGBA,    /* level, intformat */
1897                  16, 16, 1, 0,  /* w, h, d, border */
1898                  GL_RGBA, GL_UNSIGNED_BYTE, pixels,
1899                  &st->ctx->DefaultPacking,
1900                  texObj, texImg,
1901                  0, 0);
1902
1903      texObj->MinFilter = GL_NEAREST;
1904      texObj->MagFilter = GL_NEAREST;
1905      texObj->_Complete = GL_TRUE;
1906
1907      st->default_texture = texObj;
1908   }
1909   return st->default_texture;
1910}
1911
1912
1913void
1914st_init_texture_functions(struct dd_function_table *functions)
1915{
1916   functions->ChooseTextureFormat = st_ChooseTextureFormat;
1917   functions->TexImage1D = st_TexImage1D;
1918   functions->TexImage2D = st_TexImage2D;
1919   functions->TexImage3D = st_TexImage3D;
1920   functions->TexSubImage1D = st_TexSubImage1D;
1921   functions->TexSubImage2D = st_TexSubImage2D;
1922   functions->TexSubImage3D = st_TexSubImage3D;
1923   functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
1924   functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
1925   functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
1926   functions->CopyTexImage1D = st_CopyTexImage1D;
1927   functions->CopyTexImage2D = st_CopyTexImage2D;
1928   functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
1929   functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
1930   functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
1931   functions->GenerateMipmap = st_generate_mipmap;
1932
1933   functions->GetTexImage = st_GetTexImage;
1934
1935   /* compressed texture functions */
1936   functions->CompressedTexImage2D = st_CompressedTexImage2D;
1937   functions->GetCompressedTexImage = st_GetCompressedTexImage;
1938
1939   functions->NewTextureObject = st_NewTextureObject;
1940   functions->NewTextureImage = st_NewTextureImage;
1941   functions->DeleteTexture = st_DeleteTextureObject;
1942   functions->FreeTexImageData = st_FreeTextureImageData;
1943   functions->UpdateTexturePalette = 0;
1944
1945   functions->TextureMemCpy = do_memcpy;
1946
1947   /* XXX Temporary until we can query pipe's texture sizes */
1948   functions->TestProxyTexImage = _mesa_test_proxy_teximage;
1949}
1950