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