• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**************************************************************************
2  *
3  * Copyright 2007 VMware, Inc.
4  * All Rights Reserved.
5  * Copyright 2009 VMware, Inc.  All Rights Reserved.
6  * Copyright © 2010-2011 Intel Corporation
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the
10  * "Software"), to deal in the Software without restriction, including
11  * without limitation the rights to use, copy, modify, merge, publish,
12  * distribute, sub license, and/or sell copies of the Software, and to
13  * permit persons to whom the Software is furnished to do so, subject to
14  * the following conditions:
15  *
16  * The above copyright notice and this permission notice (including the
17  * next paragraph) shall be included in all copies or substantial portions
18  * of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
23  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
24  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  *
28  **************************************************************************/
29 
30 #include "main/glheader.h"
31 #include "main/context.h"
32 
33 #include "main/macros.h"
34 #include "main/samplerobj.h"
35 #include "main/shaderobj.h"
36 #include "main/state.h"
37 #include "main/texenvprogram.h"
38 #include "main/texobj.h"
39 #include "main/uniforms.h"
40 #include "compiler/glsl/ir_builder.h"
41 #include "compiler/glsl/ir_optimization.h"
42 #include "compiler/glsl/glsl_parser_extras.h"
43 #include "compiler/glsl/glsl_symbol_table.h"
44 #include "compiler/glsl_types.h"
45 #include "program/ir_to_mesa.h"
46 #include "program/program.h"
47 #include "program/programopt.h"
48 #include "program/prog_cache.h"
49 #include "program/prog_instruction.h"
50 #include "program/prog_parameter.h"
51 #include "program/prog_print.h"
52 #include "program/prog_statevars.h"
53 #include "util/bitscan.h"
54 
55 using namespace ir_builder;
56 
57 /*
58  * Note on texture units:
59  *
60  * The number of texture units supported by fixed-function fragment
61  * processing is MAX_TEXTURE_COORD_UNITS, not MAX_TEXTURE_IMAGE_UNITS.
62  * That's because there's a one-to-one correspondence between texture
63  * coordinates and samplers in fixed-function processing.
64  *
65  * Since fixed-function vertex processing is limited to MAX_TEXTURE_COORD_UNITS
66  * sets of texcoords, so is fixed-function fragment processing.
67  *
68  * We can safely use ctx->Const.MaxTextureUnits for loop bounds.
69  */
70 
71 
72 static GLboolean
texenv_doing_secondary_color(struct gl_context * ctx)73 texenv_doing_secondary_color(struct gl_context *ctx)
74 {
75    if (ctx->Light.Enabled &&
76        (ctx->Light.Model.ColorControl == GL_SEPARATE_SPECULAR_COLOR))
77       return GL_TRUE;
78 
79    if (ctx->Fog.ColorSumEnabled)
80       return GL_TRUE;
81 
82    return GL_FALSE;
83 }
84 
85 struct state_key {
86    GLuint nr_enabled_units:4;
87    GLuint separate_specular:1;
88    GLuint fog_mode:2;          /**< FOG_x */
89    GLuint inputs_available:12;
90    GLuint num_draw_buffers:4;
91 
92    /* NOTE: This array of structs must be last! (see "keySize" below) */
93    struct {
94       GLuint enabled:1;
95       GLuint source_index:4;   /**< TEXTURE_x_INDEX */
96       GLuint shadow:1;
97 
98       /***
99        * These are taken from struct gl_tex_env_combine_packed
100        * @{
101        */
102       GLuint ModeRGB:4;
103       GLuint ModeA:4;
104       GLuint ScaleShiftRGB:2;
105       GLuint ScaleShiftA:2;
106       GLuint NumArgsRGB:3;
107       GLuint NumArgsA:3;
108       struct gl_tex_env_argument ArgsRGB[MAX_COMBINER_TERMS];
109       struct gl_tex_env_argument ArgsA[MAX_COMBINER_TERMS];
110       /** @} */
111    } unit[MAX_TEXTURE_COORD_UNITS];
112 };
113 
114 
115 /**
116  * Do we need to clamp the results of the given texture env/combine mode?
117  * If the inputs to the mode are in [0,1] we don't always have to clamp
118  * the results.
119  */
120 static GLboolean
need_saturate(GLuint mode)121 need_saturate( GLuint mode )
122 {
123    switch (mode) {
124    case TEXENV_MODE_REPLACE:
125    case TEXENV_MODE_MODULATE:
126    case TEXENV_MODE_INTERPOLATE:
127       return GL_FALSE;
128    case TEXENV_MODE_ADD:
129    case TEXENV_MODE_ADD_SIGNED:
130    case TEXENV_MODE_SUBTRACT:
131    case TEXENV_MODE_DOT3_RGB:
132    case TEXENV_MODE_DOT3_RGB_EXT:
133    case TEXENV_MODE_DOT3_RGBA:
134    case TEXENV_MODE_DOT3_RGBA_EXT:
135    case TEXENV_MODE_MODULATE_ADD_ATI:
136    case TEXENV_MODE_MODULATE_SIGNED_ADD_ATI:
137    case TEXENV_MODE_MODULATE_SUBTRACT_ATI:
138    case TEXENV_MODE_ADD_PRODUCTS_NV:
139    case TEXENV_MODE_ADD_PRODUCTS_SIGNED_NV:
140       return GL_TRUE;
141    default:
142       assert(0);
143       return GL_FALSE;
144    }
145 }
146 
147 #define VERT_BIT_TEX_ANY    (0xff << VERT_ATTRIB_TEX0)
148 
149 /**
150  * Identify all possible varying inputs.  The fragment program will
151  * never reference non-varying inputs, but will track them via state
152  * constants instead.
153  *
154  * This function figures out all the inputs that the fragment program
155  * has access to and filters input bitmask.
156  */
filter_fp_input_mask(GLbitfield fp_inputs,struct gl_context * ctx)157 static GLbitfield filter_fp_input_mask( GLbitfield fp_inputs,
158 		    struct gl_context *ctx )
159 {
160    if (ctx->VertexProgram._Overriden) {
161       /* Somebody's messing with the vertex program and we don't have
162        * a clue what's happening.  Assume that it could be producing
163        * all possible outputs.
164        */
165       return fp_inputs;
166    }
167 
168    if (ctx->RenderMode == GL_FEEDBACK) {
169       /* _NEW_RENDERMODE */
170       return fp_inputs & (VARYING_BIT_COL0 | VARYING_BIT_TEX0);
171    }
172 
173    /* _NEW_PROGRAM */
174    const GLboolean vertexShader =
175          ctx->_Shader->CurrentProgram[MESA_SHADER_VERTEX] != NULL;
176    const GLboolean vertexProgram = _mesa_arb_vertex_program_enabled(ctx);
177 
178    if (!(vertexProgram || vertexShader)) {
179       /* Fixed function vertex logic */
180       GLbitfield possible_inputs = 0;
181 
182       /* _NEW_VARYING_VP_INPUTS */
183       GLbitfield varying_inputs = ctx->varying_vp_inputs;
184       /* We only update ctx->varying_vp_inputs when in VP_MODE_FF _VPMode */
185       assert(VP_MODE_FF == ctx->VertexProgram._VPMode);
186 
187       /* These get generated in the setup routine regardless of the
188        * vertex program:
189        */
190       /* _NEW_POINT */
191       if (ctx->Point.PointSprite) {
192          /* All texture varyings are possible to use */
193          possible_inputs = VARYING_BITS_TEX_ANY;
194       }
195       else {
196          /* _NEW_TEXTURE_STATE */
197          const GLbitfield possible_tex_inputs =
198                ctx->Texture._TexGenEnabled |
199                ctx->Texture._TexMatEnabled |
200                ((varying_inputs & VERT_BIT_TEX_ANY) >> VERT_ATTRIB_TEX0);
201 
202          possible_inputs = (possible_tex_inputs << VARYING_SLOT_TEX0);
203       }
204 
205       /* First look at what values may be computed by the generated
206        * vertex program:
207        */
208       /* _NEW_LIGHT */
209       if (ctx->Light.Enabled) {
210          possible_inputs |= VARYING_BIT_COL0;
211 
212          if (texenv_doing_secondary_color(ctx))
213             possible_inputs |= VARYING_BIT_COL1;
214       }
215 
216       /* Then look at what might be varying as a result of enabled
217        * arrays, etc:
218        */
219       if (varying_inputs & VERT_BIT_COLOR0)
220          possible_inputs |= VARYING_BIT_COL0;
221       if (varying_inputs & VERT_BIT_COLOR1)
222          possible_inputs |= VARYING_BIT_COL1;
223 
224       return fp_inputs & possible_inputs;
225    }
226 
227    /* calculate from vp->outputs */
228    struct gl_program *vprog;
229 
230    /* Choose GLSL vertex shader over ARB vertex program.  Need this
231     * since vertex shader state validation comes after fragment state
232     * validation (see additional comments in state.c).
233     */
234    if (ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY] != NULL)
235       vprog = ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY];
236    else if (ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL] != NULL)
237       vprog = ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
238    else if (vertexShader)
239       vprog = ctx->_Shader->CurrentProgram[MESA_SHADER_VERTEX];
240    else
241       vprog = ctx->VertexProgram.Current;
242 
243    GLbitfield possible_inputs = vprog->info.outputs_written;
244 
245    /* These get generated in the setup routine regardless of the
246     * vertex program:
247     */
248    /* _NEW_POINT */
249    if (ctx->Point.PointSprite) {
250       /* All texture varyings are possible to use */
251       possible_inputs |= VARYING_BITS_TEX_ANY;
252    }
253 
254    return fp_inputs & possible_inputs;
255 }
256 
257 
258 /**
259  * Examine current texture environment state and generate a unique
260  * key to identify it.
261  */
make_state_key(struct gl_context * ctx,struct state_key * key)262 static GLuint make_state_key( struct gl_context *ctx,  struct state_key *key )
263 {
264    GLbitfield inputs_referenced = VARYING_BIT_COL0;
265    GLbitfield mask;
266    GLuint keySize;
267 
268    memset(key, 0, sizeof(*key));
269 
270    /* _NEW_TEXTURE_OBJECT */
271    mask = ctx->Texture._EnabledCoordUnits;
272    int i = -1;
273    while (mask) {
274       i = u_bit_scan(&mask);
275       const struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
276       const struct gl_texture_object *texObj = texUnit->_Current;
277       const struct gl_tex_env_combine_packed *comb =
278          &ctx->Texture.FixedFuncUnit[i]._CurrentCombinePacked;
279 
280       if (!texObj)
281          continue;
282 
283       key->unit[i].enabled = 1;
284       inputs_referenced |= VARYING_BIT_TEX(i);
285 
286       key->unit[i].source_index = texObj->TargetIndex;
287 
288       const struct gl_sampler_object *samp = _mesa_get_samplerobj(ctx, i);
289       if (samp->CompareMode == GL_COMPARE_R_TO_TEXTURE) {
290          const GLenum format = _mesa_texture_base_format(texObj);
291          key->unit[i].shadow = (format == GL_DEPTH_COMPONENT ||
292 				format == GL_DEPTH_STENCIL_EXT);
293       }
294 
295       key->unit[i].ModeRGB = comb->ModeRGB;
296       key->unit[i].ModeA = comb->ModeA;
297       key->unit[i].ScaleShiftRGB = comb->ScaleShiftRGB;
298       key->unit[i].ScaleShiftA = comb->ScaleShiftA;
299       key->unit[i].NumArgsRGB = comb->NumArgsRGB;
300       key->unit[i].NumArgsA = comb->NumArgsA;
301 
302       memcpy(key->unit[i].ArgsRGB, comb->ArgsRGB, sizeof comb->ArgsRGB);
303       memcpy(key->unit[i].ArgsA, comb->ArgsA, sizeof comb->ArgsA);
304    }
305 
306    key->nr_enabled_units = i + 1;
307 
308    /* _NEW_LIGHT | _NEW_FOG */
309    if (texenv_doing_secondary_color(ctx)) {
310       key->separate_specular = 1;
311       inputs_referenced |= VARYING_BIT_COL1;
312    }
313 
314    /* _NEW_FOG */
315    key->fog_mode = ctx->Fog._PackedEnabledMode;
316 
317    /* _NEW_BUFFERS */
318    key->num_draw_buffers = ctx->DrawBuffer->_NumColorDrawBuffers;
319 
320    /* _NEW_COLOR */
321    if (ctx->Color.AlphaEnabled && key->num_draw_buffers == 0) {
322       /* if alpha test is enabled we need to emit at least one color */
323       key->num_draw_buffers = 1;
324    }
325 
326    key->inputs_available = filter_fp_input_mask(inputs_referenced, ctx);
327 
328    /* compute size of state key, ignoring unused texture units */
329    keySize = sizeof(*key) - sizeof(key->unit)
330       + key->nr_enabled_units * sizeof(key->unit[0]);
331 
332    return keySize;
333 }
334 
335 
336 /** State used to build the fragment program:
337  */
338 class texenv_fragment_program : public ir_factory {
339 public:
340    struct gl_shader_program *shader_program;
341    struct gl_shader *shader;
342    exec_list *top_instructions;
343    struct state_key *state;
344 
345    ir_variable *src_texture[MAX_TEXTURE_COORD_UNITS];
346    /* Reg containing each texture unit's sampled texture color,
347     * else undef.
348     */
349 
350    ir_rvalue *src_previous;	/**< Reg containing color from previous
351 				 * stage.  May need to be decl'd.
352 				 */
353 };
354 
355 static ir_rvalue *
get_current_attrib(texenv_fragment_program * p,GLuint attrib)356 get_current_attrib(texenv_fragment_program *p, GLuint attrib)
357 {
358    ir_variable *current;
359    ir_rvalue *val;
360 
361    current = p->shader->symbols->get_variable("gl_CurrentAttribFragMESA");
362    assert(current);
363    current->data.max_array_access = MAX2(current->data.max_array_access, (int)attrib);
364    val = new(p->mem_ctx) ir_dereference_variable(current);
365    ir_rvalue *index = new(p->mem_ctx) ir_constant(attrib);
366    return new(p->mem_ctx) ir_dereference_array(val, index);
367 }
368 
369 static ir_rvalue *
get_gl_Color(texenv_fragment_program * p)370 get_gl_Color(texenv_fragment_program *p)
371 {
372    if (p->state->inputs_available & VARYING_BIT_COL0) {
373       ir_variable *var = p->shader->symbols->get_variable("gl_Color");
374       assert(var);
375       return new(p->mem_ctx) ir_dereference_variable(var);
376    } else {
377       return get_current_attrib(p, VERT_ATTRIB_COLOR0);
378    }
379 }
380 
381 static ir_rvalue *
get_source(texenv_fragment_program * p,GLuint src,GLuint unit)382 get_source(texenv_fragment_program *p,
383 	   GLuint src, GLuint unit)
384 {
385    ir_variable *var;
386    ir_dereference *deref;
387 
388    switch (src) {
389    case TEXENV_SRC_TEXTURE:
390       return new(p->mem_ctx) ir_dereference_variable(p->src_texture[unit]);
391 
392    case TEXENV_SRC_TEXTURE0:
393    case TEXENV_SRC_TEXTURE1:
394    case TEXENV_SRC_TEXTURE2:
395    case TEXENV_SRC_TEXTURE3:
396    case TEXENV_SRC_TEXTURE4:
397    case TEXENV_SRC_TEXTURE5:
398    case TEXENV_SRC_TEXTURE6:
399    case TEXENV_SRC_TEXTURE7:
400       return new(p->mem_ctx)
401 	 ir_dereference_variable(p->src_texture[src - TEXENV_SRC_TEXTURE0]);
402 
403    case TEXENV_SRC_CONSTANT:
404       var = p->shader->symbols->get_variable("gl_TextureEnvColor");
405       assert(var);
406       deref = new(p->mem_ctx) ir_dereference_variable(var);
407       var->data.max_array_access = MAX2(var->data.max_array_access, (int)unit);
408       return new(p->mem_ctx) ir_dereference_array(deref,
409 						  new(p->mem_ctx) ir_constant(unit));
410 
411    case TEXENV_SRC_PRIMARY_COLOR:
412       var = p->shader->symbols->get_variable("gl_Color");
413       assert(var);
414       return new(p->mem_ctx) ir_dereference_variable(var);
415 
416    case TEXENV_SRC_ZERO:
417       return new(p->mem_ctx) ir_constant(0.0f);
418 
419    case TEXENV_SRC_ONE:
420       return new(p->mem_ctx) ir_constant(1.0f);
421 
422    case TEXENV_SRC_PREVIOUS:
423       if (!p->src_previous) {
424 	 return get_gl_Color(p);
425       } else {
426 	 return p->src_previous->clone(p->mem_ctx, NULL);
427       }
428 
429    default:
430       assert(0);
431       return NULL;
432    }
433 }
434 
435 static ir_rvalue *
emit_combine_source(texenv_fragment_program * p,GLuint unit,GLuint source,GLuint operand)436 emit_combine_source(texenv_fragment_program *p,
437 		    GLuint unit,
438 		    GLuint source,
439 		    GLuint operand)
440 {
441    ir_rvalue *src;
442 
443    src = get_source(p, source, unit);
444 
445    switch (operand) {
446    case TEXENV_OPR_ONE_MINUS_COLOR:
447       return sub(new(p->mem_ctx) ir_constant(1.0f), src);
448 
449    case TEXENV_OPR_ALPHA:
450       return src->type->is_scalar() ? src : swizzle_w(src);
451 
452    case TEXENV_OPR_ONE_MINUS_ALPHA: {
453       ir_rvalue *const scalar = src->type->is_scalar() ? src : swizzle_w(src);
454 
455       return sub(new(p->mem_ctx) ir_constant(1.0f), scalar);
456    }
457 
458    case TEXENV_OPR_COLOR:
459       return src;
460 
461    default:
462       assert(0);
463       return src;
464    }
465 }
466 
467 /**
468  * Check if the RGB and Alpha sources and operands match for the given
469  * texture unit's combinder state.  When the RGB and A sources and
470  * operands match, we can emit fewer instructions.
471  */
args_match(const struct state_key * key,GLuint unit)472 static GLboolean args_match( const struct state_key *key, GLuint unit )
473 {
474    GLuint i, numArgs = key->unit[unit].NumArgsRGB;
475 
476    for (i = 0; i < numArgs; i++) {
477       if (key->unit[unit].ArgsA[i].Source != key->unit[unit].ArgsRGB[i].Source)
478 	 return GL_FALSE;
479 
480       switch (key->unit[unit].ArgsA[i].Operand) {
481       case TEXENV_OPR_ALPHA:
482 	 switch (key->unit[unit].ArgsRGB[i].Operand) {
483 	 case TEXENV_OPR_COLOR:
484 	 case TEXENV_OPR_ALPHA:
485 	    break;
486 	 default:
487 	    return GL_FALSE;
488 	 }
489 	 break;
490       case TEXENV_OPR_ONE_MINUS_ALPHA:
491 	 switch (key->unit[unit].ArgsRGB[i].Operand) {
492 	 case TEXENV_OPR_ONE_MINUS_COLOR:
493 	 case TEXENV_OPR_ONE_MINUS_ALPHA:
494 	    break;
495 	 default:
496 	    return GL_FALSE;
497 	 }
498 	 break;
499       default:
500 	 return GL_FALSE;	/* impossible */
501       }
502    }
503 
504    return GL_TRUE;
505 }
506 
507 static ir_rvalue *
smear(ir_rvalue * val)508 smear(ir_rvalue *val)
509 {
510    if (!val->type->is_scalar())
511       return val;
512 
513    return swizzle_xxxx(val);
514 }
515 
516 static ir_rvalue *
emit_combine(texenv_fragment_program * p,GLuint unit,GLuint nr,GLuint mode,const struct gl_tex_env_argument * opt)517 emit_combine(texenv_fragment_program *p,
518 	     GLuint unit,
519 	     GLuint nr,
520 	     GLuint mode,
521 	     const struct gl_tex_env_argument *opt)
522 {
523    ir_rvalue *src[MAX_COMBINER_TERMS];
524    ir_rvalue *tmp0, *tmp1;
525    GLuint i;
526 
527    assert(nr <= MAX_COMBINER_TERMS);
528 
529    for (i = 0; i < nr; i++)
530       src[i] = emit_combine_source( p, unit, opt[i].Source, opt[i].Operand );
531 
532    switch (mode) {
533    case TEXENV_MODE_REPLACE:
534       return src[0];
535 
536    case TEXENV_MODE_MODULATE:
537       return mul(src[0], src[1]);
538 
539    case TEXENV_MODE_ADD:
540       return add(src[0], src[1]);
541 
542    case TEXENV_MODE_ADD_SIGNED:
543       return add(add(src[0], src[1]), new(p->mem_ctx) ir_constant(-0.5f));
544 
545    case TEXENV_MODE_INTERPOLATE:
546       /* Arg0 * (Arg2) + Arg1 * (1-Arg2) */
547       tmp0 = mul(src[0], src[2]);
548       tmp1 = mul(src[1], sub(new(p->mem_ctx) ir_constant(1.0f),
549 			     src[2]->clone(p->mem_ctx, NULL)));
550       return add(tmp0, tmp1);
551 
552    case TEXENV_MODE_SUBTRACT:
553       return sub(src[0], src[1]);
554 
555    case TEXENV_MODE_DOT3_RGBA:
556    case TEXENV_MODE_DOT3_RGBA_EXT:
557    case TEXENV_MODE_DOT3_RGB_EXT:
558    case TEXENV_MODE_DOT3_RGB: {
559       tmp0 = mul(src[0], new(p->mem_ctx) ir_constant(2.0f));
560       tmp0 = add(tmp0, new(p->mem_ctx) ir_constant(-1.0f));
561 
562       tmp1 = mul(src[1], new(p->mem_ctx) ir_constant(2.0f));
563       tmp1 = add(tmp1, new(p->mem_ctx) ir_constant(-1.0f));
564 
565       return dot(swizzle_xyz(smear(tmp0)), swizzle_xyz(smear(tmp1)));
566    }
567    case TEXENV_MODE_MODULATE_ADD_ATI:
568       return add(mul(src[0], src[2]), src[1]);
569 
570    case TEXENV_MODE_MODULATE_SIGNED_ADD_ATI:
571       return add(add(mul(src[0], src[2]), src[1]),
572 		 new(p->mem_ctx) ir_constant(-0.5f));
573 
574    case TEXENV_MODE_MODULATE_SUBTRACT_ATI:
575       return sub(mul(src[0], src[2]), src[1]);
576 
577    case TEXENV_MODE_ADD_PRODUCTS_NV:
578       return add(mul(src[0], src[1]), mul(src[2], src[3]));
579 
580    case TEXENV_MODE_ADD_PRODUCTS_SIGNED_NV:
581       return add(add(mul(src[0], src[1]), mul(src[2], src[3])),
582 		 new(p->mem_ctx) ir_constant(-0.5f));
583    default:
584       assert(0);
585       return src[0];
586    }
587 }
588 
589 /**
590  * Generate instructions for one texture unit's env/combiner mode.
591  */
592 static ir_rvalue *
emit_texenv(texenv_fragment_program * p,GLuint unit)593 emit_texenv(texenv_fragment_program *p, GLuint unit)
594 {
595    const struct state_key *key = p->state;
596    GLboolean rgb_saturate, alpha_saturate;
597    GLuint rgb_shift, alpha_shift;
598 
599    if (!key->unit[unit].enabled) {
600       return get_source(p, TEXENV_SRC_PREVIOUS, 0);
601    }
602 
603    switch (key->unit[unit].ModeRGB) {
604    case TEXENV_MODE_DOT3_RGB_EXT:
605       alpha_shift = key->unit[unit].ScaleShiftA;
606       rgb_shift = 0;
607       break;
608    case TEXENV_MODE_DOT3_RGBA_EXT:
609       alpha_shift = 0;
610       rgb_shift = 0;
611       break;
612    default:
613       rgb_shift = key->unit[unit].ScaleShiftRGB;
614       alpha_shift = key->unit[unit].ScaleShiftA;
615       break;
616    }
617 
618    /* If we'll do rgb/alpha shifting don't saturate in emit_combine().
619     * We don't want to clamp twice.
620     */
621    if (rgb_shift)
622       rgb_saturate = GL_FALSE;  /* saturate after rgb shift */
623    else if (need_saturate(key->unit[unit].ModeRGB))
624       rgb_saturate = GL_TRUE;
625    else
626       rgb_saturate = GL_FALSE;
627 
628    if (alpha_shift)
629       alpha_saturate = GL_FALSE;  /* saturate after alpha shift */
630    else if (need_saturate(key->unit[unit].ModeA))
631       alpha_saturate = GL_TRUE;
632    else
633       alpha_saturate = GL_FALSE;
634 
635    ir_variable *temp_var = p->make_temp(glsl_type::vec4_type, "texenv_combine");
636    ir_dereference *deref;
637    ir_rvalue *val;
638 
639    /* Emit the RGB and A combine ops
640     */
641    if (key->unit[unit].ModeRGB == key->unit[unit].ModeA &&
642        args_match(key, unit)) {
643       val = emit_combine(p, unit,
644 			 key->unit[unit].NumArgsRGB,
645 			 key->unit[unit].ModeRGB,
646 			 key->unit[unit].ArgsRGB);
647       val = smear(val);
648       if (rgb_saturate)
649 	 val = saturate(val);
650 
651       p->emit(assign(temp_var, val));
652    }
653    else if (key->unit[unit].ModeRGB == TEXENV_MODE_DOT3_RGBA_EXT ||
654 	    key->unit[unit].ModeRGB == TEXENV_MODE_DOT3_RGBA) {
655       ir_rvalue *val = emit_combine(p, unit,
656 				    key->unit[unit].NumArgsRGB,
657 				    key->unit[unit].ModeRGB,
658 				    key->unit[unit].ArgsRGB);
659       val = smear(val);
660       if (rgb_saturate)
661 	 val = saturate(val);
662       p->emit(assign(temp_var, val));
663    }
664    else {
665       /* Need to do something to stop from re-emitting identical
666        * argument calculations here:
667        */
668       val = emit_combine(p, unit,
669 			 key->unit[unit].NumArgsRGB,
670 			 key->unit[unit].ModeRGB,
671 			 key->unit[unit].ArgsRGB);
672       val = swizzle_xyz(smear(val));
673       if (rgb_saturate)
674 	 val = saturate(val);
675       p->emit(assign(temp_var, val, WRITEMASK_XYZ));
676 
677       val = emit_combine(p, unit,
678 			 key->unit[unit].NumArgsA,
679 			 key->unit[unit].ModeA,
680 			 key->unit[unit].ArgsA);
681       val = swizzle_w(smear(val));
682       if (alpha_saturate)
683 	 val = saturate(val);
684       p->emit(assign(temp_var, val, WRITEMASK_W));
685    }
686 
687    deref = new(p->mem_ctx) ir_dereference_variable(temp_var);
688 
689    /* Deal with the final shift:
690     */
691    if (alpha_shift || rgb_shift) {
692       ir_constant *shift;
693 
694       if (rgb_shift == alpha_shift) {
695 	 shift = new(p->mem_ctx) ir_constant((float)(1 << rgb_shift));
696       }
697       else {
698          ir_constant_data const_data;
699 
700          const_data.f[0] = float(1 << rgb_shift);
701          const_data.f[1] = float(1 << rgb_shift);
702          const_data.f[2] = float(1 << rgb_shift);
703          const_data.f[3] = float(1 << alpha_shift);
704 
705          shift = new(p->mem_ctx) ir_constant(glsl_type::vec4_type,
706                                              &const_data);
707       }
708 
709       return saturate(mul(deref, shift));
710    }
711    else
712       return deref;
713 }
714 
715 
716 /**
717  * Generate instruction for getting a texture source term.
718  */
load_texture(texenv_fragment_program * p,GLuint unit)719 static void load_texture( texenv_fragment_program *p, GLuint unit )
720 {
721    ir_dereference *deref;
722 
723    if (p->src_texture[unit])
724       return;
725 
726    const GLuint texTarget = p->state->unit[unit].source_index;
727    ir_rvalue *texcoord;
728 
729    if (!(p->state->inputs_available & (VARYING_BIT_TEX0 << unit))) {
730       texcoord = get_current_attrib(p, VERT_ATTRIB_TEX0 + unit);
731    } else {
732       ir_variable *tc_array = p->shader->symbols->get_variable("gl_TexCoord");
733       assert(tc_array);
734       texcoord = new(p->mem_ctx) ir_dereference_variable(tc_array);
735       ir_rvalue *index = new(p->mem_ctx) ir_constant(unit);
736       texcoord = new(p->mem_ctx) ir_dereference_array(texcoord, index);
737       tc_array->data.max_array_access = MAX2(tc_array->data.max_array_access, (int)unit);
738    }
739 
740    if (!p->state->unit[unit].enabled) {
741       p->src_texture[unit] = p->make_temp(glsl_type::vec4_type,
742 					  "dummy_tex");
743       p->emit(p->src_texture[unit]);
744 
745       p->emit(assign(p->src_texture[unit], new(p->mem_ctx) ir_constant(0.0f)));
746       return ;
747    }
748 
749    const glsl_type *sampler_type = NULL;
750    int coords = 0;
751 
752    switch (texTarget) {
753    case TEXTURE_1D_INDEX:
754       if (p->state->unit[unit].shadow)
755 	 sampler_type = glsl_type::sampler1DShadow_type;
756       else
757 	 sampler_type = glsl_type::sampler1D_type;
758       coords = 1;
759       break;
760    case TEXTURE_1D_ARRAY_INDEX:
761       if (p->state->unit[unit].shadow)
762 	 sampler_type = glsl_type::sampler1DArrayShadow_type;
763       else
764 	 sampler_type = glsl_type::sampler1DArray_type;
765       coords = 2;
766       break;
767    case TEXTURE_2D_INDEX:
768       if (p->state->unit[unit].shadow)
769 	 sampler_type = glsl_type::sampler2DShadow_type;
770       else
771 	 sampler_type = glsl_type::sampler2D_type;
772       coords = 2;
773       break;
774    case TEXTURE_2D_ARRAY_INDEX:
775       if (p->state->unit[unit].shadow)
776 	 sampler_type = glsl_type::sampler2DArrayShadow_type;
777       else
778 	 sampler_type = glsl_type::sampler2DArray_type;
779       coords = 3;
780       break;
781    case TEXTURE_RECT_INDEX:
782       if (p->state->unit[unit].shadow)
783 	 sampler_type = glsl_type::sampler2DRectShadow_type;
784       else
785 	 sampler_type = glsl_type::sampler2DRect_type;
786       coords = 2;
787       break;
788    case TEXTURE_3D_INDEX:
789       assert(!p->state->unit[unit].shadow);
790       sampler_type = glsl_type::sampler3D_type;
791       coords = 3;
792       break;
793    case TEXTURE_CUBE_INDEX:
794       if (p->state->unit[unit].shadow)
795 	 sampler_type = glsl_type::samplerCubeShadow_type;
796       else
797 	 sampler_type = glsl_type::samplerCube_type;
798       coords = 3;
799       break;
800    case TEXTURE_EXTERNAL_INDEX:
801       assert(!p->state->unit[unit].shadow);
802       sampler_type = glsl_type::samplerExternalOES_type;
803       coords = 2;
804       break;
805    }
806 
807    p->src_texture[unit] = p->make_temp(glsl_type::vec4_type,
808 				       "tex");
809 
810    ir_texture *tex = new(p->mem_ctx) ir_texture(ir_tex);
811 
812 
813    char *sampler_name = ralloc_asprintf(p->mem_ctx, "sampler_%d", unit);
814    ir_variable *sampler = new(p->mem_ctx) ir_variable(sampler_type,
815 						      sampler_name,
816 						      ir_var_uniform);
817    p->top_instructions->push_head(sampler);
818 
819    /* Set the texture unit for this sampler in the same way that
820     * layout(binding=X) would.
821     */
822    sampler->data.explicit_binding = true;
823    sampler->data.binding = unit;
824 
825    deref = new(p->mem_ctx) ir_dereference_variable(sampler);
826    tex->set_sampler(deref, glsl_type::vec4_type);
827 
828    tex->coordinate = new(p->mem_ctx) ir_swizzle(texcoord, 0, 1, 2, 3, coords);
829 
830    if (p->state->unit[unit].shadow) {
831       texcoord = texcoord->clone(p->mem_ctx, NULL);
832       tex->shadow_comparator = new(p->mem_ctx) ir_swizzle(texcoord,
833 							  coords, 0, 0, 0,
834 							  1);
835       coords++;
836    }
837 
838    texcoord = texcoord->clone(p->mem_ctx, NULL);
839    tex->projector = swizzle_w(texcoord);
840 
841    p->emit(assign(p->src_texture[unit], tex));
842 }
843 
844 static void
load_texenv_source(texenv_fragment_program * p,GLuint src,GLuint unit)845 load_texenv_source(texenv_fragment_program *p,
846 		   GLuint src, GLuint unit)
847 {
848    switch (src) {
849    case TEXENV_SRC_TEXTURE:
850       load_texture(p, unit);
851       break;
852 
853    case TEXENV_SRC_TEXTURE0:
854    case TEXENV_SRC_TEXTURE1:
855    case TEXENV_SRC_TEXTURE2:
856    case TEXENV_SRC_TEXTURE3:
857    case TEXENV_SRC_TEXTURE4:
858    case TEXENV_SRC_TEXTURE5:
859    case TEXENV_SRC_TEXTURE6:
860    case TEXENV_SRC_TEXTURE7:
861       load_texture(p, src - TEXENV_SRC_TEXTURE0);
862       break;
863 
864    default:
865       /* not a texture src - do nothing */
866       break;
867    }
868 }
869 
870 
871 /**
872  * Generate instructions for loading all texture source terms.
873  */
874 static GLboolean
load_texunit_sources(texenv_fragment_program * p,GLuint unit)875 load_texunit_sources( texenv_fragment_program *p, GLuint unit )
876 {
877    const struct state_key *key = p->state;
878    GLuint i;
879 
880    for (i = 0; i < key->unit[unit].NumArgsRGB; i++) {
881       load_texenv_source( p, key->unit[unit].ArgsRGB[i].Source, unit );
882    }
883 
884    for (i = 0; i < key->unit[unit].NumArgsA; i++) {
885       load_texenv_source( p, key->unit[unit].ArgsA[i].Source, unit );
886    }
887 
888    return GL_TRUE;
889 }
890 
891 /**
892  * Applies the fog calculations.
893  *
894  * This is basically like the ARB_fragment_prorgam fog options.  Note
895  * that ffvertex_prog.c produces fogcoord for us when
896  * GL_FOG_COORDINATE_EXT is set to GL_FRAGMENT_DEPTH_EXT.
897  */
898 static ir_rvalue *
emit_fog_instructions(texenv_fragment_program * p,ir_rvalue * fragcolor)899 emit_fog_instructions(texenv_fragment_program *p,
900 		      ir_rvalue *fragcolor)
901 {
902    struct state_key *key = p->state;
903    ir_rvalue *f, *temp;
904    ir_variable *params, *oparams;
905    ir_variable *fogcoord;
906 
907    /* Temporary storage for the whole fog result.  Fog calculations
908     * only affect rgb so we're hanging on to the .a value of fragcolor
909     * this way.
910     */
911    ir_variable *fog_result = p->make_temp(glsl_type::vec4_type, "fog_result");
912    p->emit(assign(fog_result, fragcolor));
913 
914    fragcolor = swizzle_xyz(fog_result);
915 
916    oparams = p->shader->symbols->get_variable("gl_FogParamsOptimizedMESA");
917    assert(oparams);
918    fogcoord = p->shader->symbols->get_variable("gl_FogFragCoord");
919    assert(fogcoord);
920    params = p->shader->symbols->get_variable("gl_Fog");
921    assert(params);
922    f = new(p->mem_ctx) ir_dereference_variable(fogcoord);
923 
924    ir_variable *f_var = p->make_temp(glsl_type::float_type, "fog_factor");
925 
926    switch (key->fog_mode) {
927    case FOG_LINEAR:
928       /* f = (end - z) / (end - start)
929        *
930        * gl_MesaFogParamsOptimized gives us (-1 / (end - start)) and
931        * (end / (end - start)) so we can generate a single MAD.
932        */
933       f = add(mul(f, swizzle_x(oparams)), swizzle_y(oparams));
934       break;
935    case FOG_EXP:
936       /* f = e^(-(density * fogcoord))
937        *
938        * gl_MesaFogParamsOptimized gives us density/ln(2) so we can
939        * use EXP2 which is generally the native instruction without
940        * having to do any further math on the fog density uniform.
941        */
942       f = mul(f, swizzle_z(oparams));
943       f = new(p->mem_ctx) ir_expression(ir_unop_neg, f);
944       f = new(p->mem_ctx) ir_expression(ir_unop_exp2, f);
945       break;
946    case FOG_EXP2:
947       /* f = e^(-(density * fogcoord)^2)
948        *
949        * gl_MesaFogParamsOptimized gives us density/sqrt(ln(2)) so we
950        * can do this like FOG_EXP but with a squaring after the
951        * multiply by density.
952        */
953       ir_variable *temp_var = p->make_temp(glsl_type::float_type, "fog_temp");
954       p->emit(assign(temp_var, mul(f, swizzle_w(oparams))));
955 
956       f = mul(temp_var, temp_var);
957       f = new(p->mem_ctx) ir_expression(ir_unop_neg, f);
958       f = new(p->mem_ctx) ir_expression(ir_unop_exp2, f);
959       break;
960    }
961 
962    p->emit(assign(f_var, saturate(f)));
963 
964    f = sub(new(p->mem_ctx) ir_constant(1.0f), f_var);
965    temp = new(p->mem_ctx) ir_dereference_variable(params);
966    temp = new(p->mem_ctx) ir_dereference_record(temp, "color");
967    temp = mul(swizzle_xyz(temp), f);
968 
969    p->emit(assign(fog_result, add(temp, mul(fragcolor, f_var)), WRITEMASK_XYZ));
970 
971    return new(p->mem_ctx) ir_dereference_variable(fog_result);
972 }
973 
974 static void
emit_instructions(texenv_fragment_program * p)975 emit_instructions(texenv_fragment_program *p)
976 {
977    struct state_key *key = p->state;
978    GLuint unit;
979 
980    if (key->nr_enabled_units) {
981       /* First pass - to support texture_env_crossbar, first identify
982        * all referenced texture sources and emit texld instructions
983        * for each:
984        */
985       for (unit = 0; unit < key->nr_enabled_units; unit++)
986 	 if (key->unit[unit].enabled) {
987 	    load_texunit_sources(p, unit);
988 	 }
989 
990       /* Second pass - emit combine instructions to build final color:
991        */
992       for (unit = 0; unit < key->nr_enabled_units; unit++) {
993 	 if (key->unit[unit].enabled) {
994 	    p->src_previous = emit_texenv(p, unit);
995 	 }
996       }
997    }
998 
999    ir_rvalue *cf = get_source(p, TEXENV_SRC_PREVIOUS, 0);
1000 
1001    if (key->separate_specular) {
1002       ir_variable *spec_result = p->make_temp(glsl_type::vec4_type,
1003 					      "specular_add");
1004       p->emit(assign(spec_result, cf));
1005 
1006       ir_rvalue *secondary;
1007       if (p->state->inputs_available & VARYING_BIT_COL1) {
1008 	 ir_variable *var =
1009 	    p->shader->symbols->get_variable("gl_SecondaryColor");
1010 	 assert(var);
1011 	 secondary = swizzle_xyz(var);
1012       } else {
1013 	 secondary = swizzle_xyz(get_current_attrib(p, VERT_ATTRIB_COLOR1));
1014       }
1015 
1016       p->emit(assign(spec_result, add(swizzle_xyz(spec_result), secondary),
1017 		     WRITEMASK_XYZ));
1018 
1019       cf = new(p->mem_ctx) ir_dereference_variable(spec_result);
1020    }
1021 
1022    if (key->fog_mode) {
1023       cf = emit_fog_instructions(p, cf);
1024    }
1025 
1026    ir_variable *frag_color = p->shader->symbols->get_variable("gl_FragColor");
1027    assert(frag_color);
1028    p->emit(assign(frag_color, cf));
1029 }
1030 
1031 /**
1032  * Generate a new fragment program which implements the context's
1033  * current texture env/combine mode.
1034  */
1035 static struct gl_shader_program *
create_new_program(struct gl_context * ctx,struct state_key * key)1036 create_new_program(struct gl_context *ctx, struct state_key *key)
1037 {
1038    texenv_fragment_program p;
1039    unsigned int unit;
1040    _mesa_glsl_parse_state *state;
1041 
1042    p.mem_ctx = ralloc_context(NULL);
1043    p.shader = _mesa_new_shader(0, MESA_SHADER_FRAGMENT);
1044 #ifdef DEBUG
1045    p.shader->SourceChecksum = 0xf18ed; /* fixed */
1046 #endif
1047    p.shader->ir = new(p.shader) exec_list;
1048    state = new(p.shader) _mesa_glsl_parse_state(ctx, MESA_SHADER_FRAGMENT,
1049 						p.shader);
1050    p.shader->symbols = state->symbols;
1051    p.top_instructions = p.shader->ir;
1052    p.instructions = p.shader->ir;
1053    p.state = key;
1054    p.shader_program = _mesa_new_shader_program(0);
1055 
1056    /* Tell the linker to ignore the fact that we're building a
1057     * separate shader, in case we're in a GLES2 context that would
1058     * normally reject that.  The real problem is that we're building a
1059     * fixed function program in a GLES2 context at all, but that's a
1060     * big mess to clean up.
1061     */
1062    p.shader_program->SeparateShader = GL_TRUE;
1063 
1064    /* The legacy GLSL shadow functions follow the depth texture
1065     * mode and return vec4. The GLSL 1.30 shadow functions return float and
1066     * ignore the depth texture mode. That's a shader and state dependency
1067     * that's difficult to deal with. st/mesa uses a simple but not
1068     * completely correct solution: if the shader declares GLSL >= 1.30 and
1069     * the depth texture mode is GL_ALPHA (000X), it sets the XXXX swizzle
1070     * instead. Thus, the GLSL 1.30 shadow function will get the result in .x
1071     * and legacy shadow functions will get it in .w as expected.
1072     * For the fixed-function fragment shader, use 120 to get correct behavior
1073     * for GL_ALPHA.
1074     */
1075    state->language_version = 120;
1076 
1077    state->es_shader = false;
1078    if (_mesa_is_gles(ctx) && ctx->Extensions.OES_EGL_image_external)
1079       state->OES_EGL_image_external_enable = true;
1080    _mesa_glsl_initialize_types(state);
1081    _mesa_glsl_initialize_variables(p.instructions, state);
1082 
1083    for (unit = 0; unit < ctx->Const.MaxTextureUnits; unit++)
1084       p.src_texture[unit] = NULL;
1085 
1086    p.src_previous = NULL;
1087 
1088    ir_function *main_f = new(p.mem_ctx) ir_function("main");
1089    p.emit(main_f);
1090    state->symbols->add_function(main_f);
1091 
1092    ir_function_signature *main_sig =
1093       new(p.mem_ctx) ir_function_signature(glsl_type::void_type);
1094    main_sig->is_defined = true;
1095    main_f->add_signature(main_sig);
1096 
1097    p.instructions = &main_sig->body;
1098    if (key->num_draw_buffers)
1099       emit_instructions(&p);
1100 
1101    validate_ir_tree(p.shader->ir);
1102 
1103    const struct gl_shader_compiler_options *options =
1104       &ctx->Const.ShaderCompilerOptions[MESA_SHADER_FRAGMENT];
1105 
1106    /* Conservative approach: Don't optimize here, the linker does it too. */
1107    if (!ctx->Const.GLSLOptimizeConservatively) {
1108       while (do_common_optimization(p.shader->ir, false, false, options,
1109                                     ctx->Const.NativeIntegers))
1110          ;
1111    }
1112 
1113    reparent_ir(p.shader->ir, p.shader->ir);
1114 
1115    p.shader->CompileStatus = COMPILE_SUCCESS;
1116    p.shader->Version = state->language_version;
1117    p.shader_program->Shaders =
1118       (gl_shader **)malloc(sizeof(*p.shader_program->Shaders));
1119    p.shader_program->Shaders[0] = p.shader;
1120    p.shader_program->NumShaders = 1;
1121 
1122    _mesa_glsl_link_shader(ctx, p.shader_program);
1123 
1124    if (!p.shader_program->data->LinkStatus)
1125       _mesa_problem(ctx, "Failed to link fixed function fragment shader: %s\n",
1126                     p.shader_program->data->InfoLog);
1127 
1128    ralloc_free(p.mem_ctx);
1129    return p.shader_program;
1130 }
1131 
1132 extern "C" {
1133 
1134 /**
1135  * Return a fragment program which implements the current
1136  * fixed-function texture, fog and color-sum operations.
1137  */
1138 struct gl_shader_program *
_mesa_get_fixed_func_fragment_program(struct gl_context * ctx)1139 _mesa_get_fixed_func_fragment_program(struct gl_context *ctx)
1140 {
1141    struct gl_shader_program *shader_program;
1142    struct state_key key;
1143    GLuint keySize;
1144 
1145    keySize = make_state_key(ctx, &key);
1146 
1147    shader_program = (struct gl_shader_program *)
1148       _mesa_search_program_cache(ctx->FragmentProgram.Cache,
1149                                  &key, keySize);
1150 
1151    if (!shader_program) {
1152       shader_program = create_new_program(ctx, &key);
1153 
1154       _mesa_shader_cache_insert(ctx, ctx->FragmentProgram.Cache,
1155 				&key, keySize, shader_program);
1156    }
1157 
1158    return shader_program;
1159 }
1160 
1161 }
1162