st_cb_texture.c revision 7e9670c8bc9422296ce07dce99e1d266063952c3
1/**************************************************************************
2 *
3 * Copyright 2007 VMware, Inc.
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 VMWARE 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 <stdio.h>
29#include "main/bufferobj.h"
30#include "main/enums.h"
31#include "main/fbobject.h"
32#include "main/formats.h"
33#include "main/format_utils.h"
34#include "main/glformats.h"
35#include "main/image.h"
36#include "main/imports.h"
37#include "main/macros.h"
38#include "main/mipmap.h"
39#include "main/pack.h"
40#include "main/pbo.h"
41#include "main/pixeltransfer.h"
42#include "main/texcompress.h"
43#include "main/texcompress_etc.h"
44#include "main/texgetimage.h"
45#include "main/teximage.h"
46#include "main/texobj.h"
47#include "main/texstore.h"
48
49#include "state_tracker/st_debug.h"
50#include "state_tracker/st_context.h"
51#include "state_tracker/st_cb_fbo.h"
52#include "state_tracker/st_cb_flush.h"
53#include "state_tracker/st_cb_texture.h"
54#include "state_tracker/st_cb_bufferobjects.h"
55#include "state_tracker/st_format.h"
56#include "state_tracker/st_texture.h"
57#include "state_tracker/st_gen_mipmap.h"
58#include "state_tracker/st_atom.h"
59
60#include "pipe/p_context.h"
61#include "pipe/p_defines.h"
62#include "util/u_inlines.h"
63#include "util/u_upload_mgr.h"
64#include "pipe/p_shader_tokens.h"
65#include "util/u_tile.h"
66#include "util/u_format.h"
67#include "util/u_surface.h"
68#include "util/u_sampler.h"
69#include "util/u_math.h"
70#include "util/u_box.h"
71#include "util/u_simple_shaders.h"
72#include "cso_cache/cso_context.h"
73#include "tgsi/tgsi_ureg.h"
74
75#define DBG if (0) printf
76
77
78enum pipe_texture_target
79gl_target_to_pipe(GLenum target)
80{
81   switch (target) {
82   case GL_TEXTURE_1D:
83   case GL_PROXY_TEXTURE_1D:
84      return PIPE_TEXTURE_1D;
85   case GL_TEXTURE_2D:
86   case GL_PROXY_TEXTURE_2D:
87   case GL_TEXTURE_EXTERNAL_OES:
88   case GL_TEXTURE_2D_MULTISAMPLE:
89   case GL_PROXY_TEXTURE_2D_MULTISAMPLE:
90      return PIPE_TEXTURE_2D;
91   case GL_TEXTURE_RECTANGLE_NV:
92   case GL_PROXY_TEXTURE_RECTANGLE_NV:
93      return PIPE_TEXTURE_RECT;
94   case GL_TEXTURE_3D:
95   case GL_PROXY_TEXTURE_3D:
96      return PIPE_TEXTURE_3D;
97   case GL_TEXTURE_CUBE_MAP_ARB:
98   case GL_PROXY_TEXTURE_CUBE_MAP_ARB:
99   case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
100   case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
101   case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
102   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
103   case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
104   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
105      return PIPE_TEXTURE_CUBE;
106   case GL_TEXTURE_1D_ARRAY_EXT:
107   case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
108      return PIPE_TEXTURE_1D_ARRAY;
109   case GL_TEXTURE_2D_ARRAY_EXT:
110   case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
111   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
112   case GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY:
113      return PIPE_TEXTURE_2D_ARRAY;
114   case GL_TEXTURE_BUFFER:
115      return PIPE_BUFFER;
116   case GL_TEXTURE_CUBE_MAP_ARRAY:
117   case GL_PROXY_TEXTURE_CUBE_MAP_ARRAY:
118      return PIPE_TEXTURE_CUBE_ARRAY;
119   default:
120      assert(0);
121      return 0;
122   }
123}
124
125
126/** called via ctx->Driver.NewTextureImage() */
127static struct gl_texture_image *
128st_NewTextureImage(struct gl_context * ctx)
129{
130   DBG("%s\n", __func__);
131   (void) ctx;
132   return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
133}
134
135
136/** called via ctx->Driver.DeleteTextureImage() */
137static void
138st_DeleteTextureImage(struct gl_context * ctx, struct gl_texture_image *img)
139{
140   /* nothing special (yet) for st_texture_image */
141   _mesa_delete_texture_image(ctx, img);
142}
143
144
145/** called via ctx->Driver.NewTextureObject() */
146static struct gl_texture_object *
147st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
148{
149   struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
150
151   DBG("%s\n", __func__);
152   _mesa_initialize_texture_object(ctx, &obj->base, name, target);
153
154   return &obj->base;
155}
156
157/** called via ctx->Driver.DeleteTextureObject() */
158static void
159st_DeleteTextureObject(struct gl_context *ctx,
160                       struct gl_texture_object *texObj)
161{
162   struct st_context *st = st_context(ctx);
163   struct st_texture_object *stObj = st_texture_object(texObj);
164
165   pipe_resource_reference(&stObj->pt, NULL);
166   st_texture_release_all_sampler_views(st, stObj);
167   st_texture_free_sampler_views(stObj);
168   _mesa_delete_texture_object(ctx, texObj);
169}
170
171
172/** called via ctx->Driver.FreeTextureImageBuffer() */
173static void
174st_FreeTextureImageBuffer(struct gl_context *ctx,
175                          struct gl_texture_image *texImage)
176{
177   struct st_texture_image *stImage = st_texture_image(texImage);
178
179   DBG("%s\n", __func__);
180
181   if (stImage->pt) {
182      pipe_resource_reference(&stImage->pt, NULL);
183   }
184
185   free(stImage->transfer);
186   stImage->transfer = NULL;
187   stImage->num_transfers = 0;
188}
189
190
191/** called via ctx->Driver.MapTextureImage() */
192static void
193st_MapTextureImage(struct gl_context *ctx,
194                   struct gl_texture_image *texImage,
195                   GLuint slice, GLuint x, GLuint y, GLuint w, GLuint h,
196                   GLbitfield mode,
197                   GLubyte **mapOut, GLint *rowStrideOut)
198{
199   struct st_context *st = st_context(ctx);
200   struct st_texture_image *stImage = st_texture_image(texImage);
201   unsigned pipeMode;
202   GLubyte *map;
203   struct pipe_transfer *transfer;
204
205   pipeMode = 0x0;
206   if (mode & GL_MAP_READ_BIT)
207      pipeMode |= PIPE_TRANSFER_READ;
208   if (mode & GL_MAP_WRITE_BIT)
209      pipeMode |= PIPE_TRANSFER_WRITE;
210   if (mode & GL_MAP_INVALIDATE_RANGE_BIT)
211      pipeMode |= PIPE_TRANSFER_DISCARD_RANGE;
212
213   map = st_texture_image_map(st, stImage, pipeMode, x, y, slice, w, h, 1,
214                              &transfer);
215   if (map) {
216      if ((_mesa_is_format_etc2(texImage->TexFormat) && !st->has_etc2) ||
217          (texImage->TexFormat == MESA_FORMAT_ETC1_RGB8 && !st->has_etc1)) {
218         /* ETC isn't supported by gallium and it's represented
219          * by uncompressed formats. Only write transfers with precompressed
220          * data are supported by ES3, which makes this really simple.
221          *
222          * Just create a temporary storage where the ETC texture will
223          * be stored. It will be decompressed in the Unmap function.
224          */
225         unsigned z = transfer->box.z;
226         struct st_texture_image_transfer *itransfer = &stImage->transfer[z];
227
228         itransfer->temp_data =
229            malloc(_mesa_format_image_size(texImage->TexFormat, w, h, 1));
230         itransfer->temp_stride =
231            _mesa_format_row_stride(texImage->TexFormat, w);
232         itransfer->map = map;
233
234         *mapOut = itransfer->temp_data;
235         *rowStrideOut = itransfer->temp_stride;
236      }
237      else {
238         /* supported mapping */
239         *mapOut = map;
240         *rowStrideOut = transfer->stride;
241      }
242   }
243   else {
244      *mapOut = NULL;
245      *rowStrideOut = 0;
246   }
247}
248
249
250/** called via ctx->Driver.UnmapTextureImage() */
251static void
252st_UnmapTextureImage(struct gl_context *ctx,
253                     struct gl_texture_image *texImage,
254                     GLuint slice)
255{
256   struct st_context *st = st_context(ctx);
257   struct st_texture_image *stImage  = st_texture_image(texImage);
258
259   if ((_mesa_is_format_etc2(texImage->TexFormat) && !st->has_etc2) ||
260       (texImage->TexFormat == MESA_FORMAT_ETC1_RGB8 && !st->has_etc1)) {
261      /* Decompress the ETC texture to the mapped one. */
262      unsigned z = slice + stImage->base.Face;
263      struct st_texture_image_transfer *itransfer = &stImage->transfer[z];
264      struct pipe_transfer *transfer = itransfer->transfer;
265
266      assert(z == transfer->box.z);
267
268      if (texImage->TexFormat == MESA_FORMAT_ETC1_RGB8) {
269         _mesa_etc1_unpack_rgba8888(itransfer->map, transfer->stride,
270                                    itransfer->temp_data,
271                                    itransfer->temp_stride,
272                                    transfer->box.width, transfer->box.height);
273      }
274      else {
275         _mesa_unpack_etc2_format(itransfer->map, transfer->stride,
276                                  itransfer->temp_data, itransfer->temp_stride,
277                                  transfer->box.width, transfer->box.height,
278                                  texImage->TexFormat);
279      }
280
281      free(itransfer->temp_data);
282      itransfer->temp_data = NULL;
283      itransfer->temp_stride = 0;
284      itransfer->map = 0;
285   }
286
287   st_texture_image_unmap(st, stImage, slice);
288}
289
290
291/**
292 * Return default texture resource binding bitmask for the given format.
293 */
294static GLuint
295default_bindings(struct st_context *st, enum pipe_format format)
296{
297   struct pipe_screen *screen = st->pipe->screen;
298   const unsigned target = PIPE_TEXTURE_2D;
299   unsigned bindings;
300
301   if (util_format_is_depth_or_stencil(format))
302      bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
303   else
304      bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
305
306   if (screen->is_format_supported(screen, format, target, 0, bindings))
307      return bindings;
308   else {
309      /* Try non-sRGB. */
310      format = util_format_linear(format);
311
312      if (screen->is_format_supported(screen, format, target, 0, bindings))
313         return bindings;
314      else
315         return PIPE_BIND_SAMPLER_VIEW;
316   }
317}
318
319
320/**
321 * Given the size of a mipmap image, try to compute the size of the level=0
322 * mipmap image.
323 *
324 * Note that this isn't always accurate for odd-sized, non-POW textures.
325 * For example, if level=1 and width=40 then the level=0 width may be 80 or 81.
326 *
327 * \return GL_TRUE for success, GL_FALSE for failure
328 */
329static GLboolean
330guess_base_level_size(GLenum target,
331                      GLuint width, GLuint height, GLuint depth, GLuint level,
332                      GLuint *width0, GLuint *height0, GLuint *depth0)
333{
334   assert(width >= 1);
335   assert(height >= 1);
336   assert(depth >= 1);
337
338   if (level > 0) {
339      /* Guess the size of the base level.
340       * Depending on the image's size, we can't always make a guess here.
341       */
342      switch (target) {
343      case GL_TEXTURE_1D:
344      case GL_TEXTURE_1D_ARRAY:
345         width <<= level;
346         break;
347
348      case GL_TEXTURE_2D:
349      case GL_TEXTURE_2D_ARRAY:
350         /* We can't make a good guess here, because the base level dimensions
351          * can be non-square.
352          */
353         if (width == 1 || height == 1) {
354            return GL_FALSE;
355         }
356         width <<= level;
357         height <<= level;
358         break;
359
360      case GL_TEXTURE_CUBE_MAP:
361      case GL_TEXTURE_CUBE_MAP_ARRAY:
362         width <<= level;
363         height <<= level;
364         break;
365
366      case GL_TEXTURE_3D:
367         /* We can't make a good guess here, because the base level dimensions
368          * can be non-cube.
369          */
370         if (width == 1 || height == 1 || depth == 1) {
371            return GL_FALSE;
372         }
373         width <<= level;
374         height <<= level;
375         depth <<= level;
376         break;
377
378      case GL_TEXTURE_RECTANGLE:
379         break;
380
381      default:
382         assert(0);
383      }
384   }
385
386   *width0 = width;
387   *height0 = height;
388   *depth0 = depth;
389
390   return GL_TRUE;
391}
392
393
394/**
395 * Try to determine whether we should allocate memory for a full texture
396 * mipmap.  The problem is when we get a glTexImage(level=0) call, we
397 * can't immediately know if other mipmap levels are coming next.  Here
398 * we try to guess whether to allocate memory for a mipmap or just the
399 * 0th level.
400 *
401 * If we guess incorrectly here we'll later reallocate the right amount of
402 * memory either in st_AllocTextureImageBuffer() or st_finalize_texture().
403 *
404 * \param stObj  the texture object we're going to allocate memory for.
405 * \param stImage  describes the incoming image which we need to store.
406 */
407static boolean
408allocate_full_mipmap(const struct st_texture_object *stObj,
409                     const struct st_texture_image *stImage)
410{
411   switch (stObj->base.Target) {
412   case GL_TEXTURE_RECTANGLE_NV:
413   case GL_TEXTURE_BUFFER:
414   case GL_TEXTURE_EXTERNAL_OES:
415   case GL_TEXTURE_2D_MULTISAMPLE:
416   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
417      /* these texture types cannot be mipmapped */
418      return FALSE;
419   }
420
421   if (stImage->base.Level > 0 || stObj->base.GenerateMipmap)
422      return TRUE;
423
424   if (stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
425       stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT)
426      /* depth/stencil textures are seldom mipmapped */
427      return FALSE;
428
429   if (stObj->base.BaseLevel == 0 && stObj->base.MaxLevel == 0)
430      return FALSE;
431
432   if (stObj->base.Sampler.MinFilter == GL_NEAREST ||
433       stObj->base.Sampler.MinFilter == GL_LINEAR)
434      /* not a mipmap minification filter */
435      return FALSE;
436
437   if (stObj->base.Target == GL_TEXTURE_3D)
438      /* 3D textures are seldom mipmapped */
439      return FALSE;
440
441   return TRUE;
442}
443
444
445/**
446 * Try to allocate a pipe_resource object for the given st_texture_object.
447 *
448 * We use the given st_texture_image as a clue to determine the size of the
449 * mipmap image at level=0.
450 *
451 * \return GL_TRUE for success, GL_FALSE if out of memory.
452 */
453static GLboolean
454guess_and_alloc_texture(struct st_context *st,
455			struct st_texture_object *stObj,
456			const struct st_texture_image *stImage)
457{
458   GLuint lastLevel, width, height, depth;
459   GLuint bindings;
460   GLuint ptWidth, ptHeight, ptDepth, ptLayers;
461   enum pipe_format fmt;
462
463   DBG("%s\n", __func__);
464
465   assert(!stObj->pt);
466
467   if (!guess_base_level_size(stObj->base.Target,
468                              stImage->base.Width2,
469                              stImage->base.Height2,
470                              stImage->base.Depth2,
471                              stImage->base.Level,
472                              &width, &height, &depth)) {
473      /* we can't determine the image size at level=0 */
474      stObj->width0 = stObj->height0 = stObj->depth0 = 0;
475      /* this is not an out of memory error */
476      return GL_TRUE;
477   }
478
479   /* At this point, (width x height x depth) is the expected size of
480    * the level=0 mipmap image.
481    */
482
483   /* Guess a reasonable value for lastLevel.  With OpenGL we have no
484    * idea how many mipmap levels will be in a texture until we start
485    * to render with it.  Make an educated guess here but be prepared
486    * to re-allocating a texture buffer with space for more (or fewer)
487    * mipmap levels later.
488    */
489   if (allocate_full_mipmap(stObj, stImage)) {
490      /* alloc space for a full mipmap */
491      lastLevel = _mesa_get_tex_max_num_levels(stObj->base.Target,
492                                               width, height, depth) - 1;
493   }
494   else {
495      /* only alloc space for a single mipmap level */
496      lastLevel = 0;
497   }
498
499   /* Save the level=0 dimensions */
500   stObj->width0 = width;
501   stObj->height0 = height;
502   stObj->depth0 = depth;
503
504   fmt = st_mesa_format_to_pipe_format(st, stImage->base.TexFormat);
505
506   bindings = default_bindings(st, fmt);
507
508   st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
509                                   width, height, depth,
510                                   &ptWidth, &ptHeight, &ptDepth, &ptLayers);
511
512   stObj->pt = st_texture_create(st,
513                                 gl_target_to_pipe(stObj->base.Target),
514                                 fmt,
515                                 lastLevel,
516                                 ptWidth,
517                                 ptHeight,
518                                 ptDepth,
519                                 ptLayers, 0,
520                                 bindings);
521
522   stObj->lastLevel = lastLevel;
523
524   DBG("%s returning %d\n", __func__, (stObj->pt != NULL));
525
526   return stObj->pt != NULL;
527}
528
529
530/**
531 * Called via ctx->Driver.AllocTextureImageBuffer().
532 * If the texture object/buffer already has space for the indicated image,
533 * we're done.  Otherwise, allocate memory for the new texture image.
534 */
535static GLboolean
536st_AllocTextureImageBuffer(struct gl_context *ctx,
537                           struct gl_texture_image *texImage)
538{
539   struct st_context *st = st_context(ctx);
540   struct st_texture_image *stImage = st_texture_image(texImage);
541   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
542   const GLuint level = texImage->Level;
543   GLuint width = texImage->Width;
544   GLuint height = texImage->Height;
545   GLuint depth = texImage->Depth;
546
547   DBG("%s\n", __func__);
548
549   assert(!stImage->pt); /* xxx this might be wrong */
550
551   /* Look if the parent texture object has space for this image */
552   if (stObj->pt &&
553       level <= stObj->pt->last_level &&
554       st_texture_match_image(st, stObj->pt, texImage)) {
555      /* this image will fit in the existing texture object's memory */
556      pipe_resource_reference(&stImage->pt, stObj->pt);
557      return GL_TRUE;
558   }
559
560   /* The parent texture object does not have space for this image */
561
562   pipe_resource_reference(&stObj->pt, NULL);
563   st_texture_release_all_sampler_views(st, stObj);
564
565   if (!guess_and_alloc_texture(st, stObj, stImage)) {
566      /* Probably out of memory.
567       * Try flushing any pending rendering, then retry.
568       */
569      st_finish(st);
570      if (!guess_and_alloc_texture(st, stObj, stImage)) {
571         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
572         return GL_FALSE;
573      }
574   }
575
576   if (stObj->pt &&
577       st_texture_match_image(st, stObj->pt, texImage)) {
578      /* The image will live in the object's mipmap memory */
579      pipe_resource_reference(&stImage->pt, stObj->pt);
580      assert(stImage->pt);
581      return GL_TRUE;
582   }
583   else {
584      /* Create a new, temporary texture/resource/buffer to hold this
585       * one texture image.  Note that when we later access this image
586       * (either for mapping or copying) we'll want to always specify
587       * mipmap level=0, even if the image represents some other mipmap
588       * level.
589       */
590      enum pipe_format format =
591         st_mesa_format_to_pipe_format(st, texImage->TexFormat);
592      GLuint bindings = default_bindings(st, format);
593      GLuint ptWidth, ptHeight, ptDepth, ptLayers;
594
595      st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
596                                      width, height, depth,
597                                      &ptWidth, &ptHeight, &ptDepth, &ptLayers);
598
599      stImage->pt = st_texture_create(st,
600                                      gl_target_to_pipe(stObj->base.Target),
601                                      format,
602                                      0, /* lastLevel */
603                                      ptWidth,
604                                      ptHeight,
605                                      ptDepth,
606                                      ptLayers, 0,
607                                      bindings);
608      return stImage->pt != NULL;
609   }
610}
611
612
613/**
614 * Preparation prior to glTexImage.  Basically check the 'surface_based'
615 * field and switch to a "normal" tex image if necessary.
616 */
617static void
618prep_teximage(struct gl_context *ctx, struct gl_texture_image *texImage,
619              GLenum format, GLenum type)
620{
621   struct gl_texture_object *texObj = texImage->TexObject;
622   struct st_texture_object *stObj = st_texture_object(texObj);
623
624   /* switch to "normal" */
625   if (stObj->surface_based) {
626      const GLenum target = texObj->Target;
627      const GLuint level = texImage->Level;
628      mesa_format texFormat;
629
630      _mesa_clear_texture_object(ctx, texObj);
631      pipe_resource_reference(&stObj->pt, NULL);
632
633      /* oops, need to init this image again */
634      texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
635                                              texImage->InternalFormat, format,
636                                              type);
637
638      _mesa_init_teximage_fields(ctx, texImage,
639                                 texImage->Width, texImage->Height,
640                                 texImage->Depth, texImage->Border,
641                                 texImage->InternalFormat, texFormat);
642
643      stObj->surface_based = GL_FALSE;
644   }
645}
646
647
648/**
649 * Return a writemask for the gallium blit. The parameters can be base
650 * formats or "format" from glDrawPixels/glTexImage/glGetTexImage.
651 */
652unsigned
653st_get_blit_mask(GLenum srcFormat, GLenum dstFormat)
654{
655   switch (dstFormat) {
656   case GL_DEPTH_STENCIL:
657      switch (srcFormat) {
658      case GL_DEPTH_STENCIL:
659         return PIPE_MASK_ZS;
660      case GL_DEPTH_COMPONENT:
661         return PIPE_MASK_Z;
662      case GL_STENCIL_INDEX:
663         return PIPE_MASK_S;
664      default:
665         assert(0);
666         return 0;
667      }
668
669   case GL_DEPTH_COMPONENT:
670      switch (srcFormat) {
671      case GL_DEPTH_STENCIL:
672      case GL_DEPTH_COMPONENT:
673         return PIPE_MASK_Z;
674      default:
675         assert(0);
676         return 0;
677      }
678
679   case GL_STENCIL_INDEX:
680      switch (srcFormat) {
681      case GL_STENCIL_INDEX:
682         return PIPE_MASK_S;
683      default:
684         assert(0);
685         return 0;
686      }
687
688   default:
689      return PIPE_MASK_RGBA;
690   }
691}
692
693void
694st_init_pbo_upload(struct st_context *st)
695{
696   struct pipe_context *pipe = st->pipe;
697   struct pipe_screen *screen = pipe->screen;
698
699   st->pbo_upload.enabled =
700      screen->get_param(screen, PIPE_CAP_TEXTURE_BUFFER_OBJECTS) &&
701      screen->get_param(screen, PIPE_CAP_TEXTURE_BUFFER_OFFSET_ALIGNMENT) >= 1 &&
702      screen->get_shader_param(screen, PIPE_SHADER_FRAGMENT, PIPE_SHADER_CAP_INTEGERS);
703   if (!st->pbo_upload.enabled)
704      return;
705
706   st->pbo_upload.rgba_only =
707      screen->get_param(screen, PIPE_CAP_BUFFER_SAMPLER_VIEW_RGBA_ONLY);
708
709   if (screen->get_param(screen, PIPE_CAP_TGSI_INSTANCEID)) {
710      if (screen->get_param(screen, PIPE_CAP_TGSI_VS_LAYER_VIEWPORT)) {
711         st->pbo_upload.upload_layers = true;
712      } else if (screen->get_param(screen, PIPE_CAP_MAX_GEOMETRY_OUTPUT_VERTICES) >= 3) {
713         st->pbo_upload.upload_layers = true;
714         st->pbo_upload.use_gs = true;
715      }
716   }
717
718   /* Blend state */
719   memset(&st->pbo_upload.blend, 0, sizeof(struct pipe_blend_state));
720   st->pbo_upload.blend.rt[0].colormask = PIPE_MASK_RGBA;
721
722   /* Rasterizer state */
723   memset(&st->pbo_upload.raster, 0, sizeof(struct pipe_rasterizer_state));
724   st->pbo_upload.raster.half_pixel_center = 1;
725}
726
727void
728st_destroy_pbo_upload(struct st_context *st)
729{
730   if (st->pbo_upload.fs) {
731      cso_delete_fragment_shader(st->cso_context, st->pbo_upload.fs);
732      st->pbo_upload.fs = NULL;
733   }
734
735   if (st->pbo_upload.gs) {
736      cso_delete_geometry_shader(st->cso_context, st->pbo_upload.gs);
737      st->pbo_upload.gs = NULL;
738   }
739
740   if (st->pbo_upload.vs) {
741      cso_delete_vertex_shader(st->cso_context, st->pbo_upload.vs);
742      st->pbo_upload.vs = NULL;
743   }
744}
745
746/**
747 * Converts format to a format with the same components, types
748 * and sizes, but with the components in RGBA order.
749 */
750static enum pipe_format
751unswizzle_format(enum pipe_format format)
752{
753   switch (format)
754   {
755   case PIPE_FORMAT_B8G8R8A8_UNORM:
756   case PIPE_FORMAT_A8R8G8B8_UNORM:
757   case PIPE_FORMAT_A8B8G8R8_UNORM:
758      return PIPE_FORMAT_R8G8B8A8_UNORM;
759
760   case PIPE_FORMAT_B10G10R10A2_UNORM:
761      return PIPE_FORMAT_R10G10B10A2_UNORM;
762
763   case PIPE_FORMAT_B10G10R10A2_SNORM:
764      return PIPE_FORMAT_R10G10B10A2_SNORM;
765
766   case PIPE_FORMAT_B10G10R10A2_UINT:
767      return PIPE_FORMAT_R10G10B10A2_UINT;
768
769   default:
770      return format;
771   }
772}
773
774/**
775 * Converts PIPE_FORMAT_A* to PIPE_FORMAT_R*.
776 */
777static enum pipe_format
778alpha_to_red(enum pipe_format format)
779{
780   switch (format)
781   {
782   case PIPE_FORMAT_A8_UNORM:
783      return PIPE_FORMAT_R8_UNORM;
784   case PIPE_FORMAT_A8_SNORM:
785      return PIPE_FORMAT_R8_SNORM;
786   case PIPE_FORMAT_A8_UINT:
787      return PIPE_FORMAT_R8_UINT;
788   case PIPE_FORMAT_A8_SINT:
789      return PIPE_FORMAT_R8_SINT;
790
791   case PIPE_FORMAT_A16_UNORM:
792      return PIPE_FORMAT_R16_UNORM;
793   case PIPE_FORMAT_A16_SNORM:
794      return PIPE_FORMAT_R16_SNORM;
795   case PIPE_FORMAT_A16_UINT:
796      return PIPE_FORMAT_R16_UINT;
797   case PIPE_FORMAT_A16_SINT:
798      return PIPE_FORMAT_R16_SINT;
799   case PIPE_FORMAT_A16_FLOAT:
800      return PIPE_FORMAT_R16_FLOAT;
801
802   case PIPE_FORMAT_A32_UINT:
803      return PIPE_FORMAT_R32_UINT;
804   case PIPE_FORMAT_A32_SINT:
805      return PIPE_FORMAT_R32_SINT;
806   case PIPE_FORMAT_A32_FLOAT:
807      return PIPE_FORMAT_R32_FLOAT;
808
809   default:
810      return format;
811   }
812}
813
814/**
815 * Converts PIPE_FORMAT_R*A* to PIPE_FORMAT_R*G*.
816 */
817static enum pipe_format
818red_alpha_to_red_green(enum pipe_format format)
819{
820   switch (format)
821   {
822   case PIPE_FORMAT_R8A8_UNORM:
823      return PIPE_FORMAT_R8G8_UNORM;
824   case PIPE_FORMAT_R8A8_SNORM:
825      return PIPE_FORMAT_R8G8_SNORM;
826   case PIPE_FORMAT_R8A8_UINT:
827      return PIPE_FORMAT_R8G8_UINT;
828   case PIPE_FORMAT_R8A8_SINT:
829      return PIPE_FORMAT_R8G8_SINT;
830
831   case PIPE_FORMAT_R16A16_UNORM:
832      return PIPE_FORMAT_R16G16_UNORM;
833   case PIPE_FORMAT_R16A16_SNORM:
834      return PIPE_FORMAT_R16G16_SNORM;
835   case PIPE_FORMAT_R16A16_UINT:
836      return PIPE_FORMAT_R16G16_UINT;
837   case PIPE_FORMAT_R16A16_SINT:
838      return PIPE_FORMAT_R16G16_SINT;
839   case PIPE_FORMAT_R16A16_FLOAT:
840      return PIPE_FORMAT_R16G16_FLOAT;
841
842   case PIPE_FORMAT_R32A32_UINT:
843      return PIPE_FORMAT_R32G32_UINT;
844   case PIPE_FORMAT_R32A32_SINT:
845      return PIPE_FORMAT_R32G32_SINT;
846   case PIPE_FORMAT_R32A32_FLOAT:
847      return PIPE_FORMAT_R32G32_FLOAT;
848
849   default:
850       return format;
851   }
852}
853
854/**
855 * Converts PIPE_FORMAT_L*A* to PIPE_FORMAT_R*G*.
856 */
857static enum pipe_format
858luminance_alpha_to_red_green(enum pipe_format format)
859{
860   switch (format)
861   {
862   case PIPE_FORMAT_L8A8_UNORM:
863      return PIPE_FORMAT_R8G8_UNORM;
864   case PIPE_FORMAT_L8A8_SNORM:
865      return PIPE_FORMAT_R8G8_SNORM;
866   case PIPE_FORMAT_L8A8_UINT:
867      return PIPE_FORMAT_R8G8_UINT;
868   case PIPE_FORMAT_L8A8_SINT:
869      return PIPE_FORMAT_R8G8_SINT;
870
871   case PIPE_FORMAT_L16A16_UNORM:
872      return PIPE_FORMAT_R16G16_UNORM;
873   case PIPE_FORMAT_L16A16_SNORM:
874      return PIPE_FORMAT_R16G16_SNORM;
875   case PIPE_FORMAT_L16A16_UINT:
876      return PIPE_FORMAT_R16G16_UINT;
877   case PIPE_FORMAT_L16A16_SINT:
878      return PIPE_FORMAT_R16G16_SINT;
879   case PIPE_FORMAT_L16A16_FLOAT:
880      return PIPE_FORMAT_R16G16_FLOAT;
881
882   case PIPE_FORMAT_L32A32_UINT:
883      return PIPE_FORMAT_R32G32_UINT;
884   case PIPE_FORMAT_L32A32_SINT:
885      return PIPE_FORMAT_R32G32_SINT;
886   case PIPE_FORMAT_L32A32_FLOAT:
887      return PIPE_FORMAT_R32G32_FLOAT;
888
889   default:
890       return format;
891   }
892}
893
894/**
895 * Returns true if format is a PIPE_FORMAT_A* format, and false otherwise.
896 */
897static bool
898format_is_alpha(enum pipe_format format)
899{
900   const struct util_format_description *desc = util_format_description(format);
901
902   if (desc->nr_channels == 1 &&
903       desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_0 &&
904       desc->swizzle[1] == UTIL_FORMAT_SWIZZLE_0 &&
905       desc->swizzle[2] == UTIL_FORMAT_SWIZZLE_0 &&
906       desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_X)
907      return true;
908
909   return false;
910}
911
912/**
913 * Returns true if format is a PIPE_FORMAT_R* format, and false otherwise.
914 */
915static bool
916format_is_red(enum pipe_format format)
917{
918   const struct util_format_description *desc = util_format_description(format);
919
920   if (desc->nr_channels == 1 &&
921       desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_X &&
922       desc->swizzle[1] == UTIL_FORMAT_SWIZZLE_0 &&
923       desc->swizzle[2] == UTIL_FORMAT_SWIZZLE_0 &&
924       desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_1)
925      return true;
926
927   return false;
928}
929
930
931/**
932 * Returns true if format is a PIPE_FORMAT_L* format, and false otherwise.
933 */
934static bool
935format_is_luminance(enum pipe_format format)
936{
937   const struct util_format_description *desc = util_format_description(format);
938
939   if (desc->nr_channels == 1 &&
940       desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_X &&
941       desc->swizzle[1] == UTIL_FORMAT_SWIZZLE_X &&
942       desc->swizzle[2] == UTIL_FORMAT_SWIZZLE_X &&
943       desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_1)
944      return true;
945
946   return false;
947}
948
949/**
950 * Returns true if format is a PIPE_FORMAT_R*A* format, and false otherwise.
951 */
952static bool
953format_is_red_alpha(enum pipe_format format)
954{
955   const struct util_format_description *desc = util_format_description(format);
956
957   if (desc->nr_channels == 2 &&
958       desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_X &&
959       desc->swizzle[1] == UTIL_FORMAT_SWIZZLE_0 &&
960       desc->swizzle[2] == UTIL_FORMAT_SWIZZLE_0 &&
961       desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_Y)
962      return true;
963
964   return false;
965}
966
967static bool
968format_is_swizzled_rgba(enum pipe_format format)
969{
970    const struct util_format_description *desc = util_format_description(format);
971
972    if ((desc->swizzle[0] == TGSI_SWIZZLE_X || desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_0) &&
973        (desc->swizzle[1] == TGSI_SWIZZLE_Y || desc->swizzle[1] == UTIL_FORMAT_SWIZZLE_0) &&
974        (desc->swizzle[2] == TGSI_SWIZZLE_Z || desc->swizzle[2] == UTIL_FORMAT_SWIZZLE_0) &&
975        (desc->swizzle[3] == TGSI_SWIZZLE_W || desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_1))
976       return false;
977
978    return true;
979}
980
981struct format_table
982{
983   unsigned char swizzle[4];
984   enum pipe_format format;
985};
986
987static const struct format_table table_8888_unorm[] = {
988   { { 0, 1, 2, 3 }, PIPE_FORMAT_R8G8B8A8_UNORM },
989   { { 2, 1, 0, 3 }, PIPE_FORMAT_B8G8R8A8_UNORM },
990   { { 3, 0, 1, 2 }, PIPE_FORMAT_A8R8G8B8_UNORM },
991   { { 3, 2, 1, 0 }, PIPE_FORMAT_A8B8G8R8_UNORM }
992};
993
994static const struct format_table table_1010102_unorm[] = {
995   { { 0, 1, 2, 3 }, PIPE_FORMAT_R10G10B10A2_UNORM },
996   { { 2, 1, 0, 3 }, PIPE_FORMAT_B10G10R10A2_UNORM }
997};
998
999static const struct format_table table_1010102_snorm[] = {
1000   { { 0, 1, 2, 3 }, PIPE_FORMAT_R10G10B10A2_SNORM },
1001   { { 2, 1, 0, 3 }, PIPE_FORMAT_B10G10R10A2_SNORM }
1002};
1003
1004static const struct format_table table_1010102_uint[] = {
1005   { { 0, 1, 2, 3 }, PIPE_FORMAT_R10G10B10A2_UINT },
1006   { { 2, 1, 0, 3 }, PIPE_FORMAT_B10G10R10A2_UINT }
1007};
1008
1009static enum pipe_format
1010swizzle_format(enum pipe_format format, const int * const swizzle)
1011{
1012   unsigned i;
1013
1014   switch (format) {
1015   case PIPE_FORMAT_R8G8B8A8_UNORM:
1016   case PIPE_FORMAT_B8G8R8A8_UNORM:
1017   case PIPE_FORMAT_A8R8G8B8_UNORM:
1018   case PIPE_FORMAT_A8B8G8R8_UNORM:
1019      for (i = 0; i < ARRAY_SIZE(table_8888_unorm); i++) {
1020         if (swizzle[0] == table_8888_unorm[i].swizzle[0] &&
1021             swizzle[1] == table_8888_unorm[i].swizzle[1] &&
1022             swizzle[2] == table_8888_unorm[i].swizzle[2] &&
1023             swizzle[3] == table_8888_unorm[i].swizzle[3])
1024            return table_8888_unorm[i].format;
1025      }
1026      break;
1027
1028   case PIPE_FORMAT_R10G10B10A2_UNORM:
1029   case PIPE_FORMAT_B10G10R10A2_UNORM:
1030      for (i = 0; i < ARRAY_SIZE(table_1010102_unorm); i++) {
1031         if (swizzle[0] == table_1010102_unorm[i].swizzle[0] &&
1032             swizzle[1] == table_1010102_unorm[i].swizzle[1] &&
1033             swizzle[2] == table_1010102_unorm[i].swizzle[2] &&
1034             swizzle[3] == table_1010102_unorm[i].swizzle[3])
1035            return table_1010102_unorm[i].format;
1036      }
1037      break;
1038
1039   case PIPE_FORMAT_R10G10B10A2_SNORM:
1040   case PIPE_FORMAT_B10G10R10A2_SNORM:
1041      for (i = 0; i < ARRAY_SIZE(table_1010102_snorm); i++) {
1042         if (swizzle[0] == table_1010102_snorm[i].swizzle[0] &&
1043             swizzle[1] == table_1010102_snorm[i].swizzle[1] &&
1044             swizzle[2] == table_1010102_snorm[i].swizzle[2] &&
1045             swizzle[3] == table_1010102_snorm[i].swizzle[3])
1046            return table_1010102_snorm[i].format;
1047      }
1048      break;
1049
1050   case PIPE_FORMAT_R10G10B10A2_UINT:
1051   case PIPE_FORMAT_B10G10R10A2_UINT:
1052      for (i = 0; i < ARRAY_SIZE(table_1010102_uint); i++) {
1053         if (swizzle[0] == table_1010102_uint[i].swizzle[0] &&
1054             swizzle[1] == table_1010102_uint[i].swizzle[1] &&
1055             swizzle[2] == table_1010102_uint[i].swizzle[2] &&
1056             swizzle[3] == table_1010102_uint[i].swizzle[3])
1057            return table_1010102_uint[i].format;
1058      }
1059      break;
1060
1061   default:
1062      break;
1063   }
1064
1065   return PIPE_FORMAT_NONE;
1066}
1067
1068static bool
1069reinterpret_formats(enum pipe_format *src_format, enum pipe_format *dst_format)
1070{
1071   enum pipe_format src = *src_format;
1072   enum pipe_format dst = *dst_format;
1073
1074   /* Note: dst_format has already been transformed from luminance/intensity
1075    *       to red when this function is called.  The source format will never
1076    *       be an intensity format, because GL_INTENSITY is not a legal value
1077    *       for the format parameter in glTex(Sub)Image(). */
1078
1079   if (format_is_alpha(src)) {
1080      if (!format_is_alpha(dst))
1081         return false;
1082
1083      src = alpha_to_red(src);
1084      dst = alpha_to_red(dst);
1085   } else if (format_is_luminance(src)) {
1086      if (!format_is_red(dst) && !format_is_red_alpha(dst))
1087         return false;
1088
1089      src = util_format_luminance_to_red(src);
1090   } else if (util_format_is_luminance_alpha(src)) {
1091      src = luminance_alpha_to_red_green(src);
1092
1093      if (format_is_red_alpha(dst)) {
1094         dst = red_alpha_to_red_green(dst);
1095      } else if (!format_is_red(dst))
1096         return false;
1097   } else if (format_is_swizzled_rgba(src)) {
1098      const struct util_format_description *src_desc = util_format_description(src);
1099      const struct util_format_description *dst_desc = util_format_description(dst);
1100      int swizzle[4];
1101      unsigned i;
1102
1103      /* Make sure the format is an RGBA and not an RGBX format */
1104      if (src_desc->nr_channels != 4 || src_desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_1)
1105         return false;
1106
1107      if (dst_desc->nr_channels != 4 || dst_desc->swizzle[3] == UTIL_FORMAT_SWIZZLE_1)
1108         return false;
1109
1110      for (i = 0; i < 4; i++)
1111         swizzle[i] = dst_desc->swizzle[src_desc->swizzle[i]];
1112
1113      dst = swizzle_format(dst, swizzle);
1114      if (dst == PIPE_FORMAT_NONE)
1115         return false;
1116
1117      src = unswizzle_format(src);
1118   }
1119
1120   *src_format = src;
1121   *dst_format = dst;
1122   return true;
1123}
1124
1125static void *
1126create_pbo_upload_vs(struct st_context *st)
1127{
1128   struct ureg_program *ureg;
1129   struct ureg_src in_pos;
1130   struct ureg_src in_instanceid;
1131   struct ureg_dst out_pos;
1132   struct ureg_dst out_layer;
1133
1134   ureg = ureg_create(TGSI_PROCESSOR_VERTEX);
1135
1136   in_pos = ureg_DECL_vs_input(ureg, TGSI_SEMANTIC_POSITION);
1137
1138   out_pos = ureg_DECL_output(ureg, TGSI_SEMANTIC_POSITION, 0);
1139
1140   if (st->pbo_upload.upload_layers) {
1141      in_instanceid = ureg_DECL_system_value(ureg, TGSI_SEMANTIC_INSTANCEID, 0);
1142
1143      if (!st->pbo_upload.use_gs)
1144         out_layer = ureg_DECL_output(ureg, TGSI_SEMANTIC_LAYER, 0);
1145   }
1146
1147   /* out_pos = in_pos */
1148   ureg_MOV(ureg, out_pos, in_pos);
1149
1150   if (st->pbo_upload.upload_layers) {
1151      if (st->pbo_upload.use_gs) {
1152         /* out_pos.z = i2f(gl_InstanceID) */
1153         ureg_I2F(ureg, ureg_writemask(out_pos, TGSI_WRITEMASK_Z),
1154                        ureg_scalar(in_instanceid, TGSI_SWIZZLE_X));
1155      } else {
1156         /* out_layer = gl_InstanceID */
1157         ureg_MOV(ureg, out_layer, in_instanceid);
1158      }
1159   }
1160
1161   ureg_END(ureg);
1162
1163   return ureg_create_shader_and_destroy(ureg, st->pipe);
1164}
1165
1166static void *
1167create_pbo_upload_gs(struct st_context *st)
1168{
1169   static const int zero = 0;
1170   struct ureg_program *ureg;
1171   struct ureg_dst out_pos;
1172   struct ureg_dst out_layer;
1173   struct ureg_src in_pos;
1174   struct ureg_src imm;
1175   unsigned i;
1176
1177   ureg = ureg_create(TGSI_PROCESSOR_GEOMETRY);
1178   if (!ureg)
1179      return NULL;
1180
1181   ureg_property(ureg, TGSI_PROPERTY_GS_INPUT_PRIM, PIPE_PRIM_TRIANGLES);
1182   ureg_property(ureg, TGSI_PROPERTY_GS_OUTPUT_PRIM, PIPE_PRIM_TRIANGLE_STRIP);
1183   ureg_property(ureg, TGSI_PROPERTY_GS_MAX_OUTPUT_VERTICES, 3);
1184
1185   out_pos = ureg_DECL_output(ureg, TGSI_SEMANTIC_POSITION, 0);
1186   out_layer = ureg_DECL_output(ureg, TGSI_SEMANTIC_LAYER, 0);
1187
1188   in_pos = ureg_DECL_input(ureg, TGSI_SEMANTIC_POSITION, 0, 0, 1);
1189
1190   imm = ureg_DECL_immediate_int(ureg, &zero, 1);
1191
1192   for (i = 0; i < 3; ++i) {
1193      struct ureg_src in_pos_vertex = ureg_src_dimension(in_pos, i);
1194
1195      /* out_pos = in_pos[i] */
1196      ureg_MOV(ureg, out_pos, in_pos_vertex);
1197
1198      /* out_layer.x = f2i(in_pos[i].z) */
1199      ureg_F2I(ureg, ureg_writemask(out_layer, TGSI_WRITEMASK_X),
1200                     ureg_scalar(in_pos_vertex, TGSI_SWIZZLE_Z));
1201
1202      ureg_EMIT(ureg, ureg_scalar(imm, TGSI_SWIZZLE_X));
1203   }
1204
1205   ureg_END(ureg);
1206
1207   return ureg_create_shader_and_destroy(ureg, st->pipe);
1208}
1209
1210static void *
1211create_pbo_upload_fs(struct st_context *st)
1212{
1213   struct pipe_context *pipe = st->pipe;
1214   struct pipe_screen *screen = pipe->screen;
1215   struct ureg_program *ureg;
1216   struct ureg_dst out;
1217   struct ureg_src sampler;
1218   struct ureg_src pos;
1219   struct ureg_src layer;
1220   struct ureg_src const0;
1221   struct ureg_dst temp0;
1222
1223   ureg = ureg_create(TGSI_PROCESSOR_FRAGMENT);
1224   if (!ureg)
1225      return NULL;
1226
1227   out     = ureg_DECL_output(ureg, TGSI_SEMANTIC_COLOR, 0);
1228   sampler = ureg_DECL_sampler(ureg, 0);
1229   if (screen->get_param(screen, PIPE_CAP_TGSI_FS_POSITION_IS_SYSVAL)) {
1230      pos = ureg_DECL_system_value(ureg, TGSI_SEMANTIC_POSITION, 0);
1231   } else {
1232      pos = ureg_DECL_fs_input(ureg, TGSI_SEMANTIC_POSITION, 0,
1233                               TGSI_INTERPOLATE_LINEAR);
1234   }
1235   if (st->pbo_upload.upload_layers) {
1236      layer = ureg_DECL_fs_input(ureg, TGSI_SEMANTIC_LAYER, 0,
1237                                       TGSI_INTERPOLATE_CONSTANT);
1238   }
1239   const0  = ureg_DECL_constant(ureg, 0);
1240   temp0   = ureg_DECL_temporary(ureg);
1241
1242   /* Note: const0 = [ -xoffset + skip_pixels, -yoffset, stride, image_height ] */
1243
1244   /* temp0.xy = f2i(temp0.xy) */
1245   ureg_F2I(ureg, ureg_writemask(temp0, TGSI_WRITEMASK_XY),
1246                  ureg_swizzle(pos,
1247                               TGSI_SWIZZLE_X, TGSI_SWIZZLE_Y,
1248                               TGSI_SWIZZLE_Y, TGSI_SWIZZLE_Y));
1249
1250   /* temp0.xy = temp0.xy + const0.xy */
1251   ureg_UADD(ureg, ureg_writemask(temp0, TGSI_WRITEMASK_XY),
1252                   ureg_swizzle(ureg_src(temp0),
1253                                TGSI_SWIZZLE_X, TGSI_SWIZZLE_Y,
1254                                TGSI_SWIZZLE_Y, TGSI_SWIZZLE_Y),
1255                   ureg_swizzle(const0,
1256                                TGSI_SWIZZLE_X, TGSI_SWIZZLE_Y,
1257                                TGSI_SWIZZLE_Y, TGSI_SWIZZLE_Y));
1258
1259   /* temp0.x = const0.z * temp0.y + temp0.x */
1260   ureg_UMAD(ureg, ureg_writemask(temp0, TGSI_WRITEMASK_X),
1261                   ureg_scalar(const0, TGSI_SWIZZLE_Z),
1262                   ureg_scalar(ureg_src(temp0), TGSI_SWIZZLE_Y),
1263                   ureg_scalar(ureg_src(temp0), TGSI_SWIZZLE_X));
1264
1265   if (st->pbo_upload.upload_layers) {
1266      /* temp0.x = const0.w * layer + temp0.x */
1267      ureg_UMAD(ureg, ureg_writemask(temp0, TGSI_WRITEMASK_X),
1268                      ureg_scalar(const0, TGSI_SWIZZLE_W),
1269                      ureg_scalar(layer, TGSI_SWIZZLE_X),
1270                      ureg_scalar(ureg_src(temp0), TGSI_SWIZZLE_X));
1271   }
1272
1273   /* out = txf(sampler, temp0.x) */
1274   ureg_TXF(ureg, out, TGSI_TEXTURE_BUFFER,
1275                  ureg_scalar(ureg_src(temp0), TGSI_SWIZZLE_X),
1276                  sampler);
1277
1278   ureg_release_temporary(ureg, temp0);
1279
1280   ureg_END(ureg);
1281
1282   return ureg_create_shader_and_destroy(ureg, pipe);
1283}
1284
1285static bool
1286try_pbo_upload_common(struct gl_context *ctx,
1287                      struct pipe_surface *surface,
1288                      int xoffset, int yoffset,
1289                      unsigned upload_width, unsigned upload_height,
1290                      struct pipe_resource *buffer,
1291                      enum pipe_format src_format,
1292                      intptr_t buf_offset,
1293                      unsigned bytes_per_pixel,
1294                      unsigned stride,
1295                      unsigned image_height)
1296{
1297   struct st_context *st = st_context(ctx);
1298   struct pipe_context *pipe = st->pipe;
1299   unsigned depth = surface->u.tex.last_layer - surface->u.tex.first_layer + 1;
1300   unsigned skip_pixels = 0;
1301   bool success = false;
1302
1303   /* Check alignment. */
1304   {
1305      unsigned ofs = (buf_offset * bytes_per_pixel) % ctx->Const.TextureBufferOffsetAlignment;
1306      if (ofs != 0) {
1307         if (ofs % bytes_per_pixel != 0)
1308            return false;
1309
1310         skip_pixels = ofs / bytes_per_pixel;
1311         buf_offset -= skip_pixels;
1312      }
1313   }
1314
1315   /* Create the shaders */
1316   if (!st->pbo_upload.vs) {
1317      st->pbo_upload.vs = create_pbo_upload_vs(st);
1318      if (!st->pbo_upload.vs)
1319         return false;
1320   }
1321
1322   if (depth != 1 && st->pbo_upload.use_gs && !st->pbo_upload.gs) {
1323      st->pbo_upload.gs = create_pbo_upload_gs(st);
1324      if (!st->pbo_upload.gs)
1325         return false;
1326   }
1327
1328   if (!st->pbo_upload.fs) {
1329      st->pbo_upload.fs = create_pbo_upload_fs(st);
1330      if (!st->pbo_upload.fs)
1331         return false;
1332   }
1333
1334   /* Set up the sampler_view */
1335   {
1336      unsigned first_element = buf_offset;
1337      unsigned last_element = buf_offset + skip_pixels + upload_width - 1
1338         + (upload_height - 1 + (depth - 1) * image_height) * stride;
1339      struct pipe_sampler_view templ;
1340      struct pipe_sampler_view *sampler_view;
1341
1342      /* This should be ensured by Mesa before calling our callbacks */
1343      assert((last_element + 1) * bytes_per_pixel <= buffer->width0);
1344
1345      if (last_element - first_element > ctx->Const.MaxTextureBufferSize - 1)
1346         return false;
1347
1348      memset(&templ, 0, sizeof(templ));
1349      templ.format = src_format;
1350      templ.u.buf.first_element = first_element;
1351      templ.u.buf.last_element = last_element;
1352      templ.swizzle_r = PIPE_SWIZZLE_RED;
1353      templ.swizzle_g = PIPE_SWIZZLE_GREEN;
1354      templ.swizzle_b = PIPE_SWIZZLE_BLUE;
1355      templ.swizzle_a = PIPE_SWIZZLE_ALPHA;
1356
1357      sampler_view = pipe->create_sampler_view(pipe, buffer, &templ);
1358      if (sampler_view == NULL)
1359         return false;
1360
1361      cso_save_fragment_sampler_views(st->cso_context);
1362      cso_set_sampler_views(st->cso_context, PIPE_SHADER_FRAGMENT, 1,
1363                            &sampler_view);
1364
1365      pipe_sampler_view_reference(&sampler_view, NULL);
1366   }
1367
1368   /* Upload vertices */
1369   {
1370      struct pipe_vertex_buffer vbo;
1371      struct pipe_vertex_element velem;
1372
1373      float x0 = (float) xoffset / surface->width * 2.0f - 1.0f;
1374      float y0 = (float) yoffset / surface->height * 2.0f - 1.0f;
1375      float x1 = (float) (xoffset + upload_width) / surface->width * 2.0f - 1.0f;
1376      float y1 = (float) (yoffset + upload_height) / surface->height * 2.0f - 1.0f;
1377
1378      float *verts = NULL;
1379
1380      vbo.user_buffer = NULL;
1381      vbo.buffer = NULL;
1382      vbo.stride = 2 * sizeof(float);
1383
1384      u_upload_alloc(st->uploader, 0, 8 * sizeof(float), 4,
1385                     &vbo.buffer_offset, &vbo.buffer, (void **) &verts);
1386      if (!verts)
1387         goto fail_vertex_upload;
1388
1389      verts[0] = x0;
1390      verts[1] = y0;
1391      verts[2] = x0;
1392      verts[3] = y1;
1393      verts[4] = x1;
1394      verts[5] = y0;
1395      verts[6] = x1;
1396      verts[7] = y1;
1397
1398      u_upload_unmap(st->uploader);
1399
1400      velem.src_offset = 0;
1401      velem.instance_divisor = 0;
1402      velem.vertex_buffer_index = cso_get_aux_vertex_buffer_slot(st->cso_context);
1403      velem.src_format = PIPE_FORMAT_R32G32_FLOAT;
1404
1405      cso_save_vertex_elements(st->cso_context);
1406      cso_set_vertex_elements(st->cso_context, 1, &velem);
1407
1408      cso_save_aux_vertex_buffer_slot(st->cso_context);
1409      cso_set_vertex_buffers(st->cso_context, velem.vertex_buffer_index,
1410                             1, &vbo);
1411
1412      pipe_resource_reference(&vbo.buffer, NULL);
1413   }
1414
1415   /* Upload constants */
1416   {
1417      struct pipe_constant_buffer cb;
1418
1419      struct {
1420         int32_t xoffset;
1421         int32_t yoffset;
1422         int32_t stride;
1423         int32_t image_size;
1424      } constants;
1425
1426      constants.xoffset = -xoffset + skip_pixels;
1427      constants.yoffset = -yoffset;
1428      constants.stride = stride;
1429      constants.image_size = stride * image_height;
1430
1431      if (st->constbuf_uploader) {
1432         cb.buffer = NULL;
1433         cb.user_buffer = NULL;
1434         u_upload_data(st->constbuf_uploader, 0, sizeof(constants),
1435                       st->ctx->Const.UniformBufferOffsetAlignment,
1436                       &constants, &cb.buffer_offset, &cb.buffer);
1437         if (!cb.buffer)
1438            goto fail_constant_upload;
1439
1440         u_upload_unmap(st->constbuf_uploader);
1441      } else {
1442         cb.buffer = NULL;
1443         cb.user_buffer = &constants;
1444         cb.buffer_offset = 0;
1445      }
1446      cb.buffer_size = sizeof(constants);
1447
1448      cso_save_constant_buffer_slot0(st->cso_context, PIPE_SHADER_FRAGMENT);
1449      cso_set_constant_buffer(st->cso_context, PIPE_SHADER_FRAGMENT, 0, &cb);
1450
1451      pipe_resource_reference(&cb.buffer, NULL);
1452   }
1453
1454   /* Framebuffer_state */
1455   {
1456      struct pipe_framebuffer_state fb;
1457      memset(&fb, 0, sizeof(fb));
1458      fb.width = surface->width;
1459      fb.height = surface->height;
1460      fb.nr_cbufs = 1;
1461      pipe_surface_reference(&fb.cbufs[0], surface);
1462
1463      cso_save_framebuffer(st->cso_context);
1464      cso_set_framebuffer(st->cso_context, &fb);
1465
1466      pipe_surface_reference(&fb.cbufs[0], NULL);
1467   }
1468
1469   /* Viewport state */
1470   {
1471      struct pipe_viewport_state vp;
1472      vp.scale[0] = 0.5f * surface->width;
1473      vp.scale[1] = 0.5f * surface->height;
1474      vp.scale[2] = 1.0f;
1475      vp.translate[0] = 0.5f * surface->width;
1476      vp.translate[1] = 0.5f * surface->height;
1477      vp.translate[2] = 0.0f;
1478
1479      cso_save_viewport(st->cso_context);
1480      cso_set_viewport(st->cso_context, &vp);
1481   }
1482
1483   /* Blend state */
1484   cso_save_blend(st->cso_context);
1485   cso_set_blend(st->cso_context, &st->pbo_upload.blend);
1486
1487   /* Rasterizer state */
1488   cso_save_rasterizer(st->cso_context);
1489   cso_set_rasterizer(st->cso_context, &st->pbo_upload.raster);
1490
1491   /* Set up the shaders */
1492   cso_save_vertex_shader(st->cso_context);
1493   cso_set_vertex_shader_handle(st->cso_context, st->pbo_upload.vs);
1494
1495   cso_save_geometry_shader(st->cso_context);
1496   cso_set_geometry_shader_handle(st->cso_context,
1497                                  depth != 1 ? st->pbo_upload.gs : NULL);
1498
1499   cso_save_tessctrl_shader(st->cso_context);
1500   cso_set_tessctrl_shader_handle(st->cso_context, NULL);
1501
1502   cso_save_tesseval_shader(st->cso_context);
1503   cso_set_tesseval_shader_handle(st->cso_context, NULL);
1504
1505   cso_save_fragment_shader(st->cso_context);
1506   cso_set_fragment_shader_handle(st->cso_context, st->pbo_upload.fs);
1507
1508   /* Disable stream output */
1509   cso_save_stream_outputs(st->cso_context);
1510   cso_set_stream_outputs(st->cso_context, 0, NULL, 0);
1511
1512   if (depth == 1) {
1513      cso_draw_arrays(st->cso_context, PIPE_PRIM_TRIANGLE_STRIP, 0, 4);
1514   } else {
1515      cso_draw_arrays_instanced(st->cso_context, PIPE_PRIM_TRIANGLE_STRIP,
1516                                0, 4, 0, depth);
1517   }
1518
1519   success = true;
1520
1521   cso_restore_framebuffer(st->cso_context);
1522   cso_restore_viewport(st->cso_context);
1523   cso_restore_blend(st->cso_context);
1524   cso_restore_rasterizer(st->cso_context);
1525   cso_restore_vertex_shader(st->cso_context);
1526   cso_restore_geometry_shader(st->cso_context);
1527   cso_restore_tessctrl_shader(st->cso_context);
1528   cso_restore_tesseval_shader(st->cso_context);
1529   cso_restore_fragment_shader(st->cso_context);
1530   cso_restore_stream_outputs(st->cso_context);
1531   cso_restore_constant_buffer_slot0(st->cso_context, PIPE_SHADER_FRAGMENT);
1532fail_constant_upload:
1533   cso_restore_vertex_elements(st->cso_context);
1534   cso_restore_aux_vertex_buffer_slot(st->cso_context);
1535fail_vertex_upload:
1536   cso_restore_fragment_sampler_views(st->cso_context);
1537
1538   return success;
1539}
1540
1541static bool
1542try_pbo_upload(struct gl_context *ctx, GLuint dims,
1543               struct gl_texture_image *texImage,
1544               GLenum format, GLenum type,
1545               enum pipe_format dst_format,
1546               GLint xoffset, GLint yoffset, GLint zoffset,
1547               GLint width, GLint height, GLint depth,
1548               const void *pixels,
1549               const struct gl_pixelstore_attrib *unpack)
1550{
1551   struct st_context *st = st_context(ctx);
1552   struct st_texture_image *stImage = st_texture_image(texImage);
1553   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
1554   struct pipe_resource *texture = stImage->pt;
1555   struct pipe_context *pipe = st->pipe;
1556   struct pipe_screen *screen = pipe->screen;
1557   struct pipe_surface *surface = NULL;
1558   enum pipe_format src_format;
1559   const struct util_format_description *desc;
1560   GLenum gl_target = texImage->TexObject->Target;
1561   intptr_t buf_offset;
1562   unsigned bytes_per_pixel;
1563   unsigned stride, image_height;
1564   bool success;
1565
1566   if (!st->pbo_upload.enabled)
1567      return false;
1568
1569   /* From now on, we need the gallium representation of dimensions. */
1570   if (gl_target == GL_TEXTURE_1D_ARRAY) {
1571      depth = height;
1572      height = 1;
1573      zoffset = yoffset;
1574      yoffset = 0;
1575      image_height = 1;
1576   } else {
1577      image_height = unpack->ImageHeight > 0 ? unpack->ImageHeight : height;
1578   }
1579
1580   if (depth != 1 && !st->pbo_upload.upload_layers)
1581      return false;
1582
1583   /* Choose the source format. Initially, we do so without checking driver
1584    * support at all because of the remapping we later perform and because
1585    * at least the Radeon driver actually supports some formats for texture
1586    * buffers which it doesn't support for regular textures. */
1587   src_format = st_choose_matching_format(st, 0, format, type, unpack->SwapBytes);
1588   if (!src_format) {
1589      return false;
1590   }
1591
1592   src_format = util_format_linear(src_format);
1593   desc = util_format_description(src_format);
1594
1595   if (desc->layout != UTIL_FORMAT_LAYOUT_PLAIN)
1596      return false;
1597
1598   if (desc->colorspace != UTIL_FORMAT_COLORSPACE_RGB)
1599      return false;
1600
1601   if (st->pbo_upload.rgba_only) {
1602      enum pipe_format orig_dst_format = dst_format;
1603
1604      if (!reinterpret_formats(&src_format, &dst_format)) {
1605         return false;
1606      }
1607
1608      if (dst_format != orig_dst_format &&
1609          !screen->is_format_supported(screen, dst_format, PIPE_TEXTURE_2D, 0,
1610                                       PIPE_BIND_RENDER_TARGET)) {
1611         return false;
1612      }
1613   }
1614
1615   if (!src_format ||
1616       !screen->is_format_supported(screen, src_format, PIPE_BUFFER, 0,
1617                                    PIPE_BIND_SAMPLER_VIEW)) {
1618      return false;
1619   }
1620
1621   /* Check if the offset satisfies the alignment requirements */
1622   buf_offset = (intptr_t) pixels;
1623   bytes_per_pixel = desc->block.bits / 8;
1624
1625   if (buf_offset % bytes_per_pixel) {
1626      return false;
1627   }
1628
1629   /* Convert to texels */
1630   buf_offset = buf_offset / bytes_per_pixel;
1631
1632   /* Compute the stride, taking unpack->Alignment into account */
1633   {
1634       unsigned pixels_per_row = unpack->RowLength > 0 ?
1635                           unpack->RowLength : width;
1636       unsigned bytes_per_row = pixels_per_row * bytes_per_pixel;
1637       unsigned remainder = bytes_per_row % unpack->Alignment;
1638       unsigned offset_rows;
1639
1640       if (remainder > 0)
1641          bytes_per_row += (unpack->Alignment - remainder);
1642
1643       if (bytes_per_row % bytes_per_pixel) {
1644          return false;
1645       }
1646
1647       stride = bytes_per_row / bytes_per_pixel;
1648
1649       offset_rows = unpack->SkipRows;
1650       if (dims == 3)
1651          offset_rows += image_height * unpack->SkipImages;
1652
1653       buf_offset += unpack->SkipPixels + stride * offset_rows;
1654   }
1655
1656   /* Set up the surface */
1657   {
1658      unsigned level = stObj->pt != stImage->pt ? 0 : texImage->TexObject->MinLevel + texImage->Level;
1659      unsigned max_layer = util_max_layer(texture, level);
1660
1661      zoffset += texImage->Face + texImage->TexObject->MinLayer;
1662
1663      struct pipe_surface templ;
1664      memset(&templ, 0, sizeof(templ));
1665      templ.format = dst_format;
1666      templ.u.tex.level = level;
1667      templ.u.tex.first_layer = MIN2(zoffset, max_layer);
1668      templ.u.tex.last_layer = MIN2(zoffset + depth - 1, max_layer);
1669
1670      surface = pipe->create_surface(pipe, texture, &templ);
1671      if (!surface)
1672         return false;
1673   }
1674
1675   success = try_pbo_upload_common(ctx,  surface,
1676                                   xoffset, yoffset, width, height,
1677                                   st_buffer_object(unpack->BufferObj)->buffer,
1678                                   src_format,
1679                                   buf_offset,
1680                                   bytes_per_pixel, stride, image_height);
1681
1682   pipe_surface_reference(&surface, NULL);
1683
1684   return success;
1685}
1686
1687static void
1688st_TexSubImage(struct gl_context *ctx, GLuint dims,
1689               struct gl_texture_image *texImage,
1690               GLint xoffset, GLint yoffset, GLint zoffset,
1691               GLint width, GLint height, GLint depth,
1692               GLenum format, GLenum type, const void *pixels,
1693               const struct gl_pixelstore_attrib *unpack)
1694{
1695   struct st_context *st = st_context(ctx);
1696   struct st_texture_image *stImage = st_texture_image(texImage);
1697   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
1698   struct pipe_context *pipe = st->pipe;
1699   struct pipe_screen *screen = pipe->screen;
1700   struct pipe_resource *dst = stImage->pt;
1701   struct pipe_resource *src = NULL;
1702   struct pipe_resource src_templ;
1703   struct pipe_transfer *transfer;
1704   struct pipe_blit_info blit;
1705   enum pipe_format src_format, dst_format;
1706   mesa_format mesa_src_format;
1707   GLenum gl_target = texImage->TexObject->Target;
1708   unsigned bind;
1709   GLubyte *map;
1710
1711   assert(!_mesa_is_format_etc2(texImage->TexFormat) &&
1712          texImage->TexFormat != MESA_FORMAT_ETC1_RGB8);
1713
1714   if (!st->prefer_blit_based_texture_transfer) {
1715      goto fallback;
1716   }
1717
1718   if (!dst) {
1719      goto fallback;
1720   }
1721
1722   /* XXX Fallback for depth-stencil formats due to an incomplete stencil
1723    * blit implementation in some drivers. */
1724   if (format == GL_DEPTH_STENCIL) {
1725      goto fallback;
1726   }
1727
1728   /* If the base internal format and the texture format don't match,
1729    * we can't use blit-based TexSubImage. */
1730   if (texImage->_BaseFormat !=
1731       _mesa_get_format_base_format(texImage->TexFormat)) {
1732      goto fallback;
1733   }
1734
1735
1736   /* See if the destination format is supported. */
1737   if (format == GL_DEPTH_COMPONENT || format == GL_DEPTH_STENCIL)
1738      bind = PIPE_BIND_DEPTH_STENCIL;
1739   else
1740      bind = PIPE_BIND_RENDER_TARGET;
1741
1742   /* For luminance and intensity, only the red channel is stored
1743    * in the destination. */
1744   dst_format = util_format_linear(dst->format);
1745   dst_format = util_format_luminance_to_red(dst_format);
1746   dst_format = util_format_intensity_to_red(dst_format);
1747
1748   if (!dst_format ||
1749       !screen->is_format_supported(screen, dst_format, dst->target,
1750                                    dst->nr_samples, bind)) {
1751      goto fallback;
1752   }
1753
1754   if (_mesa_is_bufferobj(unpack->BufferObj)) {
1755      if (try_pbo_upload(ctx, dims, texImage, format, type, dst_format,
1756                         xoffset, yoffset, zoffset,
1757                         width, height, depth, pixels, unpack))
1758         return;
1759   }
1760
1761   /* See if the texture format already matches the format and type,
1762    * in which case the memcpy-based fast path will likely be used and
1763    * we don't have to blit. */
1764   if (_mesa_format_matches_format_and_type(texImage->TexFormat, format,
1765                                            type, unpack->SwapBytes, NULL)) {
1766      goto fallback;
1767   }
1768
1769   /* Choose the source format. */
1770   src_format = st_choose_matching_format(st, PIPE_BIND_SAMPLER_VIEW,
1771                                          format, type, unpack->SwapBytes);
1772   if (!src_format) {
1773      goto fallback;
1774   }
1775
1776   mesa_src_format = st_pipe_format_to_mesa_format(src_format);
1777
1778   /* There is no reason to do this if we cannot use memcpy for the temporary
1779    * source texture at least. This also takes transfer ops into account,
1780    * etc. */
1781   if (!_mesa_texstore_can_use_memcpy(ctx,
1782                             _mesa_get_format_base_format(mesa_src_format),
1783                             mesa_src_format, format, type, unpack)) {
1784      goto fallback;
1785   }
1786
1787   /* TexSubImage only sets a single cubemap face. */
1788   if (gl_target == GL_TEXTURE_CUBE_MAP) {
1789      gl_target = GL_TEXTURE_2D;
1790   }
1791   /* TexSubImage can specify subsets of cube map array faces
1792    * so we need to upload via 2D array instead */
1793   if (gl_target == GL_TEXTURE_CUBE_MAP_ARRAY) {
1794      gl_target = GL_TEXTURE_2D_ARRAY;
1795   }
1796
1797   /* Initialize the source texture description. */
1798   memset(&src_templ, 0, sizeof(src_templ));
1799   src_templ.target = gl_target_to_pipe(gl_target);
1800   src_templ.format = src_format;
1801   src_templ.bind = PIPE_BIND_SAMPLER_VIEW;
1802   src_templ.usage = PIPE_USAGE_STAGING;
1803
1804   st_gl_texture_dims_to_pipe_dims(gl_target, width, height, depth,
1805                                   &src_templ.width0, &src_templ.height0,
1806                                   &src_templ.depth0, &src_templ.array_size);
1807
1808   /* Check for NPOT texture support. */
1809   if (!screen->get_param(screen, PIPE_CAP_NPOT_TEXTURES) &&
1810       (!util_is_power_of_two(src_templ.width0) ||
1811        !util_is_power_of_two(src_templ.height0) ||
1812        !util_is_power_of_two(src_templ.depth0))) {
1813      goto fallback;
1814   }
1815
1816   /* Create the source texture. */
1817   src = screen->resource_create(screen, &src_templ);
1818   if (!src) {
1819      goto fallback;
1820   }
1821
1822   /* Map source pixels. */
1823   pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, depth,
1824                                        format, type, pixels, unpack,
1825                                        "glTexSubImage");
1826   if (!pixels) {
1827      /* This is a GL error. */
1828      pipe_resource_reference(&src, NULL);
1829      return;
1830   }
1831
1832   /* From now on, we need the gallium representation of dimensions. */
1833   if (gl_target == GL_TEXTURE_1D_ARRAY) {
1834      zoffset = yoffset;
1835      yoffset = 0;
1836      depth = height;
1837      height = 1;
1838   }
1839
1840   map = pipe_transfer_map_3d(pipe, src, 0, PIPE_TRANSFER_WRITE, 0, 0, 0,
1841                              width, height, depth, &transfer);
1842   if (!map) {
1843      _mesa_unmap_teximage_pbo(ctx, unpack);
1844      pipe_resource_reference(&src, NULL);
1845      goto fallback;
1846   }
1847
1848   /* Upload pixels (just memcpy). */
1849   {
1850      const uint bytesPerRow = width * util_format_get_blocksize(src_format);
1851      GLuint row, slice;
1852
1853      for (slice = 0; slice < (unsigned) depth; slice++) {
1854         if (gl_target == GL_TEXTURE_1D_ARRAY) {
1855            /* 1D array textures.
1856             * We need to convert gallium coords to GL coords.
1857             */
1858            GLvoid *src = _mesa_image_address2d(unpack, pixels,
1859                                                width, depth, format,
1860                                                type, slice, 0);
1861            memcpy(map, src, bytesPerRow);
1862         }
1863         else {
1864            ubyte *slice_map = map;
1865
1866            for (row = 0; row < (unsigned) height; row++) {
1867               GLvoid *src = _mesa_image_address(dims, unpack, pixels,
1868                                                 width, height, format,
1869                                                 type, slice, row, 0);
1870               memcpy(slice_map, src, bytesPerRow);
1871               slice_map += transfer->stride;
1872            }
1873         }
1874         map += transfer->layer_stride;
1875      }
1876   }
1877
1878   pipe_transfer_unmap(pipe, transfer);
1879   _mesa_unmap_teximage_pbo(ctx, unpack);
1880
1881   /* Blit. */
1882   memset(&blit, 0, sizeof(blit));
1883   blit.src.resource = src;
1884   blit.src.level = 0;
1885   blit.src.format = src_format;
1886   blit.dst.resource = dst;
1887   blit.dst.level = stObj->pt != stImage->pt ? 0 : texImage->TexObject->MinLevel + texImage->Level;
1888   blit.dst.format = dst_format;
1889   blit.src.box.x = blit.src.box.y = blit.src.box.z = 0;
1890   blit.dst.box.x = xoffset;
1891   blit.dst.box.y = yoffset;
1892   blit.dst.box.z = zoffset + texImage->Face + texImage->TexObject->MinLayer;
1893   blit.src.box.width = blit.dst.box.width = width;
1894   blit.src.box.height = blit.dst.box.height = height;
1895   blit.src.box.depth = blit.dst.box.depth = depth;
1896   blit.mask = st_get_blit_mask(format, texImage->_BaseFormat);
1897   blit.filter = PIPE_TEX_FILTER_NEAREST;
1898   blit.scissor_enable = FALSE;
1899
1900   st->pipe->blit(st->pipe, &blit);
1901
1902   pipe_resource_reference(&src, NULL);
1903   return;
1904
1905fallback:
1906   _mesa_store_texsubimage(ctx, dims, texImage, xoffset, yoffset, zoffset,
1907                           width, height, depth, format, type, pixels,
1908                           unpack);
1909}
1910
1911static void
1912st_TexImage(struct gl_context * ctx, GLuint dims,
1913            struct gl_texture_image *texImage,
1914            GLenum format, GLenum type, const void *pixels,
1915            const struct gl_pixelstore_attrib *unpack)
1916{
1917   assert(dims == 1 || dims == 2 || dims == 3);
1918
1919   prep_teximage(ctx, texImage, format, type);
1920
1921   if (texImage->Width == 0 || texImage->Height == 0 || texImage->Depth == 0)
1922      return;
1923
1924   /* allocate storage for texture data */
1925   if (!ctx->Driver.AllocTextureImageBuffer(ctx, texImage)) {
1926      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage%uD", dims);
1927      return;
1928   }
1929
1930   st_TexSubImage(ctx, dims, texImage, 0, 0, 0,
1931                  texImage->Width, texImage->Height, texImage->Depth,
1932                  format, type, pixels, unpack);
1933}
1934
1935
1936static void
1937st_CompressedTexSubImage(struct gl_context *ctx, GLuint dims,
1938                         struct gl_texture_image *texImage,
1939                         GLint x, GLint y, GLint z,
1940                         GLsizei w, GLsizei h, GLsizei d,
1941                         GLenum format, GLsizei imageSize, const GLvoid *data)
1942{
1943   struct st_context *st = st_context(ctx);
1944   struct st_texture_image *stImage = st_texture_image(texImage);
1945   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
1946   struct pipe_resource *texture = stImage->pt;
1947   struct pipe_context *pipe = st->pipe;
1948   struct pipe_screen *screen = pipe->screen;
1949   struct pipe_resource *dst = stImage->pt;
1950   struct pipe_surface *surface = NULL;
1951   struct compressed_pixelstore store;
1952   enum pipe_format copy_format;
1953   unsigned bytes_per_block;
1954   unsigned bw, bh;
1955   intptr_t buf_offset;
1956   bool success = false;
1957
1958   /* Check basic pre-conditions for PBO upload */
1959   if (!st->prefer_blit_based_texture_transfer) {
1960      goto fallback;
1961   }
1962
1963   if (!_mesa_is_bufferobj(ctx->Unpack.BufferObj))
1964      goto fallback;
1965
1966   if ((_mesa_is_format_etc2(texImage->TexFormat) && !st->has_etc2) ||
1967       (texImage->TexFormat == MESA_FORMAT_ETC1_RGB8 && !st->has_etc1)) {
1968      /* ETC isn't supported and is represented by uncompressed formats. */
1969      goto fallback;
1970   }
1971
1972   if (!dst) {
1973      goto fallback;
1974   }
1975
1976   if (!st->pbo_upload.enabled ||
1977       !screen->get_param(screen, PIPE_CAP_SURFACE_REINTERPRET_BLOCKS)) {
1978      goto fallback;
1979   }
1980
1981   /* Choose the pipe format for the upload. */
1982   bytes_per_block = util_format_get_blocksize(dst->format);
1983   bw = util_format_get_blockwidth(dst->format);
1984   bh = util_format_get_blockheight(dst->format);
1985
1986   switch (bytes_per_block) {
1987   case 8:
1988      copy_format = PIPE_FORMAT_R16G16B16A16_UINT;
1989      break;
1990   case 16:
1991      copy_format = PIPE_FORMAT_R32G32B32A32_UINT;
1992      break;
1993   default:
1994      goto fallback;
1995   }
1996
1997   if (!screen->is_format_supported(screen, copy_format, PIPE_BUFFER, 0,
1998                                    PIPE_BIND_SAMPLER_VIEW)) {
1999      goto fallback;
2000   }
2001
2002   if (!screen->is_format_supported(screen, copy_format, dst->target,
2003                                    dst->nr_samples, PIPE_BIND_RENDER_TARGET)) {
2004      goto fallback;
2005   }
2006
2007   /* Interpret the pixelstore settings. */
2008   _mesa_compute_compressed_pixelstore(dims, texImage->TexFormat, w, h, d,
2009                                       &ctx->Unpack, &store);
2010   assert(store.CopyBytesPerRow % bytes_per_block == 0);
2011   assert(store.SkipBytes % bytes_per_block == 0);
2012
2013   /* Compute the offset into the buffer */
2014   buf_offset = (intptr_t)data + store.SkipBytes;
2015
2016   if (buf_offset % bytes_per_block) {
2017      goto fallback;
2018   }
2019
2020   buf_offset = buf_offset / bytes_per_block;
2021
2022   /* Set up the surface. */
2023   {
2024      unsigned level = stObj->pt != stImage->pt ? 0 : texImage->TexObject->MinLevel + texImage->Level;
2025      unsigned max_layer = util_max_layer(texture, level);
2026
2027      z += texImage->Face + texImage->TexObject->MinLayer;
2028
2029      struct pipe_surface templ;
2030      memset(&templ, 0, sizeof(templ));
2031      templ.format = copy_format;
2032      templ.u.tex.level = level;
2033      templ.u.tex.first_layer = MIN2(z, max_layer);
2034      templ.u.tex.last_layer = MIN2(z + d - 1, max_layer);
2035
2036      surface = pipe->create_surface(pipe, texture, &templ);
2037      if (!surface)
2038         goto fallback;
2039   }
2040
2041   success = try_pbo_upload_common(ctx, surface,
2042                                   x / bw, y / bh,
2043                                   store.CopyBytesPerRow / bytes_per_block,
2044                                   store.CopyRowsPerSlice,
2045                                   st_buffer_object(ctx->Unpack.BufferObj)->buffer,
2046                                   copy_format,
2047                                   buf_offset,
2048                                   bytes_per_block,
2049                                   store.TotalBytesPerRow / bytes_per_block,
2050                                   store.TotalRowsPerSlice);
2051
2052   pipe_surface_reference(&surface, NULL);
2053
2054   if (success)
2055      return;
2056
2057fallback:
2058   _mesa_store_compressed_texsubimage(ctx, dims, texImage,
2059                                      x, y, z, w, h, d,
2060                                      format, imageSize, data);
2061}
2062
2063static void
2064st_CompressedTexImage(struct gl_context *ctx, GLuint dims,
2065                      struct gl_texture_image *texImage,
2066                      GLsizei imageSize, const GLvoid *data)
2067{
2068   prep_teximage(ctx, texImage, GL_NONE, GL_NONE);
2069
2070   /* only 2D and 3D compressed images are supported at this time */
2071   if (dims == 1) {
2072      _mesa_problem(ctx, "Unexpected glCompressedTexImage1D call");
2073      return;
2074   }
2075
2076   /* This is pretty simple, because unlike the general texstore path we don't
2077    * have to worry about the usual image unpacking or image transfer
2078    * operations.
2079    */
2080   assert(texImage);
2081   assert(texImage->Width > 0);
2082   assert(texImage->Height > 0);
2083   assert(texImage->Depth > 0);
2084
2085   /* allocate storage for texture data */
2086   if (!st_AllocTextureImageBuffer(ctx, texImage)) {
2087      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage%uD", dims);
2088      return;
2089   }
2090
2091   st_CompressedTexSubImage(ctx, dims, texImage,
2092                            0, 0, 0,
2093                            texImage->Width, texImage->Height, texImage->Depth,
2094                            texImage->TexFormat,
2095                            imageSize, data);
2096}
2097
2098
2099
2100
2101/**
2102 * Called via ctx->Driver.GetTexSubImage()
2103 *
2104 * This uses a blit to copy the texture to a texture format which matches
2105 * the format and type combo and then a fast read-back is done using memcpy.
2106 * We can do arbitrary X/Y/Z/W/0/1 swizzling here as long as there is
2107 * a format which matches the swizzling.
2108 *
2109 * If such a format isn't available, it falls back to _mesa_GetTexImage_sw.
2110 *
2111 * NOTE: Drivers usually do a blit to convert between tiled and linear
2112 *       texture layouts during texture uploads/downloads, so the blit
2113 *       we do here should be free in such cases.
2114 */
2115static void
2116st_GetTexSubImage(struct gl_context * ctx,
2117                  GLint xoffset, GLint yoffset, GLint zoffset,
2118                  GLsizei width, GLsizei height, GLint depth,
2119                  GLenum format, GLenum type, GLvoid * pixels,
2120                  struct gl_texture_image *texImage)
2121{
2122   struct st_context *st = st_context(ctx);
2123   struct pipe_context *pipe = st->pipe;
2124   struct pipe_screen *screen = pipe->screen;
2125   struct st_texture_image *stImage = st_texture_image(texImage);
2126   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
2127   struct pipe_resource *src = stObj->pt;
2128   struct pipe_resource *dst = NULL;
2129   struct pipe_resource dst_templ;
2130   enum pipe_format dst_format, src_format;
2131   mesa_format mesa_format;
2132   GLenum gl_target = texImage->TexObject->Target;
2133   enum pipe_texture_target pipe_target;
2134   struct pipe_blit_info blit;
2135   unsigned bind = PIPE_BIND_TRANSFER_READ;
2136   struct pipe_transfer *tex_xfer;
2137   ubyte *map = NULL;
2138   boolean done = FALSE;
2139
2140   assert(!_mesa_is_format_etc2(texImage->TexFormat) &&
2141          texImage->TexFormat != MESA_FORMAT_ETC1_RGB8);
2142
2143   if (!st->prefer_blit_based_texture_transfer &&
2144       !_mesa_is_format_compressed(texImage->TexFormat)) {
2145      /* Try to avoid the fallback if we're doing texture decompression here */
2146      goto fallback;
2147   }
2148
2149   if (!stImage->pt || !src) {
2150      goto fallback;
2151   }
2152
2153   /* XXX Fallback to _mesa_GetTexImage_sw for depth-stencil formats
2154    * due to an incomplete stencil blit implementation in some drivers. */
2155   if (format == GL_DEPTH_STENCIL || format == GL_STENCIL_INDEX) {
2156      goto fallback;
2157   }
2158
2159   /* If the base internal format and the texture format don't match, we have
2160    * to fall back to _mesa_GetTexImage_sw. */
2161   if (texImage->_BaseFormat !=
2162       _mesa_get_format_base_format(texImage->TexFormat)) {
2163      goto fallback;
2164   }
2165
2166   /* See if the texture format already matches the format and type,
2167    * in which case the memcpy-based fast path will be used. */
2168   if (_mesa_format_matches_format_and_type(texImage->TexFormat, format,
2169                                            type, ctx->Pack.SwapBytes, NULL)) {
2170      goto fallback;
2171   }
2172
2173   /* Convert the source format to what is expected by GetTexImage
2174    * and see if it's supported.
2175    *
2176    * This only applies to glGetTexImage:
2177    * - Luminance must be returned as (L,0,0,1).
2178    * - Luminance alpha must be returned as (L,0,0,A).
2179    * - Intensity must be returned as (I,0,0,1)
2180    */
2181   if (stObj->surface_based)
2182      src_format = util_format_linear(stObj->surface_format);
2183   else
2184      src_format = util_format_linear(src->format);
2185   src_format = util_format_luminance_to_red(src_format);
2186   src_format = util_format_intensity_to_red(src_format);
2187
2188   if (!src_format ||
2189       !screen->is_format_supported(screen, src_format, src->target,
2190                                    src->nr_samples,
2191                                    PIPE_BIND_SAMPLER_VIEW)) {
2192      goto fallback;
2193   }
2194
2195   if (format == GL_DEPTH_COMPONENT || format == GL_DEPTH_STENCIL)
2196      bind |= PIPE_BIND_DEPTH_STENCIL;
2197   else
2198      bind |= PIPE_BIND_RENDER_TARGET;
2199
2200   /* GetTexImage only returns a single face for cubemaps. */
2201   if (gl_target == GL_TEXTURE_CUBE_MAP) {
2202      gl_target = GL_TEXTURE_2D;
2203   }
2204   pipe_target = gl_target_to_pipe(gl_target);
2205
2206   /* Choose the destination format by finding the best match
2207    * for the format+type combo. */
2208   dst_format = st_choose_matching_format(st, bind, format, type,
2209					  ctx->Pack.SwapBytes);
2210
2211   if (dst_format == PIPE_FORMAT_NONE) {
2212      GLenum dst_glformat;
2213
2214      /* Fall back to _mesa_GetTexImage_sw except for compressed formats,
2215       * where decompression with a blit is always preferred. */
2216      if (!util_format_is_compressed(src->format)) {
2217         goto fallback;
2218      }
2219
2220      /* Set the appropriate format for the decompressed texture.
2221       * Luminance and sRGB formats shouldn't appear here.*/
2222      switch (src_format) {
2223      case PIPE_FORMAT_DXT1_RGB:
2224      case PIPE_FORMAT_DXT1_RGBA:
2225      case PIPE_FORMAT_DXT3_RGBA:
2226      case PIPE_FORMAT_DXT5_RGBA:
2227      case PIPE_FORMAT_RGTC1_UNORM:
2228      case PIPE_FORMAT_RGTC2_UNORM:
2229      case PIPE_FORMAT_ETC1_RGB8:
2230      case PIPE_FORMAT_BPTC_RGBA_UNORM:
2231         dst_glformat = GL_RGBA8;
2232         break;
2233      case PIPE_FORMAT_RGTC1_SNORM:
2234      case PIPE_FORMAT_RGTC2_SNORM:
2235         if (!ctx->Extensions.EXT_texture_snorm)
2236            goto fallback;
2237         dst_glformat = GL_RGBA8_SNORM;
2238         break;
2239      case PIPE_FORMAT_BPTC_RGB_FLOAT:
2240      case PIPE_FORMAT_BPTC_RGB_UFLOAT:
2241         if (!ctx->Extensions.ARB_texture_float)
2242            goto fallback;
2243         dst_glformat = GL_RGBA32F;
2244         break;
2245      default:
2246         assert(0);
2247         goto fallback;
2248      }
2249
2250      dst_format = st_choose_format(st, dst_glformat, format, type,
2251                                    pipe_target, 0, bind, FALSE);
2252
2253      if (dst_format == PIPE_FORMAT_NONE) {
2254         /* unable to get an rgba format!?! */
2255         goto fallback;
2256      }
2257   }
2258
2259   /* create the destination texture of size (width X height X depth) */
2260   memset(&dst_templ, 0, sizeof(dst_templ));
2261   dst_templ.target = pipe_target;
2262   dst_templ.format = dst_format;
2263   dst_templ.bind = bind;
2264   dst_templ.usage = PIPE_USAGE_STAGING;
2265
2266   st_gl_texture_dims_to_pipe_dims(gl_target, width, height, depth,
2267                                   &dst_templ.width0, &dst_templ.height0,
2268                                   &dst_templ.depth0, &dst_templ.array_size);
2269
2270   dst = screen->resource_create(screen, &dst_templ);
2271   if (!dst) {
2272      goto fallback;
2273   }
2274
2275   /* From now on, we need the gallium representation of dimensions. */
2276   if (gl_target == GL_TEXTURE_1D_ARRAY) {
2277      zoffset = yoffset;
2278      yoffset = 0;
2279      depth = height;
2280      height = 1;
2281   }
2282
2283   assert(texImage->Face == 0 ||
2284          texImage->TexObject->MinLayer == 0 ||
2285          zoffset == 0);
2286
2287   memset(&blit, 0, sizeof(blit));
2288   blit.src.resource = src;
2289   blit.src.level = texImage->Level + texImage->TexObject->MinLevel;
2290   blit.src.format = src_format;
2291   blit.dst.resource = dst;
2292   blit.dst.level = 0;
2293   blit.dst.format = dst->format;
2294   blit.src.box.x = xoffset;
2295   blit.dst.box.x = 0;
2296   blit.src.box.y = yoffset;
2297   blit.dst.box.y = 0;
2298   blit.src.box.z = texImage->Face + texImage->TexObject->MinLayer + zoffset;
2299   blit.dst.box.z = 0;
2300   blit.src.box.width = blit.dst.box.width = width;
2301   blit.src.box.height = blit.dst.box.height = height;
2302   blit.src.box.depth = blit.dst.box.depth = depth;
2303   blit.mask = st_get_blit_mask(texImage->_BaseFormat, format);
2304   blit.filter = PIPE_TEX_FILTER_NEAREST;
2305   blit.scissor_enable = FALSE;
2306
2307   /* blit/render/decompress */
2308   st->pipe->blit(st->pipe, &blit);
2309
2310   pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
2311
2312   map = pipe_transfer_map_3d(pipe, dst, 0, PIPE_TRANSFER_READ,
2313                              0, 0, 0, width, height, depth, &tex_xfer);
2314   if (!map) {
2315      goto end;
2316   }
2317
2318   mesa_format = st_pipe_format_to_mesa_format(dst_format);
2319
2320   /* copy/pack data into user buffer */
2321   if (_mesa_format_matches_format_and_type(mesa_format, format, type,
2322                                            ctx->Pack.SwapBytes, NULL)) {
2323      /* memcpy */
2324      const uint bytesPerRow = width * util_format_get_blocksize(dst_format);
2325      GLuint row, slice;
2326
2327      for (slice = 0; slice < depth; slice++) {
2328         if (gl_target == GL_TEXTURE_1D_ARRAY) {
2329            /* 1D array textures.
2330             * We need to convert gallium coords to GL coords.
2331             */
2332            GLvoid *dest = _mesa_image_address3d(&ctx->Pack, pixels,
2333                                                 width, depth, format,
2334                                                 type, 0, slice, 0);
2335            memcpy(dest, map, bytesPerRow);
2336         }
2337         else {
2338            ubyte *slice_map = map;
2339
2340            for (row = 0; row < height; row++) {
2341               GLvoid *dest = _mesa_image_address3d(&ctx->Pack, pixels,
2342                                                    width, height, format,
2343                                                    type, slice, row, 0);
2344               memcpy(dest, slice_map, bytesPerRow);
2345               slice_map += tex_xfer->stride;
2346            }
2347         }
2348         map += tex_xfer->layer_stride;
2349      }
2350   }
2351   else {
2352      /* format translation via floats */
2353      GLuint row, slice;
2354      GLfloat *rgba;
2355      uint32_t dstMesaFormat;
2356      int dstStride, srcStride;
2357
2358      assert(util_format_is_compressed(src->format));
2359
2360      rgba = malloc(width * 4 * sizeof(GLfloat));
2361      if (!rgba) {
2362         goto end;
2363      }
2364
2365      if (ST_DEBUG & DEBUG_FALLBACK)
2366         debug_printf("%s: fallback format translation\n", __func__);
2367
2368      dstMesaFormat = _mesa_format_from_format_and_type(format, type);
2369      dstStride = _mesa_image_row_stride(&ctx->Pack, width, format, type);
2370      srcStride = 4 * width * sizeof(GLfloat);
2371      for (slice = 0; slice < depth; slice++) {
2372         if (gl_target == GL_TEXTURE_1D_ARRAY) {
2373            /* 1D array textures.
2374             * We need to convert gallium coords to GL coords.
2375             */
2376            GLvoid *dest = _mesa_image_address3d(&ctx->Pack, pixels,
2377                                                 width, depth, format,
2378                                                 type, 0, slice, 0);
2379
2380            /* get float[4] rgba row from surface */
2381            pipe_get_tile_rgba_format(tex_xfer, map, 0, 0, width, 1,
2382                                      dst_format, rgba);
2383
2384            _mesa_format_convert(dest, dstMesaFormat, dstStride,
2385                                 rgba, RGBA32_FLOAT, srcStride,
2386                                 width, 1, NULL);
2387         }
2388         else {
2389            for (row = 0; row < height; row++) {
2390               GLvoid *dest = _mesa_image_address3d(&ctx->Pack, pixels,
2391                                                    width, height, format,
2392                                                    type, slice, row, 0);
2393
2394               /* get float[4] rgba row from surface */
2395               pipe_get_tile_rgba_format(tex_xfer, map, 0, row, width, 1,
2396                                         dst_format, rgba);
2397
2398               _mesa_format_convert(dest, dstMesaFormat, dstStride,
2399                                    rgba, RGBA32_FLOAT, srcStride,
2400                                    width, 1, NULL);
2401            }
2402         }
2403         map += tex_xfer->layer_stride;
2404      }
2405
2406      free(rgba);
2407   }
2408   done = TRUE;
2409
2410end:
2411   if (map)
2412      pipe_transfer_unmap(pipe, tex_xfer);
2413
2414   _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
2415   pipe_resource_reference(&dst, NULL);
2416
2417fallback:
2418   if (!done) {
2419      _mesa_GetTexSubImage_sw(ctx, xoffset, yoffset, zoffset,
2420                              width, height, depth,
2421                              format, type, pixels, texImage);
2422   }
2423}
2424
2425
2426/**
2427 * Do a CopyTexSubImage operation using a read transfer from the source,
2428 * a write transfer to the destination and get_tile()/put_tile() to access
2429 * the pixels/texels.
2430 *
2431 * Note: srcY=0=TOP of renderbuffer
2432 */
2433static void
2434fallback_copy_texsubimage(struct gl_context *ctx,
2435                          struct st_renderbuffer *strb,
2436                          struct st_texture_image *stImage,
2437                          GLenum baseFormat,
2438                          GLint destX, GLint destY, GLint slice,
2439                          GLint srcX, GLint srcY,
2440                          GLsizei width, GLsizei height)
2441{
2442   struct st_context *st = st_context(ctx);
2443   struct pipe_context *pipe = st->pipe;
2444   struct pipe_transfer *src_trans;
2445   GLubyte *texDest;
2446   enum pipe_transfer_usage transfer_usage;
2447   void *map;
2448   unsigned dst_width = width;
2449   unsigned dst_height = height;
2450   unsigned dst_depth = 1;
2451   struct pipe_transfer *transfer;
2452
2453   if (ST_DEBUG & DEBUG_FALLBACK)
2454      debug_printf("%s: fallback processing\n", __func__);
2455
2456   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
2457      srcY = strb->Base.Height - srcY - height;
2458   }
2459
2460   map = pipe_transfer_map(pipe,
2461                           strb->texture,
2462                           strb->surface->u.tex.level,
2463                           strb->surface->u.tex.first_layer,
2464                           PIPE_TRANSFER_READ,
2465                           srcX, srcY,
2466                           width, height, &src_trans);
2467
2468   if ((baseFormat == GL_DEPTH_COMPONENT ||
2469        baseFormat == GL_DEPTH_STENCIL) &&
2470       util_format_is_depth_and_stencil(stImage->pt->format))
2471      transfer_usage = PIPE_TRANSFER_READ_WRITE;
2472   else
2473      transfer_usage = PIPE_TRANSFER_WRITE;
2474
2475   texDest = st_texture_image_map(st, stImage, transfer_usage,
2476                                  destX, destY, slice,
2477                                  dst_width, dst_height, dst_depth,
2478                                  &transfer);
2479
2480   if (baseFormat == GL_DEPTH_COMPONENT ||
2481       baseFormat == GL_DEPTH_STENCIL) {
2482      const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
2483                                     ctx->Pixel.DepthBias != 0.0F);
2484      GLint row, yStep;
2485      uint *data;
2486
2487      /* determine bottom-to-top vs. top-to-bottom order for src buffer */
2488      if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
2489         srcY = height - 1;
2490         yStep = -1;
2491      }
2492      else {
2493         srcY = 0;
2494         yStep = 1;
2495      }
2496
2497      data = malloc(width * sizeof(uint));
2498
2499      if (data) {
2500         /* To avoid a large temp memory allocation, do copy row by row */
2501         for (row = 0; row < height; row++, srcY += yStep) {
2502            pipe_get_tile_z(src_trans, map, 0, srcY, width, 1, data);
2503            if (scaleOrBias) {
2504               _mesa_scale_and_bias_depth_uint(ctx, width, data);
2505            }
2506
2507            if (stImage->pt->target == PIPE_TEXTURE_1D_ARRAY) {
2508               pipe_put_tile_z(transfer, texDest + row*transfer->layer_stride,
2509                               0, 0, width, 1, data);
2510            }
2511            else {
2512               pipe_put_tile_z(transfer, texDest, 0, row, width, 1, data);
2513            }
2514         }
2515      }
2516      else {
2517         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyTexSubImage()");
2518      }
2519
2520      free(data);
2521   }
2522   else {
2523      /* RGBA format */
2524      GLfloat *tempSrc =
2525         malloc(width * height * 4 * sizeof(GLfloat));
2526
2527      if (tempSrc && texDest) {
2528         const GLint dims = 2;
2529         GLint dstRowStride;
2530         struct gl_texture_image *texImage = &stImage->base;
2531         struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
2532
2533         if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
2534            unpack.Invert = GL_TRUE;
2535         }
2536
2537         if (stImage->pt->target == PIPE_TEXTURE_1D_ARRAY) {
2538            dstRowStride = transfer->layer_stride;
2539         }
2540         else {
2541            dstRowStride = transfer->stride;
2542         }
2543
2544         /* get float/RGBA image from framebuffer */
2545         /* XXX this usually involves a lot of int/float conversion.
2546          * try to avoid that someday.
2547          */
2548         pipe_get_tile_rgba_format(src_trans, map, 0, 0, width, height,
2549                                   util_format_linear(strb->texture->format),
2550                                   tempSrc);
2551
2552         /* Store into texture memory.
2553          * Note that this does some special things such as pixel transfer
2554          * ops and format conversion.  In particular, if the dest tex format
2555          * is actually RGBA but the user created the texture as GL_RGB we
2556          * need to fill-in/override the alpha channel with 1.0.
2557          */
2558         _mesa_texstore(ctx, dims,
2559                        texImage->_BaseFormat,
2560                        texImage->TexFormat,
2561                        dstRowStride,
2562                        &texDest,
2563                        width, height, 1,
2564                        GL_RGBA, GL_FLOAT, tempSrc, /* src */
2565                        &unpack);
2566      }
2567      else {
2568         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
2569      }
2570
2571      free(tempSrc);
2572   }
2573
2574   st_texture_image_unmap(st, stImage, slice);
2575   pipe->transfer_unmap(pipe, src_trans);
2576}
2577
2578
2579/**
2580 * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
2581 * Note that the region to copy has already been clipped so we know we
2582 * won't read from outside the source renderbuffer's bounds.
2583 *
2584 * Note: srcY=0=Bottom of renderbuffer (GL convention)
2585 */
2586static void
2587st_CopyTexSubImage(struct gl_context *ctx, GLuint dims,
2588                   struct gl_texture_image *texImage,
2589                   GLint destX, GLint destY, GLint slice,
2590                   struct gl_renderbuffer *rb,
2591                   GLint srcX, GLint srcY, GLsizei width, GLsizei height)
2592{
2593   struct st_texture_image *stImage = st_texture_image(texImage);
2594   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
2595   struct st_renderbuffer *strb = st_renderbuffer(rb);
2596   struct st_context *st = st_context(ctx);
2597   struct pipe_context *pipe = st->pipe;
2598   struct pipe_screen *screen = pipe->screen;
2599   struct pipe_blit_info blit;
2600   enum pipe_format dst_format;
2601   GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
2602   unsigned bind;
2603   GLint srcY0, srcY1;
2604
2605   assert(!_mesa_is_format_etc2(texImage->TexFormat) &&
2606          texImage->TexFormat != MESA_FORMAT_ETC1_RGB8);
2607
2608   if (!strb || !strb->surface || !stImage->pt) {
2609      debug_printf("%s: null strb or stImage\n", __func__);
2610      return;
2611   }
2612
2613   if (_mesa_texstore_needs_transfer_ops(ctx, texImage->_BaseFormat,
2614                                         texImage->TexFormat)) {
2615      goto fallback;
2616   }
2617
2618   /* The base internal format must match the mesa format, so make sure
2619    * e.g. an RGB internal format is really allocated as RGB and not as RGBA.
2620    */
2621   if (texImage->_BaseFormat !=
2622       _mesa_get_format_base_format(texImage->TexFormat) ||
2623       rb->_BaseFormat != _mesa_get_format_base_format(rb->Format)) {
2624      goto fallback;
2625   }
2626
2627   /* Choose the destination format to match the TexImage behavior. */
2628   dst_format = util_format_linear(stImage->pt->format);
2629   dst_format = util_format_luminance_to_red(dst_format);
2630   dst_format = util_format_intensity_to_red(dst_format);
2631
2632   /* See if the destination format is supported. */
2633   if (texImage->_BaseFormat == GL_DEPTH_STENCIL ||
2634       texImage->_BaseFormat == GL_DEPTH_COMPONENT) {
2635      bind = PIPE_BIND_DEPTH_STENCIL;
2636   }
2637   else {
2638      bind = PIPE_BIND_RENDER_TARGET;
2639   }
2640
2641   if (!dst_format ||
2642       !screen->is_format_supported(screen, dst_format, stImage->pt->target,
2643                                    stImage->pt->nr_samples, bind)) {
2644      goto fallback;
2645   }
2646
2647   /* Y flipping for the main framebuffer. */
2648   if (do_flip) {
2649      srcY1 = strb->Base.Height - srcY - height;
2650      srcY0 = srcY1 + height;
2651   }
2652   else {
2653      srcY0 = srcY;
2654      srcY1 = srcY0 + height;
2655   }
2656
2657   /* Blit the texture.
2658    * This supports flipping, format conversions, and downsampling.
2659    */
2660   memset(&blit, 0, sizeof(blit));
2661   blit.src.resource = strb->texture;
2662   blit.src.format = util_format_linear(strb->surface->format);
2663   blit.src.level = strb->surface->u.tex.level;
2664   blit.src.box.x = srcX;
2665   blit.src.box.y = srcY0;
2666   blit.src.box.z = strb->surface->u.tex.first_layer;
2667   blit.src.box.width = width;
2668   blit.src.box.height = srcY1 - srcY0;
2669   blit.src.box.depth = 1;
2670   blit.dst.resource = stImage->pt;
2671   blit.dst.format = dst_format;
2672   blit.dst.level = stObj->pt != stImage->pt ? 0 : texImage->Level + texImage->TexObject->MinLevel;
2673   blit.dst.box.x = destX;
2674   blit.dst.box.y = destY;
2675   blit.dst.box.z = stImage->base.Face + slice + texImage->TexObject->MinLayer;
2676   blit.dst.box.width = width;
2677   blit.dst.box.height = height;
2678   blit.dst.box.depth = 1;
2679   blit.mask = st_get_blit_mask(rb->_BaseFormat, texImage->_BaseFormat);
2680   blit.filter = PIPE_TEX_FILTER_NEAREST;
2681   pipe->blit(pipe, &blit);
2682   return;
2683
2684fallback:
2685   /* software fallback */
2686   fallback_copy_texsubimage(ctx,
2687                             strb, stImage, texImage->_BaseFormat,
2688                             destX, destY, slice,
2689                             srcX, srcY, width, height);
2690}
2691
2692
2693/**
2694 * Copy image data from stImage into the texture object 'stObj' at level
2695 * 'dstLevel'.
2696 */
2697static void
2698copy_image_data_to_texture(struct st_context *st,
2699			   struct st_texture_object *stObj,
2700                           GLuint dstLevel,
2701			   struct st_texture_image *stImage)
2702{
2703   /* debug checks */
2704   {
2705      const struct gl_texture_image *dstImage =
2706         stObj->base.Image[stImage->base.Face][dstLevel];
2707      assert(dstImage);
2708      assert(dstImage->Width == stImage->base.Width);
2709      assert(dstImage->Height == stImage->base.Height);
2710      assert(dstImage->Depth == stImage->base.Depth);
2711   }
2712
2713   if (stImage->pt) {
2714      /* Copy potentially with the blitter:
2715       */
2716      GLuint src_level;
2717      if (stImage->pt->last_level == 0)
2718         src_level = 0;
2719      else
2720         src_level = stImage->base.Level;
2721
2722      assert(src_level <= stImage->pt->last_level);
2723      assert(u_minify(stImage->pt->width0, src_level) == stImage->base.Width);
2724      assert(stImage->pt->target == PIPE_TEXTURE_1D_ARRAY ||
2725             u_minify(stImage->pt->height0, src_level) == stImage->base.Height);
2726      assert(stImage->pt->target == PIPE_TEXTURE_2D_ARRAY ||
2727             stImage->pt->target == PIPE_TEXTURE_CUBE_ARRAY ||
2728             u_minify(stImage->pt->depth0, src_level) == stImage->base.Depth);
2729
2730      st_texture_image_copy(st->pipe,
2731                            stObj->pt, dstLevel,  /* dest texture, level */
2732                            stImage->pt, src_level, /* src texture, level */
2733                            stImage->base.Face);
2734
2735      pipe_resource_reference(&stImage->pt, NULL);
2736   }
2737   pipe_resource_reference(&stImage->pt, stObj->pt);
2738}
2739
2740
2741/**
2742 * Called during state validation.  When this function is finished,
2743 * the texture object should be ready for rendering.
2744 * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
2745 */
2746GLboolean
2747st_finalize_texture(struct gl_context *ctx,
2748		    struct pipe_context *pipe,
2749		    struct gl_texture_object *tObj)
2750{
2751   struct st_context *st = st_context(ctx);
2752   struct st_texture_object *stObj = st_texture_object(tObj);
2753   const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
2754   GLuint face;
2755   const struct st_texture_image *firstImage;
2756   enum pipe_format firstImageFormat;
2757   GLuint ptWidth, ptHeight, ptDepth, ptLayers, ptNumSamples;
2758
2759   if (tObj->Immutable)
2760      return GL_TRUE;
2761
2762   if (_mesa_is_texture_complete(tObj, &tObj->Sampler)) {
2763      /* The texture is complete and we know exactly how many mipmap levels
2764       * are present/needed.  This is conditional because we may be called
2765       * from the st_generate_mipmap() function when the texture object is
2766       * incomplete.  In that case, we'll have set stObj->lastLevel before
2767       * we get here.
2768       */
2769      if (stObj->base.Sampler.MinFilter == GL_LINEAR ||
2770          stObj->base.Sampler.MinFilter == GL_NEAREST)
2771         stObj->lastLevel = stObj->base.BaseLevel;
2772      else
2773         stObj->lastLevel = stObj->base._MaxLevel;
2774   }
2775
2776   if (tObj->Target == GL_TEXTURE_BUFFER) {
2777      struct st_buffer_object *st_obj = st_buffer_object(tObj->BufferObject);
2778
2779      if (!st_obj) {
2780         pipe_resource_reference(&stObj->pt, NULL);
2781         st_texture_release_all_sampler_views(st, stObj);
2782         return GL_TRUE;
2783      }
2784
2785      if (st_obj->buffer != stObj->pt) {
2786         pipe_resource_reference(&stObj->pt, st_obj->buffer);
2787         st_texture_release_all_sampler_views(st, stObj);
2788         stObj->width0 = stObj->pt->width0 / _mesa_get_format_bytes(tObj->_BufferObjectFormat);
2789         stObj->height0 = 1;
2790         stObj->depth0 = 1;
2791      }
2792      return GL_TRUE;
2793
2794   }
2795
2796   firstImage = st_texture_image_const(_mesa_base_tex_image(&stObj->base));
2797   assert(firstImage);
2798
2799   /* If both firstImage and stObj point to a texture which can contain
2800    * all active images, favour firstImage.  Note that because of the
2801    * completeness requirement, we know that the image dimensions
2802    * will match.
2803    */
2804   if (firstImage->pt &&
2805       firstImage->pt != stObj->pt &&
2806       (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
2807      pipe_resource_reference(&stObj->pt, firstImage->pt);
2808      st_texture_release_all_sampler_views(st, stObj);
2809   }
2810
2811   /* If this texture comes from a window system, there is nothing else to do. */
2812   if (stObj->surface_based) {
2813      return GL_TRUE;
2814   }
2815
2816   /* Find gallium format for the Mesa texture */
2817   firstImageFormat =
2818      st_mesa_format_to_pipe_format(st, firstImage->base.TexFormat);
2819
2820   /* Find size of level=0 Gallium mipmap image, plus number of texture layers */
2821   {
2822      GLuint width, height, depth;
2823      if (!guess_base_level_size(stObj->base.Target,
2824                                 firstImage->base.Width2,
2825                                 firstImage->base.Height2,
2826                                 firstImage->base.Depth2,
2827                                 firstImage->base.Level,
2828                                 &width, &height, &depth)) {
2829         width = stObj->width0;
2830         height = stObj->height0;
2831         depth = stObj->depth0;
2832      } else {
2833         /* The width/height/depth may have been previously reset in
2834          * guess_and_alloc_texture. */
2835         stObj->width0 = width;
2836         stObj->height0 = height;
2837         stObj->depth0 = depth;
2838      }
2839      /* convert GL dims to Gallium dims */
2840      st_gl_texture_dims_to_pipe_dims(stObj->base.Target, width, height, depth,
2841                                      &ptWidth, &ptHeight, &ptDepth, &ptLayers);
2842      ptNumSamples = firstImage->base.NumSamples;
2843   }
2844
2845   /* If we already have a gallium texture, check that it matches the texture
2846    * object's format, target, size, num_levels, etc.
2847    */
2848   if (stObj->pt) {
2849      if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
2850          stObj->pt->format != firstImageFormat ||
2851          stObj->pt->last_level < stObj->lastLevel ||
2852          stObj->pt->width0 != ptWidth ||
2853          stObj->pt->height0 != ptHeight ||
2854          stObj->pt->depth0 != ptDepth ||
2855          stObj->pt->nr_samples != ptNumSamples ||
2856          stObj->pt->array_size != ptLayers)
2857      {
2858         /* The gallium texture does not match the Mesa texture so delete the
2859          * gallium texture now.  We'll make a new one below.
2860          */
2861         pipe_resource_reference(&stObj->pt, NULL);
2862         st_texture_release_all_sampler_views(st, stObj);
2863         st->dirty.st |= ST_NEW_FRAMEBUFFER;
2864      }
2865   }
2866
2867   /* May need to create a new gallium texture:
2868    */
2869   if (!stObj->pt) {
2870      GLuint bindings = default_bindings(st, firstImageFormat);
2871
2872      stObj->pt = st_texture_create(st,
2873                                    gl_target_to_pipe(stObj->base.Target),
2874                                    firstImageFormat,
2875                                    stObj->lastLevel,
2876                                    ptWidth,
2877                                    ptHeight,
2878                                    ptDepth,
2879                                    ptLayers, ptNumSamples,
2880                                    bindings);
2881
2882      if (!stObj->pt) {
2883         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
2884         return GL_FALSE;
2885      }
2886   }
2887
2888   /* Pull in any images not in the object's texture:
2889    */
2890   for (face = 0; face < nr_faces; face++) {
2891      GLuint level;
2892      for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
2893         struct st_texture_image *stImage =
2894            st_texture_image(stObj->base.Image[face][level]);
2895
2896         /* Need to import images in main memory or held in other textures.
2897          */
2898         if (stImage && stObj->pt != stImage->pt) {
2899            if (level == 0 ||
2900                (stImage->base.Width == u_minify(stObj->width0, level) &&
2901                 stImage->base.Height == u_minify(stObj->height0, level) &&
2902                 stImage->base.Depth == u_minify(stObj->depth0, level))) {
2903               /* src image fits expected dest mipmap level size */
2904               copy_image_data_to_texture(st, stObj, level, stImage);
2905            }
2906         }
2907      }
2908   }
2909
2910   return GL_TRUE;
2911}
2912
2913
2914/**
2915 * Called via ctx->Driver.AllocTextureStorage() to allocate texture memory
2916 * for a whole mipmap stack.
2917 */
2918static GLboolean
2919st_AllocTextureStorage(struct gl_context *ctx,
2920                       struct gl_texture_object *texObj,
2921                       GLsizei levels, GLsizei width,
2922                       GLsizei height, GLsizei depth)
2923{
2924   const GLuint numFaces = _mesa_num_tex_faces(texObj->Target);
2925   struct gl_texture_image *texImage = texObj->Image[0][0];
2926   struct st_context *st = st_context(ctx);
2927   struct st_texture_object *stObj = st_texture_object(texObj);
2928   struct pipe_screen *screen = st->pipe->screen;
2929   GLuint ptWidth, ptHeight, ptDepth, ptLayers, bindings;
2930   enum pipe_format fmt;
2931   GLint level;
2932   GLuint num_samples = texImage->NumSamples;
2933
2934   assert(levels > 0);
2935
2936   /* Save the level=0 dimensions */
2937   stObj->width0 = width;
2938   stObj->height0 = height;
2939   stObj->depth0 = depth;
2940   stObj->lastLevel = levels - 1;
2941
2942   fmt = st_mesa_format_to_pipe_format(st, texImage->TexFormat);
2943
2944   bindings = default_bindings(st, fmt);
2945
2946   /* Raise the sample count if the requested one is unsupported. */
2947   if (num_samples > 1) {
2948      boolean found = FALSE;
2949
2950      for (; num_samples <= ctx->Const.MaxSamples; num_samples++) {
2951         if (screen->is_format_supported(screen, fmt, PIPE_TEXTURE_2D,
2952                                         num_samples,
2953                                         PIPE_BIND_SAMPLER_VIEW)) {
2954            /* Update the sample count in gl_texture_image as well. */
2955            texImage->NumSamples = num_samples;
2956            found = TRUE;
2957            break;
2958         }
2959      }
2960
2961      if (!found) {
2962         return GL_FALSE;
2963      }
2964   }
2965
2966   st_gl_texture_dims_to_pipe_dims(texObj->Target,
2967                                   width, height, depth,
2968                                   &ptWidth, &ptHeight, &ptDepth, &ptLayers);
2969
2970   stObj->pt = st_texture_create(st,
2971                                 gl_target_to_pipe(texObj->Target),
2972                                 fmt,
2973                                 levels - 1,
2974                                 ptWidth,
2975                                 ptHeight,
2976                                 ptDepth,
2977                                 ptLayers, num_samples,
2978                                 bindings);
2979   if (!stObj->pt)
2980      return GL_FALSE;
2981
2982   /* Set image resource pointers */
2983   for (level = 0; level < levels; level++) {
2984      GLuint face;
2985      for (face = 0; face < numFaces; face++) {
2986         struct st_texture_image *stImage =
2987            st_texture_image(texObj->Image[face][level]);
2988         pipe_resource_reference(&stImage->pt, stObj->pt);
2989      }
2990   }
2991
2992   return GL_TRUE;
2993}
2994
2995
2996static GLboolean
2997st_TestProxyTexImage(struct gl_context *ctx, GLenum target,
2998                     GLint level, mesa_format format,
2999                     GLint width, GLint height,
3000                     GLint depth, GLint border)
3001{
3002   struct st_context *st = st_context(ctx);
3003   struct pipe_context *pipe = st->pipe;
3004
3005   if (width == 0 || height == 0 || depth == 0) {
3006      /* zero-sized images are legal, and always fit! */
3007      return GL_TRUE;
3008   }
3009
3010   if (pipe->screen->can_create_resource) {
3011      /* Ask the gallium driver if the texture is too large */
3012      struct gl_texture_object *texObj =
3013         _mesa_get_current_tex_object(ctx, target);
3014      struct pipe_resource pt;
3015
3016      /* Setup the pipe_resource object
3017       */
3018      memset(&pt, 0, sizeof(pt));
3019
3020      pt.target = gl_target_to_pipe(target);
3021      pt.format = st_mesa_format_to_pipe_format(st, format);
3022
3023      st_gl_texture_dims_to_pipe_dims(target,
3024                                      width, height, depth,
3025                                      &pt.width0, &pt.height0,
3026                                      &pt.depth0, &pt.array_size);
3027
3028      if (level == 0 && (texObj->Sampler.MinFilter == GL_LINEAR ||
3029                         texObj->Sampler.MinFilter == GL_NEAREST)) {
3030         /* assume just one mipmap level */
3031         pt.last_level = 0;
3032      }
3033      else {
3034         /* assume a full set of mipmaps */
3035         pt.last_level = _mesa_logbase2(MAX3(width, height, depth));
3036      }
3037
3038      return pipe->screen->can_create_resource(pipe->screen, &pt);
3039   }
3040   else {
3041      /* Use core Mesa fallback */
3042      return _mesa_test_proxy_teximage(ctx, target, level, format,
3043                                       width, height, depth, border);
3044   }
3045}
3046
3047static GLboolean
3048st_TextureView(struct gl_context *ctx,
3049               struct gl_texture_object *texObj,
3050               struct gl_texture_object *origTexObj)
3051{
3052   struct st_texture_object *orig = st_texture_object(origTexObj);
3053   struct st_texture_object *tex = st_texture_object(texObj);
3054   struct gl_texture_image *image = texObj->Image[0][0];
3055
3056   const int numFaces = _mesa_num_tex_faces(texObj->Target);
3057   const int numLevels = texObj->NumLevels;
3058
3059   int face;
3060   int level;
3061
3062   pipe_resource_reference(&tex->pt, orig->pt);
3063
3064   /* Set image resource pointers */
3065   for (level = 0; level < numLevels; level++) {
3066      for (face = 0; face < numFaces; face++) {
3067         struct st_texture_image *stImage =
3068            st_texture_image(texObj->Image[face][level]);
3069         pipe_resource_reference(&stImage->pt, tex->pt);
3070      }
3071   }
3072
3073   tex->surface_based = GL_TRUE;
3074   tex->surface_format =
3075      st_mesa_format_to_pipe_format(st_context(ctx), image->TexFormat);
3076
3077   tex->width0 = image->Width;
3078   tex->height0 = image->Height;
3079   tex->depth0 = image->Depth;
3080   tex->lastLevel = numLevels - 1;
3081
3082   return GL_TRUE;
3083}
3084
3085static void
3086st_ClearTexSubImage(struct gl_context *ctx,
3087                    struct gl_texture_image *texImage,
3088                    GLint xoffset, GLint yoffset, GLint zoffset,
3089                    GLsizei width, GLsizei height, GLsizei depth,
3090                    const GLvoid *clearValue)
3091{
3092   static const char zeros[16] = {0};
3093   struct st_texture_image *stImage = st_texture_image(texImage);
3094   struct pipe_resource *pt = stImage->pt;
3095   struct st_context *st = st_context(ctx);
3096   struct pipe_context *pipe = st->pipe;
3097   unsigned level = texImage->Level;
3098   struct pipe_box box;
3099
3100   if (!pt)
3101      return;
3102
3103   u_box_3d(xoffset, yoffset, zoffset + texImage->Face,
3104            width, height, depth, &box);
3105   if (texImage->TexObject->Immutable) {
3106      level += texImage->TexObject->MinLevel;
3107      box.z += texImage->TexObject->MinLayer;
3108   }
3109
3110   pipe->clear_texture(pipe, pt, level, &box, clearValue ? clearValue : zeros);
3111}
3112
3113void
3114st_init_texture_functions(struct dd_function_table *functions)
3115{
3116   functions->ChooseTextureFormat = st_ChooseTextureFormat;
3117   functions->QuerySamplesForFormat = st_QuerySamplesForFormat;
3118   functions->TexImage = st_TexImage;
3119   functions->TexSubImage = st_TexSubImage;
3120   functions->CompressedTexSubImage = st_CompressedTexSubImage;
3121   functions->CopyTexSubImage = st_CopyTexSubImage;
3122   functions->GenerateMipmap = st_generate_mipmap;
3123
3124   functions->GetTexSubImage = st_GetTexSubImage;
3125
3126   /* compressed texture functions */
3127   functions->CompressedTexImage = st_CompressedTexImage;
3128   functions->GetCompressedTexSubImage = _mesa_GetCompressedTexSubImage_sw;
3129
3130   functions->NewTextureObject = st_NewTextureObject;
3131   functions->NewTextureImage = st_NewTextureImage;
3132   functions->DeleteTextureImage = st_DeleteTextureImage;
3133   functions->DeleteTexture = st_DeleteTextureObject;
3134   functions->AllocTextureImageBuffer = st_AllocTextureImageBuffer;
3135   functions->FreeTextureImageBuffer = st_FreeTextureImageBuffer;
3136   functions->MapTextureImage = st_MapTextureImage;
3137   functions->UnmapTextureImage = st_UnmapTextureImage;
3138
3139   /* XXX Temporary until we can query pipe's texture sizes */
3140   functions->TestProxyTexImage = st_TestProxyTexImage;
3141
3142   functions->AllocTextureStorage = st_AllocTextureStorage;
3143   functions->TextureView = st_TextureView;
3144   functions->ClearTexSubImage = st_ClearTexSubImage;
3145}
3146