st_cb_texture.c revision 6b0fd0f1572cd6af1e931b70f75852de25d32649
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/imports.h"
29#include "main/convolve.h"
30#include "main/enums.h"
31#include "main/image.h"
32#include "main/macros.h"
33#include "main/mipmap.h"
34#include "main/pixel.h"
35#include "main/texcompress.h"
36#include "main/texformat.h"
37#include "main/teximage.h"
38#include "main/texobj.h"
39#include "main/texstore.h"
40
41#include "state_tracker/st_context.h"
42#include "state_tracker/st_cb_fbo.h"
43#include "state_tracker/st_cb_texture.h"
44#include "state_tracker/st_format.h"
45#include "state_tracker/st_public.h"
46#include "state_tracker/st_texture.h"
47#include "state_tracker/st_gen_mipmap.h"
48
49#include "pipe/p_context.h"
50#include "pipe/p_defines.h"
51#include "pipe/p_inlines.h"
52#include "util/p_tile.h"
53#include "util/u_blit.h"
54
55
56#define DBG if (0) printf
57
58
59static INLINE struct st_texture_image *
60st_texture_image(struct gl_texture_image *img)
61{
62   return (struct st_texture_image *) img;
63}
64
65
66static enum pipe_texture_target
67gl_target_to_pipe(GLenum target)
68{
69   switch (target) {
70   case GL_TEXTURE_1D:
71      return PIPE_TEXTURE_1D;
72
73   case GL_TEXTURE_2D:
74   case GL_TEXTURE_RECTANGLE_NV:
75      return PIPE_TEXTURE_2D;
76
77   case GL_TEXTURE_3D:
78      return PIPE_TEXTURE_3D;
79
80   case GL_TEXTURE_CUBE_MAP_ARB:
81      return PIPE_TEXTURE_CUBE;
82
83   default:
84      assert(0);
85      return 0;
86   }
87}
88
89
90/**
91 * Return nominal bytes per texel for a compressed format, 0 for non-compressed
92 * format.
93 */
94static int
95compressed_num_bytes(GLuint mesaFormat)
96{
97   switch(mesaFormat) {
98   case MESA_FORMAT_RGB_FXT1:
99   case MESA_FORMAT_RGBA_FXT1:
100   case MESA_FORMAT_RGB_DXT1:
101   case MESA_FORMAT_RGBA_DXT1:
102      return 2;
103   case MESA_FORMAT_RGBA_DXT3:
104   case MESA_FORMAT_RGBA_DXT5:
105      return 4;
106   default:
107      return 0;
108   }
109}
110
111
112static GLboolean
113st_IsTextureResident(GLcontext * ctx, struct gl_texture_object *texObj)
114{
115#if 0
116   struct intel_context *intel = intel_context(ctx);
117   struct st_texture_object *stObj = st_texture_object(texObj);
118
119   return
120      stObj->pt &&
121      stObj->pt->region &&
122      intel_is_region_resident(intel, stObj->pt->region);
123#endif
124   return 1;
125}
126
127
128static struct gl_texture_image *
129st_NewTextureImage(GLcontext * ctx)
130{
131   DBG("%s\n", __FUNCTION__);
132   (void) ctx;
133   return (struct gl_texture_image *) CALLOC_STRUCT(st_texture_image);
134}
135
136
137static struct gl_texture_object *
138st_NewTextureObject(GLcontext * ctx, GLuint name, GLenum target)
139{
140   struct st_texture_object *obj = CALLOC_STRUCT(st_texture_object);
141
142   DBG("%s\n", __FUNCTION__);
143   _mesa_initialize_texture_object(&obj->base, name, target);
144
145   return &obj->base;
146}
147
148static void
149st_DeleteTextureObject(GLcontext *ctx,
150                       struct gl_texture_object *texObj)
151{
152   struct st_texture_object *stObj = st_texture_object(texObj);
153   if (stObj->pt)
154      pipe_texture_release(&stObj->pt);
155
156   _mesa_delete_texture_object(ctx, texObj);
157}
158
159
160static void
161st_FreeTextureImageData(GLcontext * ctx, struct gl_texture_image *texImage)
162{
163   struct st_texture_image *stImage = st_texture_image(texImage);
164
165   DBG("%s\n", __FUNCTION__);
166
167   if (stImage->pt) {
168      pipe_texture_release(&stImage->pt);
169   }
170
171   if (texImage->Data) {
172      free(texImage->Data);
173      texImage->Data = NULL;
174   }
175}
176
177
178/* ================================================================
179 * From linux kernel i386 header files, copes with odd sizes better
180 * than COPY_DWORDS would:
181 * XXX Put this in src/mesa/main/imports.h ???
182 */
183#if defined(i386) || defined(__i386__)
184static INLINE void *
185__memcpy(void *to, const void *from, size_t n)
186{
187   int d0, d1, d2;
188   __asm__ __volatile__("rep ; movsl\n\t"
189                        "testb $2,%b4\n\t"
190                        "je 1f\n\t"
191                        "movsw\n"
192                        "1:\ttestb $1,%b4\n\t"
193                        "je 2f\n\t"
194                        "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
195                        :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
196                        :"memory");
197   return (to);
198}
199#else
200#define __memcpy(a,b,c) memcpy(a,b,c)
201#endif
202
203
204/* The system memcpy (at least on ubuntu 5.10) has problems copying
205 * to agp (writecombined) memory from a source which isn't 64-byte
206 * aligned - there is a 4x performance falloff.
207 *
208 * The x86 __memcpy is immune to this but is slightly slower
209 * (10%-ish) than the system memcpy.
210 *
211 * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
212 * isn't much faster than x86_memcpy for agp copies.
213 *
214 * TODO: switch dynamically.
215 */
216static void *
217do_memcpy(void *dest, const void *src, size_t n)
218{
219   if ((((unsigned) src) & 63) || (((unsigned) dest) & 63)) {
220      return __memcpy(dest, src, n);
221   }
222   else
223      return memcpy(dest, src, n);
224}
225
226
227/* Functions to store texture images.  Where possible, textures
228 * will be created or further instantiated with image data, otherwise
229 * images will be stored in malloc'd memory.  A validation step is
230 * required to pull those images into a texture, or otherwise
231 * decide a fallback is required.
232 */
233
234
235static int
236logbase2(int n)
237{
238   GLint i = 1;
239   GLint log2 = 0;
240
241   while (n > i) {
242      i *= 2;
243      log2++;
244   }
245
246   return log2;
247}
248
249
250/**
251 * Allocate a pipe_texture object for the given st_texture_object using
252 * the given st_texture_image to guess the mipmap size/levels.
253 *
254 * [comments...]
255 * Otherwise, store it in memory if (Border != 0) or (any dimension ==
256 * 1).
257 *
258 * Otherwise, if max_level >= level >= min_level, create texture with
259 * space for images from min_level down to max_level.
260 *
261 * Otherwise, create texture with space for images from (level 0)..(1x1).
262 * Consider pruning this texture at a validation if the saving is worth it.
263 */
264static void
265guess_and_alloc_texture(struct st_context *st,
266			struct st_texture_object *stObj,
267			const struct st_texture_image *stImage)
268{
269   GLuint firstLevel;
270   GLuint lastLevel;
271   GLuint width = stImage->base.Width2;  /* size w/out border */
272   GLuint height = stImage->base.Height2;
273   GLuint depth = stImage->base.Depth2;
274   GLuint i, comp_byte = 0;
275
276   DBG("%s\n", __FUNCTION__);
277
278   assert(!stObj->pt);
279
280   if (stObj->pt &&
281       stImage->level > stObj->base.BaseLevel &&
282       (stImage->base.Width == 1 ||
283        (stObj->base.Target != GL_TEXTURE_1D &&
284         stImage->base.Height == 1) ||
285        (stObj->base.Target == GL_TEXTURE_3D &&
286         stImage->base.Depth == 1)))
287      return;
288
289   /* If this image disrespects BaseLevel, allocate from level zero.
290    * Usually BaseLevel == 0, so it's unlikely to happen.
291    */
292   if (stImage->level < stObj->base.BaseLevel)
293      firstLevel = 0;
294   else
295      firstLevel = stObj->base.BaseLevel;
296
297
298   /* Figure out image dimensions at start level.
299    */
300   for (i = stImage->level; i > firstLevel; i--) {
301      if (width != 1)
302         width <<= 1;
303      if (height != 1)
304         height <<= 1;
305      if (depth != 1)
306         depth <<= 1;
307   }
308
309   if (width == 0 || height == 0 || depth == 0) {
310      /* no texture needed */
311      return;
312   }
313
314   /* Guess a reasonable value for lastLevel.  This is probably going
315    * to be wrong fairly often and might mean that we have to look at
316    * resizable buffers, or require that buffers implement lazy
317    * pagetable arrangements.
318    */
319   if ((stObj->base.MinFilter == GL_NEAREST ||
320        stObj->base.MinFilter == GL_LINEAR) &&
321       stImage->level == firstLevel) {
322      lastLevel = firstLevel;
323   }
324   else {
325      GLuint l2width = logbase2(width);
326      GLuint l2height = logbase2(height);
327      GLuint l2depth = logbase2(depth);
328      lastLevel = firstLevel + MAX2(MAX2(l2width, l2height), l2depth);
329   }
330
331   if (stImage->base.IsCompressed)
332      comp_byte = compressed_num_bytes(stImage->base.TexFormat->MesaFormat);
333
334   stObj->pt = st_texture_create(st,
335                                 gl_target_to_pipe(stObj->base.Target),
336                                 st_mesa_format_to_pipe_format(stImage->base.TexFormat->MesaFormat),
337                                 lastLevel,
338                                 width,
339                                 height,
340                                 depth,
341                                 comp_byte,
342                                 ( PIPE_TEXTURE_USAGE_RENDER_TARGET |
343                                   PIPE_TEXTURE_USAGE_SAMPLER ));
344
345   DBG("%s - success\n", __FUNCTION__);
346}
347
348
349/* There are actually quite a few combinations this will work for,
350 * more than what I've listed here.
351 */
352static GLboolean
353check_pbo_format(GLint internalFormat,
354                 GLenum format, GLenum type,
355                 const struct gl_texture_format *mesa_format)
356{
357   switch (internalFormat) {
358   case 4:
359   case GL_RGBA:
360      return (format == GL_BGRA &&
361              (type == GL_UNSIGNED_BYTE ||
362               type == GL_UNSIGNED_INT_8_8_8_8_REV) &&
363              mesa_format == &_mesa_texformat_argb8888);
364   case 3:
365   case GL_RGB:
366      return (format == GL_RGB &&
367              type == GL_UNSIGNED_SHORT_5_6_5 &&
368              mesa_format == &_mesa_texformat_rgb565);
369   case GL_YCBCR_MESA:
370      return (type == GL_UNSIGNED_SHORT_8_8_MESA || type == GL_UNSIGNED_BYTE);
371   default:
372      return GL_FALSE;
373   }
374}
375
376
377/* XXX: Do this for TexSubImage also:
378 */
379static GLboolean
380try_pbo_upload(GLcontext *ctx,
381               struct st_texture_image *stImage,
382               const struct gl_pixelstore_attrib *unpack,
383               GLint internalFormat,
384               GLint width, GLint height,
385               GLenum format, GLenum type, const void *pixels)
386{
387   return GL_FALSE;  /* XXX fix flushing/locking/blitting below */
388#if 000
389   struct intel_context *intel = intel_context(ctx);
390   struct intel_buffer_object *pbo = intel_buffer_object(unpack->BufferObj);
391   GLuint src_offset, src_stride;
392   GLuint dst_offset, dst_stride;
393
394   if (!pbo ||
395       ctx._ImageTransferState ||
396       unpack->SkipPixels || unpack->SkipRows) {
397      _mesa_printf("%s: failure 1\n", __FUNCTION__);
398      return GL_FALSE;
399   }
400
401   src_offset = (GLuint) pixels;
402
403   if (unpack->RowLength > 0)
404      src_stride = unpack->RowLength;
405   else
406      src_stride = width;
407
408   dst_offset = st_texture_image_offset(stImage->pt,
409                                           stImage->face,
410                                           stImage->level);
411
412   dst_stride = stImage->pt->pitch;
413
414   {
415      struct _DriBufferObject *src_buffer =
416         intel_bufferobj_buffer(intel, pbo, INTEL_READ);
417
418      /* Temporary hack: cast to _DriBufferObject:
419       */
420      struct _DriBufferObject *dst_buffer =
421         (struct _DriBufferObject *)stImage->pt->region->buffer;
422
423
424      intelEmitCopyBlit(intel,
425                        stImage->pt->cpp,
426                        src_stride, src_buffer, src_offset,
427                        dst_stride, dst_buffer, dst_offset,
428                        0, 0, 0, 0, width, height,
429			GL_COPY);
430   }
431
432   return GL_TRUE;
433#endif
434}
435
436
437/**
438 * Adjust pixel unpack params and image dimensions to strip off the
439 * texture border.
440 * Gallium doesn't support texture borders.  They've seldem been used
441 * and seldom been implemented correctly anyway.
442 * \param unpackNew  returns the new pixel unpack parameters
443 */
444static void
445strip_texture_border(GLint border,
446                     GLint *width, GLint *height, GLint *depth,
447                     const struct gl_pixelstore_attrib *unpack,
448                     struct gl_pixelstore_attrib *unpackNew)
449{
450   assert(border > 0);  /* sanity check */
451
452   *unpackNew = *unpack;
453
454   if (unpackNew->RowLength == 0)
455      unpackNew->RowLength = *width;
456
457   if (depth && unpackNew->ImageHeight == 0)
458      unpackNew->ImageHeight = *height;
459
460   unpackNew->SkipPixels += border;
461   if (height)
462      unpackNew->SkipRows += border;
463   if (depth)
464      unpackNew->SkipImages += border;
465
466   assert(*width >= 3);
467   *width = *width - 2 * border;
468   if (height && *height >= 3)
469      *height = *height - 2 * border;
470   if (depth && *depth >= 3)
471      *depth = *depth - 2 * border;
472}
473
474
475static void
476st_TexImage(GLcontext * ctx,
477            GLint dims,
478            GLenum target, GLint level,
479            GLint internalFormat,
480            GLint width, GLint height, GLint depth,
481            GLint border,
482            GLenum format, GLenum type, const void *pixels,
483            const struct gl_pixelstore_attrib *unpack,
484            struct gl_texture_object *texObj,
485            struct gl_texture_image *texImage,
486            GLsizei imageSize, int compressed)
487{
488   struct st_texture_object *stObj = st_texture_object(texObj);
489   struct st_texture_image *stImage = st_texture_image(texImage);
490   GLint postConvWidth, postConvHeight;
491   GLint texelBytes, sizeInBytes;
492   GLuint dstRowStride;
493   struct gl_pixelstore_attrib unpackNB;
494
495   DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
496       _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
497
498   /* gallium does not support texture borders, strip it off */
499   if (border) {
500      strip_texture_border(border, &width, &height, &depth,
501                           unpack, &unpackNB);
502      unpack = &unpackNB;
503      texImage->Width = width;
504      texImage->Height = height;
505      texImage->Depth = depth;
506      texImage->Border = 0;
507      border = 0;
508   }
509
510   postConvWidth = width;
511   postConvHeight = height;
512
513   stImage->face = _mesa_tex_target_to_face(target);
514   stImage->level = level;
515
516   if (ctx->_ImageTransferState & IMAGE_CONVOLUTION_BIT) {
517      _mesa_adjust_image_for_convolution(ctx, dims, &postConvWidth,
518                                         &postConvHeight);
519   }
520
521   /* choose the texture format */
522   texImage->TexFormat = st_ChooseTextureFormat(ctx, internalFormat,
523                                                format, type);
524
525   _mesa_set_fetch_functions(texImage, dims);
526
527   if (texImage->TexFormat->TexelBytes == 0) {
528      /* must be a compressed format */
529      texelBytes = 0;
530      texImage->IsCompressed = GL_TRUE;
531      texImage->CompressedSize =
532	 ctx->Driver.CompressedTextureSize(ctx, texImage->Width,
533					   texImage->Height, texImage->Depth,
534					   texImage->TexFormat->MesaFormat);
535   }
536   else {
537      texelBytes = texImage->TexFormat->TexelBytes;
538
539      /* Minimum pitch of 32 bytes */
540      if (postConvWidth * texelBytes < 32) {
541	 postConvWidth = 32 / texelBytes;
542	 texImage->RowStride = postConvWidth;
543      }
544
545      /* we'll set RowStride elsewhere when the texture is a "mapped" state */
546      /*assert(texImage->RowStride == postConvWidth);*/
547   }
548
549   /* Release the reference to a potentially orphaned buffer.
550    * Release any old malloced memory.
551    */
552   if (stImage->pt) {
553      pipe_texture_release(&stImage->pt);
554      assert(!texImage->Data);
555   }
556   else if (texImage->Data) {
557      _mesa_align_free(texImage->Data);
558   }
559
560   /* If this is the only mipmap level in the texture, could call
561    * bmBufferData with NULL data to free the old block and avoid
562    * waiting on any outstanding fences.
563    */
564   if (stObj->pt &&
565       (stObj->teximage_realloc ||
566        (/*stObj->pt->first_level == level &&*/
567         stObj->pt->last_level == level &&
568         stObj->pt->target != PIPE_TEXTURE_CUBE &&
569         !st_texture_match_image(stObj->pt, &stImage->base,
570                                 stImage->face, stImage->level)))) {
571
572      DBG("release it\n");
573      pipe_texture_release(&stObj->pt);
574      assert(!stObj->pt);
575      stObj->teximage_realloc = FALSE;
576   }
577
578   if (!stObj->pt) {
579      guess_and_alloc_texture(ctx->st, stObj, stImage);
580      if (!stObj->pt) {
581         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
582         return;
583      }
584   }
585
586   assert(!stImage->pt);
587
588   if (stObj->pt &&
589       st_texture_match_image(stObj->pt, &stImage->base,
590                                 stImage->face, stImage->level)) {
591
592      pipe_texture_reference(&stImage->pt, stObj->pt);
593      assert(stImage->pt);
594   }
595
596   if (!stImage->pt)
597      DBG("XXX: Image did not fit into texture - storing in local memory!\n");
598
599#if 0 /* XXX FIX when st_buffer_objects are in place */
600   /* PBO fastpaths:
601    */
602   if (dims <= 2 &&
603       stImage->pt &&
604       intel_buffer_object(unpack->BufferObj) &&
605       check_pbo_format(internalFormat, format,
606                        type, texImage->TexFormat)) {
607
608      DBG("trying pbo upload\n");
609
610
611
612      /* Otherwise, attempt to use the blitter for PBO image uploads.
613       */
614      if (try_pbo_upload(intel, stImage, unpack,
615                         internalFormat,
616                         width, height, format, type, pixels)) {
617         DBG("pbo upload succeeded\n");
618         return;
619      }
620
621      DBG("pbo upload failed\n");
622   }
623#else
624   (void) try_pbo_upload;
625   (void) check_pbo_format;
626#endif
627
628
629   /* st_CopyTexImage calls this function with pixels == NULL, with
630    * the expectation that the texture will be set up but nothing
631    * more will be done.  This is where those calls return:
632    */
633   if (compressed) {
634      pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
635						      unpack,
636						      "glCompressedTexImage");
637   } else {
638      pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
639					   format, type,
640					   pixels, unpack, "glTexImage");
641   }
642   if (!pixels)
643      return;
644
645   if (stImage->pt) {
646      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
647                                            PIPE_BUFFER_USAGE_CPU_WRITE);
648      dstRowStride = stImage->surface->pitch * stImage->surface->cpp;
649   }
650   else {
651      /* Allocate regular memory and store the image there temporarily.   */
652      if (texImage->IsCompressed) {
653         sizeInBytes = texImage->CompressedSize;
654         dstRowStride =
655            _mesa_compressed_row_stride(texImage->TexFormat->MesaFormat, width);
656         assert(dims != 3);
657      }
658      else {
659         dstRowStride = postConvWidth * texelBytes;
660         sizeInBytes = depth * dstRowStride * postConvHeight;
661      }
662
663      texImage->Data = malloc(sizeInBytes);
664   }
665
666   DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
667       width, height, depth, width * texelBytes, dstRowStride);
668
669   /* Copy data.  Would like to know when it's ok for us to eg. use
670    * the blitter to copy.  Or, use the hardware to do the format
671    * conversion and copy:
672    */
673   if (compressed) {
674      memcpy(texImage->Data, pixels, imageSize);
675   }
676   else {
677      GLuint srcImageStride = _mesa_image_image_stride(unpack, width, height,
678						       format, type);
679      int i;
680      const GLubyte *src = (const GLubyte *) pixels;
681
682      for (i = 0; i++ < depth;) {
683	 if (!texImage->TexFormat->StoreImage(ctx, dims,
684					      texImage->_BaseFormat,
685					      texImage->TexFormat,
686					      texImage->Data,
687					      0, 0, 0, /* dstX/Y/Zoffset */
688					      dstRowStride,
689					      texImage->ImageOffsets,
690					      width, height, 1,
691					      format, type, src, unpack)) {
692	    _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
693	 }
694
695	 if (stImage->pt && i < depth) {
696	    st_texture_image_unmap(ctx->st, stImage);
697	    texImage->Data = st_texture_image_map(ctx->st, stImage, i,
698                                                  PIPE_BUFFER_USAGE_CPU_WRITE);
699	    src += srcImageStride;
700	 }
701      }
702   }
703
704   _mesa_unmap_teximage_pbo(ctx, unpack);
705
706   if (stImage->pt) {
707      st_texture_image_unmap(ctx->st, stImage);
708      texImage->Data = NULL;
709   }
710
711   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
712      ctx->Driver.GenerateMipmap(ctx, target, texObj);
713   }
714}
715
716
717static void
718st_TexImage3D(GLcontext * ctx,
719                GLenum target, GLint level,
720                GLint internalFormat,
721                GLint width, GLint height, GLint depth,
722                GLint border,
723                GLenum format, GLenum type, const void *pixels,
724                const struct gl_pixelstore_attrib *unpack,
725                struct gl_texture_object *texObj,
726                struct gl_texture_image *texImage)
727{
728   st_TexImage(ctx, 3, target, level,
729                 internalFormat, width, height, depth, border,
730                 format, type, pixels, unpack, texObj, texImage, 0, 0);
731}
732
733
734static void
735st_TexImage2D(GLcontext * ctx,
736                GLenum target, GLint level,
737                GLint internalFormat,
738                GLint width, GLint height, GLint border,
739                GLenum format, GLenum type, const void *pixels,
740                const struct gl_pixelstore_attrib *unpack,
741                struct gl_texture_object *texObj,
742                struct gl_texture_image *texImage)
743{
744   st_TexImage(ctx, 2, target, level,
745                 internalFormat, width, height, 1, border,
746                 format, type, pixels, unpack, texObj, texImage, 0, 0);
747}
748
749
750static void
751st_TexImage1D(GLcontext * ctx,
752                GLenum target, GLint level,
753                GLint internalFormat,
754                GLint width, GLint border,
755                GLenum format, GLenum type, const void *pixels,
756                const struct gl_pixelstore_attrib *unpack,
757                struct gl_texture_object *texObj,
758                struct gl_texture_image *texImage)
759{
760   st_TexImage(ctx, 1, target, level,
761                 internalFormat, width, 1, 1, border,
762                 format, type, pixels, unpack, texObj, texImage, 0, 0);
763}
764
765
766static void
767st_CompressedTexImage2D( GLcontext *ctx, GLenum target, GLint level,
768				GLint internalFormat,
769				GLint width, GLint height, GLint border,
770				GLsizei imageSize, const GLvoid *data,
771				struct gl_texture_object *texObj,
772				struct gl_texture_image *texImage )
773{
774   st_TexImage(ctx, 2, target, level,
775		 internalFormat, width, height, 1, border,
776		 0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, 1);
777}
778
779
780/**
781 * Need to map texture image into memory before copying image data,
782 * then unmap it.
783 */
784static void
785st_get_tex_image(GLcontext * ctx, GLenum target, GLint level,
786                 GLenum format, GLenum type, GLvoid * pixels,
787                 struct gl_texture_object *texObj,
788                 struct gl_texture_image *texImage, int compressed)
789{
790   struct st_texture_image *stImage = st_texture_image(texImage);
791   GLuint dstImageStride = _mesa_image_image_stride(&ctx->Pack, texImage->Width,
792						    texImage->Height, format,
793						    type);
794   GLuint depth;
795   int i;
796   GLubyte *dest;
797
798   /* Map */
799   if (stImage->pt) {
800      /* Image is stored in hardware format in a buffer managed by the
801       * kernel.  Need to explicitly map and unmap it.
802       */
803      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
804                                            PIPE_BUFFER_USAGE_CPU_READ);
805      texImage->RowStride = stImage->surface->pitch;
806   }
807   else {
808      /* Otherwise, the image should actually be stored in
809       * texImage->Data.  This is pretty confusing for
810       * everybody, I'd much prefer to separate the two functions of
811       * texImage->Data - storage for texture images in main memory
812       * and access (ie mappings) of images.  In other words, we'd
813       * create a new texImage->Map field and leave Data simply for
814       * storage.
815       */
816      assert(texImage->Data);
817   }
818
819   depth = texImage->Depth;
820   texImage->Depth = 1;
821
822   dest = (GLubyte *) pixels;
823
824   for (i = 0; i++ < depth;) {
825      if (compressed) {
826	 _mesa_get_compressed_teximage(ctx, target, level, dest,
827				       texObj, texImage);
828      } else {
829	 _mesa_get_teximage(ctx, target, level, format, type, dest,
830			    texObj, texImage);
831      }
832
833      if (stImage->pt && i < depth) {
834	 st_texture_image_unmap(ctx->st, stImage);
835	 texImage->Data = st_texture_image_map(ctx->st, stImage, i,
836                                               PIPE_BUFFER_USAGE_CPU_READ);
837	 dest += dstImageStride;
838      }
839   }
840
841   texImage->Depth = depth;
842
843   /* Unmap */
844   if (stImage->pt) {
845      st_texture_image_unmap(ctx->st, stImage);
846      texImage->Data = NULL;
847   }
848}
849
850
851static void
852st_GetTexImage(GLcontext * ctx, GLenum target, GLint level,
853                 GLenum format, GLenum type, GLvoid * pixels,
854                 struct gl_texture_object *texObj,
855                 struct gl_texture_image *texImage)
856{
857   st_get_tex_image(ctx, target, level, format, type, pixels,
858                    texObj, texImage, 0);
859}
860
861
862static void
863st_GetCompressedTexImage(GLcontext *ctx, GLenum target, GLint level,
864			   GLvoid *pixels,
865			   const struct gl_texture_object *texObj,
866			   const struct gl_texture_image *texImage)
867{
868   st_get_tex_image(ctx, target, level, 0, 0, pixels,
869                    (struct gl_texture_object *) texObj,
870                    (struct gl_texture_image *) texImage, 1);
871}
872
873
874
875static void
876st_TexSubimage(GLcontext * ctx,
877                 GLint dims,
878                 GLenum target, GLint level,
879                 GLint xoffset, GLint yoffset, GLint zoffset,
880                 GLint width, GLint height, GLint depth,
881                 GLenum format, GLenum type, const void *pixels,
882                 const struct gl_pixelstore_attrib *packing,
883                 struct gl_texture_object *texObj,
884                 struct gl_texture_image *texImage)
885{
886   struct st_texture_image *stImage = st_texture_image(texImage);
887   GLuint dstRowStride;
888   GLuint srcImageStride = _mesa_image_image_stride(packing, width, height,
889						    format, type);
890   int i;
891   const GLubyte *src;
892
893   DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
894       _mesa_lookup_enum_by_nr(target),
895       level, xoffset, yoffset, width, height);
896
897   pixels =
898      _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
899                                  type, pixels, packing, "glTexSubImage2D");
900   if (!pixels)
901      return;
902
903   /* Map buffer if necessary.  Need to lock to prevent other contexts
904    * from uploading the buffer under us.
905    */
906   if (stImage->pt) {
907      texImage->Data = st_texture_image_map(ctx->st, stImage, zoffset,
908                                            PIPE_BUFFER_USAGE_CPU_WRITE);
909      dstRowStride = stImage->surface->pitch * stImage->surface->cpp;
910   }
911
912   if (!texImage->Data) {
913      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
914      return;
915   }
916
917   src = (const GLubyte *) pixels;
918
919   for (i = 0; i++ < depth;) {
920      if (!texImage->TexFormat->StoreImage(ctx, dims, texImage->_BaseFormat,
921					   texImage->TexFormat,
922					   texImage->Data,
923					   xoffset, yoffset, 0,
924					   dstRowStride,
925					   texImage->ImageOffsets,
926					   width, height, 1,
927					   format, type, src, packing)) {
928	 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
929      }
930
931      if (stImage->pt && i < depth) {
932         /* map next slice of 3D texture */
933	 st_texture_image_unmap(ctx->st, stImage);
934	 texImage->Data = st_texture_image_map(ctx->st, stImage, zoffset + i,
935                                               PIPE_BUFFER_USAGE_CPU_WRITE);
936	 src += srcImageStride;
937      }
938   }
939
940   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
941      ctx->Driver.GenerateMipmap(ctx, target, texObj);
942   }
943
944   _mesa_unmap_teximage_pbo(ctx, packing);
945
946   if (stImage->pt) {
947      st_texture_image_unmap(ctx->st, stImage);
948      texImage->Data = NULL;
949   }
950}
951
952
953
954static void
955st_TexSubImage3D(GLcontext * ctx,
956                   GLenum target,
957                   GLint level,
958                   GLint xoffset, GLint yoffset, GLint zoffset,
959                   GLsizei width, GLsizei height, GLsizei depth,
960                   GLenum format, GLenum type,
961                   const GLvoid * pixels,
962                   const struct gl_pixelstore_attrib *packing,
963                   struct gl_texture_object *texObj,
964                   struct gl_texture_image *texImage)
965{
966   st_TexSubimage(ctx, 3, target, level,
967                  xoffset, yoffset, zoffset,
968                  width, height, depth,
969                  format, type, pixels, packing, texObj, texImage);
970}
971
972
973
974static void
975st_TexSubImage2D(GLcontext * ctx,
976                   GLenum target,
977                   GLint level,
978                   GLint xoffset, GLint yoffset,
979                   GLsizei width, GLsizei height,
980                   GLenum format, GLenum type,
981                   const GLvoid * pixels,
982                   const struct gl_pixelstore_attrib *packing,
983                   struct gl_texture_object *texObj,
984                   struct gl_texture_image *texImage)
985{
986   st_TexSubimage(ctx, 2, target, level,
987                  xoffset, yoffset, 0,
988                  width, height, 1,
989                  format, type, pixels, packing, texObj, texImage);
990}
991
992
993static void
994st_TexSubImage1D(GLcontext * ctx,
995                   GLenum target,
996                   GLint level,
997                   GLint xoffset,
998                   GLsizei width,
999                   GLenum format, GLenum type,
1000                   const GLvoid * pixels,
1001                   const struct gl_pixelstore_attrib *packing,
1002                   struct gl_texture_object *texObj,
1003                   struct gl_texture_image *texImage)
1004{
1005   st_TexSubimage(ctx, 1, target, level,
1006                  xoffset, 0, 0,
1007                  width, 1, 1,
1008                  format, type, pixels, packing, texObj, texImage);
1009}
1010
1011
1012
1013/**
1014 * Return 0 for GL_TEXTURE_CUBE_MAP_POSITIVE_X,
1015 *        1 for GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
1016 *        etc.
1017 * XXX duplicated from main/teximage.c
1018 */
1019static uint
1020texture_face(GLenum target)
1021{
1022   if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB &&
1023       target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB)
1024      return (GLuint) target - (GLuint) GL_TEXTURE_CUBE_MAP_POSITIVE_X;
1025   else
1026      return 0;
1027}
1028
1029
1030
1031/**
1032 * Do a CopyTexSubImage operation by mapping the source surface and
1033 * dest surface and using get_tile()/put_tile() to access the pixels/texels.
1034 *
1035 * Note: srcY=0=TOP of renderbuffer
1036 */
1037static void
1038fallback_copy_texsubimage(GLcontext *ctx,
1039                          GLenum target,
1040                          GLint level,
1041                          struct st_renderbuffer *strb,
1042                          struct st_texture_image *stImage,
1043                          GLenum baseFormat,
1044                          GLint destX, GLint destY, GLint destZ,
1045                          GLint srcX, GLint srcY,
1046                          GLsizei width, GLsizei height)
1047{
1048   struct pipe_context *pipe = ctx->st->pipe;
1049   struct pipe_screen *screen = pipe->screen;
1050   const uint face = texture_face(target);
1051   struct pipe_texture *pt = stImage->pt;
1052   struct pipe_surface *src_surf, *dest_surf;
1053   GLint row, yStep;
1054
1055   st_flush(ctx->st, PIPE_FLUSH_RENDER_CACHE, NULL);
1056
1057   /* determine bottom-to-top vs. top-to-bottom order */
1058   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1059      destY = height - 1 - destY;
1060      yStep = -1;
1061   }
1062   else {
1063      yStep = 1;
1064   }
1065
1066   src_surf = strb->surface;
1067   src_surf = screen->get_tex_surface(screen, strb->texture, face, level, destZ,
1068                                       PIPE_BUFFER_USAGE_CPU_READ);
1069
1070   dest_surf = screen->get_tex_surface(screen, pt, face, level, destZ,
1071                                       PIPE_BUFFER_USAGE_CPU_WRITE);
1072
1073   assert(width <= MAX_WIDTH);
1074
1075   /*
1076    * To avoid a large temp memory allocation, do copy row by row.
1077    */
1078   if (baseFormat == GL_DEPTH_COMPONENT) {
1079      const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
1080                                     ctx->Pixel.DepthBias != 0.0F);
1081
1082      for (row = 0; row < height; row++, srcY++, destY += yStep) {
1083         uint data[MAX_WIDTH];
1084         pipe_get_tile_z(pipe, src_surf, srcX, srcY, width, 1, data);
1085         if (scaleOrBias) {
1086            _mesa_scale_and_bias_depth_uint(ctx, width, data);
1087         }
1088         pipe_put_tile_z(pipe, dest_surf, destX, destY, width, 1, data);
1089      }
1090   }
1091   else {
1092      /* RGBA format */
1093      for (row = 0; row < height; row++, srcY++, destY += yStep) {
1094         float data[4 * MAX_WIDTH];
1095         pipe_get_tile_rgba(pipe, src_surf, srcX, srcY, width, 1, data);
1096         /* XXX we're ignoring convolution for now */
1097         if (ctx->_ImageTransferState) {
1098            _mesa_apply_rgba_transfer_ops(ctx,
1099                          ctx->_ImageTransferState & ~IMAGE_CONVOLUTION_BIT,
1100                          width, (GLfloat (*)[4]) data);
1101         }
1102         pipe_put_tile_rgba(pipe, dest_surf, destX, destY, width, 1, data);
1103      }
1104   }
1105
1106   screen->tex_surface_release(screen, &dest_surf);
1107   screen->tex_surface_release(screen, &src_surf);
1108}
1109
1110
1111
1112
1113/**
1114 * Do a CopyTex[Sub]Image using an optimized hardware (blit) path.
1115 * Note that the region to copy has already been clip tested.
1116 *
1117 * Note: srcY=0=Bottom of renderbuffer
1118 *
1119 * \return GL_TRUE if success, GL_FALSE if failure (use a fallback)
1120 */
1121static void
1122do_copy_texsubimage(GLcontext *ctx,
1123                    GLenum target, GLint level,
1124                    GLint destX, GLint destY, GLint destZ,
1125                    GLint srcX, GLint srcY,
1126                    GLsizei width, GLsizei height)
1127{
1128   struct gl_texture_unit *texUnit =
1129      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1130   struct gl_texture_object *texObj =
1131      _mesa_select_tex_object(ctx, texUnit, target);
1132   struct gl_texture_image *texImage =
1133      _mesa_select_tex_image(ctx, texObj, target, level);
1134   struct st_texture_image *stImage = st_texture_image(texImage);
1135   GLenum baseFormat = texImage->InternalFormat;
1136   struct gl_framebuffer *fb = ctx->ReadBuffer;
1137   struct st_renderbuffer *strb;
1138   struct pipe_context *pipe = ctx->st->pipe;
1139   struct pipe_screen *screen = pipe->screen;
1140   struct pipe_surface *dest_surface;
1141   uint dest_format, src_format;
1142   uint do_flip = FALSE;
1143   GLboolean use_fallback = GL_TRUE;
1144
1145   (void) texImage;
1146
1147   /* determine if copying depth or color data */
1148   if (baseFormat == GL_DEPTH_COMPONENT) {
1149      strb = st_renderbuffer(fb->_DepthBuffer);
1150   }
1151   else if (baseFormat == GL_DEPTH_STENCIL_EXT) {
1152      strb = st_renderbuffer(fb->_StencilBuffer);
1153   }
1154   else {
1155      /* baseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
1156      strb = st_renderbuffer(fb->_ColorReadBuffer);
1157   }
1158
1159   assert(strb);
1160   assert(strb->surface);
1161   assert(stImage->pt);
1162
1163   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1164      srcY = strb->Base.Height - srcY - height;
1165      do_flip = TRUE;
1166   }
1167
1168   src_format = strb->surface->format;
1169   dest_format = stImage->pt->format;
1170
1171   dest_surface = screen->get_tex_surface(screen, stImage->pt, stImage->face,
1172                                          stImage->level, destZ,
1173                                          PIPE_BUFFER_USAGE_CPU_WRITE);
1174
1175   if (ctx->_ImageTransferState == 0x0 &&
1176       strb->surface->buffer &&
1177       dest_surface->buffer) {
1178      /* do blit-style copy */
1179
1180      /* XXX may need to invert image depending on window
1181       * vs. user-created FBO
1182       */
1183
1184#if 0
1185      /* A bit of fiddling to get the blitter to work with -ve
1186       * pitches.  But we get a nice inverted blit this way, so it's
1187       * worth it:
1188       */
1189      intelEmitCopyBlit(intel,
1190                        stImage->pt->cpp,
1191                        -src->pitch,
1192                        src->buffer,
1193                        src->height * src->pitch * src->cpp,
1194                        stImage->pt->pitch,
1195                        stImage->pt->region->buffer,
1196                        dest_offset,
1197                        x, y + height, dstx, dsty, width, height,
1198                        GL_COPY); /* ? */
1199#else
1200
1201      if (src_format == dest_format) {
1202          pipe->surface_copy(pipe,
1203			     do_flip,
1204			     /* dest */
1205			     dest_surface,
1206			     destX, destY,
1207			     /* src */
1208			     strb->surface,
1209			     srcX, srcY,
1210			     /* size */
1211			     width, height);
1212          use_fallback = GL_FALSE;
1213      }
1214      else if (screen->is_format_supported(screen, strb->surface->format,
1215                                           PIPE_TEXTURE) &&
1216               screen->is_format_supported(screen, dest_surface->format,
1217                                           PIPE_SURFACE)) {
1218         util_blit_pixels(ctx->st->blit,
1219                          strb->surface,
1220                          srcX, do_flip ? srcY + height : srcY,
1221                          srcX + width, do_flip ? srcY : srcY + height,
1222                          dest_surface,
1223                          destX, destY, destX + width, destY + height,
1224                          0.0, PIPE_TEX_MIPFILTER_NEAREST);
1225         use_fallback = GL_FALSE;
1226      }
1227#endif
1228   }
1229
1230   if (use_fallback) {
1231      fallback_copy_texsubimage(ctx, target, level,
1232                                strb, stImage, baseFormat,
1233                                destX, destY, destZ,
1234                                srcX, srcY, width, height);
1235   }
1236
1237   pipe_surface_reference(&dest_surface, NULL);
1238
1239   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
1240      ctx->Driver.GenerateMipmap(ctx, target, texObj);
1241   }
1242}
1243
1244
1245
1246static void
1247st_CopyTexImage1D(GLcontext * ctx, GLenum target, GLint level,
1248                  GLenum internalFormat,
1249                  GLint x, GLint y, GLsizei width, GLint border)
1250{
1251   struct gl_texture_unit *texUnit =
1252      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1253   struct gl_texture_object *texObj =
1254      _mesa_select_tex_object(ctx, texUnit, target);
1255   struct gl_texture_image *texImage =
1256      _mesa_select_tex_image(ctx, texObj, target, level);
1257
1258#if 0
1259   if (border)
1260      goto fail;
1261#endif
1262
1263   /* Setup or redefine the texture object, texture and texture
1264    * image.  Don't populate yet.
1265    */
1266   ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
1267                          width, border,
1268                          GL_RGBA, CHAN_TYPE, NULL,
1269                          &ctx->DefaultPacking, texObj, texImage);
1270
1271   do_copy_texsubimage(ctx, target, level,
1272                       0, 0, 0,
1273                       x, y, width, 1);
1274}
1275
1276
1277static void
1278st_CopyTexImage2D(GLcontext * ctx, GLenum target, GLint level,
1279                  GLenum internalFormat,
1280                  GLint x, GLint y, GLsizei width, GLsizei height,
1281                  GLint border)
1282{
1283   struct gl_texture_unit *texUnit =
1284      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1285   struct gl_texture_object *texObj =
1286      _mesa_select_tex_object(ctx, texUnit, target);
1287   struct gl_texture_image *texImage =
1288      _mesa_select_tex_image(ctx, texObj, target, level);
1289
1290#if 0
1291   if (border)
1292      goto fail;
1293#endif
1294
1295   /* Setup or redefine the texture object, texture and texture
1296    * image.  Don't populate yet.
1297    */
1298   ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
1299                          width, height, border,
1300                          GL_RGBA, CHAN_TYPE, NULL,
1301                          &ctx->DefaultPacking, texObj, texImage);
1302
1303
1304   do_copy_texsubimage(ctx, target, level,
1305                       0, 0, 0,
1306                       x, y, width, height);
1307}
1308
1309
1310static void
1311st_CopyTexSubImage1D(GLcontext * ctx, GLenum target, GLint level,
1312                     GLint xoffset, GLint x, GLint y, GLsizei width)
1313{
1314   const GLint yoffset = 0, zoffset = 0;
1315   const GLsizei height = 1;
1316   do_copy_texsubimage(ctx, target, level,
1317                       xoffset, yoffset, zoffset,
1318                       x, y, width, height);
1319}
1320
1321
1322static void
1323st_CopyTexSubImage2D(GLcontext * ctx, GLenum target, GLint level,
1324                     GLint xoffset, GLint yoffset,
1325                     GLint x, GLint y, GLsizei width, GLsizei height)
1326{
1327   const GLint zoffset = 0;
1328   do_copy_texsubimage(ctx, target, level,
1329                       xoffset, yoffset, zoffset,
1330                       x, y, width, height);
1331}
1332
1333
1334static void
1335st_CopyTexSubImage3D(GLcontext * ctx, GLenum target, GLint level,
1336                     GLint xoffset, GLint yoffset, GLint zoffset,
1337                     GLint x, GLint y, GLsizei width, GLsizei height)
1338{
1339   do_copy_texsubimage(ctx, target, level,
1340                       xoffset, yoffset, zoffset,
1341                       x, y, width, height);
1342}
1343
1344
1345
1346
1347/**
1348 * Compute which mipmap levels that really need to be sent to the hardware.
1349 * This depends on the base image size, GL_TEXTURE_MIN_LOD,
1350 * GL_TEXTURE_MAX_LOD, GL_TEXTURE_BASE_LEVEL, and GL_TEXTURE_MAX_LEVEL.
1351 */
1352static void
1353calculate_first_last_level(struct st_texture_object *stObj)
1354{
1355   struct gl_texture_object *tObj = &stObj->base;
1356
1357   /* These must be signed values.  MinLod and MaxLod can be negative numbers,
1358    * and having firstLevel and lastLevel as signed prevents the need for
1359    * extra sign checks.
1360    */
1361   int firstLevel;
1362   int lastLevel;
1363
1364   /* Yes, this looks overly complicated, but it's all needed.
1365    */
1366   switch (tObj->Target) {
1367   case GL_TEXTURE_1D:
1368   case GL_TEXTURE_2D:
1369   case GL_TEXTURE_3D:
1370   case GL_TEXTURE_CUBE_MAP:
1371      if (tObj->MinFilter == GL_NEAREST || tObj->MinFilter == GL_LINEAR) {
1372         /* GL_NEAREST and GL_LINEAR only care about GL_TEXTURE_BASE_LEVEL.
1373          */
1374         firstLevel = lastLevel = tObj->BaseLevel;
1375      }
1376      else {
1377         firstLevel = 0;
1378         lastLevel = MIN2(tObj->MaxLevel, tObj->Image[0][tObj->BaseLevel]->WidthLog2);
1379      }
1380      break;
1381   case GL_TEXTURE_RECTANGLE_NV:
1382   case GL_TEXTURE_4D_SGIS:
1383      firstLevel = lastLevel = 0;
1384      break;
1385   default:
1386      return;
1387   }
1388
1389   stObj->lastLevel = lastLevel;
1390}
1391
1392
1393static void
1394copy_image_data_to_texture(struct st_context *st,
1395			   struct st_texture_object *stObj,
1396                           GLuint dstLevel,
1397			   struct st_texture_image *stImage)
1398{
1399   if (stImage->pt) {
1400      /* Copy potentially with the blitter:
1401       */
1402      st_texture_image_copy(st->pipe,
1403                            stObj->pt, dstLevel,  /* dest texture, level */
1404                            stImage->pt, /* src texture */
1405                            stImage->face
1406                            );
1407
1408      pipe_texture_release(&stImage->pt);
1409   }
1410   else if (stImage->base.Data) {
1411      assert(stImage->base.Data != NULL);
1412
1413      /* More straightforward upload.
1414       */
1415      st_texture_image_data(st->pipe,
1416                               stObj->pt,
1417                               stImage->face,
1418                               dstLevel,
1419                               stImage->base.Data,
1420                               stImage->base.RowStride,
1421                               stImage->base.RowStride *
1422                               stImage->base.Height);
1423      _mesa_align_free(stImage->base.Data);
1424      stImage->base.Data = NULL;
1425   }
1426
1427   pipe_texture_reference(&stImage->pt, stObj->pt);
1428}
1429
1430
1431/**
1432 * Called during state validation.  When this function is finished,
1433 * the texture object should be ready for rendering.
1434 * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
1435 */
1436GLboolean
1437st_finalize_texture(GLcontext *ctx,
1438		    struct pipe_context *pipe,
1439		    struct gl_texture_object *tObj,
1440		    GLboolean *needFlush)
1441{
1442   struct st_texture_object *stObj = st_texture_object(tObj);
1443   const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
1444   int comp_byte = 0;
1445   int cpp;
1446   GLuint face;
1447   struct st_texture_image *firstImage;
1448
1449   *needFlush = GL_FALSE;
1450
1451   /* We know/require this is true by now:
1452    */
1453   assert(stObj->base._Complete);
1454
1455   /* What levels must the texture include at a minimum?
1456    */
1457   calculate_first_last_level(stObj);
1458   firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
1459
1460   /* If both firstImage and stObj point to a texture which can contain
1461    * all active images, favour firstImage.  Note that because of the
1462    * completeness requirement, we know that the image dimensions
1463    * will match.
1464    */
1465   if (firstImage->pt &&
1466       firstImage->pt != stObj->pt &&
1467       firstImage->pt->last_level >= stObj->lastLevel) {
1468
1469      if (stObj->pt)
1470         pipe_texture_release(&stObj->pt);
1471
1472      pipe_texture_reference(&stObj->pt, firstImage->pt);
1473   }
1474
1475   if (firstImage->base.IsCompressed) {
1476      comp_byte = compressed_num_bytes(firstImage->base.TexFormat->MesaFormat);
1477      cpp = comp_byte;
1478   }
1479   else {
1480      cpp = firstImage->base.TexFormat->TexelBytes;
1481   }
1482
1483   /* If we already have a gallium texture, check that it matches the texture
1484    * object's format, target, size, num_levels, etc.
1485    */
1486   if (stObj->pt) {
1487      const enum pipe_format fmt =
1488         st_mesa_format_to_pipe_format(firstImage->base.TexFormat->MesaFormat);
1489      if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
1490          stObj->pt->format != fmt ||
1491          stObj->pt->last_level < stObj->lastLevel ||
1492          stObj->pt->width[0] != firstImage->base.Width2 ||
1493          stObj->pt->height[0] != firstImage->base.Height2 ||
1494          stObj->pt->depth[0] != firstImage->base.Depth2 ||
1495          stObj->pt->cpp != cpp ||
1496          stObj->pt->compressed != firstImage->base.IsCompressed) {
1497         pipe_texture_release(&stObj->pt);
1498      }
1499   }
1500
1501   /* May need to create a new gallium texture:
1502    */
1503   if (!stObj->pt) {
1504      stObj->pt = st_texture_create(ctx->st,
1505                                    gl_target_to_pipe(stObj->base.Target),
1506                                    st_mesa_format_to_pipe_format(firstImage->base.TexFormat->MesaFormat),
1507                                    stObj->lastLevel,
1508                                    firstImage->base.Width2,
1509                                    firstImage->base.Height2,
1510                                    firstImage->base.Depth2,
1511                                    comp_byte,
1512
1513                                    ( PIPE_TEXTURE_USAGE_RENDER_TARGET |
1514                                      PIPE_TEXTURE_USAGE_SAMPLER ));
1515
1516      if (!stObj->pt) {
1517         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
1518         return GL_FALSE;
1519      }
1520   }
1521
1522   /* Pull in any images not in the object's texture:
1523    */
1524   for (face = 0; face < nr_faces; face++) {
1525      GLuint level;
1526      for (level = 0; level <= stObj->lastLevel; level++) {
1527         struct st_texture_image *stImage =
1528            st_texture_image(stObj->base.Image[face][stObj->base.BaseLevel + level]);
1529
1530         /* Need to import images in main memory or held in other textures.
1531          */
1532         if (stImage && stObj->pt != stImage->pt) {
1533            copy_image_data_to_texture(ctx->st, stObj, level, stImage);
1534	    *needFlush = GL_TRUE;
1535         }
1536      }
1537   }
1538
1539   return GL_TRUE;
1540}
1541
1542
1543
1544
1545void
1546st_init_texture_functions(struct dd_function_table *functions)
1547{
1548   functions->ChooseTextureFormat = st_ChooseTextureFormat;
1549   functions->TexImage1D = st_TexImage1D;
1550   functions->TexImage2D = st_TexImage2D;
1551   functions->TexImage3D = st_TexImage3D;
1552   functions->TexSubImage1D = st_TexSubImage1D;
1553   functions->TexSubImage2D = st_TexSubImage2D;
1554   functions->TexSubImage3D = st_TexSubImage3D;
1555   functions->CopyTexImage1D = st_CopyTexImage1D;
1556   functions->CopyTexImage2D = st_CopyTexImage2D;
1557   functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
1558   functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
1559   functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
1560   functions->GenerateMipmap = st_generate_mipmap;
1561
1562   functions->GetTexImage = st_GetTexImage;
1563
1564   /* compressed texture functions */
1565   functions->CompressedTexImage2D = st_CompressedTexImage2D;
1566   functions->GetCompressedTexImage = st_GetCompressedTexImage;
1567   functions->CompressedTextureSize = _mesa_compressed_texture_size;
1568
1569   functions->NewTextureObject = st_NewTextureObject;
1570   functions->NewTextureImage = st_NewTextureImage;
1571   functions->DeleteTexture = st_DeleteTextureObject;
1572   functions->FreeTexImageData = st_FreeTextureImageData;
1573   functions->UpdateTexturePalette = 0;
1574   functions->IsTextureResident = st_IsTextureResident;
1575
1576   functions->TextureMemCpy = do_memcpy;
1577
1578   /* XXX Temporary until we can query pipe's texture sizes */
1579   functions->TestProxyTexImage = _mesa_test_proxy_teximage;
1580}
1581