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