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