d3d10core: Implement d3d10_device_GSSetShader().
[wine] / dlls / wined3d / glsl_shader.c
1 /*
2  * GLSL pixel and vertex shader implementation
3  *
4  * Copyright 2006 Jason Green
5  * Copyright 2006-2007 Henri Verbeet
6  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7  * Copyright 2009-2011 Henri Verbeet for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 /*
25  * D3D shader asm has swizzles on source parameters, and write masks for
26  * destination parameters. GLSL uses swizzles for both. The result of this is
27  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29  * mask for the destination parameter into account.
30  */
31
32 #include "config.h"
33 #include "wine/port.h"
34
35 #include <limits.h>
36 #include <stdio.h>
37
38 #include "wined3d_private.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
41 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
42 WINE_DECLARE_DEBUG_CHANNEL(d3d);
43 WINE_DECLARE_DEBUG_CHANNEL(winediag);
44
45 #define WINED3D_GLSL_SAMPLE_PROJECTED   0x1
46 #define WINED3D_GLSL_SAMPLE_RECT        0x2
47 #define WINED3D_GLSL_SAMPLE_LOD         0x4
48 #define WINED3D_GLSL_SAMPLE_GRAD        0x8
49
50 struct glsl_dst_param
51 {
52     char reg_name[150];
53     char mask_str[6];
54 };
55
56 struct glsl_src_param
57 {
58     char reg_name[150];
59     char param_str[200];
60 };
61
62 struct glsl_sample_function
63 {
64     const char *name;
65     DWORD coord_mask;
66 };
67
68 enum heap_node_op
69 {
70     HEAP_NODE_TRAVERSE_LEFT,
71     HEAP_NODE_TRAVERSE_RIGHT,
72     HEAP_NODE_POP,
73 };
74
75 struct constant_entry
76 {
77     unsigned int idx;
78     unsigned int version;
79 };
80
81 struct constant_heap
82 {
83     struct constant_entry *entries;
84     unsigned int *positions;
85     unsigned int size;
86 };
87
88 /* GLSL shader private data */
89 struct shader_glsl_priv {
90     struct wined3d_shader_buffer shader_buffer;
91     struct wine_rb_tree program_lookup;
92     struct glsl_shader_prog_link *glsl_program;
93     struct constant_heap vconst_heap;
94     struct constant_heap pconst_heap;
95     unsigned char *stack;
96     GLhandleARB depth_blt_program_full[tex_type_count];
97     GLhandleARB depth_blt_program_masked[tex_type_count];
98     UINT next_constant_version;
99
100     const struct fragment_pipeline *fragment_pipe;
101     struct wine_rb_tree ffp_fragment_shaders;
102 };
103
104 struct glsl_vs_program
105 {
106     struct list shader_entry;
107     GLhandleARB id;
108     GLenum vertex_color_clamp;
109     GLint *uniform_f_locations;
110     GLint uniform_i_locations[MAX_CONST_I];
111     GLint pos_fixup_location;
112 };
113
114 struct glsl_ps_program
115 {
116     struct list shader_entry;
117     GLhandleARB id;
118     GLint *uniform_f_locations;
119     GLint uniform_i_locations[MAX_CONST_I];
120     GLint bumpenv_mat_location[MAX_TEXTURES];
121     GLint bumpenv_lum_scale_location[MAX_TEXTURES];
122     GLint bumpenv_lum_offset_location[MAX_TEXTURES];
123     GLint tex_factor_location;
124     GLint specular_enable_location;
125     GLint ycorrection_location;
126     GLint np2_fixup_location;
127     const struct ps_np2fixup_info *np2_fixup_info;
128 };
129
130 /* Struct to maintain data about a linked GLSL program */
131 struct glsl_shader_prog_link
132 {
133     struct wine_rb_entry program_lookup_entry;
134     struct glsl_vs_program vs;
135     struct glsl_ps_program ps;
136     GLhandleARB programId;
137     UINT constant_version;
138 };
139
140 struct glsl_program_key
141 {
142     GLhandleARB vs_id;
143     GLhandleARB ps_id;
144 };
145
146 struct shader_glsl_ctx_priv {
147     const struct vs_compile_args    *cur_vs_args;
148     const struct ps_compile_args    *cur_ps_args;
149     struct ps_np2fixup_info         *cur_np2fixup_info;
150 };
151
152 struct glsl_ps_compiled_shader
153 {
154     struct ps_compile_args          args;
155     struct ps_np2fixup_info         np2fixup;
156     GLhandleARB                     prgId;
157 };
158
159 struct glsl_vs_compiled_shader
160 {
161     struct vs_compile_args          args;
162     GLhandleARB                     prgId;
163 };
164
165 struct glsl_shader_private
166 {
167     union
168     {
169         struct glsl_vs_compiled_shader *vs;
170         struct glsl_ps_compiled_shader *ps;
171     } gl_shaders;
172     UINT num_gl_shaders, shader_array_size;
173 };
174
175 struct glsl_ffp_fragment_shader
176 {
177     struct ffp_frag_desc entry;
178     GLhandleARB id;
179     struct list linked_programs;
180 };
181
182 static const char *debug_gl_shader_type(GLenum type)
183 {
184     switch (type)
185     {
186 #define WINED3D_TO_STR(u) case u: return #u
187         WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
188         WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
189         WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
190 #undef WINED3D_TO_STR
191         default:
192             return wine_dbg_sprintf("UNKNOWN(%#x)", type);
193     }
194 }
195
196 static const char *shader_glsl_get_prefix(enum wined3d_shader_type type)
197 {
198     switch (type)
199     {
200         case WINED3D_SHADER_TYPE_VERTEX:
201             return "vs";
202
203         case WINED3D_SHADER_TYPE_GEOMETRY:
204             return "gs";
205
206         case WINED3D_SHADER_TYPE_PIXEL:
207             return "ps";
208
209         default:
210             FIXME("Unhandled shader type %#x.\n", type);
211             return "unknown";
212     }
213 }
214
215 /* Extract a line from the info log.
216  * Note that this modifies the source string. */
217 static char *get_info_log_line(char **ptr)
218 {
219     char *p, *q;
220
221     p = *ptr;
222     if (!(q = strstr(p, "\n")))
223     {
224         if (!*p) return NULL;
225         *ptr += strlen(p);
226         return p;
227     }
228     *q = '\0';
229     *ptr = q + 1;
230
231     return p;
232 }
233
234 /** Prints the GLSL info log which will contain error messages if they exist */
235 /* GL locking is done by the caller */
236 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
237 {
238     int infologLength = 0;
239     char *infoLog;
240
241     if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
242         return;
243
244     GL_EXTCALL(glGetObjectParameterivARB(obj,
245                GL_OBJECT_INFO_LOG_LENGTH_ARB,
246                &infologLength));
247
248     /* A size of 1 is just a null-terminated string, so the log should be bigger than
249      * that if there are errors. */
250     if (infologLength > 1)
251     {
252         char *ptr, *line;
253
254         infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
255         /* The info log is supposed to be zero-terminated, but at least some
256          * versions of fglrx don't terminate the string properly. The reported
257          * length does include the terminator, so explicitly set it to zero
258          * here. */
259         infoLog[infologLength - 1] = 0;
260         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
261
262         ptr = infoLog;
263         if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
264         {
265             WARN("Info log received from GLSL shader #%u:\n", obj);
266             while ((line = get_info_log_line(&ptr))) WARN("    %s\n", line);
267         }
268         else
269         {
270             FIXME("Info log received from GLSL shader #%u:\n", obj);
271             while ((line = get_info_log_line(&ptr))) FIXME("    %s\n", line);
272         }
273         HeapFree(GetProcessHeap(), 0, infoLog);
274     }
275 }
276
277 /* GL locking is done by the caller. */
278 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
279 {
280     TRACE("Compiling shader object %u.\n", shader);
281     GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
282     checkGLcall("glShaderSourceARB");
283     GL_EXTCALL(glCompileShaderARB(shader));
284     checkGLcall("glCompileShaderARB");
285     print_glsl_info_log(gl_info, shader);
286 }
287
288 /* GL locking is done by the caller. */
289 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
290 {
291     GLint i, object_count, source_size = -1;
292     GLhandleARB *objects;
293     char *source = NULL;
294
295     GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
296     objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
297     if (!objects)
298     {
299         ERR("Failed to allocate object array memory.\n");
300         return;
301     }
302
303     GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
304     for (i = 0; i < object_count; ++i)
305     {
306         char *ptr, *line;
307         GLint tmp;
308
309         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
310
311         if (source_size < tmp)
312         {
313             HeapFree(GetProcessHeap(), 0, source);
314
315             source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
316             if (!source)
317             {
318                 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
319                 HeapFree(GetProcessHeap(), 0, objects);
320                 return;
321             }
322             source_size = tmp;
323         }
324
325         FIXME("Object %u:\n", objects[i]);
326         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
327         FIXME("    GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
328         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
329         FIXME("    GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
330         FIXME("\n");
331
332         ptr = source;
333         GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
334         while ((line = get_info_log_line(&ptr))) FIXME("    %s\n", line);
335         FIXME("\n");
336     }
337
338     HeapFree(GetProcessHeap(), 0, source);
339     HeapFree(GetProcessHeap(), 0, objects);
340 }
341
342 /* GL locking is done by the caller. */
343 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
344 {
345     GLint tmp;
346
347     if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
348
349     GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
350     if (tmp == GL_PROGRAM_OBJECT_ARB)
351     {
352         GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
353         if (!tmp)
354         {
355             FIXME("Program %u link status invalid.\n", program);
356             shader_glsl_dump_program_source(gl_info, program);
357         }
358     }
359
360     print_glsl_info_log(gl_info, program);
361 }
362
363 /**
364  * Loads (pixel shader) samplers
365  */
366 /* GL locking is done by the caller */
367 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
368         const DWORD *tex_unit_map, GLhandleARB programId)
369 {
370     GLint name_loc;
371     char sampler_name[20];
372     unsigned int i;
373
374     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
375     {
376         snprintf(sampler_name, sizeof(sampler_name), "ps_sampler%u", i);
377         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
378         if (name_loc != -1) {
379             DWORD mapped_unit = tex_unit_map[i];
380             if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
381             {
382                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
383                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
384                 checkGLcall("glUniform1iARB");
385             } else {
386                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
387             }
388         }
389     }
390 }
391
392 /* GL locking is done by the caller */
393 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
394         const DWORD *tex_unit_map, GLhandleARB programId)
395 {
396     GLint name_loc;
397     char sampler_name[20];
398     unsigned int i;
399
400     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
401     {
402         snprintf(sampler_name, sizeof(sampler_name), "vs_sampler%u", i);
403         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
404         if (name_loc != -1) {
405             DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
406             if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
407             {
408                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
409                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
410                 checkGLcall("glUniform1iARB");
411             } else {
412                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
413             }
414         }
415     }
416 }
417
418 /* GL locking is done by the caller */
419 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
420         const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
421 {
422     int stack_idx = 0;
423     unsigned int heap_idx = 1;
424     unsigned int idx;
425
426     if (heap->entries[heap_idx].version <= version) return;
427
428     idx = heap->entries[heap_idx].idx;
429     if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
430     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
431
432     while (stack_idx >= 0)
433     {
434         /* Note that we fall through to the next case statement. */
435         switch(stack[stack_idx])
436         {
437             case HEAP_NODE_TRAVERSE_LEFT:
438             {
439                 unsigned int left_idx = heap_idx << 1;
440                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
441                 {
442                     heap_idx = left_idx;
443                     idx = heap->entries[heap_idx].idx;
444                     if (constant_locations[idx] != -1)
445                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
446
447                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
448                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
449                     break;
450                 }
451             }
452
453             case HEAP_NODE_TRAVERSE_RIGHT:
454             {
455                 unsigned int right_idx = (heap_idx << 1) + 1;
456                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
457                 {
458                     heap_idx = right_idx;
459                     idx = heap->entries[heap_idx].idx;
460                     if (constant_locations[idx] != -1)
461                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
462
463                     stack[stack_idx++] = HEAP_NODE_POP;
464                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
465                     break;
466                 }
467             }
468
469             case HEAP_NODE_POP:
470                 heap_idx >>= 1;
471                 --stack_idx;
472                 break;
473         }
474     }
475     checkGLcall("walk_constant_heap()");
476 }
477
478 /* GL locking is done by the caller */
479 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
480 {
481     GLfloat clamped_constant[4];
482
483     if (location == -1) return;
484
485     clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
486     clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
487     clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
488     clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
489
490     GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
491 }
492
493 /* GL locking is done by the caller */
494 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
495         const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
496 {
497     int stack_idx = 0;
498     unsigned int heap_idx = 1;
499     unsigned int idx;
500
501     if (heap->entries[heap_idx].version <= version) return;
502
503     idx = heap->entries[heap_idx].idx;
504     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
505     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
506
507     while (stack_idx >= 0)
508     {
509         /* Note that we fall through to the next case statement. */
510         switch(stack[stack_idx])
511         {
512             case HEAP_NODE_TRAVERSE_LEFT:
513             {
514                 unsigned int left_idx = heap_idx << 1;
515                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
516                 {
517                     heap_idx = left_idx;
518                     idx = heap->entries[heap_idx].idx;
519                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
520
521                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
522                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
523                     break;
524                 }
525             }
526
527             case HEAP_NODE_TRAVERSE_RIGHT:
528             {
529                 unsigned int right_idx = (heap_idx << 1) + 1;
530                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
531                 {
532                     heap_idx = right_idx;
533                     idx = heap->entries[heap_idx].idx;
534                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
535
536                     stack[stack_idx++] = HEAP_NODE_POP;
537                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
538                     break;
539                 }
540             }
541
542             case HEAP_NODE_POP:
543                 heap_idx >>= 1;
544                 --stack_idx;
545                 break;
546         }
547     }
548     checkGLcall("walk_constant_heap_clamped()");
549 }
550
551 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
552 /* GL locking is done by the caller */
553 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
554         const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
555         unsigned char *stack, UINT version)
556 {
557     const struct wined3d_shader_lconst *lconst;
558
559     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
560     if (shader->reg_maps.shader_version.major == 1
561             && shader->reg_maps.shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
562         walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
563     else
564         walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
565
566     if (!shader->load_local_constsF)
567     {
568         TRACE("No need to load local float constants for this shader\n");
569         return;
570     }
571
572     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
573     LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
574     {
575         GLint location = constant_locations[lconst->idx];
576         /* We found this uniform name in the program - go ahead and send the data */
577         if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
578     }
579     checkGLcall("glUniform4fvARB()");
580 }
581
582 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
583 /* GL locking is done by the caller */
584 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
585         const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
586 {
587     unsigned int i;
588     struct list* ptr;
589
590     for (i = 0; constants_set; constants_set >>= 1, ++i)
591     {
592         if (!(constants_set & 1)) continue;
593
594         TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
595                 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
596
597         /* We found this uniform name in the program - go ahead and send the data */
598         GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
599         checkGLcall("glUniform4ivARB");
600     }
601
602     /* Load immediate constants */
603     ptr = list_head(&shader->constantsI);
604     while (ptr)
605     {
606         const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
607         unsigned int idx = lconst->idx;
608         const GLint *values = (const GLint *)lconst->value;
609
610         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
611             values[0], values[1], values[2], values[3]);
612
613         /* We found this uniform name in the program - go ahead and send the data */
614         GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
615         checkGLcall("glUniform4ivARB");
616         ptr = list_next(&shader->constantsI, ptr);
617     }
618 }
619
620 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
621 /* GL locking is done by the caller */
622 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
623         GLhandleARB programId, const BOOL *constants, WORD constants_set)
624 {
625     GLint tmp_loc;
626     unsigned int i;
627     char tmp_name[10];
628     const char *prefix;
629     struct list* ptr;
630
631     prefix = shader_glsl_get_prefix(shader->reg_maps.shader_version.type);
632
633     /* TODO: Benchmark and see if it would be beneficial to store the
634      * locations of the constants to avoid looking up each time */
635     for (i = 0; constants_set; constants_set >>= 1, ++i)
636     {
637         if (!(constants_set & 1)) continue;
638
639         TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
640
641         /* TODO: Benchmark and see if it would be beneficial to store the
642          * locations of the constants to avoid looking up each time */
643         snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, i);
644         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
645         if (tmp_loc != -1)
646         {
647             /* We found this uniform name in the program - go ahead and send the data */
648             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
649             checkGLcall("glUniform1ivARB");
650         }
651     }
652
653     /* Load immediate constants */
654     ptr = list_head(&shader->constantsB);
655     while (ptr)
656     {
657         const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
658         unsigned int idx = lconst->idx;
659         const GLint *values = (const GLint *)lconst->value;
660
661         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
662
663         snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, idx);
664         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
665         if (tmp_loc != -1) {
666             /* We found this uniform name in the program - go ahead and send the data */
667             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
668             checkGLcall("glUniform1ivARB");
669         }
670         ptr = list_next(&shader->constantsB, ptr);
671     }
672 }
673
674 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
675 {
676     WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
677 }
678
679 /**
680  * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
681  */
682 /* GL locking is done by the caller (state handler) */
683 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
684         const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
685 {
686     struct shader_glsl_priv *glsl_priv = shader_priv;
687     const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
688
689     /* No GLSL program set - nothing to do. */
690     if (!prog) return;
691
692     /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
693     if (!use_ps(state)) return;
694
695     if (prog->ps.np2_fixup_info && prog->ps.np2_fixup_location != -1)
696     {
697         UINT i;
698         UINT fixup = prog->ps.np2_fixup_info->active;
699         GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
700
701         for (i = 0; fixup; fixup >>= 1, ++i)
702         {
703             const struct wined3d_texture *tex = state->textures[i];
704             const unsigned char idx = prog->ps.np2_fixup_info->idx[i];
705             GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
706
707             if (!tex)
708             {
709                 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
710                 continue;
711             }
712
713             if (idx % 2)
714             {
715                 tex_dim[2] = tex->pow2_matrix[0];
716                 tex_dim[3] = tex->pow2_matrix[5];
717             }
718             else
719             {
720                 tex_dim[0] = tex->pow2_matrix[0];
721                 tex_dim[1] = tex->pow2_matrix[5];
722             }
723         }
724
725         GL_EXTCALL(glUniform4fvARB(prog->ps.np2_fixup_location,
726                 prog->ps.np2_fixup_info->num_consts, np2fixup_constants));
727     }
728 }
729
730 /**
731  * Loads the app-supplied constants into the currently set GLSL program.
732  */
733 /* GL locking is done by the caller (state handler) */
734 static void shader_glsl_load_constants(const struct wined3d_context *context,
735         BOOL usePixelShader, BOOL useVertexShader)
736 {
737     const struct wined3d_gl_info *gl_info = context->gl_info;
738     struct wined3d_device *device = context->swapchain->device;
739     struct wined3d_stateblock *stateBlock = device->stateBlock;
740     const struct wined3d_state *state = &stateBlock->state;
741     struct shader_glsl_priv *priv = device->shader_priv;
742     float position_fixup[4];
743
744     GLhandleARB programId;
745     struct glsl_shader_prog_link *prog = priv->glsl_program;
746     UINT constant_version;
747     int i;
748
749     if (!prog) {
750         /* No GLSL program set - nothing to do. */
751         return;
752     }
753     programId = prog->programId;
754     constant_version = prog->constant_version;
755
756     if (useVertexShader)
757     {
758         const struct wined3d_shader *vshader = state->vertex_shader;
759
760         /* Load DirectX 9 float constants/uniforms for vertex shader */
761         shader_glsl_load_constantsF(vshader, gl_info, state->vs_consts_f,
762                 prog->vs.uniform_f_locations, &priv->vconst_heap, priv->stack, constant_version);
763
764         /* Load DirectX 9 integer constants/uniforms for vertex shader */
765         shader_glsl_load_constantsI(vshader, gl_info, prog->vs.uniform_i_locations, state->vs_consts_i,
766                 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
767
768         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
769         shader_glsl_load_constantsB(vshader, gl_info, programId, state->vs_consts_b,
770                 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
771
772         /* Upload the position fixup params */
773         shader_get_position_fixup(context, state, position_fixup);
774         GL_EXTCALL(glUniform4fvARB(prog->vs.pos_fixup_location, 1, position_fixup));
775         checkGLcall("glUniform4fvARB");
776     }
777
778     if (usePixelShader)
779     {
780         const struct wined3d_shader *pshader = state->pixel_shader;
781
782         /* Load DirectX 9 float constants/uniforms for pixel shader */
783         shader_glsl_load_constantsF(pshader, gl_info, state->ps_consts_f,
784                 prog->ps.uniform_f_locations, &priv->pconst_heap, priv->stack, constant_version);
785
786         /* Load DirectX 9 integer constants/uniforms for pixel shader */
787         shader_glsl_load_constantsI(pshader, gl_info, prog->ps.uniform_i_locations, state->ps_consts_i,
788                 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
789
790         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
791         shader_glsl_load_constantsB(pshader, gl_info, programId, state->ps_consts_b,
792                 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
793
794         /* Upload the environment bump map matrix if needed. The needsbumpmat
795          * member specifies the texture stage to load the matrix from. It
796          * can't be 0 for a valid texbem instruction. */
797         for (i = 0; i < MAX_TEXTURES; ++i)
798         {
799             const float *data;
800
801             if (prog->ps.bumpenv_mat_location[i] == -1)
802                 continue;
803
804             data = (const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_MAT00];
805             GL_EXTCALL(glUniformMatrix2fvARB(prog->ps.bumpenv_mat_location[i], 1, 0, data));
806             checkGLcall("glUniformMatrix2fvARB");
807
808             /* texbeml needs the luminance scale and offset too. If texbeml
809              * is used, needsbumpmat is set too, so we can check that in the
810              * needsbumpmat check. */
811             if (prog->ps.bumpenv_lum_scale_location[i] != -1)
812             {
813                 const GLfloat *scale = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LSCALE];
814                 const GLfloat *offset = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LOFFSET];
815
816                 GL_EXTCALL(glUniform1fvARB(prog->ps.bumpenv_lum_scale_location[i], 1, scale));
817                 checkGLcall("glUniform1fvARB");
818                 GL_EXTCALL(glUniform1fvARB(prog->ps.bumpenv_lum_offset_location[i], 1, offset));
819                 checkGLcall("glUniform1fvARB");
820             }
821         }
822
823         if (prog->ps.ycorrection_location != -1)
824         {
825             float correction_params[4];
826
827             if (context->render_offscreen)
828             {
829                 correction_params[0] = 0.0f;
830                 correction_params[1] = 1.0f;
831             } else {
832                 /* position is window relative, not viewport relative */
833                 correction_params[0] = (float) context->current_rt->resource.height;
834                 correction_params[1] = -1.0f;
835             }
836             GL_EXTCALL(glUniform4fvARB(prog->ps.ycorrection_location, 1, correction_params));
837         }
838     }
839     else if (priv->fragment_pipe == &glsl_fragment_pipe)
840     {
841         float col[4];
842
843         for (i = 0; i < MAX_TEXTURES; ++i)
844         {
845             GL_EXTCALL(glUniformMatrix2fvARB(prog->ps.bumpenv_mat_location[i], 1, 0,
846                         (const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_MAT00]));
847             GL_EXTCALL(glUniform1fARB(prog->ps.bumpenv_lum_scale_location[i],
848                         *(const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LSCALE]));
849             GL_EXTCALL(glUniform1fARB(prog->ps.bumpenv_lum_offset_location[i],
850                         *(const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LOFFSET]));
851         }
852
853         D3DCOLORTOGLFLOAT4(state->render_states[WINED3D_RS_TEXTUREFACTOR], col);
854         GL_EXTCALL(glUniform4fARB(prog->ps.tex_factor_location, col[0], col[1], col[2], col[3]));
855
856         if (state->render_states[WINED3D_RS_SPECULARENABLE])
857             GL_EXTCALL(glUniform4fARB(prog->ps.specular_enable_location, 1.0f, 1.0f, 1.0f, 0.0f));
858         else
859             GL_EXTCALL(glUniform4fARB(prog->ps.specular_enable_location, 0.0f, 0.0f, 0.0f, 0.0f));
860
861         checkGLcall("fixed function uniforms");
862     }
863
864     if (priv->next_constant_version == UINT_MAX)
865     {
866         TRACE("Max constant version reached, resetting to 0.\n");
867         wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
868         priv->next_constant_version = 1;
869     }
870     else
871     {
872         prog->constant_version = priv->next_constant_version++;
873     }
874 }
875
876 static void update_heap_entry(const struct constant_heap *heap, unsigned int idx,
877         unsigned int heap_idx, DWORD new_version)
878 {
879     struct constant_entry *entries = heap->entries;
880     unsigned int *positions = heap->positions;
881     unsigned int parent_idx;
882
883     while (heap_idx > 1)
884     {
885         parent_idx = heap_idx >> 1;
886
887         if (new_version <= entries[parent_idx].version) break;
888
889         entries[heap_idx] = entries[parent_idx];
890         positions[entries[parent_idx].idx] = heap_idx;
891         heap_idx = parent_idx;
892     }
893
894     entries[heap_idx].version = new_version;
895     entries[heap_idx].idx = idx;
896     positions[idx] = heap_idx;
897 }
898
899 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
900 {
901     struct shader_glsl_priv *priv = device->shader_priv;
902     struct constant_heap *heap = &priv->vconst_heap;
903     UINT i;
904
905     for (i = start; i < count + start; ++i)
906     {
907         if (!device->stateBlock->changed.vertexShaderConstantsF[i])
908             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
909         else
910             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
911     }
912 }
913
914 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
915 {
916     struct shader_glsl_priv *priv = device->shader_priv;
917     struct constant_heap *heap = &priv->pconst_heap;
918     UINT i;
919
920     for (i = start; i < count + start; ++i)
921     {
922         if (!device->stateBlock->changed.pixelShaderConstantsF[i])
923             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
924         else
925             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
926     }
927 }
928
929 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
930 {
931     unsigned int ret = gl_info->limits.glsl_varyings / 4;
932     /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
933     if(shader_major > 3) return ret;
934
935     /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
936     if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
937     return ret;
938 }
939
940 /** Generate the variable & register declarations for the GLSL output target */
941 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
942         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
943         const struct wined3d_shader_reg_maps *reg_maps, const struct shader_glsl_ctx_priv *ctx_priv)
944 {
945     const struct wined3d_shader_version *version = &reg_maps->shader_version;
946     const struct wined3d_state *state = &shader->device->stateBlock->state;
947     const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
948     const struct wined3d_gl_info *gl_info = context->gl_info;
949     const struct wined3d_fb_state *fb = &shader->device->fb;
950     unsigned int i, extra_constants_needed = 0;
951     const struct wined3d_shader_lconst *lconst;
952     const char *prefix;
953     DWORD map;
954
955     prefix = shader_glsl_get_prefix(version->type);
956
957     /* Prototype the subroutines */
958     for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
959     {
960         if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
961     }
962
963     /* Declare the constants (aka uniforms) */
964     if (shader->limits.constant_float > 0)
965     {
966         unsigned max_constantsF;
967
968         /* Unless the shader uses indirect addressing, always declare the
969          * maximum array size and ignore that we need some uniforms privately.
970          * E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup
971          * and immediate values, still declare VC[256]. If the shader needs
972          * more uniforms than we have it won't work in any case. If it uses
973          * less, the compiler will figure out which uniforms are really used
974          * and strip them out. This allows a shader to use c255 on a dx9 card,
975          * as long as it doesn't also use all the other constants.
976          *
977          * If the shader uses indirect addressing the compiler must assume
978          * that all declared uniforms are used. In this case, declare only the
979          * amount that we're assured to have.
980          *
981          * Thus we run into problems in these two cases:
982          * 1) The shader really uses more uniforms than supported.
983          * 2) The shader uses indirect addressing, less constants than
984          *    supported, but uses a constant index > #supported consts. */
985         if (version->type == WINED3D_SHADER_TYPE_PIXEL)
986         {
987             /* No indirect addressing here. */
988             max_constantsF = gl_info->limits.glsl_ps_float_constants;
989         }
990         else
991         {
992             if (reg_maps->usesrelconstF)
993             {
994                 /* Subtract the other potential uniforms from the max
995                  * available (bools, ints, and 1 row of projection matrix).
996                  * Subtract another uniform for immediate values, which have
997                  * to be loaded via uniform by the driver as well. The shader
998                  * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
999                  * shader code, so one vec4 should be enough. (Unfortunately
1000                  * the Nvidia driver doesn't store 128 and -128 in one float).
1001                  *
1002                  * Writing gl_ClipVertex requires one uniform for each
1003                  * clipplane as well. */
1004                 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
1005                 if(ctx_priv->cur_vs_args->clip_enabled)
1006                 {
1007                     max_constantsF -= gl_info->limits.clipplanes;
1008                 }
1009                 max_constantsF -= count_bits(reg_maps->integer_constants);
1010                 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
1011                  * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
1012                  * for now take this into account when calculating the number of available constants
1013                  */
1014                 max_constantsF -= count_bits(reg_maps->boolean_constants);
1015                 /* Set by driver quirks in directx.c */
1016                 max_constantsF -= gl_info->reserved_glsl_constants;
1017
1018                 if (max_constantsF < shader->limits.constant_float)
1019                 {
1020                     static unsigned int once;
1021
1022                     if (!once++)
1023                         ERR_(winediag)("The hardware does not support enough uniform components to run this shader,"
1024                                 " it may not render correctly.\n");
1025                     else
1026                         WARN("The hardware does not support enough uniform components to run this shader.\n");
1027                 }
1028             }
1029             else
1030             {
1031                 max_constantsF = gl_info->limits.glsl_vs_float_constants;
1032             }
1033         }
1034         max_constantsF = min(shader->limits.constant_float, max_constantsF);
1035         shader_addline(buffer, "uniform vec4 %s_c[%u];\n", prefix, max_constantsF);
1036     }
1037
1038     /* Always declare the full set of constants, the compiler can remove the
1039      * unused ones because d3d doesn't (yet) support indirect int and bool
1040      * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
1041     if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
1042         shader_addline(buffer, "uniform ivec4 %s_i[%u];\n", prefix, shader->limits.constant_int);
1043
1044     if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
1045         shader_addline(buffer, "uniform bool %s_b[%u];\n", prefix, shader->limits.constant_bool);
1046
1047     for (i = 0; i < WINED3D_MAX_CBS; ++i)
1048     {
1049         if (reg_maps->cb_sizes[i])
1050             shader_addline(buffer, "uniform vec4 %s_cb%u[%u];\n", prefix, i, reg_maps->cb_sizes[i]);
1051     }
1052
1053     /* Declare texture samplers */
1054     for (i = 0; i < shader->limits.sampler; ++i)
1055     {
1056         if (reg_maps->sampler_type[i])
1057         {
1058             BOOL shadow_sampler = version->type == WINED3D_SHADER_TYPE_PIXEL && (ps_args->shadow & (1 << i));
1059             const struct wined3d_texture *texture;
1060
1061             switch (reg_maps->sampler_type[i])
1062             {
1063                 case WINED3DSTT_1D:
1064                     if (shadow_sampler)
1065                         shader_addline(buffer, "uniform sampler1DShadow %s_sampler%u;\n", prefix, i);
1066                     else
1067                         shader_addline(buffer, "uniform sampler1D %s_sampler%u;\n", prefix, i);
1068                     break;
1069                 case WINED3DSTT_2D:
1070                     texture = state->textures[i];
1071                     if (shadow_sampler)
1072                     {
1073                         if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1074                             shader_addline(buffer, "uniform sampler2DRectShadow %s_sampler%u;\n", prefix, i);
1075                         else
1076                             shader_addline(buffer, "uniform sampler2DShadow %s_sampler%u;\n", prefix, i);
1077                     }
1078                     else
1079                     {
1080                         if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1081                             shader_addline(buffer, "uniform sampler2DRect %s_sampler%u;\n", prefix, i);
1082                         else
1083                             shader_addline(buffer, "uniform sampler2D %s_sampler%u;\n", prefix, i);
1084                     }
1085                     break;
1086                 case WINED3DSTT_CUBE:
1087                     if (shadow_sampler)
1088                         FIXME("Unsupported Cube shadow sampler.\n");
1089                     shader_addline(buffer, "uniform samplerCube %s_sampler%u;\n", prefix, i);
1090                     break;
1091                 case WINED3DSTT_VOLUME:
1092                     if (shadow_sampler)
1093                         FIXME("Unsupported 3D shadow sampler.\n");
1094                     shader_addline(buffer, "uniform sampler3D %s_sampler%u;\n", prefix, i);
1095                     break;
1096                 default:
1097                     shader_addline(buffer, "uniform unsupported_sampler %s_sampler%u;\n", prefix, i);
1098                     FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1099                     break;
1100             }
1101         }
1102     }
1103
1104     /* Declare uniforms for NP2 texcoord fixup:
1105      * This is NOT done inside the loop that declares the texture samplers
1106      * since the NP2 fixup code is currently only used for the GeforceFX
1107      * series and when forcing the ARB_npot extension off. Modern cards just
1108      * skip the code anyway, so put it inside a separate loop. */
1109     if (version->type == WINED3D_SHADER_TYPE_PIXEL && ps_args->np2_fixup)
1110     {
1111         struct ps_np2fixup_info *fixup = ctx_priv->cur_np2fixup_info;
1112         UINT cur = 0;
1113
1114         /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1115          * while D3D has them in the (normalized) [0,1]x[0,1] range.
1116          * samplerNP2Fixup stores texture dimensions and is updated through
1117          * shader_glsl_load_np2fixup_constants when the sampler changes. */
1118
1119         for (i = 0; i < shader->limits.sampler; ++i)
1120         {
1121             if (reg_maps->sampler_type[i])
1122             {
1123                 if (!(ps_args->np2_fixup & (1 << i))) continue;
1124
1125                 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1126                     FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1127                     continue;
1128                 }
1129
1130                 fixup->idx[i] = cur++;
1131             }
1132         }
1133
1134         fixup->num_consts = (cur + 1) >> 1;
1135         fixup->active = ps_args->np2_fixup;
1136         shader_addline(buffer, "uniform vec4 %s_samplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1137     }
1138
1139     /* Declare address variables */
1140     for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1141     {
1142         if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1143     }
1144
1145     /* Declare texture coordinate temporaries and initialize them */
1146     for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1147     {
1148         if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1149     }
1150
1151     if (version->type == WINED3D_SHADER_TYPE_VERTEX)
1152     {
1153         /* Declare attributes. */
1154         for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1155         {
1156             if (map & 1)
1157                 shader_addline(buffer, "attribute vec4 %s_in%u;\n", prefix, i);
1158         }
1159
1160         shader_addline(buffer, "uniform vec4 posFixup;\n");
1161         shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", shader->limits.packed_output);
1162     }
1163     else if (version->type == WINED3D_SHADER_TYPE_PIXEL)
1164     {
1165         if (version->major >= 3)
1166         {
1167             UINT in_count = min(vec4_varyings(version->major, gl_info), shader->limits.packed_input);
1168
1169             if (use_vs(state))
1170                 shader_addline(buffer, "varying vec4 %s_in[%u];\n", prefix, in_count);
1171             else
1172                 /* TODO: Write a replacement shader for the fixed function
1173                  * vertex pipeline, so this isn't needed. For fixed function
1174                  * vertex processing + 3.0 pixel shader we need a separate
1175                  * function in the pixel shader that reads the fixed function
1176                  * color into the packed input registers. */
1177                 shader_addline(buffer, "vec4 %s_in[%u];\n", prefix, in_count);
1178         }
1179
1180         for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1181         {
1182             if (!(map & 1))
1183                 continue;
1184
1185             shader_addline(buffer, "uniform mat2 bumpenv_mat%u;\n", i);
1186
1187             if (reg_maps->luminanceparams & (1 << i))
1188             {
1189                 shader_addline(buffer, "uniform float bumpenv_lum_scale%u;\n", i);
1190                 shader_addline(buffer, "uniform float bumpenv_lum_offset%u;\n", i);
1191                 extra_constants_needed++;
1192             }
1193
1194             extra_constants_needed++;
1195         }
1196
1197         if (ps_args->srgb_correction)
1198         {
1199             shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1200                     srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1201             shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1202                     srgb_cmp);
1203         }
1204         if (reg_maps->vpos || reg_maps->usesdsy)
1205         {
1206             if (shader->limits.constant_float + extra_constants_needed
1207                     + 1 < gl_info->limits.glsl_ps_float_constants)
1208             {
1209                 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1210                 extra_constants_needed++;
1211             }
1212             else
1213             {
1214                 /* This happens because we do not have proper tracking of the constant registers that are
1215                  * actually used, only the max limit of the shader version
1216                  */
1217                 FIXME("Cannot find a free uniform for vpos correction params\n");
1218                 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1219                         context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1220                         context->render_offscreen ? 1.0f : -1.0f);
1221             }
1222             shader_addline(buffer, "vec4 vpos;\n");
1223         }
1224     }
1225
1226     /* Declare output register temporaries */
1227     if (shader->limits.packed_output)
1228         shader_addline(buffer, "vec4 %s_out[%u];\n", prefix, shader->limits.packed_output);
1229
1230     /* Declare temporary variables */
1231     for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1232     {
1233         if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1234     }
1235
1236     /* Declare loop registers aLx */
1237     if (version->major < 4)
1238     {
1239         for (i = 0; i < reg_maps->loop_depth; ++i)
1240         {
1241             shader_addline(buffer, "int aL%u;\n", i);
1242             shader_addline(buffer, "int tmpInt%u;\n", i);
1243         }
1244     }
1245
1246     /* Temporary variables for matrix operations */
1247     shader_addline(buffer, "vec4 tmp0;\n");
1248     shader_addline(buffer, "vec4 tmp1;\n");
1249
1250     /* Local constants use a different name so they can be loaded once at shader link time
1251      * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1252      * float -> string conversion can cause precision loss.
1253      */
1254     if (!shader->load_local_constsF)
1255     {
1256         LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1257         {
1258             shader_addline(buffer, "uniform vec4 %s_lc%u;\n", prefix, lconst->idx);
1259         }
1260     }
1261
1262     /* Start the main program. */
1263     shader_addline(buffer, "void main()\n{\n");
1264
1265     /* Direct3D applications expect integer vPos values, while OpenGL drivers
1266      * add approximately 0.5. This causes off-by-one problems as spotted by
1267      * the vPos d3d9 visual test. Unfortunately ATI cards do not add exactly
1268      * 0.5, but rather something like 0.49999999 or 0.50000001, which still
1269      * causes precision troubles when we just subtract 0.5.
1270      *
1271      * To deal with that, just floor() the position. This will eliminate the
1272      * fraction on all cards.
1273      *
1274      * TODO: Test how this behaves with multisampling.
1275      *
1276      * An advantage of floor is that it works even if the driver doesn't add
1277      * 0.5. It is somewhat questionable if 1.5, 2.5, ... are the proper values
1278      * to return in gl_FragCoord, even though coordinates specify the pixel
1279      * centers instead of the pixel corners. This code will behave correctly
1280      * on drivers that returns integer values. */
1281     if (version->type == WINED3D_SHADER_TYPE_PIXEL && reg_maps->vpos)
1282         shader_addline(buffer,
1283                 "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1284 }
1285
1286 /*****************************************************************************
1287  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1288  *
1289  * For more information, see http://wiki.winehq.org/DirectX-Shaders
1290  ****************************************************************************/
1291
1292 /* Prototypes */
1293 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1294         const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1295
1296 /** Used for opcode modifiers - They multiply the result by the specified amount */
1297 static const char * const shift_glsl_tab[] = {
1298     "",           /*  0 (none) */
1299     "2.0 * ",     /*  1 (x2)   */
1300     "4.0 * ",     /*  2 (x4)   */
1301     "8.0 * ",     /*  3 (x8)   */
1302     "16.0 * ",    /*  4 (x16)  */
1303     "32.0 * ",    /*  5 (x32)  */
1304     "",           /*  6 (x64)  */
1305     "",           /*  7 (x128) */
1306     "",           /*  8 (d256) */
1307     "",           /*  9 (d128) */
1308     "",           /* 10 (d64)  */
1309     "",           /* 11 (d32)  */
1310     "0.0625 * ",  /* 12 (d16)  */
1311     "0.125 * ",   /* 13 (d8)   */
1312     "0.25 * ",    /* 14 (d4)   */
1313     "0.5 * "      /* 15 (d2)   */
1314 };
1315
1316 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1317 static void shader_glsl_gen_modifier(enum wined3d_shader_src_modifier src_modifier,
1318         const char *in_reg, const char *in_regswizzle, char *out_str)
1319 {
1320     out_str[0] = 0;
1321
1322     switch (src_modifier)
1323     {
1324     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1325     case WINED3DSPSM_DW:
1326     case WINED3DSPSM_NONE:
1327         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1328         break;
1329     case WINED3DSPSM_NEG:
1330         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1331         break;
1332     case WINED3DSPSM_NOT:
1333         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1334         break;
1335     case WINED3DSPSM_BIAS:
1336         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1337         break;
1338     case WINED3DSPSM_BIASNEG:
1339         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1340         break;
1341     case WINED3DSPSM_SIGN:
1342         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1343         break;
1344     case WINED3DSPSM_SIGNNEG:
1345         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1346         break;
1347     case WINED3DSPSM_COMP:
1348         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1349         break;
1350     case WINED3DSPSM_X2:
1351         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1352         break;
1353     case WINED3DSPSM_X2NEG:
1354         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1355         break;
1356     case WINED3DSPSM_ABS:
1357         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1358         break;
1359     case WINED3DSPSM_ABSNEG:
1360         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1361         break;
1362     default:
1363         FIXME("Unhandled modifier %u\n", src_modifier);
1364         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1365     }
1366 }
1367
1368 /** Writes the GLSL variable name that corresponds to the register that the
1369  * DX opcode parameter is trying to access */
1370 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1371         char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1372 {
1373     /* oPos, oFog and oPts in D3D */
1374     static const char * const hwrastout_reg_names[] = {"vs_out[10]", "vs_out[11].x", "vs_out[11].y"};
1375
1376     const struct wined3d_shader *shader = ins->ctx->shader;
1377     const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1378     const struct wined3d_shader_version *version = &reg_maps->shader_version;
1379     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1380     const char *prefix = shader_glsl_get_prefix(version->type);
1381     struct glsl_src_param rel_param0, rel_param1;
1382
1383     if (reg->idx[0].offset != ~0U && reg->idx[0].rel_addr)
1384         shader_glsl_add_src_param(ins, reg->idx[0].rel_addr, WINED3DSP_WRITEMASK_0, &rel_param0);
1385     if (reg->idx[1].offset != ~0U && reg->idx[1].rel_addr)
1386         shader_glsl_add_src_param(ins, reg->idx[1].rel_addr, WINED3DSP_WRITEMASK_0, &rel_param1);
1387     *is_color = FALSE;
1388
1389     switch (reg->type)
1390     {
1391         case WINED3DSPR_TEMP:
1392             sprintf(register_name, "R%u", reg->idx[0].offset);
1393             break;
1394
1395         case WINED3DSPR_INPUT:
1396             /* vertex shaders */
1397             if (version->type == WINED3D_SHADER_TYPE_VERTEX)
1398             {
1399                 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1400                 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx[0].offset))
1401                     *is_color = TRUE;
1402                 sprintf(register_name, "%s_in%u", prefix, reg->idx[0].offset);
1403                 break;
1404             }
1405
1406             /* pixel shaders >= 3.0 */
1407             if (version->major >= 3)
1408             {
1409                 DWORD idx = shader->u.ps.input_reg_map[reg->idx[0].offset];
1410                 unsigned int in_count = vec4_varyings(version->major, gl_info);
1411
1412                 if (reg->idx[0].rel_addr)
1413                 {
1414                     /* Removing a + 0 would be an obvious optimization, but
1415                      * OS X doesn't see the NOP operation there. */
1416                     if (idx)
1417                     {
1418                         if (shader->u.ps.declared_in_count > in_count)
1419                         {
1420                             sprintf(register_name,
1421                                     "((%s + %u) > %u ? (%s + %u) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s + %u])",
1422                                     rel_param0.param_str, idx, in_count - 1, rel_param0.param_str, idx, in_count,
1423                                     prefix, rel_param0.param_str, idx);
1424                         }
1425                         else
1426                         {
1427                             sprintf(register_name, "%s_in[%s + %u]", prefix, rel_param0.param_str, idx);
1428                         }
1429                     }
1430                     else
1431                     {
1432                         if (shader->u.ps.declared_in_count > in_count)
1433                         {
1434                             sprintf(register_name, "((%s) > %u ? (%s) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s])",
1435                                     rel_param0.param_str, in_count - 1, rel_param0.param_str, in_count,
1436                                     prefix, rel_param0.param_str);
1437                         }
1438                         else
1439                         {
1440                             sprintf(register_name, "%s_in[%s]", prefix, rel_param0.param_str);
1441                         }
1442                     }
1443                 }
1444                 else
1445                 {
1446                     if (idx == in_count) sprintf(register_name, "gl_Color");
1447                     else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1448                     else sprintf(register_name, "%s_in[%u]", prefix, idx);
1449                 }
1450             }
1451             else
1452             {
1453                 if (!reg->idx[0].offset)
1454                     strcpy(register_name, "gl_Color");
1455                 else
1456                     strcpy(register_name, "gl_SecondaryColor");
1457                 break;
1458             }
1459             break;
1460
1461         case WINED3DSPR_CONST:
1462             {
1463                 /* Relative addressing */
1464                 if (reg->idx[0].rel_addr)
1465                 {
1466                     if (reg->idx[0].offset)
1467                         sprintf(register_name, "%s_c[%s + %u]", prefix, rel_param0.param_str, reg->idx[0].offset);
1468                     else
1469                         sprintf(register_name, "%s_c[%s]", prefix, rel_param0.param_str);
1470                 }
1471                 else
1472                 {
1473                     if (shader_constant_is_local(shader, reg->idx[0].offset))
1474                         sprintf(register_name, "%s_lc%u", prefix, reg->idx[0].offset);
1475                     else
1476                         sprintf(register_name, "%s_c[%u]", prefix, reg->idx[0].offset);
1477                 }
1478             }
1479             break;
1480
1481         case WINED3DSPR_CONSTINT:
1482             sprintf(register_name, "%s_i[%u]", prefix, reg->idx[0].offset);
1483             break;
1484
1485         case WINED3DSPR_CONSTBOOL:
1486             sprintf(register_name, "%s_b[%u]", prefix, reg->idx[0].offset);
1487             break;
1488
1489         case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1490             if (version->type == WINED3D_SHADER_TYPE_PIXEL)
1491                 sprintf(register_name, "T%u", reg->idx[0].offset);
1492             else
1493                 sprintf(register_name, "A%u", reg->idx[0].offset);
1494             break;
1495
1496         case WINED3DSPR_LOOP:
1497             sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1498             break;
1499
1500         case WINED3DSPR_SAMPLER:
1501             sprintf(register_name, "%s_sampler%u", prefix, reg->idx[0].offset);
1502             break;
1503
1504         case WINED3DSPR_COLOROUT:
1505             if (reg->idx[0].offset >= gl_info->limits.buffers)
1506                 WARN("Write to render target %u, only %d supported.\n",
1507                         reg->idx[0].offset, gl_info->limits.buffers);
1508
1509             sprintf(register_name, "gl_FragData[%u]", reg->idx[0].offset);
1510             break;
1511
1512         case WINED3DSPR_RASTOUT:
1513             sprintf(register_name, "%s", hwrastout_reg_names[reg->idx[0].offset]);
1514             break;
1515
1516         case WINED3DSPR_DEPTHOUT:
1517             sprintf(register_name, "gl_FragDepth");
1518             break;
1519
1520         case WINED3DSPR_ATTROUT:
1521             if (!reg->idx[0].offset)
1522                 sprintf(register_name, "%s_out[8]", prefix);
1523             else
1524                 sprintf(register_name, "%s_out[9]", prefix);
1525             break;
1526
1527         case WINED3DSPR_TEXCRDOUT:
1528             /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1529             sprintf(register_name, "%s_out[%u]", prefix, reg->idx[0].offset);
1530             break;
1531
1532         case WINED3DSPR_MISCTYPE:
1533             if (!reg->idx[0].offset)
1534             {
1535                 /* vPos */
1536                 sprintf(register_name, "vpos");
1537             }
1538             else if (reg->idx[0].offset == 1)
1539             {
1540                 /* Note that gl_FrontFacing is a bool, while vFace is
1541                  * a float for which the sign determines front/back */
1542                 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1543             }
1544             else
1545             {
1546                 FIXME("Unhandled misctype register %u.\n", reg->idx[0].offset);
1547                 sprintf(register_name, "unrecognized_register");
1548             }
1549             break;
1550
1551         case WINED3DSPR_IMMCONST:
1552             switch (reg->immconst_type)
1553             {
1554                 case WINED3D_IMMCONST_SCALAR:
1555                     switch (reg->data_type)
1556                     {
1557                         case WINED3D_DATA_FLOAT:
1558                             sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1559                             break;
1560                         case WINED3D_DATA_INT:
1561                             sprintf(register_name, "%#x", reg->immconst_data[0]);
1562                             break;
1563                         case WINED3D_DATA_RESOURCE:
1564                         case WINED3D_DATA_SAMPLER:
1565                         case WINED3D_DATA_UINT:
1566                             sprintf(register_name, "%#xu", reg->immconst_data[0]);
1567                             break;
1568                         default:
1569                             sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1570                             break;
1571                     }
1572                     break;
1573
1574                 case WINED3D_IMMCONST_VEC4:
1575                     switch (reg->data_type)
1576                     {
1577                         case WINED3D_DATA_FLOAT:
1578                             sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1579                                     *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1580                                     *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1581                             break;
1582                         case WINED3D_DATA_INT:
1583                             sprintf(register_name, "ivec4(%#x, %#x, %#x, %#x)",
1584                                     reg->immconst_data[0], reg->immconst_data[1],
1585                                     reg->immconst_data[2], reg->immconst_data[3]);
1586                             break;
1587                         case WINED3D_DATA_RESOURCE:
1588                         case WINED3D_DATA_SAMPLER:
1589                         case WINED3D_DATA_UINT:
1590                             sprintf(register_name, "uvec4(%#xu, %#xu, %#xu, %#xu)",
1591                                     reg->immconst_data[0], reg->immconst_data[1],
1592                                     reg->immconst_data[2], reg->immconst_data[3]);
1593                             break;
1594                         default:
1595                             sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1596                             break;
1597                     }
1598                     break;
1599
1600                 default:
1601                     FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1602                     sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1603             }
1604             break;
1605
1606         case WINED3DSPR_CONSTBUFFER:
1607             if (reg->idx[1].rel_addr)
1608                 sprintf(register_name, "%s_cb%u[%s + %u]",
1609                         prefix, reg->idx[0].offset, rel_param1.param_str, reg->idx[1].offset);
1610             else
1611                 sprintf(register_name, "%s_cb%u[%u]", prefix, reg->idx[0].offset, reg->idx[1].offset);
1612             break;
1613
1614         case WINED3DSPR_PRIMID:
1615             sprintf(register_name, "uint(gl_PrimitiveIDIn)");
1616             break;
1617
1618         default:
1619             FIXME("Unhandled register type %#x.\n", reg->type);
1620             sprintf(register_name, "unrecognized_register");
1621             break;
1622     }
1623 }
1624
1625 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1626 {
1627     *str++ = '.';
1628     if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1629     if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1630     if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1631     if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1632     *str = '\0';
1633 }
1634
1635 /* Get the GLSL write mask for the destination register */
1636 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1637 {
1638     DWORD mask = param->write_mask;
1639
1640     if (shader_is_scalar(&param->reg))
1641     {
1642         mask = WINED3DSP_WRITEMASK_0;
1643         *write_mask = '\0';
1644     }
1645     else
1646     {
1647         shader_glsl_write_mask_to_str(mask, write_mask);
1648     }
1649
1650     return mask;
1651 }
1652
1653 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1654     unsigned int size = 0;
1655
1656     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1657     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1658     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1659     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1660
1661     return size;
1662 }
1663
1664 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1665 {
1666     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1667      * but addressed as "rgba". To fix this we need to swap the register's x
1668      * and z components. */
1669     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1670
1671     *str++ = '.';
1672     /* swizzle bits fields: wwzzyyxx */
1673     if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1674     if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1675     if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1676     if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1677     *str = '\0';
1678 }
1679
1680 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1681         BOOL fixup, DWORD mask, char *swizzle_str)
1682 {
1683     if (shader_is_scalar(&param->reg))
1684         *swizzle_str = '\0';
1685     else
1686         shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1687 }
1688
1689 /* From a given parameter token, generate the corresponding GLSL string.
1690  * Also, return the actual register name and swizzle in case the
1691  * caller needs this information as well. */
1692 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1693         const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1694 {
1695     BOOL is_color = FALSE;
1696     char swizzle_str[6];
1697
1698     glsl_src->reg_name[0] = '\0';
1699     glsl_src->param_str[0] = '\0';
1700     swizzle_str[0] = '\0';
1701
1702     shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1703     shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1704
1705     if (wined3d_src->reg.type == WINED3DSPR_IMMCONST || wined3d_src->reg.type == WINED3DSPR_PRIMID)
1706     {
1707         shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1708     }
1709     else
1710     {
1711         char param_str[200];
1712
1713         shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, param_str);
1714
1715         switch (wined3d_src->reg.data_type)
1716         {
1717             case WINED3D_DATA_FLOAT:
1718                 sprintf(glsl_src->param_str, "%s", param_str);
1719                 break;
1720             case WINED3D_DATA_INT:
1721                 sprintf(glsl_src->param_str, "floatBitsToInt(%s)", param_str);
1722                 break;
1723             case WINED3D_DATA_RESOURCE:
1724             case WINED3D_DATA_SAMPLER:
1725             case WINED3D_DATA_UINT:
1726                 sprintf(glsl_src->param_str, "floatBitsToUint(%s)", param_str);
1727                 break;
1728             default:
1729                 FIXME("Unhandled data type %#x.\n", wined3d_src->reg.data_type);
1730                 sprintf(glsl_src->param_str, "%s", param_str);
1731                 break;
1732         }
1733     }
1734 }
1735
1736 /* From a given parameter token, generate the corresponding GLSL string.
1737  * Also, return the actual register name and swizzle in case the
1738  * caller needs this information as well. */
1739 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1740         const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1741 {
1742     BOOL is_color = FALSE;
1743
1744     glsl_dst->mask_str[0] = '\0';
1745     glsl_dst->reg_name[0] = '\0';
1746
1747     shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1748     return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1749 }
1750
1751 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1752 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1753         const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1754 {
1755     struct glsl_dst_param glsl_dst;
1756     DWORD mask;
1757
1758     if ((mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst)))
1759     {
1760         switch (dst->reg.data_type)
1761         {
1762             case WINED3D_DATA_FLOAT:
1763                 shader_addline(buffer, "%s%s = %s(",
1764                         glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1765                 break;
1766             case WINED3D_DATA_INT:
1767                 shader_addline(buffer, "%s%s = %sintBitsToFloat(",
1768                         glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1769                 break;
1770             case WINED3D_DATA_RESOURCE:
1771             case WINED3D_DATA_SAMPLER:
1772             case WINED3D_DATA_UINT:
1773                 shader_addline(buffer, "%s%s = %suintBitsToFloat(",
1774                         glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1775                 break;
1776             default:
1777                 FIXME("Unhandled data type %#x.\n", dst->reg.data_type);
1778                 shader_addline(buffer, "%s%s = %s(",
1779                         glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1780                 break;
1781         }
1782     }
1783
1784     return mask;
1785 }
1786
1787 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1788 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1789 {
1790     return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1791 }
1792
1793 /** Process GLSL instruction modifiers */
1794 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1795 {
1796     struct glsl_dst_param dst_param;
1797     DWORD modifiers;
1798
1799     if (!ins->dst_count) return;
1800
1801     modifiers = ins->dst[0].modifiers;
1802     if (!modifiers) return;
1803
1804     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1805
1806     if (modifiers & WINED3DSPDM_SATURATE)
1807     {
1808         /* _SAT means to clamp the value of the register to between 0 and 1 */
1809         shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1810                 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1811     }
1812
1813     if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1814     {
1815         FIXME("_centroid modifier not handled\n");
1816     }
1817
1818     if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1819     {
1820         /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1821     }
1822 }
1823
1824 static const char *shader_glsl_get_rel_op(enum wined3d_shader_rel_op op)
1825 {
1826     switch (op)
1827     {
1828         case WINED3D_SHADER_REL_OP_GT: return ">";
1829         case WINED3D_SHADER_REL_OP_EQ: return "==";
1830         case WINED3D_SHADER_REL_OP_GE: return ">=";
1831         case WINED3D_SHADER_REL_OP_LT: return "<";
1832         case WINED3D_SHADER_REL_OP_NE: return "!=";
1833         case WINED3D_SHADER_REL_OP_LE: return "<=";
1834         default:
1835             FIXME("Unrecognized operator %#x.\n", op);
1836             return "(\?\?)";
1837     }
1838 }
1839
1840 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1841         DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1842 {
1843     enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1844     const struct wined3d_gl_info *gl_info = ctx->gl_info;
1845     BOOL shadow = ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_PIXEL
1846             && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1847     BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1848     BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1849     BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1850     BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1851
1852     /* Note that there's no such thing as a projected cube texture. */
1853     switch(sampler_type) {
1854         case WINED3DSTT_1D:
1855             if (shadow)
1856             {
1857                 if (lod)
1858                 {
1859                     sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1860                 }
1861                 else if (grad)
1862                 {
1863                     if (gl_info->supported[EXT_GPU_SHADER4])
1864                         sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1865                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1866                         sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1867                     else
1868                     {
1869                         FIXME("Unsupported 1D shadow grad function.\n");
1870                         sample_function->name = "unsupported1DGrad";
1871                     }
1872                 }
1873                 else
1874                 {
1875                     sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1876                 }
1877                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1878             }
1879             else
1880             {
1881                 if (lod)
1882                 {
1883                     sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1884                 }
1885                 else if (grad)
1886                 {
1887                     if (gl_info->supported[EXT_GPU_SHADER4])
1888                         sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1889                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1890                         sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1891                     else
1892                     {
1893                         FIXME("Unsupported 1D grad function.\n");
1894                         sample_function->name = "unsupported1DGrad";
1895                     }
1896                 }
1897                 else
1898                 {
1899                     sample_function->name = projected ? "texture1DProj" : "texture1D";
1900                 }
1901                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1902             }
1903             break;
1904
1905         case WINED3DSTT_2D:
1906             if (shadow)
1907             {
1908                 if (texrect)
1909                 {
1910                     if (lod)
1911                     {
1912                         sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1913                     }
1914                     else if (grad)
1915                     {
1916                         if (gl_info->supported[EXT_GPU_SHADER4])
1917                             sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1918                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1919                             sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1920                         else
1921                         {
1922                             FIXME("Unsupported RECT shadow grad function.\n");
1923                             sample_function->name = "unsupported2DRectGrad";
1924                         }
1925                     }
1926                     else
1927                     {
1928                         sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1929                     }
1930                 }
1931                 else
1932                 {
1933                     if (lod)
1934                     {
1935                         sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1936                     }
1937                     else if (grad)
1938                     {
1939                         if (gl_info->supported[EXT_GPU_SHADER4])
1940                             sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1941                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1942                             sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1943                         else
1944                         {
1945                             FIXME("Unsupported 2D shadow grad function.\n");
1946                             sample_function->name = "unsupported2DGrad";
1947                         }
1948                     }
1949                     else
1950                     {
1951                         sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1952                     }
1953                 }
1954                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1955             }
1956             else
1957             {
1958                 if (texrect)
1959                 {
1960                     if (lod)
1961                     {
1962                         sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1963                     }
1964                     else if (grad)
1965                     {
1966                         if (gl_info->supported[EXT_GPU_SHADER4])
1967                             sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1968                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1969                             sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1970                         else
1971                         {
1972                             FIXME("Unsupported RECT grad function.\n");
1973                             sample_function->name = "unsupported2DRectGrad";
1974                         }
1975                     }
1976                     else
1977                     {
1978                         sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1979                     }
1980                 }
1981                 else
1982                 {
1983                     if (lod)
1984                     {
1985                         sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1986                     }
1987                     else if (grad)
1988                     {
1989                         if (gl_info->supported[EXT_GPU_SHADER4])
1990                             sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1991                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1992                             sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1993                         else
1994                         {
1995                             FIXME("Unsupported 2D grad function.\n");
1996                             sample_function->name = "unsupported2DGrad";
1997                         }
1998                     }
1999                     else
2000                     {
2001                         sample_function->name = projected ? "texture2DProj" : "texture2D";
2002                     }
2003                 }
2004                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
2005             }
2006             break;
2007
2008         case WINED3DSTT_CUBE:
2009             if (shadow)
2010             {
2011                 FIXME("Unsupported Cube shadow function.\n");
2012                 sample_function->name = "unsupportedCubeShadow";
2013                 sample_function->coord_mask = 0;
2014             }
2015             else
2016             {
2017                 if (lod)
2018                 {
2019                     sample_function->name = "textureCubeLod";
2020                 }
2021                 else if (grad)
2022                 {
2023                     if (gl_info->supported[EXT_GPU_SHADER4])
2024                         sample_function->name = "textureCubeGrad";
2025                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
2026                         sample_function->name = "textureCubeGradARB";
2027                     else
2028                     {
2029                         FIXME("Unsupported Cube grad function.\n");
2030                         sample_function->name = "unsupportedCubeGrad";
2031                     }
2032                 }
2033                 else
2034                 {
2035                     sample_function->name = "textureCube";
2036                 }
2037                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2038             }
2039             break;
2040
2041         case WINED3DSTT_VOLUME:
2042             if (shadow)
2043             {
2044                 FIXME("Unsupported 3D shadow function.\n");
2045                 sample_function->name = "unsupported3DShadow";
2046                 sample_function->coord_mask = 0;
2047             }
2048             else
2049             {
2050                 if (lod)
2051                 {
2052                     sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
2053                 }
2054                 else  if (grad)
2055                 {
2056                     if (gl_info->supported[EXT_GPU_SHADER4])
2057                         sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
2058                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
2059                         sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
2060                     else
2061                     {
2062                         FIXME("Unsupported 3D grad function.\n");
2063                         sample_function->name = "unsupported3DGrad";
2064                     }
2065                 }
2066                 else
2067                 {
2068                     sample_function->name = projected ? "texture3DProj" : "texture3D";
2069                 }
2070                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2071             }
2072             break;
2073
2074         default:
2075             sample_function->name = "";
2076             sample_function->coord_mask = 0;
2077             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
2078             break;
2079     }
2080 }
2081
2082 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
2083         BOOL sign_fixup, enum fixup_channel_source channel_source)
2084 {
2085     switch(channel_source)
2086     {
2087         case CHANNEL_SOURCE_ZERO:
2088             strcat(arguments, "0.0");
2089             break;
2090
2091         case CHANNEL_SOURCE_ONE:
2092             strcat(arguments, "1.0");
2093             break;
2094
2095         case CHANNEL_SOURCE_X:
2096             strcat(arguments, reg_name);
2097             strcat(arguments, ".x");
2098             break;
2099
2100         case CHANNEL_SOURCE_Y:
2101             strcat(arguments, reg_name);
2102             strcat(arguments, ".y");
2103             break;
2104
2105         case CHANNEL_SOURCE_Z:
2106             strcat(arguments, reg_name);
2107             strcat(arguments, ".z");
2108             break;
2109
2110         case CHANNEL_SOURCE_W:
2111             strcat(arguments, reg_name);
2112             strcat(arguments, ".w");
2113             break;
2114
2115         default:
2116             FIXME("Unhandled channel source %#x\n", channel_source);
2117             strcat(arguments, "undefined");
2118             break;
2119     }
2120
2121     if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
2122 }
2123
2124 static void shader_glsl_color_correction_ext(struct wined3d_shader_buffer *buffer,
2125         const char *reg_name, DWORD mask, struct color_fixup_desc fixup)
2126 {
2127     unsigned int mask_size, remaining;
2128     DWORD fixup_mask = 0;
2129     char arguments[256];
2130     char mask_str[6];
2131
2132     if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) fixup_mask |= WINED3DSP_WRITEMASK_0;
2133     if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) fixup_mask |= WINED3DSP_WRITEMASK_1;
2134     if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) fixup_mask |= WINED3DSP_WRITEMASK_2;
2135     if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) fixup_mask |= WINED3DSP_WRITEMASK_3;
2136     if (!(mask &= fixup_mask))
2137         return;
2138
2139     if (is_complex_fixup(fixup))
2140     {
2141         enum complex_fixup complex_fixup = get_complex_fixup(fixup);
2142         FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
2143         return;
2144     }
2145
2146     shader_glsl_write_mask_to_str(mask, mask_str);
2147     mask_size = shader_glsl_get_write_mask_size(mask);
2148
2149     arguments[0] = '\0';
2150     remaining = mask_size;
2151     if (mask & WINED3DSP_WRITEMASK_0)
2152     {
2153         shader_glsl_append_fixup_arg(arguments, reg_name, fixup.x_sign_fixup, fixup.x_source);
2154         if (--remaining) strcat(arguments, ", ");
2155     }
2156     if (mask & WINED3DSP_WRITEMASK_1)
2157     {
2158         shader_glsl_append_fixup_arg(arguments, reg_name, fixup.y_sign_fixup, fixup.y_source);
2159         if (--remaining) strcat(arguments, ", ");
2160     }
2161     if (mask & WINED3DSP_WRITEMASK_2)
2162     {
2163         shader_glsl_append_fixup_arg(arguments, reg_name, fixup.z_sign_fixup, fixup.z_source);
2164         if (--remaining) strcat(arguments, ", ");
2165     }
2166     if (mask & WINED3DSP_WRITEMASK_3)
2167     {
2168         shader_glsl_append_fixup_arg(arguments, reg_name, fixup.w_sign_fixup, fixup.w_source);
2169         if (--remaining) strcat(arguments, ", ");
2170     }
2171
2172     if (mask_size > 1)
2173         shader_addline(buffer, "%s%s = vec%u(%s);\n", reg_name, mask_str, mask_size, arguments);
2174     else
2175         shader_addline(buffer, "%s%s = %s;\n", reg_name, mask_str, arguments);
2176 }
2177
2178 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
2179 {
2180     char reg_name[256];
2181     BOOL is_color;
2182
2183     shader_glsl_get_register_name(&ins->dst[0].reg, reg_name, &is_color, ins);
2184     shader_glsl_color_correction_ext(ins->ctx->buffer, reg_name, ins->dst[0].write_mask, fixup);
2185 }
2186
2187 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2188         DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2189         const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2190 {
2191     const struct wined3d_shader_version *version = &ins->ctx->reg_maps->shader_version;
2192     char dst_swizzle[6];
2193     struct color_fixup_desc fixup;
2194     BOOL np2_fixup = FALSE;
2195     va_list args;
2196
2197     shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2198
2199     if (version->type == WINED3D_SHADER_TYPE_PIXEL)
2200     {
2201         const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2202         fixup = priv->cur_ps_args->color_fixup[sampler];
2203
2204         if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2205             if(bias) {
2206                 FIXME("Biased sampling from NP2 textures is unsupported\n");
2207             } else {
2208                 np2_fixup = TRUE;
2209             }
2210         }
2211     }
2212     else
2213     {
2214         fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2215     }
2216
2217     shader_glsl_append_dst(ins->ctx->buffer, ins);
2218
2219     shader_addline(ins->ctx->buffer, "%s(%s_sampler%u, ",
2220             sample_function->name, shader_glsl_get_prefix(version->type), sampler);
2221
2222     va_start(args, coord_reg_fmt);
2223     shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2224     va_end(args);
2225
2226     if(bias) {
2227         shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2228     } else {
2229         if (np2_fixup) {
2230             const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2231             const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2232
2233             shader_addline(ins->ctx->buffer, " * ps_samplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2234                            (idx % 2) ? "zw" : "xy", dst_swizzle);
2235         } else if(dx && dy) {
2236             shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2237         } else {
2238             shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2239         }
2240     }
2241
2242     if(!is_identity_fixup(fixup)) {
2243         shader_glsl_color_correction(ins, fixup);
2244     }
2245 }
2246
2247 /*****************************************************************************
2248  * Begin processing individual instruction opcodes
2249  ****************************************************************************/
2250
2251 static void shader_glsl_binop(const struct wined3d_shader_instruction *ins)
2252 {
2253     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2254     struct glsl_src_param src0_param;
2255     struct glsl_src_param src1_param;
2256     DWORD write_mask;
2257     const char *op;
2258
2259     /* Determine the GLSL operator to use based on the opcode */
2260     switch (ins->handler_idx)
2261     {
2262         case WINED3DSIH_ADD:  op = "+";  break;
2263         case WINED3DSIH_AND:  op = "&";  break;
2264         case WINED3DSIH_DIV:  op = "/";  break;
2265         case WINED3DSIH_IADD: op = "+";  break;
2266         case WINED3DSIH_MUL:  op = "*";  break;
2267         case WINED3DSIH_SUB:  op = "-";  break;
2268         case WINED3DSIH_USHR: op = ">>"; break;
2269         case WINED3DSIH_XOR:  op = "^";  break;
2270         default:
2271             op = "<unhandled operator>";
2272             FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2273             break;
2274     }
2275
2276     write_mask = shader_glsl_append_dst(buffer, ins);
2277     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2278     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2279     shader_addline(buffer, "%s %s %s);\n", src0_param.param_str, op, src1_param.param_str);
2280 }
2281
2282 static void shader_glsl_relop(const struct wined3d_shader_instruction *ins)
2283 {
2284     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2285     struct glsl_src_param src0_param;
2286     struct glsl_src_param src1_param;
2287     unsigned int mask_size;
2288     DWORD write_mask;
2289     const char *op;
2290
2291     write_mask = shader_glsl_append_dst(buffer, ins);
2292     mask_size = shader_glsl_get_write_mask_size(write_mask);
2293     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2294     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2295
2296     if (mask_size > 1)
2297     {
2298         switch (ins->handler_idx)
2299         {
2300             case WINED3DSIH_EQ:  op = "equal"; break;
2301             case WINED3DSIH_GE:  op = "greaterThanEqual"; break;
2302             case WINED3DSIH_IGE: op = "greaterThanEqual"; break;
2303             case WINED3DSIH_LT:  op = "lessThan"; break;
2304             default:
2305                 op = "<unhandled operator>";
2306                 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2307                 break;
2308         }
2309
2310         shader_addline(buffer, "uvec%u(%s(%s, %s)) * 0xffffffffu);\n",
2311                 mask_size, op, src0_param.param_str, src1_param.param_str);
2312     }
2313     else
2314     {
2315         switch (ins->handler_idx)
2316         {
2317             case WINED3DSIH_EQ:  op = "=="; break;
2318             case WINED3DSIH_GE:  op = ">="; break;
2319             case WINED3DSIH_IGE: op = ">="; break;
2320             case WINED3DSIH_LT:  op = "<"; break;
2321             default:
2322                 op = "<unhandled operator>";
2323                 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2324                 break;
2325         }
2326
2327         shader_addline(buffer, "%s %s %s ? 0xffffffffu : 0u);\n",
2328                 src0_param.param_str, op, src1_param.param_str);
2329     }
2330 }
2331
2332 static void shader_glsl_imul(const struct wined3d_shader_instruction *ins)
2333 {
2334     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2335     struct glsl_src_param src0_param;
2336     struct glsl_src_param src1_param;
2337     DWORD write_mask;
2338
2339     /* If we have ARB_gpu_shader5 or GLSL 4.0, we can use imulExtended(). If
2340      * not, we can emulate it. */
2341     if (ins->dst[0].reg.type != WINED3DSPR_NULL)
2342         FIXME("64-bit integer multiplies not implemented.\n");
2343
2344     if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2345     {
2346         write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2347         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2348         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2349
2350         shader_addline(ins->ctx->buffer, "%s * %s);\n",
2351                 src0_param.param_str, src1_param.param_str);
2352     }
2353 }
2354
2355 static void shader_glsl_udiv(const struct wined3d_shader_instruction *ins)
2356 {
2357     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2358     struct glsl_src_param src0_param, src1_param;
2359     DWORD write_mask;
2360
2361     if (ins->dst[0].reg.type != WINED3DSPR_NULL)
2362     {
2363
2364         if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2365         {
2366             char dst_mask[6];
2367
2368             write_mask = shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2369             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2370             shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2371             shader_addline(buffer, "tmp0%s = %s / %s;\n",
2372                     dst_mask, src0_param.param_str, src1_param.param_str);
2373
2374             write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2375             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2376             shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2377             shader_addline(buffer, "%s %% %s));\n", src0_param.param_str, src1_param.param_str);
2378
2379             shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
2380             shader_addline(buffer, "tmp0%s);\n", dst_mask);
2381         }
2382         else
2383         {
2384             write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
2385             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2386             shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2387             shader_addline(buffer, "%s / %s);\n", src0_param.param_str, src1_param.param_str);
2388         }
2389     }
2390     else if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2391     {
2392         write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2393         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2394         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2395         shader_addline(buffer, "%s %% %s);\n", src0_param.param_str, src1_param.param_str);
2396     }
2397 }
2398
2399 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2400 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2401 {
2402     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2403     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2404     struct glsl_src_param src0_param;
2405     DWORD write_mask;
2406
2407     write_mask = shader_glsl_append_dst(buffer, ins);
2408     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2409
2410     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2411      * shader versions WINED3DSIO_MOVA is used for this. */
2412     if (ins->ctx->reg_maps->shader_version.major == 1
2413             && ins->ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX
2414             && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2415     {
2416         /* This is a simple floor() */
2417         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2418         if (mask_size > 1) {
2419             shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2420         } else {
2421             shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2422         }
2423     }
2424     else if(ins->handler_idx == WINED3DSIH_MOVA)
2425     {
2426         /* We need to *round* to the nearest int here. */
2427         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2428
2429         if (gl_info->supported[EXT_GPU_SHADER4])
2430         {
2431             if (mask_size > 1)
2432                 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2433             else
2434                 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2435         }
2436         else
2437         {
2438             if (mask_size > 1)
2439                 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2440                         mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2441             else
2442                 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2443                         src0_param.param_str, src0_param.param_str);
2444         }
2445     }
2446     else
2447     {
2448         shader_addline(buffer, "%s);\n", src0_param.param_str);
2449     }
2450 }
2451
2452 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2453 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2454 {
2455     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2456     struct glsl_src_param src0_param;
2457     struct glsl_src_param src1_param;
2458     DWORD dst_write_mask, src_write_mask;
2459     unsigned int dst_size = 0;
2460
2461     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2462     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2463
2464     /* dp3 works on vec3, dp4 on vec4 */
2465     if (ins->handler_idx == WINED3DSIH_DP4)
2466     {
2467         src_write_mask = WINED3DSP_WRITEMASK_ALL;
2468     } else {
2469         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2470     }
2471
2472     shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2473     shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2474
2475     if (dst_size > 1) {
2476         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2477     } else {
2478         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2479     }
2480 }
2481
2482 /* Note that this instruction has some restrictions. The destination write mask
2483  * can't contain the w component, and the source swizzles have to be .xyzw */
2484 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2485 {
2486     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2487     struct glsl_src_param src0_param;
2488     struct glsl_src_param src1_param;
2489     char dst_mask[6];
2490
2491     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2492     shader_glsl_append_dst(ins->ctx->buffer, ins);
2493     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2494     shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2495     shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2496 }
2497
2498 static void shader_glsl_cut(const struct wined3d_shader_instruction *ins)
2499 {
2500     shader_addline(ins->ctx->buffer, "EndPrimitive();\n");
2501 }
2502
2503 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2504  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2505  * GLSL uses the value as-is. */
2506 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2507 {
2508     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2509     struct glsl_src_param src0_param;
2510     struct glsl_src_param src1_param;
2511     DWORD dst_write_mask;
2512     unsigned int dst_size;
2513
2514     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2515     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2516
2517     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2518     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2519
2520     if (dst_size > 1)
2521     {
2522         shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2523                 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2524     }
2525     else
2526     {
2527         shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2528                 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2529     }
2530 }
2531
2532 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2533  * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2534  * GLSL uses the value as-is. */
2535 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2536 {
2537     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2538     struct glsl_src_param src0_param;
2539     DWORD dst_write_mask;
2540     unsigned int dst_size;
2541
2542     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2543     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2544
2545     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2546
2547     if (dst_size > 1)
2548     {
2549         shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2550                 dst_size, src0_param.param_str);
2551     }
2552     else
2553     {
2554         shader_addline(buffer, "log2(abs(%s)));\n",
2555                 src0_param.param_str);
2556     }
2557 }
2558
2559 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2560 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2561 {
2562     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2563     struct glsl_src_param src_param;
2564     const char *instruction;
2565     DWORD write_mask;
2566     unsigned i;
2567
2568     /* Determine the GLSL function to use based on the opcode */
2569     /* TODO: Possibly make this a table for faster lookups */
2570     switch (ins->handler_idx)
2571     {
2572         case WINED3DSIH_MIN: instruction = "min"; break;
2573         case WINED3DSIH_MAX: instruction = "max"; break;
2574         case WINED3DSIH_ABS: instruction = "abs"; break;
2575         case WINED3DSIH_FRC: instruction = "fract"; break;
2576         case WINED3DSIH_EXP: instruction = "exp2"; break;
2577         case WINED3DSIH_DSX: instruction = "dFdx"; break;
2578         case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2579         case WINED3DSIH_ROUND_NI: instruction = "floor"; break;
2580         default: instruction = "";
2581             FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2582             break;
2583     }
2584
2585     write_mask = shader_glsl_append_dst(buffer, ins);
2586
2587     shader_addline(buffer, "%s(", instruction);
2588
2589     if (ins->src_count)
2590     {
2591         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2592         shader_addline(buffer, "%s", src_param.param_str);
2593         for (i = 1; i < ins->src_count; ++i)
2594         {
2595             shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2596             shader_addline(buffer, ", %s", src_param.param_str);
2597         }
2598     }
2599
2600     shader_addline(buffer, "));\n");
2601 }
2602
2603 static void shader_glsl_nop(const struct wined3d_shader_instruction *ins) {}
2604
2605 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2606 {
2607     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2608     struct glsl_src_param src_param;
2609     unsigned int mask_size;
2610     DWORD write_mask;
2611     char dst_mask[6];
2612
2613     write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2614     mask_size = shader_glsl_get_write_mask_size(write_mask);
2615     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2616
2617     shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2618             src_param.param_str, src_param.param_str);
2619     shader_glsl_append_dst(buffer, ins);
2620
2621     if (mask_size > 1)
2622     {
2623         shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2624                 mask_size, src_param.param_str);
2625     }
2626     else
2627     {
2628         shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2629                 src_param.param_str);
2630     }
2631 }
2632
2633 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2634  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2635  *   dst.x = 2^(floor(src))
2636  *   dst.y = src - floor(src)
2637  *   dst.z = 2^src   (partial precision is allowed, but optional)
2638  *   dst.w = 1.0;
2639  * For 2.0 shaders, just do this (honoring writemask and swizzle):
2640  *   dst = 2^src;    (partial precision is allowed, but optional)
2641  */
2642 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2643 {
2644     struct glsl_src_param src_param;
2645
2646     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2647
2648     if (ins->ctx->reg_maps->shader_version.major < 2)
2649     {
2650         char dst_mask[6];
2651
2652         shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2653         shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2654         shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2655         shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2656
2657         shader_glsl_append_dst(ins->ctx->buffer, ins);
2658         shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2659         shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2660     } else {
2661         DWORD write_mask;
2662         unsigned int mask_size;
2663
2664         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2665         mask_size = shader_glsl_get_write_mask_size(write_mask);
2666
2667         if (mask_size > 1) {
2668             shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2669         } else {
2670             shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2671         }
2672     }
2673 }
2674
2675 static void shader_glsl_to_int(const struct wined3d_shader_instruction *ins)
2676 {
2677     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2678     struct glsl_src_param src_param;
2679     unsigned int mask_size;
2680     DWORD write_mask;
2681
2682     write_mask = shader_glsl_append_dst(buffer, ins);
2683     mask_size = shader_glsl_get_write_mask_size(write_mask);
2684     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2685
2686     if (mask_size > 1)
2687         shader_addline(buffer, "ivec%u(%s));\n", mask_size, src_param.param_str);
2688     else
2689         shader_addline(buffer, "int(%s));\n", src_param.param_str);
2690 }
2691
2692 static void shader_glsl_to_float(const struct wined3d_shader_instruction *ins)
2693 {
2694     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2695     struct glsl_src_param src_param;
2696     unsigned int mask_size;
2697     DWORD write_mask;
2698
2699     write_mask = shader_glsl_append_dst(buffer, ins);
2700     mask_size = shader_glsl_get_write_mask_size(write_mask);
2701     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2702
2703     if (mask_size > 1)
2704         shader_addline(buffer, "vec%u(%s));\n", mask_size, src_param.param_str);
2705     else
2706         shader_addline(buffer, "float(%s));\n", src_param.param_str);
2707 }
2708
2709 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2710 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2711 {
2712     struct glsl_src_param src_param;
2713     DWORD write_mask;
2714     unsigned int mask_size;
2715
2716     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2717     mask_size = shader_glsl_get_write_mask_size(write_mask);
2718     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2719
2720     if (mask_size > 1)
2721     {
2722         shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2723                 mask_size, src_param.param_str);
2724     }
2725     else
2726     {
2727         shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2728                 src_param.param_str);
2729     }
2730 }
2731
2732 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2733 {
2734     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2735     struct glsl_src_param src_param;
2736     DWORD write_mask;
2737     unsigned int mask_size;
2738
2739     write_mask = shader_glsl_append_dst(buffer, ins);
2740     mask_size = shader_glsl_get_write_mask_size(write_mask);
2741
2742     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2743
2744     if (mask_size > 1)
2745     {
2746         shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2747                 mask_size, src_param.param_str);
2748     }
2749     else
2750     {
2751         shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2752                 src_param.param_str);
2753     }
2754 }
2755
2756 /** Process signed comparison opcodes in GLSL. */
2757 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2758 {
2759     struct glsl_src_param src0_param;
2760     struct glsl_src_param src1_param;
2761     DWORD write_mask;
2762     unsigned int mask_size;
2763
2764     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2765     mask_size = shader_glsl_get_write_mask_size(write_mask);
2766     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2767     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2768
2769     if (mask_size > 1) {
2770         const char *compare;
2771
2772         switch(ins->handler_idx)
2773         {
2774             case WINED3DSIH_SLT: compare = "lessThan"; break;
2775             case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2776             default: compare = "";
2777                 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2778         }
2779
2780         shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2781                 src0_param.param_str, src1_param.param_str);
2782     } else {
2783         switch(ins->handler_idx)
2784         {
2785             case WINED3DSIH_SLT:
2786                 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2787                  * to return 0.0 but step returns 1.0 because step is not < x
2788                  * An alternative is a bvec compare padded with an unused second component.
2789                  * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2790                  * issue. Playing with not() is not possible either because not() does not accept
2791                  * a scalar.
2792                  */
2793                 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2794                         src0_param.param_str, src1_param.param_str);
2795                 break;
2796             case WINED3DSIH_SGE:
2797                 /* Here we can use the step() function and safe a conditional */
2798                 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2799                 break;
2800             default:
2801                 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2802         }
2803
2804     }
2805 }
2806
2807 static void shader_glsl_conditional_move(const struct wined3d_shader_instruction *ins)
2808 {
2809     const char *condition_prefix, *condition_suffix;
2810     struct wined3d_shader_dst_param dst;
2811     struct glsl_src_param src0_param;
2812     struct glsl_src_param src1_param;
2813     struct glsl_src_param src2_param;
2814     BOOL temp_destination = FALSE;
2815     DWORD cmp_channel = 0;
2816     unsigned int i, j;
2817     char mask_char[6];
2818     DWORD write_mask;
2819
2820     switch (ins->handler_idx)
2821     {
2822         case WINED3DSIH_CMP:
2823             condition_prefix = "";
2824             condition_suffix = " >= 0.0";
2825             break;
2826
2827         case WINED3DSIH_CND:
2828             condition_prefix = "";
2829             condition_suffix = " > 0.5";
2830             break;
2831
2832         case WINED3DSIH_MOVC:
2833             condition_prefix = "bool(";
2834             condition_suffix = ")";
2835             break;
2836
2837         default:
2838             FIXME("Unhandled instruction %#x.\n", ins->handler_idx);
2839             condition_prefix = "<unhandled prefix>";
2840             condition_suffix = "<unhandled suffix>";
2841             break;
2842     }
2843
2844     if (shader_is_scalar(&ins->src[0].reg))
2845     {
2846         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2847         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2848         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2849         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2850
2851         shader_addline(ins->ctx->buffer, "%s%s%s ? %s : %s);\n",
2852                 condition_prefix, src0_param.param_str, condition_suffix,
2853                 src1_param.param_str, src2_param.param_str);
2854         return;
2855     }
2856
2857     dst = ins->dst[0];
2858
2859     /* Splitting the instruction up in multiple lines imposes a problem:
2860      * The first lines may overwrite source parameters of the following lines.
2861      * Deal with that by using a temporary destination register if needed. */
2862     if ((ins->src[0].reg.idx[0].offset == dst.reg.idx[0].offset
2863                 && ins->src[0].reg.type == dst.reg.type)
2864             || (ins->src[1].reg.idx[0].offset == dst.reg.idx[0].offset
2865                 && ins->src[1].reg.type == dst.reg.type)
2866             || (ins->src[2].reg.idx[0].offset == dst.reg.idx[0].offset
2867                 && ins->src[2].reg.type == dst.reg.type))
2868         temp_destination = TRUE;
2869
2870     /* Cycle through all source0 channels. */
2871     for (i = 0; i < 4; ++i)
2872     {
2873         write_mask = 0;
2874         /* Find the destination channels which use the current source0 channel. */
2875         for (j = 0; j < 4; ++j)
2876         {
2877             if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2878             {
2879                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2880                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2881             }
2882         }
2883         dst.write_mask = ins->dst[0].write_mask & write_mask;
2884
2885         if (temp_destination)
2886         {
2887             if (!(write_mask = shader_glsl_get_write_mask(&dst, mask_char)))
2888                 continue;
2889             shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2890         }
2891         else if (!(write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst)))
2892             continue;
2893
2894         shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2895         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2896         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2897
2898         shader_addline(ins->ctx->buffer, "%s%s%s ? %s : %s);\n",
2899                 condition_prefix, src0_param.param_str, condition_suffix,
2900                 src1_param.param_str, src2_param.param_str);
2901     }
2902
2903     if (temp_destination)
2904     {
2905         shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2906         shader_glsl_append_dst(ins->ctx->buffer, ins);
2907         shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2908     }
2909 }
2910
2911 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2912 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2913  * the compare is done per component of src0. */
2914 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2915 {
2916     struct glsl_src_param src0_param;
2917     struct glsl_src_param src1_param;
2918     struct glsl_src_param src2_param;
2919     DWORD write_mask;
2920     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2921             ins->ctx->reg_maps->shader_version.minor);
2922
2923     if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2924     {
2925         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2926         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2927         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2928         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2929
2930         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2931         if (ins->coissue)
2932         {
2933             shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2934         } else {
2935             shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2936                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
2937         }
2938         return;
2939     }
2940
2941     shader_glsl_conditional_move(ins);
2942 }
2943
2944 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2945 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2946 {
2947     struct glsl_src_param src0_param;
2948     struct glsl_src_param src1_param;
2949     struct glsl_src_param src2_param;
2950     DWORD write_mask;
2951
2952     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2953     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2954     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2955     shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2956     shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2957             src0_param.param_str, src1_param.param_str, src2_param.param_str);
2958 }
2959
2960 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2961    Vertex shaders to GLSL codes */
2962 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2963 {
2964     int i;
2965     int nComponents = 0;
2966     struct wined3d_shader_dst_param tmp_dst = {{0}};
2967     struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2968     struct wined3d_shader_instruction tmp_ins;
2969
2970     memset(&tmp_ins, 0, sizeof(tmp_ins));
2971
2972     /* Set constants for the temporary argument */
2973     tmp_ins.ctx = ins->ctx;
2974     tmp_ins.dst_count = 1;
2975     tmp_ins.dst = &tmp_dst;
2976     tmp_ins.src_count = 2;
2977     tmp_ins.src = tmp_src;
2978
2979     switch(ins->handler_idx)
2980     {
2981         case WINED3DSIH_M4x4:
2982             nComponents = 4;
2983             tmp_ins.handler_idx = WINED3DSIH_DP4;
2984             break;
2985         case WINED3DSIH_M4x3:
2986             nComponents = 3;
2987             tmp_ins.handler_idx = WINED3DSIH_DP4;
2988             break;
2989         case WINED3DSIH_M3x4:
2990             nComponents = 4;
2991             tmp_ins.handler_idx = WINED3DSIH_DP3;
2992             break;
2993         case WINED3DSIH_M3x3:
2994             nComponents = 3;
2995             tmp_ins.handler_idx = WINED3DSIH_DP3;
2996             break;
2997         case WINED3DSIH_M3x2:
2998             nComponents = 2;
2999             tmp_ins.handler_idx = WINED3DSIH_DP3;
3000             break;
3001         default:
3002             break;
3003     }
3004
3005     tmp_dst = ins->dst[0];
3006     tmp_src[0] = ins->src[0];
3007     tmp_src[1] = ins->src[1];
3008     for (i = 0; i < nComponents; ++i)
3009     {
3010         tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
3011         shader_glsl_dot(&tmp_ins);
3012         ++tmp_src[1].reg.idx[0].offset;
3013     }
3014 }
3015
3016 /**
3017     The LRP instruction performs a component-wise linear interpolation
3018     between the second and third operands using the first operand as the
3019     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
3020     This is equivalent to mix(src2, src1, src0);
3021 */
3022 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
3023 {
3024     struct glsl_src_param src0_param;
3025     struct glsl_src_param src1_param;
3026     struct glsl_src_param src2_param;
3027     DWORD write_mask;
3028
3029     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3030
3031     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3032     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
3033     shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
3034
3035     shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
3036             src2_param.param_str, src1_param.param_str, src0_param.param_str);
3037 }
3038
3039 /** Process the WINED3DSIO_LIT instruction in GLSL:
3040  * dst.x = dst.w = 1.0
3041  * dst.y = (src0.x > 0) ? src0.x
3042  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
3043  *                                        where src.w is clamped at +- 128
3044  */
3045 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
3046 {
3047     struct glsl_src_param src0_param;
3048     struct glsl_src_param src1_param;
3049     struct glsl_src_param src3_param;
3050     char dst_mask[6];
3051
3052     shader_glsl_append_dst(ins->ctx->buffer, ins);
3053     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3054
3055     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3056     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
3057     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
3058
3059     /* The sdk specifies the instruction like this
3060      * dst.x = 1.0;
3061      * if(src.x > 0.0) dst.y = src.x
3062      * else dst.y = 0.0.
3063      * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
3064      * else dst.z = 0.0;
3065      * dst.w = 1.0;
3066      * (where power = src.w clamped between -128 and 128)
3067      *
3068      * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
3069      * dst.x = 1.0                                  ... No further explanation needed
3070      * dst.y = max(src.y, 0.0);                     ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
3071      * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0;   ... 0 ^ power is 0, and otherwise we use y anyway
3072      * dst.w = 1.0.                                 ... Nothing fancy.
3073      *
3074      * So we still have one conditional in there. So do this:
3075      * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
3076      *
3077      * step(0.0, x) will return 1 if src.x > 0.0, and 0 otherwise. So if y is 0 we get pow(0.0 * 1.0, power),
3078      * which sets dst.z to 0. If y > 0, but x = 0.0, we get pow(y * 0.0, power), which results in 0 too.
3079      * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
3080      *
3081      * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
3082      * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
3083      * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
3084      */
3085     shader_addline(ins->ctx->buffer,
3086             "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
3087             "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
3088             src0_param.param_str, src3_param.param_str, src1_param.param_str,
3089             src0_param.param_str, src3_param.param_str, dst_mask);
3090 }
3091
3092 /** Process the WINED3DSIO_DST instruction in GLSL:
3093  * dst.x = 1.0
3094  * dst.y = src0.x * src0.y
3095  * dst.z = src0.z
3096  * dst.w = src1.w
3097  */
3098 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
3099 {
3100     struct glsl_src_param src0y_param;
3101     struct glsl_src_param src0z_param;
3102     struct glsl_src_param src1y_param;
3103     struct glsl_src_param src1w_param;
3104     char dst_mask[6];
3105
3106     shader_glsl_append_dst(ins->ctx->buffer, ins);
3107     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3108
3109     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
3110     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
3111     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
3112     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
3113
3114     shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
3115             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
3116 }
3117
3118 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
3119  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
3120  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
3121  *
3122  * dst.x = cos(src0.?)
3123  * dst.y = sin(src0.?)
3124  * dst.z = dst.z
3125  * dst.w = dst.w
3126  */
3127 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
3128 {
3129     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3130     struct glsl_src_param src0_param;
3131     DWORD write_mask;
3132
3133     if (ins->ctx->reg_maps->shader_version.major < 4)
3134     {
3135         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3136
3137         write_mask = shader_glsl_append_dst(buffer, ins);
3138         switch (write_mask)
3139         {
3140             case WINED3DSP_WRITEMASK_0:
3141                 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3142                 break;
3143
3144             case WINED3DSP_WRITEMASK_1:
3145                 shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
3146                 break;
3147
3148             case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
3149                 shader_addline(buffer, "vec2(cos(%s), sin(%s)));\n",
3150                         src0_param.param_str, src0_param.param_str);
3151                 break;
3152
3153             default:
3154                 ERR("Write mask should be .x, .y or .xy\n");
3155                 break;
3156         }
3157
3158         return;
3159     }
3160
3161     if (ins->dst[0].reg.type != WINED3DSPR_NULL)
3162     {
3163
3164         if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3165         {
3166             char dst_mask[6];
3167
3168             write_mask = shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3169             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3170             shader_addline(buffer, "tmp0%s = sin(%s);\n", dst_mask, src0_param.param_str);
3171
3172             write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3173             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3174             shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3175
3176             shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3177             shader_addline(buffer, "tmp0%s);\n", dst_mask);
3178         }
3179         else
3180         {
3181             write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3182             shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3183             shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
3184         }
3185     }
3186     else if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3187     {
3188         write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3189         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3190         shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3191     }
3192 }
3193
3194 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
3195  * here. But those extra parameters require a dedicated function for sgn, since map2gl would
3196  * generate invalid code
3197  */
3198 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
3199 {
3200     struct glsl_src_param src0_param;
3201     DWORD write_mask;
3202
3203     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3204     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3205
3206     shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
3207 }
3208
3209 /** Process the WINED3DSIO_LOOP instruction in GLSL:
3210  * Start a for() loop where src1.y is the initial value of aL,
3211  *  increment aL by src1.z for a total of src1.x iterations.
3212  *  Need to use a temporary variable for this operation.
3213  */
3214 /* FIXME: I don't think nested loops will work correctly this way. */
3215 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
3216 {
3217     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3218     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3219     const struct wined3d_shader *shader = ins->ctx->shader;
3220     const struct wined3d_shader_lconst *constant;
3221     struct glsl_src_param src1_param;
3222     const DWORD *control_values = NULL;
3223
3224     if (ins->ctx->reg_maps->shader_version.major < 4)
3225     {
3226         shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
3227
3228         /* Try to hardcode the loop control parameters if possible. Direct3D 9
3229          * class hardware doesn't support real varying indexing, but Microsoft
3230          * designed this feature for Shader model 2.x+. If the loop control is
3231          * known at compile time, the GLSL compiler can unroll the loop, and
3232          * replace indirect addressing with direct addressing. */
3233         if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
3234         {
3235             LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3236             {
3237                 if (constant->idx == ins->src[1].reg.idx[0].offset)
3238                 {
3239                     control_values = constant->value;
3240                     break;
3241                 }
3242             }
3243         }
3244
3245         if (control_values)
3246         {
3247             struct wined3d_shader_loop_control loop_control;
3248             loop_control.count = control_values[0];
3249             loop_control.start = control_values[1];
3250             loop_control.step = (int)control_values[2];
3251
3252             if (loop_control.step > 0)
3253             {
3254                 shader_addline(buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d)\n{\n",
3255                         loop_state->current_depth, loop_control.start,
3256                         loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3257                         loop_state->current_depth, loop_control.step);
3258             }
3259             else if (loop_control.step < 0)
3260             {
3261                 shader_addline(buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d)\n{\n",
3262                         loop_state->current_depth, loop_control.start,
3263                         loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3264                         loop_state->current_depth, loop_control.step);
3265             }
3266             else
3267             {
3268                 shader_addline(buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++)\n{\n",
3269                         loop_state->current_depth, loop_control.start, loop_state->current_depth,
3270                         loop_state->current_depth, loop_control.count,
3271                         loop_state->current_depth);
3272             }
3273         }
3274         else
3275         {
3276             shader_addline(buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z)\n{\n",
3277                     loop_state->current_depth, loop_state->current_reg,
3278                     src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
3279                     loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
3280         }
3281
3282         ++loop_state->current_reg;
3283     }
3284     else
3285     {
3286         shader_addline(buffer, "for (;;)\n{\n");
3287     }
3288
3289     ++loop_state->current_depth;
3290 }
3291
3292 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
3293 {
3294     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3295
3296     shader_addline(ins->ctx->buffer, "}\n");
3297
3298     if (ins->handler_idx == WINED3DSIH_ENDLOOP)
3299     {
3300         --loop_state->current_depth;
3301         --loop_state->current_reg;
3302     }
3303
3304     if (ins->handler_idx == WINED3DSIH_ENDREP)
3305     {
3306         --loop_state->current_depth;
3307     }
3308 }
3309
3310 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
3311 {
3312     const struct wined3d_shader *shader = ins->ctx->shader;
3313     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3314     const struct wined3d_shader_lconst *constant;
3315     struct glsl_src_param src0_param;
3316     const DWORD *control_values = NULL;
3317
3318     /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
3319     if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
3320     {
3321         LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3322         {
3323             if (constant->idx == ins->src[0].reg.idx[0].offset)
3324             {
3325                 control_values = constant->value;
3326                 break;
3327             }
3328         }
3329     }
3330
3331     if (control_values)
3332     {
3333         shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
3334                 loop_state->current_depth, loop_state->current_depth,
3335                 control_values[0], loop_state->current_depth);
3336     }
3337     else
3338     {
3339         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3340         shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
3341                 loop_state->current_depth, loop_state->current_depth,
3342                 src0_param.param_str, loop_state->current_depth);
3343     }
3344
3345     ++loop_state->current_depth;
3346 }
3347
3348 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
3349 {
3350     struct glsl_src_param src0_param;
3351
3352     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3353     shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
3354 }
3355
3356 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
3357 {
3358     struct glsl_src_param src0_param;
3359     struct glsl_src_param src1_param;
3360
3361     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3362     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3363
3364     shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
3365             src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3366 }
3367
3368 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
3369 {
3370     shader_addline(ins->ctx->buffer, "} else {\n");
3371 }
3372
3373 static void shader_glsl_emit(const struct wined3d_shader_instruction *ins)
3374 {
3375     shader_addline(ins->ctx->buffer, "EmitVertex();\n");
3376 }
3377
3378 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
3379 {
3380     shader_addline(ins->ctx->buffer, "break;\n");
3381 }
3382
3383 /* FIXME: According to MSDN the compare is done per component. */
3384 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
3385 {
3386     struct glsl_src_param src0_param;
3387     struct glsl_src_param src1_param;
3388
3389     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3390     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3391
3392     shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3393             src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3394 }
3395
3396 static void shader_glsl_breakp(const struct wined3d_shader_instruction *ins)
3397 {
3398     struct glsl_src_param src_param;
3399
3400     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
3401     shader_addline(ins->ctx->buffer, "if (bool(%s)) break;\n", src_param.param_str);
3402 }
3403
3404 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3405 {
3406     shader_addline(ins->ctx->buffer, "}\n");
3407     shader_addline(ins->ctx->buffer, "void subroutine%u()\n{\n", ins->src[0].reg.idx[0].offset);
3408 }
3409
3410 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3411 {
3412     shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx[0].offset);
3413 }
3414
3415 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3416 {
3417     struct glsl_src_param src1_param;
3418
3419     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3420     shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n",
3421             src1_param.param_str, ins->src[0].reg.idx[0].offset);
3422 }
3423
3424 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3425 {
3426     /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3427      * function only suppresses the unhandled instruction warning
3428      */
3429 }
3430
3431 /*********************************************
3432  * Pixel Shader Specific Code begins here
3433  ********************************************/
3434 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3435 {
3436     const struct wined3d_shader *shader = ins->ctx->shader;
3437     struct wined3d_device *device = shader->device;
3438     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3439             ins->ctx->reg_maps->shader_version.minor);
3440     struct glsl_sample_function sample_function;
3441     const struct wined3d_texture *texture;
3442     DWORD sample_flags = 0;
3443     DWORD sampler_idx;
3444     DWORD mask = 0, swizzle;
3445
3446     /* 1.0-1.4: Use destination register as sampler source.
3447      * 2.0+: Use provided sampler source. */
3448     if (shader_version < WINED3D_SHADER_VERSION(2,0))
3449         sampler_idx = ins->dst[0].reg.idx[0].offset;
3450     else
3451         sampler_idx = ins->src[1].reg.idx[0].offset;
3452     texture = device->stateBlock->state.textures[sampler_idx];
3453
3454     if (shader_version < WINED3D_SHADER_VERSION(1,4))
3455     {
3456         const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3457         DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3458                 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3459         enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3460
3461         /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3462         if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE)
3463         {
3464             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3465             switch (flags & ~WINED3D_PSARGS_PROJECTED)
3466             {
3467                 case WINED3D_TTFF_COUNT1:
3468                     FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3469                     break;
3470                 case WINED3D_TTFF_COUNT2:
3471                     mask = WINED3DSP_WRITEMASK_1;
3472                     break;
3473                 case WINED3D_TTFF_COUNT3:
3474                     mask = WINED3DSP_WRITEMASK_2;
3475                     break;
3476                 case WINED3D_TTFF_COUNT4:
3477                 case WINED3D_TTFF_DISABLE:
3478                     mask = WINED3DSP_WRITEMASK_3;
3479                     break;
3480             }
3481         }
3482     }
3483     else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3484     {
3485         enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3486
3487         if (src_mod == WINED3DSPSM_DZ) {
3488             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3489             mask = WINED3DSP_WRITEMASK_2;
3490         } else if (src_mod == WINED3DSPSM_DW) {
3491             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3492             mask = WINED3DSP_WRITEMASK_3;
3493         }
3494     } else {
3495         if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3496         {
3497             /* ps 2.0 texldp instruction always divides by the fourth component. */
3498             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3499             mask = WINED3DSP_WRITEMASK_3;
3500         }
3501     }
3502
3503     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3504         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3505
3506     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3507     mask |= sample_function.coord_mask;
3508
3509     if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3510     else swizzle = ins->src[1].swizzle;
3511
3512     /* 1.0-1.3: Use destination register as coordinate source.
3513        1.4+: Use provided coordinate source register. */
3514     if (shader_version < WINED3D_SHADER_VERSION(1,4))
3515     {
3516         char coord_mask[6];
3517         shader_glsl_write_mask_to_str(mask, coord_mask);
3518         shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3519                 "T%u%s", sampler_idx, coord_mask);
3520     }
3521     else
3522     {
3523         struct glsl_src_param coord_param;
3524         shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3525         if (ins->flags & WINED3DSI_TEXLD_BIAS)
3526         {
3527             struct glsl_src_param bias;
3528             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3529             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3530                     "%s", coord_param.param_str);
3531         } else {
3532             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3533                     "%s", coord_param.param_str);
3534         }
3535     }
3536 }
3537
3538 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3539 {
3540     const struct wined3d_shader *shader = ins->ctx->shader;
3541     struct wined3d_device *device = shader->device;
3542     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3543     struct glsl_src_param coord_param, dx_param, dy_param;
3544     DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3545     struct glsl_sample_function sample_function;
3546     DWORD sampler_idx;
3547     DWORD swizzle = ins->src[1].swizzle;
3548     const struct wined3d_texture *texture;
3549
3550     if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3551     {
3552         FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3553         shader_glsl_tex(ins);
3554         return;
3555     }
3556
3557     sampler_idx = ins->src[1].reg.idx[0].offset;
3558     texture = device->stateBlock->state.textures[sampler_idx];
3559     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3560         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3561
3562     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3563     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3564     shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3565     shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3566
3567     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3568                                 "%s", coord_param.param_str);
3569 }
3570
3571 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3572 {
3573     const struct wined3d_shader *shader = ins->ctx->shader;
3574     struct wined3d_device *device = shader->device;
3575     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3576     struct glsl_src_param coord_param, lod_param;
3577     DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3578     struct glsl_sample_function sample_function;
3579     DWORD sampler_idx;
3580     DWORD swizzle = ins->src[1].swizzle;
3581     const struct wined3d_texture *texture;
3582
3583     sampler_idx = ins->src[1].reg.idx[0].offset;
3584     texture = device->stateBlock->state.textures[sampler_idx];
3585     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3586         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3587
3588     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3589     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3590
3591     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3592
3593     if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3594             && ins->ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
3595     {
3596         /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3597          * However, the NVIDIA drivers allow them in fragment shaders as well,
3598          * even without the appropriate extension. */
3599         WARN("Using %s in fragment shader.\n", sample_function.name);
3600     }
3601     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3602             "%s", coord_param.param_str);
3603 }
3604
3605 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3606 {
3607     /* FIXME: Make this work for more than just 2D textures */
3608     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3609     DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3610
3611     if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3612     {
3613         char dst_mask[6];
3614
3615         shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3616         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3617                 ins->dst[0].reg.idx[0].offset, dst_mask);
3618     }
3619     else
3620     {
3621         enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3622         DWORD reg = ins->src[0].reg.idx[0].offset;
3623         char dst_swizzle[6];
3624
3625         shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3626
3627         if (src_mod == WINED3DSPSM_DZ)
3628         {
3629             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3630             struct glsl_src_param div_param;
3631
3632             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3633
3634             if (mask_size > 1) {
3635                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3636             } else {
3637                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3638             }
3639         }
3640         else if (src_mod == WINED3DSPSM_DW)
3641         {
3642             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3643             struct glsl_src_param div_param;
3644
3645             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3646
3647             if (mask_size > 1) {
3648                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3649             } else {
3650                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3651             }
3652         } else {
3653             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3654         }
3655     }
3656 }
3657
3658 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3659  * Take a 3-component dot product of the TexCoord[dstreg] and src,
3660  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3661 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3662 {
3663     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3664     DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3665     struct glsl_sample_function sample_function;
3666     struct glsl_src_param src0_param;
3667     UINT mask_size;
3668
3669     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3670
3671     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3672      * scalar, and projected sampling would require 4.
3673      *
3674      * It is a dependent read - not valid with conditional NP2 textures
3675      */
3676     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3677     mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3678
3679     switch(mask_size)
3680     {
3681         case 1:
3682             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3683                     "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3684             break;
3685
3686         case 2:
3687             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3688                     "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3689             break;
3690
3691         case 3:
3692             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3693                     "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3694             break;
3695
3696         default:
3697             FIXME("Unexpected mask size %u\n", mask_size);
3698             break;
3699     }
3700 }
3701
3702 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3703  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3704 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3705 {
3706     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3707     DWORD dstreg = ins->dst[0].reg.idx[0].offset;
3708     struct glsl_src_param src0_param;
3709     DWORD dst_mask;
3710     unsigned int mask_size;
3711
3712     dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3713     mask_size = shader_glsl_get_write_mask_size(dst_mask);
3714     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3715
3716     if (mask_size > 1) {
3717         shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3718     } else {
3719         shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3720     }
3721 }
3722
3723 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3724  * Calculate the depth as dst.x / dst.y   */
3725 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3726 {
3727     struct glsl_dst_param dst_param;
3728
3729     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3730
3731     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3732      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3733      * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3734      * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3735      * >= 1.0 or < 0.0
3736      */
3737     shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3738             dst_param.reg_name, dst_param.reg_name);
3739 }
3740
3741 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3742  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3743  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
3744  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3745  */
3746 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3747 {
3748     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3749     DWORD dstreg = ins->dst[0].reg.idx[0].offset;
3750     struct glsl_src_param src0_param;
3751
3752     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3753
3754     shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3755     shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3756 }
3757
3758 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3759  * Calculate the 1st of a 2-row matrix multiplication. */
3760 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3761 {
3762     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3763     DWORD reg = ins->dst[0].reg.idx[0].offset;
3764     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3765     struct glsl_src_param src0_param;
3766
3767     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3768     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3769 }
3770
3771 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3772  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3773 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3774 {
3775     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3776     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3777     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3778     DWORD reg = ins->dst[0].reg.idx[0].offset;
3779     struct glsl_src_param src0_param;
3780
3781     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3782     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3783     tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3784 }
3785
3786 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3787 {
3788     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3789     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3790     struct glsl_sample_function sample_function;
3791     DWORD reg = ins->dst[0].reg.idx[0].offset;
3792     struct glsl_src_param src0_param;
3793
3794     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3795     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3796
3797     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3798
3799     /* Sample the texture using the calculated coordinates */
3800     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3801 }
3802
3803 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3804  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3805 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3806 {
3807     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3808     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3809     struct glsl_sample_function sample_function;
3810     DWORD reg = ins->dst[0].reg.idx[0].offset;
3811     struct glsl_src_param src0_param;
3812
3813     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3814     shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3815
3816     /* Dependent read, not valid with conditional NP2 */
3817     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3818
3819     /* Sample the texture using the calculated coordinates */
3820     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3821
3822     tex_mx->current_row = 0;
3823 }
3824
3825 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3826  * Perform the 3rd row of a 3x3 matrix multiply */
3827 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3828 {
3829     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3830     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3831     DWORD reg = ins->dst[0].reg.idx[0].offset;
3832     struct glsl_src_param src0_param;
3833     char dst_mask[6];
3834
3835     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3836
3837     shader_glsl_append_dst(ins->ctx->buffer, ins);
3838     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3839     shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3840
3841     tex_mx->current_row = 0;
3842 }
3843
3844 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3845  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3846 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3847 {
3848     struct glsl_src_param src0_param;
3849     struct glsl_src_param src1_param;
3850     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3851     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3852     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3853     struct glsl_sample_function sample_function;
3854     DWORD reg = ins->dst[0].reg.idx[0].offset;
3855     char coord_mask[6];
3856
3857     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3858     shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3859
3860     /* Perform the last matrix multiply operation */
3861     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3862     /* Reflection calculation */
3863     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3864
3865     /* Dependent read, not valid with conditional NP2 */
3866     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3867     shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3868
3869     /* Sample the texture */
3870     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3871             NULL, NULL, NULL, "tmp0%s", coord_mask);
3872
3873     tex_mx->current_row = 0;
3874 }
3875
3876 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3877  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3878 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3879 {
3880     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3881     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3882     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3883     struct glsl_sample_function sample_function;
3884     DWORD reg = ins->dst[0].reg.idx[0].offset;
3885     struct glsl_src_param src0_param;
3886     char coord_mask[6];
3887
3888     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3889
3890     /* Perform the last matrix multiply operation */
3891     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3892
3893     /* Construct the eye-ray vector from w coordinates */
3894     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3895             tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3896     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3897
3898     /* Dependent read, not valid with conditional NP2 */
3899     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3900     shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3901
3902     /* Sample the texture using the calculated coordinates */
3903     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3904             NULL, NULL, NULL, "tmp0%s", coord_mask);
3905
3906     tex_mx->current_row = 0;
3907 }
3908
3909 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3910  * Apply a fake bump map transform.
3911  * texbem is pshader <= 1.3 only, this saves a few version checks
3912  */
3913 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3914 {
3915     const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3916     struct glsl_sample_function sample_function;
3917     struct glsl_src_param coord_param;
3918     DWORD sampler_idx;
3919     DWORD mask;
3920     DWORD flags;
3921     char coord_mask[6];
3922
3923     sampler_idx = ins->dst[0].reg.idx[0].offset;
3924     flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3925             & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3926
3927     /* Dependent read, not valid with conditional NP2 */
3928     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3929     mask = sample_function.coord_mask;
3930
3931     shader_glsl_write_mask_to_str(mask, coord_mask);
3932
3933     /* With projected textures, texbem only divides the static texture coord,
3934      * not the displacement, so we can't let GL handle this. */
3935     if (flags & WINED3D_PSARGS_PROJECTED)
3936     {
3937         DWORD div_mask=0;
3938         char coord_div_mask[3];
3939         switch (flags & ~WINED3D_PSARGS_PROJECTED)
3940         {
3941             case WINED3D_TTFF_COUNT1:
3942                 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3943                 break;
3944             case WINED3D_TTFF_COUNT2:
3945                 div_mask = WINED3DSP_WRITEMASK_1;
3946                 break;
3947             case WINED3D_TTFF_COUNT3:
3948                 div_mask = WINED3DSP_WRITEMASK_2;
3949                 break;
3950             case WINED3D_TTFF_COUNT4:
3951             case WINED3D_TTFF_DISABLE:
3952                 div_mask = WINED3DSP_WRITEMASK_3;
3953                 break;
3954         }
3955         shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3956         shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3957     }
3958
3959     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3960
3961     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3962             "T%u%s + vec4(bumpenv_mat%u * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3963             coord_param.param_str, coord_mask);
3964
3965     if (ins->handler_idx == WINED3DSIH_TEXBEML)
3966     {
3967         struct glsl_src_param luminance_param;
3968         struct glsl_dst_param dst_param;
3969
3970         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3971         shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3972
3973         shader_addline(ins->ctx->buffer, "%s%s *= (%s * bumpenv_lum_scale%u + bumpenv_lum_offset%u);\n",
3974                 dst_param.reg_name, dst_param.mask_str,
3975                 luminance_param.param_str, sampler_idx, sampler_idx);
3976     }
3977 }
3978
3979 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3980 {
3981     DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3982     struct glsl_src_param src0_param, src1_param;
3983
3984     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3985     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3986
3987     shader_glsl_append_dst(ins->ctx->buffer, ins);
3988     shader_addline(ins->ctx->buffer, "%s + bumpenv_mat%u * %s);\n",
3989             src0_param.param_str, sampler_idx, src1_param.param_str);
3990 }
3991
3992 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3993  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3994 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3995 {
3996     DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3997     struct glsl_sample_function sample_function;
3998     struct glsl_src_param src0_param;
3999
4000     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
4001
4002     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
4003     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
4004             "%s.wx", src0_param.reg_name);
4005 }
4006
4007 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
4008  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
4009 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
4010 {
4011     DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
4012     struct glsl_sample_function sample_function;
4013     struct glsl_src_param src0_param;
4014
4015     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
4016
4017     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
4018     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
4019             "%s.yz", src0_param.reg_name);
4020 }
4021
4022 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
4023  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
4024 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
4025 {
4026     DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
4027     struct glsl_sample_function sample_function;
4028     struct glsl_src_param src0_param;
4029
4030     /* Dependent read, not valid with conditional NP2 */
4031     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
4032     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
4033
4034     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
4035             "%s", src0_param.param_str);
4036 }
4037
4038 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
4039  * If any of the first 3 components are < 0, discard this pixel */
4040 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
4041 {
4042     struct glsl_dst_param dst_param;
4043
4044     /* The argument is a destination parameter, and no writemasks are allowed */
4045     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
4046     if (ins->ctx->reg_maps->shader_version.major >= 2)
4047     {
4048         /* 2.0 shaders compare all 4 components in texkill */
4049         shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
4050     } else {
4051         /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
4052          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
4053          * 4 components are defined, only the first 3 are used
4054          */
4055         shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
4056     }
4057 }
4058
4059 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
4060  * dst = dot2(src0, src1) + src2 */
4061 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
4062 {
4063     struct glsl_src_param src0_param;
4064     struct glsl_src_param src1_param;
4065     struct glsl_src_param src2_param;
4066     DWORD write_mask;
4067     unsigned int mask_size;
4068
4069     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
4070     mask_size = shader_glsl_get_write_mask_size(write_mask);
4071
4072     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
4073     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
4074     shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
4075
4076     if (mask_size > 1) {
4077         shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
4078                 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
4079     } else {
4080         shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
4081                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
4082     }
4083 }
4084
4085 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
4086         const struct wined3d_shader_signature_element *input_signature,
4087         const struct wined3d_shader_reg_maps *reg_maps,
4088         enum vertexprocessing_mode vertexprocessing)
4089 {
4090     WORD map = reg_maps->input_registers;
4091     unsigned int i;
4092
4093     for (i = 0; map; map >>= 1, ++i)
4094     {
4095         const char *semantic_name;
4096         UINT semantic_idx;
4097         char reg_mask[6];
4098
4099         /* Unused */
4100         if (!(map & 1)) continue;
4101
4102         semantic_name = input_signature[i].semantic_name;
4103         semantic_idx = input_signature[i].semantic_idx;
4104         shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
4105
4106         if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
4107         {
4108             if (semantic_idx < 8 && vertexprocessing == pretransformed)
4109                 shader_addline(buffer, "ps_in[%u]%s = gl_TexCoord[%u]%s;\n",
4110                         shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
4111             else
4112                 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4113                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4114         }
4115         else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
4116         {
4117             if (!semantic_idx)
4118                 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_Color)%s;\n",
4119                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4120             else if (semantic_idx == 1)
4121                 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_SecondaryColor)%s;\n",
4122                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4123             else
4124                 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4125                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4126         }
4127         else
4128         {
4129             shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4130                     shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4131         }
4132     }
4133 }
4134
4135 /*********************************************
4136  * Vertex Shader Specific Code begins here
4137  ********************************************/
4138
4139 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
4140 {
4141     struct glsl_program_key key;
4142
4143     key.vs_id = entry->vs.id;
4144     key.ps_id = entry->ps.id;
4145
4146     if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
4147     {
4148         ERR("Failed to insert program entry.\n");
4149     }
4150 }
4151
4152 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
4153         GLhandleARB vs_id, GLhandleARB ps_id)
4154 {
4155     struct wine_rb_entry *entry;
4156     struct glsl_program_key key;
4157
4158     key.vs_id = vs_id;
4159     key.ps_id = ps_id;
4160
4161     entry = wine_rb_get(&priv->program_lookup, &key);
4162     return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
4163 }
4164
4165 /* GL locking is done by the caller */
4166 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
4167         struct glsl_shader_prog_link *entry)
4168 {
4169     struct glsl_program_key key;
4170
4171     key.vs_id = entry->vs.id;
4172     key.ps_id = entry->ps.id;
4173     wine_rb_remove(&priv->program_lookup, &key);
4174
4175     GL_EXTCALL(glDeleteObjectARB(entry->programId));
4176     if (entry->vs.id)
4177         list_remove(&entry->vs.shader_entry);
4178     if (entry->ps.id)
4179         list_remove(&entry->ps.shader_entry);
4180     HeapFree(GetProcessHeap(), 0, entry->vs.uniform_f_locations);
4181     HeapFree(GetProcessHeap(), 0, entry->ps.uniform_f_locations);
4182     HeapFree(GetProcessHeap(), 0, entry);
4183 }
4184
4185 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
4186         const struct wined3d_gl_info *gl_info, const DWORD *map,
4187         const struct wined3d_shader_signature_element *input_signature,
4188         const struct wined3d_shader_reg_maps *reg_maps_in,
4189         const struct wined3d_shader_signature_element *output_signature,
4190         const struct wined3d_shader_reg_maps *reg_maps_out)
4191 {
4192     unsigned int i, j;
4193     const char *semantic_name_in;
4194     UINT semantic_idx_in;
4195     DWORD *set;
4196     DWORD in_idx;
4197     unsigned int in_count = vec4_varyings(3, gl_info);
4198     char reg_mask[6];
4199     char destination[50];
4200     WORD input_map, output_map;
4201
4202     set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
4203
4204     input_map = reg_maps_in->input_registers;
4205     for (i = 0; input_map; input_map >>= 1, ++i)
4206     {
4207         if (!(input_map & 1)) continue;
4208
4209         in_idx = map[i];
4210         /* Declared, but not read register */
4211         if (in_idx == ~0U) continue;
4212         if (in_idx >= (in_count + 2))
4213         {
4214             FIXME("More input varyings declared than supported, expect issues.\n");
4215             continue;
4216         }
4217
4218         if (in_idx == in_count)
4219             sprintf(destination, "gl_FrontColor");
4220         else if (in_idx == in_count + 1)
4221             sprintf(destination, "gl_FrontSecondaryColor");
4222         else
4223             sprintf(destination, "ps_in[%u]", in_idx);
4224
4225         semantic_name_in = input_signature[i].semantic_name;
4226         semantic_idx_in = input_signature[i].semantic_idx;
4227         set[in_idx] = ~0U;
4228
4229         output_map = reg_maps_out->output_registers;
4230         for (j = 0; output_map; output_map >>= 1, ++j)
4231         {
4232             DWORD mask;
4233
4234             if (!(output_map & 1)
4235                     || semantic_idx_in != output_signature[j].semantic_idx
4236                     || strcmp(semantic_name_in, output_signature[j].semantic_name)
4237                     || !(mask = input_signature[i].mask & output_signature[j].mask))
4238                 continue;
4239
4240             set[in_idx] = mask;
4241             shader_glsl_write_mask_to_str(mask, reg_mask);
4242
4243             shader_addline(buffer, "%s%s = vs_out[%u]%s;\n",
4244                     destination, reg_mask, j, reg_mask);
4245         }
4246     }
4247
4248     for (i = 0; i < in_count + 2; ++i)
4249     {
4250         unsigned int size;
4251
4252         if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
4253             continue;
4254
4255         if (set[i] == ~0U) set[i] = 0;
4256
4257         size = 0;
4258         if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
4259         if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
4260         if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
4261         if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
4262         reg_mask[size] = '\0';
4263
4264         if (i == in_count)
4265             sprintf(destination, "gl_FrontColor");
4266         else if (i == in_count + 1)
4267             sprintf(destination, "gl_FrontSecondaryColor");
4268         else
4269             sprintf(destination, "ps_in[%u]", i);
4270
4271         if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
4272         else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
4273     }
4274
4275     HeapFree(GetProcessHeap(), 0, set);
4276 }
4277
4278 /* GL locking is done by the caller */
4279 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
4280         const struct wined3d_shader *vs, const struct wined3d_shader *ps,
4281         const struct wined3d_gl_info *gl_info)
4282 {
4283     GLhandleARB ret = 0;
4284     DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
4285     unsigned int i;
4286     const char *semantic_name;
4287     UINT semantic_idx;
4288     char reg_mask[6];
4289     const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
4290     WORD map = vs->reg_maps.output_registers;
4291
4292     shader_buffer_clear(buffer);
4293
4294     shader_addline(buffer, "#version 120\n");
4295
4296     if (ps_major < 3)
4297     {
4298         shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4299
4300         for (i = 0; map; map >>= 1, ++i)
4301         {
4302             DWORD write_mask;
4303
4304             if (!(map & 1)) continue;
4305
4306             semantic_name = output_signature[i].semantic_name;
4307             semantic_idx = output_signature[i].semantic_idx;
4308             write_mask = output_signature[i].mask;
4309             shader_glsl_write_mask_to_str(write_mask, reg_mask);
4310
4311             if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
4312             {
4313                 if (!semantic_idx)
4314                     shader_addline(buffer, "gl_FrontColor%s = vs_out[%u]%s;\n",
4315                             reg_mask, i, reg_mask);
4316                 else if (semantic_idx == 1)
4317                     shader_addline(buffer, "gl_FrontSecondaryColor%s = vs_out[%u]%s;\n",
4318                             reg_mask, i, reg_mask);
4319             }
4320             else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4321             {
4322                 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4323                         reg_mask, i, reg_mask);
4324             }
4325             else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
4326             {
4327                 if (semantic_idx < 8)
4328                 {
4329                     if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
4330                         write_mask |= WINED3DSP_WRITEMASK_3;
4331
4332                     shader_addline(buffer, "gl_TexCoord[%u]%s = vs_out[%u]%s;\n",
4333                             semantic_idx, reg_mask, i, reg_mask);
4334                     if (!(write_mask & WINED3DSP_WRITEMASK_3))
4335                         shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
4336                 }
4337             }
4338             else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4339             {
4340                 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4341             }
4342             else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_FOG))
4343             {
4344                 shader_addline(buffer, "gl_FogFragCoord = clamp(vs_out[%u].%c, 0.0, 1.0);\n", i, reg_mask[1]);
4345             }
4346         }
4347         shader_addline(buffer, "}\n");
4348     }
4349     else
4350     {
4351         UINT in_count = min(vec4_varyings(ps_major, gl_info), ps->limits.packed_input);
4352         /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
4353         shader_addline(buffer, "varying vec4 ps_in[%u];\n", in_count);
4354         shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4355
4356         /* First, sort out position and point size. Those are not passed to the pixel shader */
4357         for (i = 0; map; map >>= 1, ++i)
4358         {
4359             if (!(map & 1)) continue;
4360
4361             semantic_name = output_signature[i].semantic_name;
4362             shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
4363
4364             if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4365             {
4366                 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4367                         reg_mask, i, reg_mask);
4368             }
4369             else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4370             {
4371                 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4372             }
4373         }
4374
4375         /* Then, fix the pixel shader input */
4376         handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
4377                 &ps->reg_maps, output_signature, &vs->reg_maps);
4378
4379         shader_addline(buffer, "}\n");
4380     }
4381
4382     ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4383     checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4384     shader_glsl_compile(gl_info, ret, buffer->buffer);
4385
4386     return ret;
4387 }
4388
4389 static void shader_glsl_generate_srgb_write_correction(struct wined3d_shader_buffer *buffer)
4390 {
4391     shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4392     shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4393     shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4394     shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4395     shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4396     shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4397 }
4398
4399 static void shader_glsl_generate_fog_code(struct wined3d_shader_buffer *buffer, enum fogmode mode)
4400 {
4401     switch (mode)
4402     {
4403         case FOG_OFF:
4404             return;
4405
4406         case FOG_LINEAR:
4407             /* Fog = (gl_Fog.end - gl_FogFragCoord) / (gl_Fog.end - gl_Fog.start) */
4408             shader_addline(buffer, "float Fog = (gl_Fog.end - gl_FogFragCoord) / (gl_Fog.end - gl_Fog.start);\n");
4409             break;
4410
4411         case FOG_EXP:
4412             /* Fog = e^-(gl_Fog.density * gl_FogFragCoord) */
4413             shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4414             break;
4415
4416         case FOG_EXP2:
4417             /* Fog = e^-((gl_Fog.density * gl_FogFragCoord)^2) */
4418             shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4419             break;
4420
4421         default:
4422             ERR("Invalid fog mode %#x.\n", mode);
4423             return;
4424     }
4425
4426     shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, clamp(Fog, 0.0, 1.0));\n");
4427 }
4428
4429 /* GL locking is done by the caller */
4430 static void hardcode_local_constants(const struct wined3d_shader *shader,
4431         const struct wined3d_gl_info *gl_info, GLhandleARB programId, const char *prefix)
4432 {
4433     const struct wined3d_shader_lconst *lconst;
4434     GLint tmp_loc;
4435     const float *value;
4436     char glsl_name[10];
4437
4438     LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
4439     {
4440         value = (const float *)lconst->value;
4441         snprintf(glsl_name, sizeof(glsl_name), "%s_lc%u", prefix, lconst->idx);
4442         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4443         GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4444     }
4445     checkGLcall("Hardcoding local constants");
4446 }
4447
4448 /* GL locking is done by the caller */
4449 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4450         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4451         const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4452 {
4453     const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4454     const struct wined3d_gl_info *gl_info = context->gl_info;
4455     const DWORD *function = shader->function;
4456     struct shader_glsl_ctx_priv priv_ctx;
4457
4458     /* Create the hw GLSL shader object and assign it as the shader->prgId */
4459     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4460
4461     memset(&priv_ctx, 0, sizeof(priv_ctx));
4462     priv_ctx.cur_ps_args = args;
4463     priv_ctx.cur_np2fixup_info = np2fixup_info;
4464
4465     shader_addline(buffer, "#version 120\n");
4466
4467     if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4468         shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4469     if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
4470         shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4471     /* The spec says that it doesn't have to be explicitly enabled, but the
4472      * nvidia drivers write a warning if we don't do so. */
4473     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4474         shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4475     if (gl_info->supported[EXT_GPU_SHADER4])
4476         shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4477
4478     /* Base Declarations */
4479     shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4480
4481     /* Pack 3.0 inputs */
4482     if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4483         shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4484
4485     /* Base Shader Body */
4486     shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4487
4488     /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4489     if (reg_maps->shader_version.major < 2)
4490     {
4491         /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4492         shader_addline(buffer, "gl_FragData[0] = R0;\n");
4493     }
4494
4495     if (args->srgb_correction)
4496         shader_glsl_generate_srgb_write_correction(buffer);
4497
4498     /* SM < 3 does not replace the fog stage. */
4499     if (reg_maps->shader_version.major < 3)
4500         shader_glsl_generate_fog_code(buffer, args->fog);
4501
4502     shader_addline(buffer, "}\n");
4503
4504     TRACE("Compiling shader object %u\n", shader_obj);
4505     shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4506
4507     /* Store the shader object */
4508     return shader_obj;
4509 }
4510
4511 /* GL locking is done by the caller */
4512 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4513         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4514         const struct vs_compile_args *args)
4515 {
4516     const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4517     const struct wined3d_gl_info *gl_info = context->gl_info;
4518     const DWORD *function = shader->function;
4519     struct shader_glsl_ctx_priv priv_ctx;
4520
4521     /* Create the hw GLSL shader program and assign it as the shader->prgId */
4522     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4523
4524     shader_addline(buffer, "#version 120\n");
4525
4526     if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4527         shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4528     if (gl_info->supported[EXT_GPU_SHADER4])
4529         shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4530
4531     memset(&priv_ctx, 0, sizeof(priv_ctx));
4532     priv_ctx.cur_vs_args = args;
4533
4534     /* Base Declarations */
4535     shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4536
4537     /* Base Shader Body */
4538     shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4539
4540     /* Unpack outputs */
4541     shader_addline(buffer, "order_ps_input(vs_out);\n");
4542
4543     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4544      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4545      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4546      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4547      */
4548     if (args->fog_src == VS_FOG_Z)
4549         shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4550     else if (!reg_maps->fog)
4551         shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4552
4553     /* We always store the clipplanes without y inversion */
4554     if (args->clip_enabled)
4555         shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4556
4557     /* Write the final position.
4558      *
4559      * OpenGL coordinates specify the center of the pixel while d3d coords specify
4560      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4561      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4562      * contains 1.0 to allow a mad.
4563      */
4564     shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4565     shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4566
4567     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4568      *
4569      * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4570      * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4571      * which is the same as z = z * 2 - w.
4572      */
4573     shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4574
4575     shader_addline(buffer, "}\n");
4576
4577     TRACE("Compiling shader object %u\n", shader_obj);
4578     shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4579
4580     return shader_obj;
4581 }
4582
4583 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4584         struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4585         const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4586 {
4587     struct wined3d_state *state = &shader->device->stateBlock->state;
4588     struct glsl_ps_compiled_shader *gl_shaders, *new_array;
4589     struct glsl_shader_private *shader_data;
4590     struct ps_np2fixup_info *np2fixup;
4591     UINT i;
4592     DWORD new_size;
4593     GLhandleARB ret;
4594
4595     if (!shader->backend_data)
4596     {
4597         shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4598         if (!shader->backend_data)
4599         {
4600             ERR("Failed to allocate backend data.\n");
4601             return 0;
4602         }
4603     }
4604     shader_data = shader->backend_data;
4605     gl_shaders = shader_data->gl_shaders.ps;
4606
4607     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4608      * so a linear search is more performant than a hashmap or a binary search
4609      * (cache coherency etc)
4610      */
4611     for (i = 0; i < shader_data->num_gl_shaders; ++i)
4612     {
4613         if (!memcmp(&gl_shaders[i].args, args, sizeof(*args)))
4614         {
4615             if (args->np2_fixup)
4616                 *np2fixup_info = &gl_shaders[i].np2fixup;
4617             return gl_shaders[i].prgId;
4618         }
4619     }
4620
4621     TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4622     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4623         if (shader_data->num_gl_shaders)
4624         {
4625             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4626             new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.ps,
4627                     new_size * sizeof(*gl_shaders));
4628         }
4629         else
4630         {
4631             new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4632             new_size = 1;
4633         }
4634
4635         if(!new_array) {
4636             ERR("Out of memory\n");
4637             return 0;
4638         }
4639         shader_data->gl_shaders.ps = new_array;
4640         shader_data->shader_array_size = new_size;
4641         gl_shaders = new_array;
4642     }
4643
4644     gl_shaders[shader_data->num_gl_shaders].args = *args;
4645
4646     np2fixup = &gl_shaders[shader_data->num_gl_shaders].np2fixup;
4647     memset(np2fixup, 0, sizeof(*np2fixup));
4648     *np2fixup_info = args->np2_fixup ? np2fixup : NULL;
4649
4650     pixelshader_update_samplers(&shader->reg_maps, state->textures);
4651
4652     shader_buffer_clear(buffer);
4653     ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4654     gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4655
4656     return ret;
4657 }
4658
4659 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4660                                  const DWORD use_map) {
4661     if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4662     if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4663     return stored->fog_src == new->fog_src;
4664 }
4665
4666 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4667         struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4668         const struct vs_compile_args *args)
4669 {
4670     UINT i;
4671     DWORD new_size;
4672     DWORD use_map = shader->device->strided_streams.use_map;
4673     struct glsl_vs_compiled_shader *gl_shaders, *new_array;
4674     struct glsl_shader_private *shader_data;
4675     GLhandleARB ret;
4676
4677     if (!shader->backend_data)
4678     {
4679         shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4680         if (!shader->backend_data)
4681         {
4682             ERR("Failed to allocate backend data.\n");
4683             return 0;
4684         }
4685     }
4686     shader_data = shader->backend_data;
4687     gl_shaders = shader_data->gl_shaders.vs;
4688
4689     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4690      * so a linear search is more performant than a hashmap or a binary search
4691      * (cache coherency etc)
4692      */
4693     for (i = 0; i < shader_data->num_gl_shaders; ++i)
4694     {
4695         if (vs_args_equal(&gl_shaders[i].args, args, use_map))
4696             return gl_shaders[i].prgId;
4697     }
4698
4699     TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4700
4701     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4702         if (shader_data->num_gl_shaders)
4703         {
4704             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4705             new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.vs,
4706                     new_size * sizeof(*gl_shaders));
4707         }
4708         else
4709         {
4710             new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4711             new_size = 1;
4712         }
4713
4714         if(!new_array) {
4715             ERR("Out of memory\n");
4716             return 0;
4717         }
4718         shader_data->gl_shaders.vs = new_array;
4719         shader_data->shader_array_size = new_size;
4720         gl_shaders = new_array;
4721     }
4722
4723     gl_shaders[shader_data->num_gl_shaders].args = *args;
4724
4725     shader_buffer_clear(buffer);
4726     ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4727     gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4728
4729     return ret;
4730 }
4731
4732 static const char *shader_glsl_get_ffp_fragment_op_arg(struct wined3d_shader_buffer *buffer,
4733         DWORD argnum, unsigned int stage, DWORD arg)
4734 {
4735     const char *ret;
4736
4737     if (arg == ARG_UNUSED)
4738         return "<unused arg>";
4739
4740     switch (arg & WINED3DTA_SELECTMASK)
4741     {
4742         case WINED3DTA_DIFFUSE:
4743             ret = "gl_Color";
4744             break;
4745
4746         case WINED3DTA_CURRENT:
4747             if (!stage)
4748                 ret = "gl_Color";
4749             else
4750                 ret = "ret";
4751             break;
4752
4753         case WINED3DTA_TEXTURE:
4754             switch (stage)
4755             {
4756                 case 0: ret = "tex0"; break;
4757                 case 1: ret = "tex1"; break;
4758                 case 2: ret = "tex2"; break;
4759                 case 3: ret = "tex3"; break;
4760                 case 4: ret = "tex4"; break;
4761                 case 5: ret = "tex5"; break;
4762                 case 6: ret = "tex6"; break;
4763                 case 7: ret = "tex7"; break;
4764                 default:
4765                     ret = "<invalid texture>";
4766                     break;
4767             }
4768             break;
4769
4770         case WINED3DTA_TFACTOR:
4771             ret = "tex_factor";
4772             break;
4773
4774         case WINED3DTA_SPECULAR:
4775             ret = "gl_SecondaryColor";
4776             break;
4777
4778         case WINED3DTA_TEMP:
4779             ret = "temp_reg";
4780             break;
4781
4782         case WINED3DTA_CONSTANT:
4783             FIXME("Per-stage constants not implemented.\n");
4784             switch (stage)
4785             {
4786                 case 0: ret = "const0"; break;
4787                 case 1: ret = "const1"; break;
4788                 case 2: ret = "const2"; break;
4789                 case 3: ret = "const3"; break;
4790                 case 4: ret = "const4"; break;
4791                 case 5: ret = "const5"; break;
4792                 case 6: ret = "const6"; break;
4793                 case 7: ret = "const7"; break;
4794                 default:
4795                     ret = "<invalid constant>";
4796                     break;
4797             }
4798             break;
4799
4800         default:
4801             return "<unhandled arg>";
4802     }
4803
4804     if (arg & WINED3DTA_COMPLEMENT)
4805     {
4806         shader_addline(buffer, "arg%u = vec4(1.0) - %s;\n", argnum, ret);
4807         if (argnum == 0)
4808             ret = "arg0";
4809         else if (argnum == 1)
4810             ret = "arg1";
4811         else if (argnum == 2)
4812             ret = "arg2";
4813     }
4814
4815     if (arg & WINED3DTA_ALPHAREPLICATE)
4816     {
4817         shader_addline(buffer, "arg%u = vec4(%s.w);\n", argnum, ret);
4818         if (argnum == 0)
4819             ret = "arg0";
4820         else if (argnum == 1)
4821             ret = "arg1";
4822         else if (argnum == 2)
4823             ret = "arg2";
4824     }
4825
4826     return ret;
4827 }
4828
4829 static void shader_glsl_ffp_fragment_op(struct wined3d_shader_buffer *buffer, unsigned int stage, BOOL color,
4830         BOOL alpha, DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2)
4831 {
4832     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
4833
4834     if (color && alpha)
4835         dstmask = "";
4836     else if (color)
4837         dstmask = ".xyz";
4838     else
4839         dstmask = ".w";
4840
4841     if (dst == tempreg)
4842         dstreg = "temp_reg";
4843     else
4844         dstreg = "ret";
4845
4846     arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, dw_arg0);
4847     arg1 = shader_glsl_get_ffp_fragment_op_arg(buffer, 1, stage, dw_arg1);
4848     arg2 = shader_glsl_get_ffp_fragment_op_arg(buffer, 2, stage, dw_arg2);
4849
4850     switch (op)
4851     {
4852         case WINED3D_TOP_DISABLE:
4853             if (!stage)
4854                 shader_addline(buffer, "%s%s = gl_Color%s;\n", dstreg, dstmask, dstmask);
4855             break;
4856
4857         case WINED3D_TOP_SELECT_ARG1:
4858             shader_addline(buffer, "%s%s = %s%s;\n", dstreg, dstmask, arg1, dstmask);
4859             break;
4860
4861         case WINED3D_TOP_SELECT_ARG2:
4862             shader_addline(buffer, "%s%s = %s%s;\n", dstreg, dstmask, arg2, dstmask);
4863             break;
4864
4865         case WINED3D_TOP_MODULATE:
4866             shader_addline(buffer, "%s%s = %s%s * %s%s;\n", dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4867             break;
4868
4869         case WINED3D_TOP_MODULATE_4X:
4870             shader_addline(buffer, "%s%s = clamp(%s%s * %s%s * 4.0, 0.0, 1.0);\n",
4871                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4872             break;
4873
4874         case WINED3D_TOP_MODULATE_2X:
4875             shader_addline(buffer, "%s%s = clamp(%s%s * %s%s * 2.0, 0.0, 1.0);\n",
4876                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4877             break;
4878
4879         case WINED3D_TOP_ADD:
4880             shader_addline(buffer, "%s%s = clamp(%s%s + %s%s, 0.0, 1.0);\n",
4881                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4882             break;
4883
4884         case WINED3D_TOP_ADD_SIGNED:
4885             shader_addline(buffer, "%s%s = clamp(%s%s + (%s - vec4(0.5))%s, 0.0, 1.0);\n",
4886                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4887             break;
4888
4889         case WINED3D_TOP_ADD_SIGNED_2X:
4890             shader_addline(buffer, "%s%s = clamp((%s%s + (%s - vec4(0.5))%s) * 2.0, 0.0, 1.0);\n",
4891                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4892             break;
4893
4894         case WINED3D_TOP_SUBTRACT:
4895             shader_addline(buffer, "%s%s = clamp(%s%s - %s%s, 0.0, 1.0);\n",
4896                     dstreg, dstmask, arg1, dstmask, arg2, dstmask);
4897             break;
4898
4899         case WINED3D_TOP_ADD_SMOOTH:
4900             shader_addline(buffer, "%s%s = clamp((vec4(1.0) - %s)%s * %s%s + %s%s, 0.0, 1.0);\n",
4901                     dstreg, dstmask, arg1, dstmask, arg2, dstmask, arg1, dstmask);
4902             break;
4903
4904         case WINED3D_TOP_BLEND_DIFFUSE_ALPHA:
4905             arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, WINED3DTA_DIFFUSE);
4906             shader_addline(buffer, "%s%s = mix(%s%s, %s%s, %s.w);\n",
4907                     dstreg, dstmask, arg2, dstmask, arg1, dstmask, arg0);
4908             break;
4909
4910         case WINED3D_TOP_BLEND_TEXTURE_ALPHA:
4911             arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, WINED3DTA_TEXTURE);
4912             shader_addline(buffer, "%s%s = mix(%s%s, %s%s, %s.w);\n",
4913                     dstreg, dstmask, arg2, dstmask, arg1, dstmask, arg0);
4914             break;
4915
4916         case WINED3D_TOP_BLEND_FACTOR_ALPHA:
4917             arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, WINED3DTA_TFACTOR);
4918             shader_addline(buffer, "%s%s = mix(%s%s, %s%s, %s.w);\n",
4919                     dstreg, dstmask, arg2, dstmask, arg1, dstmask, arg0);
4920             break;
4921
4922         case WINED3D_TOP_BLEND_TEXTURE_ALPHA_PM:
4923             arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, WINED3DTA_TEXTURE);
4924             shader_addline(buffer, "%s%s = clamp(%s%s * (1.0 - %s.w) + %s%s, 0.0, 1.0);\n",
4925                     dstreg, dstmask, arg2, dstmask, arg0, arg1, dstmask);
4926             break;
4927
4928         case WINED3D_TOP_BLEND_CURRENT_ALPHA:
4929             arg0 = shader_glsl_get_ffp_fragment_op_arg(buffer, 0, stage, WINED3DTA_CURRENT);
4930             shader_addline(buffer, "%s%s = mix(%s%s, %s%s, %s.w);\n",
4931                     dstreg, dstmask, arg2, dstmask, arg1, dstmask, arg0);
4932             break;
4933
4934         case WINED3D_TOP_MODULATE_ALPHA_ADD_COLOR:
4935             shader_addline(buffer, "%s%s = clamp(%s%s * %s.w + %s%s, 0.0, 1.0);\n",
4936                     dstreg, dstmask, arg2, dstmask, arg1, arg1, dstmask);
4937             break;
4938
4939         case WINED3D_TOP_MODULATE_COLOR_ADD_ALPHA:
4940             shader_addline(buffer, "%s%s = clamp(%s%s * %s%s + %s.w, 0.0, 1.0);\n",
4941                     dstreg, dstmask, arg1, dstmask, arg2, dstmask, arg1);
4942             break;
4943
4944         case WINED3D_TOP_MODULATE_INVALPHA_ADD_COLOR:
4945             shader_addline(buffer, "%s%s = clamp(%s%s * (1.0 - %s.w) + %s%s, 0.0, 1.0);\n",
4946                     dstreg, dstmask, arg2, dstmask, arg1, arg1, dstmask);
4947             break;
4948         case WINED3D_TOP_MODULATE_INVCOLOR_ADD_ALPHA:
4949             shader_addline(buffer, "%s%s = clamp((vec4(1.0) - %s)%s * %s%s + %s.w, 0.0, 1.0);\n",
4950                     dstreg, dstmask, arg1, dstmask, arg2, dstmask, arg1);
4951             break;
4952
4953         case WINED3D_TOP_BUMPENVMAP:
4954         case WINED3D_TOP_BUMPENVMAP_LUMINANCE:
4955             /* These are handled in the first pass, nothing to do. */
4956             break;
4957
4958         case WINED3D_TOP_DOTPRODUCT3:
4959             shader_addline(buffer, "%s%s = vec4(clamp(dot(%s.xyz - 0.5, %s.xyz - 0.5) * 4.0, 0.0, 1.0))%s;\n",
4960                     dstreg, dstmask, arg1, arg2, dstmask);
4961             break;
4962
4963         case WINED3D_TOP_MULTIPLY_ADD:
4964             shader_addline(buffer, "%s%s = clamp(%s%s * %s%s + %s%s, 0.0, 1.0);\n",
4965                     dstreg, dstmask, arg1, dstmask, arg2, dstmask, arg0, dstmask);
4966             break;
4967
4968         case WINED3D_TOP_LERP:
4969             /* MSDN isn't quite right here. */
4970             shader_addline(buffer, "%s%s = mix(%s%s, %s%s, %s%s);\n",
4971                     dstreg, dstmask, arg2, dstmask, arg1, dstmask, arg0, dstmask);
4972             break;
4973
4974         default:
4975             FIXME("Unhandled operation %#x.\n", op);
4976             break;
4977     }
4978 }
4979
4980 /* Context activation is done by the caller. */
4981 static GLuint shader_glsl_generate_ffp_fragment_shader(struct wined3d_shader_buffer *buffer,
4982         const struct ffp_frag_settings *settings, const struct wined3d_gl_info *gl_info)
4983 {
4984     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
4985     BYTE lum_map = 0, bump_map = 0, tex_map = 0;
4986     const char *final_combiner_src = "ret";
4987     UINT lowest_disabled_stage;
4988     GLhandleARB shader_obj;
4989     DWORD arg0, arg1, arg2;
4990     unsigned int stage;
4991
4992     shader_buffer_clear(buffer);
4993
4994     /* Find out which textures are read */
4995     for (stage = 0; stage < MAX_TEXTURES; ++stage)
4996     {
4997         if (settings->op[stage].cop == WINED3D_TOP_DISABLE)
4998             break;
4999
5000         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
5001         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
5002         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
5003
5004         if (arg0 == WINED3DTA_TEXTURE || arg1 == WINED3DTA_TEXTURE || arg2 == WINED3DTA_TEXTURE)
5005             tex_map |= 1 << stage;
5006         if (arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR)
5007             tfactor_used = TRUE;
5008         if (arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP)
5009             tempreg_used = TRUE;
5010         if (settings->op[stage].dst == tempreg)
5011             tempreg_used = TRUE;
5012
5013         switch (settings->op[stage].cop)
5014         {
5015             case WINED3D_TOP_BUMPENVMAP_LUMINANCE:
5016                 lum_map |= 1 << stage;
5017             case WINED3D_TOP_BUMPENVMAP:
5018                 bump_map |= 1 << stage;
5019             case WINED3D_TOP_BLEND_TEXTURE_ALPHA:
5020             case WINED3D_TOP_BLEND_TEXTURE_ALPHA_PM:
5021                 tex_map |= 1 << stage;
5022                 break;
5023
5024             case WINED3D_TOP_BLEND_FACTOR_ALPHA:
5025                 tfactor_used = TRUE;
5026                 break;
5027
5028             default:
5029                 break;
5030         }
5031
5032         if (settings->op[stage].aop == WINED3D_TOP_DISABLE)
5033             continue;
5034
5035         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
5036         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
5037         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
5038
5039         if (arg0 == WINED3DTA_TEXTURE || arg1 == WINED3DTA_TEXTURE || arg2 == WINED3DTA_TEXTURE)
5040             tex_map |= 1 << stage;
5041         if (arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR)
5042             tfactor_used = TRUE;
5043         if (arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP)
5044             tempreg_used = TRUE;
5045     }
5046     lowest_disabled_stage = stage;
5047
5048     shader_addline(buffer, "#version 120\n");
5049
5050     shader_addline(buffer, "vec4 tmp0, tmp1;\n");
5051     shader_addline(buffer, "vec4 ret;\n");
5052     if (tempreg_used || settings->sRGB_write)
5053         shader_addline(buffer, "vec4 temp_reg;\n");
5054     shader_addline(buffer, "vec4 arg0, arg1, arg2;\n");
5055
5056     for (stage = 0; stage < MAX_TEXTURES; ++stage)
5057     {
5058         if (!(tex_map & (1 << stage)))
5059             continue;
5060
5061         switch (settings->op[stage].tex_type)
5062         {
5063             case tex_1d:
5064                 shader_addline(buffer, "uniform sampler1D ps_sampler%u;\n", stage);
5065                 break;
5066             case tex_2d:
5067                 shader_addline(buffer, "uniform sampler2D ps_sampler%u;\n", stage);
5068                 break;
5069             case tex_3d:
5070                 shader_addline(buffer, "uniform sampler3D ps_sampler%u;\n", stage);
5071                 break;
5072             case tex_cube:
5073                 shader_addline(buffer, "uniform samplerCube ps_sampler%u;\n", stage);
5074                 break;
5075             case tex_rect:
5076                 shader_addline(buffer, "uniform sampler2DRect ps_sampler%u;\n", stage);
5077                 break;
5078             default:
5079                 FIXME("Unhandled sampler type %#x.\n", settings->op[stage].tex_type);
5080                 break;
5081         }
5082
5083         shader_addline(buffer, "vec4 tex%u;\n", stage);
5084
5085         if (!(bump_map & (1 << stage)))
5086             continue;
5087         shader_addline(buffer, "uniform mat2 bumpenv_mat%u;\n", stage);
5088
5089         if (!(lum_map & (1 << stage)))
5090             continue;
5091         shader_addline(buffer, "uniform float bumpenv_lum_scale%u;\n", stage);
5092         shader_addline(buffer, "uniform float bumpenv_lum_offset%u;\n", stage);
5093     }
5094     if (tfactor_used)
5095         shader_addline(buffer, "uniform vec4 tex_factor;\n");
5096     shader_addline(buffer, "uniform vec4 specular_enable;\n");
5097
5098     if (settings->sRGB_write)
5099     {
5100         shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
5101                 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
5102         shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
5103                 srgb_cmp);
5104     }
5105
5106     shader_addline(buffer, "void main()\n{\n");
5107
5108     if (lowest_disabled_stage < 7 && settings->emul_clipplanes)
5109         shader_addline(buffer, "if (any(lessThan(gl_texCoord[7], vec4(0.0)))) discard;\n");
5110
5111     /* Generate texture sampling instructions) */
5112     for (stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3D_TOP_DISABLE; ++stage)
5113     {
5114         const char *texture_function, *coord_mask;
5115         char tex_reg_name[8];
5116         BOOL proj, clamp;
5117
5118         if (!(tex_map & (1 << stage)))
5119             continue;
5120
5121         if (settings->op[stage].projected == proj_none)
5122         {
5123             proj = FALSE;
5124         }
5125         else if (settings->op[stage].projected == proj_count4
5126                 || settings->op[stage].projected == proj_count3)
5127         {
5128             proj = TRUE;
5129         }
5130         else
5131         {
5132             FIXME("Unexpected projection mode %d\n", settings->op[stage].projected);
5133             proj = TRUE;
5134         }
5135
5136         if (settings->op[stage].cop == WINED3D_TOP_BUMPENVMAP
5137                 || settings->op[stage].cop == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
5138             clamp = FALSE;
5139         else
5140             clamp = TRUE;
5141
5142         switch (settings->op[stage].tex_type)
5143         {
5144             case tex_1d:
5145                 if (proj)
5146                 {
5147                     texture_function = "texture1DProj";
5148                     coord_mask = "xw";
5149                 }
5150                 else
5151                 {
5152                     texture_function = "texture1D";
5153                     coord_mask = "x";
5154                 }
5155                 break;
5156             case tex_2d:
5157                 if (proj)
5158                 {
5159                     texture_function = "texture2DProj";
5160                     coord_mask = "xyw";
5161                 }
5162                 else
5163                 {
5164                     texture_function = "texture2D";
5165                     coord_mask = "xy";
5166                 }
5167                 break;
5168             case tex_3d:
5169                 if (proj)
5170                 {
5171                     texture_function = "texture3DProj";
5172                     coord_mask = "xyzw";
5173                 }
5174                 else
5175                 {
5176                     texture_function = "texture3D";
5177                     coord_mask = "xyz";
5178                 }
5179                 break;
5180             case tex_cube:
5181                 texture_function = "textureCube";
5182                 coord_mask = "xyz";
5183                 break;
5184             case tex_rect:
5185                 if (proj)
5186                 {
5187                     texture_function = "texture2DRectProj";
5188                     coord_mask = "xyw";
5189                 }
5190                 else
5191                 {
5192                     texture_function = "texture2DRect";
5193                     coord_mask = "xy";
5194                 }
5195                 break;
5196             default:
5197                 FIXME("Unhandled texture type %#x.\n", settings->op[stage].tex_type);
5198                 texture_function = "";
5199                 coord_mask = "xyzw";
5200                 break;
5201         }
5202
5203         if (stage > 0
5204                 && (settings->op[stage - 1].cop == WINED3D_TOP_BUMPENVMAP
5205                 || settings->op[stage - 1].cop == WINED3D_TOP_BUMPENVMAP_LUMINANCE))
5206         {
5207             shader_addline(buffer, "ret.xy = bumpenv_mat%u * tex%u.xy;\n", stage - 1, stage - 1);
5208
5209             /* With projective textures, texbem only divides the static
5210              * texture coord, not the displacement, so multiply the
5211              * displacement with the dividing parameter before passing it to
5212              * TXP. */
5213             if (settings->op[stage].projected != proj_none)
5214             {
5215                 if (settings->op[stage].projected == proj_count4)
5216                 {
5217                     shader_addline(buffer, "ret.xy = (ret.xy * gl_TexCoord[%u].w) + gl_TexCoord[%u].xy;\n",
5218                             stage, stage);
5219                     shader_addline(buffer, "ret.zw = gl_TexCoord[%u].ww;\n", stage);
5220                 }
5221                 else
5222                 {
5223                     shader_addline(buffer, "ret.xy = (ret.xy * gl_TexCoord[%u].z) + gl_TexCoord[%u].xy;\n",
5224                             stage, stage);
5225                     shader_addline(buffer, "ret.zw = gl_TexCoord[%u].zz;\n", stage);
5226                 }
5227             }
5228             else
5229             {
5230                 shader_addline(buffer, "ret = gl_TexCoord[%u] + ret.xyxy;\n", stage);
5231             }
5232
5233             if (clamp)
5234                 shader_addline(buffer, "tex%u = clamp(%s(ps_sampler%u, ret.%s), 0.0, 1.0);\n",
5235                         stage, texture_function, stage, coord_mask);
5236             else
5237                 shader_addline(buffer, "tex%u = %s(ps_sampler%u, ret.%s);\n",
5238                         stage, texture_function, stage, coord_mask);
5239
5240             if (settings->op[stage - 1].cop == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
5241                 shader_addline(buffer, "tex%u *= clamp(tex%u.z * bumpenv_lum_scale%u + bumpenv_lum_offset%u, 0.0, 1.0);\n",
5242                         stage, stage - 1, stage - 1, stage - 1);
5243         }
5244         else if (settings->op[stage].projected == proj_count3)
5245         {
5246             if (clamp)
5247                 shader_addline(buffer, "tex%u = clamp(%s(ps_sampler%u, gl_TexCoord[%u].xyz), 0.0, 1.0);\n",
5248                         stage, texture_function, stage, stage);
5249             else
5250                 shader_addline(buffer, "tex%u = %s(ps_sampler%u, gl_TexCoord[%u].xyz);\n",
5251                         stage, texture_function, stage, stage);
5252         }
5253         else
5254         {
5255             if (clamp)
5256                 shader_addline(buffer, "tex%u = clamp(%s(ps_sampler%u, gl_TexCoord[%u].%s), 0.0, 1.0);\n",
5257                         stage, texture_function, stage, stage, coord_mask);
5258             else
5259                 shader_addline(buffer, "tex%u = %s(ps_sampler%u, gl_TexCoord[%u].%s);\n",
5260                         stage, texture_function, stage, stage, coord_mask);
5261         }
5262
5263         sprintf(tex_reg_name, "tex%u", stage);
5264         shader_glsl_color_correction_ext(buffer, tex_reg_name, WINED3DSP_WRITEMASK_ALL,
5265                 settings->op[stage].color_fixup);
5266     }
5267
5268     /* Generate the main shader */
5269     for (stage = 0; stage < MAX_TEXTURES; ++stage)
5270     {
5271         BOOL op_equal;
5272
5273         if (settings->op[stage].cop == WINED3D_TOP_DISABLE)
5274         {
5275             if (!stage)
5276                 final_combiner_src = "gl_Color";
5277             break;
5278         }
5279
5280         if (settings->op[stage].cop == WINED3D_TOP_SELECT_ARG1
5281                 && settings->op[stage].aop == WINED3D_TOP_SELECT_ARG1)
5282             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg1;
5283         else if (settings->op[stage].cop == WINED3D_TOP_SELECT_ARG1
5284                 && settings->op[stage].aop == WINED3D_TOP_SELECT_ARG2)
5285             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg2;
5286         else if (settings->op[stage].cop == WINED3D_TOP_SELECT_ARG2
5287                 && settings->op[stage].aop == WINED3D_TOP_SELECT_ARG1)
5288             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg1;
5289         else if (settings->op[stage].cop == WINED3D_TOP_SELECT_ARG2
5290                 && settings->op[stage].aop == WINED3D_TOP_SELECT_ARG2)
5291             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg2;
5292         else
5293             op_equal = settings->op[stage].aop == settings->op[stage].cop
5294                     && settings->op[stage].carg0 == settings->op[stage].aarg0
5295                     && settings->op[stage].carg1 == settings->op[stage].aarg1
5296                     && settings->op[stage].carg2 == settings->op[stage].aarg2;
5297
5298         if (settings->op[stage].aop == WINED3D_TOP_DISABLE)
5299         {
5300             shader_glsl_ffp_fragment_op(buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5301                     settings->op[stage].cop, settings->op[stage].carg0,
5302                     settings->op[stage].carg1, settings->op[stage].carg2);
5303             if (!stage)
5304                 shader_addline(buffer, "ret.w = gl_Color.w;\n");
5305         }
5306         else if (op_equal)
5307         {
5308             shader_glsl_ffp_fragment_op(buffer, stage, TRUE, TRUE, settings->op[stage].dst,
5309                     settings->op[stage].cop, settings->op[stage].carg0,
5310                     settings->op[stage].carg1, settings->op[stage].carg2);
5311         }
5312         else
5313         {
5314             shader_glsl_ffp_fragment_op(buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5315                     settings->op[stage].cop, settings->op[stage].carg0,
5316                     settings->op[stage].carg1, settings->op[stage].carg2);
5317             shader_glsl_ffp_fragment_op(buffer, stage, FALSE, TRUE, settings->op[stage].dst,
5318                     settings->op[stage].aop, settings->op[stage].aarg0,
5319                     settings->op[stage].aarg1, settings->op[stage].aarg2);
5320         }
5321     }
5322
5323     shader_addline(buffer, "gl_FragData[0] = gl_SecondaryColor * specular_enable + %s;\n", final_combiner_src);
5324
5325     if (settings->sRGB_write)
5326         shader_glsl_generate_srgb_write_correction(buffer);
5327
5328     shader_glsl_generate_fog_code(buffer, settings->fog);
5329
5330     shader_addline(buffer, "}\n");
5331
5332     shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
5333     shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
5334     return shader_obj;
5335 }
5336
5337 static struct glsl_ffp_fragment_shader *shader_glsl_find_ffp_fragment_shader(struct shader_glsl_priv *priv,
5338         const struct wined3d_gl_info *gl_info, const struct ffp_frag_settings *args)
5339 {
5340     struct glsl_ffp_fragment_shader *glsl_desc;
5341     const struct ffp_frag_desc *desc;
5342
5343     if ((desc = find_ffp_frag_shader(&priv->ffp_fragment_shaders, args)))
5344         return CONTAINING_RECORD(desc, struct glsl_ffp_fragment_shader, entry);
5345
5346     if (!(glsl_desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*glsl_desc))))
5347     {
5348         ERR("Failed to allocate ffp desc memory.\n");
5349         return NULL;
5350     }
5351
5352     glsl_desc->entry.settings = *args;
5353     glsl_desc->id = shader_glsl_generate_ffp_fragment_shader(&priv->shader_buffer, args, gl_info);
5354     list_init(&glsl_desc->linked_programs);
5355     add_ffp_frag_shader(&priv->ffp_fragment_shaders, &glsl_desc->entry);
5356
5357     return glsl_desc;
5358 }
5359
5360
5361 static void shader_glsl_init_vs_uniform_locations(const struct wined3d_gl_info *gl_info,
5362         GLhandleARB program_id, struct glsl_vs_program *vs)
5363 {
5364     unsigned int i;
5365     char name[32];
5366
5367     vs->uniform_f_locations = HeapAlloc(GetProcessHeap(), 0,
5368             sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
5369     for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
5370     {
5371         snprintf(name, sizeof(name), "vs_c[%u]", i);
5372         vs->uniform_f_locations[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5373     }
5374
5375     for (i = 0; i < MAX_CONST_I; ++i)
5376     {
5377         snprintf(name, sizeof(name), "vs_i[%u]", i);
5378         vs->uniform_i_locations[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5379     }
5380
5381     vs->pos_fixup_location = GL_EXTCALL(glGetUniformLocationARB(program_id, "posFixup"));
5382 }
5383
5384 static void shader_glsl_init_ps_uniform_locations(const struct wined3d_gl_info *gl_info,
5385         GLhandleARB program_id, struct glsl_ps_program *ps)
5386 {
5387     unsigned int i;
5388     char name[32];
5389
5390     ps->uniform_f_locations = HeapAlloc(GetProcessHeap(), 0,
5391             sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
5392     for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
5393     {
5394         snprintf(name, sizeof(name), "ps_c[%u]", i);
5395         ps->uniform_f_locations[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5396     }
5397
5398     for (i = 0; i < MAX_CONST_I; ++i)
5399     {
5400         snprintf(name, sizeof(name), "ps_i[%u]", i);
5401         ps->uniform_i_locations[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5402     }
5403
5404     for (i = 0; i < MAX_TEXTURES; ++i)
5405     {
5406         snprintf(name, sizeof(name), "bumpenv_mat%u", i);
5407         ps->bumpenv_mat_location[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5408         snprintf(name, sizeof(name), "bumpenv_lum_scale%u", i);
5409         ps->bumpenv_lum_scale_location[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5410         snprintf(name, sizeof(name), "bumpenv_lum_offset%u", i);
5411         ps->bumpenv_lum_offset_location[i] = GL_EXTCALL(glGetUniformLocationARB(program_id, name));
5412     }
5413
5414     ps->tex_factor_location = GL_EXTCALL(glGetUniformLocationARB(program_id, "tex_factor"));
5415     ps->specular_enable_location = GL_EXTCALL(glGetUniformLocationARB(program_id, "specular_enable"));
5416     ps->np2_fixup_location = GL_EXTCALL(glGetUniformLocationARB(program_id, "ps_samplerNP2Fixup"));
5417     ps->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(program_id, "ycorrection"));
5418 }
5419
5420 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
5421  * It sets the programId on the current StateBlock (because it should be called
5422  * inside of the DrawPrimitive() part of the render loop).
5423  *
5424  * If a program for the given combination does not exist, create one, and store
5425  * the program in the hash table.  If it creates a program, it will link the
5426  * given objects, too.
5427  */
5428
5429 /* GL locking is done by the caller */
5430 static void set_glsl_shader_program(const struct wined3d_context *context, struct wined3d_device *device,
5431         enum wined3d_shader_mode vertex_mode, enum wined3d_shader_mode fragment_mode)
5432 {
5433     const struct wined3d_state *state = &device->stateBlock->state;
5434     const struct wined3d_gl_info *gl_info = context->gl_info;
5435     const struct ps_np2fixup_info *np2fixup_info = NULL;
5436     struct shader_glsl_priv *priv = device->shader_priv;
5437     struct glsl_shader_prog_link *entry = NULL;
5438     struct wined3d_shader *vshader = NULL;
5439     struct wined3d_shader *pshader = NULL;
5440     GLhandleARB programId                  = 0;
5441     GLhandleARB reorder_shader_id          = 0;
5442     unsigned int i;
5443     struct ps_compile_args ps_compile_args;
5444     struct vs_compile_args vs_compile_args;
5445     GLhandleARB vs_id, ps_id;
5446     struct list *ps_list;
5447
5448     if (vertex_mode == WINED3D_SHADER_MODE_SHADER)
5449     {
5450         vshader = state->vertex_shader;
5451         find_vs_compile_args(state, vshader, &vs_compile_args);
5452         vs_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
5453     }
5454     else
5455     {
5456         vs_id = 0;
5457     }
5458
5459     if (fragment_mode == WINED3D_SHADER_MODE_SHADER)
5460     {
5461         pshader = state->pixel_shader;
5462         find_ps_compile_args(state, pshader, &ps_compile_args);
5463         ps_id = find_glsl_pshader(context, &priv->shader_buffer,
5464                 pshader, &ps_compile_args, &np2fixup_info);
5465         ps_list = &pshader->linked_programs;
5466     }
5467     else if (fragment_mode == WINED3D_SHADER_MODE_FFP && priv->fragment_pipe == &glsl_fragment_pipe)
5468     {
5469         struct glsl_ffp_fragment_shader *ffp_shader;
5470         struct ffp_frag_settings settings;
5471
5472         gen_ffp_frag_op(device, state, &settings, FALSE);
5473         ffp_shader = shader_glsl_find_ffp_fragment_shader(priv, gl_info, &settings);
5474         ps_id = ffp_shader->id;
5475         ps_list = &ffp_shader->linked_programs;
5476     }
5477     else
5478     {
5479         ps_id = 0;
5480     }
5481
5482     if ((!vs_id && !ps_id) || (entry = get_glsl_program_entry(priv, vs_id, ps_id)))
5483     {
5484         priv->glsl_program = entry;
5485         return;
5486     }
5487
5488     /* If we get to this point, then no matching program exists, so we create one */
5489     programId = GL_EXTCALL(glCreateProgramObjectARB());
5490     TRACE("Created new GLSL shader program %u\n", programId);
5491
5492     /* Create the entry */
5493     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
5494     entry->programId = programId;
5495     entry->vs.id = vs_id;
5496     entry->ps.id = ps_id;
5497     entry->constant_version = 0;
5498     entry->ps.np2_fixup_info = np2fixup_info;
5499     /* Add the hash table entry */
5500     add_glsl_program_entry(priv, entry);
5501
5502     /* Set the current program */
5503     priv->glsl_program = entry;
5504
5505     /* Attach GLSL vshader */
5506     if (vshader)
5507     {
5508         WORD map = vshader->reg_maps.input_registers;
5509         char tmp_name[10];
5510
5511         reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
5512         TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
5513         GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
5514         checkGLcall("glAttachObjectARB");
5515         /* Flag the reorder function for deletion, then it will be freed automatically when the program
5516          * is destroyed
5517          */
5518         GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
5519
5520         TRACE("Attaching GLSL shader object %u to program %u.\n", vs_id, programId);
5521         GL_EXTCALL(glAttachObjectARB(programId, vs_id));
5522         checkGLcall("glAttachObjectARB");
5523
5524         /* Bind vertex attributes to a corresponding index number to match
5525          * the same index numbers as ARB_vertex_programs (makes loading
5526          * vertex attributes simpler).  With this method, we can use the
5527          * exact same code to load the attributes later for both ARB and
5528          * GLSL shaders.
5529          *
5530          * We have to do this here because we need to know the Program ID
5531          * in order to make the bindings work, and it has to be done prior
5532          * to linking the GLSL program. */
5533         for (i = 0; map; map >>= 1, ++i)
5534         {
5535             if (!(map & 1)) continue;
5536
5537             snprintf(tmp_name, sizeof(tmp_name), "vs_in%u", i);
5538             GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
5539         }
5540         checkGLcall("glBindAttribLocationARB");
5541
5542         list_add_head(&vshader->linked_programs, &entry->vs.shader_entry);
5543     }
5544
5545     /* Attach GLSL pshader */
5546     if (ps_id)
5547     {
5548         TRACE("Attaching GLSL shader object %u to program %u.\n", ps_id, programId);
5549         GL_EXTCALL(glAttachObjectARB(programId, ps_id));
5550         checkGLcall("glAttachObjectARB");
5551
5552         list_add_head(ps_list, &entry->ps.shader_entry);
5553     }
5554
5555     /* Link the program */
5556     TRACE("Linking GLSL shader program %u\n", programId);
5557     GL_EXTCALL(glLinkProgramARB(programId));
5558     shader_glsl_validate_link(gl_info, programId);
5559
5560     shader_glsl_init_vs_uniform_locations(gl_info, programId, &entry->vs);
5561     shader_glsl_init_ps_uniform_locations(gl_info, programId, &entry->ps);
5562     checkGLcall("Find glsl program uniform locations");
5563
5564     if (pshader && pshader->reg_maps.shader_version.major >= 3
5565             && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
5566     {
5567         TRACE("Shader %d needs vertex color clamping disabled\n", programId);
5568         entry->vs.vertex_color_clamp = GL_FALSE;
5569     }
5570     else
5571     {
5572         entry->vs.vertex_color_clamp = GL_FIXED_ONLY_ARB;
5573     }
5574
5575     /* Set the shader to allow uniform loading on it */
5576     GL_EXTCALL(glUseProgramObjectARB(programId));
5577     checkGLcall("glUseProgramObjectARB(programId)");
5578
5579     /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
5580      * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
5581      * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
5582      * vertex shader with fixed function pixel processing is used we make sure that the card
5583      * supports enough samplers to allow the max number of vertex samplers with all possible
5584      * fixed function fragment processing setups. So once the program is linked these samplers
5585      * won't change.
5586      */
5587     shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
5588     shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
5589
5590     /* If the local constants do not have to be loaded with the environment constants,
5591      * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
5592      * later
5593      */
5594     if (pshader && !pshader->load_local_constsF)
5595         hardcode_local_constants(pshader, gl_info, programId, "ps");
5596     if (vshader && !vshader->load_local_constsF)
5597         hardcode_local_constants(vshader, gl_info, programId, "vs");
5598 }
5599
5600 /* GL locking is done by the caller */
5601 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
5602 {
5603     GLhandleARB program_id;
5604     GLhandleARB vshader_id, pshader_id;
5605     const char *blt_pshader;
5606
5607     static const char *blt_vshader =
5608         "#version 120\n"
5609         "void main(void)\n"
5610         "{\n"
5611         "    gl_Position = gl_Vertex;\n"
5612         "    gl_FrontColor = vec4(1.0);\n"
5613         "    gl_TexCoord[0] = gl_MultiTexCoord0;\n"
5614         "}\n";
5615
5616     static const char * const blt_pshaders_full[tex_type_count] =
5617     {
5618         /* tex_1d */
5619         NULL,
5620         /* tex_2d */
5621         "#version 120\n"
5622         "uniform sampler2D sampler;\n"
5623         "void main(void)\n"
5624         "{\n"
5625         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
5626         "}\n",
5627         /* tex_3d */
5628         NULL,
5629         /* tex_cube */
5630         "#version 120\n"
5631         "uniform samplerCube sampler;\n"
5632         "void main(void)\n"
5633         "{\n"
5634         "    gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
5635         "}\n",
5636         /* tex_rect */
5637         "#version 120\n"
5638         "#extension GL_ARB_texture_rectangle : enable\n"
5639         "uniform sampler2DRect sampler;\n"
5640         "void main(void)\n"
5641         "{\n"
5642         "    gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
5643         "}\n",
5644     };
5645
5646     static const char * const blt_pshaders_masked[tex_type_count] =
5647     {
5648         /* tex_1d */
5649         NULL,
5650         /* tex_2d */
5651         "#version 120\n"
5652         "uniform sampler2D sampler;\n"
5653         "uniform vec4 mask;\n"
5654         "void main(void)\n"
5655         "{\n"
5656         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
5657         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
5658         "}\n",
5659         /* tex_3d */
5660         NULL,
5661         /* tex_cube */
5662         "#version 120\n"
5663         "uniform samplerCube sampler;\n"
5664         "uniform vec4 mask;\n"
5665         "void main(void)\n"
5666         "{\n"
5667         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
5668         "    gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
5669         "}\n",
5670         /* tex_rect */
5671         "#version 120\n"
5672         "#extension GL_ARB_texture_rectangle : enable\n"
5673         "uniform sampler2DRect sampler;\n"
5674         "uniform vec4 mask;\n"
5675         "void main(void)\n"
5676         "{\n"
5677         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
5678         "    gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
5679         "}\n",
5680     };
5681
5682     blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
5683     if (!blt_pshader)
5684     {
5685         FIXME("tex_type %#x not supported\n", tex_type);
5686         return 0;
5687     }
5688
5689     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
5690     shader_glsl_compile(gl_info, vshader_id, blt_vshader);
5691
5692     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
5693     shader_glsl_compile(gl_info, pshader_id, blt_pshader);
5694
5695     program_id = GL_EXTCALL(glCreateProgramObjectARB());
5696     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
5697     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
5698     GL_EXTCALL(glLinkProgramARB(program_id));
5699
5700     shader_glsl_validate_link(gl_info, program_id);
5701
5702     /* Once linked we can mark the shaders for deletion. They will be deleted once the program
5703      * is destroyed
5704      */
5705     GL_EXTCALL(glDeleteObjectARB(vshader_id));
5706     GL_EXTCALL(glDeleteObjectARB(pshader_id));
5707     return program_id;
5708 }
5709
5710 /* GL locking is done by the caller */
5711 static void shader_glsl_select(const struct wined3d_context *context, enum wined3d_shader_mode vertex_mode,
5712         enum wined3d_shader_mode fragment_mode)
5713 {
5714     const struct wined3d_gl_info *gl_info = context->gl_info;
5715     struct wined3d_device *device = context->swapchain->device;
5716     struct shader_glsl_priv *priv = device->shader_priv;
5717     GLhandleARB program_id = 0;
5718     GLenum old_vertex_color_clamp, current_vertex_color_clamp;
5719
5720     old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vs.vertex_color_clamp : GL_FIXED_ONLY_ARB;
5721     set_glsl_shader_program(context, device, vertex_mode, fragment_mode);
5722     current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vs.vertex_color_clamp : GL_FIXED_ONLY_ARB;
5723     if (old_vertex_color_clamp != current_vertex_color_clamp)
5724     {
5725         if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
5726         {
5727             GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
5728             checkGLcall("glClampColorARB");
5729         }
5730         else
5731         {
5732             FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
5733         }
5734     }
5735
5736     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5737     if (program_id) TRACE("Using GLSL program %u\n", program_id);
5738     GL_EXTCALL(glUseProgramObjectARB(program_id));
5739     checkGLcall("glUseProgramObjectARB");
5740
5741     /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
5742      * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
5743      * called between selecting the shader and using it, which results in wrong fixup for some frames. */
5744     if (priv->glsl_program && priv->glsl_program->ps.np2_fixup_info)
5745     {
5746         shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
5747     }
5748 }
5749
5750 /* GL locking is done by the caller */
5751 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
5752         enum tex_types tex_type, const SIZE *ds_mask_size)
5753 {
5754     BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
5755     struct shader_glsl_priv *priv = shader_priv;
5756     GLhandleARB *blt_program;
5757     GLint loc;
5758
5759     blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
5760     if (!*blt_program)
5761     {
5762         *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
5763         loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
5764         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5765         GL_EXTCALL(glUniform1iARB(loc, 0));
5766     }
5767     else
5768     {
5769         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5770     }
5771
5772     if (masked)
5773     {
5774         loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
5775         GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
5776     }
5777 }
5778
5779 /* GL locking is done by the caller */
5780 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
5781 {
5782     struct shader_glsl_priv *priv = shader_priv;
5783     GLhandleARB program_id;
5784
5785     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5786     if (program_id) TRACE("Using GLSL program %u\n", program_id);
5787
5788     GL_EXTCALL(glUseProgramObjectARB(program_id));
5789     checkGLcall("glUseProgramObjectARB");
5790 }
5791
5792 static void shader_glsl_destroy(struct wined3d_shader *shader)
5793 {
5794     struct glsl_shader_private *shader_data = shader->backend_data;
5795     struct wined3d_device *device = shader->device;
5796     struct shader_glsl_priv *priv = device->shader_priv;
5797     const struct wined3d_gl_info *gl_info;
5798     const struct list *linked_programs;
5799     struct wined3d_context *context;
5800
5801     if (!shader_data || !shader_data->num_gl_shaders)
5802     {
5803         HeapFree(GetProcessHeap(), 0, shader_data);
5804         shader->backend_data = NULL;
5805         return;
5806     }
5807
5808     context = context_acquire(device, NULL);
5809     gl_info = context->gl_info;
5810
5811     TRACE("Deleting linked programs.\n");
5812     linked_programs = &shader->linked_programs;
5813     if (linked_programs->next)
5814     {
5815         struct glsl_shader_prog_link *entry, *entry2;
5816         UINT i;
5817
5818         ENTER_GL();
5819
5820         switch (shader->reg_maps.shader_version.type)
5821         {
5822             case WINED3D_SHADER_TYPE_PIXEL:
5823             {
5824                 struct glsl_ps_compiled_shader *gl_shaders = shader_data->gl_shaders.ps;
5825
5826                 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
5827                         struct glsl_shader_prog_link, ps.shader_entry)
5828                 {
5829                     delete_glsl_program_entry(priv, gl_info, entry);
5830                 }
5831
5832                 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5833                 {
5834                     TRACE("Deleting pixel shader %u.\n", gl_shaders[i].prgId);
5835                     if (priv->glsl_program && priv->glsl_program->ps.id == gl_shaders[i].prgId)
5836                         shader_glsl_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
5837                     GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5838                     checkGLcall("glDeleteObjectARB");
5839                 }
5840                 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.ps);
5841
5842                 break;
5843             }
5844
5845             case WINED3D_SHADER_TYPE_VERTEX:
5846             {
5847                 struct glsl_vs_compiled_shader *gl_shaders = shader_data->gl_shaders.vs;
5848
5849                 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
5850                         struct glsl_shader_prog_link, vs.shader_entry)
5851                 {
5852                     delete_glsl_program_entry(priv, gl_info, entry);
5853                 }
5854
5855                 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5856                 {
5857                     TRACE("Deleting vertex shader %u.\n", gl_shaders[i].prgId);
5858                     if (priv->glsl_program && priv->glsl_program->vs.id == gl_shaders[i].prgId)
5859                         shader_glsl_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
5860                     GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5861                     checkGLcall("glDeleteObjectARB");
5862                 }
5863                 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.vs);
5864
5865                 break;
5866             }
5867
5868             default:
5869                 ERR("Unhandled shader type %#x.\n", shader->reg_maps.shader_version.type);
5870                 break;
5871         }
5872
5873         LEAVE_GL();
5874     }
5875
5876     HeapFree(GetProcessHeap(), 0, shader->backend_data);
5877     shader->backend_data = NULL;
5878
5879     context_release(context);
5880 }
5881
5882 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
5883 {
5884     const struct glsl_program_key *k = key;
5885     const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
5886             const struct glsl_shader_prog_link, program_lookup_entry);
5887
5888     if (k->vs_id > prog->vs.id) return 1;
5889     else if (k->vs_id < prog->vs.id) return -1;
5890
5891     if (k->ps_id > prog->ps.id) return 1;
5892     else if (k->ps_id < prog->ps.id) return -1;
5893
5894     return 0;
5895 }
5896
5897 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
5898 {
5899     SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5900     void *mem = HeapAlloc(GetProcessHeap(), 0, size);
5901
5902     if (!mem)
5903     {
5904         ERR("Failed to allocate memory\n");
5905         return FALSE;
5906     }
5907
5908     heap->entries = mem;
5909     heap->entries[1].version = 0;
5910     heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
5911     heap->size = 1;
5912
5913     return TRUE;
5914 }
5915
5916 static void constant_heap_free(struct constant_heap *heap)
5917 {
5918     HeapFree(GetProcessHeap(), 0, heap->entries);
5919 }
5920
5921 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
5922 {
5923     wined3d_rb_alloc,
5924     wined3d_rb_realloc,
5925     wined3d_rb_free,
5926     glsl_program_key_compare,
5927 };
5928
5929 static HRESULT shader_glsl_alloc(struct wined3d_device *device, const struct fragment_pipeline *fragment_pipe)
5930 {
5931     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5932     struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
5933     SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
5934             gl_info->limits.glsl_ps_float_constants)) + 1;
5935     void *fragment_priv;
5936
5937     if (!(fragment_priv = fragment_pipe->alloc_private(&glsl_shader_backend, priv)))
5938     {
5939         ERR("Failed to initialize fragment pipe.\n");
5940         HeapFree(GetProcessHeap(), 0, priv);
5941         return E_FAIL;
5942     }
5943
5944     if (!shader_buffer_init(&priv->shader_buffer))
5945     {
5946         ERR("Failed to initialize shader buffer.\n");
5947         goto fail;
5948     }
5949
5950     priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
5951     if (!priv->stack)
5952     {
5953         ERR("Failed to allocate memory.\n");
5954         goto fail;
5955     }
5956
5957     if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
5958     {
5959         ERR("Failed to initialize vertex shader constant heap\n");
5960         goto fail;
5961     }
5962
5963     if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
5964     {
5965         ERR("Failed to initialize pixel shader constant heap\n");
5966         goto fail;
5967     }
5968
5969     if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
5970     {
5971         ERR("Failed to initialize rbtree.\n");
5972         goto fail;
5973     }
5974
5975     priv->next_constant_version = 1;
5976     device->fragment_priv = fragment_priv;
5977     priv->fragment_pipe = fragment_pipe;
5978
5979     device->shader_priv = priv;
5980     return WINED3D_OK;
5981
5982 fail:
5983     constant_heap_free(&priv->pconst_heap);
5984     constant_heap_free(&priv->vconst_heap);
5985     HeapFree(GetProcessHeap(), 0, priv->stack);
5986     shader_buffer_free(&priv->shader_buffer);
5987     fragment_pipe->free_private(device);
5988     HeapFree(GetProcessHeap(), 0, priv);
5989     return E_OUTOFMEMORY;
5990 }
5991
5992 /* Context activation is done by the caller. */
5993 static void shader_glsl_free(struct wined3d_device *device)
5994 {
5995     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5996     struct shader_glsl_priv *priv = device->shader_priv;
5997     int i;
5998
5999     ENTER_GL();
6000     for (i = 0; i < tex_type_count; ++i)
6001     {
6002         if (priv->depth_blt_program_full[i])
6003         {
6004             GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
6005         }
6006         if (priv->depth_blt_program_masked[i])
6007         {
6008             GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
6009         }
6010     }
6011     LEAVE_GL();
6012
6013     wine_rb_destroy(&priv->program_lookup, NULL, NULL);
6014     constant_heap_free(&priv->pconst_heap);
6015     constant_heap_free(&priv->vconst_heap);
6016     HeapFree(GetProcessHeap(), 0, priv->stack);
6017     shader_buffer_free(&priv->shader_buffer);
6018     priv->fragment_pipe->free_private(device);
6019
6020     HeapFree(GetProcessHeap(), 0, device->shader_priv);
6021     device->shader_priv = NULL;
6022 }
6023
6024 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
6025
6026 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
6027 {
6028     UINT shader_model;
6029
6030     if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_SHADER_BIT_ENCODING]
6031             && gl_info->supported[ARB_GEOMETRY_SHADER4] && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
6032         shader_model = 4;
6033     /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
6034      * texldd and texldl instructions. */
6035     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
6036         shader_model = 3;
6037     else
6038         shader_model = 2;
6039     TRACE("Shader model %u.\n", shader_model);
6040
6041     caps->vs_version = shader_model;
6042     caps->gs_version = shader_model;
6043     caps->ps_version = shader_model;
6044
6045     caps->vs_uniform_count = gl_info->limits.glsl_vs_float_constants;
6046     caps->ps_uniform_count = gl_info->limits.glsl_ps_float_constants;
6047
6048     /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
6049      * Direct3D minimum requirement.
6050      *
6051      * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
6052      * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
6053      *
6054      * The problem is that the refrast clamps temporary results in the shader to
6055      * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
6056      * then applications may miss the clamping behavior. On the other hand, if it is smaller,
6057      * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
6058      * offer a way to query this.
6059      */
6060     caps->ps_1x_max_value = 8.0;
6061
6062     caps->vs_clipping = TRUE;
6063 }
6064
6065 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
6066 {
6067     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
6068     {
6069         TRACE("Checking support for fixup:\n");
6070         dump_color_fixup_desc(fixup);
6071     }
6072
6073     /* We support everything except YUV conversions. */
6074     if (!is_complex_fixup(fixup))
6075     {
6076         TRACE("[OK]\n");
6077         return TRUE;
6078     }
6079
6080     TRACE("[FAILED]\n");
6081     return FALSE;
6082 }
6083
6084 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
6085 {
6086     /* WINED3DSIH_ABS                   */ shader_glsl_map2gl,
6087     /* WINED3DSIH_ADD                   */ shader_glsl_binop,
6088     /* WINED3DSIH_AND                   */ shader_glsl_binop,
6089     /* WINED3DSIH_BEM                   */ shader_glsl_bem,
6090     /* WINED3DSIH_BREAK                 */ shader_glsl_break,
6091     /* WINED3DSIH_BREAKC                */ shader_glsl_breakc,
6092     /* WINED3DSIH_BREAKP                */ shader_glsl_breakp,
6093     /* WINED3DSIH_CALL                  */ shader_glsl_call,
6094     /* WINED3DSIH_CALLNZ                */ shader_glsl_callnz,
6095     /* WINED3DSIH_CMP                   */ shader_glsl_conditional_move,
6096     /* WINED3DSIH_CND                   */ shader_glsl_cnd,
6097     /* WINED3DSIH_CRS                   */ shader_glsl_cross,
6098     /* WINED3DSIH_CUT                   */ shader_glsl_cut,
6099     /* WINED3DSIH_DCL                   */ shader_glsl_nop,
6100     /* WINED3DSIH_DCL_CONSTANT_BUFFER   */ shader_glsl_nop,
6101     /* WINED3DSIH_DCL_INPUT_PRIMITIVE   */ shader_glsl_nop,
6102     /* WINED3DSIH_DCL_OUTPUT_TOPOLOGY   */ shader_glsl_nop,
6103     /* WINED3DSIH_DCL_VERTICES_OUT      */ shader_glsl_nop,
6104     /* WINED3DSIH_DEF                   */ shader_glsl_nop,
6105     /* WINED3DSIH_DEFB                  */ shader_glsl_nop,
6106     /* WINED3DSIH_DEFI                  */ shader_glsl_nop,
6107     /* WINED3DSIH_DIV                   */ shader_glsl_binop,
6108     /* WINED3DSIH_DP2ADD                */ shader_glsl_dp2add,
6109     /* WINED3DSIH_DP3                   */ shader_glsl_dot,
6110     /* WINED3DSIH_DP4                   */ shader_glsl_dot,
6111     /* WINED3DSIH_DST                   */ shader_glsl_dst,
6112     /* WINED3DSIH_DSX                   */ shader_glsl_map2gl,
6113     /* WINED3DSIH_DSY                   */ shader_glsl_map2gl,
6114     /* WINED3DSIH_ELSE                  */ shader_glsl_else,
6115     /* WINED3DSIH_EMIT                  */ shader_glsl_emit,
6116     /* WINED3DSIH_ENDIF                 */ shader_glsl_end,
6117     /* WINED3DSIH_ENDLOOP               */ shader_glsl_end,
6118     /* WINED3DSIH_ENDREP                */ shader_glsl_end,
6119     /* WINED3DSIH_EQ                    */ shader_glsl_relop,
6120     /* WINED3DSIH_EXP                   */ shader_glsl_map2gl,
6121     /* WINED3DSIH_EXPP                  */ shader_glsl_expp,
6122     /* WINED3DSIH_FRC                   */ shader_glsl_map2gl,
6123     /* WINED3DSIH_FTOI                  */ shader_glsl_to_int,
6124     /* WINED3DSIH_GE                    */ shader_glsl_relop,
6125     /* WINED3DSIH_IADD                  */ shader_glsl_binop,
6126     /* WINED3DSIH_IEQ                   */ NULL,
6127     /* WINED3DSIH_IF                    */ shader_glsl_if,
6128     /* WINED3DSIH_IFC                   */ shader_glsl_ifc,
6129     /* WINED3DSIH_IGE                   */ shader_glsl_relop,
6130     /* WINED3DSIH_IMUL                  */ shader_glsl_imul,
6131     /* WINED3DSIH_ITOF                  */ shader_glsl_to_float,
6132     /* WINED3DSIH_LABEL                 */ shader_glsl_label,
6133     /* WINED3DSIH_LD                    */ NULL,
6134     /* WINED3DSIH_LIT                   */ shader_glsl_lit,
6135     /* WINED3DSIH_LOG                   */ shader_glsl_log,
6136     /* WINED3DSIH_LOGP                  */ shader_glsl_log,
6137     /* WINED3DSIH_LOOP                  */ shader_glsl_loop,
6138     /* WINED3DSIH_LRP                   */ shader_glsl_lrp,
6139     /* WINED3DSIH_LT                    */ shader_glsl_relop,
6140     /* WINED3DSIH_M3x2                  */ shader_glsl_mnxn,
6141     /* WINED3DSIH_M3x3                  */ shader_glsl_mnxn,
6142     /* WINED3DSIH_M3x4                  */ shader_glsl_mnxn,
6143     /* WINED3DSIH_M4x3                  */ shader_glsl_mnxn,
6144     /* WINED3DSIH_M4x4                  */ shader_glsl_mnxn,
6145     /* WINED3DSIH_MAD                   */ shader_glsl_mad,
6146     /* WINED3DSIH_MAX                   */ shader_glsl_map2gl,
6147     /* WINED3DSIH_MIN                   */ shader_glsl_map2gl,
6148     /* WINED3DSIH_MOV                   */ shader_glsl_mov,
6149     /* WINED3DSIH_MOVA                  */ shader_glsl_mov,
6150     /* WINED3DSIH_MOVC                  */ shader_glsl_conditional_move,
6151     /* WINED3DSIH_MUL                   */ shader_glsl_binop,
6152     /* WINED3DSIH_NOP                   */ shader_glsl_nop,
6153     /* WINED3DSIH_NRM                   */ shader_glsl_nrm,
6154     /* WINED3DSIH_PHASE                 */ shader_glsl_nop,
6155     /* WINED3DSIH_POW                   */ shader_glsl_pow,
6156     /* WINED3DSIH_RCP                   */ shader_glsl_rcp,
6157     /* WINED3DSIH_REP                   */ shader_glsl_rep,
6158     /* WINED3DSIH_RET                   */ shader_glsl_ret,
6159     /* WINED3DSIH_ROUND_NI              */ shader_glsl_map2gl,
6160     /* WINED3DSIH_RSQ                   */ shader_glsl_rsq,
6161     /* WINED3DSIH_SAMPLE                */ NULL,
6162     /* WINED3DSIH_SAMPLE_GRAD           */ NULL,
6163     /* WINED3DSIH_SAMPLE_LOD            */ NULL,
6164     /* WINED3DSIH_SETP                  */ NULL,
6165     /* WINED3DSIH_SGE                   */ shader_glsl_compare,
6166     /* WINED3DSIH_SGN                   */ shader_glsl_sgn,
6167     /* WINED3DSIH_SINCOS                */ shader_glsl_sincos,
6168     /* WINED3DSIH_SLT                   */ shader_glsl_compare,
6169     /* WINED3DSIH_SQRT                  */ NULL,
6170     /* WINED3DSIH_SUB                   */ shader_glsl_binop,
6171     /* WINED3DSIH_TEX                   */ shader_glsl_tex,
6172     /* WINED3DSIH_TEXBEM                */ shader_glsl_texbem,
6173     /* WINED3DSIH_TEXBEML               */ shader_glsl_texbem,
6174     /* WINED3DSIH_TEXCOORD              */ shader_glsl_texcoord,
6175     /* WINED3DSIH_TEXDEPTH              */ shader_glsl_texdepth,
6176     /* WINED3DSIH_TEXDP3                */ shader_glsl_texdp3,
6177     /* WINED3DSIH_TEXDP3TEX             */ shader_glsl_texdp3tex,
6178     /* WINED3DSIH_TEXKILL               */ shader_glsl_texkill,
6179     /* WINED3DSIH_TEXLDD                */ shader_glsl_texldd,
6180     /* WINED3DSIH_TEXLDL                */ shader_glsl_texldl,
6181     /* WINED3DSIH_TEXM3x2DEPTH          */ shader_glsl_texm3x2depth,
6182     /* WINED3DSIH_TEXM3x2PAD            */ shader_glsl_texm3x2pad,
6183     /* WINED3DSIH_TEXM3x2TEX            */ shader_glsl_texm3x2tex,
6184     /* WINED3DSIH_TEXM3x3               */ shader_glsl_texm3x3,
6185     /* WINED3DSIH_TEXM3x3DIFF           */ NULL,
6186     /* WINED3DSIH_TEXM3x3PAD            */ shader_glsl_texm3x3pad,
6187     /* WINED3DSIH_TEXM3x3SPEC           */ shader_glsl_texm3x3spec,
6188     /* WINED3DSIH_TEXM3x3TEX            */ shader_glsl_texm3x3tex,
6189     /* WINED3DSIH_TEXM3x3VSPEC          */ shader_glsl_texm3x3vspec,
6190     /* WINED3DSIH_TEXREG2AR             */ shader_glsl_texreg2ar,
6191     /* WINED3DSIH_TEXREG2GB             */ shader_glsl_texreg2gb,
6192     /* WINED3DSIH_TEXREG2RGB            */ shader_glsl_texreg2rgb,
6193     /* WINED3DSIH_UDIV                  */ shader_glsl_udiv,
6194     /* WINED3DSIH_USHR                  */ shader_glsl_binop,
6195     /* WINED3DSIH_UTOF                  */ shader_glsl_to_float,
6196     /* WINED3DSIH_XOR                   */ shader_glsl_binop,
6197 };
6198
6199 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
6200     SHADER_HANDLER hw_fct;
6201
6202     /* Select handler */
6203     hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
6204
6205     /* Unhandled opcode */
6206     if (!hw_fct)
6207     {
6208         FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
6209         return;
6210     }
6211     hw_fct(ins);
6212
6213     shader_glsl_add_instruction_modifiers(ins);
6214 }
6215
6216 static BOOL shader_glsl_has_ffp_proj_control(void *shader_priv)
6217 {
6218     struct shader_glsl_priv *priv = shader_priv;
6219
6220     return priv->fragment_pipe->ffp_proj_control;
6221 }
6222
6223 const struct wined3d_shader_backend_ops glsl_shader_backend =
6224 {
6225     shader_glsl_handle_instruction,
6226     shader_glsl_select,
6227     shader_glsl_select_depth_blt,
6228     shader_glsl_deselect_depth_blt,
6229     shader_glsl_update_float_vertex_constants,
6230     shader_glsl_update_float_pixel_constants,
6231     shader_glsl_load_constants,
6232     shader_glsl_load_np2fixup_constants,
6233     shader_glsl_destroy,
6234     shader_glsl_alloc,
6235     shader_glsl_free,
6236     shader_glsl_context_destroyed,
6237     shader_glsl_get_caps,
6238     shader_glsl_color_fixup_supported,
6239     shader_glsl_has_ffp_proj_control,
6240 };
6241
6242 static void glsl_fragment_pipe_enable(const struct wined3d_gl_info *gl_info, BOOL enable)
6243 {
6244     /* Nothing to do. */
6245 }
6246
6247 static void glsl_fragment_pipe_get_caps(const struct wined3d_gl_info *gl_info, struct fragment_caps *caps)
6248 {
6249     caps->PrimitiveMiscCaps = WINED3DPMISCCAPS_TSSARGTEMP;
6250     caps->TextureOpCaps = WINED3DTEXOPCAPS_DISABLE
6251             | WINED3DTEXOPCAPS_SELECTARG1
6252             | WINED3DTEXOPCAPS_SELECTARG2
6253             | WINED3DTEXOPCAPS_MODULATE4X
6254             | WINED3DTEXOPCAPS_MODULATE2X
6255             | WINED3DTEXOPCAPS_MODULATE
6256             | WINED3DTEXOPCAPS_ADDSIGNED2X
6257             | WINED3DTEXOPCAPS_ADDSIGNED
6258             | WINED3DTEXOPCAPS_ADD
6259             | WINED3DTEXOPCAPS_SUBTRACT
6260             | WINED3DTEXOPCAPS_ADDSMOOTH
6261             | WINED3DTEXOPCAPS_BLENDCURRENTALPHA
6262             | WINED3DTEXOPCAPS_BLENDFACTORALPHA
6263             | WINED3DTEXOPCAPS_BLENDTEXTUREALPHA
6264             | WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA
6265             | WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM
6266             | WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
6267             | WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
6268             | WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
6269             | WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
6270             | WINED3DTEXOPCAPS_DOTPRODUCT3
6271             | WINED3DTEXOPCAPS_MULTIPLYADD
6272             | WINED3DTEXOPCAPS_LERP
6273             | WINED3DTEXOPCAPS_BUMPENVMAP
6274             | WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE;
6275     caps->MaxTextureBlendStages = 8;
6276     caps->MaxSimultaneousTextures = min(gl_info->limits.fragment_samplers, 8);
6277 }
6278
6279 static void *glsl_fragment_pipe_alloc(const struct wined3d_shader_backend_ops *shader_backend, void *shader_priv)
6280 {
6281     struct shader_glsl_priv *priv;
6282
6283     if (shader_backend == &glsl_shader_backend)
6284     {
6285         priv = shader_priv;
6286
6287         if (wine_rb_init(&priv->ffp_fragment_shaders, &wined3d_ffp_frag_program_rb_functions) == -1)
6288         {
6289             ERR("Failed to initialize rbtree.\n");
6290             return NULL;
6291         }
6292
6293         return priv;
6294     }
6295
6296     FIXME("GLSL fragment pipe without GLSL shader backend not implemented.\n");
6297
6298     return NULL;
6299 }
6300
6301 struct glsl_ffp_destroy_ctx
6302 {
6303     struct shader_glsl_priv *priv;
6304     const struct wined3d_gl_info *gl_info;
6305 };
6306
6307 static void shader_glsl_free_ffp_fragment_shader(struct wine_rb_entry *entry, void *context)
6308 {
6309     struct glsl_ffp_fragment_shader *shader = WINE_RB_ENTRY_VALUE(entry,
6310             struct glsl_ffp_fragment_shader, entry.entry);
6311     struct glsl_shader_prog_link *program, *program2;
6312     struct glsl_ffp_destroy_ctx *ctx = context;
6313
6314     LIST_FOR_EACH_ENTRY_SAFE(program, program2, &shader->linked_programs,
6315             struct glsl_shader_prog_link, ps.shader_entry)
6316     {
6317         delete_glsl_program_entry(ctx->priv, ctx->gl_info, program);
6318     }
6319     ctx->gl_info->gl_ops.ext.p_glDeleteObjectARB(shader->id);
6320     HeapFree(GetProcessHeap(), 0, shader);
6321 }
6322
6323 /* Context activation is done by the caller. */
6324 static void glsl_fragment_pipe_free(struct wined3d_device *device)
6325 {
6326     struct shader_glsl_priv *priv = device->fragment_priv;
6327     struct glsl_ffp_destroy_ctx ctx;
6328
6329     ctx.priv = priv;
6330     ctx.gl_info = &device->adapter->gl_info;
6331     wine_rb_destroy(&priv->ffp_fragment_shaders, shader_glsl_free_ffp_fragment_shader, &ctx);
6332 }
6333
6334 static void glsl_fragment_pipe_shader(struct wined3d_context *context,
6335         const struct wined3d_state *state, DWORD state_id)
6336 {
6337     context->last_was_pshader = use_ps(state);
6338
6339     context->select_shader = 1;
6340     context->load_constants = 1;
6341 }
6342
6343 static void glsl_fragment_pipe_fog(struct wined3d_context *context,
6344         const struct wined3d_state *state, DWORD state_id)
6345 {
6346     BOOL use_vshader = use_vs(state);
6347     enum fogsource new_source;
6348
6349     context->select_shader = 1;
6350     context->load_constants = 1;
6351
6352     if (!state->render_states[WINED3D_RS_FOGENABLE])
6353         return;
6354
6355     if (state->render_states[WINED3D_RS_FOGTABLEMODE] == WINED3D_FOG_NONE)
6356     {
6357         if (use_vshader)
6358             new_source = FOGSOURCE_VS;
6359         else if (state->render_states[WINED3D_RS_FOGVERTEXMODE] == WINED3D_FOG_NONE || context->last_was_rhw)
6360             new_source = FOGSOURCE_COORD;
6361         else
6362             new_source = FOGSOURCE_FFP;
6363     }
6364     else
6365     {
6366         new_source = FOGSOURCE_FFP;
6367     }
6368
6369     if (new_source != context->fog_source)
6370     {
6371         context->fog_source = new_source;
6372         state_fogstartend(context, state, STATE_RENDER(WINED3D_RS_FOGSTART));
6373     }
6374 }
6375
6376 static void glsl_fragment_pipe_tex_transform(struct wined3d_context *context,
6377         const struct wined3d_state *state, DWORD state_id)
6378 {
6379     context->select_shader = 1;
6380     context->load_constants = 1;
6381 }
6382
6383 static void glsl_fragment_pipe_invalidate_constants(struct wined3d_context *context,
6384         const struct wined3d_state *state, DWORD state_id)
6385 {
6386     context->load_constants = 1;
6387 }
6388
6389 static const struct StateEntryTemplate glsl_fragment_pipe_state_template[] =
6390 {
6391     {STATE_RENDER(WINED3D_RS_TEXTUREFACTOR),                    {STATE_RENDER(WINED3D_RS_TEXTUREFACTOR),                     glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6392     {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6393     {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6394     {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6395     {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6396     {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6397     {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6398     {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6399     {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6400     {STATE_TEXTURESTAGE(0, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6401     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6402     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6403     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6404     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6405     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6406     {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6407     {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6408     {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6409     {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6410     {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6411     {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6412     {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6413     {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6414     {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6415     {STATE_TEXTURESTAGE(1, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6416     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6417     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6418     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6419     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6420     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6421     {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6422     {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6423     {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6424     {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6425     {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6426     {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6427     {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6428     {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6429     {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6430     {STATE_TEXTURESTAGE(2, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6431     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6432     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6433     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6434     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6435     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6436     {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6437     {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6438     {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6439     {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6440     {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6441     {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6442     {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6443     {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6444     {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6445     {STATE_TEXTURESTAGE(3, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6446     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6447     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6448     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6449     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6450     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6451     {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6452     {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6453     {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6454     {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6455     {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6456     {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6457     {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6458     {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6459     {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6460     {STATE_TEXTURESTAGE(4, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6461     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6462     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6463     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6464     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6465     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6466     {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6467     {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6468     {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6469     {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6470     {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6471     {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6472     {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6473     {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6474     {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6475     {STATE_TEXTURESTAGE(5, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6476     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6477     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6478     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6479     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6480     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6481     {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6482     {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6483     {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6484     {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6485     {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6486     {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6487     {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6488     {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6489     {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6490     {STATE_TEXTURESTAGE(6, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6491     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6492     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6493     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6494     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6495     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6496     {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6497     {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6498     {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6499     {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6500     {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6501     {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_OP),               {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6502     {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG1),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6503     {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG2),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6504     {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG0),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6505     {STATE_TEXTURESTAGE(7, WINED3D_TSS_RESULT_ARG),             {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6506     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00),          {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00),           glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6507     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT01),          {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6508     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT10),          {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6509     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT11),          {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00),           NULL                                   }, WINED3D_GL_EXT_NONE },
6510     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_LSCALE),         {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_LSCALE),          glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6511     {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_LOFFSET),        {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_LSCALE),          NULL                                   }, WINED3D_GL_EXT_NONE },
6512     {STATE_PIXELSHADER,                                         {STATE_PIXELSHADER,                                          glsl_fragment_pipe_shader              }, WINED3D_GL_EXT_NONE },
6513     {STATE_RENDER(WINED3D_RS_FOGENABLE),                        {STATE_RENDER(WINED3D_RS_FOGENABLE),                         glsl_fragment_pipe_fog                 }, WINED3D_GL_EXT_NONE },
6514     {STATE_RENDER(WINED3D_RS_FOGTABLEMODE),                     {STATE_RENDER(WINED3D_RS_FOGENABLE),                         NULL                                   }, WINED3D_GL_EXT_NONE },
6515     {STATE_RENDER(WINED3D_RS_FOGVERTEXMODE),                    {STATE_RENDER(WINED3D_RS_FOGENABLE),                         NULL                                   }, WINED3D_GL_EXT_NONE },
6516     {STATE_RENDER(WINED3D_RS_FOGSTART),                         {STATE_RENDER(WINED3D_RS_FOGSTART),                          state_fogstartend                      }, WINED3D_GL_EXT_NONE },
6517     {STATE_RENDER(WINED3D_RS_FOGEND),                           {STATE_RENDER(WINED3D_RS_FOGSTART),                          NULL                                   }, WINED3D_GL_EXT_NONE },
6518     {STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE),                  {STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE),                   state_srgbwrite                        }, ARB_FRAMEBUFFER_SRGB},
6519     {STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE),                  {STATE_PIXELSHADER,                                          NULL                                   }, WINED3D_GL_EXT_NONE },
6520     {STATE_RENDER(WINED3D_RS_FOGCOLOR),                         {STATE_RENDER(WINED3D_RS_FOGCOLOR),                          state_fogcolor                         }, WINED3D_GL_EXT_NONE },
6521     {STATE_RENDER(WINED3D_RS_FOGDENSITY),                       {STATE_RENDER(WINED3D_RS_FOGDENSITY),                        state_fogdensity                       }, WINED3D_GL_EXT_NONE },
6522     {STATE_TEXTURESTAGE(0,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(0, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6523     {STATE_TEXTURESTAGE(1,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(1, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6524     {STATE_TEXTURESTAGE(2,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(2, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6525     {STATE_TEXTURESTAGE(3,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(3, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6526     {STATE_TEXTURESTAGE(4,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(4, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6527     {STATE_TEXTURESTAGE(5,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(5, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6528     {STATE_TEXTURESTAGE(6,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(6, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6529     {STATE_TEXTURESTAGE(7,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(7, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), glsl_fragment_pipe_tex_transform       }, WINED3D_GL_EXT_NONE },
6530     {STATE_RENDER(WINED3D_RS_SPECULARENABLE),                   {STATE_RENDER(WINED3D_RS_SPECULARENABLE),                    glsl_fragment_pipe_invalidate_constants}, WINED3D_GL_EXT_NONE },
6531     {0 /* Terminate */,                                         {0,                                                          0                                      }, WINED3D_GL_EXT_NONE },
6532 };
6533
6534 const struct fragment_pipeline glsl_fragment_pipe =
6535 {
6536     glsl_fragment_pipe_enable,
6537     glsl_fragment_pipe_get_caps,
6538     glsl_fragment_pipe_alloc,
6539     glsl_fragment_pipe_free,
6540     shader_glsl_color_fixup_supported,
6541     glsl_fragment_pipe_state_template,
6542     TRUE,
6543 };