OSDN Git Service

Merge branch 'mesa_7_5_branch'
[android-x86/external-mesa.git] / src / mesa / main / texobj.c
1 /**
2  * \file texobj.c
3  * Texture object management.
4  */
5
6 /*
7  * Mesa 3-D graphics library
8  * Version:  7.1
9  *
10  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a
13  * copy of this software and associated documentation files (the "Software"),
14  * to deal in the Software without restriction, including without limitation
15  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16  * and/or sell copies of the Software, and to permit persons to whom the
17  * Software is furnished to do so, subject to the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be included
20  * in all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
25  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
26  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28  */
29
30
31 #include "mfeatures.h"
32 #if FEATURE_colortable
33 #include "colortab.h"
34 #endif
35 #include "context.h"
36 #include "enums.h"
37 #include "fbobject.h"
38 #include "hash.h"
39 #include "imports.h"
40 #include "macros.h"
41 #include "teximage.h"
42 #include "texstate.h"
43 #include "texobj.h"
44 #include "mtypes.h"
45 #include "shader/prog_instruction.h"
46
47
48
49 /**********************************************************************/
50 /** \name Internal functions */
51 /*@{*/
52
53
54 /**
55  * Return the gl_texture_object for a given ID.
56  */
57 struct gl_texture_object *
58 _mesa_lookup_texture(GLcontext *ctx, GLuint id)
59 {
60    return (struct gl_texture_object *)
61       _mesa_HashLookup(ctx->Shared->TexObjects, id);
62 }
63
64
65
66 /**
67  * Allocate and initialize a new texture object.  But don't put it into the
68  * texture object hash table.
69  *
70  * Called via ctx->Driver.NewTextureObject, unless overridden by a device
71  * driver.
72  * 
73  * \param shared the shared GL state structure to contain the texture object
74  * \param name integer name for the texture object
75  * \param target either GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D,
76  * GL_TEXTURE_CUBE_MAP_ARB or GL_TEXTURE_RECTANGLE_NV.  zero is ok for the sake
77  * of GenTextures()
78  *
79  * \return pointer to new texture object.
80  */
81 struct gl_texture_object *
82 _mesa_new_texture_object( GLcontext *ctx, GLuint name, GLenum target )
83 {
84    struct gl_texture_object *obj;
85    (void) ctx;
86    obj = MALLOC_STRUCT(gl_texture_object);
87    _mesa_initialize_texture_object(obj, name, target);
88    return obj;
89 }
90
91
92 /**
93  * Initialize a new texture object to default values.
94  * \param obj  the texture object
95  * \param name  the texture name
96  * \param target  the texture target
97  */
98 void
99 _mesa_initialize_texture_object( struct gl_texture_object *obj,
100                                  GLuint name, GLenum target )
101 {
102    ASSERT(target == 0 ||
103           target == GL_TEXTURE_1D ||
104           target == GL_TEXTURE_2D ||
105           target == GL_TEXTURE_3D ||
106           target == GL_TEXTURE_CUBE_MAP_ARB ||
107           target == GL_TEXTURE_RECTANGLE_NV ||
108           target == GL_TEXTURE_1D_ARRAY_EXT ||
109           target == GL_TEXTURE_2D_ARRAY_EXT);
110
111    _mesa_bzero(obj, sizeof(*obj));
112    /* init the non-zero fields */
113    _glthread_INIT_MUTEX(obj->Mutex);
114    obj->RefCount = 1;
115    obj->Name = name;
116    obj->Target = target;
117    obj->Priority = 1.0F;
118    if (target == GL_TEXTURE_RECTANGLE_NV) {
119       obj->WrapS = GL_CLAMP_TO_EDGE;
120       obj->WrapT = GL_CLAMP_TO_EDGE;
121       obj->WrapR = GL_CLAMP_TO_EDGE;
122       obj->MinFilter = GL_LINEAR;
123    }
124    else {
125       obj->WrapS = GL_REPEAT;
126       obj->WrapT = GL_REPEAT;
127       obj->WrapR = GL_REPEAT;
128       obj->MinFilter = GL_NEAREST_MIPMAP_LINEAR;
129    }
130    obj->MagFilter = GL_LINEAR;
131    obj->MinLod = -1000.0;
132    obj->MaxLod = 1000.0;
133    obj->LodBias = 0.0;
134    obj->BaseLevel = 0;
135    obj->MaxLevel = 1000;
136    obj->MaxAnisotropy = 1.0;
137    obj->CompareMode = GL_NONE;         /* ARB_shadow */
138    obj->CompareFunc = GL_LEQUAL;       /* ARB_shadow */
139    obj->CompareFailValue = 0.0F;       /* ARB_shadow_ambient */
140    obj->DepthMode = GL_LUMINANCE;      /* ARB_depth_texture */
141    obj->Swizzle[0] = GL_RED;
142    obj->Swizzle[1] = GL_GREEN;
143    obj->Swizzle[2] = GL_BLUE;
144    obj->Swizzle[3] = GL_ALPHA;
145    obj->_Swizzle = SWIZZLE_NOOP;
146 }
147
148
149 /**
150  * Some texture initialization can't be finished until we know which
151  * target it's getting bound to (GL_TEXTURE_1D/2D/etc).
152  */
153 static void
154 finish_texture_init(GLcontext *ctx, GLenum target,
155                     struct gl_texture_object *obj)
156 {
157    assert(obj->Target == 0);
158
159    if (target == GL_TEXTURE_RECTANGLE_NV) {
160       /* have to init wrap and filter state here - kind of klunky */
161       obj->WrapS = GL_CLAMP_TO_EDGE;
162       obj->WrapT = GL_CLAMP_TO_EDGE;
163       obj->WrapR = GL_CLAMP_TO_EDGE;
164       obj->MinFilter = GL_LINEAR;
165       if (ctx->Driver.TexParameter) {
166          static const GLfloat fparam_wrap[1] = {(GLfloat) GL_CLAMP_TO_EDGE};
167          static const GLfloat fparam_filter[1] = {(GLfloat) GL_LINEAR};
168          ctx->Driver.TexParameter(ctx, target, obj, GL_TEXTURE_WRAP_S, fparam_wrap);
169          ctx->Driver.TexParameter(ctx, target, obj, GL_TEXTURE_WRAP_T, fparam_wrap);
170          ctx->Driver.TexParameter(ctx, target, obj, GL_TEXTURE_WRAP_R, fparam_wrap);
171          ctx->Driver.TexParameter(ctx, target, obj, GL_TEXTURE_MIN_FILTER, fparam_filter);
172       }
173    }
174 }
175
176
177 /**
178  * Deallocate a texture object struct.  It should have already been
179  * removed from the texture object pool.
180  * Called via ctx->Driver.DeleteTexture() if not overriden by a driver.
181  *
182  * \param shared the shared GL state to which the object belongs.
183  * \param texObj the texture object to delete.
184  */
185 void
186 _mesa_delete_texture_object( GLcontext *ctx, struct gl_texture_object *texObj )
187 {
188    GLuint i, face;
189
190    (void) ctx;
191
192    /* Set Target to an invalid value.  With some assertions elsewhere
193     * we can try to detect possible use of deleted textures.
194     */
195    texObj->Target = 0x99;
196
197 #if FEATURE_colortable
198    _mesa_free_colortable_data(&texObj->Palette);
199 #endif
200
201    /* free the texture images */
202    for (face = 0; face < 6; face++) {
203       for (i = 0; i < MAX_TEXTURE_LEVELS; i++) {
204          if (texObj->Image[face][i]) {
205             _mesa_delete_texture_image( ctx, texObj->Image[face][i] );
206          }
207       }
208    }
209
210    /* destroy the mutex -- it may have allocated memory (eg on bsd) */
211    _glthread_DESTROY_MUTEX(texObj->Mutex);
212
213    /* free this object */
214    _mesa_free(texObj);
215 }
216
217
218
219
220 /**
221  * Copy texture object state from one texture object to another.
222  * Use for glPush/PopAttrib.
223  *
224  * \param dest destination texture object.
225  * \param src source texture object.
226  */
227 void
228 _mesa_copy_texture_object( struct gl_texture_object *dest,
229                            const struct gl_texture_object *src )
230 {
231    dest->Target = src->Target;
232    dest->Name = src->Name;
233    dest->Priority = src->Priority;
234    dest->BorderColor[0] = src->BorderColor[0];
235    dest->BorderColor[1] = src->BorderColor[1];
236    dest->BorderColor[2] = src->BorderColor[2];
237    dest->BorderColor[3] = src->BorderColor[3];
238    dest->WrapS = src->WrapS;
239    dest->WrapT = src->WrapT;
240    dest->WrapR = src->WrapR;
241    dest->MinFilter = src->MinFilter;
242    dest->MagFilter = src->MagFilter;
243    dest->MinLod = src->MinLod;
244    dest->MaxLod = src->MaxLod;
245    dest->LodBias = src->LodBias;
246    dest->BaseLevel = src->BaseLevel;
247    dest->MaxLevel = src->MaxLevel;
248    dest->MaxAnisotropy = src->MaxAnisotropy;
249    dest->CompareMode = src->CompareMode;
250    dest->CompareFunc = src->CompareFunc;
251    dest->CompareFailValue = src->CompareFailValue;
252    dest->DepthMode = src->DepthMode;
253    dest->_MaxLevel = src->_MaxLevel;
254    dest->_MaxLambda = src->_MaxLambda;
255    dest->GenerateMipmap = src->GenerateMipmap;
256    dest->Palette = src->Palette;
257    dest->_Complete = src->_Complete;
258    COPY_4V(dest->Swizzle, src->Swizzle);
259    dest->_Swizzle = src->_Swizzle;
260 }
261
262
263 /**
264  * Check if the given texture object is valid by examining its Target field.
265  * For debugging only.
266  */
267 static GLboolean
268 valid_texture_object(const struct gl_texture_object *tex)
269 {
270    switch (tex->Target) {
271    case 0:
272    case GL_TEXTURE_1D:
273    case GL_TEXTURE_2D:
274    case GL_TEXTURE_3D:
275    case GL_TEXTURE_CUBE_MAP_ARB:
276    case GL_TEXTURE_RECTANGLE_NV:
277    case GL_TEXTURE_1D_ARRAY_EXT:
278    case GL_TEXTURE_2D_ARRAY_EXT:
279       return GL_TRUE;
280    case 0x99:
281       _mesa_problem(NULL, "invalid reference to a deleted texture object");
282       return GL_FALSE;
283    default:
284       _mesa_problem(NULL, "invalid texture object Target 0x%x, Id = %u",
285                     tex->Target, tex->Name);
286       return GL_FALSE;
287    }
288 }
289
290
291 /**
292  * Reference (or unreference) a texture object.
293  * If '*ptr', decrement *ptr's refcount (and delete if it becomes zero).
294  * If 'tex' is non-null, increment its refcount.
295  */
296 void
297 _mesa_reference_texobj(struct gl_texture_object **ptr,
298                        struct gl_texture_object *tex)
299 {
300    assert(ptr);
301    if (*ptr == tex) {
302       /* no change */
303       return;
304    }
305
306    if (*ptr) {
307       /* Unreference the old texture */
308       GLboolean deleteFlag = GL_FALSE;
309       struct gl_texture_object *oldTex = *ptr;
310
311       assert(valid_texture_object(oldTex));
312
313       _glthread_LOCK_MUTEX(oldTex->Mutex);
314       ASSERT(oldTex->RefCount > 0);
315       oldTex->RefCount--;
316
317       deleteFlag = (oldTex->RefCount == 0);
318       _glthread_UNLOCK_MUTEX(oldTex->Mutex);
319
320       if (deleteFlag) {
321          GET_CURRENT_CONTEXT(ctx);
322          if (ctx)
323             ctx->Driver.DeleteTexture(ctx, oldTex);
324          else
325             _mesa_problem(NULL, "Unable to delete texture, no context");
326       }
327
328       *ptr = NULL;
329    }
330    assert(!*ptr);
331
332    if (tex) {
333       /* reference new texture */
334       assert(valid_texture_object(tex));
335       _glthread_LOCK_MUTEX(tex->Mutex);
336       if (tex->RefCount == 0) {
337          /* this texture's being deleted (look just above) */
338          /* Not sure this can every really happen.  Warn if it does. */
339          _mesa_problem(NULL, "referencing deleted texture object");
340          *ptr = NULL;
341       }
342       else {
343          tex->RefCount++;
344          *ptr = tex;
345       }
346       _glthread_UNLOCK_MUTEX(tex->Mutex);
347    }
348 }
349
350
351
352 /**
353  * Report why a texture object is incomplete.  
354  *
355  * \param t texture object.
356  * \param why string describing why it's incomplete.
357  *
358  * \note For debug purposes only.
359  */
360 #if 0
361 static void
362 incomplete(const struct gl_texture_object *t, const char *why)
363 {
364    _mesa_printf("Texture Obj %d incomplete because: %s\n", t->Name, why);
365 }
366 #else
367 #define incomplete(t, why)
368 #endif
369
370
371 /**
372  * Examine a texture object to determine if it is complete.
373  *
374  * The gl_texture_object::Complete flag will be set to GL_TRUE or GL_FALSE
375  * accordingly.
376  *
377  * \param ctx GL context.
378  * \param t texture object.
379  *
380  * According to the texture target, verifies that each of the mipmaps is
381  * present and has the expected size.
382  */
383 void
384 _mesa_test_texobj_completeness( const GLcontext *ctx,
385                                 struct gl_texture_object *t )
386 {
387    const GLint baseLevel = t->BaseLevel;
388    GLint maxLog2 = 0, maxLevels = 0;
389
390    t->_Complete = GL_TRUE;  /* be optimistic */
391
392    /* Detect cases where the application set the base level to an invalid
393     * value.
394     */
395    if ((baseLevel < 0) || (baseLevel > MAX_TEXTURE_LEVELS)) {
396       char s[100];
397       _mesa_sprintf(s, "base level = %d is invalid", baseLevel);
398       incomplete(t, s);
399       t->_Complete = GL_FALSE;
400       return;
401    }
402
403    /* Always need the base level image */
404    if (!t->Image[0][baseLevel]) {
405       char s[100];
406       _mesa_sprintf(s, "Image[baseLevel=%d] == NULL", baseLevel);
407       incomplete(t, s);
408       t->_Complete = GL_FALSE;
409       return;
410    }
411
412    /* Check width/height/depth for zero */
413    if (t->Image[0][baseLevel]->Width == 0 ||
414        t->Image[0][baseLevel]->Height == 0 ||
415        t->Image[0][baseLevel]->Depth == 0) {
416       incomplete(t, "texture width = 0");
417       t->_Complete = GL_FALSE;
418       return;
419    }
420
421    /* Compute _MaxLevel */
422    if ((t->Target == GL_TEXTURE_1D) ||
423        (t->Target == GL_TEXTURE_1D_ARRAY_EXT)) {
424       maxLog2 = t->Image[0][baseLevel]->WidthLog2;
425       maxLevels = ctx->Const.MaxTextureLevels;
426    }
427    else if ((t->Target == GL_TEXTURE_2D) ||
428             (t->Target == GL_TEXTURE_2D_ARRAY_EXT)) {
429       maxLog2 = MAX2(t->Image[0][baseLevel]->WidthLog2,
430                      t->Image[0][baseLevel]->HeightLog2);
431       maxLevels = ctx->Const.MaxTextureLevels;
432    }
433    else if (t->Target == GL_TEXTURE_3D) {
434       GLint max = MAX2(t->Image[0][baseLevel]->WidthLog2,
435                        t->Image[0][baseLevel]->HeightLog2);
436       maxLog2 = MAX2(max, (GLint)(t->Image[0][baseLevel]->DepthLog2));
437       maxLevels = ctx->Const.Max3DTextureLevels;
438    }
439    else if (t->Target == GL_TEXTURE_CUBE_MAP_ARB) {
440       maxLog2 = MAX2(t->Image[0][baseLevel]->WidthLog2,
441                      t->Image[0][baseLevel]->HeightLog2);
442       maxLevels = ctx->Const.MaxCubeTextureLevels;
443    }
444    else if (t->Target == GL_TEXTURE_RECTANGLE_NV) {
445       maxLog2 = 0;  /* not applicable */
446       maxLevels = 1;  /* no mipmapping */
447    }
448    else {
449       _mesa_problem(ctx, "Bad t->Target in _mesa_test_texobj_completeness");
450       return;
451    }
452
453    ASSERT(maxLevels > 0);
454
455    t->_MaxLevel = baseLevel + maxLog2;
456    t->_MaxLevel = MIN2(t->_MaxLevel, t->MaxLevel);
457    t->_MaxLevel = MIN2(t->_MaxLevel, maxLevels - 1);
458
459    /* Compute _MaxLambda = q - b (see the 1.2 spec) used during mipmapping */
460    t->_MaxLambda = (GLfloat) (t->_MaxLevel - t->BaseLevel);
461
462    if (t->Target == GL_TEXTURE_CUBE_MAP_ARB) {
463       /* make sure that all six cube map level 0 images are the same size */
464       const GLuint w = t->Image[0][baseLevel]->Width2;
465       const GLuint h = t->Image[0][baseLevel]->Height2;
466       GLuint face;
467       for (face = 1; face < 6; face++) {
468          if (t->Image[face][baseLevel] == NULL ||
469              t->Image[face][baseLevel]->Width2 != w ||
470              t->Image[face][baseLevel]->Height2 != h) {
471             t->_Complete = GL_FALSE;
472             incomplete(t, "Non-quare cubemap image");
473             return;
474          }
475       }
476    }
477
478    /* extra checking for mipmaps */
479    if (t->MinFilter != GL_NEAREST && t->MinFilter != GL_LINEAR) {
480       /*
481        * Mipmapping: determine if we have a complete set of mipmaps
482        */
483       GLint i;
484       GLint minLevel = baseLevel;
485       GLint maxLevel = t->_MaxLevel;
486
487       if (minLevel > maxLevel) {
488          t->_Complete = GL_FALSE;
489          incomplete(t, "minLevel > maxLevel");
490          return;
491       }
492
493       /* Test dimension-independent attributes */
494       for (i = minLevel; i <= maxLevel; i++) {
495          if (t->Image[0][i]) {
496             if (t->Image[0][i]->TexFormat != t->Image[0][baseLevel]->TexFormat) {
497                t->_Complete = GL_FALSE;
498                incomplete(t, "Format[i] != Format[baseLevel]");
499                return;
500             }
501             if (t->Image[0][i]->Border != t->Image[0][baseLevel]->Border) {
502                t->_Complete = GL_FALSE;
503                incomplete(t, "Border[i] != Border[baseLevel]");
504                return;
505             }
506          }
507       }
508
509       /* Test things which depend on number of texture image dimensions */
510       if ((t->Target == GL_TEXTURE_1D) ||
511           (t->Target == GL_TEXTURE_1D_ARRAY_EXT)) {
512          /* Test 1-D mipmaps */
513          GLuint width = t->Image[0][baseLevel]->Width2;
514          for (i = baseLevel + 1; i < maxLevels; i++) {
515             if (width > 1) {
516                width /= 2;
517             }
518             if (i >= minLevel && i <= maxLevel) {
519                if (!t->Image[0][i]) {
520                   t->_Complete = GL_FALSE;
521                   incomplete(t, "1D Image[0][i] == NULL");
522                   return;
523                }
524                if (t->Image[0][i]->Width2 != width ) {
525                   t->_Complete = GL_FALSE;
526                   incomplete(t, "1D Image[0][i] bad width");
527                   return;
528                }
529             }
530             if (width == 1) {
531                return;  /* found smallest needed mipmap, all done! */
532             }
533          }
534       }
535       else if ((t->Target == GL_TEXTURE_2D) ||
536                (t->Target == GL_TEXTURE_2D_ARRAY_EXT)) {
537          /* Test 2-D mipmaps */
538          GLuint width = t->Image[0][baseLevel]->Width2;
539          GLuint height = t->Image[0][baseLevel]->Height2;
540          for (i = baseLevel + 1; i < maxLevels; i++) {
541             if (width > 1) {
542                width /= 2;
543             }
544             if (height > 1) {
545                height /= 2;
546             }
547             if (i >= minLevel && i <= maxLevel) {
548                if (!t->Image[0][i]) {
549                   t->_Complete = GL_FALSE;
550                   incomplete(t, "2D Image[0][i] == NULL");
551                   return;
552                }
553                if (t->Image[0][i]->Width2 != width) {
554                   t->_Complete = GL_FALSE;
555                   incomplete(t, "2D Image[0][i] bad width");
556                   return;
557                }
558                if (t->Image[0][i]->Height2 != height) {
559                   t->_Complete = GL_FALSE;
560                   incomplete(t, "2D Image[0][i] bad height");
561                   return;
562                }
563                if (width==1 && height==1) {
564                   return;  /* found smallest needed mipmap, all done! */
565                }
566             }
567          }
568       }
569       else if (t->Target == GL_TEXTURE_3D) {
570          /* Test 3-D mipmaps */
571          GLuint width = t->Image[0][baseLevel]->Width2;
572          GLuint height = t->Image[0][baseLevel]->Height2;
573          GLuint depth = t->Image[0][baseLevel]->Depth2;
574          for (i = baseLevel + 1; i < maxLevels; i++) {
575             if (width > 1) {
576                width /= 2;
577             }
578             if (height > 1) {
579                height /= 2;
580             }
581             if (depth > 1) {
582                depth /= 2;
583             }
584             if (i >= minLevel && i <= maxLevel) {
585                if (!t->Image[0][i]) {
586                   incomplete(t, "3D Image[0][i] == NULL");
587                   t->_Complete = GL_FALSE;
588                   return;
589                }
590                if (t->Image[0][i]->_BaseFormat == GL_DEPTH_COMPONENT) {
591                   t->_Complete = GL_FALSE;
592                   incomplete(t, "GL_DEPTH_COMPONENT only works with 1/2D tex");
593                   return;
594                }
595                if (t->Image[0][i]->Width2 != width) {
596                   t->_Complete = GL_FALSE;
597                   incomplete(t, "3D Image[0][i] bad width");
598                   return;
599                }
600                if (t->Image[0][i]->Height2 != height) {
601                   t->_Complete = GL_FALSE;
602                   incomplete(t, "3D Image[0][i] bad height");
603                   return;
604                }
605                if (t->Image[0][i]->Depth2 != depth) {
606                   t->_Complete = GL_FALSE;
607                   incomplete(t, "3D Image[0][i] bad depth");
608                   return;
609                }
610             }
611             if (width == 1 && height == 1 && depth == 1) {
612                return;  /* found smallest needed mipmap, all done! */
613             }
614          }
615       }
616       else if (t->Target == GL_TEXTURE_CUBE_MAP_ARB) {
617          /* make sure 6 cube faces are consistant */
618          GLuint width = t->Image[0][baseLevel]->Width2;
619          GLuint height = t->Image[0][baseLevel]->Height2;
620          for (i = baseLevel + 1; i < maxLevels; i++) {
621             if (width > 1) {
622                width /= 2;
623             }
624             if (height > 1) {
625                height /= 2;
626             }
627             if (i >= minLevel && i <= maxLevel) {
628                GLuint face;
629                for (face = 0; face < 6; face++) {
630                   /* check that we have images defined */
631                   if (!t->Image[face][i]) {
632                      t->_Complete = GL_FALSE;
633                      incomplete(t, "CubeMap Image[n][i] == NULL");
634                      return;
635                   }
636                   /* Don't support GL_DEPTH_COMPONENT for cube maps */
637                   if (t->Image[face][i]->_BaseFormat == GL_DEPTH_COMPONENT) {
638                      t->_Complete = GL_FALSE;
639                      incomplete(t, "GL_DEPTH_COMPONENT only works with 1/2D tex");
640                      return;
641                   }
642                   /* check that all six images have same size */
643                   if (t->Image[face][i]->Width2!=width || 
644                       t->Image[face][i]->Height2!=height) {
645                      t->_Complete = GL_FALSE;
646                      incomplete(t, "CubeMap Image[n][i] bad size");
647                      return;
648                   }
649                }
650             }
651             if (width == 1 && height == 1) {
652                return;  /* found smallest needed mipmap, all done! */
653             }
654          }
655       }
656       else if (t->Target == GL_TEXTURE_RECTANGLE_NV) {
657          /* XXX special checking? */
658       }
659       else {
660          /* Target = ??? */
661          _mesa_problem(ctx, "Bug in gl_test_texture_object_completeness\n");
662       }
663    }
664 }
665
666
667 /**
668  * Return pointer to a default/fallback texture.
669  * The texture is a 2D 8x8 RGBA texture with all texels = (0,0,0,1).
670  * That's the value a sampler should get when sampling from an
671  * incomplete texture.
672  */
673 struct gl_texture_object *
674 _mesa_get_fallback_texture(GLcontext *ctx)
675 {
676    if (!ctx->Shared->FallbackTex) {
677       /* create fallback texture now */
678       static GLubyte texels[8 * 8][4];
679       struct gl_texture_object *texObj;
680       struct gl_texture_image *texImage;
681       GLuint i;
682
683       for (i = 0; i < 8 * 8; i++) {
684          texels[i][0] =
685          texels[i][1] =
686          texels[i][2] = 0x0;
687          texels[i][3] = 0xff;
688       }
689
690       /* create texture object */
691       texObj = ctx->Driver.NewTextureObject(ctx, 0, GL_TEXTURE_2D);
692       assert(texObj->RefCount == 1);
693       texObj->MinFilter = GL_NEAREST;
694       texObj->MagFilter = GL_NEAREST;
695
696       /* create level[0] texture image */
697       texImage = _mesa_get_tex_image(ctx, texObj, GL_TEXTURE_2D, 0);
698
699       /* init the image fields */
700       _mesa_init_teximage_fields(ctx, GL_TEXTURE_2D, texImage,
701                                     8, 8, 1, 0, GL_RGBA); 
702
703       /* set image data */
704       ctx->Driver.TexImage2D(ctx, GL_TEXTURE_2D, 0, GL_RGBA,
705                              8, 8, 0,
706                              GL_RGBA, GL_UNSIGNED_BYTE, texels,
707                              &ctx->DefaultPacking, texObj, texImage);
708
709       _mesa_test_texobj_completeness(ctx, texObj);
710       assert(texObj->_Complete);
711
712       ctx->Shared->FallbackTex = texObj;
713    }
714    return ctx->Shared->FallbackTex;
715 }
716
717
718
719 /*@}*/
720
721
722 /***********************************************************************/
723 /** \name API functions */
724 /*@{*/
725
726
727 /**
728  * Generate texture names.
729  *
730  * \param n number of texture names to be generated.
731  * \param textures an array in which will hold the generated texture names.
732  *
733  * \sa glGenTextures().
734  *
735  * Calls _mesa_HashFindFreeKeyBlock() to find a block of free texture
736  * IDs which are stored in \p textures.  Corresponding empty texture
737  * objects are also generated.
738  */ 
739 void GLAPIENTRY
740 _mesa_GenTextures( GLsizei n, GLuint *textures )
741 {
742    GET_CURRENT_CONTEXT(ctx);
743    GLuint first;
744    GLint i;
745    ASSERT_OUTSIDE_BEGIN_END(ctx);
746
747    if (n < 0) {
748       _mesa_error( ctx, GL_INVALID_VALUE, "glGenTextures" );
749       return;
750    }
751
752    if (!textures)
753       return;
754
755    /*
756     * This must be atomic (generation and allocation of texture IDs)
757     */
758    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
759
760    first = _mesa_HashFindFreeKeyBlock(ctx->Shared->TexObjects, n);
761
762    /* Allocate new, empty texture objects */
763    for (i = 0; i < n; i++) {
764       struct gl_texture_object *texObj;
765       GLuint name = first + i;
766       GLenum target = 0;
767       texObj = (*ctx->Driver.NewTextureObject)( ctx, name, target);
768       if (!texObj) {
769          _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
770          _mesa_error(ctx, GL_OUT_OF_MEMORY, "glGenTextures");
771          return;
772       }
773
774       /* insert into hash table */
775       _mesa_HashInsert(ctx->Shared->TexObjects, texObj->Name, texObj);
776
777       textures[i] = name;
778    }
779
780    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
781 }
782
783
784 /**
785  * Check if the given texture object is bound to the current draw or
786  * read framebuffer.  If so, Unbind it.
787  */
788 static void
789 unbind_texobj_from_fbo(GLcontext *ctx, struct gl_texture_object *texObj)
790 {
791    const GLuint n = (ctx->DrawBuffer == ctx->ReadBuffer) ? 1 : 2;
792    GLuint i;
793
794    for (i = 0; i < n; i++) {
795       struct gl_framebuffer *fb = (i == 0) ? ctx->DrawBuffer : ctx->ReadBuffer;
796       if (fb->Name) {
797          GLuint j;
798          for (j = 0; j < BUFFER_COUNT; j++) {
799             if (fb->Attachment[j].Type == GL_TEXTURE &&
800                 fb->Attachment[j].Texture == texObj) {
801                _mesa_remove_attachment(ctx, fb->Attachment + j);         
802             }
803          }
804       }
805    }
806 }
807
808
809 /**
810  * Check if the given texture object is bound to any texture image units and
811  * unbind it if so (revert to default textures).
812  */
813 static void
814 unbind_texobj_from_texunits(GLcontext *ctx, struct gl_texture_object *texObj)
815 {
816    GLuint u, tex;
817
818    for (u = 0; u < MAX_TEXTURE_IMAGE_UNITS; u++) {
819       struct gl_texture_unit *unit = &ctx->Texture.Unit[u];
820       for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
821          if (texObj == unit->CurrentTex[tex]) {
822             _mesa_reference_texobj(&unit->CurrentTex[tex],
823                                    ctx->Shared->DefaultTex[TEXTURE_1D_INDEX]);
824             ASSERT(unit->CurrentTex[tex]);
825             break;
826          }
827       }
828    }
829 }
830
831
832 /**
833  * Delete named textures.
834  *
835  * \param n number of textures to be deleted.
836  * \param textures array of texture IDs to be deleted.
837  *
838  * \sa glDeleteTextures().
839  *
840  * If we're about to delete a texture that's currently bound to any
841  * texture unit, unbind the texture first.  Decrement the reference
842  * count on the texture object and delete it if it's zero.
843  * Recall that texture objects can be shared among several rendering
844  * contexts.
845  */
846 void GLAPIENTRY
847 _mesa_DeleteTextures( GLsizei n, const GLuint *textures)
848 {
849    GET_CURRENT_CONTEXT(ctx);
850    GLint i;
851    ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); /* too complex */
852
853    if (!textures)
854       return;
855
856    for (i = 0; i < n; i++) {
857       if (textures[i] > 0) {
858          struct gl_texture_object *delObj
859             = _mesa_lookup_texture(ctx, textures[i]);
860
861          if (delObj) {
862             _mesa_lock_texture(ctx, delObj);
863
864             /* Check if texture is bound to any framebuffer objects.
865              * If so, unbind.
866              * See section 4.4.2.3 of GL_EXT_framebuffer_object.
867              */
868             unbind_texobj_from_fbo(ctx, delObj);
869
870             /* Check if this texture is currently bound to any texture units.
871              * If so, unbind it.
872              */
873             unbind_texobj_from_texunits(ctx, delObj);
874
875             _mesa_unlock_texture(ctx, delObj);
876
877             ctx->NewState |= _NEW_TEXTURE;
878
879             /* The texture _name_ is now free for re-use.
880              * Remove it from the hash table now.
881              */
882             _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
883             _mesa_HashRemove(ctx->Shared->TexObjects, delObj->Name);
884             _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
885
886             /* Unreference the texobj.  If refcount hits zero, the texture
887              * will be deleted.
888              */
889             _mesa_reference_texobj(&delObj, NULL);
890          }
891       }
892    }
893 }
894
895
896 /**
897  * Convert a GL texture target enum such as GL_TEXTURE_2D or GL_TEXTURE_3D
898  * into the corresponding Mesa texture target index.
899  * Return -1 if target is invalid.
900  */
901 static GLint
902 target_enum_to_index(GLenum target)
903 {
904    switch (target) {
905    case GL_TEXTURE_1D:
906       return TEXTURE_1D_INDEX;
907    case GL_TEXTURE_2D:
908       return TEXTURE_2D_INDEX;
909    case GL_TEXTURE_3D:
910       return TEXTURE_3D_INDEX;
911    case GL_TEXTURE_CUBE_MAP_ARB:
912       return TEXTURE_CUBE_INDEX;
913    case GL_TEXTURE_RECTANGLE_NV:
914       return TEXTURE_RECT_INDEX;
915    case GL_TEXTURE_1D_ARRAY_EXT:
916       return TEXTURE_1D_ARRAY_INDEX;
917    case GL_TEXTURE_2D_ARRAY_EXT:
918       return TEXTURE_2D_ARRAY_INDEX;
919    default:
920       return -1;
921    }
922 }
923
924
925 /**
926  * Bind a named texture to a texturing target.
927  * 
928  * \param target texture target.
929  * \param texName texture name.
930  * 
931  * \sa glBindTexture().
932  *
933  * Determines the old texture object bound and returns immediately if rebinding
934  * the same texture.  Get the current texture which is either a default texture
935  * if name is null, a named texture from the hash, or a new texture if the
936  * given texture name is new. Increments its reference count, binds it, and
937  * calls dd_function_table::BindTexture. Decrements the old texture reference
938  * count and deletes it if it reaches zero.
939  */
940 void GLAPIENTRY
941 _mesa_BindTexture( GLenum target, GLuint texName )
942 {
943    GET_CURRENT_CONTEXT(ctx);
944    const GLuint unit = ctx->Texture.CurrentUnit;
945    struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
946    struct gl_texture_object *newTexObj = NULL, *defaultTexObj = NULL;
947    GLint targetIndex;
948    GLboolean early_out = GL_FALSE;
949    ASSERT_OUTSIDE_BEGIN_END(ctx);
950
951    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
952       _mesa_debug(ctx, "glBindTexture %s %d\n",
953                   _mesa_lookup_enum_by_nr(target), (GLint) texName);
954
955    targetIndex = target_enum_to_index(target);
956    if (targetIndex < 0) {
957       _mesa_error(ctx, GL_INVALID_ENUM, "glBindTexture(target)");
958       return;
959    }
960    assert(targetIndex < NUM_TEXTURE_TARGETS);
961    defaultTexObj = ctx->Shared->DefaultTex[targetIndex];
962
963    /*
964     * Get pointer to new texture object (newTexObj)
965     */
966    if (texName == 0) {
967       newTexObj = defaultTexObj;
968    }
969    else {
970       /* non-default texture object */
971       newTexObj = _mesa_lookup_texture(ctx, texName);
972       if (newTexObj) {
973          /* error checking */
974          if (newTexObj->Target != 0 && newTexObj->Target != target) {
975             /* the named texture object's target doesn't match the given target */
976             _mesa_error( ctx, GL_INVALID_OPERATION,
977                          "glBindTexture(target mismatch)" );
978             return;
979          }
980          if (newTexObj->Target == 0) {
981             finish_texture_init(ctx, target, newTexObj);
982          }
983       }
984       else {
985          /* if this is a new texture id, allocate a texture object now */
986          newTexObj = (*ctx->Driver.NewTextureObject)(ctx, texName, target);
987          if (!newTexObj) {
988             _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindTexture");
989             return;
990          }
991
992          /* and insert it into hash table */
993          _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
994          _mesa_HashInsert(ctx->Shared->TexObjects, texName, newTexObj);
995          _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
996       }
997       newTexObj->Target = target;
998    }
999
1000    assert(valid_texture_object(newTexObj));
1001
1002    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
1003    if ((ctx->Shared->RefCount == 1)
1004        && (newTexObj == texUnit->CurrentTex[targetIndex])) {
1005       early_out = GL_TRUE;
1006    }
1007    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
1008
1009    if (early_out) {
1010       return;
1011    }
1012
1013    /* flush before changing binding */
1014    FLUSH_VERTICES(ctx, _NEW_TEXTURE);
1015
1016    /* Do the actual binding.  The refcount on the previously bound
1017     * texture object will be decremented.  It'll be deleted if the
1018     * count hits zero.
1019     */
1020    _mesa_reference_texobj(&texUnit->CurrentTex[targetIndex], newTexObj);
1021    ASSERT(texUnit->CurrentTex[targetIndex]);
1022
1023    /* Pass BindTexture call to device driver */
1024    if (ctx->Driver.BindTexture)
1025       (*ctx->Driver.BindTexture)( ctx, target, newTexObj );
1026 }
1027
1028
1029 /**
1030  * Set texture priorities.
1031  * 
1032  * \param n number of textures.
1033  * \param texName texture names.
1034  * \param priorities corresponding texture priorities.
1035  * 
1036  * \sa glPrioritizeTextures().
1037  * 
1038  * Looks up each texture in the hash, clamps the corresponding priority between
1039  * 0.0 and 1.0, and calls dd_function_table::PrioritizeTexture.
1040  */
1041 void GLAPIENTRY
1042 _mesa_PrioritizeTextures( GLsizei n, const GLuint *texName,
1043                           const GLclampf *priorities )
1044 {
1045    GET_CURRENT_CONTEXT(ctx);
1046    GLint i;
1047    ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
1048
1049    if (n < 0) {
1050       _mesa_error( ctx, GL_INVALID_VALUE, "glPrioritizeTextures" );
1051       return;
1052    }
1053
1054    if (!priorities)
1055       return;
1056
1057    for (i = 0; i < n; i++) {
1058       if (texName[i] > 0) {
1059          struct gl_texture_object *t = _mesa_lookup_texture(ctx, texName[i]);
1060          if (t) {
1061             t->Priority = CLAMP( priorities[i], 0.0F, 1.0F );
1062             if (ctx->Driver.PrioritizeTexture)
1063                ctx->Driver.PrioritizeTexture( ctx, t, t->Priority );
1064          }
1065       }
1066    }
1067
1068    ctx->NewState |= _NEW_TEXTURE;
1069 }
1070
1071 /**
1072  * See if textures are loaded in texture memory.
1073  * 
1074  * \param n number of textures to query.
1075  * \param texName array with the texture names.
1076  * \param residences array which will hold the residence status.
1077  *
1078  * \return GL_TRUE if all textures are resident and \p residences is left unchanged, 
1079  * 
1080  * \sa glAreTexturesResident().
1081  *
1082  * Looks up each texture in the hash and calls
1083  * dd_function_table::IsTextureResident.
1084  */
1085 GLboolean GLAPIENTRY
1086 _mesa_AreTexturesResident(GLsizei n, const GLuint *texName,
1087                           GLboolean *residences)
1088 {
1089    GET_CURRENT_CONTEXT(ctx);
1090    GLboolean allResident = GL_TRUE;
1091    GLint i, j;
1092    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1093
1094    if (n < 0) {
1095       _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident(n)");
1096       return GL_FALSE;
1097    }
1098
1099    if (!texName || !residences)
1100       return GL_FALSE;
1101
1102    for (i = 0; i < n; i++) {
1103       struct gl_texture_object *t;
1104       if (texName[i] == 0) {
1105          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
1106          return GL_FALSE;
1107       }
1108       t = _mesa_lookup_texture(ctx, texName[i]);
1109       if (!t) {
1110          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
1111          return GL_FALSE;
1112       }
1113       if (!ctx->Driver.IsTextureResident ||
1114           ctx->Driver.IsTextureResident(ctx, t)) {
1115          /* The texture is resident */
1116          if (!allResident)
1117             residences[i] = GL_TRUE;
1118       }
1119       else {
1120          /* The texture is not resident */
1121          if (allResident) {
1122             allResident = GL_FALSE;
1123             for (j = 0; j < i; j++)
1124                residences[j] = GL_TRUE;
1125          }
1126          residences[i] = GL_FALSE;
1127       }
1128    }
1129    
1130    return allResident;
1131 }
1132
1133 /**
1134  * See if a name corresponds to a texture.
1135  *
1136  * \param texture texture name.
1137  *
1138  * \return GL_TRUE if texture name corresponds to a texture, or GL_FALSE
1139  * otherwise.
1140  * 
1141  * \sa glIsTexture().
1142  *
1143  * Calls _mesa_HashLookup().
1144  */
1145 GLboolean GLAPIENTRY
1146 _mesa_IsTexture( GLuint texture )
1147 {
1148    struct gl_texture_object *t;
1149    GET_CURRENT_CONTEXT(ctx);
1150    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1151
1152    if (!texture)
1153       return GL_FALSE;
1154
1155    t = _mesa_lookup_texture(ctx, texture);
1156
1157    /* IsTexture is true only after object has been bound once. */
1158    return t && t->Target;
1159 }
1160
1161
1162 /**
1163  * Simplest implementation of texture locking: Grab the a new mutex in
1164  * the shared context.  Examine the shared context state timestamp and
1165  * if there has been a change, set the appropriate bits in
1166  * ctx->NewState.
1167  *
1168  * This is used to deal with synchronizing things when a texture object
1169  * is used/modified by different contexts (or threads) which are sharing
1170  * the texture.
1171  *
1172  * See also _mesa_lock/unlock_texture() in teximage.h
1173  */
1174 void
1175 _mesa_lock_context_textures( GLcontext *ctx )
1176 {
1177    _glthread_LOCK_MUTEX(ctx->Shared->TexMutex);
1178
1179    if (ctx->Shared->TextureStateStamp != ctx->TextureStateTimestamp) {
1180       ctx->NewState |= _NEW_TEXTURE;
1181       ctx->TextureStateTimestamp = ctx->Shared->TextureStateStamp;
1182    }
1183 }
1184
1185
1186 void
1187 _mesa_unlock_context_textures( GLcontext *ctx )
1188 {
1189    assert(ctx->Shared->TextureStateStamp == ctx->TextureStateTimestamp);
1190    _glthread_UNLOCK_MUTEX(ctx->Shared->TexMutex);
1191 }
1192
1193 /*@}*/
1194
1195