OSDN Git Service

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