1 /**
2  * \file texobj.c
3  * Texture object management.
4  */
5 
6 /*
7  * Mesa 3-D graphics library
8  *
9  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included
19  * in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
25  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27  * OTHER DEALINGS IN THE SOFTWARE.
28  */
29 
30 
31 #include <stdio.h>
32 #include "bufferobj.h"
33 #include "context.h"
34 #include "enums.h"
35 #include "fbobject.h"
36 #include "formats.h"
37 #include "hash.h"
38 
39 #include "macros.h"
40 #include "shaderimage.h"
41 #include "teximage.h"
42 #include "texobj.h"
43 #include "texstate.h"
44 #include "mtypes.h"
45 #include "program/prog_instruction.h"
46 #include "texturebindless.h"
47 #include "util/u_memory.h"
48 #include "util/u_inlines.h"
49 #include "api_exec_decl.h"
50 
51 #include "state_tracker/st_cb_texture.h"
52 #include "state_tracker/st_context.h"
53 #include "state_tracker/st_format.h"
54 #include "state_tracker/st_cb_flush.h"
55 #include "state_tracker/st_texture.h"
56 #include "state_tracker/st_sampler_view.h"
57 
58 /**********************************************************************/
59 /** \name Internal functions */
60 /*@{*/
61 
62 /**
63  * This function checks for all valid combinations of Min and Mag filters for
64  * Float types, when extensions like OES_texture_float and
65  * OES_texture_float_linear are supported. OES_texture_float mentions support
66  * for NEAREST, NEAREST_MIPMAP_NEAREST magnification and minification filters.
67  * Mag filters like LINEAR and min filters like NEAREST_MIPMAP_LINEAR,
68  * LINEAR_MIPMAP_NEAREST and LINEAR_MIPMAP_LINEAR are only valid in case
69  * OES_texture_float_linear is supported.
70  *
71  * Returns true in case the filter is valid for given Float type else false.
72  */
73 static bool
valid_filter_for_float(const struct gl_context * ctx,const struct gl_texture_object * obj)74 valid_filter_for_float(const struct gl_context *ctx,
75                        const struct gl_texture_object *obj)
76 {
77    switch (obj->Sampler.Attrib.MagFilter) {
78    case GL_LINEAR:
79       if (obj->_IsHalfFloat && !ctx->Extensions.OES_texture_half_float_linear) {
80          return false;
81       } else if (obj->_IsFloat && !ctx->Extensions.OES_texture_float_linear) {
82          return false;
83       }
84       FALLTHROUGH;
85    case GL_NEAREST:
86    case GL_NEAREST_MIPMAP_NEAREST:
87       break;
88    default:
89       unreachable("Invalid mag filter");
90    }
91 
92    switch (obj->Sampler.Attrib.MinFilter) {
93    case GL_LINEAR:
94    case GL_NEAREST_MIPMAP_LINEAR:
95    case GL_LINEAR_MIPMAP_NEAREST:
96    case GL_LINEAR_MIPMAP_LINEAR:
97       if (obj->_IsHalfFloat && !ctx->Extensions.OES_texture_half_float_linear) {
98          return false;
99       } else if (obj->_IsFloat && !ctx->Extensions.OES_texture_float_linear) {
100          return false;
101       }
102       FALLTHROUGH;
103    case GL_NEAREST:
104    case GL_NEAREST_MIPMAP_NEAREST:
105       break;
106    default:
107       unreachable("Invalid min filter");
108    }
109 
110    return true;
111 }
112 
113 /**
114  * Return the gl_texture_object for a given ID.
115  */
116 struct gl_texture_object *
_mesa_lookup_texture(struct gl_context * ctx,GLuint id)117 _mesa_lookup_texture(struct gl_context *ctx, GLuint id)
118 {
119    return (struct gl_texture_object *)
120       _mesa_HashLookup(ctx->Shared->TexObjects, id);
121 }
122 
123 /**
124  * Wrapper around _mesa_lookup_texture that throws GL_INVALID_OPERATION if id
125  * is not in the hash table. After calling _mesa_error, it returns NULL.
126  */
127 struct gl_texture_object *
_mesa_lookup_texture_err(struct gl_context * ctx,GLuint id,const char * func)128 _mesa_lookup_texture_err(struct gl_context *ctx, GLuint id, const char* func)
129 {
130    struct gl_texture_object *texObj = NULL;
131 
132    if (id > 0)
133       texObj = _mesa_lookup_texture(ctx, id); /* Returns NULL if not found. */
134 
135    if (!texObj)
136       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(texture)", func);
137 
138    return texObj;
139 }
140 
141 
142 struct gl_texture_object *
_mesa_lookup_texture_locked(struct gl_context * ctx,GLuint id)143 _mesa_lookup_texture_locked(struct gl_context *ctx, GLuint id)
144 {
145    return (struct gl_texture_object *)
146       _mesa_HashLookupLocked(ctx->Shared->TexObjects, id);
147 }
148 
149 /**
150  * Return a pointer to the current texture object for the given target
151  * on the current texture unit.
152  * Note: all <target> error checking should have been done by this point.
153  */
154 struct gl_texture_object *
_mesa_get_current_tex_object(struct gl_context * ctx,GLenum target)155 _mesa_get_current_tex_object(struct gl_context *ctx, GLenum target)
156 {
157    struct gl_texture_unit *texUnit = _mesa_get_current_tex_unit(ctx);
158    const GLboolean arrayTex = ctx->Extensions.EXT_texture_array;
159 
160    switch (target) {
161       case GL_TEXTURE_1D:
162          return texUnit->CurrentTex[TEXTURE_1D_INDEX];
163       case GL_PROXY_TEXTURE_1D:
164          return ctx->Texture.ProxyTex[TEXTURE_1D_INDEX];
165       case GL_TEXTURE_2D:
166          return texUnit->CurrentTex[TEXTURE_2D_INDEX];
167       case GL_PROXY_TEXTURE_2D:
168          return ctx->Texture.ProxyTex[TEXTURE_2D_INDEX];
169       case GL_TEXTURE_3D:
170          return texUnit->CurrentTex[TEXTURE_3D_INDEX];
171       case GL_PROXY_TEXTURE_3D:
172          return ctx->Texture.ProxyTex[TEXTURE_3D_INDEX];
173       case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
174       case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
175       case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
176       case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
177       case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
178       case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
179       case GL_TEXTURE_CUBE_MAP:
180          return texUnit->CurrentTex[TEXTURE_CUBE_INDEX];
181       case GL_PROXY_TEXTURE_CUBE_MAP:
182          return ctx->Texture.ProxyTex[TEXTURE_CUBE_INDEX];
183       case GL_TEXTURE_CUBE_MAP_ARRAY:
184          return _mesa_has_texture_cube_map_array(ctx)
185                 ? texUnit->CurrentTex[TEXTURE_CUBE_ARRAY_INDEX] : NULL;
186       case GL_PROXY_TEXTURE_CUBE_MAP_ARRAY:
187          return _mesa_has_texture_cube_map_array(ctx)
188                 ? ctx->Texture.ProxyTex[TEXTURE_CUBE_ARRAY_INDEX] : NULL;
189       case GL_TEXTURE_RECTANGLE_NV:
190          return ctx->Extensions.NV_texture_rectangle
191                 ? texUnit->CurrentTex[TEXTURE_RECT_INDEX] : NULL;
192       case GL_PROXY_TEXTURE_RECTANGLE_NV:
193          return ctx->Extensions.NV_texture_rectangle
194                 ? ctx->Texture.ProxyTex[TEXTURE_RECT_INDEX] : NULL;
195       case GL_TEXTURE_1D_ARRAY_EXT:
196          return arrayTex ? texUnit->CurrentTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
197       case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
198          return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
199       case GL_TEXTURE_2D_ARRAY_EXT:
200          return arrayTex ? texUnit->CurrentTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
201       case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
202          return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
203       case GL_TEXTURE_BUFFER:
204          return (_mesa_has_ARB_texture_buffer_object(ctx) ||
205                  _mesa_has_OES_texture_buffer(ctx)) ?
206                 texUnit->CurrentTex[TEXTURE_BUFFER_INDEX] : NULL;
207       case GL_TEXTURE_EXTERNAL_OES:
208          return _mesa_is_gles(ctx) && ctx->Extensions.OES_EGL_image_external
209             ? texUnit->CurrentTex[TEXTURE_EXTERNAL_INDEX] : NULL;
210       case GL_TEXTURE_2D_MULTISAMPLE:
211          return ctx->Extensions.ARB_texture_multisample
212             ? texUnit->CurrentTex[TEXTURE_2D_MULTISAMPLE_INDEX] : NULL;
213       case GL_PROXY_TEXTURE_2D_MULTISAMPLE:
214          return ctx->Extensions.ARB_texture_multisample
215             ? ctx->Texture.ProxyTex[TEXTURE_2D_MULTISAMPLE_INDEX] : NULL;
216       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
217          return ctx->Extensions.ARB_texture_multisample
218             ? texUnit->CurrentTex[TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX] : NULL;
219       case GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY:
220          return ctx->Extensions.ARB_texture_multisample
221             ? ctx->Texture.ProxyTex[TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX] : NULL;
222       default:
223          _mesa_problem(NULL, "bad target in _mesa_get_current_tex_object(): 0x%04x", target);
224          return NULL;
225    }
226 }
227 
228 
229 /**
230  * Get the texture object for given target and texunit
231  * Proxy targets are accepted only allowProxyTarget is true.
232  * Return NULL if any error (and record the error).
233  */
234 struct gl_texture_object *
_mesa_get_texobj_by_target_and_texunit(struct gl_context * ctx,GLenum target,GLuint texunit,bool allowProxyTarget,const char * caller)235 _mesa_get_texobj_by_target_and_texunit(struct gl_context *ctx, GLenum target,
236                                        GLuint texunit, bool allowProxyTarget,
237                                        const char* caller)
238 {
239    struct gl_texture_unit *texUnit;
240    int targetIndex;
241 
242    if (_mesa_is_proxy_texture(target) && allowProxyTarget) {
243       return _mesa_get_current_tex_object(ctx, target);
244    }
245 
246    if (texunit >= ctx->Const.MaxCombinedTextureImageUnits) {
247       _mesa_error(ctx, GL_INVALID_OPERATION,
248                   "%s(texunit=%d)", caller, texunit);
249       return NULL;
250    }
251 
252    texUnit = _mesa_get_tex_unit(ctx, texunit);
253 
254    targetIndex = _mesa_tex_target_to_index(ctx, target);
255    if (targetIndex < 0 || targetIndex == TEXTURE_BUFFER_INDEX) {
256       _mesa_error(ctx, GL_INVALID_ENUM, "%s(target)", caller);
257       return NULL;
258    }
259    assert(targetIndex < NUM_TEXTURE_TARGETS);
260 
261    return texUnit->CurrentTex[targetIndex];
262 }
263 
264 
265 /**
266  * Initialize a new texture object to default values.
267  * \param obj  the texture object
268  * \param name  the texture name
269  * \param target  the texture target
270  */
271 static bool
_mesa_initialize_texture_object(struct gl_context * ctx,struct gl_texture_object * obj,GLuint name,GLenum target)272 _mesa_initialize_texture_object( struct gl_context *ctx,
273                                  struct gl_texture_object *obj,
274                                  GLuint name, GLenum target )
275 {
276    assert(target == 0 ||
277           target == GL_TEXTURE_1D ||
278           target == GL_TEXTURE_2D ||
279           target == GL_TEXTURE_3D ||
280           target == GL_TEXTURE_CUBE_MAP ||
281           target == GL_TEXTURE_RECTANGLE_NV ||
282           target == GL_TEXTURE_1D_ARRAY_EXT ||
283           target == GL_TEXTURE_2D_ARRAY_EXT ||
284           target == GL_TEXTURE_EXTERNAL_OES ||
285           target == GL_TEXTURE_CUBE_MAP_ARRAY ||
286           target == GL_TEXTURE_BUFFER ||
287           target == GL_TEXTURE_2D_MULTISAMPLE ||
288           target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
289 
290    memset(obj, 0, sizeof(*obj));
291    /* init the non-zero fields */
292    obj->RefCount = 1;
293    obj->Name = name;
294    obj->Target = target;
295    if (target != 0) {
296       obj->TargetIndex = _mesa_tex_target_to_index(ctx, target);
297    }
298    else {
299       obj->TargetIndex = NUM_TEXTURE_TARGETS; /* invalid/error value */
300    }
301    obj->Attrib.Priority = 1.0F;
302    obj->Attrib.BaseLevel = 0;
303    obj->Attrib.MaxLevel = 1000;
304 
305    /* must be one; no support for (YUV) planes in separate buffers */
306    obj->RequiredTextureImageUnits = 1;
307 
308    /* sampler state */
309    if (target == GL_TEXTURE_RECTANGLE_NV ||
310        target == GL_TEXTURE_EXTERNAL_OES) {
311       obj->Sampler.Attrib.WrapS = GL_CLAMP_TO_EDGE;
312       obj->Sampler.Attrib.WrapT = GL_CLAMP_TO_EDGE;
313       obj->Sampler.Attrib.WrapR = GL_CLAMP_TO_EDGE;
314       obj->Sampler.Attrib.MinFilter = GL_LINEAR;
315       obj->Sampler.Attrib.state.wrap_s = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
316       obj->Sampler.Attrib.state.wrap_t = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
317       obj->Sampler.Attrib.state.wrap_r = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
318       obj->Sampler.Attrib.state.min_img_filter = PIPE_TEX_FILTER_LINEAR;
319       obj->Sampler.Attrib.state.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
320    }
321    else {
322       obj->Sampler.Attrib.WrapS = GL_REPEAT;
323       obj->Sampler.Attrib.WrapT = GL_REPEAT;
324       obj->Sampler.Attrib.WrapR = GL_REPEAT;
325       obj->Sampler.Attrib.MinFilter = GL_NEAREST_MIPMAP_LINEAR;
326       obj->Sampler.Attrib.state.wrap_s = PIPE_TEX_WRAP_REPEAT;
327       obj->Sampler.Attrib.state.wrap_t = PIPE_TEX_WRAP_REPEAT;
328       obj->Sampler.Attrib.state.wrap_r = PIPE_TEX_WRAP_REPEAT;
329       obj->Sampler.Attrib.state.min_img_filter = PIPE_TEX_FILTER_NEAREST;
330       obj->Sampler.Attrib.state.min_mip_filter = PIPE_TEX_MIPFILTER_LINEAR;
331    }
332    obj->Sampler.Attrib.MagFilter = GL_LINEAR;
333    obj->Sampler.Attrib.state.mag_img_filter = PIPE_TEX_FILTER_LINEAR;
334    obj->Sampler.Attrib.MinLod = -1000.0;
335    obj->Sampler.Attrib.MaxLod = 1000.0;
336    obj->Sampler.Attrib.state.min_lod = 0; /* no negative numbers */
337    obj->Sampler.Attrib.state.max_lod = 1000;
338    obj->Sampler.Attrib.LodBias = 0.0;
339    obj->Sampler.Attrib.state.lod_bias = 0;
340    obj->Sampler.Attrib.MaxAnisotropy = 1.0;
341    obj->Sampler.Attrib.state.max_anisotropy = 0; /* gallium sets 0 instead of 1 */
342    obj->Sampler.Attrib.CompareMode = GL_NONE;         /* ARB_shadow */
343    obj->Sampler.Attrib.CompareFunc = GL_LEQUAL;       /* ARB_shadow */
344    obj->Sampler.Attrib.state.compare_mode = PIPE_TEX_COMPARE_NONE;
345    obj->Sampler.Attrib.state.compare_func = PIPE_FUNC_LEQUAL;
346    obj->Attrib.DepthMode = ctx->API == API_OPENGL_CORE ? GL_RED : GL_LUMINANCE;
347    obj->StencilSampling = false;
348    obj->Sampler.Attrib.CubeMapSeamless = GL_FALSE;
349    obj->Sampler.Attrib.state.seamless_cube_map = false;
350    obj->Sampler.HandleAllocated = GL_FALSE;
351    obj->Attrib.Swizzle[0] = GL_RED;
352    obj->Attrib.Swizzle[1] = GL_GREEN;
353    obj->Attrib.Swizzle[2] = GL_BLUE;
354    obj->Attrib.Swizzle[3] = GL_ALPHA;
355    obj->Attrib._Swizzle = SWIZZLE_NOOP;
356    obj->Sampler.Attrib.sRGBDecode = GL_DECODE_EXT;
357    obj->Sampler.Attrib.ReductionMode = GL_WEIGHTED_AVERAGE_EXT;
358    obj->Sampler.Attrib.state.reduction_mode = PIPE_TEX_REDUCTION_WEIGHTED_AVERAGE;
359    obj->BufferObjectFormat = ctx->API == API_OPENGL_COMPAT ? GL_LUMINANCE8 : GL_R8;
360    obj->_BufferObjectFormat = ctx->API == API_OPENGL_COMPAT
361       ? MESA_FORMAT_L_UNORM8 : MESA_FORMAT_R_UNORM8;
362    obj->Attrib.ImageFormatCompatibilityType = GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE;
363 
364    /* GL_ARB_bindless_texture */
365    _mesa_init_texture_handles(obj);
366 
367    obj->level_override = -1;
368    obj->layer_override = -1;
369    simple_mtx_init(&obj->validate_mutex, mtx_plain);
370    obj->needs_validation = true;
371    /* Pre-allocate a sampler views container to save a branch in the
372     * fast path.
373     */
374    obj->sampler_views = calloc(1, sizeof(struct st_sampler_views)
375                                + sizeof(struct st_sampler_view));
376    if (!obj->sampler_views) {
377       return false;
378    }
379    obj->sampler_views->max = 1;
380    return true;
381 }
382 
383 /**
384  * Allocate and initialize a new texture object.  But don't put it into the
385  * texture object hash table.
386  *
387  * \param shared the shared GL state structure to contain the texture object
388  * \param name integer name for the texture object
389  * \param target either GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D,
390  * GL_TEXTURE_CUBE_MAP or GL_TEXTURE_RECTANGLE_NV.  zero is ok for the sake
391  * of GenTextures()
392  *
393  * \return pointer to new texture object.
394  */
395 struct gl_texture_object *
_mesa_new_texture_object(struct gl_context * ctx,GLuint name,GLenum target)396 _mesa_new_texture_object(struct gl_context *ctx, GLuint name, GLenum target)
397 {
398    struct gl_texture_object *obj;
399 
400    obj = MALLOC_STRUCT(gl_texture_object);
401    if (!obj)
402       return NULL;
403 
404    if (!_mesa_initialize_texture_object(ctx, obj, name, target)) {
405       free(obj);
406       return NULL;
407    }
408    return obj;
409 }
410 
411 /**
412  * Some texture initialization can't be finished until we know which
413  * target it's getting bound to (GL_TEXTURE_1D/2D/etc).
414  */
415 static void
finish_texture_init(struct gl_context * ctx,GLenum target,struct gl_texture_object * obj,int targetIndex)416 finish_texture_init(struct gl_context *ctx, GLenum target,
417                     struct gl_texture_object *obj, int targetIndex)
418 {
419    GLenum filter = GL_LINEAR;
420    assert(obj->Target == 0);
421 
422    obj->Target = target;
423    obj->TargetIndex = targetIndex;
424    assert(obj->TargetIndex < NUM_TEXTURE_TARGETS);
425 
426    switch (target) {
427       case GL_TEXTURE_2D_MULTISAMPLE:
428       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
429          filter = GL_NEAREST;
430          FALLTHROUGH;
431 
432       case GL_TEXTURE_RECTANGLE_NV:
433       case GL_TEXTURE_EXTERNAL_OES:
434          /* have to init wrap and filter state here - kind of klunky */
435          obj->Sampler.Attrib.WrapS = GL_CLAMP_TO_EDGE;
436          obj->Sampler.Attrib.WrapT = GL_CLAMP_TO_EDGE;
437          obj->Sampler.Attrib.WrapR = GL_CLAMP_TO_EDGE;
438          obj->Sampler.Attrib.state.wrap_s = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
439          obj->Sampler.Attrib.state.wrap_t = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
440          obj->Sampler.Attrib.state.wrap_r = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
441          obj->Sampler.Attrib.MinFilter = filter;
442          obj->Sampler.Attrib.MagFilter = filter;
443          obj->Sampler.Attrib.state.min_img_filter = filter_to_gallium(filter);
444          obj->Sampler.Attrib.state.min_mip_filter = mipfilter_to_gallium(filter);
445          obj->Sampler.Attrib.state.mag_img_filter = filter_to_gallium(filter);
446          break;
447 
448       default:
449          /* nothing needs done */
450          break;
451    }
452 }
453 
454 
455 /**
456  * Deallocate a texture object struct.  It should have already been
457  * removed from the texture object pool.
458  *
459  * \param shared the shared GL state to which the object belongs.
460  * \param texObj the texture object to delete.
461  */
462 void
_mesa_delete_texture_object(struct gl_context * ctx,struct gl_texture_object * texObj)463 _mesa_delete_texture_object(struct gl_context *ctx,
464                             struct gl_texture_object *texObj)
465 {
466    GLuint i, face;
467 
468    /* Set Target to an invalid value.  With some assertions elsewhere
469     * we can try to detect possible use of deleted textures.
470     */
471    texObj->Target = 0x99;
472 
473    pipe_resource_reference(&texObj->pt, NULL);
474    st_delete_texture_sampler_views(ctx->st, texObj);
475    simple_mtx_destroy(&texObj->validate_mutex);
476 
477    /* free the texture images */
478    for (face = 0; face < 6; face++) {
479       for (i = 0; i < MAX_TEXTURE_LEVELS; i++) {
480          if (texObj->Image[face][i]) {
481             _mesa_delete_texture_image(ctx, texObj->Image[face][i]);
482          }
483       }
484    }
485 
486    /* Delete all texture/image handles. */
487    _mesa_delete_texture_handles(ctx, texObj);
488 
489    _mesa_reference_buffer_object_shared(ctx, &texObj->BufferObject, NULL);
490    free(texObj->Label);
491 
492    /* free this object */
493    FREE(texObj);
494 }
495 
496 
497 /**
498  * Free all texture images of the given texture objectm, except for
499  * \p retainTexImage.
500  *
501  * \param ctx GL context.
502  * \param texObj texture object.
503  * \param retainTexImage a texture image that will \em not be freed.
504  *
505  * \sa _mesa_clear_texture_image().
506  */
507 void
_mesa_clear_texture_object(struct gl_context * ctx,struct gl_texture_object * texObj,struct gl_texture_image * retainTexImage)508 _mesa_clear_texture_object(struct gl_context *ctx,
509                            struct gl_texture_object *texObj,
510                            struct gl_texture_image *retainTexImage)
511 {
512    GLuint i, j;
513 
514    if (texObj->Target == 0)
515       return;
516 
517    for (i = 0; i < MAX_FACES; i++) {
518       for (j = 0; j < MAX_TEXTURE_LEVELS; j++) {
519          struct gl_texture_image *texImage = texObj->Image[i][j];
520          if (texImage && texImage != retainTexImage)
521             _mesa_clear_texture_image(ctx, texImage);
522       }
523    }
524 }
525 
526 
527 /**
528  * Check if the given texture object is valid by examining its Target field.
529  * For debugging only.
530  */
531 static GLboolean
valid_texture_object(const struct gl_texture_object * tex)532 valid_texture_object(const struct gl_texture_object *tex)
533 {
534    switch (tex->Target) {
535    case 0:
536    case GL_TEXTURE_1D:
537    case GL_TEXTURE_2D:
538    case GL_TEXTURE_3D:
539    case GL_TEXTURE_CUBE_MAP:
540    case GL_TEXTURE_RECTANGLE_NV:
541    case GL_TEXTURE_1D_ARRAY_EXT:
542    case GL_TEXTURE_2D_ARRAY_EXT:
543    case GL_TEXTURE_BUFFER:
544    case GL_TEXTURE_EXTERNAL_OES:
545    case GL_TEXTURE_CUBE_MAP_ARRAY:
546    case GL_TEXTURE_2D_MULTISAMPLE:
547    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
548       return GL_TRUE;
549    case 0x99:
550       _mesa_problem(NULL, "invalid reference to a deleted texture object");
551       return GL_FALSE;
552    default:
553       _mesa_problem(NULL, "invalid texture object Target 0x%x, Id = %u",
554                     tex->Target, tex->Name);
555       return GL_FALSE;
556    }
557 }
558 
559 
560 /**
561  * Reference (or unreference) a texture object.
562  * If '*ptr', decrement *ptr's refcount (and delete if it becomes zero).
563  * If 'tex' is non-null, increment its refcount.
564  * This is normally only called from the _mesa_reference_texobj() macro
565  * when there's a real pointer change.
566  */
567 void
_mesa_reference_texobj_(struct gl_texture_object ** ptr,struct gl_texture_object * tex)568 _mesa_reference_texobj_(struct gl_texture_object **ptr,
569                         struct gl_texture_object *tex)
570 {
571    assert(ptr);
572 
573    if (*ptr) {
574       /* Unreference the old texture */
575       struct gl_texture_object *oldTex = *ptr;
576 
577       assert(valid_texture_object(oldTex));
578       (void) valid_texture_object; /* silence warning in release builds */
579 
580       assert(oldTex->RefCount > 0);
581 
582       if (p_atomic_dec_zero(&oldTex->RefCount)) {
583          /* Passing in the context drastically changes the driver code for
584           * framebuffer deletion.
585           */
586          GET_CURRENT_CONTEXT(ctx);
587          if (ctx)
588             _mesa_delete_texture_object(ctx, oldTex);
589          else
590             _mesa_problem(NULL, "Unable to delete texture, no context");
591       }
592    }
593 
594    if (tex) {
595       /* reference new texture */
596       assert(valid_texture_object(tex));
597       assert(tex->RefCount > 0);
598 
599       p_atomic_inc(&tex->RefCount);
600    }
601 
602    *ptr = tex;
603 }
604 
605 
606 enum base_mipmap { BASE, MIPMAP };
607 
608 
609 /**
610  * Mark a texture object as incomplete.  There are actually three kinds of
611  * (in)completeness:
612  * 1. "base incomplete": the base level of the texture is invalid so no
613  *    texturing is possible.
614  * 2. "mipmap incomplete": a non-base level of the texture is invalid so
615  *    mipmap filtering isn't possible, but non-mipmap filtering is.
616  * 3. "texture incompleteness": some combination of texture state and
617  *    sampler state renders the texture incomplete.
618  *
619  * \param t  texture object
620  * \param bm  either BASE or MIPMAP to indicate what's incomplete
621  * \param fmt...  string describing why it's incomplete (for debugging).
622  */
623 static void
incomplete(struct gl_texture_object * t,enum base_mipmap bm,const char * fmt,...)624 incomplete(struct gl_texture_object *t, enum base_mipmap bm,
625            const char *fmt, ...)
626 {
627    if (MESA_DEBUG_FLAGS & DEBUG_INCOMPLETE_TEXTURE) {
628       va_list args;
629       char s[100];
630 
631       va_start(args, fmt);
632       vsnprintf(s, sizeof(s), fmt, args);
633       va_end(args);
634 
635       _mesa_debug(NULL, "Texture Obj %d incomplete because: %s\n", t->Name, s);
636    }
637 
638    if (bm == BASE)
639       t->_BaseComplete = GL_FALSE;
640    t->_MipmapComplete = GL_FALSE;
641 }
642 
643 
644 /**
645  * Examine a texture object to determine if it is complete.
646  *
647  * The gl_texture_object::Complete flag will be set to GL_TRUE or GL_FALSE
648  * accordingly.
649  *
650  * \param ctx GL context.
651  * \param t texture object.
652  *
653  * According to the texture target, verifies that each of the mipmaps is
654  * present and has the expected size.
655  */
656 void
_mesa_test_texobj_completeness(const struct gl_context * ctx,struct gl_texture_object * t)657 _mesa_test_texobj_completeness( const struct gl_context *ctx,
658                                 struct gl_texture_object *t )
659 {
660    const GLint baseLevel = t->Attrib.BaseLevel;
661    const struct gl_texture_image *baseImage;
662    GLint maxLevels = 0;
663 
664    /* We'll set these to FALSE if tests fail below */
665    t->_BaseComplete = GL_TRUE;
666    t->_MipmapComplete = GL_TRUE;
667 
668    if (t->Target == GL_TEXTURE_BUFFER) {
669       /* Buffer textures are always considered complete.  The obvious case where
670        * they would be incomplete (no BO attached) is actually specced to be
671        * undefined rendering results.
672        */
673       return;
674    }
675 
676    /* Detect cases where the application set the base level to an invalid
677     * value.
678     */
679    if ((baseLevel < 0) || (baseLevel >= MAX_TEXTURE_LEVELS)) {
680       incomplete(t, BASE, "base level = %d is invalid", baseLevel);
681       return;
682    }
683 
684    if (t->Attrib.MaxLevel < baseLevel) {
685       incomplete(t, MIPMAP, "MAX_LEVEL (%d) < BASE_LEVEL (%d)",
686 		 t->Attrib.MaxLevel, baseLevel);
687       return;
688    }
689 
690    baseImage = t->Image[0][baseLevel];
691 
692    /* Always need the base level image */
693    if (!baseImage) {
694       incomplete(t, BASE, "Image[baseLevel=%d] == NULL", baseLevel);
695       return;
696    }
697 
698    /* Check width/height/depth for zero */
699    if (baseImage->Width == 0 ||
700        baseImage->Height == 0 ||
701        baseImage->Depth == 0) {
702       incomplete(t, BASE, "texture width or height or depth = 0");
703       return;
704    }
705 
706    /* Check if the texture values are integer */
707    {
708       GLenum datatype = _mesa_get_format_datatype(baseImage->TexFormat);
709       t->_IsIntegerFormat = datatype == GL_INT || datatype == GL_UNSIGNED_INT;
710    }
711 
712    /* Check if the texture type is Float or HalfFloatOES and ensure Min and Mag
713     * filters are supported in this case.
714     */
715    if (_mesa_is_gles(ctx) && !valid_filter_for_float(ctx, t)) {
716       incomplete(t, BASE, "Filter is not supported with Float types.");
717       return;
718    }
719 
720    maxLevels = _mesa_max_texture_levels(ctx, t->Target);
721    if (maxLevels == 0) {
722       _mesa_problem(ctx, "Bad t->Target in _mesa_test_texobj_completeness");
723       return;
724    }
725 
726    assert(maxLevels > 0);
727 
728    t->_MaxLevel = MIN3(t->Attrib.MaxLevel,
729                        /* 'p' in the GL spec */
730                        (int) (baseLevel + baseImage->MaxNumLevels - 1),
731                        /* 'q' in the GL spec */
732                        maxLevels - 1);
733 
734    if (t->Immutable) {
735       /* Adjust max level for views: the data store may have more levels than
736        * the view exposes.
737        */
738       t->_MaxLevel = MAX2(MIN2(t->_MaxLevel, t->Attrib.NumLevels - 1), 0);
739    }
740 
741    /* Compute _MaxLambda = q - p in the spec used during mipmapping */
742    t->_MaxLambda = (GLfloat) (t->_MaxLevel - baseLevel);
743 
744    if (t->Immutable) {
745       /* This texture object was created with glTexStorage1/2/3D() so we
746        * know that all the mipmap levels are the right size and all cube
747        * map faces are the same size.
748        * We don't need to do any of the additional checks below.
749        */
750       return;
751    }
752 
753    if (t->Target == GL_TEXTURE_CUBE_MAP) {
754       /* Make sure that all six cube map level 0 images are the same size and
755        * format.
756        * Note:  we know that the image's width==height (we enforce that
757        * at glTexImage time) so we only need to test the width here.
758        */
759       GLuint face;
760       assert(baseImage->Width2 == baseImage->Height);
761       for (face = 1; face < 6; face++) {
762          assert(t->Image[face][baseLevel] == NULL ||
763                 t->Image[face][baseLevel]->Width2 ==
764                 t->Image[face][baseLevel]->Height2);
765          if (t->Image[face][baseLevel] == NULL ||
766              t->Image[face][baseLevel]->Width2 != baseImage->Width2) {
767             incomplete(t, BASE, "Cube face missing or mismatched size");
768             return;
769          }
770          if (t->Image[face][baseLevel]->InternalFormat !=
771              baseImage->InternalFormat) {
772             incomplete(t, BASE, "Cube face format mismatch");
773             return;
774          }
775          if (t->Image[face][baseLevel]->Border != baseImage->Border) {
776             incomplete(t, BASE, "Cube face border size mismatch");
777             return;
778          }
779       }
780    }
781 
782    /*
783     * Do mipmap consistency checking.
784     * Note: we don't care about the current texture sampler state here.
785     * To determine texture completeness we'll either look at _BaseComplete
786     * or _MipmapComplete depending on the current minification filter mode.
787     */
788    {
789       GLint i;
790       const GLint minLevel = baseLevel;
791       const GLint maxLevel = t->_MaxLevel;
792       const GLuint numFaces = _mesa_num_tex_faces(t->Target);
793       GLuint width, height, depth, face;
794 
795       if (minLevel > maxLevel) {
796          incomplete(t, MIPMAP, "minLevel > maxLevel");
797          return;
798       }
799 
800       /* Get the base image's dimensions */
801       width = baseImage->Width2;
802       height = baseImage->Height2;
803       depth = baseImage->Depth2;
804 
805       /* Note: this loop will be a no-op for RECT, BUFFER, EXTERNAL,
806        * MULTISAMPLE and MULTISAMPLE_ARRAY textures
807        */
808       for (i = baseLevel + 1; i < maxLevels; i++) {
809          /* Compute the expected size of image at level[i] */
810          if (width > 1) {
811             width /= 2;
812          }
813          if (height > 1 && t->Target != GL_TEXTURE_1D_ARRAY) {
814             height /= 2;
815          }
816          if (depth > 1 && t->Target != GL_TEXTURE_2D_ARRAY
817              && t->Target != GL_TEXTURE_CUBE_MAP_ARRAY) {
818             depth /= 2;
819          }
820 
821          /* loop over cube faces (or single face otherwise) */
822          for (face = 0; face < numFaces; face++) {
823             if (i >= minLevel && i <= maxLevel) {
824                const struct gl_texture_image *img = t->Image[face][i];
825 
826                if (!img) {
827                   incomplete(t, MIPMAP, "TexImage[%d] is missing", i);
828                   return;
829                }
830                if (img->InternalFormat != baseImage->InternalFormat) {
831                   incomplete(t, MIPMAP, "Format[i] != Format[baseLevel]");
832                   return;
833                }
834                if (img->Border != baseImage->Border) {
835                   incomplete(t, MIPMAP, "Border[i] != Border[baseLevel]");
836                   return;
837                }
838                if (img->Width2 != width) {
839                   incomplete(t, MIPMAP, "TexImage[%d] bad width %u", i,
840                              img->Width2);
841                   return;
842                }
843                if (img->Height2 != height) {
844                   incomplete(t, MIPMAP, "TexImage[%d] bad height %u", i,
845                              img->Height2);
846                   return;
847                }
848                if (img->Depth2 != depth) {
849                   incomplete(t, MIPMAP, "TexImage[%d] bad depth %u", i,
850                              img->Depth2);
851                   return;
852                }
853             }
854          }
855 
856          if (width == 1 && height == 1 && depth == 1) {
857             return;  /* found smallest needed mipmap, all done! */
858          }
859       }
860    }
861 }
862 
863 
864 GLboolean
_mesa_cube_level_complete(const struct gl_texture_object * texObj,const GLint level)865 _mesa_cube_level_complete(const struct gl_texture_object *texObj,
866                           const GLint level)
867 {
868    const struct gl_texture_image *img0, *img;
869    GLuint face;
870 
871    if (texObj->Target != GL_TEXTURE_CUBE_MAP)
872       return GL_FALSE;
873 
874    if ((level < 0) || (level >= MAX_TEXTURE_LEVELS))
875       return GL_FALSE;
876 
877    /* check first face */
878    img0 = texObj->Image[0][level];
879    if (!img0 ||
880        img0->Width < 1 ||
881        img0->Width != img0->Height)
882       return GL_FALSE;
883 
884    /* check remaining faces vs. first face */
885    for (face = 1; face < 6; face++) {
886       img = texObj->Image[face][level];
887       if (!img ||
888           img->Width != img0->Width ||
889           img->Height != img0->Height ||
890           img->TexFormat != img0->TexFormat)
891          return GL_FALSE;
892    }
893 
894    return GL_TRUE;
895 }
896 
897 /**
898  * Check if the given cube map texture is "cube complete" as defined in
899  * the OpenGL specification.
900  */
901 GLboolean
_mesa_cube_complete(const struct gl_texture_object * texObj)902 _mesa_cube_complete(const struct gl_texture_object *texObj)
903 {
904    return _mesa_cube_level_complete(texObj, texObj->Attrib.BaseLevel);
905 }
906 
907 /**
908  * Mark a texture object dirty.  It forces the object to be incomplete
909  * and forces the context to re-validate its state.
910  *
911  * \param ctx GL context.
912  * \param texObj texture object.
913  */
914 void
_mesa_dirty_texobj(struct gl_context * ctx,struct gl_texture_object * texObj)915 _mesa_dirty_texobj(struct gl_context *ctx, struct gl_texture_object *texObj)
916 {
917    texObj->_BaseComplete = GL_FALSE;
918    texObj->_MipmapComplete = GL_FALSE;
919    ctx->NewState |= _NEW_TEXTURE_OBJECT;
920    ctx->PopAttribState |= GL_TEXTURE_BIT;
921 }
922 
923 
924 /**
925  * Return pointer to a default/fallback texture of the given type/target.
926  * The texture is an RGBA texture with all texels = (0,0,0,1).
927  * That's the value a GLSL sampler should get when sampling from an
928  * incomplete texture.
929  */
930 struct gl_texture_object *
_mesa_get_fallback_texture(struct gl_context * ctx,gl_texture_index tex)931 _mesa_get_fallback_texture(struct gl_context *ctx, gl_texture_index tex)
932 {
933    if (!ctx->Shared->FallbackTex[tex]) {
934       /* create fallback texture now */
935       const GLsizei width = 1, height = 1;
936       GLsizei depth = 1;
937       GLubyte texel[24];
938       struct gl_texture_object *texObj;
939       struct gl_texture_image *texImage;
940       mesa_format texFormat;
941       GLuint dims, face, numFaces = 1;
942       GLenum target;
943 
944       for (face = 0; face < 6; face++) {
945          texel[4*face + 0] =
946          texel[4*face + 1] =
947          texel[4*face + 2] = 0x0;
948          texel[4*face + 3] = 0xff;
949       }
950 
951       switch (tex) {
952       case TEXTURE_2D_ARRAY_INDEX:
953          dims = 3;
954          target = GL_TEXTURE_2D_ARRAY;
955          break;
956       case TEXTURE_1D_ARRAY_INDEX:
957          dims = 2;
958          target = GL_TEXTURE_1D_ARRAY;
959          break;
960       case TEXTURE_CUBE_INDEX:
961          dims = 2;
962          target = GL_TEXTURE_CUBE_MAP;
963          numFaces = 6;
964          break;
965       case TEXTURE_3D_INDEX:
966          dims = 3;
967          target = GL_TEXTURE_3D;
968          break;
969       case TEXTURE_RECT_INDEX:
970          dims = 2;
971          target = GL_TEXTURE_RECTANGLE;
972          break;
973       case TEXTURE_2D_INDEX:
974          dims = 2;
975          target = GL_TEXTURE_2D;
976          break;
977       case TEXTURE_1D_INDEX:
978          dims = 1;
979          target = GL_TEXTURE_1D;
980          break;
981       case TEXTURE_BUFFER_INDEX:
982          dims = 0;
983          target = GL_TEXTURE_BUFFER;
984          break;
985       case TEXTURE_CUBE_ARRAY_INDEX:
986          dims = 3;
987          target = GL_TEXTURE_CUBE_MAP_ARRAY;
988          depth = 6;
989          break;
990       case TEXTURE_EXTERNAL_INDEX:
991          dims = 2;
992          target = GL_TEXTURE_EXTERNAL_OES;
993          break;
994       case TEXTURE_2D_MULTISAMPLE_INDEX:
995          dims = 2;
996          target = GL_TEXTURE_2D_MULTISAMPLE;
997          break;
998       case TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX:
999          dims = 3;
1000          target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
1001          break;
1002       default:
1003          /* no-op */
1004          return NULL;
1005       }
1006 
1007       /* create texture object */
1008       texObj = _mesa_new_texture_object(ctx, 0, target);
1009       if (!texObj)
1010          return NULL;
1011 
1012       assert(texObj->RefCount == 1);
1013       texObj->Sampler.Attrib.MinFilter = GL_NEAREST;
1014       texObj->Sampler.Attrib.MagFilter = GL_NEAREST;
1015       texObj->Sampler.Attrib.state.min_img_filter = PIPE_TEX_FILTER_NEAREST;
1016       texObj->Sampler.Attrib.state.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
1017       texObj->Sampler.Attrib.state.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
1018 
1019       texFormat = st_ChooseTextureFormat(ctx, target,
1020                                          GL_RGBA, GL_RGBA,
1021                                          GL_UNSIGNED_BYTE);
1022 
1023       /* need a loop here just for cube maps */
1024       for (face = 0; face < numFaces; face++) {
1025          const GLenum faceTarget = _mesa_cube_face_target(target, face);
1026 
1027          /* initialize level[0] texture image */
1028          texImage = _mesa_get_tex_image(ctx, texObj, faceTarget, 0);
1029 
1030          _mesa_init_teximage_fields(ctx, texImage,
1031                                     width,
1032                                     (dims > 1) ? height : 1,
1033                                     (dims > 2) ? depth : 1,
1034                                     0, /* border */
1035                                     GL_RGBA, texFormat);
1036 
1037          st_TexImage(ctx, dims, texImage,
1038                      GL_RGBA, GL_UNSIGNED_BYTE, texel,
1039                      &ctx->DefaultPacking);
1040       }
1041 
1042       _mesa_test_texobj_completeness(ctx, texObj);
1043       assert(texObj->_BaseComplete);
1044       assert(texObj->_MipmapComplete);
1045 
1046       ctx->Shared->FallbackTex[tex] = texObj;
1047 
1048       /* Complete the driver's operation in case another context will also
1049        * use the same fallback texture. */
1050       st_glFinish(ctx);
1051    }
1052    return ctx->Shared->FallbackTex[tex];
1053 }
1054 
1055 
1056 /**
1057  * Compute the size of the given texture object, in bytes.
1058  */
1059 static GLuint
texture_size(const struct gl_texture_object * texObj)1060 texture_size(const struct gl_texture_object *texObj)
1061 {
1062    const GLuint numFaces = _mesa_num_tex_faces(texObj->Target);
1063    GLuint face, level, size = 0;
1064 
1065    for (face = 0; face < numFaces; face++) {
1066       for (level = 0; level < MAX_TEXTURE_LEVELS; level++) {
1067          const struct gl_texture_image *img = texObj->Image[face][level];
1068          if (img) {
1069             GLuint sz = _mesa_format_image_size(img->TexFormat, img->Width,
1070                                                 img->Height, img->Depth);
1071             size += sz;
1072          }
1073       }
1074    }
1075 
1076    return size;
1077 }
1078 
1079 
1080 /**
1081  * Callback called from _mesa_HashWalk()
1082  */
1083 static void
count_tex_size(void * data,void * userData)1084 count_tex_size(void *data, void *userData)
1085 {
1086    const struct gl_texture_object *texObj =
1087       (const struct gl_texture_object *) data;
1088    GLuint *total = (GLuint *) userData;
1089 
1090    *total = *total + texture_size(texObj);
1091 }
1092 
1093 
1094 /**
1095  * Compute total size (in bytes) of all textures for the given context.
1096  * For debugging purposes.
1097  */
1098 GLuint
_mesa_total_texture_memory(struct gl_context * ctx)1099 _mesa_total_texture_memory(struct gl_context *ctx)
1100 {
1101    GLuint tgt, total = 0;
1102 
1103    _mesa_HashWalk(ctx->Shared->TexObjects, count_tex_size, &total);
1104 
1105    /* plus, the default texture objects */
1106    for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
1107       total += texture_size(ctx->Shared->DefaultTex[tgt]);
1108    }
1109 
1110    return total;
1111 }
1112 
1113 
1114 /**
1115  * Return the base format for the given texture object by looking
1116  * at the base texture image.
1117  * \return base format (such as GL_RGBA) or GL_NONE if it can't be determined
1118  */
1119 GLenum
_mesa_texture_base_format(const struct gl_texture_object * texObj)1120 _mesa_texture_base_format(const struct gl_texture_object *texObj)
1121 {
1122    const struct gl_texture_image *texImage = _mesa_base_tex_image(texObj);
1123 
1124    return texImage ? texImage->_BaseFormat : GL_NONE;
1125 }
1126 
1127 
1128 static struct gl_texture_object *
invalidate_tex_image_error_check(struct gl_context * ctx,GLuint texture,GLint level,const char * name)1129 invalidate_tex_image_error_check(struct gl_context *ctx, GLuint texture,
1130                                  GLint level, const char *name)
1131 {
1132    /* The GL_ARB_invalidate_subdata spec says:
1133     *
1134     *     "If <texture> is zero or is not the name of a texture, the error
1135     *     INVALID_VALUE is generated."
1136     *
1137     * This performs the error check in a different order than listed in the
1138     * spec.  We have to get the texture object before we can validate the
1139     * other parameters against values in the texture object.
1140     */
1141    struct gl_texture_object *const t = _mesa_lookup_texture(ctx, texture);
1142    if (texture == 0 || t == NULL) {
1143       _mesa_error(ctx, GL_INVALID_VALUE, "%s(texture)", name);
1144       return NULL;
1145    }
1146 
1147    /* The GL_ARB_invalidate_subdata spec says:
1148     *
1149     *     "If <level> is less than zero or greater than the base 2 logarithm
1150     *     of the maximum texture width, height, or depth, the error
1151     *     INVALID_VALUE is generated."
1152     */
1153    if (level < 0 || level > t->Attrib.MaxLevel) {
1154       _mesa_error(ctx, GL_INVALID_VALUE, "%s(level)", name);
1155       return NULL;
1156    }
1157 
1158    /* The GL_ARB_invalidate_subdata spec says:
1159     *
1160     *     "If the target of <texture> is TEXTURE_RECTANGLE, TEXTURE_BUFFER,
1161     *     TEXTURE_2D_MULTISAMPLE, or TEXTURE_2D_MULTISAMPLE_ARRAY, and <level>
1162     *     is not zero, the error INVALID_VALUE is generated."
1163     */
1164    if (level != 0) {
1165       switch (t->Target) {
1166       case GL_TEXTURE_RECTANGLE:
1167       case GL_TEXTURE_BUFFER:
1168       case GL_TEXTURE_2D_MULTISAMPLE:
1169       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
1170          _mesa_error(ctx, GL_INVALID_VALUE, "%s(level)", name);
1171          return NULL;
1172 
1173       default:
1174          break;
1175       }
1176    }
1177 
1178    return t;
1179 }
1180 
1181 
1182 /**
1183  * Helper function for glCreateTextures and glGenTextures. Need this because
1184  * glCreateTextures should throw errors if target = 0. This is not exposed to
1185  * the rest of Mesa to encourage Mesa internals to use nameless textures,
1186  * which do not require expensive hash lookups.
1187  * \param target  either 0 or a valid / error-checked texture target enum
1188  */
1189 static void
create_textures(struct gl_context * ctx,GLenum target,GLsizei n,GLuint * textures,const char * caller)1190 create_textures(struct gl_context *ctx, GLenum target,
1191                 GLsizei n, GLuint *textures, const char *caller)
1192 {
1193    GLint i;
1194 
1195    if (!textures)
1196       return;
1197 
1198    /*
1199     * This must be atomic (generation and allocation of texture IDs)
1200     */
1201    _mesa_HashLockMutex(ctx->Shared->TexObjects);
1202 
1203    _mesa_HashFindFreeKeys(ctx->Shared->TexObjects, textures, n);
1204 
1205    /* Allocate new, empty texture objects */
1206    for (i = 0; i < n; i++) {
1207       struct gl_texture_object *texObj;
1208       texObj = _mesa_new_texture_object(ctx, textures[i], target);
1209       if (!texObj) {
1210          _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
1211          _mesa_error(ctx, GL_OUT_OF_MEMORY, "%s", caller);
1212          return;
1213       }
1214 
1215       /* insert into hash table */
1216       _mesa_HashInsertLocked(ctx->Shared->TexObjects, texObj->Name, texObj, true);
1217    }
1218 
1219    _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
1220 }
1221 
1222 
1223 static void
create_textures_err(struct gl_context * ctx,GLenum target,GLsizei n,GLuint * textures,const char * caller)1224 create_textures_err(struct gl_context *ctx, GLenum target,
1225                     GLsizei n, GLuint *textures, const char *caller)
1226 {
1227    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1228       _mesa_debug(ctx, "%s %d\n", caller, n);
1229 
1230    if (n < 0) {
1231       _mesa_error(ctx, GL_INVALID_VALUE, "%s(n < 0)", caller);
1232       return;
1233    }
1234 
1235    create_textures(ctx, target, n, textures, caller);
1236 }
1237 
1238 /*@}*/
1239 
1240 
1241 /***********************************************************************/
1242 /** \name API functions */
1243 /*@{*/
1244 
1245 
1246 /**
1247  * Generate texture names.
1248  *
1249  * \param n number of texture names to be generated.
1250  * \param textures an array in which will hold the generated texture names.
1251  *
1252  * \sa glGenTextures(), glCreateTextures().
1253  *
1254  * Calls _mesa_HashFindFreeKeys() to find a block of free texture
1255  * IDs which are stored in \p textures.  Corresponding empty texture
1256  * objects are also generated.
1257  */
1258 void GLAPIENTRY
_mesa_GenTextures_no_error(GLsizei n,GLuint * textures)1259 _mesa_GenTextures_no_error(GLsizei n, GLuint *textures)
1260 {
1261    GET_CURRENT_CONTEXT(ctx);
1262    create_textures(ctx, 0, n, textures, "glGenTextures");
1263 }
1264 
1265 
1266 void GLAPIENTRY
_mesa_GenTextures(GLsizei n,GLuint * textures)1267 _mesa_GenTextures(GLsizei n, GLuint *textures)
1268 {
1269    GET_CURRENT_CONTEXT(ctx);
1270    create_textures_err(ctx, 0, n, textures, "glGenTextures");
1271 }
1272 
1273 /**
1274  * Create texture objects.
1275  *
1276  * \param target the texture target for each name to be generated.
1277  * \param n number of texture names to be generated.
1278  * \param textures an array in which will hold the generated texture names.
1279  *
1280  * \sa glCreateTextures(), glGenTextures().
1281  *
1282  * Calls _mesa_HashFindFreeKeys() to find a block of free texture
1283  * IDs which are stored in \p textures.  Corresponding empty texture
1284  * objects are also generated.
1285  */
1286 void GLAPIENTRY
_mesa_CreateTextures_no_error(GLenum target,GLsizei n,GLuint * textures)1287 _mesa_CreateTextures_no_error(GLenum target, GLsizei n, GLuint *textures)
1288 {
1289    GET_CURRENT_CONTEXT(ctx);
1290    create_textures(ctx, target, n, textures, "glCreateTextures");
1291 }
1292 
1293 
1294 void GLAPIENTRY
_mesa_CreateTextures(GLenum target,GLsizei n,GLuint * textures)1295 _mesa_CreateTextures(GLenum target, GLsizei n, GLuint *textures)
1296 {
1297    GLint targetIndex;
1298    GET_CURRENT_CONTEXT(ctx);
1299 
1300    /*
1301     * The 4.5 core profile spec (30.10.2014) doesn't specify what
1302     * glCreateTextures should do with invalid targets, which was probably an
1303     * oversight.  This conforms to the spec for glBindTexture.
1304     */
1305    targetIndex = _mesa_tex_target_to_index(ctx, target);
1306    if (targetIndex < 0) {
1307       _mesa_error(ctx, GL_INVALID_ENUM, "glCreateTextures(target)");
1308       return;
1309    }
1310 
1311    create_textures_err(ctx, target, n, textures, "glCreateTextures");
1312 }
1313 
1314 /**
1315  * Check if the given texture object is bound to the current draw or
1316  * read framebuffer.  If so, Unbind it.
1317  */
1318 static void
unbind_texobj_from_fbo(struct gl_context * ctx,struct gl_texture_object * texObj)1319 unbind_texobj_from_fbo(struct gl_context *ctx,
1320                        struct gl_texture_object *texObj)
1321 {
1322    bool progress = false;
1323 
1324    /* Section 4.4.2 (Attaching Images to Framebuffer Objects), subsection
1325     * "Attaching Texture Images to a Framebuffer," of the OpenGL 3.1 spec
1326     * says:
1327     *
1328     *     "If a texture object is deleted while its image is attached to one
1329     *     or more attachment points in the currently bound framebuffer, then
1330     *     it is as if FramebufferTexture* had been called, with a texture of
1331     *     zero, for each attachment point to which this image was attached in
1332     *     the currently bound framebuffer. In other words, this texture image
1333     *     is first detached from all attachment points in the currently bound
1334     *     framebuffer. Note that the texture image is specifically not
1335     *     detached from any other framebuffer objects. Detaching the texture
1336     *     image from any other framebuffer objects is the responsibility of
1337     *     the application."
1338     */
1339    if (_mesa_is_user_fbo(ctx->DrawBuffer)) {
1340       progress = _mesa_detach_renderbuffer(ctx, ctx->DrawBuffer, texObj);
1341    }
1342    if (_mesa_is_user_fbo(ctx->ReadBuffer)
1343        && ctx->ReadBuffer != ctx->DrawBuffer) {
1344       progress = _mesa_detach_renderbuffer(ctx, ctx->ReadBuffer, texObj)
1345          || progress;
1346    }
1347 
1348    if (progress)
1349       /* Vertices are already flushed by _mesa_DeleteTextures */
1350       ctx->NewState |= _NEW_BUFFERS;
1351 }
1352 
1353 
1354 /**
1355  * Check if the given texture object is bound to any texture image units and
1356  * unbind it if so (revert to default textures).
1357  */
1358 static void
unbind_texobj_from_texunits(struct gl_context * ctx,struct gl_texture_object * texObj)1359 unbind_texobj_from_texunits(struct gl_context *ctx,
1360                             struct gl_texture_object *texObj)
1361 {
1362    const gl_texture_index index = texObj->TargetIndex;
1363    GLuint u;
1364 
1365    if (texObj->Target == 0) {
1366       /* texture was never bound */
1367       return;
1368    }
1369 
1370    assert(index < NUM_TEXTURE_TARGETS);
1371 
1372    for (u = 0; u < ctx->Texture.NumCurrentTexUsed; u++) {
1373       struct gl_texture_unit *unit = &ctx->Texture.Unit[u];
1374 
1375       if (texObj == unit->CurrentTex[index]) {
1376          /* Bind the default texture for this unit/target */
1377          _mesa_reference_texobj(&unit->CurrentTex[index],
1378                                 ctx->Shared->DefaultTex[index]);
1379          unit->_BoundTextures &= ~(1 << index);
1380       }
1381    }
1382 }
1383 
1384 
1385 /**
1386  * Check if the given texture object is bound to any shader image unit
1387  * and unbind it if that's the case.
1388  */
1389 static void
unbind_texobj_from_image_units(struct gl_context * ctx,struct gl_texture_object * texObj)1390 unbind_texobj_from_image_units(struct gl_context *ctx,
1391                                struct gl_texture_object *texObj)
1392 {
1393    GLuint i;
1394 
1395    for (i = 0; i < ctx->Const.MaxImageUnits; i++) {
1396       struct gl_image_unit *unit = &ctx->ImageUnits[i];
1397 
1398       if (texObj == unit->TexObj) {
1399          _mesa_reference_texobj(&unit->TexObj, NULL);
1400          *unit = _mesa_default_image_unit(ctx);
1401       }
1402    }
1403 }
1404 
1405 
1406 /**
1407  * Unbinds all textures bound to the given texture image unit.
1408  */
1409 static void
unbind_textures_from_unit(struct gl_context * ctx,GLuint unit)1410 unbind_textures_from_unit(struct gl_context *ctx, GLuint unit)
1411 {
1412    struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
1413 
1414    while (texUnit->_BoundTextures) {
1415       const GLuint index = ffs(texUnit->_BoundTextures) - 1;
1416       struct gl_texture_object *texObj = ctx->Shared->DefaultTex[index];
1417 
1418       _mesa_reference_texobj(&texUnit->CurrentTex[index], texObj);
1419 
1420       texUnit->_BoundTextures &= ~(1 << index);
1421       ctx->NewState |= _NEW_TEXTURE_OBJECT;
1422       ctx->PopAttribState |= GL_TEXTURE_BIT;
1423    }
1424 }
1425 
1426 
1427 /**
1428  * Delete named textures.
1429  *
1430  * \param n number of textures to be deleted.
1431  * \param textures array of texture IDs to be deleted.
1432  *
1433  * \sa glDeleteTextures().
1434  *
1435  * If we're about to delete a texture that's currently bound to any
1436  * texture unit, unbind the texture first.  Decrement the reference
1437  * count on the texture object and delete it if it's zero.
1438  * Recall that texture objects can be shared among several rendering
1439  * contexts.
1440  */
1441 static void
delete_textures(struct gl_context * ctx,GLsizei n,const GLuint * textures)1442 delete_textures(struct gl_context *ctx, GLsizei n, const GLuint *textures)
1443 {
1444    FLUSH_VERTICES(ctx, 0, 0); /* too complex */
1445 
1446    if (!textures)
1447       return;
1448 
1449    for (GLsizei i = 0; i < n; i++) {
1450       if (textures[i] > 0) {
1451          struct gl_texture_object *delObj
1452             = _mesa_lookup_texture(ctx, textures[i]);
1453 
1454          if (delObj) {
1455             _mesa_lock_texture(ctx, delObj);
1456 
1457             /* Check if texture is bound to any framebuffer objects.
1458              * If so, unbind.
1459              * See section 4.4.2.3 of GL_EXT_framebuffer_object.
1460              */
1461             unbind_texobj_from_fbo(ctx, delObj);
1462 
1463             /* Check if this texture is currently bound to any texture units.
1464              * If so, unbind it.
1465              */
1466             unbind_texobj_from_texunits(ctx, delObj);
1467 
1468             /* Check if this texture is currently bound to any shader
1469              * image unit.  If so, unbind it.
1470              * See section 3.9.X of GL_ARB_shader_image_load_store.
1471              */
1472             unbind_texobj_from_image_units(ctx, delObj);
1473 
1474             /* Make all handles that reference this texture object non-resident
1475              * in the current context.
1476              */
1477             _mesa_make_texture_handles_non_resident(ctx, delObj);
1478 
1479             _mesa_unlock_texture(ctx, delObj);
1480 
1481             ctx->NewState |= _NEW_TEXTURE_OBJECT;
1482             ctx->PopAttribState |= GL_TEXTURE_BIT;
1483 
1484             /* The texture _name_ is now free for re-use.
1485              * Remove it from the hash table now.
1486              */
1487             _mesa_HashRemove(ctx->Shared->TexObjects, delObj->Name);
1488 
1489             st_texture_release_all_sampler_views(st_context(ctx), delObj);
1490 
1491             /* Unreference the texobj.  If refcount hits zero, the texture
1492              * will be deleted.
1493              */
1494             _mesa_reference_texobj(&delObj, NULL);
1495          }
1496       }
1497    }
1498 }
1499 
1500 void GLAPIENTRY
_mesa_DeleteTextures_no_error(GLsizei n,const GLuint * textures)1501 _mesa_DeleteTextures_no_error(GLsizei n, const GLuint *textures)
1502 {
1503    GET_CURRENT_CONTEXT(ctx);
1504    delete_textures(ctx, n, textures);
1505 }
1506 
1507 
1508 void GLAPIENTRY
_mesa_DeleteTextures(GLsizei n,const GLuint * textures)1509 _mesa_DeleteTextures(GLsizei n, const GLuint *textures)
1510 {
1511    GET_CURRENT_CONTEXT(ctx);
1512 
1513    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1514       _mesa_debug(ctx, "glDeleteTextures %d\n", n);
1515 
1516    if (n < 0) {
1517       _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteTextures(n < 0)");
1518       return;
1519    }
1520 
1521    delete_textures(ctx, n, textures);
1522 }
1523 
1524 
1525 /**
1526  * Convert a GL texture target enum such as GL_TEXTURE_2D or GL_TEXTURE_3D
1527  * into the corresponding Mesa texture target index.
1528  * Note that proxy targets are not valid here.
1529  * \return TEXTURE_x_INDEX or -1 if target is invalid
1530  */
1531 int
_mesa_tex_target_to_index(const struct gl_context * ctx,GLenum target)1532 _mesa_tex_target_to_index(const struct gl_context *ctx, GLenum target)
1533 {
1534    switch (target) {
1535    case GL_TEXTURE_1D:
1536       return _mesa_is_desktop_gl(ctx) ? TEXTURE_1D_INDEX : -1;
1537    case GL_TEXTURE_2D:
1538       return TEXTURE_2D_INDEX;
1539    case GL_TEXTURE_3D:
1540       return ctx->API != API_OPENGLES ? TEXTURE_3D_INDEX : -1;
1541    case GL_TEXTURE_CUBE_MAP:
1542       return TEXTURE_CUBE_INDEX;
1543    case GL_TEXTURE_RECTANGLE:
1544       return _mesa_is_desktop_gl(ctx) && ctx->Extensions.NV_texture_rectangle
1545          ? TEXTURE_RECT_INDEX : -1;
1546    case GL_TEXTURE_1D_ARRAY:
1547       return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_array
1548          ? TEXTURE_1D_ARRAY_INDEX : -1;
1549    case GL_TEXTURE_2D_ARRAY:
1550       return (_mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_array)
1551          || _mesa_is_gles3(ctx)
1552          ? TEXTURE_2D_ARRAY_INDEX : -1;
1553    case GL_TEXTURE_BUFFER:
1554       return (_mesa_has_ARB_texture_buffer_object(ctx) ||
1555               _mesa_has_OES_texture_buffer(ctx)) ?
1556              TEXTURE_BUFFER_INDEX : -1;
1557    case GL_TEXTURE_EXTERNAL_OES:
1558       return _mesa_is_gles(ctx) && ctx->Extensions.OES_EGL_image_external
1559          ? TEXTURE_EXTERNAL_INDEX : -1;
1560    case GL_TEXTURE_CUBE_MAP_ARRAY:
1561       return _mesa_has_texture_cube_map_array(ctx)
1562          ? TEXTURE_CUBE_ARRAY_INDEX : -1;
1563    case GL_TEXTURE_2D_MULTISAMPLE:
1564       return ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_texture_multisample) ||
1565               _mesa_is_gles31(ctx)) ? TEXTURE_2D_MULTISAMPLE_INDEX: -1;
1566    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
1567       return ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_texture_multisample) ||
1568               _mesa_is_gles31(ctx))
1569          ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX: -1;
1570    default:
1571       return -1;
1572    }
1573 }
1574 
1575 
1576 /**
1577  * Do actual texture binding.  All error checking should have been done prior
1578  * to calling this function.  Note that the texture target (1D, 2D, etc) is
1579  * always specified by the texObj->TargetIndex.
1580  *
1581  * \param unit  index of texture unit to update
1582  * \param texObj  the new texture object (cannot be NULL)
1583  */
1584 static void
bind_texture_object(struct gl_context * ctx,unsigned unit,struct gl_texture_object * texObj)1585 bind_texture_object(struct gl_context *ctx, unsigned unit,
1586                     struct gl_texture_object *texObj)
1587 {
1588    struct gl_texture_unit *texUnit;
1589    int targetIndex;
1590 
1591    assert(unit < ARRAY_SIZE(ctx->Texture.Unit));
1592    texUnit = &ctx->Texture.Unit[unit];
1593 
1594    assert(texObj);
1595    assert(valid_texture_object(texObj));
1596 
1597    targetIndex = texObj->TargetIndex;
1598    assert(targetIndex >= 0);
1599    assert(targetIndex < NUM_TEXTURE_TARGETS);
1600 
1601    /* Check if this texture is only used by this context and is already bound.
1602     * If so, just return. For GL_OES_image_external, rebinding the texture
1603     * always must invalidate cached resources.
1604     */
1605    if (targetIndex != TEXTURE_EXTERNAL_INDEX &&
1606        ctx->Shared->RefCount == 1 &&
1607        texObj == texUnit->CurrentTex[targetIndex])
1608       return;
1609 
1610    /* Flush before changing binding.
1611     *
1612     * Note: Multisample textures don't need to flag GL_TEXTURE_BIT because
1613     *       they are not restored by glPopAttrib according to the GL 4.6
1614     *       Compatibility Profile specification. We set GL_TEXTURE_BIT anyway
1615     *       to simplify the code. This has no effect on behavior.
1616     */
1617    FLUSH_VERTICES(ctx, _NEW_TEXTURE_OBJECT, GL_TEXTURE_BIT);
1618 
1619    /* If the refcount on the previously bound texture is decremented to
1620     * zero, it'll be deleted here.
1621     */
1622    _mesa_reference_texobj(&texUnit->CurrentTex[targetIndex], texObj);
1623 
1624    ctx->Texture.NumCurrentTexUsed = MAX2(ctx->Texture.NumCurrentTexUsed,
1625                                          unit + 1);
1626 
1627    if (texObj->Name != 0)
1628       texUnit->_BoundTextures |= (1 << targetIndex);
1629    else
1630       texUnit->_BoundTextures &= ~(1 << targetIndex);
1631 }
1632 
1633 struct gl_texture_object *
_mesa_lookup_or_create_texture(struct gl_context * ctx,GLenum target,GLuint texName,bool no_error,bool is_ext_dsa,const char * caller)1634 _mesa_lookup_or_create_texture(struct gl_context *ctx, GLenum target,
1635                                GLuint texName, bool no_error, bool is_ext_dsa,
1636                                const char *caller)
1637 {
1638    struct gl_texture_object *newTexObj = NULL;
1639    int targetIndex;
1640 
1641    if (is_ext_dsa) {
1642       if (_mesa_is_proxy_texture(target)) {
1643          /* EXT_dsa allows proxy targets only when texName is 0 */
1644          if (texName != 0) {
1645             _mesa_error(ctx, GL_INVALID_OPERATION, "%s(target = %s)", caller,
1646                         _mesa_enum_to_string(target));
1647             return NULL;
1648          }
1649          return _mesa_get_current_tex_object(ctx, target);
1650       }
1651       if (GL_TEXTURE_CUBE_MAP_POSITIVE_X <= target &&
1652           target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) {
1653          target = GL_TEXTURE_CUBE_MAP;
1654       }
1655    }
1656 
1657    targetIndex = _mesa_tex_target_to_index(ctx, target);
1658    if (!no_error && targetIndex < 0) {
1659       _mesa_error(ctx, GL_INVALID_ENUM, "%s(target = %s)", caller,
1660                   _mesa_enum_to_string(target));
1661       return NULL;
1662    }
1663    assert(targetIndex < NUM_TEXTURE_TARGETS);
1664 
1665    /*
1666     * Get pointer to new texture object (newTexObj)
1667     */
1668    if (texName == 0) {
1669       /* Use a default texture object */
1670       newTexObj = ctx->Shared->DefaultTex[targetIndex];
1671    } else {
1672       /* non-default texture object */
1673       newTexObj = _mesa_lookup_texture(ctx, texName);
1674       if (newTexObj) {
1675          /* error checking */
1676          if (!no_error &&
1677              newTexObj->Target != 0 && newTexObj->Target != target) {
1678             /* The named texture object's target doesn't match the
1679              * given target
1680              */
1681             _mesa_error(ctx, GL_INVALID_OPERATION,
1682                         "%s(target mismatch)", caller);
1683             return NULL;
1684          }
1685          if (newTexObj->Target == 0) {
1686             finish_texture_init(ctx, target, newTexObj, targetIndex);
1687          }
1688       } else {
1689          if (!no_error && ctx->API == API_OPENGL_CORE) {
1690             _mesa_error(ctx, GL_INVALID_OPERATION,
1691                         "%s(non-gen name)", caller);
1692             return NULL;
1693          }
1694 
1695          /* if this is a new texture id, allocate a texture object now */
1696          newTexObj = _mesa_new_texture_object(ctx, texName, target);
1697          if (!newTexObj) {
1698             _mesa_error(ctx, GL_OUT_OF_MEMORY, "%s", caller);
1699             return NULL;
1700          }
1701 
1702          /* and insert it into hash table */
1703          _mesa_HashInsert(ctx->Shared->TexObjects, texName, newTexObj, false);
1704       }
1705    }
1706 
1707    assert(newTexObj->Target == target);
1708    assert(newTexObj->TargetIndex == targetIndex);
1709 
1710    return newTexObj;
1711 }
1712 
1713 /**
1714  * Implement glBindTexture().  Do error checking, look-up or create a new
1715  * texture object, then bind it in the current texture unit.
1716  *
1717  * \param target texture target.
1718  * \param texName texture name.
1719  * \param texunit texture unit.
1720  */
1721 static ALWAYS_INLINE void
bind_texture(struct gl_context * ctx,GLenum target,GLuint texName,GLenum texunit,bool no_error,const char * caller)1722 bind_texture(struct gl_context *ctx, GLenum target, GLuint texName,
1723              GLenum texunit, bool no_error, const char *caller)
1724 {
1725    struct gl_texture_object *newTexObj =
1726       _mesa_lookup_or_create_texture(ctx, target, texName, no_error, false,
1727                                      caller);
1728    if (!newTexObj)
1729       return;
1730 
1731    bind_texture_object(ctx, texunit, newTexObj);
1732 }
1733 
1734 void GLAPIENTRY
_mesa_BindTexture_no_error(GLenum target,GLuint texName)1735 _mesa_BindTexture_no_error(GLenum target, GLuint texName)
1736 {
1737    GET_CURRENT_CONTEXT(ctx);
1738    bind_texture(ctx, target, texName, ctx->Texture.CurrentUnit, true,
1739                 "glBindTexture");
1740 }
1741 
1742 
1743 void GLAPIENTRY
_mesa_BindTexture(GLenum target,GLuint texName)1744 _mesa_BindTexture(GLenum target, GLuint texName)
1745 {
1746    GET_CURRENT_CONTEXT(ctx);
1747 
1748    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1749       _mesa_debug(ctx, "glBindTexture %s %d\n",
1750                   _mesa_enum_to_string(target), (GLint) texName);
1751 
1752    bind_texture(ctx, target, texName, ctx->Texture.CurrentUnit, false,
1753                 "glBindTexture");
1754 }
1755 
1756 
1757 void GLAPIENTRY
_mesa_BindMultiTextureEXT(GLenum texunit,GLenum target,GLuint texture)1758 _mesa_BindMultiTextureEXT(GLenum texunit, GLenum target, GLuint texture)
1759 {
1760    GET_CURRENT_CONTEXT(ctx);
1761 
1762    unsigned unit = texunit - GL_TEXTURE0;
1763 
1764    if (texunit < GL_TEXTURE0 || unit >= _mesa_max_tex_unit(ctx)) {
1765       _mesa_error(ctx, GL_INVALID_ENUM, "glBindMultiTextureEXT(texunit=%s)",
1766                   _mesa_enum_to_string(texunit));
1767       return;
1768    }
1769 
1770    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1771       _mesa_debug(ctx, "glBindMultiTextureEXT %s %d\n",
1772                   _mesa_enum_to_string(texunit), (GLint) texture);
1773 
1774    bind_texture(ctx, target, texture, unit, false, "glBindMultiTextureEXT");
1775 }
1776 
1777 
1778 /**
1779  * OpenGL 4.5 / GL_ARB_direct_state_access glBindTextureUnit().
1780  *
1781  * \param unit texture unit.
1782  * \param texture texture name.
1783  *
1784  * \sa glBindTexture().
1785  *
1786  * If the named texture is 0, this will reset each target for the specified
1787  * texture unit to its default texture.
1788  * If the named texture is not 0 or a recognized texture name, this throws
1789  * GL_INVALID_OPERATION.
1790  */
1791 static ALWAYS_INLINE void
bind_texture_unit(struct gl_context * ctx,GLuint unit,GLuint texture,bool no_error)1792 bind_texture_unit(struct gl_context *ctx, GLuint unit, GLuint texture,
1793                   bool no_error)
1794 {
1795    struct gl_texture_object *texObj;
1796 
1797    /* Section 8.1 (Texture Objects) of the OpenGL 4.5 core profile spec
1798     * (20141030) says:
1799     *    "When texture is zero, each of the targets enumerated at the
1800     *    beginning of this section is reset to its default texture for the
1801     *    corresponding texture image unit."
1802     */
1803    if (texture == 0) {
1804       unbind_textures_from_unit(ctx, unit);
1805       return;
1806    }
1807 
1808    /* Get the non-default texture object */
1809    texObj = _mesa_lookup_texture(ctx, texture);
1810    if (!no_error) {
1811       /* Error checking */
1812       if (!texObj) {
1813          _mesa_error(ctx, GL_INVALID_OPERATION,
1814                      "glBindTextureUnit(non-gen name)");
1815          return;
1816       }
1817 
1818       if (texObj->Target == 0) {
1819          /* Texture object was gen'd but never bound so the target is not set */
1820          _mesa_error(ctx, GL_INVALID_OPERATION, "glBindTextureUnit(target)");
1821          return;
1822       }
1823    }
1824 
1825    assert(valid_texture_object(texObj));
1826 
1827    bind_texture_object(ctx, unit, texObj);
1828 }
1829 
1830 
1831 void GLAPIENTRY
_mesa_BindTextureUnit_no_error(GLuint unit,GLuint texture)1832 _mesa_BindTextureUnit_no_error(GLuint unit, GLuint texture)
1833 {
1834    GET_CURRENT_CONTEXT(ctx);
1835    bind_texture_unit(ctx, unit, texture, true);
1836 }
1837 
1838 
1839 void GLAPIENTRY
_mesa_BindTextureUnit(GLuint unit,GLuint texture)1840 _mesa_BindTextureUnit(GLuint unit, GLuint texture)
1841 {
1842    GET_CURRENT_CONTEXT(ctx);
1843 
1844    if (unit >= _mesa_max_tex_unit(ctx)) {
1845       _mesa_error(ctx, GL_INVALID_VALUE, "glBindTextureUnit(unit=%u)", unit);
1846       return;
1847    }
1848 
1849    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1850       _mesa_debug(ctx, "glBindTextureUnit %s %d\n",
1851                   _mesa_enum_to_string(GL_TEXTURE0+unit), (GLint) texture);
1852 
1853    bind_texture_unit(ctx, unit, texture, false);
1854 }
1855 
1856 
1857 /**
1858  * OpenGL 4.4 / GL_ARB_multi_bind glBindTextures().
1859  */
1860 static ALWAYS_INLINE void
bind_textures(struct gl_context * ctx,GLuint first,GLsizei count,const GLuint * textures,bool no_error)1861 bind_textures(struct gl_context *ctx, GLuint first, GLsizei count,
1862               const GLuint *textures, bool no_error)
1863 {
1864    GLsizei i;
1865 
1866    if (textures) {
1867       /* Note that the error semantics for multi-bind commands differ from
1868        * those of other GL commands.
1869        *
1870        * The issues section in the ARB_multi_bind spec says:
1871        *
1872        *    "(11) Typically, OpenGL specifies that if an error is generated by
1873        *          a command, that command has no effect.  This is somewhat
1874        *          unfortunate for multi-bind commands, because it would require
1875        *          a first pass to scan the entire list of bound objects for
1876        *          errors and then a second pass to actually perform the
1877        *          bindings.  Should we have different error semantics?
1878        *
1879        *       RESOLVED:  Yes.  In this specification, when the parameters for
1880        *       one of the <count> binding points are invalid, that binding
1881        *       point is not updated and an error will be generated.  However,
1882        *       other binding points in the same command will be updated if
1883        *       their parameters are valid and no other error occurs."
1884        */
1885 
1886       _mesa_HashLockMutex(ctx->Shared->TexObjects);
1887 
1888       for (i = 0; i < count; i++) {
1889          if (textures[i] != 0) {
1890             struct gl_texture_unit *texUnit = &ctx->Texture.Unit[first + i];
1891             struct gl_texture_object *current = texUnit->_Current;
1892             struct gl_texture_object *texObj;
1893 
1894             if (current && current->Name == textures[i])
1895                texObj = current;
1896             else
1897                texObj = _mesa_lookup_texture_locked(ctx, textures[i]);
1898 
1899             if (texObj && texObj->Target != 0) {
1900                bind_texture_object(ctx, first + i, texObj);
1901             } else if (!no_error) {
1902                /* The ARB_multi_bind spec says:
1903                 *
1904                 *     "An INVALID_OPERATION error is generated if any value
1905                 *      in <textures> is not zero or the name of an existing
1906                 *      texture object (per binding)."
1907                 */
1908                _mesa_error(ctx, GL_INVALID_OPERATION,
1909                            "glBindTextures(textures[%d]=%u is not zero "
1910                            "or the name of an existing texture object)",
1911                            i, textures[i]);
1912             }
1913          } else {
1914             unbind_textures_from_unit(ctx, first + i);
1915          }
1916       }
1917 
1918       _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
1919    } else {
1920       /* Unbind all textures in the range <first> through <first>+<count>-1 */
1921       for (i = 0; i < count; i++)
1922          unbind_textures_from_unit(ctx, first + i);
1923    }
1924 }
1925 
1926 
1927 void GLAPIENTRY
_mesa_BindTextures_no_error(GLuint first,GLsizei count,const GLuint * textures)1928 _mesa_BindTextures_no_error(GLuint first, GLsizei count, const GLuint *textures)
1929 {
1930    GET_CURRENT_CONTEXT(ctx);
1931    bind_textures(ctx, first, count, textures, true);
1932 }
1933 
1934 
1935 void GLAPIENTRY
_mesa_BindTextures(GLuint first,GLsizei count,const GLuint * textures)1936 _mesa_BindTextures(GLuint first, GLsizei count, const GLuint *textures)
1937 {
1938    GET_CURRENT_CONTEXT(ctx);
1939 
1940    /* The ARB_multi_bind spec says:
1941     *
1942     *     "An INVALID_OPERATION error is generated if <first> + <count>
1943     *      is greater than the number of texture image units supported
1944     *      by the implementation."
1945     */
1946    if (first + count > ctx->Const.MaxCombinedTextureImageUnits) {
1947       _mesa_error(ctx, GL_INVALID_OPERATION,
1948                   "glBindTextures(first=%u + count=%d > the value of "
1949                   "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=%u)",
1950                   first, count, ctx->Const.MaxCombinedTextureImageUnits);
1951       return;
1952    }
1953 
1954    bind_textures(ctx, first, count, textures, false);
1955 }
1956 
1957 
1958 /**
1959  * Set texture priorities.
1960  *
1961  * \param n number of textures.
1962  * \param texName texture names.
1963  * \param priorities corresponding texture priorities.
1964  *
1965  * \sa glPrioritizeTextures().
1966  *
1967  * Looks up each texture in the hash, clamps the corresponding priority between
1968  * 0.0 and 1.0, and calls dd_function_table::PrioritizeTexture.
1969  */
1970 void GLAPIENTRY
_mesa_PrioritizeTextures(GLsizei n,const GLuint * texName,const GLclampf * priorities)1971 _mesa_PrioritizeTextures( GLsizei n, const GLuint *texName,
1972                           const GLclampf *priorities )
1973 {
1974    GET_CURRENT_CONTEXT(ctx);
1975    GLint i;
1976 
1977    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1978       _mesa_debug(ctx, "glPrioritizeTextures %d\n", n);
1979 
1980 
1981    if (n < 0) {
1982       _mesa_error( ctx, GL_INVALID_VALUE, "glPrioritizeTextures" );
1983       return;
1984    }
1985 
1986    if (!priorities)
1987       return;
1988 
1989    FLUSH_VERTICES(ctx, _NEW_TEXTURE_OBJECT, GL_TEXTURE_BIT);
1990 
1991    for (i = 0; i < n; i++) {
1992       if (texName[i] > 0) {
1993          struct gl_texture_object *t = _mesa_lookup_texture(ctx, texName[i]);
1994          if (t) {
1995             t->Attrib.Priority = CLAMP( priorities[i], 0.0F, 1.0F );
1996          }
1997       }
1998    }
1999 }
2000 
2001 
2002 
2003 /**
2004  * See if textures are loaded in texture memory.
2005  *
2006  * \param n number of textures to query.
2007  * \param texName array with the texture names.
2008  * \param residences array which will hold the residence status.
2009  *
2010  * \return GL_TRUE if all textures are resident and
2011  *                 residences is left unchanged,
2012  *
2013  * Note: we assume all textures are always resident
2014  */
2015 GLboolean GLAPIENTRY
_mesa_AreTexturesResident(GLsizei n,const GLuint * texName,GLboolean * residences)2016 _mesa_AreTexturesResident(GLsizei n, const GLuint *texName,
2017                           GLboolean *residences)
2018 {
2019    GET_CURRENT_CONTEXT(ctx);
2020    GLboolean allResident = GL_TRUE;
2021    GLint i;
2022    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
2023 
2024    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2025       _mesa_debug(ctx, "glAreTexturesResident %d\n", n);
2026 
2027    if (n < 0) {
2028       _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident(n)");
2029       return GL_FALSE;
2030    }
2031 
2032    if (!texName || !residences)
2033       return GL_FALSE;
2034 
2035    /* We only do error checking on the texture names */
2036    for (i = 0; i < n; i++) {
2037       struct gl_texture_object *t;
2038       if (texName[i] == 0) {
2039          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
2040          return GL_FALSE;
2041       }
2042       t = _mesa_lookup_texture(ctx, texName[i]);
2043       if (!t) {
2044          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
2045          return GL_FALSE;
2046       }
2047    }
2048 
2049    return allResident;
2050 }
2051 
2052 
2053 /**
2054  * See if a name corresponds to a texture.
2055  *
2056  * \param texture texture name.
2057  *
2058  * \return GL_TRUE if texture name corresponds to a texture, or GL_FALSE
2059  * otherwise.
2060  *
2061  * \sa glIsTexture().
2062  *
2063  * Calls _mesa_HashLookup().
2064  */
2065 GLboolean GLAPIENTRY
_mesa_IsTexture(GLuint texture)2066 _mesa_IsTexture( GLuint texture )
2067 {
2068    struct gl_texture_object *t;
2069    GET_CURRENT_CONTEXT(ctx);
2070    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
2071 
2072    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2073       _mesa_debug(ctx, "glIsTexture %d\n", texture);
2074 
2075    if (!texture)
2076       return GL_FALSE;
2077 
2078    t = _mesa_lookup_texture(ctx, texture);
2079 
2080    /* IsTexture is true only after object has been bound once. */
2081    return t && t->Target;
2082 }
2083 
2084 
2085 /**
2086  * Simplest implementation of texture locking: grab the shared tex
2087  * mutex.  Examine the shared context state timestamp and if there has
2088  * been a change, set the appropriate bits in ctx->NewState.
2089  *
2090  * This is used to deal with synchronizing things when a texture object
2091  * is used/modified by different contexts (or threads) which are sharing
2092  * the texture.
2093  *
2094  * See also _mesa_lock/unlock_texture() in teximage.h
2095  */
2096 void
_mesa_lock_context_textures(struct gl_context * ctx)2097 _mesa_lock_context_textures( struct gl_context *ctx )
2098 {
2099    if (!ctx->TexturesLocked)
2100       simple_mtx_lock(&ctx->Shared->TexMutex);
2101 
2102    if (ctx->Shared->TextureStateStamp != ctx->TextureStateTimestamp) {
2103       ctx->NewState |= _NEW_TEXTURE_OBJECT;
2104       ctx->PopAttribState |= GL_TEXTURE_BIT;
2105       ctx->TextureStateTimestamp = ctx->Shared->TextureStateStamp;
2106    }
2107 }
2108 
2109 
2110 void
_mesa_unlock_context_textures(struct gl_context * ctx)2111 _mesa_unlock_context_textures( struct gl_context *ctx )
2112 {
2113    assert(ctx->Shared->TextureStateStamp == ctx->TextureStateTimestamp);
2114    if (!ctx->TexturesLocked)
2115       simple_mtx_unlock(&ctx->Shared->TexMutex);
2116 }
2117 
2118 
2119 void GLAPIENTRY
_mesa_InvalidateTexSubImage_no_error(GLuint texture,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth)2120 _mesa_InvalidateTexSubImage_no_error(GLuint texture, GLint level, GLint xoffset,
2121                                      GLint yoffset, GLint zoffset,
2122                                      GLsizei width, GLsizei height,
2123                                      GLsizei depth)
2124 {
2125    /* no-op */
2126 }
2127 
2128 
2129 void GLAPIENTRY
_mesa_InvalidateTexSubImage(GLuint texture,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth)2130 _mesa_InvalidateTexSubImage(GLuint texture, GLint level, GLint xoffset,
2131                             GLint yoffset, GLint zoffset, GLsizei width,
2132                             GLsizei height, GLsizei depth)
2133 {
2134    struct gl_texture_object *t;
2135    struct gl_texture_image *image;
2136    GET_CURRENT_CONTEXT(ctx);
2137 
2138    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2139       _mesa_debug(ctx, "glInvalidateTexSubImage %d\n", texture);
2140 
2141    t = invalidate_tex_image_error_check(ctx, texture, level,
2142                                         "glInvalidateTexSubImage");
2143 
2144    /* The GL_ARB_invalidate_subdata spec says:
2145     *
2146     *     "...the specified subregion must be between -<b> and <dim>+<b> where
2147     *     <dim> is the size of the dimension of the texture image, and <b> is
2148     *     the size of the border of that texture image, otherwise
2149     *     INVALID_VALUE is generated (border is not applied to dimensions that
2150     *     don't exist in a given texture target)."
2151     */
2152    image = t->Image[0][level];
2153    if (image) {
2154       int xBorder;
2155       int yBorder;
2156       int zBorder;
2157       int imageWidth;
2158       int imageHeight;
2159       int imageDepth;
2160 
2161       /* The GL_ARB_invalidate_subdata spec says:
2162        *
2163        *     "For texture targets that don't have certain dimensions, this
2164        *     command treats those dimensions as having a size of 1. For
2165        *     example, to invalidate a portion of a two-dimensional texture,
2166        *     the application would use <zoffset> equal to zero and <depth>
2167        *     equal to one."
2168        */
2169       switch (t->Target) {
2170       case GL_TEXTURE_BUFFER:
2171          xBorder = 0;
2172          yBorder = 0;
2173          zBorder = 0;
2174          imageWidth = 1;
2175          imageHeight = 1;
2176          imageDepth = 1;
2177          break;
2178       case GL_TEXTURE_1D:
2179          xBorder = image->Border;
2180          yBorder = 0;
2181          zBorder = 0;
2182          imageWidth = image->Width;
2183          imageHeight = 1;
2184          imageDepth = 1;
2185          break;
2186       case GL_TEXTURE_1D_ARRAY:
2187          xBorder = image->Border;
2188          yBorder = 0;
2189          zBorder = 0;
2190          imageWidth = image->Width;
2191          imageHeight = image->Height;
2192          imageDepth = 1;
2193          break;
2194       case GL_TEXTURE_2D:
2195       case GL_TEXTURE_CUBE_MAP:
2196       case GL_TEXTURE_RECTANGLE:
2197       case GL_TEXTURE_2D_MULTISAMPLE:
2198          xBorder = image->Border;
2199          yBorder = image->Border;
2200          zBorder = 0;
2201          imageWidth = image->Width;
2202          imageHeight = image->Height;
2203          imageDepth = 1;
2204          break;
2205       case GL_TEXTURE_2D_ARRAY:
2206       case GL_TEXTURE_CUBE_MAP_ARRAY:
2207       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
2208          xBorder = image->Border;
2209          yBorder = image->Border;
2210          zBorder = 0;
2211          imageWidth = image->Width;
2212          imageHeight = image->Height;
2213          imageDepth = image->Depth;
2214          break;
2215       case GL_TEXTURE_3D:
2216          xBorder = image->Border;
2217          yBorder = image->Border;
2218          zBorder = image->Border;
2219          imageWidth = image->Width;
2220          imageHeight = image->Height;
2221          imageDepth = image->Depth;
2222          break;
2223       default:
2224          assert(!"Should not get here.");
2225          xBorder = 0;
2226          yBorder = 0;
2227          zBorder = 0;
2228          imageWidth = 0;
2229          imageHeight = 0;
2230          imageDepth = 0;
2231          break;
2232       }
2233 
2234       if (xoffset < -xBorder) {
2235          _mesa_error(ctx, GL_INVALID_VALUE, "glInvalidateSubTexImage(xoffset)");
2236          return;
2237       }
2238 
2239       if (xoffset + width > imageWidth + xBorder) {
2240          _mesa_error(ctx, GL_INVALID_VALUE,
2241                      "glInvalidateSubTexImage(xoffset+width)");
2242          return;
2243       }
2244 
2245       if (yoffset < -yBorder) {
2246          _mesa_error(ctx, GL_INVALID_VALUE, "glInvalidateSubTexImage(yoffset)");
2247          return;
2248       }
2249 
2250       if (yoffset + height > imageHeight + yBorder) {
2251          _mesa_error(ctx, GL_INVALID_VALUE,
2252                      "glInvalidateSubTexImage(yoffset+height)");
2253          return;
2254       }
2255 
2256       if (zoffset < -zBorder) {
2257          _mesa_error(ctx, GL_INVALID_VALUE,
2258                      "glInvalidateSubTexImage(zoffset)");
2259          return;
2260       }
2261 
2262       if (zoffset + depth  > imageDepth + zBorder) {
2263          _mesa_error(ctx, GL_INVALID_VALUE,
2264                      "glInvalidateSubTexImage(zoffset+depth)");
2265          return;
2266       }
2267    }
2268 
2269    /* We don't actually do anything for this yet.  Just return after
2270     * validating the parameters and generating the required errors.
2271     */
2272    return;
2273 }
2274 
2275 
2276 void GLAPIENTRY
_mesa_InvalidateTexImage_no_error(GLuint texture,GLint level)2277 _mesa_InvalidateTexImage_no_error(GLuint texture, GLint level)
2278 {
2279    /* no-op */
2280 }
2281 
2282 
2283 void GLAPIENTRY
_mesa_InvalidateTexImage(GLuint texture,GLint level)2284 _mesa_InvalidateTexImage(GLuint texture, GLint level)
2285 {
2286    GET_CURRENT_CONTEXT(ctx);
2287 
2288    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2289       _mesa_debug(ctx, "glInvalidateTexImage(%d, %d)\n", texture, level);
2290 
2291    invalidate_tex_image_error_check(ctx, texture, level,
2292                                     "glInvalidateTexImage");
2293 
2294    /* We don't actually do anything for this yet.  Just return after
2295     * validating the parameters and generating the required errors.
2296     */
2297    return;
2298 }
2299 
2300 static void
texture_page_commitment(struct gl_context * ctx,GLenum target,struct gl_texture_object * tex_obj,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth,GLboolean commit,const char * func)2301 texture_page_commitment(struct gl_context *ctx, GLenum target,
2302                         struct gl_texture_object *tex_obj,
2303                         GLint level, GLint xoffset, GLint yoffset, GLint zoffset,
2304                         GLsizei width, GLsizei height, GLsizei depth,
2305                         GLboolean commit, const char *func)
2306 {
2307    if (!tex_obj->Immutable || !tex_obj->IsSparse) {
2308       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(immutable sparse texture)", func);
2309       return;
2310    }
2311 
2312    if (level < 0 || level > tex_obj->_MaxLevel) {
2313       /* Not in error list of ARB_sparse_texture. */
2314       _mesa_error(ctx, GL_INVALID_VALUE, "%s(level %d)", func, level);
2315       return;
2316    }
2317 
2318    struct gl_texture_image *image = tex_obj->Image[0][level];
2319 
2320    int max_depth = image->Depth;
2321    if (target == GL_TEXTURE_CUBE_MAP)
2322       max_depth *= 6;
2323 
2324    if (xoffset + width > image->Width ||
2325        yoffset + height > image->Height ||
2326        zoffset + depth > max_depth) {
2327       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(exceed max size)", func);
2328       return;
2329    }
2330 
2331    int px, py, pz;
2332    bool ret = st_GetSparseTextureVirtualPageSize(
2333       ctx, target, image->TexFormat, tex_obj->VirtualPageSizeIndex, &px, &py, &pz);
2334    assert(ret);
2335 
2336    if (xoffset % px || yoffset % py || zoffset % pz) {
2337       _mesa_error(ctx, GL_INVALID_VALUE, "%s(offset multiple of page size)", func);
2338       return;
2339    }
2340 
2341    if ((width % px && xoffset + width != image->Width) ||
2342        (height % py && yoffset + height != image->Height) ||
2343        (depth % pz && zoffset + depth != max_depth)) {
2344       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(alignment)", func);
2345       return;
2346    }
2347 
2348    st_TexturePageCommitment(ctx, tex_obj, level, xoffset, yoffset, zoffset,
2349                             width, height, depth, commit);
2350 }
2351 
2352 void GLAPIENTRY
_mesa_TexPageCommitmentARB(GLenum target,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth,GLboolean commit)2353 _mesa_TexPageCommitmentARB(GLenum target, GLint level, GLint xoffset,
2354                            GLint yoffset, GLint zoffset, GLsizei width,
2355                            GLsizei height, GLsizei depth, GLboolean commit)
2356 {
2357    GET_CURRENT_CONTEXT(ctx);
2358    struct gl_texture_object *texObj;
2359 
2360    texObj = _mesa_get_current_tex_object(ctx, target);
2361    if (!texObj) {
2362       _mesa_error(ctx, GL_INVALID_ENUM, "glTexPageCommitmentARB(target)");
2363       return;
2364    }
2365 
2366    texture_page_commitment(ctx, target, texObj, level, xoffset, yoffset, zoffset,
2367                            width, height, depth, commit,
2368                            "glTexPageCommitmentARB");
2369 }
2370 
2371 void GLAPIENTRY
_mesa_TexturePageCommitmentEXT(GLuint texture,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth,GLboolean commit)2372 _mesa_TexturePageCommitmentEXT(GLuint texture, GLint level, GLint xoffset,
2373                                GLint yoffset, GLint zoffset, GLsizei width,
2374                                GLsizei height, GLsizei depth, GLboolean commit)
2375 {
2376    GET_CURRENT_CONTEXT(ctx);
2377    struct gl_texture_object *texObj;
2378 
2379    texObj = _mesa_lookup_texture(ctx, texture);
2380    if (texture == 0 || texObj == NULL) {
2381       _mesa_error(ctx, GL_INVALID_OPERATION, "glTexturePageCommitmentEXT(texture)");
2382       return;
2383    }
2384 
2385    texture_page_commitment(ctx, texObj->Target, texObj, level, xoffset, yoffset,
2386                            zoffset, width, height, depth, commit,
2387                            "glTexturePageCommitmentEXT");
2388 }
2389 
2390 /*@}*/
2391