st_cb_texture.c revision 56b57aa360a8bad0c4b68fbdf7c64ac33f9e7661
1/**************************************************************************
2 *
3 * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include "main/mfeatures.h"
29#include "main/bufferobj.h"
30#include "main/enums.h"
31#include "main/fbobject.h"
32#include "main/formats.h"
33#include "main/image.h"
34#include "main/imports.h"
35#include "main/macros.h"
36#include "main/mipmap.h"
37#include "main/pack.h"
38#include "main/pbo.h"
39#include "main/pixeltransfer.h"
40#include "main/texcompress.h"
41#include "main/texgetimage.h"
42#include "main/teximage.h"
43#include "main/texobj.h"
44#include "main/texstore.h"
45
46#include "state_tracker/st_debug.h"
47#include "state_tracker/st_context.h"
48#include "state_tracker/st_cb_fbo.h"
49#include "state_tracker/st_cb_flush.h"
50#include "state_tracker/st_cb_texture.h"
51#include "state_tracker/st_format.h"
52#include "state_tracker/st_texture.h"
53#include "state_tracker/st_gen_mipmap.h"
54#include "state_tracker/st_atom.h"
55
56#include "pipe/p_context.h"
57#include "pipe/p_defines.h"
58#include "util/u_inlines.h"
59#include "pipe/p_shader_tokens.h"
60#include "util/u_tile.h"
61#include "util/u_blit.h"
62#include "util/u_format.h"
63#include "util/u_surface.h"
64#include "util/u_sampler.h"
65#include "util/u_math.h"
66#include "util/u_box.h"
67
68#define DBG if (0) printf
69
70
71static enum pipe_texture_target
72gl_target_to_pipe(GLenum target)
73{
74   switch (target) {
75   case GL_TEXTURE_1D:
76      return PIPE_TEXTURE_1D;
77   case GL_TEXTURE_2D:
78   case GL_TEXTURE_EXTERNAL_OES:
79      return PIPE_TEXTURE_2D;
80   case GL_TEXTURE_RECTANGLE_NV:
81      return PIPE_TEXTURE_RECT;
82   case GL_TEXTURE_3D:
83      return PIPE_TEXTURE_3D;
84   case GL_TEXTURE_CUBE_MAP_ARB:
85      return PIPE_TEXTURE_CUBE;
86   case GL_TEXTURE_1D_ARRAY_EXT:
87      return PIPE_TEXTURE_1D_ARRAY;
88   case GL_TEXTURE_2D_ARRAY_EXT:
89      return PIPE_TEXTURE_2D_ARRAY;
90   case GL_TEXTURE_BUFFER:
91      return PIPE_BUFFER;
92   default:
93      assert(0);
94      return 0;
95   }
96}
97
98
99/** called via ctx->Driver.NewTextureImage() */
100static struct gl_texture_image *
101st_NewTextureImage(struct gl_context * ctx)
102{
103   DBG("%s\n", __FUNCTION__);
104   (void) ctx;
105   return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
106}
107
108
109/** called via ctx->Driver.DeleteTextureImage() */
110static void
111st_DeleteTextureImage(struct gl_context * ctx, struct gl_texture_image *img)
112{
113   /* nothing special (yet) for st_texture_image */
114   _mesa_delete_texture_image(ctx, img);
115}
116
117
118/** called via ctx->Driver.NewTextureObject() */
119static struct gl_texture_object *
120st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
121{
122   struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
123
124   DBG("%s\n", __FUNCTION__);
125   _mesa_initialize_texture_object(&obj->base, name, target);
126
127   return &obj->base;
128}
129
130/** called via ctx->Driver.DeleteTextureObject() */
131static void
132st_DeleteTextureObject(struct gl_context *ctx,
133                       struct gl_texture_object *texObj)
134{
135   struct st_context *st = st_context(ctx);
136   struct st_texture_object *stObj = st_texture_object(texObj);
137   if (stObj->pt)
138      pipe_resource_reference(&stObj->pt, NULL);
139   if (stObj->sampler_view) {
140      if (stObj->sampler_view->context != st->pipe) {
141         /* Take "ownership" of this texture sampler view by setting
142          * its context pointer to this context.  This avoids potential
143          * crashes when the texture object is shared among contexts
144          * and the original/owner context has already been destroyed.
145          */
146         stObj->sampler_view->context = st->pipe;
147      }
148      pipe_sampler_view_reference(&stObj->sampler_view, NULL);
149   }
150   _mesa_delete_texture_object(ctx, texObj);
151}
152
153
154/** called via ctx->Driver.FreeTextureImageBuffer() */
155static void
156st_FreeTextureImageBuffer(struct gl_context *ctx,
157                          struct gl_texture_image *texImage)
158{
159   struct st_texture_image *stImage = st_texture_image(texImage);
160
161   DBG("%s\n", __FUNCTION__);
162
163   if (stImage->pt) {
164      pipe_resource_reference(&stImage->pt, NULL);
165   }
166
167   if (stImage->TexData) {
168      _mesa_align_free(stImage->TexData);
169      stImage->TexData = NULL;
170   }
171}
172
173
174/** called via ctx->Driver.MapTextureImage() */
175static void
176st_MapTextureImage(struct gl_context *ctx,
177                   struct gl_texture_image *texImage,
178                   GLuint slice, GLuint x, GLuint y, GLuint w, GLuint h,
179                   GLbitfield mode,
180                   GLubyte **mapOut, GLint *rowStrideOut)
181{
182   struct st_context *st = st_context(ctx);
183   struct st_texture_image *stImage = st_texture_image(texImage);
184   unsigned pipeMode;
185   GLubyte *map;
186
187   pipeMode = 0x0;
188   if (mode & GL_MAP_READ_BIT)
189      pipeMode |= PIPE_TRANSFER_READ;
190   if (mode & GL_MAP_WRITE_BIT)
191      pipeMode |= PIPE_TRANSFER_WRITE;
192
193   map = st_texture_image_map(st, stImage, slice, pipeMode, x, y, w, h);
194   if (map) {
195      *mapOut = map;
196      *rowStrideOut = stImage->transfer->stride;
197   }
198   else {
199      *mapOut = NULL;
200      *rowStrideOut = 0;
201   }
202}
203
204
205/** called via ctx->Driver.UnmapTextureImage() */
206static void
207st_UnmapTextureImage(struct gl_context *ctx,
208                     struct gl_texture_image *texImage,
209                     GLuint slice)
210{
211   struct st_context *st = st_context(ctx);
212   struct st_texture_image *stImage  = st_texture_image(texImage);
213   st_texture_image_unmap(st, stImage);
214}
215
216
217/**
218 * Return default texture resource binding bitmask for the given format.
219 */
220static GLuint
221default_bindings(struct st_context *st, enum pipe_format format)
222{
223   struct pipe_screen *screen = st->pipe->screen;
224   const unsigned target = PIPE_TEXTURE_2D;
225   unsigned bindings;
226
227   if (util_format_is_depth_or_stencil(format))
228      bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
229   else
230      bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
231
232   if (screen->is_format_supported(screen, format, target, 0, bindings))
233      return bindings;
234   else {
235      /* Try non-sRGB. */
236      format = util_format_linear(format);
237
238      if (screen->is_format_supported(screen, format, target, 0, bindings))
239         return bindings;
240      else
241         return PIPE_BIND_SAMPLER_VIEW;
242   }
243}
244
245
246/** Return number of image dimensions (1, 2 or 3) for a texture target. */
247static GLuint
248get_texture_dims(GLenum target)
249{
250   switch (target) {
251   case GL_TEXTURE_1D:
252   case GL_TEXTURE_1D_ARRAY_EXT:
253   case GL_TEXTURE_BUFFER:
254      return 1;
255   case GL_TEXTURE_2D:
256   case GL_TEXTURE_CUBE_MAP_ARB:
257   case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB:
258   case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB:
259   case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB:
260   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB:
261   case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB:
262   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB:
263   case GL_TEXTURE_RECTANGLE_NV:
264   case GL_TEXTURE_2D_ARRAY_EXT:
265   case GL_TEXTURE_EXTERNAL_OES:
266      return 2;
267   case GL_TEXTURE_3D:
268      return 3;
269   default:
270      assert(0 && "invalid texture target in get_texture_dims()");
271      return 1;
272   }
273}
274
275
276/**
277 * Given the size of a mipmap image, try to compute the size of the level=0
278 * mipmap image.
279 *
280 * Note that this isn't always accurate for odd-sized, non-POW textures.
281 * For example, if level=1 and width=40 then the level=0 width may be 80 or 81.
282 *
283 * \return GL_TRUE for success, GL_FALSE for failure
284 */
285static GLboolean
286guess_base_level_size(GLenum target,
287                      GLuint width, GLuint height, GLuint depth, GLuint level,
288                      GLuint *width0, GLuint *height0, GLuint *depth0)
289{
290   const GLuint dims = get_texture_dims(target);
291
292   assert(width >= 1);
293   assert(height >= 1);
294   assert(depth >= 1);
295
296   if (level > 0) {
297      /* Depending on the image's size, we can't always make a guess here */
298      if ((dims >= 1 && width == 1) ||
299          (dims >= 2 && height == 1) ||
300          (dims >= 3 && depth == 1)) {
301         /* we can't determine the image size at level=0 */
302         return GL_FALSE;
303      }
304
305      /* grow the image size until we hit level = 0 */
306      while (level > 0) {
307         if (width > 1)
308            width <<= 1;
309         if (height > 1)
310            height <<= 1;
311         if (depth > 1)
312            depth <<= 1;
313         level--;
314      }
315   }
316
317   *width0 = width;
318   *height0 = height;
319   *depth0 = depth;
320
321   return GL_TRUE;
322}
323
324
325/**
326 * Try to allocate a pipe_resource object for the given st_texture_object.
327 *
328 * We use the given st_texture_image as a clue to determine the size of the
329 * mipmap image at level=0.
330 *
331 * \return GL_TRUE for success, GL_FALSE if out of memory.
332 */
333static GLboolean
334guess_and_alloc_texture(struct st_context *st,
335			struct st_texture_object *stObj,
336			const struct st_texture_image *stImage)
337{
338   GLuint lastLevel, width, height, depth;
339   GLuint bindings;
340   GLuint ptWidth, ptHeight, ptDepth, ptLayers;
341   enum pipe_format fmt;
342
343   DBG("%s\n", __FUNCTION__);
344
345   assert(!stObj->pt);
346
347   if (!guess_base_level_size(stObj->base.Target,
348                              stImage->base.Width2,
349                              stImage->base.Height2,
350                              stImage->base.Depth2,
351                              stImage->base.Level,
352                              &width, &height, &depth)) {
353      /* we can't determine the image size at level=0 */
354      stObj->width0 = stObj->height0 = stObj->depth0 = 0;
355      /* this is not an out of memory error */
356      return GL_TRUE;
357   }
358
359   /* At this point, (width x height x depth) is the expected size of
360    * the level=0 mipmap image.
361    */
362
363   /* Guess a reasonable value for lastLevel.  With OpenGL we have no
364    * idea how many mipmap levels will be in a texture until we start
365    * to render with it.  Make an educated guess here but be prepared
366    * to re-allocating a texture buffer with space for more (or fewer)
367    * mipmap levels later.
368    */
369   if ((stObj->base.Sampler.MinFilter == GL_NEAREST ||
370        stObj->base.Sampler.MinFilter == GL_LINEAR ||
371        stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
372        stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
373       !stObj->base.GenerateMipmap &&
374       stImage->base.Level == 0) {
375      /* only alloc space for a single mipmap level */
376      lastLevel = 0;
377   }
378   else {
379      /* alloc space for a full mipmap */
380      GLuint l2width = util_logbase2(width);
381      GLuint l2height = util_logbase2(height);
382      GLuint l2depth = util_logbase2(depth);
383      lastLevel = MAX2(MAX2(l2width, l2height), l2depth);
384   }
385
386   /* Save the level=0 dimensions */
387   stObj->width0 = width;
388   stObj->height0 = height;
389   stObj->depth0 = depth;
390
391   fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
392
393   bindings = default_bindings(st, fmt);
394
395   st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
396                                   width, height, depth,
397                                   &ptWidth, &ptHeight, &ptDepth, &ptLayers);
398
399   stObj->pt = st_texture_create(st,
400                                 gl_target_to_pipe(stObj->base.Target),
401                                 fmt,
402                                 lastLevel,
403                                 ptWidth,
404                                 ptHeight,
405                                 ptDepth,
406                                 ptLayers,
407                                 bindings);
408
409   DBG("%s returning %d\n", __FUNCTION__, (stObj->pt != NULL));
410
411   return stObj->pt != NULL;
412}
413
414
415/**
416 * Called via ctx->Driver.AllocTextureImageBuffer().
417 * If the texture object/buffer already has space for the indicated image,
418 * we're done.  Otherwise, allocate memory for the new texture image.
419 */
420static GLboolean
421st_AllocTextureImageBuffer(struct gl_context *ctx,
422                           struct gl_texture_image *texImage,
423                           gl_format format, GLsizei width,
424                           GLsizei height, GLsizei depth)
425{
426   struct st_context *st = st_context(ctx);
427   struct st_texture_image *stImage = st_texture_image(texImage);
428   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
429   const GLuint level = texImage->Level;
430
431   DBG("%s\n", __FUNCTION__);
432
433   assert(width > 0);
434   assert(height > 0);
435   assert(depth > 0);
436   assert(!stImage->TexData);
437   assert(!stImage->pt); /* xxx this might be wrong */
438
439   /* Look if the parent texture object has space for this image */
440   if (stObj->pt &&
441       level <= stObj->pt->last_level &&
442       st_texture_match_image(stObj->pt, texImage)) {
443      /* this image will fit in the existing texture object's memory */
444      pipe_resource_reference(&stImage->pt, stObj->pt);
445      return GL_TRUE;
446   }
447
448   /* The parent texture object does not have space for this image */
449
450   pipe_resource_reference(&stObj->pt, NULL);
451   pipe_sampler_view_reference(&stObj->sampler_view, NULL);
452
453   if (!guess_and_alloc_texture(st, stObj, stImage)) {
454      /* Probably out of memory.
455       * Try flushing any pending rendering, then retry.
456       */
457      st_finish(st);
458      if (!guess_and_alloc_texture(st, stObj, stImage)) {
459         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
460         return GL_FALSE;
461      }
462   }
463
464   if (stObj->pt &&
465       st_texture_match_image(stObj->pt, texImage)) {
466      /* The image will live in the object's mipmap memory */
467      pipe_resource_reference(&stImage->pt, stObj->pt);
468      assert(stImage->pt);
469      return GL_TRUE;
470   }
471   else {
472      /* Create a new, temporary texture/resource/buffer to hold this
473       * one texture image.  Note that when we later access this image
474       * (either for mapping or copying) we'll want to always specify
475       * mipmap level=0, even if the image represents some other mipmap
476       * level.
477       */
478      enum pipe_format format =
479         st_mesa_format_to_pipe_format(texImage->TexFormat);
480      GLuint bindings = default_bindings(st, format);
481      GLuint ptWidth, ptHeight, ptDepth, ptLayers;
482
483      st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
484                                      width, height, depth,
485                                      &ptWidth, &ptHeight, &ptDepth, &ptLayers);
486
487      stImage->pt = st_texture_create(st,
488                                      gl_target_to_pipe(stObj->base.Target),
489                                      format,
490                                      0, /* lastLevel */
491                                      ptWidth,
492                                      ptHeight,
493                                      ptDepth,
494                                      ptLayers,
495                                      bindings);
496      return stImage->pt != NULL;
497   }
498}
499
500
501/**
502 * Preparation prior to glTexImage.  Basically check the 'surface_based'
503 * field and switch to a "normal" tex image if necessary.
504 */
505static void
506prep_teximage(struct gl_context *ctx, struct gl_texture_image *texImage,
507              GLint internalFormat,
508              GLint width, GLint height, GLint depth, GLint border,
509              GLenum format, GLenum type)
510{
511   struct gl_texture_object *texObj = texImage->TexObject;
512   struct st_texture_object *stObj = st_texture_object(texObj);
513
514   /* switch to "normal" */
515   if (stObj->surface_based) {
516      const GLenum target = texObj->Target;
517      const GLuint level = texImage->Level;
518      gl_format texFormat;
519
520      _mesa_clear_texture_object(ctx, texObj);
521      pipe_resource_reference(&stObj->pt, NULL);
522
523      /* oops, need to init this image again */
524      texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
525                                              internalFormat, format, type);
526
527      _mesa_init_teximage_fields(ctx, texImage,
528                                 width, height, depth, border,
529                                 internalFormat, texFormat);
530
531      stObj->surface_based = GL_FALSE;
532   }
533}
534
535
536static void
537st_TexImage3D(struct gl_context * ctx,
538              struct gl_texture_image *texImage,
539              GLint internalFormat,
540              GLint width, GLint height, GLint depth,
541              GLint border,
542              GLenum format, GLenum type, const void *pixels,
543              const struct gl_pixelstore_attrib *unpack)
544{
545   prep_teximage(ctx, texImage, internalFormat, width, height, depth, border,
546                 format, type);
547   _mesa_store_teximage3d(ctx, texImage, internalFormat, width, height, depth,
548                          border, format, type, pixels, unpack);
549}
550
551
552static void
553st_TexImage2D(struct gl_context * ctx,
554              struct gl_texture_image *texImage,
555              GLint internalFormat,
556              GLint width, GLint height, GLint border,
557              GLenum format, GLenum type, const void *pixels,
558              const struct gl_pixelstore_attrib *unpack)
559{
560   prep_teximage(ctx, texImage, internalFormat, width, height, 1, border,
561                 format, type);
562   _mesa_store_teximage2d(ctx, texImage, internalFormat, width, height,
563                          border, format, type, pixels, unpack);
564}
565
566
567static void
568st_TexImage1D(struct gl_context * ctx,
569              struct gl_texture_image *texImage,
570              GLint internalFormat,
571              GLint width, GLint border,
572              GLenum format, GLenum type, const void *pixels,
573              const struct gl_pixelstore_attrib *unpack)
574{
575   prep_teximage(ctx, texImage, internalFormat, width, 1, 1, border,
576                 format, type);
577   _mesa_store_teximage1d(ctx, texImage, internalFormat, width,
578                          border, format, type, pixels, unpack);
579}
580
581
582static void
583st_CompressedTexImage2D(struct gl_context *ctx,
584                        struct gl_texture_image *texImage,
585                        GLint internalFormat,
586                        GLint width, GLint height, GLint border,
587                        GLsizei imageSize, const GLvoid *data)
588{
589   prep_teximage(ctx, texImage, internalFormat, width, 1, 1, border,
590                 GL_NONE, GL_NONE);
591   _mesa_store_compressed_teximage2d(ctx, texImage, internalFormat, width,
592                                     height, border, imageSize, data);
593}
594
595
596
597/**
598 * glGetTexImage() helper: decompress a compressed texture by rendering
599 * a textured quad.  Store the results in the user's buffer.
600 */
601static void
602decompress_with_blit(struct gl_context * ctx,
603                     GLenum format, GLenum type, GLvoid *pixels,
604                     struct gl_texture_image *texImage)
605{
606   struct st_context *st = st_context(ctx);
607   struct pipe_context *pipe = st->pipe;
608   struct st_texture_image *stImage = st_texture_image(texImage);
609   struct st_texture_object *stObj = st_texture_object(texImage->TexObject);
610   struct pipe_sampler_view *src_view =
611      st_get_texture_sampler_view(stObj, pipe);
612   const GLuint width = texImage->Width;
613   const GLuint height = texImage->Height;
614   struct pipe_surface *dst_surface;
615   struct pipe_resource *dst_texture;
616   struct pipe_transfer *tex_xfer;
617   unsigned bind = (PIPE_BIND_RENDER_TARGET | /* util_blit may choose to render */
618		    PIPE_BIND_TRANSFER_READ);
619
620   /* create temp / dest surface */
621   if (!util_create_rgba_surface(pipe, width, height, bind,
622                                 &dst_texture, &dst_surface)) {
623      _mesa_problem(ctx, "util_create_rgba_surface() failed "
624                    "in decompress_with_blit()");
625      return;
626   }
627
628   /* Disable conditional rendering. */
629   if (st->render_condition) {
630      pipe->render_condition(pipe, NULL, 0);
631   }
632
633   /* Choose the source mipmap level */
634   src_view->u.tex.first_level = src_view->u.tex.last_level = texImage->Level;
635
636   /* blit/render/decompress */
637   util_blit_pixels_tex(st->blit,
638                        src_view,      /* pipe_resource (src) */
639                        0, 0,             /* src x0, y0 */
640                        width, height,    /* src x1, y1 */
641                        dst_surface,      /* pipe_surface (dst) */
642                        0, 0,             /* dst x0, y0 */
643                        width, height,    /* dst x1, y1 */
644                        0.0,              /* z */
645                        PIPE_TEX_MIPFILTER_NEAREST);
646
647   /* Restore conditional rendering state. */
648   if (st->render_condition) {
649      pipe->render_condition(pipe, st->render_condition,
650                             st->condition_mode);
651   }
652
653   /* map the dst_surface so we can read from it */
654   tex_xfer = pipe_get_transfer(pipe,
655                                dst_texture, 0, 0,
656                                PIPE_TRANSFER_READ,
657                                0, 0, width, height);
658
659   pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
660
661   /* copy/pack data into user buffer */
662   if (st_equal_formats(stImage->pt->format, format, type)) {
663      /* memcpy */
664      const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
665      ubyte *map = pipe_transfer_map(pipe, tex_xfer);
666      GLuint row;
667      for (row = 0; row < height; row++) {
668         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
669                                              height, format, type, row, 0);
670         memcpy(dest, map, bytesPerRow);
671         map += tex_xfer->stride;
672      }
673      pipe_transfer_unmap(pipe, tex_xfer);
674   }
675   else {
676      /* format translation via floats */
677      GLuint row;
678      enum pipe_format pformat = util_format_linear(dst_texture->format);
679      for (row = 0; row < height; row++) {
680         const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
681         GLfloat rgba[4 * MAX_WIDTH];
682         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
683                                              height, format, type, row, 0);
684
685         if (ST_DEBUG & DEBUG_FALLBACK)
686            debug_printf("%s: fallback format translation\n", __FUNCTION__);
687
688         /* get float[4] rgba row from surface */
689         pipe_get_tile_rgba_format(pipe, tex_xfer, 0, row, width, 1,
690                                   pformat, rgba);
691
692         _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
693                                    type, dest, &ctx->Pack, transferOps);
694      }
695   }
696
697   _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
698
699   pipe->transfer_destroy(pipe, tex_xfer);
700
701   /* destroy the temp / dest surface */
702   util_destroy_rgba_surface(dst_texture, dst_surface);
703}
704
705
706
707/**
708 * Called via ctx->Driver.GetTexImage()
709 */
710static void
711st_GetTexImage(struct gl_context * ctx,
712               GLenum format, GLenum type, GLvoid * pixels,
713               struct gl_texture_image *texImage)
714{
715   struct st_texture_image *stImage = st_texture_image(texImage);
716
717   if (stImage->pt && util_format_is_s3tc(stImage->pt->format)) {
718      /* Need to decompress the texture.
719       * We'll do this by rendering a textured quad (which is hopefully
720       * faster than using the fallback code in texcompress.c).
721       * Note that we only expect RGBA formats (no Z/depth formats).
722       */
723      decompress_with_blit(ctx, format, type, pixels, texImage);
724   }
725   else {
726      _mesa_get_teximage(ctx, format, type, pixels, texImage);
727   }
728}
729
730
731/**
732 * Do a CopyTexSubImage operation using a read transfer from the source,
733 * a write transfer to the destination and get_tile()/put_tile() to access
734 * the pixels/texels.
735 *
736 * Note: srcY=0=TOP of renderbuffer
737 */
738static void
739fallback_copy_texsubimage(struct gl_context *ctx,
740                          struct st_renderbuffer *strb,
741                          struct st_texture_image *stImage,
742                          GLenum baseFormat,
743                          GLint destX, GLint destY, GLint destZ,
744                          GLint srcX, GLint srcY,
745                          GLsizei width, GLsizei height)
746{
747   struct st_context *st = st_context(ctx);
748   struct pipe_context *pipe = st->pipe;
749   struct pipe_transfer *src_trans;
750   GLvoid *texDest;
751   enum pipe_transfer_usage transfer_usage;
752
753   if (ST_DEBUG & DEBUG_FALLBACK)
754      debug_printf("%s: fallback processing\n", __FUNCTION__);
755
756   assert(width <= MAX_WIDTH);
757
758   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
759      srcY = strb->Base.Height - srcY - height;
760   }
761
762   src_trans = pipe_get_transfer(pipe,
763                                 strb->texture,
764                                 strb->rtt_level,
765                                 strb->rtt_face + strb->rtt_slice,
766                                 PIPE_TRANSFER_READ,
767                                 srcX, srcY,
768                                 width, height);
769
770   if ((baseFormat == GL_DEPTH_COMPONENT ||
771        baseFormat == GL_DEPTH_STENCIL) &&
772       util_format_is_depth_and_stencil(stImage->pt->format))
773      transfer_usage = PIPE_TRANSFER_READ_WRITE;
774   else
775      transfer_usage = PIPE_TRANSFER_WRITE;
776
777   /* XXX this used to ignore destZ param */
778   texDest = st_texture_image_map(st, stImage, destZ, transfer_usage,
779                                  destX, destY, width, height);
780
781   if (baseFormat == GL_DEPTH_COMPONENT ||
782       baseFormat == GL_DEPTH_STENCIL) {
783      const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
784                                     ctx->Pixel.DepthBias != 0.0F);
785      GLint row, yStep;
786
787      /* determine bottom-to-top vs. top-to-bottom order for src buffer */
788      if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
789         srcY = height - 1;
790         yStep = -1;
791      }
792      else {
793         srcY = 0;
794         yStep = 1;
795      }
796
797      /* To avoid a large temp memory allocation, do copy row by row */
798      for (row = 0; row < height; row++, srcY += yStep) {
799         uint data[MAX_WIDTH];
800         pipe_get_tile_z(pipe, src_trans, 0, srcY, width, 1, data);
801         if (scaleOrBias) {
802            _mesa_scale_and_bias_depth_uint(ctx, width, data);
803         }
804         pipe_put_tile_z(pipe, stImage->transfer, 0, row, width, 1, data);
805      }
806   }
807   else {
808      /* RGBA format */
809      GLfloat *tempSrc =
810         (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
811
812      if (tempSrc && texDest) {
813         const GLint dims = 2;
814         const GLint dstRowStride = stImage->transfer->stride;
815         struct gl_texture_image *texImage = &stImage->base;
816         struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
817
818         if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
819            unpack.Invert = GL_TRUE;
820         }
821
822         /* get float/RGBA image from framebuffer */
823         /* XXX this usually involves a lot of int/float conversion.
824          * try to avoid that someday.
825          */
826         pipe_get_tile_rgba_format(pipe, src_trans, 0, 0, width, height,
827                                   util_format_linear(strb->texture->format),
828                                   tempSrc);
829
830         /* Store into texture memory.
831          * Note that this does some special things such as pixel transfer
832          * ops and format conversion.  In particular, if the dest tex format
833          * is actually RGBA but the user created the texture as GL_RGB we
834          * need to fill-in/override the alpha channel with 1.0.
835          */
836         _mesa_texstore(ctx, dims,
837                        texImage->_BaseFormat,
838                        texImage->TexFormat,
839                        dstRowStride,
840                        (GLubyte **) &texDest,
841                        width, height, 1,
842                        GL_RGBA, GL_FLOAT, tempSrc, /* src */
843                        &unpack);
844      }
845      else {
846         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
847      }
848
849      if (tempSrc)
850         free(tempSrc);
851   }
852
853   st_texture_image_unmap(st, stImage);
854   pipe->transfer_destroy(pipe, src_trans);
855}
856
857
858
859/**
860 * If the format of the src renderbuffer and the format of the dest
861 * texture are compatible (in terms of blitting), return a TGSI writemask
862 * to be used during the blit.
863 * If the src/dest are incompatible, return 0.
864 */
865static unsigned
866compatible_src_dst_formats(struct gl_context *ctx,
867                           const struct gl_renderbuffer *src,
868                           const struct gl_texture_image *dst)
869{
870   /* Get logical base formats for the src and dest.
871    * That is, use the user-requested formats and not the actual, device-
872    * chosen formats.
873    * For example, the user may have requested an A8 texture but the
874    * driver may actually be using an RGBA texture format.  When we
875    * copy/blit to that texture, we only want to copy the Alpha channel
876    * and not the RGB channels.
877    *
878    * Similarly, when the src FBO was created an RGB format may have been
879    * requested but the driver actually chose an RGBA format.  In that case,
880    * we don't want to copy the undefined Alpha channel to the dest texture
881    * (it should be 1.0).
882    */
883   const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
884   const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
885
886   /**
887    * XXX when we have red-only and red/green renderbuffers we'll need
888    * to add more cases here (or implement a general-purpose routine that
889    * queries the existance of the R,G,B,A channels in the src and dest).
890    */
891   if (srcFormat == dstFormat) {
892      /* This is the same as matching_base_formats, which should
893       * always pass, as it did previously.
894       */
895      return TGSI_WRITEMASK_XYZW;
896   }
897   else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
898      /* Make sure that A in the dest is 1.  The actual src format
899       * may be RGBA and have undefined A values.
900       */
901      return TGSI_WRITEMASK_XYZ;
902   }
903   else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
904      /* Make sure that A in the dest is 1.  The actual dst format
905       * may be RGBA and will need A=1 to provide proper alpha values
906       * when sampled later.
907       */
908      return TGSI_WRITEMASK_XYZ;
909   }
910   else {
911      if (ST_DEBUG & DEBUG_FALLBACK)
912         debug_printf("%s failed for src %s, dst %s\n",
913                      __FUNCTION__,
914                      _mesa_lookup_enum_by_nr(srcFormat),
915                      _mesa_lookup_enum_by_nr(dstFormat));
916
917      /* Otherwise fail.
918       */
919      return 0;
920   }
921}
922
923
924
925/**
926 * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
927 * Note that the region to copy has already been clipped so we know we
928 * won't read from outside the source renderbuffer's bounds.
929 *
930 * Note: srcY=0=Bottom of renderbuffer (GL convention)
931 */
932static void
933st_copy_texsubimage(struct gl_context *ctx,
934                    struct gl_texture_image *texImage,
935                    GLint destX, GLint destY, GLint destZ,
936                    struct gl_renderbuffer *rb,
937                    GLint srcX, GLint srcY,
938                    GLsizei width, GLsizei height)
939{
940   struct st_texture_image *stImage = st_texture_image(texImage);
941   const GLenum texBaseFormat = texImage->_BaseFormat;
942   struct gl_framebuffer *fb = ctx->ReadBuffer;
943   struct st_renderbuffer *strb;
944   struct st_context *st = st_context(ctx);
945   struct pipe_context *pipe = st->pipe;
946   struct pipe_screen *screen = pipe->screen;
947   enum pipe_format dest_format, src_format;
948   GLboolean matching_base_formats;
949   GLuint format_writemask, sample_count;
950   struct pipe_surface *dest_surface = NULL;
951   GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
952   struct pipe_surface surf_tmpl;
953   unsigned int dst_usage;
954   GLint srcY0, srcY1;
955
956   /* make sure finalize_textures has been called?
957    */
958   if (0) st_validate_state(st);
959
960   /* determine if copying depth or color data */
961   if (texBaseFormat == GL_DEPTH_COMPONENT ||
962       texBaseFormat == GL_DEPTH_STENCIL) {
963      strb = st_renderbuffer(fb->Attachment[BUFFER_DEPTH].Renderbuffer);
964   }
965   else {
966      /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
967      strb = st_renderbuffer(fb->_ColorReadBuffer);
968   }
969
970   if (!strb || !strb->surface || !stImage->pt) {
971      debug_printf("%s: null strb or stImage\n", __FUNCTION__);
972      return;
973   }
974
975   sample_count = strb->surface->texture->nr_samples;
976   /* I believe this would be legal, presumably would need to do a resolve
977      for color, and for depth/stencil spec says to just use one of the
978      depth/stencil samples per pixel? Need some transfer clarifications. */
979   assert(sample_count < 2);
980
981   assert(strb);
982   assert(strb->surface);
983   assert(stImage->pt);
984
985   src_format = strb->surface->format;
986   dest_format = stImage->pt->format;
987
988   /*
989    * Determine if the src framebuffer and dest texture have the same
990    * base format.  We need this to detect a case such as the framebuffer
991    * being GL_RGBA but the texture being GL_RGB.  If the actual hardware
992    * texture format stores RGBA we need to set A=1 (overriding the
993    * framebuffer's alpha values).  We can't do that with the blit or
994    * textured-quad paths.
995    */
996   matching_base_formats =
997      (_mesa_get_format_base_format(strb->Base.Format) ==
998       _mesa_get_format_base_format(texImage->TexFormat));
999
1000   if (ctx->_ImageTransferState) {
1001      goto fallback;
1002   }
1003
1004   if (matching_base_formats &&
1005       src_format == dest_format &&
1006       !do_flip) {
1007      /* use surface_copy() / blit */
1008      struct pipe_box src_box;
1009      u_box_2d_zslice(srcX, srcY, strb->surface->u.tex.first_layer,
1010                      width, height, &src_box);
1011
1012      /* for resource_copy_region(), y=0=top, always */
1013      pipe->resource_copy_region(pipe,
1014                                 /* dest */
1015                                 stImage->pt,
1016                                 stImage->base.Level,
1017                                 destX, destY, destZ + stImage->base.Face,
1018                                 /* src */
1019                                 strb->texture,
1020                                 strb->surface->u.tex.level,
1021                                 &src_box);
1022      return;
1023   }
1024
1025   if (texBaseFormat == GL_DEPTH_STENCIL) {
1026      goto fallback;
1027   }
1028
1029   if (texBaseFormat == GL_DEPTH_COMPONENT) {
1030      format_writemask = TGSI_WRITEMASK_XYZW;
1031      dst_usage = PIPE_BIND_DEPTH_STENCIL;
1032   }
1033   else {
1034      format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
1035      dst_usage = PIPE_BIND_RENDER_TARGET;
1036   }
1037
1038   if (!format_writemask ||
1039       !screen->is_format_supported(screen, src_format,
1040                                    PIPE_TEXTURE_2D, sample_count,
1041                                    PIPE_BIND_SAMPLER_VIEW) ||
1042       !screen->is_format_supported(screen, dest_format,
1043                                    PIPE_TEXTURE_2D, 0,
1044                                    dst_usage)) {
1045      goto fallback;
1046   }
1047
1048   if (do_flip) {
1049      srcY1 = strb->Base.Height - srcY - height;
1050      srcY0 = srcY1 + height;
1051   }
1052   else {
1053      srcY0 = srcY;
1054      srcY1 = srcY0 + height;
1055   }
1056
1057   /* Disable conditional rendering. */
1058   if (st->render_condition) {
1059      pipe->render_condition(pipe, NULL, 0);
1060   }
1061
1062   memset(&surf_tmpl, 0, sizeof(surf_tmpl));
1063   surf_tmpl.format = util_format_linear(stImage->pt->format);
1064   surf_tmpl.usage = dst_usage;
1065   surf_tmpl.u.tex.level = stImage->base.Level;
1066   surf_tmpl.u.tex.first_layer = stImage->base.Face + destZ;
1067   surf_tmpl.u.tex.last_layer = stImage->base.Face + destZ;
1068
1069   dest_surface = pipe->create_surface(pipe, stImage->pt,
1070                                       &surf_tmpl);
1071   util_blit_pixels_writemask(st->blit,
1072                              strb->texture,
1073                              strb->surface->u.tex.level,
1074                              srcX, srcY0,
1075                              srcX + width, srcY1,
1076                              strb->surface->u.tex.first_layer,
1077                              dest_surface,
1078                              destX, destY,
1079                              destX + width, destY + height,
1080                              0.0, PIPE_TEX_MIPFILTER_NEAREST,
1081                              format_writemask);
1082   pipe_surface_reference(&dest_surface, NULL);
1083
1084   /* Restore conditional rendering state. */
1085   if (st->render_condition) {
1086      pipe->render_condition(pipe, st->render_condition,
1087                             st->condition_mode);
1088   }
1089
1090   return;
1091
1092fallback:
1093   /* software fallback */
1094   fallback_copy_texsubimage(ctx,
1095                             strb, stImage, texBaseFormat,
1096                             destX, destY, destZ,
1097                             srcX, srcY, width, height);
1098}
1099
1100
1101
1102static void
1103st_CopyTexSubImage1D(struct gl_context *ctx,
1104                     struct gl_texture_image *texImage,
1105                     GLint xoffset,
1106                     struct gl_renderbuffer *rb,
1107                     GLint x, GLint y, GLsizei width)
1108{
1109   const GLint yoffset = 0, zoffset = 0;
1110   const GLsizei height = 1;
1111   st_copy_texsubimage(ctx, texImage,
1112                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1113                       rb, x, y, width, height);  /* src X, Y, size */
1114}
1115
1116
1117static void
1118st_CopyTexSubImage2D(struct gl_context *ctx,
1119                     struct gl_texture_image *texImage,
1120                     GLint xoffset, GLint yoffset,
1121                     struct gl_renderbuffer *rb,
1122                     GLint x, GLint y, GLsizei width, GLsizei height)
1123{
1124   const GLint zoffset = 0;
1125   st_copy_texsubimage(ctx, texImage,
1126                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1127                       rb, x, y, width, height);  /* src X, Y, size */
1128}
1129
1130
1131static void
1132st_CopyTexSubImage3D(struct gl_context *ctx,
1133                     struct gl_texture_image *texImage,
1134                     GLint xoffset, GLint yoffset, GLint zoffset,
1135                     struct gl_renderbuffer *rb,
1136                     GLint x, GLint y, GLsizei width, GLsizei height)
1137{
1138   st_copy_texsubimage(ctx, texImage,
1139                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1140                       rb, x, y, width, height);  /* src X, Y, size */
1141}
1142
1143
1144/**
1145 * Copy image data from stImage into the texture object 'stObj' at level
1146 * 'dstLevel'.
1147 */
1148static void
1149copy_image_data_to_texture(struct st_context *st,
1150			   struct st_texture_object *stObj,
1151                           GLuint dstLevel,
1152			   struct st_texture_image *stImage)
1153{
1154   /* debug checks */
1155   {
1156      const struct gl_texture_image *dstImage =
1157         stObj->base.Image[stImage->base.Face][dstLevel];
1158      assert(dstImage);
1159      assert(dstImage->Width == stImage->base.Width);
1160      assert(dstImage->Height == stImage->base.Height);
1161      assert(dstImage->Depth == stImage->base.Depth);
1162   }
1163
1164   if (stImage->pt) {
1165      /* Copy potentially with the blitter:
1166       */
1167      GLuint src_level;
1168      if (stImage->pt != stObj->pt)
1169         src_level = 0;
1170      else
1171         src_level = stImage->base.Level;
1172
1173      st_texture_image_copy(st->pipe,
1174                            stObj->pt, dstLevel,  /* dest texture, level */
1175                            stImage->pt, src_level, /* src texture, level */
1176                            stImage->base.Face);
1177
1178      pipe_resource_reference(&stImage->pt, NULL);
1179   }
1180   else if (stImage->TexData) {
1181      /* Copy from malloc'd memory */
1182      /* XXX this should be re-examined/tested with a compressed format */
1183      GLuint blockSize = util_format_get_blocksize(stObj->pt->format);
1184      GLuint srcRowStride = stImage->base.Width * blockSize;
1185      GLuint srcSliceStride = stImage->base.Height * srcRowStride;
1186      st_texture_image_data(st,
1187                            stObj->pt,
1188                            stImage->base.Face,
1189                            dstLevel,
1190                            stImage->TexData,
1191                            srcRowStride,
1192                            srcSliceStride);
1193      _mesa_align_free(stImage->TexData);
1194      stImage->TexData = NULL;
1195   }
1196
1197   pipe_resource_reference(&stImage->pt, stObj->pt);
1198}
1199
1200
1201/**
1202 * Called during state validation.  When this function is finished,
1203 * the texture object should be ready for rendering.
1204 * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
1205 */
1206GLboolean
1207st_finalize_texture(struct gl_context *ctx,
1208		    struct pipe_context *pipe,
1209		    struct gl_texture_object *tObj)
1210{
1211   struct st_context *st = st_context(ctx);
1212   struct st_texture_object *stObj = st_texture_object(tObj);
1213   const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
1214   GLuint face;
1215   struct st_texture_image *firstImage;
1216   enum pipe_format firstImageFormat;
1217   GLuint ptWidth, ptHeight, ptDepth, ptLayers;
1218
1219   if (stObj->base._Complete) {
1220      /* The texture is complete and we know exactly how many mipmap levels
1221       * are present/needed.  This is conditional because we may be called
1222       * from the st_generate_mipmap() function when the texture object is
1223       * incomplete.  In that case, we'll have set stObj->lastLevel before
1224       * we get here.
1225       */
1226      if (stObj->base.Sampler.MinFilter == GL_LINEAR ||
1227          stObj->base.Sampler.MinFilter == GL_NEAREST)
1228         stObj->lastLevel = stObj->base.BaseLevel;
1229      else
1230         stObj->lastLevel = stObj->base._MaxLevel;
1231   }
1232
1233   firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
1234   assert(firstImage);
1235
1236   /* If both firstImage and stObj point to a texture which can contain
1237    * all active images, favour firstImage.  Note that because of the
1238    * completeness requirement, we know that the image dimensions
1239    * will match.
1240    */
1241   if (firstImage->pt &&
1242       firstImage->pt != stObj->pt &&
1243       (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
1244      pipe_resource_reference(&stObj->pt, firstImage->pt);
1245      pipe_sampler_view_reference(&stObj->sampler_view, NULL);
1246   }
1247
1248   /* Find gallium format for the Mesa texture */
1249   firstImageFormat = st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
1250
1251   /* Find size of level=0 Gallium mipmap image, plus number of texture layers */
1252   {
1253      GLuint width, height, depth;
1254      if (!guess_base_level_size(stObj->base.Target,
1255                                 firstImage->base.Width2,
1256                                 firstImage->base.Height2,
1257                                 firstImage->base.Depth2,
1258                                 firstImage->base.Level,
1259                                 &width, &height, &depth)) {
1260         width = stObj->width0;
1261         height = stObj->height0;
1262         depth = stObj->depth0;
1263      }
1264      /* convert GL dims to Gallium dims */
1265      st_gl_texture_dims_to_pipe_dims(stObj->base.Target, width, height, depth,
1266                                      &ptWidth, &ptHeight, &ptDepth, &ptLayers);
1267   }
1268
1269   /* If we already have a gallium texture, check that it matches the texture
1270    * object's format, target, size, num_levels, etc.
1271    */
1272   if (stObj->pt) {
1273      if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
1274          !st_sampler_compat_formats(stObj->pt->format, firstImageFormat) ||
1275          stObj->pt->last_level < stObj->lastLevel ||
1276          stObj->pt->width0 != ptWidth ||
1277          stObj->pt->height0 != ptHeight ||
1278          stObj->pt->depth0 != ptDepth ||
1279          stObj->pt->array_size != ptLayers)
1280      {
1281         /* The gallium texture does not match the Mesa texture so delete the
1282          * gallium texture now.  We'll make a new one below.
1283          */
1284         pipe_resource_reference(&stObj->pt, NULL);
1285         pipe_sampler_view_reference(&stObj->sampler_view, NULL);
1286         st->dirty.st |= ST_NEW_FRAMEBUFFER;
1287      }
1288   }
1289
1290   /* May need to create a new gallium texture:
1291    */
1292   if (!stObj->pt) {
1293      GLuint bindings = default_bindings(st, firstImageFormat);
1294
1295      stObj->pt = st_texture_create(st,
1296                                    gl_target_to_pipe(stObj->base.Target),
1297                                    firstImageFormat,
1298                                    stObj->lastLevel,
1299                                    ptWidth,
1300                                    ptHeight,
1301                                    ptDepth,
1302                                    ptLayers,
1303                                    bindings);
1304
1305      if (!stObj->pt) {
1306         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
1307         return GL_FALSE;
1308      }
1309   }
1310
1311   /* Pull in any images not in the object's texture:
1312    */
1313   for (face = 0; face < nr_faces; face++) {
1314      GLuint level;
1315      for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
1316         struct st_texture_image *stImage =
1317            st_texture_image(stObj->base.Image[face][level]);
1318
1319         /* Need to import images in main memory or held in other textures.
1320          */
1321         if (stImage && stObj->pt != stImage->pt) {
1322            if (level == 0 ||
1323                (stImage->base.Width == u_minify(stObj->width0, level) &&
1324                 stImage->base.Height == u_minify(stObj->height0, level) &&
1325                 stImage->base.Depth == u_minify(stObj->depth0, level))) {
1326               /* src image fits expected dest mipmap level size */
1327               copy_image_data_to_texture(st, stObj, level, stImage);
1328            }
1329         }
1330      }
1331   }
1332
1333   return GL_TRUE;
1334}
1335
1336
1337/**
1338 * Returns pointer to a default/dummy texture.
1339 * This is typically used when the current shader has tex/sample instructions
1340 * but the user has not provided a (any) texture(s).
1341 */
1342struct gl_texture_object *
1343st_get_default_texture(struct st_context *st)
1344{
1345   if (!st->default_texture) {
1346      static const GLenum target = GL_TEXTURE_2D;
1347      GLubyte pixels[16][16][4];
1348      struct gl_texture_object *texObj;
1349      struct gl_texture_image *texImg;
1350      GLuint i, j;
1351
1352      /* The ARB_fragment_program spec says (0,0,0,1) should be returned
1353       * when attempting to sample incomplete textures.
1354       */
1355      for (i = 0; i < 16; i++) {
1356         for (j = 0; j < 16; j++) {
1357            pixels[i][j][0] = 0;
1358            pixels[i][j][1] = 0;
1359            pixels[i][j][2] = 0;
1360            pixels[i][j][3] = 255;
1361         }
1362      }
1363
1364      texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
1365
1366      texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
1367
1368      _mesa_init_teximage_fields(st->ctx, texImg,
1369                                 16, 16, 1, 0,  /* w, h, d, border */
1370                                 GL_RGBA, MESA_FORMAT_RGBA8888);
1371
1372      _mesa_store_teximage2d(st->ctx, texImg,
1373                             GL_RGBA,    /* level, intformat */
1374                             16, 16, 1,  /* w, h, d, border */
1375                             GL_RGBA, GL_UNSIGNED_BYTE, pixels,
1376                             &st->ctx->DefaultPacking);
1377
1378      texObj->Sampler.MinFilter = GL_NEAREST;
1379      texObj->Sampler.MagFilter = GL_NEAREST;
1380      texObj->_Complete = GL_TRUE;
1381
1382      st->default_texture = texObj;
1383   }
1384   return st->default_texture;
1385}
1386
1387
1388/**
1389 * Called via ctx->Driver.AllocTextureStorage() to allocate texture memory
1390 * for a whole mipmap stack.
1391 */
1392static GLboolean
1393st_AllocTextureStorage(struct gl_context *ctx,
1394                       struct gl_texture_object *texObj,
1395                       GLsizei levels, GLsizei width,
1396                       GLsizei height, GLsizei depth)
1397{
1398   const GLuint numFaces = (texObj->Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
1399   struct st_context *st = st_context(ctx);
1400   struct st_texture_object *stObj = st_texture_object(texObj);
1401   GLuint ptWidth, ptHeight, ptDepth, ptLayers, bindings;
1402   enum pipe_format fmt;
1403   GLint level;
1404
1405   assert(levels > 0);
1406
1407   /* Save the level=0 dimensions */
1408   stObj->width0 = width;
1409   stObj->height0 = height;
1410   stObj->depth0 = depth;
1411   stObj->lastLevel = levels - 1;
1412
1413   fmt = st_mesa_format_to_pipe_format(texObj->Image[0][0]->TexFormat);
1414
1415   bindings = default_bindings(st, fmt);
1416
1417   st_gl_texture_dims_to_pipe_dims(texObj->Target,
1418                                   width, height, depth,
1419                                   &ptWidth, &ptHeight, &ptDepth, &ptLayers);
1420
1421   stObj->pt = st_texture_create(st,
1422                                 gl_target_to_pipe(texObj->Target),
1423                                 fmt,
1424                                 levels,
1425                                 ptWidth,
1426                                 ptHeight,
1427                                 ptDepth,
1428                                 ptLayers,
1429                                 bindings);
1430   if (!stObj->pt)
1431      return GL_FALSE;
1432
1433   /* Set image resource pointers */
1434   for (level = 0; level < levels; level++) {
1435      GLuint face;
1436      for (face = 0; face < numFaces; face++) {
1437         struct st_texture_image *stImage =
1438            st_texture_image(texObj->Image[face][level]);
1439         pipe_resource_reference(&stImage->pt, stObj->pt);
1440      }
1441   }
1442
1443   return GL_TRUE;
1444}
1445
1446
1447
1448void
1449st_init_texture_functions(struct dd_function_table *functions)
1450{
1451   functions->ChooseTextureFormat = st_ChooseTextureFormat;
1452   functions->TexImage1D = st_TexImage1D;
1453   functions->TexImage2D = st_TexImage2D;
1454   functions->TexImage3D = st_TexImage3D;
1455   functions->TexSubImage1D = _mesa_store_texsubimage1d;
1456   functions->TexSubImage2D = _mesa_store_texsubimage2d;
1457   functions->TexSubImage3D = _mesa_store_texsubimage3d;
1458   functions->CompressedTexSubImage1D = _mesa_store_compressed_texsubimage1d;
1459   functions->CompressedTexSubImage2D = _mesa_store_compressed_texsubimage2d;
1460   functions->CompressedTexSubImage3D = _mesa_store_compressed_texsubimage3d;
1461   functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
1462   functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
1463   functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
1464   functions->GenerateMipmap = st_generate_mipmap;
1465
1466   functions->GetTexImage = st_GetTexImage;
1467
1468   /* compressed texture functions */
1469   functions->CompressedTexImage2D = st_CompressedTexImage2D;
1470   functions->GetCompressedTexImage = _mesa_get_compressed_teximage;
1471
1472   functions->NewTextureObject = st_NewTextureObject;
1473   functions->NewTextureImage = st_NewTextureImage;
1474   functions->DeleteTextureImage = st_DeleteTextureImage;
1475   functions->DeleteTexture = st_DeleteTextureObject;
1476   functions->AllocTextureImageBuffer = st_AllocTextureImageBuffer;
1477   functions->FreeTextureImageBuffer = st_FreeTextureImageBuffer;
1478   functions->MapTextureImage = st_MapTextureImage;
1479   functions->UnmapTextureImage = st_UnmapTextureImage;
1480
1481   /* XXX Temporary until we can query pipe's texture sizes */
1482   functions->TestProxyTexImage = _mesa_test_proxy_teximage;
1483
1484   functions->AllocTextureStorage = st_AllocTextureStorage;
1485}
1486