texstate.c revision b167d5e7
1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25/**
26 * \file texstate.c
27 *
28 * Texture state handling.
29 */
30
31#include "glheader.h"
32#include "bufferobj.h"
33#include "colormac.h"
34#include "colortab.h"
35#include "context.h"
36#include "enums.h"
37#include "macros.h"
38#include "shaderimage.h"
39#include "texobj.h"
40#include "teximage.h"
41#include "texstate.h"
42#include "mtypes.h"
43#include "bitset.h"
44
45
46/**
47 * Default texture combine environment state.  This is used to initialize
48 * a context's texture units and as the basis for converting "classic"
49 * texture environmnets to ARB_texture_env_combine style values.
50 */
51static const struct gl_tex_env_combine_state default_combine_state = {
52   GL_MODULATE, GL_MODULATE,
53   { GL_TEXTURE, GL_PREVIOUS, GL_CONSTANT, GL_CONSTANT },
54   { GL_TEXTURE, GL_PREVIOUS, GL_CONSTANT, GL_CONSTANT },
55   { GL_SRC_COLOR, GL_SRC_COLOR, GL_SRC_ALPHA, GL_SRC_ALPHA },
56   { GL_SRC_ALPHA, GL_SRC_ALPHA, GL_SRC_ALPHA, GL_SRC_ALPHA },
57   0, 0,
58   2, 2
59};
60
61
62
63/**
64 * Used by glXCopyContext to copy texture state from one context to another.
65 */
66void
67_mesa_copy_texture_state( const struct gl_context *src, struct gl_context *dst )
68{
69   GLuint u, tex;
70
71   ASSERT(src);
72   ASSERT(dst);
73
74   dst->Texture.CurrentUnit = src->Texture.CurrentUnit;
75   dst->Texture._GenFlags = src->Texture._GenFlags;
76   dst->Texture._TexGenEnabled = src->Texture._TexGenEnabled;
77   dst->Texture._TexMatEnabled = src->Texture._TexMatEnabled;
78
79   /* per-unit state */
80   for (u = 0; u < src->Const.MaxCombinedTextureImageUnits; u++) {
81      dst->Texture.Unit[u].Enabled = src->Texture.Unit[u].Enabled;
82      dst->Texture.Unit[u].EnvMode = src->Texture.Unit[u].EnvMode;
83      COPY_4V(dst->Texture.Unit[u].EnvColor, src->Texture.Unit[u].EnvColor);
84      dst->Texture.Unit[u].TexGenEnabled = src->Texture.Unit[u].TexGenEnabled;
85      dst->Texture.Unit[u].GenS = src->Texture.Unit[u].GenS;
86      dst->Texture.Unit[u].GenT = src->Texture.Unit[u].GenT;
87      dst->Texture.Unit[u].GenR = src->Texture.Unit[u].GenR;
88      dst->Texture.Unit[u].GenQ = src->Texture.Unit[u].GenQ;
89      dst->Texture.Unit[u].LodBias = src->Texture.Unit[u].LodBias;
90
91      /* GL_EXT_texture_env_combine */
92      dst->Texture.Unit[u].Combine = src->Texture.Unit[u].Combine;
93
94      /*
95       * XXX strictly speaking, we should compare texture names/ids and
96       * bind textures in the dest context according to id.  For now, only
97       * copy bindings if the contexts share the same pool of textures to
98       * avoid refcounting bugs.
99       */
100      if (dst->Shared == src->Shared) {
101         /* copy texture object bindings, not contents of texture objects */
102         _mesa_lock_context_textures(dst);
103
104         for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
105            _mesa_reference_texobj(&dst->Texture.Unit[u].CurrentTex[tex],
106                                   src->Texture.Unit[u].CurrentTex[tex]);
107            if (src->Texture.Unit[u].CurrentTex[tex]) {
108               dst->Texture.NumCurrentTexUsed =
109                  MAX2(dst->Texture.NumCurrentTexUsed, u + 1);
110            }
111         }
112         dst->Texture.Unit[u]._BoundTextures = src->Texture.Unit[u]._BoundTextures;
113         _mesa_unlock_context_textures(dst);
114      }
115   }
116}
117
118
119/*
120 * For debugging
121 */
122void
123_mesa_print_texunit_state( struct gl_context *ctx, GLuint unit )
124{
125   const struct gl_texture_unit *texUnit = ctx->Texture.Unit + unit;
126   printf("Texture Unit %d\n", unit);
127   printf("  GL_TEXTURE_ENV_MODE = %s\n", _mesa_lookup_enum_by_nr(texUnit->EnvMode));
128   printf("  GL_COMBINE_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.ModeRGB));
129   printf("  GL_COMBINE_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.ModeA));
130   printf("  GL_SOURCE0_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceRGB[0]));
131   printf("  GL_SOURCE1_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceRGB[1]));
132   printf("  GL_SOURCE2_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceRGB[2]));
133   printf("  GL_SOURCE0_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceA[0]));
134   printf("  GL_SOURCE1_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceA[1]));
135   printf("  GL_SOURCE2_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.SourceA[2]));
136   printf("  GL_OPERAND0_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandRGB[0]));
137   printf("  GL_OPERAND1_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandRGB[1]));
138   printf("  GL_OPERAND2_RGB = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandRGB[2]));
139   printf("  GL_OPERAND0_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandA[0]));
140   printf("  GL_OPERAND1_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandA[1]));
141   printf("  GL_OPERAND2_ALPHA = %s\n", _mesa_lookup_enum_by_nr(texUnit->Combine.OperandA[2]));
142   printf("  GL_RGB_SCALE = %d\n", 1 << texUnit->Combine.ScaleShiftRGB);
143   printf("  GL_ALPHA_SCALE = %d\n", 1 << texUnit->Combine.ScaleShiftA);
144   printf("  GL_TEXTURE_ENV_COLOR = (%f, %f, %f, %f)\n", texUnit->EnvColor[0], texUnit->EnvColor[1], texUnit->EnvColor[2], texUnit->EnvColor[3]);
145}
146
147
148
149/**********************************************************************/
150/*                       Texture Environment                          */
151/**********************************************************************/
152
153/**
154 * Convert "classic" texture environment to ARB_texture_env_combine style
155 * environments.
156 *
157 * \param state  texture_env_combine state vector to be filled-in.
158 * \param mode   Classic texture environment mode (i.e., \c GL_REPLACE,
159 *               \c GL_BLEND, \c GL_DECAL, etc.).
160 * \param texBaseFormat  Base format of the texture associated with the
161 *               texture unit.
162 */
163static void
164calculate_derived_texenv( struct gl_tex_env_combine_state *state,
165			  GLenum mode, GLenum texBaseFormat )
166{
167   GLenum mode_rgb;
168   GLenum mode_a;
169
170   *state = default_combine_state;
171
172   switch (texBaseFormat) {
173   case GL_ALPHA:
174      state->SourceRGB[0] = GL_PREVIOUS;
175      break;
176
177   case GL_LUMINANCE_ALPHA:
178   case GL_INTENSITY:
179   case GL_RGBA:
180      break;
181
182   case GL_LUMINANCE:
183   case GL_RED:
184   case GL_RG:
185   case GL_RGB:
186   case GL_YCBCR_MESA:
187      state->SourceA[0] = GL_PREVIOUS;
188      break;
189
190   default:
191      _mesa_problem(NULL,
192                    "Invalid texBaseFormat 0x%x in calculate_derived_texenv",
193                    texBaseFormat);
194      return;
195   }
196
197   if (mode == GL_REPLACE_EXT)
198      mode = GL_REPLACE;
199
200   switch (mode) {
201   case GL_REPLACE:
202   case GL_MODULATE:
203      mode_rgb = (texBaseFormat == GL_ALPHA) ? GL_REPLACE : mode;
204      mode_a   = mode;
205      break;
206
207   case GL_DECAL:
208      mode_rgb = GL_INTERPOLATE;
209      mode_a   = GL_REPLACE;
210
211      state->SourceA[0] = GL_PREVIOUS;
212
213      /* Having alpha / luminance / intensity textures replace using the
214       * incoming fragment color matches the definition in NV_texture_shader.
215       * The 1.5 spec simply marks these as "undefined".
216       */
217      switch (texBaseFormat) {
218      case GL_ALPHA:
219      case GL_LUMINANCE:
220      case GL_LUMINANCE_ALPHA:
221      case GL_INTENSITY:
222	 state->SourceRGB[0] = GL_PREVIOUS;
223	 break;
224      case GL_RED:
225      case GL_RG:
226      case GL_RGB:
227      case GL_YCBCR_MESA:
228	 mode_rgb = GL_REPLACE;
229	 break;
230      case GL_RGBA:
231	 state->SourceRGB[2] = GL_TEXTURE;
232	 break;
233      }
234      break;
235
236   case GL_BLEND:
237      mode_rgb = GL_INTERPOLATE;
238      mode_a   = GL_MODULATE;
239
240      switch (texBaseFormat) {
241      case GL_ALPHA:
242	 mode_rgb = GL_REPLACE;
243	 break;
244      case GL_INTENSITY:
245	 mode_a = GL_INTERPOLATE;
246	 state->SourceA[0] = GL_CONSTANT;
247	 state->OperandA[2] = GL_SRC_ALPHA;
248	 /* FALLTHROUGH */
249      case GL_LUMINANCE:
250      case GL_RED:
251      case GL_RG:
252      case GL_RGB:
253      case GL_LUMINANCE_ALPHA:
254      case GL_RGBA:
255      case GL_YCBCR_MESA:
256	 state->SourceRGB[2] = GL_TEXTURE;
257	 state->SourceA[2]   = GL_TEXTURE;
258	 state->SourceRGB[0] = GL_CONSTANT;
259	 state->OperandRGB[2] = GL_SRC_COLOR;
260	 break;
261      }
262      break;
263
264   case GL_ADD:
265      mode_rgb = (texBaseFormat == GL_ALPHA) ? GL_REPLACE : GL_ADD;
266      mode_a   = (texBaseFormat == GL_INTENSITY) ? GL_ADD : GL_MODULATE;
267      break;
268
269   default:
270      _mesa_problem(NULL,
271                    "Invalid texture env mode 0x%x in calculate_derived_texenv",
272                    mode);
273      return;
274   }
275
276   state->ModeRGB = (state->SourceRGB[0] != GL_PREVIOUS)
277       ? mode_rgb : GL_REPLACE;
278   state->ModeA   = (state->SourceA[0]   != GL_PREVIOUS)
279       ? mode_a   : GL_REPLACE;
280}
281
282
283
284
285/* GL_ARB_multitexture */
286void GLAPIENTRY
287_mesa_ActiveTexture(GLenum texture)
288{
289   const GLuint texUnit = texture - GL_TEXTURE0;
290   GLuint k;
291   GET_CURRENT_CONTEXT(ctx);
292
293   /* See OpenGL spec for glActiveTexture: */
294   k = MAX2(ctx->Const.MaxCombinedTextureImageUnits,
295            ctx->Const.MaxTextureCoordUnits);
296
297   ASSERT(k <= Elements(ctx->Texture.Unit));
298
299   if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
300      _mesa_debug(ctx, "glActiveTexture %s\n",
301                  _mesa_lookup_enum_by_nr(texture));
302
303   if (texUnit >= k) {
304      _mesa_error(ctx, GL_INVALID_ENUM, "glActiveTexture(texture=%s)",
305                  _mesa_lookup_enum_by_nr(texture));
306      return;
307   }
308
309   if (ctx->Texture.CurrentUnit == texUnit)
310      return;
311
312   FLUSH_VERTICES(ctx, _NEW_TEXTURE);
313
314   ctx->Texture.CurrentUnit = texUnit;
315   if (ctx->Transform.MatrixMode == GL_TEXTURE) {
316      /* update current stack pointer */
317      ctx->CurrentStack = &ctx->TextureMatrixStack[texUnit];
318   }
319}
320
321
322/* GL_ARB_multitexture */
323void GLAPIENTRY
324_mesa_ClientActiveTexture(GLenum texture)
325{
326   GET_CURRENT_CONTEXT(ctx);
327   GLuint texUnit = texture - GL_TEXTURE0;
328
329   if (MESA_VERBOSE & (VERBOSE_API | VERBOSE_TEXTURE))
330      _mesa_debug(ctx, "glClientActiveTexture %s\n",
331                  _mesa_lookup_enum_by_nr(texture));
332
333   if (texUnit >= ctx->Const.MaxTextureCoordUnits) {
334      _mesa_error(ctx, GL_INVALID_ENUM, "glClientActiveTexture(texture)");
335      return;
336   }
337
338   if (ctx->Array.ActiveTexture == texUnit)
339      return;
340
341   FLUSH_VERTICES(ctx, _NEW_ARRAY);
342   ctx->Array.ActiveTexture = texUnit;
343}
344
345
346
347/**********************************************************************/
348/*****                    State management                        *****/
349/**********************************************************************/
350
351
352/**
353 * \note This routine refers to derived texture attribute values to
354 * compute the ENABLE_TEXMAT flags, but is only called on
355 * _NEW_TEXTURE_MATRIX.  On changes to _NEW_TEXTURE, the ENABLE_TEXMAT
356 * flags are updated by _mesa_update_textures(), below.
357 *
358 * \param ctx GL context.
359 */
360static void
361update_texture_matrices( struct gl_context *ctx )
362{
363   GLuint u;
364
365   ctx->Texture._TexMatEnabled = 0x0;
366
367   for (u = 0; u < ctx->Const.MaxTextureCoordUnits; u++) {
368      ASSERT(u < Elements(ctx->TextureMatrixStack));
369      if (_math_matrix_is_dirty(ctx->TextureMatrixStack[u].Top)) {
370	 _math_matrix_analyse( ctx->TextureMatrixStack[u].Top );
371
372	 if (ctx->Texture.Unit[u]._Current &&
373	     ctx->TextureMatrixStack[u].Top->type != MATRIX_IDENTITY)
374	    ctx->Texture._TexMatEnabled |= ENABLE_TEXMAT(u);
375      }
376   }
377}
378
379
380/**
381 * Examine texture unit's combine/env state to update derived state.
382 */
383static void
384update_tex_combine(struct gl_context *ctx, struct gl_texture_unit *texUnit)
385{
386   struct gl_tex_env_combine_state *combine;
387
388   /* No combiners will apply to this. */
389   if (texUnit->_Current->Target == GL_TEXTURE_BUFFER)
390      return;
391
392   /* Set the texUnit->_CurrentCombine field to point to the user's combiner
393    * state, or the combiner state which is derived from traditional texenv
394    * mode.
395    */
396   if (texUnit->EnvMode == GL_COMBINE ||
397       texUnit->EnvMode == GL_COMBINE4_NV) {
398      texUnit->_CurrentCombine = & texUnit->Combine;
399   }
400   else {
401      const struct gl_texture_object *texObj = texUnit->_Current;
402      GLenum format = texObj->Image[0][texObj->BaseLevel]->_BaseFormat;
403
404      if (format == GL_DEPTH_COMPONENT || format == GL_DEPTH_STENCIL_EXT) {
405         format = texObj->DepthMode;
406      }
407      calculate_derived_texenv(&texUnit->_EnvMode, texUnit->EnvMode, format);
408      texUnit->_CurrentCombine = & texUnit->_EnvMode;
409   }
410
411   combine = texUnit->_CurrentCombine;
412
413   /* Determine number of source RGB terms in the combiner function */
414   switch (combine->ModeRGB) {
415   case GL_REPLACE:
416      combine->_NumArgsRGB = 1;
417      break;
418   case GL_ADD:
419   case GL_ADD_SIGNED:
420      if (texUnit->EnvMode == GL_COMBINE4_NV)
421         combine->_NumArgsRGB = 4;
422      else
423         combine->_NumArgsRGB = 2;
424      break;
425   case GL_MODULATE:
426   case GL_SUBTRACT:
427   case GL_DOT3_RGB:
428   case GL_DOT3_RGBA:
429   case GL_DOT3_RGB_EXT:
430   case GL_DOT3_RGBA_EXT:
431      combine->_NumArgsRGB = 2;
432      break;
433   case GL_INTERPOLATE:
434   case GL_MODULATE_ADD_ATI:
435   case GL_MODULATE_SIGNED_ADD_ATI:
436   case GL_MODULATE_SUBTRACT_ATI:
437      combine->_NumArgsRGB = 3;
438      break;
439   default:
440      combine->_NumArgsRGB = 0;
441      _mesa_problem(ctx, "invalid RGB combine mode in update_texture_state");
442      return;
443   }
444
445   /* Determine number of source Alpha terms in the combiner function */
446   switch (combine->ModeA) {
447   case GL_REPLACE:
448      combine->_NumArgsA = 1;
449      break;
450   case GL_ADD:
451   case GL_ADD_SIGNED:
452      if (texUnit->EnvMode == GL_COMBINE4_NV)
453         combine->_NumArgsA = 4;
454      else
455         combine->_NumArgsA = 2;
456      break;
457   case GL_MODULATE:
458   case GL_SUBTRACT:
459      combine->_NumArgsA = 2;
460      break;
461   case GL_INTERPOLATE:
462   case GL_MODULATE_ADD_ATI:
463   case GL_MODULATE_SIGNED_ADD_ATI:
464   case GL_MODULATE_SUBTRACT_ATI:
465      combine->_NumArgsA = 3;
466      break;
467   default:
468      combine->_NumArgsA = 0;
469      _mesa_problem(ctx, "invalid Alpha combine mode in update_texture_state");
470      break;
471   }
472}
473
474static void
475update_texgen(struct gl_context *ctx)
476{
477   GLuint unit;
478
479   /* Setup texgen for those texture coordinate sets that are in use */
480   for (unit = 0; unit < ctx->Const.MaxTextureCoordUnits; unit++) {
481      struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
482
483      texUnit->_GenFlags = 0x0;
484
485      if (!(ctx->Texture._EnabledCoordUnits & (1 << unit)))
486	 continue;
487
488      if (texUnit->TexGenEnabled) {
489	 if (texUnit->TexGenEnabled & S_BIT) {
490	    texUnit->_GenFlags |= texUnit->GenS._ModeBit;
491	 }
492	 if (texUnit->TexGenEnabled & T_BIT) {
493	    texUnit->_GenFlags |= texUnit->GenT._ModeBit;
494	 }
495	 if (texUnit->TexGenEnabled & R_BIT) {
496	    texUnit->_GenFlags |= texUnit->GenR._ModeBit;
497	 }
498	 if (texUnit->TexGenEnabled & Q_BIT) {
499	    texUnit->_GenFlags |= texUnit->GenQ._ModeBit;
500	 }
501
502	 ctx->Texture._TexGenEnabled |= ENABLE_TEXGEN(unit);
503	 ctx->Texture._GenFlags |= texUnit->_GenFlags;
504      }
505
506      ASSERT(unit < Elements(ctx->TextureMatrixStack));
507      if (ctx->TextureMatrixStack[unit].Top->type != MATRIX_IDENTITY)
508	 ctx->Texture._TexMatEnabled |= ENABLE_TEXMAT(unit);
509   }
510}
511
512static struct gl_texture_object *
513update_single_program_texture(struct gl_context *ctx, struct gl_program *prog,
514                              int s)
515{
516   gl_texture_index target_index;
517   struct gl_texture_unit *texUnit;
518   struct gl_texture_object *texObj;
519   struct gl_sampler_object *sampler;
520   int unit;
521
522   if (!(prog->SamplersUsed & (1 << s)))
523      return NULL;
524
525   unit = prog->SamplerUnits[s];
526   texUnit = &ctx->Texture.Unit[unit];
527
528   /* Note: If more than one bit was set in TexturesUsed[unit], then we should
529    * have had the draw call rejected already.  From the GL 4.4 specification,
530    * section 7.10 ("Samplers"):
531    *
532    *     "It is not allowed to have variables of different sampler types
533    *      pointing to the same texture image unit within a program
534    *      object. This situation can only be detected at the next rendering
535    *      command issued which triggers shader invocations, and an
536    *      INVALID_OPERATION error will then be generated."
537    */
538   target_index = ffs(prog->TexturesUsed[unit]) - 1;
539   texObj = texUnit->CurrentTex[target_index];
540
541   sampler = texUnit->Sampler ?
542      texUnit->Sampler : &texObj->Sampler;
543
544   if (likely(texObj)) {
545      if (_mesa_is_texture_complete(texObj, sampler))
546         return texObj;
547
548      _mesa_test_texobj_completeness(ctx, texObj);
549      if (_mesa_is_texture_complete(texObj, sampler))
550         return texObj;
551   }
552
553   /* If we've reached this point, we didn't find a complete texture of the
554    * shader's target.  From the GL 4.4 core specification, section 11.1.3.5
555    * ("Texture Access"):
556    *
557    *     "If a sampler is used in a shader and the sampler’s associated
558    *      texture is not complete, as defined in section 8.17, (0, 0, 0, 1)
559    *      will be returned for a non-shadow sampler and 0 for a shadow
560    *      sampler."
561    *
562    * Mesa implements this by creating a hidden texture object with a pixel of
563    * that value.
564    */
565   texObj = _mesa_get_fallback_texture(ctx, target_index);
566   assert(texObj);
567
568   return texObj;
569}
570
571static void
572update_program_texture_state(struct gl_context *ctx, struct gl_program **prog,
573                             BITSET_WORD *enabled_texture_units)
574{
575   int i;
576
577   for (i = 0; i < MESA_SHADER_STAGES; i++) {
578      int s;
579
580      if (!prog[i])
581         continue;
582
583      /* We can't only do the shifting trick as the loop condition because if
584       * sampler 31 is active, the next iteration tries to shift by 32, which is
585       * undefined.
586       */
587      for (s = 0; s < MAX_SAMPLERS && (1 << s) <= prog[i]->SamplersUsed; s++) {
588         struct gl_texture_object *texObj;
589
590         texObj = update_single_program_texture(ctx, prog[i], s);
591         if (texObj) {
592            int unit = prog[i]->SamplerUnits[s];
593            _mesa_reference_texobj(&ctx->Texture.Unit[unit]._Current, texObj);
594            BITSET_SET(enabled_texture_units, unit);
595            ctx->Texture._MaxEnabledTexImageUnit =
596               MAX2(ctx->Texture._MaxEnabledTexImageUnit, (int)unit);
597         }
598      }
599   }
600
601   if (prog[MESA_SHADER_FRAGMENT]) {
602      const GLuint coordMask = (1 << MAX_TEXTURE_COORD_UNITS) - 1;
603      ctx->Texture._EnabledCoordUnits |=
604         (prog[MESA_SHADER_FRAGMENT]->InputsRead >> VARYING_SLOT_TEX0) &
605         coordMask;
606   }
607}
608
609static void
610update_ff_texture_state(struct gl_context *ctx,
611                        BITSET_WORD *enabled_texture_units)
612{
613   int unit;
614
615   for (unit = 0; unit < ctx->Const.MaxTextureUnits; unit++) {
616      struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
617      GLuint texIndex;
618
619      if (texUnit->Enabled == 0x0)
620         continue;
621
622      /* If a shader already dictated what texture target was used for this
623       * unit, just go along with it.
624       */
625      if (BITSET_TEST(enabled_texture_units, unit))
626         continue;
627
628      /* From the GL 4.4 compat specification, section 16.2 ("Texture Application"):
629       *
630       *     "Texturing is enabled or disabled using the generic Enable and
631       *      Disable commands, respectively, with the symbolic constants
632       *      TEXTURE_1D, TEXTURE_2D, TEXTURE_RECTANGLE, TEXTURE_3D, or
633       *      TEXTURE_CUBE_MAP to enable the one-, two-, rectangular,
634       *      three-dimensional, or cube map texture, respectively. If more
635       *      than one of these textures is enabled, the first one enabled
636       *      from the following list is used:
637       *
638       *      • cube map texture
639       *      • three-dimensional texture
640       *      • rectangular texture
641       *      • two-dimensional texture
642       *      • one-dimensional texture"
643       *
644       * Note that the TEXTURE_x_INDEX values are in high to low priority.
645       * Also:
646       *
647       *     "If a texture unit is disabled or has an invalid or incomplete
648       *      texture (as defined in section 8.17) bound to it, then blending
649       *      is disabled for that texture unit. If the texture environment
650       *      for a given enabled texture unit references a disabled texture
651       *      unit, or an invalid or incomplete texture that is bound to
652       *      another unit, then the results of texture blending are
653       *      undefined."
654       */
655      for (texIndex = 0; texIndex < NUM_TEXTURE_TARGETS; texIndex++) {
656         if (texUnit->Enabled & (1 << texIndex)) {
657            struct gl_texture_object *texObj = texUnit->CurrentTex[texIndex];
658            struct gl_sampler_object *sampler = texUnit->Sampler ?
659               texUnit->Sampler : &texObj->Sampler;
660
661            if (!_mesa_is_texture_complete(texObj, sampler)) {
662               _mesa_test_texobj_completeness(ctx, texObj);
663            }
664            if (_mesa_is_texture_complete(texObj, sampler)) {
665               _mesa_reference_texobj(&texUnit->_Current, texObj);
666               break;
667            }
668         }
669      }
670
671      if (texIndex == NUM_TEXTURE_TARGETS)
672         continue;
673
674      /* if we get here, we know this texture unit is enabled */
675      BITSET_SET(enabled_texture_units, unit);
676      ctx->Texture._MaxEnabledTexImageUnit =
677         MAX2(ctx->Texture._MaxEnabledTexImageUnit, (int)unit);
678
679      ctx->Texture._EnabledCoordUnits |= 1 << unit;
680
681      update_tex_combine(ctx, texUnit);
682   }
683}
684
685/**
686 * \note This routine refers to derived texture matrix values to
687 * compute the ENABLE_TEXMAT flags, but is only called on
688 * _NEW_TEXTURE.  On changes to _NEW_TEXTURE_MATRIX, the ENABLE_TEXMAT
689 * flags are updated by _mesa_update_texture_matrices, above.
690 *
691 * \param ctx GL context.
692 */
693static void
694update_texture_state( struct gl_context *ctx )
695{
696   struct gl_program *prog[MESA_SHADER_STAGES];
697   int i;
698   int old_max_unit = ctx->Texture._MaxEnabledTexImageUnit;
699   BITSET_DECLARE(enabled_texture_units, MAX_COMBINED_TEXTURE_IMAGE_UNITS);
700
701   for (i = 0; i < MESA_SHADER_STAGES; i++) {
702      if (ctx->_Shader->CurrentProgram[i] &&
703          ctx->_Shader->CurrentProgram[i]->LinkStatus) {
704         prog[i] = ctx->_Shader->CurrentProgram[i]->_LinkedShaders[i]->Program;
705      } else {
706         if (i == MESA_SHADER_FRAGMENT && ctx->FragmentProgram._Enabled)
707            prog[i] = &ctx->FragmentProgram.Current->Base;
708         else
709            prog[i] = NULL;
710      }
711   }
712
713   /* TODO: only set this if there are actual changes */
714   ctx->NewState |= _NEW_TEXTURE;
715
716   ctx->Texture._GenFlags = 0x0;
717   ctx->Texture._TexMatEnabled = 0x0;
718   ctx->Texture._TexGenEnabled = 0x0;
719   ctx->Texture._MaxEnabledTexImageUnit = -1;
720   ctx->Texture._EnabledCoordUnits = 0x0;
721
722   memset(&enabled_texture_units, 0, sizeof(enabled_texture_units));
723
724   /* First, walk over our programs pulling in all the textures for them.
725    * Programs dictate specific texture targets to be enabled, and for a draw
726    * call to be valid they can't conflict about which texture targets are
727    * used.
728    */
729   update_program_texture_state(ctx, prog, enabled_texture_units);
730
731   /* Also pull in any textures necessary for fixed function fragment shading.
732    */
733   if (!prog[MESA_SHADER_FRAGMENT])
734      update_ff_texture_state(ctx, enabled_texture_units);
735
736   /* Now, clear out the _Current of any disabled texture units. */
737   for (i = 0; i <= ctx->Texture._MaxEnabledTexImageUnit; i++) {
738      if (!BITSET_TEST(enabled_texture_units, i))
739         _mesa_reference_texobj(&ctx->Texture.Unit[i]._Current, NULL);
740   }
741   for (i = ctx->Texture._MaxEnabledTexImageUnit + 1; i <= old_max_unit; i++) {
742      _mesa_reference_texobj(&ctx->Texture.Unit[i]._Current, NULL);
743   }
744
745   if (!prog[MESA_SHADER_FRAGMENT] || !prog[MESA_SHADER_VERTEX])
746      update_texgen(ctx);
747
748   _mesa_validate_image_units(ctx);
749}
750
751
752/**
753 * Update texture-related derived state.
754 */
755void
756_mesa_update_texture( struct gl_context *ctx, GLuint new_state )
757{
758   if (new_state & _NEW_TEXTURE_MATRIX)
759      update_texture_matrices( ctx );
760
761   if (new_state & (_NEW_TEXTURE | _NEW_PROGRAM))
762      update_texture_state( ctx );
763}
764
765
766/**********************************************************************/
767/*****                      Initialization                        *****/
768/**********************************************************************/
769
770/**
771 * Allocate the proxy textures for the given context.
772 *
773 * \param ctx the context to allocate proxies for.
774 *
775 * \return GL_TRUE on success, or GL_FALSE on failure
776 *
777 * If run out of memory part way through the allocations, clean up and return
778 * GL_FALSE.
779 */
780static GLboolean
781alloc_proxy_textures( struct gl_context *ctx )
782{
783   /* NOTE: these values must be in the same order as the TEXTURE_x_INDEX
784    * values!
785    */
786   static const GLenum targets[] = {
787      GL_TEXTURE_2D_MULTISAMPLE,
788      GL_TEXTURE_2D_MULTISAMPLE_ARRAY,
789      GL_TEXTURE_CUBE_MAP_ARRAY,
790      GL_TEXTURE_BUFFER,
791      GL_TEXTURE_2D_ARRAY_EXT,
792      GL_TEXTURE_1D_ARRAY_EXT,
793      GL_TEXTURE_EXTERNAL_OES,
794      GL_TEXTURE_CUBE_MAP_ARB,
795      GL_TEXTURE_3D,
796      GL_TEXTURE_RECTANGLE_NV,
797      GL_TEXTURE_2D,
798      GL_TEXTURE_1D,
799   };
800   GLint tgt;
801
802   STATIC_ASSERT(Elements(targets) == NUM_TEXTURE_TARGETS);
803   assert(targets[TEXTURE_2D_INDEX] == GL_TEXTURE_2D);
804   assert(targets[TEXTURE_CUBE_INDEX] == GL_TEXTURE_CUBE_MAP);
805
806   for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
807      if (!(ctx->Texture.ProxyTex[tgt]
808            = ctx->Driver.NewTextureObject(ctx, 0, targets[tgt]))) {
809         /* out of memory, free what we did allocate */
810         while (--tgt >= 0) {
811            ctx->Driver.DeleteTexture(ctx, ctx->Texture.ProxyTex[tgt]);
812         }
813         return GL_FALSE;
814      }
815   }
816
817   assert(ctx->Texture.ProxyTex[0]->RefCount == 1); /* sanity check */
818   return GL_TRUE;
819}
820
821
822/**
823 * Initialize a texture unit.
824 *
825 * \param ctx GL context.
826 * \param unit texture unit number to be initialized.
827 */
828static void
829init_texture_unit( struct gl_context *ctx, GLuint unit )
830{
831   struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
832   GLuint tex;
833
834   texUnit->EnvMode = GL_MODULATE;
835   ASSIGN_4V( texUnit->EnvColor, 0.0, 0.0, 0.0, 0.0 );
836
837   texUnit->Combine = default_combine_state;
838   texUnit->_EnvMode = default_combine_state;
839   texUnit->_CurrentCombine = & texUnit->_EnvMode;
840
841   texUnit->TexGenEnabled = 0x0;
842   texUnit->GenS.Mode = GL_EYE_LINEAR;
843   texUnit->GenT.Mode = GL_EYE_LINEAR;
844   texUnit->GenR.Mode = GL_EYE_LINEAR;
845   texUnit->GenQ.Mode = GL_EYE_LINEAR;
846   texUnit->GenS._ModeBit = TEXGEN_EYE_LINEAR;
847   texUnit->GenT._ModeBit = TEXGEN_EYE_LINEAR;
848   texUnit->GenR._ModeBit = TEXGEN_EYE_LINEAR;
849   texUnit->GenQ._ModeBit = TEXGEN_EYE_LINEAR;
850
851   /* Yes, these plane coefficients are correct! */
852   ASSIGN_4V( texUnit->GenS.ObjectPlane, 1.0, 0.0, 0.0, 0.0 );
853   ASSIGN_4V( texUnit->GenT.ObjectPlane, 0.0, 1.0, 0.0, 0.0 );
854   ASSIGN_4V( texUnit->GenR.ObjectPlane, 0.0, 0.0, 0.0, 0.0 );
855   ASSIGN_4V( texUnit->GenQ.ObjectPlane, 0.0, 0.0, 0.0, 0.0 );
856   ASSIGN_4V( texUnit->GenS.EyePlane, 1.0, 0.0, 0.0, 0.0 );
857   ASSIGN_4V( texUnit->GenT.EyePlane, 0.0, 1.0, 0.0, 0.0 );
858   ASSIGN_4V( texUnit->GenR.EyePlane, 0.0, 0.0, 0.0, 0.0 );
859   ASSIGN_4V( texUnit->GenQ.EyePlane, 0.0, 0.0, 0.0, 0.0 );
860
861   /* initialize current texture object ptrs to the shared default objects */
862   for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
863      _mesa_reference_texobj(&texUnit->CurrentTex[tex],
864                             ctx->Shared->DefaultTex[tex]);
865   }
866
867   texUnit->_BoundTextures = 0;
868}
869
870
871/**
872 * Initialize texture state for the given context.
873 */
874GLboolean
875_mesa_init_texture(struct gl_context *ctx)
876{
877   GLuint u;
878
879   /* Texture group */
880   ctx->Texture.CurrentUnit = 0;      /* multitexture */
881
882   /* Appendix F.2 of the OpenGL ES 3.0 spec says:
883    *
884    *     "OpenGL ES 3.0 requires that all cube map filtering be
885    *     seamless. OpenGL ES 2.0 specified that a single cube map face be
886    *     selected and used for filtering."
887    */
888   ctx->Texture.CubeMapSeamless = _mesa_is_gles3(ctx);
889
890   for (u = 0; u < Elements(ctx->Texture.Unit); u++)
891      init_texture_unit(ctx, u);
892
893   /* After we're done initializing the context's texture state the default
894    * texture objects' refcounts should be at least
895    * MAX_COMBINED_TEXTURE_IMAGE_UNITS + 1.
896    */
897   assert(ctx->Shared->DefaultTex[TEXTURE_1D_INDEX]->RefCount
898          >= MAX_COMBINED_TEXTURE_IMAGE_UNITS + 1);
899
900   /* Allocate proxy textures */
901   if (!alloc_proxy_textures( ctx ))
902      return GL_FALSE;
903
904   /* GL_ARB_texture_buffer_object */
905   _mesa_reference_buffer_object(ctx, &ctx->Texture.BufferObject,
906                                 ctx->Shared->NullBufferObj);
907
908   ctx->Texture.NumCurrentTexUsed = 0;
909
910   return GL_TRUE;
911}
912
913
914/**
915 * Free dynamically-allocted texture data attached to the given context.
916 */
917void
918_mesa_free_texture_data(struct gl_context *ctx)
919{
920   GLuint u, tgt;
921
922   /* unreference current textures */
923   for (u = 0; u < Elements(ctx->Texture.Unit); u++) {
924      /* The _Current texture could account for another reference */
925      _mesa_reference_texobj(&ctx->Texture.Unit[u]._Current, NULL);
926
927      for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
928         _mesa_reference_texobj(&ctx->Texture.Unit[u].CurrentTex[tgt], NULL);
929      }
930   }
931
932   /* Free proxy texture objects */
933   for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++)
934      ctx->Driver.DeleteTexture(ctx, ctx->Texture.ProxyTex[tgt]);
935
936   /* GL_ARB_texture_buffer_object */
937   _mesa_reference_buffer_object(ctx, &ctx->Texture.BufferObject, NULL);
938
939   for (u = 0; u < Elements(ctx->Texture.Unit); u++) {
940      _mesa_reference_sampler_object(ctx, &ctx->Texture.Unit[u].Sampler, NULL);
941   }
942}
943
944
945/**
946 * Update the default texture objects in the given context to reference those
947 * specified in the shared state and release those referencing the old
948 * shared state.
949 */
950void
951_mesa_update_default_objects_texture(struct gl_context *ctx)
952{
953   GLuint u, tex;
954
955   for (u = 0; u < Elements(ctx->Texture.Unit); u++) {
956      struct gl_texture_unit *texUnit = &ctx->Texture.Unit[u];
957      for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
958         _mesa_reference_texobj(&texUnit->CurrentTex[tex],
959                                ctx->Shared->DefaultTex[tex]);
960      }
961   }
962}
963