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