wined3d: Get rid of the WINED3DSAMPLER_TEXTURE_TYPE typedef.
[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 <limits.h>
34 #include <stdio.h>
35 #include "wined3d_private.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
41
42 #define WINED3D_GLSL_SAMPLE_PROJECTED   0x1
43 #define WINED3D_GLSL_SAMPLE_RECT        0x2
44 #define WINED3D_GLSL_SAMPLE_LOD         0x4
45 #define WINED3D_GLSL_SAMPLE_GRAD        0x8
46
47 struct glsl_dst_param
48 {
49     char reg_name[150];
50     char mask_str[6];
51 };
52
53 struct glsl_src_param
54 {
55     char reg_name[150];
56     char param_str[200];
57 };
58
59 struct glsl_sample_function
60 {
61     const char *name;
62     DWORD coord_mask;
63 };
64
65 enum heap_node_op
66 {
67     HEAP_NODE_TRAVERSE_LEFT,
68     HEAP_NODE_TRAVERSE_RIGHT,
69     HEAP_NODE_POP,
70 };
71
72 struct constant_entry
73 {
74     unsigned int idx;
75     unsigned int version;
76 };
77
78 struct constant_heap
79 {
80     struct constant_entry *entries;
81     unsigned int *positions;
82     unsigned int size;
83 };
84
85 /* GLSL shader private data */
86 struct shader_glsl_priv {
87     struct wined3d_shader_buffer shader_buffer;
88     struct wine_rb_tree program_lookup;
89     struct glsl_shader_prog_link *glsl_program;
90     struct constant_heap vconst_heap;
91     struct constant_heap pconst_heap;
92     unsigned char *stack;
93     GLhandleARB depth_blt_program_full[tex_type_count];
94     GLhandleARB depth_blt_program_masked[tex_type_count];
95     UINT next_constant_version;
96 };
97
98 /* Struct to maintain data about a linked GLSL program */
99 struct glsl_shader_prog_link {
100     struct wine_rb_entry        program_lookup_entry;
101     struct list                 vshader_entry;
102     struct list                 pshader_entry;
103     GLhandleARB                 programId;
104     GLint                       *vuniformF_locations;
105     GLint                       *puniformF_locations;
106     GLint                       vuniformI_locations[MAX_CONST_I];
107     GLint                       puniformI_locations[MAX_CONST_I];
108     GLint                       posFixup_location;
109     GLint                       np2Fixup_location;
110     GLint                       bumpenvmat_location[MAX_TEXTURES];
111     GLint                       luminancescale_location[MAX_TEXTURES];
112     GLint                       luminanceoffset_location[MAX_TEXTURES];
113     GLint                       ycorrection_location;
114     GLenum                      vertex_color_clamp;
115     const struct wined3d_shader *vshader;
116     const struct wined3d_shader *pshader;
117     struct vs_compile_args      vs_args;
118     struct ps_compile_args      ps_args;
119     UINT                        constant_version;
120     const struct ps_np2fixup_info *np2Fixup_info;
121 };
122
123 struct glsl_program_key
124 {
125     const struct wined3d_shader *vshader;
126     const struct wined3d_shader *pshader;
127     struct ps_compile_args      ps_args;
128     struct vs_compile_args      vs_args;
129 };
130
131 struct shader_glsl_ctx_priv {
132     const struct vs_compile_args    *cur_vs_args;
133     const struct ps_compile_args    *cur_ps_args;
134     struct ps_np2fixup_info         *cur_np2fixup_info;
135 };
136
137 struct glsl_ps_compiled_shader
138 {
139     struct ps_compile_args          args;
140     struct ps_np2fixup_info         np2fixup;
141     GLhandleARB                     prgId;
142 };
143
144 struct glsl_pshader_private
145 {
146     struct glsl_ps_compiled_shader  *gl_shaders;
147     UINT                            num_gl_shaders, shader_array_size;
148 };
149
150 struct glsl_vs_compiled_shader
151 {
152     struct vs_compile_args          args;
153     GLhandleARB                     prgId;
154 };
155
156 struct glsl_vshader_private
157 {
158     struct glsl_vs_compiled_shader  *gl_shaders;
159     UINT                            num_gl_shaders, shader_array_size;
160 };
161
162 static const char *debug_gl_shader_type(GLenum type)
163 {
164     switch (type)
165     {
166 #define WINED3D_TO_STR(u) case u: return #u
167         WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
168         WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
169         WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
170 #undef WINED3D_TO_STR
171         default:
172             return wine_dbg_sprintf("UNKNOWN(%#x)", type);
173     }
174 }
175
176 /* Extract a line from the info log.
177  * Note that this modifies the source string. */
178 static char *get_info_log_line(char **ptr)
179 {
180     char *p, *q;
181
182     p = *ptr;
183     if (!(q = strstr(p, "\n")))
184     {
185         if (!*p) return NULL;
186         *ptr += strlen(p);
187         return p;
188     }
189     *q = '\0';
190     *ptr = q + 1;
191
192     return p;
193 }
194
195 /** Prints the GLSL info log which will contain error messages if they exist */
196 /* GL locking is done by the caller */
197 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
198 {
199     int infologLength = 0;
200     char *infoLog;
201
202     if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
203         return;
204
205     GL_EXTCALL(glGetObjectParameterivARB(obj,
206                GL_OBJECT_INFO_LOG_LENGTH_ARB,
207                &infologLength));
208
209     /* A size of 1 is just a null-terminated string, so the log should be bigger than
210      * that if there are errors. */
211     if (infologLength > 1)
212     {
213         char *ptr, *line;
214
215         infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
216         /* The info log is supposed to be zero-terminated, but at least some
217          * versions of fglrx don't terminate the string properly. The reported
218          * length does include the terminator, so explicitly set it to zero
219          * here. */
220         infoLog[infologLength - 1] = 0;
221         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
222
223         ptr = infoLog;
224         if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
225         {
226             WARN("Info log received from GLSL shader #%u:\n", obj);
227             while ((line = get_info_log_line(&ptr))) WARN("    %s\n", line);
228         }
229         else
230         {
231             FIXME("Info log received from GLSL shader #%u:\n", obj);
232             while ((line = get_info_log_line(&ptr))) FIXME("    %s\n", line);
233         }
234         HeapFree(GetProcessHeap(), 0, infoLog);
235     }
236 }
237
238 /* GL locking is done by the caller. */
239 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
240 {
241     TRACE("Compiling shader object %u.\n", shader);
242     GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
243     checkGLcall("glShaderSourceARB");
244     GL_EXTCALL(glCompileShaderARB(shader));
245     checkGLcall("glCompileShaderARB");
246     print_glsl_info_log(gl_info, shader);
247 }
248
249 /* GL locking is done by the caller. */
250 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
251 {
252     GLint i, object_count, source_size = -1;
253     GLhandleARB *objects;
254     char *source = NULL;
255
256     GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
257     objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
258     if (!objects)
259     {
260         ERR("Failed to allocate object array memory.\n");
261         return;
262     }
263
264     GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
265     for (i = 0; i < object_count; ++i)
266     {
267         char *ptr, *line;
268         GLint tmp;
269
270         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
271
272         if (source_size < tmp)
273         {
274             HeapFree(GetProcessHeap(), 0, source);
275
276             source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
277             if (!source)
278             {
279                 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
280                 HeapFree(GetProcessHeap(), 0, objects);
281                 return;
282             }
283             source_size = tmp;
284         }
285
286         FIXME("Object %u:\n", objects[i]);
287         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
288         FIXME("    GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
289         GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
290         FIXME("    GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
291         FIXME("\n");
292
293         ptr = source;
294         GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
295         while ((line = get_info_log_line(&ptr))) FIXME("    %s\n", line);
296         FIXME("\n");
297     }
298
299     HeapFree(GetProcessHeap(), 0, source);
300     HeapFree(GetProcessHeap(), 0, objects);
301 }
302
303 /* GL locking is done by the caller. */
304 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
305 {
306     GLint tmp;
307
308     if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
309
310     GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
311     if (tmp == GL_PROGRAM_OBJECT_ARB)
312     {
313         GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
314         if (!tmp)
315         {
316             FIXME("Program %u link status invalid.\n", program);
317             shader_glsl_dump_program_source(gl_info, program);
318         }
319     }
320
321     print_glsl_info_log(gl_info, program);
322 }
323
324 /**
325  * Loads (pixel shader) samplers
326  */
327 /* GL locking is done by the caller */
328 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
329         const DWORD *tex_unit_map, GLhandleARB programId)
330 {
331     GLint name_loc;
332     int i;
333     char sampler_name[20];
334
335     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
336         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
337         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
338         if (name_loc != -1) {
339             DWORD mapped_unit = tex_unit_map[i];
340             if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
341             {
342                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
343                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
344                 checkGLcall("glUniform1iARB");
345             } else {
346                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
347             }
348         }
349     }
350 }
351
352 /* GL locking is done by the caller */
353 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
354         const DWORD *tex_unit_map, GLhandleARB programId)
355 {
356     GLint name_loc;
357     char sampler_name[20];
358     int i;
359
360     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
361         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
362         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
363         if (name_loc != -1) {
364             DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
365             if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
366             {
367                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
368                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
369                 checkGLcall("glUniform1iARB");
370             } else {
371                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
372             }
373         }
374     }
375 }
376
377 /* GL locking is done by the caller */
378 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
379         const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
380 {
381     int stack_idx = 0;
382     unsigned int heap_idx = 1;
383     unsigned int idx;
384
385     if (heap->entries[heap_idx].version <= version) return;
386
387     idx = heap->entries[heap_idx].idx;
388     if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
389     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
390
391     while (stack_idx >= 0)
392     {
393         /* Note that we fall through to the next case statement. */
394         switch(stack[stack_idx])
395         {
396             case HEAP_NODE_TRAVERSE_LEFT:
397             {
398                 unsigned int left_idx = heap_idx << 1;
399                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
400                 {
401                     heap_idx = left_idx;
402                     idx = heap->entries[heap_idx].idx;
403                     if (constant_locations[idx] != -1)
404                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
405
406                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
407                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
408                     break;
409                 }
410             }
411
412             case HEAP_NODE_TRAVERSE_RIGHT:
413             {
414                 unsigned int right_idx = (heap_idx << 1) + 1;
415                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
416                 {
417                     heap_idx = right_idx;
418                     idx = heap->entries[heap_idx].idx;
419                     if (constant_locations[idx] != -1)
420                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
421
422                     stack[stack_idx++] = HEAP_NODE_POP;
423                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
424                     break;
425                 }
426             }
427
428             case HEAP_NODE_POP:
429                 heap_idx >>= 1;
430                 --stack_idx;
431                 break;
432         }
433     }
434     checkGLcall("walk_constant_heap()");
435 }
436
437 /* GL locking is done by the caller */
438 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
439 {
440     GLfloat clamped_constant[4];
441
442     if (location == -1) return;
443
444     clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
445     clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
446     clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
447     clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
448
449     GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
450 }
451
452 /* GL locking is done by the caller */
453 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
454         const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
455 {
456     int stack_idx = 0;
457     unsigned int heap_idx = 1;
458     unsigned int idx;
459
460     if (heap->entries[heap_idx].version <= version) return;
461
462     idx = heap->entries[heap_idx].idx;
463     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
464     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
465
466     while (stack_idx >= 0)
467     {
468         /* Note that we fall through to the next case statement. */
469         switch(stack[stack_idx])
470         {
471             case HEAP_NODE_TRAVERSE_LEFT:
472             {
473                 unsigned int left_idx = heap_idx << 1;
474                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
475                 {
476                     heap_idx = left_idx;
477                     idx = heap->entries[heap_idx].idx;
478                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
479
480                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
481                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
482                     break;
483                 }
484             }
485
486             case HEAP_NODE_TRAVERSE_RIGHT:
487             {
488                 unsigned int right_idx = (heap_idx << 1) + 1;
489                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
490                 {
491                     heap_idx = right_idx;
492                     idx = heap->entries[heap_idx].idx;
493                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
494
495                     stack[stack_idx++] = HEAP_NODE_POP;
496                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
497                     break;
498                 }
499             }
500
501             case HEAP_NODE_POP:
502                 heap_idx >>= 1;
503                 --stack_idx;
504                 break;
505         }
506     }
507     checkGLcall("walk_constant_heap_clamped()");
508 }
509
510 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
511 /* GL locking is done by the caller */
512 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
513         const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
514         unsigned char *stack, UINT version)
515 {
516     const struct wined3d_shader_lconst *lconst;
517
518     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
519     if (shader->reg_maps.shader_version.major == 1
520             && shader_is_pshader_version(shader->reg_maps.shader_version.type))
521         walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
522     else
523         walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
524
525     if (!shader->load_local_constsF)
526     {
527         TRACE("No need to load local float constants for this shader\n");
528         return;
529     }
530
531     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
532     LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
533     {
534         GLint location = constant_locations[lconst->idx];
535         /* We found this uniform name in the program - go ahead and send the data */
536         if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
537     }
538     checkGLcall("glUniform4fvARB()");
539 }
540
541 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
542 /* GL locking is done by the caller */
543 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
544         const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
545 {
546     unsigned int i;
547     struct list* ptr;
548
549     for (i = 0; constants_set; constants_set >>= 1, ++i)
550     {
551         if (!(constants_set & 1)) continue;
552
553         TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
554                 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
555
556         /* We found this uniform name in the program - go ahead and send the data */
557         GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
558         checkGLcall("glUniform4ivARB");
559     }
560
561     /* Load immediate constants */
562     ptr = list_head(&shader->constantsI);
563     while (ptr)
564     {
565         const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
566         unsigned int idx = lconst->idx;
567         const GLint *values = (const GLint *)lconst->value;
568
569         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
570             values[0], values[1], values[2], values[3]);
571
572         /* We found this uniform name in the program - go ahead and send the data */
573         GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
574         checkGLcall("glUniform4ivARB");
575         ptr = list_next(&shader->constantsI, ptr);
576     }
577 }
578
579 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
580 /* GL locking is done by the caller */
581 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
582         GLhandleARB programId, const BOOL *constants, WORD constants_set)
583 {
584     GLint tmp_loc;
585     unsigned int i;
586     char tmp_name[8];
587     const char *prefix;
588     struct list* ptr;
589
590     switch (shader->reg_maps.shader_version.type)
591     {
592         case WINED3D_SHADER_TYPE_VERTEX:
593             prefix = "VB";
594             break;
595
596         case WINED3D_SHADER_TYPE_GEOMETRY:
597             prefix = "GB";
598             break;
599
600         case WINED3D_SHADER_TYPE_PIXEL:
601             prefix = "PB";
602             break;
603
604         default:
605             FIXME("Unknown shader type %#x.\n",
606                     shader->reg_maps.shader_version.type);
607             prefix = "UB";
608             break;
609     }
610
611     /* TODO: Benchmark and see if it would be beneficial to store the
612      * locations of the constants to avoid looking up each time */
613     for (i = 0; constants_set; constants_set >>= 1, ++i)
614     {
615         if (!(constants_set & 1)) continue;
616
617         TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
618
619         /* TODO: Benchmark and see if it would be beneficial to store the
620          * locations of the constants to avoid looking up each time */
621         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
622         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
623         if (tmp_loc != -1)
624         {
625             /* We found this uniform name in the program - go ahead and send the data */
626             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
627             checkGLcall("glUniform1ivARB");
628         }
629     }
630
631     /* Load immediate constants */
632     ptr = list_head(&shader->constantsB);
633     while (ptr)
634     {
635         const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
636         unsigned int idx = lconst->idx;
637         const GLint *values = (const GLint *)lconst->value;
638
639         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
640
641         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
642         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
643         if (tmp_loc != -1) {
644             /* We found this uniform name in the program - go ahead and send the data */
645             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
646             checkGLcall("glUniform1ivARB");
647         }
648         ptr = list_next(&shader->constantsB, ptr);
649     }
650 }
651
652 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
653 {
654     WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
655 }
656
657 /**
658  * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
659  */
660 /* GL locking is done by the caller (state handler) */
661 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
662         const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
663 {
664     struct shader_glsl_priv *glsl_priv = shader_priv;
665     const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
666
667     /* No GLSL program set - nothing to do. */
668     if (!prog) return;
669
670     /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
671     if (!use_ps(state)) return;
672
673     if (prog->ps_args.np2_fixup && prog->np2Fixup_location != -1)
674     {
675         UINT i;
676         UINT fixup = prog->ps_args.np2_fixup;
677         GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
678
679         for (i = 0; fixup; fixup >>= 1, ++i)
680         {
681             const struct wined3d_texture *tex = state->textures[i];
682             const unsigned char idx = prog->np2Fixup_info->idx[i];
683             GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
684
685             if (!tex)
686             {
687                 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
688                 continue;
689             }
690
691             if (idx % 2)
692             {
693                 tex_dim[2] = tex->pow2_matrix[0];
694                 tex_dim[3] = tex->pow2_matrix[5];
695             }
696             else
697             {
698                 tex_dim[0] = tex->pow2_matrix[0];
699                 tex_dim[1] = tex->pow2_matrix[5];
700             }
701         }
702
703         GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
704     }
705 }
706
707 /**
708  * Loads the app-supplied constants into the currently set GLSL program.
709  */
710 /* GL locking is done by the caller (state handler) */
711 static void shader_glsl_load_constants(const struct wined3d_context *context,
712         char usePixelShader, char useVertexShader)
713 {
714     const struct wined3d_gl_info *gl_info = context->gl_info;
715     struct wined3d_device *device = context->swapchain->device;
716     struct wined3d_stateblock *stateBlock = device->stateBlock;
717     struct shader_glsl_priv *priv = device->shader_priv;
718     float position_fixup[4];
719
720     GLhandleARB programId;
721     struct glsl_shader_prog_link *prog = priv->glsl_program;
722     UINT constant_version;
723     int i;
724
725     if (!prog) {
726         /* No GLSL program set - nothing to do. */
727         return;
728     }
729     programId = prog->programId;
730     constant_version = prog->constant_version;
731
732     if (useVertexShader)
733     {
734         const struct wined3d_shader *vshader = stateBlock->state.vertex_shader;
735
736         /* Load DirectX 9 float constants/uniforms for vertex shader */
737         shader_glsl_load_constantsF(vshader, gl_info, stateBlock->state.vs_consts_f,
738                 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
739
740         /* Load DirectX 9 integer constants/uniforms for vertex shader */
741         shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->state.vs_consts_i,
742                 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
743
744         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
745         shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->state.vs_consts_b,
746                 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
747
748         /* Upload the position fixup params */
749         shader_get_position_fixup(context, &stateBlock->state, position_fixup);
750         GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
751         checkGLcall("glUniform4fvARB");
752     }
753
754     if (usePixelShader)
755     {
756         const struct wined3d_shader *pshader = stateBlock->state.pixel_shader;
757
758         /* Load DirectX 9 float constants/uniforms for pixel shader */
759         shader_glsl_load_constantsF(pshader, gl_info, stateBlock->state.ps_consts_f,
760                 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
761
762         /* Load DirectX 9 integer constants/uniforms for pixel shader */
763         shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->state.ps_consts_i,
764                 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
765
766         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
767         shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->state.ps_consts_b,
768                 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
769
770         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
771          * It can't be 0 for a valid texbem instruction.
772          */
773         for(i = 0; i < MAX_TEXTURES; i++) {
774             const float *data;
775
776             if(prog->bumpenvmat_location[i] == -1) continue;
777
778             data = (const float *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVMAT00];
779             GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
780             checkGLcall("glUniformMatrix2fvARB");
781
782             /* texbeml needs the luminance scale and offset too. If texbeml
783              * is used, needsbumpmat is set too, so we can check that in the
784              * needsbumpmat check. */
785             if (prog->luminancescale_location[i] != -1)
786             {
787                 const GLfloat *scale = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLSCALE];
788                 const GLfloat *offset = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLOFFSET];
789
790                 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
791                 checkGLcall("glUniform1fvARB");
792                 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
793                 checkGLcall("glUniform1fvARB");
794             }
795         }
796
797         if (prog->ycorrection_location != -1)
798         {
799             float correction_params[4];
800
801             if (context->render_offscreen)
802             {
803                 correction_params[0] = 0.0f;
804                 correction_params[1] = 1.0f;
805             } else {
806                 /* position is window relative, not viewport relative */
807                 correction_params[0] = (float) context->current_rt->resource.height;
808                 correction_params[1] = -1.0f;
809             }
810             GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
811         }
812     }
813
814     if (priv->next_constant_version == UINT_MAX)
815     {
816         TRACE("Max constant version reached, resetting to 0.\n");
817         wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
818         priv->next_constant_version = 1;
819     }
820     else
821     {
822         prog->constant_version = priv->next_constant_version++;
823     }
824 }
825
826 static void update_heap_entry(const struct constant_heap *heap, unsigned int idx,
827         unsigned int heap_idx, DWORD new_version)
828 {
829     struct constant_entry *entries = heap->entries;
830     unsigned int *positions = heap->positions;
831     unsigned int parent_idx;
832
833     while (heap_idx > 1)
834     {
835         parent_idx = heap_idx >> 1;
836
837         if (new_version <= entries[parent_idx].version) break;
838
839         entries[heap_idx] = entries[parent_idx];
840         positions[entries[parent_idx].idx] = heap_idx;
841         heap_idx = parent_idx;
842     }
843
844     entries[heap_idx].version = new_version;
845     entries[heap_idx].idx = idx;
846     positions[idx] = heap_idx;
847 }
848
849 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
850 {
851     struct shader_glsl_priv *priv = device->shader_priv;
852     struct constant_heap *heap = &priv->vconst_heap;
853     UINT i;
854
855     for (i = start; i < count + start; ++i)
856     {
857         if (!device->stateBlock->changed.vertexShaderConstantsF[i])
858             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
859         else
860             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
861     }
862 }
863
864 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
865 {
866     struct shader_glsl_priv *priv = device->shader_priv;
867     struct constant_heap *heap = &priv->pconst_heap;
868     UINT i;
869
870     for (i = start; i < count + start; ++i)
871     {
872         if (!device->stateBlock->changed.pixelShaderConstantsF[i])
873             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
874         else
875             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
876     }
877 }
878
879 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
880 {
881     unsigned int ret = gl_info->limits.glsl_varyings / 4;
882     /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
883     if(shader_major > 3) return ret;
884
885     /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
886     if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
887     return ret;
888 }
889
890 /** Generate the variable & register declarations for the GLSL output target */
891 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
892         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
893         const struct wined3d_shader_reg_maps *reg_maps, const struct shader_glsl_ctx_priv *ctx_priv)
894 {
895     const struct wined3d_state *state = &shader->device->stateBlock->state;
896     const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
897     const struct wined3d_gl_info *gl_info = context->gl_info;
898     const struct wined3d_fb_state *fb = &shader->device->fb;
899     unsigned int i, extra_constants_needed = 0;
900     const struct wined3d_shader_lconst *lconst;
901     DWORD map;
902
903     /* There are some minor differences between pixel and vertex shaders */
904     char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
905     char prefix = pshader ? 'P' : 'V';
906
907     /* Prototype the subroutines */
908     for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
909     {
910         if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
911     }
912
913     /* Declare the constants (aka uniforms) */
914     if (shader->limits.constant_float > 0)
915     {
916         unsigned max_constantsF;
917         /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
918          * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
919          * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
920          * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
921          * a dx9 card, as long as it doesn't also use all the other constants.
922          *
923          * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
924          * declare only the amount that we're assured to have.
925          *
926          * Thus we run into problems in these two cases:
927          * 1) The shader really uses more uniforms than supported
928          * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
929          */
930         if (pshader)
931         {
932             /* No indirect addressing here. */
933             max_constantsF = gl_info->limits.glsl_ps_float_constants;
934         }
935         else
936         {
937             if (reg_maps->usesrelconstF)
938             {
939                 /* Subtract the other potential uniforms from the max
940                  * available (bools, ints, and 1 row of projection matrix).
941                  * Subtract another uniform for immediate values, which have
942                  * to be loaded via uniform by the driver as well. The shader
943                  * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
944                  * shader code, so one vec4 should be enough. (Unfortunately
945                  * the Nvidia driver doesn't store 128 and -128 in one float).
946                  *
947                  * Writing gl_ClipVertex requires one uniform for each
948                  * clipplane as well. */
949                 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
950                 if(ctx_priv->cur_vs_args->clip_enabled)
951                 {
952                     max_constantsF -= gl_info->limits.clipplanes;
953                 }
954                 max_constantsF -= count_bits(reg_maps->integer_constants);
955                 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
956                  * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
957                  * for now take this into account when calculating the number of available constants
958                  */
959                 max_constantsF -= count_bits(reg_maps->boolean_constants);
960                 /* Set by driver quirks in directx.c */
961                 max_constantsF -= gl_info->reserved_glsl_constants;
962             }
963             else
964             {
965                 max_constantsF = gl_info->limits.glsl_vs_float_constants;
966             }
967         }
968         max_constantsF = min(shader->limits.constant_float, max_constantsF);
969         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
970     }
971
972     /* Always declare the full set of constants, the compiler can remove the
973      * unused ones because d3d doesn't (yet) support indirect int and bool
974      * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
975     if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
976         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, shader->limits.constant_int);
977
978     if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
979         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, shader->limits.constant_bool);
980
981     if (!pshader)
982     {
983         shader_addline(buffer, "uniform vec4 posFixup;\n");
984         shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
985     }
986     else
987     {
988         for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
989         {
990             if (!(map & 1)) continue;
991
992             shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
993
994             if (reg_maps->luminanceparams & (1 << i))
995             {
996                 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
997                 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
998                 extra_constants_needed++;
999             }
1000
1001             extra_constants_needed++;
1002         }
1003
1004         if (ps_args->srgb_correction)
1005         {
1006             shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1007                     srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1008             shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1009                     srgb_cmp);
1010         }
1011         if (reg_maps->vpos || reg_maps->usesdsy)
1012         {
1013             if (shader->limits.constant_float + extra_constants_needed
1014                     + 1 < gl_info->limits.glsl_ps_float_constants)
1015             {
1016                 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1017                 extra_constants_needed++;
1018             }
1019             else
1020             {
1021                 /* This happens because we do not have proper tracking of the constant registers that are
1022                  * actually used, only the max limit of the shader version
1023                  */
1024                 FIXME("Cannot find a free uniform for vpos correction params\n");
1025                 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1026                         context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1027                         context->render_offscreen ? 1.0f : -1.0f);
1028             }
1029             shader_addline(buffer, "vec4 vpos;\n");
1030         }
1031     }
1032
1033     /* Declare texture samplers */
1034     for (i = 0; i < shader->limits.sampler; ++i)
1035     {
1036         if (reg_maps->sampler_type[i])
1037         {
1038             const struct wined3d_texture *texture;
1039
1040             switch (reg_maps->sampler_type[i])
1041             {
1042                 case WINED3DSTT_1D:
1043                     if (pshader && ps_args->shadow & (1 << i))
1044                         shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1045                     else
1046                         shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1047                     break;
1048                 case WINED3DSTT_2D:
1049                     texture = state->textures[i];
1050                     if (pshader && ps_args->shadow & (1 << i))
1051                     {
1052                         if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1053                             shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1054                         else
1055                             shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1056                     }
1057                     else
1058                     {
1059                         if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1060                             shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1061                         else
1062                             shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1063                     }
1064                     break;
1065                 case WINED3DSTT_CUBE:
1066                     if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1067                     shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1068                     break;
1069                 case WINED3DSTT_VOLUME:
1070                     if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1071                     shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1072                     break;
1073                 default:
1074                     shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1075                     FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1076                     break;
1077             }
1078         }
1079     }
1080
1081     /* Declare uniforms for NP2 texcoord fixup:
1082      * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1083      * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1084      * Modern cards just skip the code anyway, so put it inside a separate loop. */
1085     if (pshader && ps_args->np2_fixup) {
1086
1087         struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1088         UINT cur = 0;
1089
1090         /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1091          * while D3D has them in the (normalized) [0,1]x[0,1] range.
1092          * samplerNP2Fixup stores texture dimensions and is updated through
1093          * shader_glsl_load_np2fixup_constants when the sampler changes. */
1094
1095         for (i = 0; i < shader->limits.sampler; ++i)
1096         {
1097             if (reg_maps->sampler_type[i])
1098             {
1099                 if (!(ps_args->np2_fixup & (1 << i))) continue;
1100
1101                 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1102                     FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1103                     continue;
1104                 }
1105
1106                 fixup->idx[i] = cur++;
1107             }
1108         }
1109
1110         fixup->num_consts = (cur + 1) >> 1;
1111         shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1112     }
1113
1114     /* Declare address variables */
1115     for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1116     {
1117         if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1118     }
1119
1120     /* Declare texture coordinate temporaries and initialize them */
1121     for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1122     {
1123         if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1124     }
1125
1126     /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1127      * helper function shader that is linked in at link time
1128      */
1129     if (pshader && reg_maps->shader_version.major >= 3)
1130     {
1131         if (use_vs(state))
1132         {
1133             shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1134         } else {
1135             /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1136              * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1137              * pixel shader that reads the fixed function color into the packed input registers.
1138              */
1139             shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1140         }
1141     }
1142
1143     /* Declare output register temporaries */
1144     if (shader->limits.packed_output)
1145         shader_addline(buffer, "vec4 OUT[%u];\n", shader->limits.packed_output);
1146
1147     /* Declare temporary variables */
1148     for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1149     {
1150         if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1151     }
1152
1153     /* Declare attributes */
1154     if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1155     {
1156         for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1157         {
1158             if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1159         }
1160     }
1161
1162     /* Declare loop registers aLx */
1163     for (i = 0; i < reg_maps->loop_depth; i++) {
1164         shader_addline(buffer, "int aL%u;\n", i);
1165         shader_addline(buffer, "int tmpInt%u;\n", i);
1166     }
1167
1168     /* Temporary variables for matrix operations */
1169     shader_addline(buffer, "vec4 tmp0;\n");
1170     shader_addline(buffer, "vec4 tmp1;\n");
1171
1172     /* Local constants use a different name so they can be loaded once at shader link time
1173      * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1174      * float -> string conversion can cause precision loss.
1175      */
1176     if (!shader->load_local_constsF)
1177     {
1178         LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1179         {
1180             shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1181         }
1182     }
1183
1184     /* Start the main program */
1185     shader_addline(buffer, "void main() {\n");
1186     if(pshader && reg_maps->vpos) {
1187         /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1188          * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1189          * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1190          * precision troubles when we just subtract 0.5.
1191          *
1192          * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1193          *
1194          * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1195          *
1196          * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1197          * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1198          * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1199          * correctly on drivers that returns integer values.
1200          */
1201         shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1202     }
1203 }
1204
1205 /*****************************************************************************
1206  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1207  *
1208  * For more information, see http://wiki.winehq.org/DirectX-Shaders
1209  ****************************************************************************/
1210
1211 /* Prototypes */
1212 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1213         const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1214
1215 /** Used for opcode modifiers - They multiply the result by the specified amount */
1216 static const char * const shift_glsl_tab[] = {
1217     "",           /*  0 (none) */
1218     "2.0 * ",     /*  1 (x2)   */
1219     "4.0 * ",     /*  2 (x4)   */
1220     "8.0 * ",     /*  3 (x8)   */
1221     "16.0 * ",    /*  4 (x16)  */
1222     "32.0 * ",    /*  5 (x32)  */
1223     "",           /*  6 (x64)  */
1224     "",           /*  7 (x128) */
1225     "",           /*  8 (d256) */
1226     "",           /*  9 (d128) */
1227     "",           /* 10 (d64)  */
1228     "",           /* 11 (d32)  */
1229     "0.0625 * ",  /* 12 (d16)  */
1230     "0.125 * ",   /* 13 (d8)   */
1231     "0.25 * ",    /* 14 (d4)   */
1232     "0.5 * "      /* 15 (d2)   */
1233 };
1234
1235 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1236 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1237 {
1238     out_str[0] = 0;
1239
1240     switch (src_modifier)
1241     {
1242     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1243     case WINED3DSPSM_DW:
1244     case WINED3DSPSM_NONE:
1245         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1246         break;
1247     case WINED3DSPSM_NEG:
1248         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1249         break;
1250     case WINED3DSPSM_NOT:
1251         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1252         break;
1253     case WINED3DSPSM_BIAS:
1254         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1255         break;
1256     case WINED3DSPSM_BIASNEG:
1257         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1258         break;
1259     case WINED3DSPSM_SIGN:
1260         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1261         break;
1262     case WINED3DSPSM_SIGNNEG:
1263         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1264         break;
1265     case WINED3DSPSM_COMP:
1266         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1267         break;
1268     case WINED3DSPSM_X2:
1269         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1270         break;
1271     case WINED3DSPSM_X2NEG:
1272         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1273         break;
1274     case WINED3DSPSM_ABS:
1275         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1276         break;
1277     case WINED3DSPSM_ABSNEG:
1278         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1279         break;
1280     default:
1281         FIXME("Unhandled modifier %u\n", src_modifier);
1282         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1283     }
1284 }
1285
1286 /** Writes the GLSL variable name that corresponds to the register that the
1287  * DX opcode parameter is trying to access */
1288 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1289         char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1290 {
1291     /* oPos, oFog and oPts in D3D */
1292     static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1293
1294     const struct wined3d_shader *shader = ins->ctx->shader;
1295     const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1296     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1297     char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1298
1299     *is_color = FALSE;
1300
1301     switch (reg->type)
1302     {
1303         case WINED3DSPR_TEMP:
1304             sprintf(register_name, "R%u", reg->idx);
1305             break;
1306
1307         case WINED3DSPR_INPUT:
1308             /* vertex shaders */
1309             if (!pshader)
1310             {
1311                 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1312                 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1313                 sprintf(register_name, "attrib%u", reg->idx);
1314                 break;
1315             }
1316
1317             /* pixel shaders >= 3.0 */
1318             if (reg_maps->shader_version.major >= 3)
1319             {
1320                 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1321                 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1322
1323                 if (reg->rel_addr)
1324                 {
1325                     struct glsl_src_param rel_param;
1326
1327                     shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1328
1329                     /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1330                      * operation there */
1331                     if (idx)
1332                     {
1333                         if (shader->u.ps.declared_in_count > in_count)
1334                         {
1335                             sprintf(register_name,
1336                                     "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1337                                     rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1338                                     rel_param.param_str, idx);
1339                         }
1340                         else
1341                         {
1342                             sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1343                         }
1344                     }
1345                     else
1346                     {
1347                         if (shader->u.ps.declared_in_count > in_count)
1348                         {
1349                             sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1350                                     rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1351                                     rel_param.param_str);
1352                         }
1353                         else
1354                         {
1355                             sprintf(register_name, "IN[%s]", rel_param.param_str);
1356                         }
1357                     }
1358                 }
1359                 else
1360                 {
1361                     if (idx == in_count) sprintf(register_name, "gl_Color");
1362                     else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1363                     else sprintf(register_name, "IN[%u]", idx);
1364                 }
1365             }
1366             else
1367             {
1368                 if (!reg->idx) strcpy(register_name, "gl_Color");
1369                 else strcpy(register_name, "gl_SecondaryColor");
1370                 break;
1371             }
1372             break;
1373
1374         case WINED3DSPR_CONST:
1375             {
1376                 const char prefix = pshader ? 'P' : 'V';
1377
1378                 /* Relative addressing */
1379                 if (reg->rel_addr)
1380                 {
1381                     struct glsl_src_param rel_param;
1382                     shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1383                     if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1384                     else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1385                 }
1386                 else
1387                 {
1388                     if (shader_constant_is_local(shader, reg->idx))
1389                         sprintf(register_name, "%cLC%u", prefix, reg->idx);
1390                     else
1391                         sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1392                 }
1393             }
1394             break;
1395
1396         case WINED3DSPR_CONSTINT:
1397             if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1398             else sprintf(register_name, "VI[%u]", reg->idx);
1399             break;
1400
1401         case WINED3DSPR_CONSTBOOL:
1402             if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1403             else sprintf(register_name, "VB[%u]", reg->idx);
1404             break;
1405
1406         case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1407             if (pshader) sprintf(register_name, "T%u", reg->idx);
1408             else sprintf(register_name, "A%u", reg->idx);
1409             break;
1410
1411         case WINED3DSPR_LOOP:
1412             sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1413             break;
1414
1415         case WINED3DSPR_SAMPLER:
1416             if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1417             else sprintf(register_name, "Vsampler%u", reg->idx);
1418             break;
1419
1420         case WINED3DSPR_COLOROUT:
1421             if (reg->idx >= gl_info->limits.buffers)
1422                 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1423
1424             sprintf(register_name, "gl_FragData[%u]", reg->idx);
1425             break;
1426
1427         case WINED3DSPR_RASTOUT:
1428             sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1429             break;
1430
1431         case WINED3DSPR_DEPTHOUT:
1432             sprintf(register_name, "gl_FragDepth");
1433             break;
1434
1435         case WINED3DSPR_ATTROUT:
1436             if (!reg->idx) sprintf(register_name, "OUT[8]");
1437             else sprintf(register_name, "OUT[9]");
1438             break;
1439
1440         case WINED3DSPR_TEXCRDOUT:
1441             /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1442             sprintf(register_name, "OUT[%u]", reg->idx);
1443             break;
1444
1445         case WINED3DSPR_MISCTYPE:
1446             if (!reg->idx)
1447             {
1448                 /* vPos */
1449                 sprintf(register_name, "vpos");
1450             }
1451             else if (reg->idx == 1)
1452             {
1453                 /* Note that gl_FrontFacing is a bool, while vFace is
1454                  * a float for which the sign determines front/back */
1455                 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1456             }
1457             else
1458             {
1459                 FIXME("Unhandled misctype register %d\n", reg->idx);
1460                 sprintf(register_name, "unrecognized_register");
1461             }
1462             break;
1463
1464         case WINED3DSPR_IMMCONST:
1465             switch (reg->immconst_type)
1466             {
1467                 case WINED3D_IMMCONST_SCALAR:
1468                     sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1469                     break;
1470
1471                 case WINED3D_IMMCONST_VEC4:
1472                     sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1473                             *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1474                             *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1475                     break;
1476
1477                 default:
1478                     FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1479                     sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1480             }
1481             break;
1482
1483         default:
1484             FIXME("Unhandled register name Type(%d)\n", reg->type);
1485             sprintf(register_name, "unrecognized_register");
1486             break;
1487     }
1488 }
1489
1490 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1491 {
1492     *str++ = '.';
1493     if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1494     if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1495     if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1496     if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1497     *str = '\0';
1498 }
1499
1500 /* Get the GLSL write mask for the destination register */
1501 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1502 {
1503     DWORD mask = param->write_mask;
1504
1505     if (shader_is_scalar(&param->reg))
1506     {
1507         mask = WINED3DSP_WRITEMASK_0;
1508         *write_mask = '\0';
1509     }
1510     else
1511     {
1512         shader_glsl_write_mask_to_str(mask, write_mask);
1513     }
1514
1515     return mask;
1516 }
1517
1518 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1519     unsigned int size = 0;
1520
1521     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1522     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1523     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1524     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1525
1526     return size;
1527 }
1528
1529 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1530 {
1531     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1532      * but addressed as "rgba". To fix this we need to swap the register's x
1533      * and z components. */
1534     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1535
1536     *str++ = '.';
1537     /* swizzle bits fields: wwzzyyxx */
1538     if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1539     if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1540     if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1541     if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1542     *str = '\0';
1543 }
1544
1545 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1546         BOOL fixup, DWORD mask, char *swizzle_str)
1547 {
1548     if (shader_is_scalar(&param->reg))
1549         *swizzle_str = '\0';
1550     else
1551         shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1552 }
1553
1554 /* From a given parameter token, generate the corresponding GLSL string.
1555  * Also, return the actual register name and swizzle in case the
1556  * caller needs this information as well. */
1557 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1558         const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1559 {
1560     BOOL is_color = FALSE;
1561     char swizzle_str[6];
1562
1563     glsl_src->reg_name[0] = '\0';
1564     glsl_src->param_str[0] = '\0';
1565     swizzle_str[0] = '\0';
1566
1567     shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1568     shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1569     shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1570 }
1571
1572 /* From a given parameter token, generate the corresponding GLSL string.
1573  * Also, return the actual register name and swizzle in case the
1574  * caller needs this information as well. */
1575 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1576         const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1577 {
1578     BOOL is_color = FALSE;
1579
1580     glsl_dst->mask_str[0] = '\0';
1581     glsl_dst->reg_name[0] = '\0';
1582
1583     shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1584     return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1585 }
1586
1587 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1588 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1589         const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1590 {
1591     struct glsl_dst_param glsl_dst;
1592     DWORD mask;
1593
1594     mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1595     if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1596
1597     return mask;
1598 }
1599
1600 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1601 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1602 {
1603     return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1604 }
1605
1606 /** Process GLSL instruction modifiers */
1607 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1608 {
1609     struct glsl_dst_param dst_param;
1610     DWORD modifiers;
1611
1612     if (!ins->dst_count) return;
1613
1614     modifiers = ins->dst[0].modifiers;
1615     if (!modifiers) return;
1616
1617     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1618
1619     if (modifiers & WINED3DSPDM_SATURATE)
1620     {
1621         /* _SAT means to clamp the value of the register to between 0 and 1 */
1622         shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1623                 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1624     }
1625
1626     if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1627     {
1628         FIXME("_centroid modifier not handled\n");
1629     }
1630
1631     if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1632     {
1633         /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1634     }
1635 }
1636
1637 static inline const char *shader_get_comp_op(DWORD op)
1638 {
1639     switch (op) {
1640         case COMPARISON_GT: return ">";
1641         case COMPARISON_EQ: return "==";
1642         case COMPARISON_GE: return ">=";
1643         case COMPARISON_LT: return "<";
1644         case COMPARISON_NE: return "!=";
1645         case COMPARISON_LE: return "<=";
1646         default:
1647             FIXME("Unrecognized comparison value: %u\n", op);
1648             return "(\?\?)";
1649     }
1650 }
1651
1652 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1653         DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1654 {
1655     enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1656     const struct wined3d_gl_info *gl_info = ctx->gl_info;
1657     BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1658             && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1659     BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1660     BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1661     BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1662     BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1663
1664     /* Note that there's no such thing as a projected cube texture. */
1665     switch(sampler_type) {
1666         case WINED3DSTT_1D:
1667             if (shadow)
1668             {
1669                 if (lod)
1670                 {
1671                     sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1672                 }
1673                 else if (grad)
1674                 {
1675                     if (gl_info->supported[EXT_GPU_SHADER4])
1676                         sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1677                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1678                         sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1679                     else
1680                     {
1681                         FIXME("Unsupported 1D shadow grad function.\n");
1682                         sample_function->name = "unsupported1DGrad";
1683                     }
1684                 }
1685                 else
1686                 {
1687                     sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1688                 }
1689                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1690             }
1691             else
1692             {
1693                 if (lod)
1694                 {
1695                     sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1696                 }
1697                 else if (grad)
1698                 {
1699                     if (gl_info->supported[EXT_GPU_SHADER4])
1700                         sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1701                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1702                         sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1703                     else
1704                     {
1705                         FIXME("Unsupported 1D grad function.\n");
1706                         sample_function->name = "unsupported1DGrad";
1707                     }
1708                 }
1709                 else
1710                 {
1711                     sample_function->name = projected ? "texture1DProj" : "texture1D";
1712                 }
1713                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1714             }
1715             break;
1716
1717         case WINED3DSTT_2D:
1718             if (shadow)
1719             {
1720                 if (texrect)
1721                 {
1722                     if (lod)
1723                     {
1724                         sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1725                     }
1726                     else if (grad)
1727                     {
1728                         if (gl_info->supported[EXT_GPU_SHADER4])
1729                             sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1730                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1731                             sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1732                         else
1733                         {
1734                             FIXME("Unsupported RECT shadow grad function.\n");
1735                             sample_function->name = "unsupported2DRectGrad";
1736                         }
1737                     }
1738                     else
1739                     {
1740                         sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1741                     }
1742                 }
1743                 else
1744                 {
1745                     if (lod)
1746                     {
1747                         sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1748                     }
1749                     else if (grad)
1750                     {
1751                         if (gl_info->supported[EXT_GPU_SHADER4])
1752                             sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1753                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1754                             sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1755                         else
1756                         {
1757                             FIXME("Unsupported 2D shadow grad function.\n");
1758                             sample_function->name = "unsupported2DGrad";
1759                         }
1760                     }
1761                     else
1762                     {
1763                         sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1764                     }
1765                 }
1766                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1767             }
1768             else
1769             {
1770                 if (texrect)
1771                 {
1772                     if (lod)
1773                     {
1774                         sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1775                     }
1776                     else if (grad)
1777                     {
1778                         if (gl_info->supported[EXT_GPU_SHADER4])
1779                             sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1780                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1781                             sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1782                         else
1783                         {
1784                             FIXME("Unsupported RECT grad function.\n");
1785                             sample_function->name = "unsupported2DRectGrad";
1786                         }
1787                     }
1788                     else
1789                     {
1790                         sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1791                     }
1792                 }
1793                 else
1794                 {
1795                     if (lod)
1796                     {
1797                         sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1798                     }
1799                     else if (grad)
1800                     {
1801                         if (gl_info->supported[EXT_GPU_SHADER4])
1802                             sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1803                         else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1804                             sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1805                         else
1806                         {
1807                             FIXME("Unsupported 2D grad function.\n");
1808                             sample_function->name = "unsupported2DGrad";
1809                         }
1810                     }
1811                     else
1812                     {
1813                         sample_function->name = projected ? "texture2DProj" : "texture2D";
1814                     }
1815                 }
1816                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1817             }
1818             break;
1819
1820         case WINED3DSTT_CUBE:
1821             if (shadow)
1822             {
1823                 FIXME("Unsupported Cube shadow function.\n");
1824                 sample_function->name = "unsupportedCubeShadow";
1825                 sample_function->coord_mask = 0;
1826             }
1827             else
1828             {
1829                 if (lod)
1830                 {
1831                     sample_function->name = "textureCubeLod";
1832                 }
1833                 else if (grad)
1834                 {
1835                     if (gl_info->supported[EXT_GPU_SHADER4])
1836                         sample_function->name = "textureCubeGrad";
1837                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1838                         sample_function->name = "textureCubeGradARB";
1839                     else
1840                     {
1841                         FIXME("Unsupported Cube grad function.\n");
1842                         sample_function->name = "unsupportedCubeGrad";
1843                     }
1844                 }
1845                 else
1846                 {
1847                     sample_function->name = "textureCube";
1848                 }
1849                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1850             }
1851             break;
1852
1853         case WINED3DSTT_VOLUME:
1854             if (shadow)
1855             {
1856                 FIXME("Unsupported 3D shadow function.\n");
1857                 sample_function->name = "unsupported3DShadow";
1858                 sample_function->coord_mask = 0;
1859             }
1860             else
1861             {
1862                 if (lod)
1863                 {
1864                     sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1865                 }
1866                 else  if (grad)
1867                 {
1868                     if (gl_info->supported[EXT_GPU_SHADER4])
1869                         sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1870                     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1871                         sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1872                     else
1873                     {
1874                         FIXME("Unsupported 3D grad function.\n");
1875                         sample_function->name = "unsupported3DGrad";
1876                     }
1877                 }
1878                 else
1879                 {
1880                     sample_function->name = projected ? "texture3DProj" : "texture3D";
1881                 }
1882                 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1883             }
1884             break;
1885
1886         default:
1887             sample_function->name = "";
1888             sample_function->coord_mask = 0;
1889             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1890             break;
1891     }
1892 }
1893
1894 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1895         BOOL sign_fixup, enum fixup_channel_source channel_source)
1896 {
1897     switch(channel_source)
1898     {
1899         case CHANNEL_SOURCE_ZERO:
1900             strcat(arguments, "0.0");
1901             break;
1902
1903         case CHANNEL_SOURCE_ONE:
1904             strcat(arguments, "1.0");
1905             break;
1906
1907         case CHANNEL_SOURCE_X:
1908             strcat(arguments, reg_name);
1909             strcat(arguments, ".x");
1910             break;
1911
1912         case CHANNEL_SOURCE_Y:
1913             strcat(arguments, reg_name);
1914             strcat(arguments, ".y");
1915             break;
1916
1917         case CHANNEL_SOURCE_Z:
1918             strcat(arguments, reg_name);
1919             strcat(arguments, ".z");
1920             break;
1921
1922         case CHANNEL_SOURCE_W:
1923             strcat(arguments, reg_name);
1924             strcat(arguments, ".w");
1925             break;
1926
1927         default:
1928             FIXME("Unhandled channel source %#x\n", channel_source);
1929             strcat(arguments, "undefined");
1930             break;
1931     }
1932
1933     if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1934 }
1935
1936 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1937 {
1938     struct wined3d_shader_dst_param dst;
1939     unsigned int mask_size, remaining;
1940     struct glsl_dst_param dst_param;
1941     char arguments[256];
1942     DWORD mask;
1943
1944     mask = 0;
1945     if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1946     if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1947     if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1948     if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1949     mask &= ins->dst[0].write_mask;
1950
1951     if (!mask) return; /* Nothing to do */
1952
1953     if (is_complex_fixup(fixup))
1954     {
1955         enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1956         FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1957         return;
1958     }
1959
1960     mask_size = shader_glsl_get_write_mask_size(mask);
1961
1962     dst = ins->dst[0];
1963     dst.write_mask = mask;
1964     shader_glsl_add_dst_param(ins, &dst, &dst_param);
1965
1966     arguments[0] = '\0';
1967     remaining = mask_size;
1968     if (mask & WINED3DSP_WRITEMASK_0)
1969     {
1970         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1971         if (--remaining) strcat(arguments, ", ");
1972     }
1973     if (mask & WINED3DSP_WRITEMASK_1)
1974     {
1975         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1976         if (--remaining) strcat(arguments, ", ");
1977     }
1978     if (mask & WINED3DSP_WRITEMASK_2)
1979     {
1980         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1981         if (--remaining) strcat(arguments, ", ");
1982     }
1983     if (mask & WINED3DSP_WRITEMASK_3)
1984     {
1985         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1986         if (--remaining) strcat(arguments, ", ");
1987     }
1988
1989     if (mask_size > 1)
1990     {
1991         shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1992                 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1993     }
1994     else
1995     {
1996         shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1997     }
1998 }
1999
2000 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2001         DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2002         const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2003 {
2004     const char *sampler_base;
2005     char dst_swizzle[6];
2006     struct color_fixup_desc fixup;
2007     BOOL np2_fixup = FALSE;
2008     va_list args;
2009
2010     shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2011
2012     if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2013     {
2014         const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2015         fixup = priv->cur_ps_args->color_fixup[sampler];
2016         sampler_base = "Psampler";
2017
2018         if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2019             if(bias) {
2020                 FIXME("Biased sampling from NP2 textures is unsupported\n");
2021             } else {
2022                 np2_fixup = TRUE;
2023             }
2024         }
2025     } else {
2026         sampler_base = "Vsampler";
2027         fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2028     }
2029
2030     shader_glsl_append_dst(ins->ctx->buffer, ins);
2031
2032     shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2033
2034     va_start(args, coord_reg_fmt);
2035     shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2036     va_end(args);
2037
2038     if(bias) {
2039         shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2040     } else {
2041         if (np2_fixup) {
2042             const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2043             const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2044
2045             shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2046                            (idx % 2) ? "zw" : "xy", dst_swizzle);
2047         } else if(dx && dy) {
2048             shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2049         } else {
2050             shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2051         }
2052     }
2053
2054     if(!is_identity_fixup(fixup)) {
2055         shader_glsl_color_correction(ins, fixup);
2056     }
2057 }
2058
2059 /*****************************************************************************
2060  * Begin processing individual instruction opcodes
2061  ****************************************************************************/
2062
2063 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2064 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2065 {
2066     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2067     struct glsl_src_param src0_param;
2068     struct glsl_src_param src1_param;
2069     DWORD write_mask;
2070     char op;
2071
2072     /* Determine the GLSL operator to use based on the opcode */
2073     switch (ins->handler_idx)
2074     {
2075         case WINED3DSIH_MUL: op = '*'; break;
2076         case WINED3DSIH_ADD: op = '+'; break;
2077         case WINED3DSIH_SUB: op = '-'; break;
2078         default:
2079             op = ' ';
2080             FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2081             break;
2082     }
2083
2084     write_mask = shader_glsl_append_dst(buffer, ins);
2085     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2086     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2087     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2088 }
2089
2090 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2091 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2092 {
2093     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2094     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2095     struct glsl_src_param src0_param;
2096     DWORD write_mask;
2097
2098     write_mask = shader_glsl_append_dst(buffer, ins);
2099     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2100
2101     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2102      * shader versions WINED3DSIO_MOVA is used for this. */
2103     if (ins->ctx->reg_maps->shader_version.major == 1
2104             && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2105             && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2106     {
2107         /* This is a simple floor() */
2108         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2109         if (mask_size > 1) {
2110             shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2111         } else {
2112             shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2113         }
2114     }
2115     else if(ins->handler_idx == WINED3DSIH_MOVA)
2116     {
2117         /* We need to *round* to the nearest int here. */
2118         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2119
2120         if (gl_info->supported[EXT_GPU_SHADER4])
2121         {
2122             if (mask_size > 1)
2123                 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2124             else
2125                 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2126         }
2127         else
2128         {
2129             if (mask_size > 1)
2130                 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2131                         mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2132             else
2133                 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2134                         src0_param.param_str, src0_param.param_str);
2135         }
2136     }
2137     else
2138     {
2139         shader_addline(buffer, "%s);\n", src0_param.param_str);
2140     }
2141 }
2142
2143 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2144 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2145 {
2146     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2147     struct glsl_src_param src0_param;
2148     struct glsl_src_param src1_param;
2149     DWORD dst_write_mask, src_write_mask;
2150     unsigned int dst_size = 0;
2151
2152     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2153     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2154
2155     /* dp3 works on vec3, dp4 on vec4 */
2156     if (ins->handler_idx == WINED3DSIH_DP4)
2157     {
2158         src_write_mask = WINED3DSP_WRITEMASK_ALL;
2159     } else {
2160         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2161     }
2162
2163     shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2164     shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2165
2166     if (dst_size > 1) {
2167         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2168     } else {
2169         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2170     }
2171 }
2172
2173 /* Note that this instruction has some restrictions. The destination write mask
2174  * can't contain the w component, and the source swizzles have to be .xyzw */
2175 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2176 {
2177     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2178     struct glsl_src_param src0_param;
2179     struct glsl_src_param src1_param;
2180     char dst_mask[6];
2181
2182     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2183     shader_glsl_append_dst(ins->ctx->buffer, ins);
2184     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2185     shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2186     shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2187 }
2188
2189 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2190  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2191  * GLSL uses the value as-is. */
2192 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2193 {
2194     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2195     struct glsl_src_param src0_param;
2196     struct glsl_src_param src1_param;
2197     DWORD dst_write_mask;
2198     unsigned int dst_size;
2199
2200     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2201     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2202
2203     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2204     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2205
2206     if (dst_size > 1)
2207     {
2208         shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2209                 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2210     }
2211     else
2212     {
2213         shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2214                 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2215     }
2216 }
2217
2218 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2219  * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2220  * GLSL uses the value as-is. */
2221 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2222 {
2223     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2224     struct glsl_src_param src0_param;
2225     DWORD dst_write_mask;
2226     unsigned int dst_size;
2227
2228     dst_write_mask = shader_glsl_append_dst(buffer, ins);
2229     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2230
2231     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2232
2233     if (dst_size > 1)
2234     {
2235         shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2236                 dst_size, src0_param.param_str);
2237     }
2238     else
2239     {
2240         shader_addline(buffer, "log2(abs(%s)));\n",
2241                 src0_param.param_str);
2242     }
2243 }
2244
2245 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2246 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2247 {
2248     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2249     struct glsl_src_param src_param;
2250     const char *instruction;
2251     DWORD write_mask;
2252     unsigned i;
2253
2254     /* Determine the GLSL function to use based on the opcode */
2255     /* TODO: Possibly make this a table for faster lookups */
2256     switch (ins->handler_idx)
2257     {
2258         case WINED3DSIH_MIN: instruction = "min"; break;
2259         case WINED3DSIH_MAX: instruction = "max"; break;
2260         case WINED3DSIH_ABS: instruction = "abs"; break;
2261         case WINED3DSIH_FRC: instruction = "fract"; break;
2262         case WINED3DSIH_EXP: instruction = "exp2"; break;
2263         case WINED3DSIH_DSX: instruction = "dFdx"; break;
2264         case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2265         default: instruction = "";
2266             FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2267             break;
2268     }
2269
2270     write_mask = shader_glsl_append_dst(buffer, ins);
2271
2272     shader_addline(buffer, "%s(", instruction);
2273
2274     if (ins->src_count)
2275     {
2276         shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2277         shader_addline(buffer, "%s", src_param.param_str);
2278         for (i = 1; i < ins->src_count; ++i)
2279         {
2280             shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2281             shader_addline(buffer, ", %s", src_param.param_str);
2282         }
2283     }
2284
2285     shader_addline(buffer, "));\n");
2286 }
2287
2288 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2289 {
2290     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2291     struct glsl_src_param src_param;
2292     unsigned int mask_size;
2293     DWORD write_mask;
2294     char dst_mask[6];
2295
2296     write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2297     mask_size = shader_glsl_get_write_mask_size(write_mask);
2298     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2299
2300     shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2301             src_param.param_str, src_param.param_str);
2302     shader_glsl_append_dst(buffer, ins);
2303
2304     if (mask_size > 1)
2305     {
2306         shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2307                 mask_size, src_param.param_str);
2308     }
2309     else
2310     {
2311         shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2312                 src_param.param_str);
2313     }
2314 }
2315
2316 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2317  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2318  *   dst.x = 2^(floor(src))
2319  *   dst.y = src - floor(src)
2320  *   dst.z = 2^src   (partial precision is allowed, but optional)
2321  *   dst.w = 1.0;
2322  * For 2.0 shaders, just do this (honoring writemask and swizzle):
2323  *   dst = 2^src;    (partial precision is allowed, but optional)
2324  */
2325 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2326 {
2327     struct glsl_src_param src_param;
2328
2329     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2330
2331     if (ins->ctx->reg_maps->shader_version.major < 2)
2332     {
2333         char dst_mask[6];
2334
2335         shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2336         shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2337         shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2338         shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2339
2340         shader_glsl_append_dst(ins->ctx->buffer, ins);
2341         shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2342         shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2343     } else {
2344         DWORD write_mask;
2345         unsigned int mask_size;
2346
2347         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2348         mask_size = shader_glsl_get_write_mask_size(write_mask);
2349
2350         if (mask_size > 1) {
2351             shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2352         } else {
2353             shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2354         }
2355     }
2356 }
2357
2358 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2359 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2360 {
2361     struct glsl_src_param src_param;
2362     DWORD write_mask;
2363     unsigned int mask_size;
2364
2365     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2366     mask_size = shader_glsl_get_write_mask_size(write_mask);
2367     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2368
2369     if (mask_size > 1)
2370     {
2371         shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2372                 mask_size, src_param.param_str);
2373     }
2374     else
2375     {
2376         shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2377                 src_param.param_str);
2378     }
2379 }
2380
2381 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2382 {
2383     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2384     struct glsl_src_param src_param;
2385     DWORD write_mask;
2386     unsigned int mask_size;
2387
2388     write_mask = shader_glsl_append_dst(buffer, ins);
2389     mask_size = shader_glsl_get_write_mask_size(write_mask);
2390
2391     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2392
2393     if (mask_size > 1)
2394     {
2395         shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2396                 mask_size, src_param.param_str);
2397     }
2398     else
2399     {
2400         shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2401                 src_param.param_str);
2402     }
2403 }
2404
2405 /** Process signed comparison opcodes in GLSL. */
2406 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2407 {
2408     struct glsl_src_param src0_param;
2409     struct glsl_src_param src1_param;
2410     DWORD write_mask;
2411     unsigned int mask_size;
2412
2413     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2414     mask_size = shader_glsl_get_write_mask_size(write_mask);
2415     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2416     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2417
2418     if (mask_size > 1) {
2419         const char *compare;
2420
2421         switch(ins->handler_idx)
2422         {
2423             case WINED3DSIH_SLT: compare = "lessThan"; break;
2424             case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2425             default: compare = "";
2426                 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2427         }
2428
2429         shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2430                 src0_param.param_str, src1_param.param_str);
2431     } else {
2432         switch(ins->handler_idx)
2433         {
2434             case WINED3DSIH_SLT:
2435                 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2436                  * to return 0.0 but step returns 1.0 because step is not < x
2437                  * An alternative is a bvec compare padded with an unused second component.
2438                  * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2439                  * issue. Playing with not() is not possible either because not() does not accept
2440                  * a scalar.
2441                  */
2442                 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2443                         src0_param.param_str, src1_param.param_str);
2444                 break;
2445             case WINED3DSIH_SGE:
2446                 /* Here we can use the step() function and safe a conditional */
2447                 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2448                 break;
2449             default:
2450                 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2451         }
2452
2453     }
2454 }
2455
2456 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2457 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2458 {
2459     struct glsl_src_param src0_param;
2460     struct glsl_src_param src1_param;
2461     struct glsl_src_param src2_param;
2462     DWORD write_mask, cmp_channel = 0;
2463     unsigned int i, j;
2464     char mask_char[6];
2465     BOOL temp_destination = FALSE;
2466
2467     if (shader_is_scalar(&ins->src[0].reg))
2468     {
2469         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2470
2471         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2472         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2473         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2474
2475         shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2476                        src0_param.param_str, src1_param.param_str, src2_param.param_str);
2477     } else {
2478         DWORD dst_mask = ins->dst[0].write_mask;
2479         struct wined3d_shader_dst_param dst = ins->dst[0];
2480
2481         /* Cycle through all source0 channels */
2482         for (i=0; i<4; i++) {
2483             write_mask = 0;
2484             /* Find the destination channels which use the current source0 channel */
2485             for (j=0; j<4; j++) {
2486                 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2487                 {
2488                     write_mask |= WINED3DSP_WRITEMASK_0 << j;
2489                     cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2490                 }
2491             }
2492             dst.write_mask = dst_mask & write_mask;
2493
2494             /* Splitting the cmp instruction up in multiple lines imposes a problem:
2495             * The first lines may overwrite source parameters of the following lines.
2496             * Deal with that by using a temporary destination register if needed
2497             */
2498             if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2499                     && ins->src[0].reg.type == ins->dst[0].reg.type)
2500                     || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2501                     && ins->src[1].reg.type == ins->dst[0].reg.type)
2502                     || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2503                     && ins->src[2].reg.type == ins->dst[0].reg.type))
2504             {
2505                 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2506                 if (!write_mask) continue;
2507                 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2508                 temp_destination = TRUE;
2509             } else {
2510                 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2511                 if (!write_mask) continue;
2512             }
2513
2514             shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2515             shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2516             shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2517
2518             shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2519                         src0_param.param_str, src1_param.param_str, src2_param.param_str);
2520         }
2521
2522         if(temp_destination) {
2523             shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2524             shader_glsl_append_dst(ins->ctx->buffer, ins);
2525             shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2526         }
2527     }
2528
2529 }
2530
2531 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2532 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2533  * the compare is done per component of src0. */
2534 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2535 {
2536     struct wined3d_shader_dst_param dst;
2537     struct glsl_src_param src0_param;
2538     struct glsl_src_param src1_param;
2539     struct glsl_src_param src2_param;
2540     DWORD write_mask, cmp_channel = 0;
2541     unsigned int i, j;
2542     DWORD dst_mask;
2543     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2544             ins->ctx->reg_maps->shader_version.minor);
2545
2546     if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2547     {
2548         write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2549         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2550         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2551         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2552
2553         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2554         if (ins->coissue)
2555         {
2556             shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2557         } else {
2558             shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2559                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
2560         }
2561         return;
2562     }
2563     /* Cycle through all source0 channels */
2564     dst_mask = ins->dst[0].write_mask;
2565     dst = ins->dst[0];
2566     for (i=0; i<4; i++) {
2567         write_mask = 0;
2568         /* Find the destination channels which use the current source0 channel */
2569         for (j=0; j<4; j++) {
2570             if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2571             {
2572                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2573                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2574             }
2575         }
2576
2577         dst.write_mask = dst_mask & write_mask;
2578         write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2579         if (!write_mask) continue;
2580
2581         shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2582         shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2583         shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2584
2585         shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2586                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2587     }
2588 }
2589
2590 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2591 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2592 {
2593     struct glsl_src_param src0_param;
2594     struct glsl_src_param src1_param;
2595     struct glsl_src_param src2_param;
2596     DWORD write_mask;
2597
2598     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2599     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2600     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2601     shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2602     shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2603             src0_param.param_str, src1_param.param_str, src2_param.param_str);
2604 }
2605
2606 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2607    Vertex shaders to GLSL codes */
2608 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2609 {
2610     int i;
2611     int nComponents = 0;
2612     struct wined3d_shader_dst_param tmp_dst = {{0}};
2613     struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2614     struct wined3d_shader_instruction tmp_ins;
2615
2616     memset(&tmp_ins, 0, sizeof(tmp_ins));
2617
2618     /* Set constants for the temporary argument */
2619     tmp_ins.ctx = ins->ctx;
2620     tmp_ins.dst_count = 1;
2621     tmp_ins.dst = &tmp_dst;
2622     tmp_ins.src_count = 2;
2623     tmp_ins.src = tmp_src;
2624
2625     switch(ins->handler_idx)
2626     {
2627         case WINED3DSIH_M4x4:
2628             nComponents = 4;
2629             tmp_ins.handler_idx = WINED3DSIH_DP4;
2630             break;
2631         case WINED3DSIH_M4x3:
2632             nComponents = 3;
2633             tmp_ins.handler_idx = WINED3DSIH_DP4;
2634             break;
2635         case WINED3DSIH_M3x4:
2636             nComponents = 4;
2637             tmp_ins.handler_idx = WINED3DSIH_DP3;
2638             break;
2639         case WINED3DSIH_M3x3:
2640             nComponents = 3;
2641             tmp_ins.handler_idx = WINED3DSIH_DP3;
2642             break;
2643         case WINED3DSIH_M3x2:
2644             nComponents = 2;
2645             tmp_ins.handler_idx = WINED3DSIH_DP3;
2646             break;
2647         default:
2648             break;
2649     }
2650
2651     tmp_dst = ins->dst[0];
2652     tmp_src[0] = ins->src[0];
2653     tmp_src[1] = ins->src[1];
2654     for (i = 0; i < nComponents; ++i)
2655     {
2656         tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2657         shader_glsl_dot(&tmp_ins);
2658         ++tmp_src[1].reg.idx;
2659     }
2660 }
2661
2662 /**
2663     The LRP instruction performs a component-wise linear interpolation
2664     between the second and third operands using the first operand as the
2665     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
2666     This is equivalent to mix(src2, src1, src0);
2667 */
2668 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2669 {
2670     struct glsl_src_param src0_param;
2671     struct glsl_src_param src1_param;
2672     struct glsl_src_param src2_param;
2673     DWORD write_mask;
2674
2675     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2676
2677     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2678     shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2679     shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2680
2681     shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2682             src2_param.param_str, src1_param.param_str, src0_param.param_str);
2683 }
2684
2685 /** Process the WINED3DSIO_LIT instruction in GLSL:
2686  * dst.x = dst.w = 1.0
2687  * dst.y = (src0.x > 0) ? src0.x
2688  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2689  *                                        where src.w is clamped at +- 128
2690  */
2691 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2692 {
2693     struct glsl_src_param src0_param;
2694     struct glsl_src_param src1_param;
2695     struct glsl_src_param src3_param;
2696     char dst_mask[6];
2697
2698     shader_glsl_append_dst(ins->ctx->buffer, ins);
2699     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2700
2701     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2702     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2703     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2704
2705     /* The sdk specifies the instruction like this
2706      * dst.x = 1.0;
2707      * if(src.x > 0.0) dst.y = src.x
2708      * else dst.y = 0.0.
2709      * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2710      * else dst.z = 0.0;
2711      * dst.w = 1.0;
2712      * (where power = src.w clamped between -128 and 128)
2713      *
2714      * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2715      * dst.x = 1.0                                  ... No further explanation needed
2716      * dst.y = max(src.y, 0.0);                     ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2717      * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0;   ... 0 ^ power is 0, and otherwise we use y anyway
2718      * dst.w = 1.0.                                 ... Nothing fancy.
2719      *
2720      * So we still have one conditional in there. So do this:
2721      * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2722      *
2723      * 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),
2724      * 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.
2725      * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
2726      *
2727      * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
2728      * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
2729      * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
2730      */
2731     shader_addline(ins->ctx->buffer,
2732             "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
2733             "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2734             src0_param.param_str, src3_param.param_str, src1_param.param_str,
2735             src0_param.param_str, src3_param.param_str, dst_mask);
2736 }
2737
2738 /** Process the WINED3DSIO_DST instruction in GLSL:
2739  * dst.x = 1.0
2740  * dst.y = src0.x * src0.y
2741  * dst.z = src0.z
2742  * dst.w = src1.w
2743  */
2744 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2745 {
2746     struct glsl_src_param src0y_param;
2747     struct glsl_src_param src0z_param;
2748     struct glsl_src_param src1y_param;
2749     struct glsl_src_param src1w_param;
2750     char dst_mask[6];
2751
2752     shader_glsl_append_dst(ins->ctx->buffer, ins);
2753     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2754
2755     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2756     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2757     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2758     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2759
2760     shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2761             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2762 }
2763
2764 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2765  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2766  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2767  *
2768  * dst.x = cos(src0.?)
2769  * dst.y = sin(src0.?)
2770  * dst.z = dst.z
2771  * dst.w = dst.w
2772  */
2773 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2774 {
2775     struct glsl_src_param src0_param;
2776     DWORD write_mask;
2777
2778     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2779     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2780
2781     switch (write_mask) {
2782         case WINED3DSP_WRITEMASK_0:
2783             shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2784             break;
2785
2786         case WINED3DSP_WRITEMASK_1:
2787             shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2788             break;
2789
2790         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2791             shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2792             break;
2793
2794         default:
2795             ERR("Write mask should be .x, .y or .xy\n");
2796             break;
2797     }
2798 }
2799
2800 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2801  * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2802  * generate invalid code
2803  */
2804 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2805 {
2806     struct glsl_src_param src0_param;
2807     DWORD write_mask;
2808
2809     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2810     shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2811
2812     shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2813 }
2814
2815 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2816  * Start a for() loop where src1.y is the initial value of aL,
2817  *  increment aL by src1.z for a total of src1.x iterations.
2818  *  Need to use a temporary variable for this operation.
2819  */
2820 /* FIXME: I don't think nested loops will work correctly this way. */
2821 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2822 {
2823     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2824     const struct wined3d_shader *shader = ins->ctx->shader;
2825     const struct wined3d_shader_lconst *constant;
2826     struct glsl_src_param src1_param;
2827     const DWORD *control_values = NULL;
2828
2829     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2830
2831     /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2832      * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2833      * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2834      * addressing.
2835      */
2836     if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2837     {
2838         LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2839         {
2840             if (constant->idx == ins->src[1].reg.idx)
2841             {
2842                 control_values = constant->value;
2843                 break;
2844             }
2845         }
2846     }
2847
2848     if (control_values)
2849     {
2850         struct wined3d_shader_loop_control loop_control;
2851         loop_control.count = control_values[0];
2852         loop_control.start = control_values[1];
2853         loop_control.step = (int)control_values[2];
2854
2855         if (loop_control.step > 0)
2856         {
2857             shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2858                     loop_state->current_depth, loop_control.start,
2859                     loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2860                     loop_state->current_depth, loop_control.step);
2861         }
2862         else if (loop_control.step < 0)
2863         {
2864             shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2865                     loop_state->current_depth, loop_control.start,
2866                     loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2867                     loop_state->current_depth, loop_control.step);
2868         }
2869         else
2870         {
2871             shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2872                     loop_state->current_depth, loop_control.start, loop_state->current_depth,
2873                     loop_state->current_depth, loop_control.count,
2874                     loop_state->current_depth);
2875         }
2876     } else {
2877         shader_addline(ins->ctx->buffer,
2878                 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2879                 loop_state->current_depth, loop_state->current_reg,
2880                 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
2881                 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
2882     }
2883
2884     ++loop_state->current_depth;
2885     ++loop_state->current_reg;
2886 }
2887
2888 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2889 {
2890     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2891
2892     shader_addline(ins->ctx->buffer, "}\n");
2893
2894     if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2895     {
2896         --loop_state->current_depth;
2897         --loop_state->current_reg;
2898     }
2899
2900     if (ins->handler_idx == WINED3DSIH_ENDREP)
2901     {
2902         --loop_state->current_depth;
2903     }
2904 }
2905
2906 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2907 {
2908     const struct wined3d_shader *shader = ins->ctx->shader;
2909     struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2910     const struct wined3d_shader_lconst *constant;
2911     struct glsl_src_param src0_param;
2912     const DWORD *control_values = NULL;
2913
2914     /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2915     if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2916     {
2917         LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2918         {
2919             if (constant->idx == ins->src[0].reg.idx)
2920             {
2921                 control_values = constant->value;
2922                 break;
2923             }
2924         }
2925     }
2926
2927     if (control_values)
2928     {
2929         shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2930                 loop_state->current_depth, loop_state->current_depth,
2931                 control_values[0], loop_state->current_depth);
2932     }
2933     else
2934     {
2935         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2936         shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2937                 loop_state->current_depth, loop_state->current_depth,
2938                 src0_param.param_str, loop_state->current_depth);
2939     }
2940
2941     ++loop_state->current_depth;
2942 }
2943
2944 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2945 {
2946     struct glsl_src_param src0_param;
2947
2948     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2949     shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2950 }
2951
2952 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2953 {
2954     struct glsl_src_param src0_param;
2955     struct glsl_src_param src1_param;
2956
2957     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2958     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2959
2960     shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2961             src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2962 }
2963
2964 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2965 {
2966     shader_addline(ins->ctx->buffer, "} else {\n");
2967 }
2968
2969 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2970 {
2971     shader_addline(ins->ctx->buffer, "break;\n");
2972 }
2973
2974 /* FIXME: According to MSDN the compare is done per component. */
2975 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2976 {
2977     struct glsl_src_param src0_param;
2978     struct glsl_src_param src1_param;
2979
2980     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2981     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2982
2983     shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2984             src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2985 }
2986
2987 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2988 {
2989     shader_addline(ins->ctx->buffer, "}\n");
2990     shader_addline(ins->ctx->buffer, "void subroutine%u () {\n",  ins->src[0].reg.idx);
2991 }
2992
2993 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2994 {
2995     shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2996 }
2997
2998 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2999 {
3000     struct glsl_src_param src1_param;
3001
3002     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3003     shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3004 }
3005
3006 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3007 {
3008     /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3009      * function only suppresses the unhandled instruction warning
3010      */
3011 }
3012
3013 /*********************************************
3014  * Pixel Shader Specific Code begins here
3015  ********************************************/
3016 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3017 {
3018     const struct wined3d_shader *shader = ins->ctx->shader;
3019     struct wined3d_device *device = shader->device;
3020     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3021             ins->ctx->reg_maps->shader_version.minor);
3022     struct glsl_sample_function sample_function;
3023     const struct wined3d_texture *texture;
3024     DWORD sample_flags = 0;
3025     DWORD sampler_idx;
3026     DWORD mask = 0, swizzle;
3027
3028     /* 1.0-1.4: Use destination register as sampler source.
3029      * 2.0+: Use provided sampler source. */
3030     if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3031     else sampler_idx = ins->src[1].reg.idx;
3032     texture = device->stateBlock->state.textures[sampler_idx];
3033
3034     if (shader_version < WINED3D_SHADER_VERSION(1,4))
3035     {
3036         const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3037         DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3038                 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3039         enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3040
3041         /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3042         if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3043             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3044             switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3045                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3046                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3047                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3048                 case WINED3DTTFF_COUNT4:
3049                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3050             }
3051         }
3052     }
3053     else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3054     {
3055         DWORD src_mod = ins->src[0].modifiers;
3056
3057         if (src_mod == WINED3DSPSM_DZ) {
3058             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3059             mask = WINED3DSP_WRITEMASK_2;
3060         } else if (src_mod == WINED3DSPSM_DW) {
3061             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3062             mask = WINED3DSP_WRITEMASK_3;
3063         }
3064     } else {
3065         if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3066         {
3067             /* ps 2.0 texldp instruction always divides by the fourth component. */
3068             sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3069             mask = WINED3DSP_WRITEMASK_3;
3070         }
3071     }
3072
3073     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3074         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3075
3076     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3077     mask |= sample_function.coord_mask;
3078
3079     if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3080     else swizzle = ins->src[1].swizzle;
3081
3082     /* 1.0-1.3: Use destination register as coordinate source.
3083        1.4+: Use provided coordinate source register. */
3084     if (shader_version < WINED3D_SHADER_VERSION(1,4))
3085     {
3086         char coord_mask[6];
3087         shader_glsl_write_mask_to_str(mask, coord_mask);
3088         shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3089                 "T%u%s", sampler_idx, coord_mask);
3090     }
3091     else
3092     {
3093         struct glsl_src_param coord_param;
3094         shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3095         if (ins->flags & WINED3DSI_TEXLD_BIAS)
3096         {
3097             struct glsl_src_param bias;
3098             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3099             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3100                     "%s", coord_param.param_str);
3101         } else {
3102             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3103                     "%s", coord_param.param_str);
3104         }
3105     }
3106 }
3107
3108 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3109 {
3110     const struct wined3d_shader *shader = ins->ctx->shader;
3111     struct wined3d_device *device = shader->device;
3112     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3113     struct glsl_src_param coord_param, dx_param, dy_param;
3114     DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3115     struct glsl_sample_function sample_function;
3116     DWORD sampler_idx;
3117     DWORD swizzle = ins->src[1].swizzle;
3118     const struct wined3d_texture *texture;
3119
3120     if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3121     {
3122         FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3123         shader_glsl_tex(ins);
3124         return;
3125     }
3126
3127     sampler_idx = ins->src[1].reg.idx;
3128     texture = device->stateBlock->state.textures[sampler_idx];
3129     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3130         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3131
3132     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3133     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3134     shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3135     shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3136
3137     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3138                                 "%s", coord_param.param_str);
3139 }
3140
3141 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3142 {
3143     const struct wined3d_shader *shader = ins->ctx->shader;
3144     struct wined3d_device *device = shader->device;
3145     const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3146     struct glsl_src_param coord_param, lod_param;
3147     DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3148     struct glsl_sample_function sample_function;
3149     DWORD sampler_idx;
3150     DWORD swizzle = ins->src[1].swizzle;
3151     const struct wined3d_texture *texture;
3152
3153     sampler_idx = ins->src[1].reg.idx;
3154     texture = device->stateBlock->state.textures[sampler_idx];
3155     if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3156         sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3157
3158     shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3159     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3160
3161     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3162
3163     if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3164             && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3165     {
3166         /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3167          * However, the NVIDIA drivers allow them in fragment shaders as well,
3168          * even without the appropriate extension. */
3169         WARN("Using %s in fragment shader.\n", sample_function.name);
3170     }
3171     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3172             "%s", coord_param.param_str);
3173 }
3174
3175 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3176 {
3177     /* FIXME: Make this work for more than just 2D textures */
3178     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3179     DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3180
3181     if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3182     {
3183         char dst_mask[6];
3184
3185         shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3186         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3187                 ins->dst[0].reg.idx, dst_mask);
3188     } else {
3189         DWORD reg = ins->src[0].reg.idx;
3190         DWORD src_mod = ins->src[0].modifiers;
3191         char dst_swizzle[6];
3192
3193         shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3194
3195         if (src_mod == WINED3DSPSM_DZ)
3196         {
3197             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3198             struct glsl_src_param div_param;
3199
3200             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3201
3202             if (mask_size > 1) {
3203                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3204             } else {
3205                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3206             }
3207         }
3208         else if (src_mod == WINED3DSPSM_DW)
3209         {
3210             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3211             struct glsl_src_param div_param;
3212
3213             shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3214
3215             if (mask_size > 1) {
3216                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3217             } else {
3218                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3219             }
3220         } else {
3221             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3222         }
3223     }
3224 }
3225
3226 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3227  * Take a 3-component dot product of the TexCoord[dstreg] and src,
3228  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3229 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3230 {
3231     DWORD sampler_idx = ins->dst[0].reg.idx;
3232     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3233     struct glsl_sample_function sample_function;
3234     struct glsl_src_param src0_param;
3235     UINT mask_size;
3236
3237     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3238
3239     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3240      * scalar, and projected sampling would require 4.
3241      *
3242      * It is a dependent read - not valid with conditional NP2 textures
3243      */
3244     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3245     mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3246
3247     switch(mask_size)
3248     {
3249         case 1:
3250             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3251                     "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3252             break;
3253
3254         case 2:
3255             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3256                     "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3257             break;
3258
3259         case 3:
3260             shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3261                     "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3262             break;
3263
3264         default:
3265             FIXME("Unexpected mask size %u\n", mask_size);
3266             break;
3267     }
3268 }
3269
3270 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3271  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3272 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3273 {
3274     DWORD dstreg = ins->dst[0].reg.idx;
3275     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3276     struct glsl_src_param src0_param;
3277     DWORD dst_mask;
3278     unsigned int mask_size;
3279
3280     dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3281     mask_size = shader_glsl_get_write_mask_size(dst_mask);
3282     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3283
3284     if (mask_size > 1) {
3285         shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3286     } else {
3287         shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3288     }
3289 }
3290
3291 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3292  * Calculate the depth as dst.x / dst.y   */
3293 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3294 {
3295     struct glsl_dst_param dst_param;
3296
3297     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3298
3299     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3300      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3301      * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3302      * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3303      * >= 1.0 or < 0.0
3304      */
3305     shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3306             dst_param.reg_name, dst_param.reg_name);
3307 }
3308
3309 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3310  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3311  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
3312  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3313  */
3314 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3315 {
3316     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3317     DWORD dstreg = ins->dst[0].reg.idx;
3318     struct glsl_src_param src0_param;
3319
3320     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3321
3322     shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3323     shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3324 }
3325
3326 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3327  * Calculate the 1st of a 2-row matrix multiplication. */
3328 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3329 {
3330     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3331     DWORD reg = ins->dst[0].reg.idx;
3332     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3333     struct glsl_src_param src0_param;
3334
3335     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3336     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3337 }
3338
3339 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3340  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3341 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3342 {
3343     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3344     DWORD reg = ins->dst[0].reg.idx;
3345     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3346     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3347     struct glsl_src_param src0_param;
3348
3349     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3350     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3351     tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3352 }
3353
3354 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3355 {
3356     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3357     DWORD reg = ins->dst[0].reg.idx;
3358     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3359     struct glsl_sample_function sample_function;
3360     struct glsl_src_param src0_param;
3361
3362     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3363     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3364
3365     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3366
3367     /* Sample the texture using the calculated coordinates */
3368     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3369 }
3370
3371 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3372  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3373 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3374 {
3375     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3376     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3377     struct glsl_sample_function sample_function;
3378     struct glsl_src_param src0_param;
3379     DWORD reg = ins->dst[0].reg.idx;
3380
3381     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3382     shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3383
3384     /* Dependent read, not valid with conditional NP2 */
3385     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3386
3387     /* Sample the texture using the calculated coordinates */
3388     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3389
3390     tex_mx->current_row = 0;
3391 }
3392
3393 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3394  * Perform the 3rd row of a 3x3 matrix multiply */
3395 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3396 {
3397     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3398     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3399     struct glsl_src_param src0_param;
3400     char dst_mask[6];
3401     DWORD reg = ins->dst[0].reg.idx;
3402
3403     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3404
3405     shader_glsl_append_dst(ins->ctx->buffer, ins);
3406     shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3407     shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3408
3409     tex_mx->current_row = 0;
3410 }
3411
3412 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3413  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3414 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3415 {
3416     struct glsl_src_param src0_param;
3417     struct glsl_src_param src1_param;
3418     DWORD reg = ins->dst[0].reg.idx;
3419     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3420     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3421     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3422     struct glsl_sample_function sample_function;
3423
3424     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3425     shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3426
3427     /* Perform the last matrix multiply operation */
3428     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3429     /* Reflection calculation */
3430     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3431
3432     /* Dependent read, not valid with conditional NP2 */
3433     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3434
3435     /* Sample the texture */
3436     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3437
3438     tex_mx->current_row = 0;
3439 }
3440
3441 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3442  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3443 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3444 {
3445     DWORD reg = ins->dst[0].reg.idx;
3446     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3447     struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3448     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3449     struct glsl_sample_function sample_function;
3450     struct glsl_src_param src0_param;
3451
3452     shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3453
3454     /* Perform the last matrix multiply operation */
3455     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3456
3457     /* Construct the eye-ray vector from w coordinates */
3458     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3459             tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3460     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3461
3462     /* Dependent read, not valid with conditional NP2 */
3463     shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3464
3465     /* Sample the texture using the calculated coordinates */
3466     shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3467
3468     tex_mx->current_row = 0;
3469 }
3470
3471 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3472  * Apply a fake bump map transform.
3473  * texbem is pshader <= 1.3 only, this saves a few version checks
3474  */
3475 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3476 {
3477     const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3478     struct glsl_sample_function sample_function;
3479     struct glsl_src_param coord_param;
3480     DWORD sampler_idx;
3481     DWORD mask;
3482     DWORD flags;
3483     char coord_mask[6];
3484
3485     sampler_idx = ins->dst[0].reg.idx;
3486     flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3487             & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3488
3489     /* Dependent read, not valid with conditional NP2 */
3490     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3491     mask = sample_function.coord_mask;
3492
3493     shader_glsl_write_mask_to_str(mask, coord_mask);
3494
3495     /* with projective textures, texbem only divides the static texture coord, not the displacement,
3496          * so we can't let the GL handle this.
3497          */
3498     if (flags & WINED3D_PSARGS_PROJECTED) {
3499         DWORD div_mask=0;
3500         char coord_div_mask[3];
3501         switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3502             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3503             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3504             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3505             case WINED3DTTFF_COUNT4:
3506             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3507         }
3508         shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3509         shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3510     }
3511
3512     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3513
3514     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3515             "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3516             coord_param.param_str, coord_mask);
3517
3518     if (ins->handler_idx == WINED3DSIH_TEXBEML)
3519     {
3520         struct glsl_src_param luminance_param;
3521         struct glsl_dst_param dst_param;
3522
3523         shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3524         shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3525
3526         shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3527                 dst_param.reg_name, dst_param.mask_str,
3528                 luminance_param.param_str, sampler_idx, sampler_idx);
3529     }
3530 }
3531
3532 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3533 {
3534     struct glsl_src_param src0_param, src1_param;
3535     DWORD sampler_idx = ins->dst[0].reg.idx;
3536
3537     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3538     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3539
3540     shader_glsl_append_dst(ins->ctx->buffer, ins);
3541     shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3542             src0_param.param_str, sampler_idx, src1_param.param_str);
3543 }
3544
3545 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3546  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3547 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3548 {
3549     struct glsl_sample_function sample_function;
3550     struct glsl_src_param src0_param;
3551     DWORD sampler_idx = ins->dst[0].reg.idx;
3552
3553     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3554
3555     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3556     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3557             "%s.wx", src0_param.reg_name);
3558 }
3559
3560 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3561  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3562 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3563 {
3564     struct glsl_sample_function sample_function;
3565     struct glsl_src_param src0_param;
3566     DWORD sampler_idx = ins->dst[0].reg.idx;
3567
3568     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3569
3570     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3571     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3572             "%s.yz", src0_param.reg_name);
3573 }
3574
3575 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3576  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3577 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3578 {
3579     struct glsl_sample_function sample_function;
3580     struct glsl_src_param src0_param;
3581     DWORD sampler_idx = ins->dst[0].reg.idx;
3582
3583     /* Dependent read, not valid with conditional NP2 */
3584     shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3585     shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3586
3587     shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3588             "%s", src0_param.param_str);
3589 }
3590
3591 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3592  * If any of the first 3 components are < 0, discard this pixel */
3593 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3594 {
3595     struct glsl_dst_param dst_param;
3596
3597     /* The argument is a destination parameter, and no writemasks are allowed */
3598     shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3599     if (ins->ctx->reg_maps->shader_version.major >= 2)
3600     {
3601         /* 2.0 shaders compare all 4 components in texkill */
3602         shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3603     } else {
3604         /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3605          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3606          * 4 components are defined, only the first 3 are used
3607          */
3608         shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3609     }
3610 }
3611
3612 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3613  * dst = dot2(src0, src1) + src2 */
3614 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3615 {
3616     struct glsl_src_param src0_param;
3617     struct glsl_src_param src1_param;
3618     struct glsl_src_param src2_param;
3619     DWORD write_mask;
3620     unsigned int mask_size;
3621
3622     write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3623     mask_size = shader_glsl_get_write_mask_size(write_mask);
3624
3625     shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3626     shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3627     shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3628
3629     if (mask_size > 1) {
3630         shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3631                 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3632     } else {
3633         shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3634                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3635     }
3636 }
3637
3638 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3639         const struct wined3d_shader_signature_element *input_signature,
3640         const struct wined3d_shader_reg_maps *reg_maps,
3641         enum vertexprocessing_mode vertexprocessing)
3642 {
3643     WORD map = reg_maps->input_registers;
3644     unsigned int i;
3645
3646     for (i = 0; map; map >>= 1, ++i)
3647     {
3648         const char *semantic_name;
3649         UINT semantic_idx;
3650         char reg_mask[6];
3651
3652         /* Unused */
3653         if (!(map & 1)) continue;
3654
3655         semantic_name = input_signature[i].semantic_name;
3656         semantic_idx = input_signature[i].semantic_idx;
3657         shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3658
3659         if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3660         {
3661             if (semantic_idx < 8 && vertexprocessing == pretransformed)
3662                 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3663                         shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3664             else
3665                 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3666                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3667         }
3668         else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3669         {
3670             if (!semantic_idx)
3671                 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3672                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3673             else if (semantic_idx == 1)
3674                 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3675                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3676             else
3677                 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3678                         shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3679         }
3680         else
3681         {
3682             shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3683                     shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3684         }
3685     }
3686 }
3687
3688 /*********************************************
3689  * Vertex Shader Specific Code begins here
3690  ********************************************/
3691
3692 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3693 {
3694     struct glsl_program_key key;
3695
3696     key.vshader = entry->vshader;
3697     key.pshader = entry->pshader;
3698     key.vs_args = entry->vs_args;
3699     key.ps_args = entry->ps_args;
3700
3701     if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3702     {
3703         ERR("Failed to insert program entry.\n");
3704     }
3705 }
3706
3707 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
3708         const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3709         const struct vs_compile_args *vs_args, const struct ps_compile_args *ps_args)
3710 {
3711     struct wine_rb_entry *entry;
3712     struct glsl_program_key key;
3713
3714     key.vshader = vshader;
3715     key.pshader = pshader;
3716     key.vs_args = *vs_args;
3717     key.ps_args = *ps_args;
3718
3719     entry = wine_rb_get(&priv->program_lookup, &key);
3720     return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3721 }
3722
3723 /* GL locking is done by the caller */
3724 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3725         struct glsl_shader_prog_link *entry)
3726 {
3727     struct glsl_program_key key;
3728
3729     key.vshader = entry->vshader;
3730     key.pshader = entry->pshader;
3731     key.vs_args = entry->vs_args;
3732     key.ps_args = entry->ps_args;
3733     wine_rb_remove(&priv->program_lookup, &key);
3734
3735     GL_EXTCALL(glDeleteObjectARB(entry->programId));
3736     if (entry->vshader) list_remove(&entry->vshader_entry);
3737     if (entry->pshader) list_remove(&entry->pshader_entry);
3738     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3739     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3740     HeapFree(GetProcessHeap(), 0, entry);
3741 }
3742
3743 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
3744         const struct wined3d_gl_info *gl_info, const DWORD *map,
3745         const struct wined3d_shader_signature_element *input_signature,
3746         const struct wined3d_shader_reg_maps *reg_maps_in,
3747         const struct wined3d_shader_signature_element *output_signature,
3748         const struct wined3d_shader_reg_maps *reg_maps_out)
3749 {
3750     unsigned int i, j;
3751     const char *semantic_name_in;
3752     UINT semantic_idx_in;
3753     DWORD *set;
3754     DWORD in_idx;
3755     unsigned int in_count = vec4_varyings(3, gl_info);
3756     char reg_mask[6];
3757     char destination[50];
3758     WORD input_map, output_map;
3759
3760     set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3761
3762     input_map = reg_maps_in->input_registers;
3763     for (i = 0; input_map; input_map >>= 1, ++i)
3764     {
3765         if (!(input_map & 1)) continue;
3766
3767         in_idx = map[i];
3768         /* Declared, but not read register */
3769         if (in_idx == ~0U) continue;
3770         if (in_idx >= (in_count + 2))
3771         {
3772             FIXME("More input varyings declared than supported, expect issues.\n");
3773             continue;
3774         }
3775
3776         if (in_idx == in_count) {
3777             sprintf(destination, "gl_FrontColor");
3778         } else if (in_idx == in_count + 1) {
3779             sprintf(destination, "gl_FrontSecondaryColor");
3780         } else {
3781             sprintf(destination, "IN[%u]", in_idx);
3782         }
3783
3784         semantic_name_in = input_signature[i].semantic_name;
3785         semantic_idx_in = input_signature[i].semantic_idx;
3786         set[in_idx] = ~0U;
3787
3788         output_map = reg_maps_out->output_registers;
3789         for (j = 0; output_map; output_map >>= 1, ++j)
3790         {
3791             DWORD mask;
3792
3793             if (!(output_map & 1)
3794                     || semantic_idx_in != output_signature[j].semantic_idx
3795                     || strcmp(semantic_name_in, output_signature[j].semantic_name)
3796                     || !(mask = input_signature[i].mask & output_signature[j].mask))
3797                 continue;
3798
3799             set[in_idx] = mask;
3800             shader_glsl_write_mask_to_str(mask, reg_mask);
3801
3802             shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3803                     destination, reg_mask, j, reg_mask);
3804         }
3805     }
3806
3807     for (i = 0; i < in_count + 2; ++i)
3808     {
3809         unsigned int size;
3810
3811         if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3812             continue;
3813
3814         if (set[i] == ~0U) set[i] = 0;
3815
3816         size = 0;
3817         if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3818         if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3819         if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3820         if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3821         reg_mask[size] = '\0';
3822
3823         if (i == in_count) sprintf(destination, "gl_FrontColor");
3824         else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3825         else sprintf(destination, "IN[%u]", i);
3826
3827         if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3828         else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3829     }
3830
3831     HeapFree(GetProcessHeap(), 0, set);
3832 }
3833
3834 /* GL locking is done by the caller */
3835 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3836         const struct wined3d_shader *vs, const struct wined3d_shader *ps,
3837         const struct wined3d_gl_info *gl_info)
3838 {
3839     GLhandleARB ret = 0;
3840     DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
3841     unsigned int i;
3842     const char *semantic_name;
3843     UINT semantic_idx;
3844     char reg_mask[6];
3845     const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
3846     WORD map = vs->reg_maps.output_registers;
3847
3848     shader_buffer_clear(buffer);
3849
3850     shader_addline(buffer, "#version 120\n");
3851
3852     if (ps_major < 3)
3853     {
3854         shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3855
3856         for (i = 0; map; map >>= 1, ++i)
3857         {
3858             DWORD write_mask;
3859
3860             if (!(map & 1)) continue;
3861
3862             semantic_name = output_signature[i].semantic_name;
3863             semantic_idx = output_signature[i].semantic_idx;
3864             write_mask = output_signature[i].mask;
3865             shader_glsl_write_mask_to_str(write_mask, reg_mask);
3866
3867             if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3868             {
3869                 if (!semantic_idx)
3870                     shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n",
3871                             reg_mask, i, reg_mask);
3872                 else if (semantic_idx == 1)
3873                     shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n",
3874                             reg_mask, i, reg_mask);
3875             }
3876             else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3877             {
3878                 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3879                         reg_mask, i, reg_mask);
3880             }
3881             else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3882             {
3883                 if (semantic_idx < 8)
3884                 {
3885                     if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3886                         write_mask |= WINED3DSP_WRITEMASK_3;
3887
3888                     shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3889                             semantic_idx, reg_mask, i, reg_mask);
3890                     if (!(write_mask & WINED3DSP_WRITEMASK_3))
3891                         shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3892                 }
3893             }
3894             else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3895             {
3896                 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3897             }
3898             else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3899             {
3900                 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3901             }
3902         }
3903         shader_addline(buffer, "}\n");
3904
3905     }
3906     else
3907     {
3908         /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3909         shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3910         shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3911
3912         /* First, sort out position and point size. Those are not passed to the pixel shader */
3913         for (i = 0; map; map >>= 1, ++i)
3914         {
3915             if (!(map & 1)) continue;
3916
3917             semantic_name = output_signature[i].semantic_name;
3918             shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3919
3920             if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3921             {
3922                 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3923                         reg_mask, i, reg_mask);
3924             }
3925             else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3926             {
3927                 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3928             }
3929         }
3930
3931         /* Then, fix the pixel shader input */
3932         handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
3933                 &ps->reg_maps, output_signature, &vs->reg_maps);
3934
3935         shader_addline(buffer, "}\n");
3936     }
3937
3938     ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3939     checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3940     shader_glsl_compile(gl_info, ret, buffer->buffer);
3941
3942     return ret;
3943 }
3944
3945 /* GL locking is done by the caller */
3946 static void hardcode_local_constants(const struct wined3d_shader *shader,
3947         const struct wined3d_gl_info *gl_info, GLhandleARB programId, char prefix)
3948 {
3949     const struct wined3d_shader_lconst *lconst;
3950     GLint tmp_loc;
3951     const float *value;
3952     char glsl_name[8];
3953
3954     LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
3955     {
3956         value = (const float *)lconst->value;
3957         snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3958         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3959         GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3960     }
3961     checkGLcall("Hardcoding local constants");
3962 }
3963
3964 /* GL locking is done by the caller */
3965 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3966         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
3967         const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3968 {
3969     const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
3970     const struct wined3d_gl_info *gl_info = context->gl_info;
3971     const DWORD *function = shader->function;
3972     struct shader_glsl_ctx_priv priv_ctx;
3973
3974     /* Create the hw GLSL shader object and assign it as the shader->prgId */
3975     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3976
3977     memset(&priv_ctx, 0, sizeof(priv_ctx));
3978     priv_ctx.cur_ps_args = args;
3979     priv_ctx.cur_np2fixup_info = np2fixup_info;
3980
3981     shader_addline(buffer, "#version 120\n");
3982
3983     if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
3984     {
3985         shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3986     }
3987     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3988     {
3989         /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3990          * drivers write a warning if we don't do so
3991          */
3992         shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3993     }
3994     if (gl_info->supported[EXT_GPU_SHADER4])
3995     {
3996         shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3997     }
3998
3999     /* Base Declarations */
4000     shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4001
4002     /* Pack 3.0 inputs */
4003     if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4004         shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4005
4006     /* Base Shader Body */
4007     shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4008
4009     /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4010     if (reg_maps->shader_version.major < 2)
4011     {
4012         /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4013         shader_addline(buffer, "gl_FragData[0] = R0;\n");
4014     }
4015
4016     if (args->srgb_correction)
4017     {
4018         shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4019         shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4020         shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4021         shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4022         shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4023         shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4024     }
4025     /* Pixel shader < 3.0 do not replace the fog stage.
4026      * This implements linear fog computation and blending.
4027      * TODO: non linear fog
4028      * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4029      * -1/(e-s) and e/(e-s) respectively.
4030      */
4031     if (reg_maps->shader_version.major < 3)
4032     {
4033         switch(args->fog) {
4034             case FOG_OFF: break;
4035             case FOG_LINEAR:
4036                 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4037                 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4038                 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4039                 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4040                 break;
4041             case FOG_EXP:
4042                 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4043                 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4044                 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4045                 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4046                 break;
4047             case FOG_EXP2:
4048                 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4049                 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4050                 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4051                 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4052                 break;
4053         }
4054     }
4055
4056     shader_addline(buffer, "}\n");
4057
4058     TRACE("Compiling shader object %u\n", shader_obj);
4059     shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4060
4061     /* Store the shader object */
4062     return shader_obj;
4063 }
4064
4065 /* GL locking is done by the caller */
4066 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4067         struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4068         const struct vs_compile_args *args)
4069 {
4070     const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4071     const struct wined3d_gl_info *gl_info = context->gl_info;
4072     const DWORD *function = shader->function;
4073     struct shader_glsl_ctx_priv priv_ctx;
4074
4075     /* Create the hw GLSL shader program and assign it as the shader->prgId */
4076     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4077
4078     shader_addline(buffer, "#version 120\n");
4079
4080     if (gl_info->supported[EXT_GPU_SHADER4])
4081         shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4082
4083     memset(&priv_ctx, 0, sizeof(priv_ctx));
4084     priv_ctx.cur_vs_args = args;
4085
4086     /* Base Declarations */
4087     shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4088
4089     /* Base Shader Body */
4090     shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4091
4092     /* Unpack outputs */
4093     shader_addline(buffer, "order_ps_input(OUT);\n");
4094
4095     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4096      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4097      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4098      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4099      */
4100     if (args->fog_src == VS_FOG_Z)
4101         shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4102     else if (!reg_maps->fog)
4103         shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4104
4105     /* We always store the clipplanes without y inversion */
4106     if (args->clip_enabled)
4107         shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4108
4109     /* Write the final position.
4110      *
4111      * OpenGL coordinates specify the center of the pixel while d3d coords specify
4112      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4113      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4114      * contains 1.0 to allow a mad.
4115      */
4116     shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4117     shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4118
4119     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4120      *
4121      * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4122      * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4123      * which is the same as z = z * 2 - w.
4124      */
4125     shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4126
4127     shader_addline(buffer, "}\n");
4128
4129     TRACE("Compiling shader object %u\n", shader_obj);
4130     shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4131
4132     return shader_obj;
4133 }
4134
4135 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4136         struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4137         const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4138 {
4139     struct wined3d_state *state = &shader->device->stateBlock->state;
4140     UINT i;
4141     DWORD new_size;
4142     struct glsl_ps_compiled_shader *new_array;
4143     struct glsl_pshader_private    *shader_data;
4144     struct ps_np2fixup_info        *np2fixup = NULL;
4145     GLhandleARB ret;
4146
4147     if (!shader->backend_data)
4148     {
4149         shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4150         if (!shader->backend_data)
4151         {
4152             ERR("Failed to allocate backend data.\n");
4153             return 0;
4154         }
4155     }
4156     shader_data = shader->backend_data;
4157
4158     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4159      * so a linear search is more performant than a hashmap or a binary search
4160      * (cache coherency etc)
4161      */
4162     for (i = 0; i < shader_data->num_gl_shaders; ++i)
4163     {
4164         if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4165         {
4166             if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4167             return shader_data->gl_shaders[i].prgId;
4168         }
4169     }
4170
4171     TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4172     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4173         if (shader_data->num_gl_shaders)
4174         {
4175             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4176             new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4177                                     new_size * sizeof(*shader_data->gl_shaders));
4178         } else {
4179             new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4180             new_size = 1;
4181         }
4182
4183         if(!new_array) {
4184             ERR("Out of memory\n");
4185             return 0;
4186         }
4187         shader_data->gl_shaders = new_array;
4188         shader_data->shader_array_size = new_size;
4189     }
4190
4191     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4192
4193     memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4194     if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4195
4196     pixelshader_update_samplers(&shader->reg_maps, state->textures);
4197
4198     shader_buffer_clear(buffer);
4199     ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4200     shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4201     *np2fixup_info = np2fixup;
4202
4203     return ret;
4204 }
4205
4206 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4207                                  const DWORD use_map) {
4208     if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4209     if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4210     return stored->fog_src == new->fog_src;
4211 }
4212
4213 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4214         struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4215         const struct vs_compile_args *args)
4216 {
4217     UINT i;
4218     DWORD new_size;
4219     struct glsl_vs_compiled_shader *new_array;
4220     DWORD use_map = shader->device->strided_streams.use_map;
4221     struct glsl_vshader_private *shader_data;
4222     GLhandleARB ret;
4223
4224     if (!shader->backend_data)
4225     {
4226         shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4227         if (!shader->backend_data)
4228         {
4229             ERR("Failed to allocate backend data.\n");
4230             return 0;
4231         }
4232     }
4233     shader_data = shader->backend_data;
4234
4235     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4236      * so a linear search is more performant than a hashmap or a binary search
4237      * (cache coherency etc)
4238      */
4239     for(i = 0; i < shader_data->num_gl_shaders; i++) {
4240         if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4241             return shader_data->gl_shaders[i].prgId;
4242         }
4243     }
4244
4245     TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4246
4247     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4248         if (shader_data->num_gl_shaders)
4249         {
4250             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4251             new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4252                                     new_size * sizeof(*shader_data->gl_shaders));
4253         } else {
4254             new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4255             new_size = 1;
4256         }
4257
4258         if(!new_array) {
4259             ERR("Out of memory\n");
4260             return 0;
4261         }
4262         shader_data->gl_shaders = new_array;
4263         shader_data->shader_array_size = new_size;
4264     }
4265
4266     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4267
4268     shader_buffer_clear(buffer);
4269     ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4270     shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4271
4272     return ret;
4273 }
4274
4275 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4276  * It sets the programId on the current StateBlock (because it should be called
4277  * inside of the DrawPrimitive() part of the render loop).
4278  *
4279  * If a program for the given combination does not exist, create one, and store
4280  * the program in the hash table.  If it creates a program, it will link the
4281  * given objects, too.
4282  */
4283
4284 /* GL locking is done by the caller */
4285 static void set_glsl_shader_program(const struct wined3d_context *context,
4286         struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4287 {
4288     const struct wined3d_state *state = &device->stateBlock->state;
4289     struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4290     struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4291     const struct wined3d_gl_info *gl_info = context->gl_info;
4292     struct shader_glsl_priv *priv = device->shader_priv;
4293     struct glsl_shader_prog_link *entry    = NULL;
4294     GLhandleARB programId                  = 0;
4295     GLhandleARB reorder_shader_id          = 0;
4296     unsigned int i;
4297     char glsl_name[8];
4298     struct ps_compile_args ps_compile_args;
4299     struct vs_compile_args vs_compile_args;
4300
4301     if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4302     if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4303
4304     entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4305     if (entry)
4306     {
4307         priv->glsl_program = entry;
4308         return;
4309     }
4310
4311     /* If we get to this point, then no matching program exists, so we create one */
4312     programId = GL_EXTCALL(glCreateProgramObjectARB());
4313     TRACE("Created new GLSL shader program %u\n", programId);
4314
4315     /* Create the entry */
4316     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4317     entry->programId = programId;
4318     entry->vshader = vshader;
4319     entry->pshader = pshader;
4320     entry->vs_args = vs_compile_args;
4321     entry->ps_args = ps_compile_args;
4322     entry->constant_version = 0;
4323     entry->np2Fixup_info = NULL;
4324     /* Add the hash table entry */
4325     add_glsl_program_entry(priv, entry);
4326
4327     /* Set the current program */
4328     priv->glsl_program = entry;
4329
4330     /* Attach GLSL vshader */
4331     if (vshader)
4332     {
4333         GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4334         WORD map = vshader->reg_maps.input_registers;
4335         char tmp_name[10];
4336
4337         reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4338         TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4339         GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4340         checkGLcall("glAttachObjectARB");
4341         /* Flag the reorder function for deletion, then it will be freed automatically when the program
4342          * is destroyed
4343          */
4344         GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4345
4346         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4347         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4348         checkGLcall("glAttachObjectARB");
4349
4350         /* Bind vertex attributes to a corresponding index number to match
4351          * the same index numbers as ARB_vertex_programs (makes loading
4352          * vertex attributes simpler).  With this method, we can use the
4353          * exact same code to load the attributes later for both ARB and
4354          * GLSL shaders.
4355          *
4356          * We have to do this here because we need to know the Program ID
4357          * in order to make the bindings work, and it has to be done prior
4358          * to linking the GLSL program. */
4359         for (i = 0; map; map >>= 1, ++i)
4360         {
4361             if (!(map & 1)) continue;
4362
4363             snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4364             GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4365         }
4366         checkGLcall("glBindAttribLocationARB");
4367
4368         list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4369     }
4370
4371     /* Attach GLSL pshader */
4372     if (pshader)
4373     {
4374         GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4375                 pshader, &ps_compile_args, &entry->np2Fixup_info);
4376         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4377         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4378         checkGLcall("glAttachObjectARB");
4379
4380         list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4381     }
4382
4383     /* Link the program */
4384     TRACE("Linking GLSL shader program %u\n", programId);
4385     GL_EXTCALL(glLinkProgramARB(programId));
4386     shader_glsl_validate_link(gl_info, programId);
4387
4388     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4389             sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4390     for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4391     {
4392         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4393         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4394     }
4395     for (i = 0; i < MAX_CONST_I; ++i)
4396     {
4397         snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4398         entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4399     }
4400     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4401             sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4402     for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4403     {
4404         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4405         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4406     }
4407     for (i = 0; i < MAX_CONST_I; ++i)
4408     {
4409         snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4410         entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4411     }
4412
4413     if(pshader) {
4414         char name[32];
4415
4416         for(i = 0; i < MAX_TEXTURES; i++) {
4417             sprintf(name, "bumpenvmat%u", i);
4418             entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4419             sprintf(name, "luminancescale%u", i);
4420             entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4421             sprintf(name, "luminanceoffset%u", i);
4422             entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4423         }
4424
4425         if (ps_compile_args.np2_fixup) {
4426             if (entry->np2Fixup_info) {
4427                 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4428             } else {
4429                 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4430             }
4431         }
4432     }
4433
4434     entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4435     entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4436     checkGLcall("Find glsl program uniform locations");
4437
4438     if (pshader && pshader->reg_maps.shader_version.major >= 3
4439             && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4440     {
4441         TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4442         entry->vertex_color_clamp = GL_FALSE;
4443     } else {
4444         entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4445     }
4446
4447     /* Set the shader to allow uniform loading on it */
4448     GL_EXTCALL(glUseProgramObjectARB(programId));
4449     checkGLcall("glUseProgramObjectARB(programId)");
4450
4451     /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4452      * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4453      * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4454      * vertex shader with fixed function pixel processing is used we make sure that the card
4455      * supports enough samplers to allow the max number of vertex samplers with all possible
4456      * fixed function fragment processing setups. So once the program is linked these samplers
4457      * won't change.
4458      */
4459     if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4460     if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4461
4462     /* If the local constants do not have to be loaded with the environment constants,
4463      * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4464      * later
4465      */
4466     if (pshader && !pshader->load_local_constsF)
4467         hardcode_local_constants(pshader, gl_info, programId, 'P');
4468     if (vshader && !vshader->load_local_constsF)
4469         hardcode_local_constants(vshader, gl_info, programId, 'V');
4470 }
4471
4472 /* GL locking is done by the caller */
4473 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4474 {
4475     GLhandleARB program_id;
4476     GLhandleARB vshader_id, pshader_id;
4477     const char *blt_pshader;
4478
4479     static const char *blt_vshader =
4480         "#version 120\n"
4481         "void main(void)\n"
4482         "{\n"
4483         "    gl_Position = gl_Vertex;\n"
4484         "    gl_FrontColor = vec4(1.0);\n"
4485         "    gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4486         "}\n";
4487
4488     static const char * const blt_pshaders_full[tex_type_count] =
4489     {
4490         /* tex_1d */
4491         NULL,
4492         /* tex_2d */
4493         "#version 120\n"
4494         "uniform sampler2D sampler;\n"
4495         "void main(void)\n"
4496         "{\n"
4497         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4498         "}\n",
4499         /* tex_3d */
4500         NULL,
4501         /* tex_cube */
4502         "#version 120\n"
4503         "uniform samplerCube sampler;\n"
4504         "void main(void)\n"
4505         "{\n"
4506         "    gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4507         "}\n",
4508         /* tex_rect */
4509         "#version 120\n"
4510         "#extension GL_ARB_texture_rectangle : enable\n"
4511         "uniform sampler2DRect sampler;\n"
4512         "void main(void)\n"
4513         "{\n"
4514         "    gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4515         "}\n",
4516     };
4517
4518     static const char * const blt_pshaders_masked[tex_type_count] =
4519     {
4520         /* tex_1d */
4521         NULL,
4522         /* tex_2d */
4523         "#version 120\n"
4524         "uniform sampler2D sampler;\n"
4525         "uniform vec4 mask;\n"
4526         "void main(void)\n"
4527         "{\n"
4528         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4529         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4530         "}\n",
4531         /* tex_3d */
4532         NULL,
4533         /* tex_cube */
4534         "#version 120\n"
4535         "uniform samplerCube sampler;\n"
4536         "uniform vec4 mask;\n"
4537         "void main(void)\n"
4538         "{\n"
4539         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4540         "    gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4541         "}\n",
4542         /* tex_rect */
4543         "#version 120\n"
4544         "#extension GL_ARB_texture_rectangle : enable\n"
4545         "uniform sampler2DRect sampler;\n"
4546         "uniform vec4 mask;\n"
4547         "void main(void)\n"
4548         "{\n"
4549         "    if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4550         "    gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4551         "}\n",
4552     };
4553
4554     blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4555     if (!blt_pshader)
4556     {
4557         FIXME("tex_type %#x not supported\n", tex_type);
4558         return 0;
4559     }
4560
4561     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4562     shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4563
4564     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4565     shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4566
4567     program_id = GL_EXTCALL(glCreateProgramObjectARB());
4568     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4569     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4570     GL_EXTCALL(glLinkProgramARB(program_id));
4571
4572     shader_glsl_validate_link(gl_info, program_id);
4573
4574     /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4575      * is destroyed
4576      */
4577     GL_EXTCALL(glDeleteObjectARB(vshader_id));
4578     GL_EXTCALL(glDeleteObjectARB(pshader_id));
4579     return program_id;
4580 }
4581
4582 /* GL locking is done by the caller */
4583 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4584 {
4585     const struct wined3d_gl_info *gl_info = context->gl_info;
4586     struct wined3d_device *device = context->swapchain->device;
4587     struct shader_glsl_priv *priv = device->shader_priv;
4588     GLhandleARB program_id = 0;
4589     GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4590
4591     old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4592
4593     if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4594     else priv->glsl_program = NULL;
4595
4596     current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4597
4598     if (old_vertex_color_clamp != current_vertex_color_clamp)
4599     {
4600         if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4601         {
4602             GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4603             checkGLcall("glClampColorARB");
4604         }
4605         else
4606         {
4607             FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4608         }
4609     }
4610
4611     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4612     if (program_id) TRACE("Using GLSL program %u\n", program_id);
4613     GL_EXTCALL(glUseProgramObjectARB(program_id));
4614     checkGLcall("glUseProgramObjectARB");
4615
4616     /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4617      * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4618      * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4619     if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4620     {
4621         shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4622     }
4623 }
4624
4625 /* GL locking is done by the caller */
4626 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4627         enum tex_types tex_type, const SIZE *ds_mask_size)
4628 {
4629     BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4630     struct shader_glsl_priv *priv = shader_priv;
4631     GLhandleARB *blt_program;
4632     GLint loc;
4633
4634     blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4635     if (!*blt_program)
4636     {
4637         *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4638         loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4639         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4640         GL_EXTCALL(glUniform1iARB(loc, 0));
4641     }
4642     else
4643     {
4644         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4645     }
4646
4647     if (masked)
4648     {
4649         loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4650         GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4651     }
4652 }
4653
4654 /* GL locking is done by the caller */
4655 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4656 {
4657     struct shader_glsl_priv *priv = shader_priv;
4658     GLhandleARB program_id;
4659
4660     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4661     if (program_id) TRACE("Using GLSL program %u\n", program_id);
4662
4663     GL_EXTCALL(glUseProgramObjectARB(program_id));
4664     checkGLcall("glUseProgramObjectARB");
4665 }
4666
4667 static void shader_glsl_destroy(struct wined3d_shader *shader)
4668 {
4669     struct wined3d_device *device = shader->device;
4670     struct shader_glsl_priv *priv = device->shader_priv;
4671     const struct wined3d_gl_info *gl_info;
4672     const struct list *linked_programs;
4673     struct wined3d_context *context;
4674
4675     char pshader = shader_is_pshader_version(shader->reg_maps.shader_version.type);
4676
4677     if (pshader)
4678     {
4679         struct glsl_pshader_private *shader_data = shader->backend_data;
4680
4681         if (!shader_data || !shader_data->num_gl_shaders)
4682         {
4683             HeapFree(GetProcessHeap(), 0, shader_data);
4684             shader->backend_data = NULL;
4685             return;
4686         }
4687
4688         context = context_acquire(device, NULL);
4689         gl_info = context->gl_info;
4690
4691         if (priv->glsl_program && priv->glsl_program->pshader == shader)
4692         {
4693             ENTER_GL();
4694             shader_glsl_select(context, FALSE, FALSE);
4695             LEAVE_GL();
4696         }
4697     }
4698     else
4699     {
4700         struct glsl_vshader_private *shader_data = shader->backend_data;
4701
4702         if (!shader_data || !shader_data->num_gl_shaders)
4703         {
4704             HeapFree(GetProcessHeap(), 0, shader_data);
4705             shader->backend_data = NULL;
4706             return;
4707         }
4708
4709         context = context_acquire(device, NULL);
4710         gl_info = context->gl_info;
4711
4712         if (priv->glsl_program && priv->glsl_program->vshader == shader)
4713         {
4714             ENTER_GL();
4715             shader_glsl_select(context, FALSE, FALSE);
4716             LEAVE_GL();
4717         }
4718     }
4719
4720     linked_programs = &shader->linked_programs;
4721
4722     TRACE("Deleting linked programs\n");
4723     if (linked_programs->next) {
4724         struct glsl_shader_prog_link *entry, *entry2;
4725
4726         ENTER_GL();
4727         if(pshader) {
4728             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4729                 delete_glsl_program_entry(priv, gl_info, entry);
4730             }
4731         } else {
4732             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4733                 delete_glsl_program_entry(priv, gl_info, entry);
4734             }
4735         }
4736         LEAVE_GL();
4737     }
4738
4739     if (pshader)
4740     {
4741         struct glsl_pshader_private *shader_data = shader->backend_data;
4742         UINT i;
4743
4744         ENTER_GL();
4745         for(i = 0; i < shader_data->num_gl_shaders; i++) {
4746             TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4747             GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4748             checkGLcall("glDeleteObjectARB");
4749         }
4750         LEAVE_GL();
4751         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4752     }
4753     else
4754     {
4755         struct glsl_vshader_private *shader_data = shader->backend_data;
4756         UINT i;
4757
4758         ENTER_GL();
4759         for(i = 0; i < shader_data->num_gl_shaders; i++) {
4760             TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4761             GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4762             checkGLcall("glDeleteObjectARB");
4763         }
4764         LEAVE_GL();
4765         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4766     }
4767
4768     HeapFree(GetProcessHeap(), 0, shader->backend_data);
4769     shader->backend_data = NULL;
4770
4771     context_release(context);
4772 }
4773
4774 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4775 {
4776     const struct glsl_program_key *k = key;
4777     const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4778             const struct glsl_shader_prog_link, program_lookup_entry);
4779     int cmp;
4780
4781     if (k->vshader > prog->vshader) return 1;
4782     else if (k->vshader < prog->vshader) return -1;
4783
4784     if (k->pshader > prog->pshader) return 1;
4785     else if (k->pshader < prog->pshader) return -1;
4786
4787     if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4788     if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4789
4790     return 0;
4791 }
4792
4793 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4794 {
4795     SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4796     void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4797
4798     if (!mem)
4799     {
4800         ERR("Failed to allocate memory\n");
4801         return FALSE;
4802     }
4803
4804     heap->entries = mem;
4805     heap->entries[1].version = 0;
4806     heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4807     heap->size = 1;
4808
4809     return TRUE;
4810 }
4811
4812 static void constant_heap_free(struct constant_heap *heap)
4813 {
4814     HeapFree(GetProcessHeap(), 0, heap->entries);
4815 }
4816
4817 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4818 {
4819     wined3d_rb_alloc,
4820     wined3d_rb_realloc,
4821     wined3d_rb_free,
4822     glsl_program_key_compare,
4823 };
4824
4825 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
4826 {
4827     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4828     struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4829     SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4830             gl_info->limits.glsl_ps_float_constants)) + 1;
4831
4832     if (!shader_buffer_init(&priv->shader_buffer))
4833     {
4834         ERR("Failed to initialize shader buffer.\n");
4835         goto fail;
4836     }
4837
4838     priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4839     if (!priv->stack)
4840     {
4841         ERR("Failed to allocate memory.\n");
4842         goto fail;
4843     }
4844
4845     if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4846     {
4847         ERR("Failed to initialize vertex shader constant heap\n");
4848         goto fail;
4849     }
4850
4851     if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4852     {
4853         ERR("Failed to initialize pixel shader constant heap\n");
4854         goto fail;
4855     }
4856
4857     if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4858     {
4859         ERR("Failed to initialize rbtree.\n");
4860         goto fail;
4861     }
4862
4863     priv->next_constant_version = 1;
4864
4865     device->shader_priv = priv;
4866     return WINED3D_OK;
4867
4868 fail:
4869     constant_heap_free(&priv->pconst_heap);
4870     constant_heap_free(&priv->vconst_heap);
4871     HeapFree(GetProcessHeap(), 0, priv->stack);
4872     shader_buffer_free(&priv->shader_buffer);
4873     HeapFree(GetProcessHeap(), 0, priv);
4874     return E_OUTOFMEMORY;
4875 }
4876
4877 /* Context activation is done by the caller. */
4878 static void shader_glsl_free(struct wined3d_device *device)
4879 {
4880     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4881     struct shader_glsl_priv *priv = device->shader_priv;
4882     int i;
4883
4884     ENTER_GL();
4885     for (i = 0; i < tex_type_count; ++i)
4886     {
4887         if (priv->depth_blt_program_full[i])
4888         {
4889             GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4890         }
4891         if (priv->depth_blt_program_masked[i])
4892         {
4893             GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4894         }
4895     }
4896     LEAVE_GL();
4897
4898     wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4899     constant_heap_free(&priv->pconst_heap);
4900     constant_heap_free(&priv->vconst_heap);
4901     HeapFree(GetProcessHeap(), 0, priv->stack);
4902     shader_buffer_free(&priv->shader_buffer);
4903
4904     HeapFree(GetProcessHeap(), 0, device->shader_priv);
4905     device->shader_priv = NULL;
4906 }
4907
4908 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
4909
4910 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
4911 {
4912     if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_GEOMETRY_SHADER4]
4913             && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
4914     {
4915         caps->VertexShaderVersion = 4;
4916         caps->PixelShaderVersion = 4;
4917     }
4918     /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
4919      * texldd and texldl instructions. */
4920     else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
4921     {
4922         caps->VertexShaderVersion = 3;
4923         caps->PixelShaderVersion = 3;
4924     }
4925     else
4926     {
4927         caps->VertexShaderVersion = 2;
4928         caps->PixelShaderVersion = 2;
4929     }
4930
4931     caps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4932     caps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4933
4934     /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4935      * Direct3D minimum requirement.
4936      *
4937      * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4938      * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4939      *
4940      * The problem is that the refrast clamps temporary results in the shader to
4941      * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4942      * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4943      * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4944      * offer a way to query this.
4945      */
4946     caps->PixelShader1xMaxValue = 8.0;
4947
4948     caps->VSClipping = TRUE;
4949
4950     TRACE_(d3d_caps)("Hardware vertex shader version %u enabled (GLSL).\n",
4951             caps->VertexShaderVersion);
4952     TRACE_(d3d_caps)("Hardware pixel shader version %u enabled (GLSL).\n",
4953             caps->PixelShaderVersion);
4954 }
4955
4956 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4957 {
4958     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4959     {
4960         TRACE("Checking support for fixup:\n");
4961         dump_color_fixup_desc(fixup);
4962     }
4963
4964     /* We support everything except YUV conversions. */
4965     if (!is_complex_fixup(fixup))
4966     {
4967         TRACE("[OK]\n");
4968         return TRUE;
4969     }
4970
4971     TRACE("[FAILED]\n");
4972     return FALSE;
4973 }
4974
4975 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4976 {
4977     /* WINED3DSIH_ABS           */ shader_glsl_map2gl,
4978     /* WINED3DSIH_ADD           */ shader_glsl_arith,
4979     /* WINED3DSIH_AND           */ NULL,
4980     /* WINED3DSIH_BEM           */ shader_glsl_bem,
4981     /* WINED3DSIH_BREAK         */ shader_glsl_break,
4982     /* WINED3DSIH_BREAKC        */ shader_glsl_breakc,
4983     /* WINED3DSIH_BREAKP        */ NULL,
4984     /* WINED3DSIH_CALL          */ shader_glsl_call,
4985     /* WINED3DSIH_CALLNZ        */ shader_glsl_callnz,
4986     /* WINED3DSIH_CMP           */ shader_glsl_cmp,
4987     /* WINED3DSIH_CND           */ shader_glsl_cnd,
4988     /* WINED3DSIH_CRS           */ shader_glsl_cross,
4989     /* WINED3DSIH_CUT           */ NULL,
4990     /* WINED3DSIH_DCL           */ NULL,
4991     /* WINED3DSIH_DEF           */ NULL,
4992     /* WINED3DSIH_DEFB          */ NULL,
4993     /* WINED3DSIH_DEFI          */ NULL,
4994     /* WINED3DSIH_DIV           */ NULL,
4995     /* WINED3DSIH_DP2ADD        */ shader_glsl_dp2add,
4996     /* WINED3DSIH_DP3           */ shader_glsl_dot,
4997     /* WINED3DSIH_DP4           */ shader_glsl_dot,
4998     /* WINED3DSIH_DST           */ shader_glsl_dst,
4999     /* WINED3DSIH_DSX           */ shader_glsl_map2gl,
5000     /* WINED3DSIH_DSY           */ shader_glsl_map2gl,
5001     /* WINED3DSIH_ELSE          */ shader_glsl_else,
5002     /* WINED3DSIH_EMIT          */ NULL,
5003     /* WINED3DSIH_ENDIF         */ shader_glsl_end,
5004     /* WINED3DSIH_ENDLOOP       */ shader_glsl_end,
5005     /* WINED3DSIH_ENDREP        */ shader_glsl_end,
5006     /* WINED3DSIH_EXP           */ shader_glsl_map2gl,
5007     /* WINED3DSIH_EXPP          */ shader_glsl_expp,
5008     /* WINED3DSIH_FRC           */ shader_glsl_map2gl,
5009     /* WINED3DSIH_FTOI          */ NULL,
5010     /* WINED3DSIH_IADD          */ NULL,
5011     /* WINED3DSIH_IEQ           */ NULL,
5012     /* WINED3DSIH_IF            */ shader_glsl_if,
5013     /* WINED3DSIH_IFC           */ shader_glsl_ifc,
5014     /* WINED3DSIH_IGE           */ NULL,
5015     /* WINED3DSIH_IMUL          */ NULL,
5016     /* WINED3DSIH_ITOF          */ NULL,
5017     /* WINED3DSIH_LABEL         */ shader_glsl_label,
5018     /* WINED3DSIH_LD            */ NULL,
5019     /* WINED3DSIH_LIT           */ shader_glsl_lit,
5020     /* WINED3DSIH_LOG           */ shader_glsl_log,
5021     /* WINED3DSIH_LOGP          */ shader_glsl_log,
5022     /* WINED3DSIH_LOOP          */ shader_glsl_loop,
5023     /* WINED3DSIH_LRP           */ shader_glsl_lrp,
5024     /* WINED3DSIH_LT            */ NULL,
5025     /* WINED3DSIH_M3x2          */ shader_glsl_mnxn,
5026     /* WINED3DSIH_M3x3          */ shader_glsl_mnxn,
5027     /* WINED3DSIH_M3x4          */ shader_glsl_mnxn,
5028     /* WINED3DSIH_M4x3          */ shader_glsl_mnxn,
5029     /* WINED3DSIH_M4x4          */ shader_glsl_mnxn,
5030     /* WINED3DSIH_MAD           */ shader_glsl_mad,
5031     /* WINED3DSIH_MAX           */ shader_glsl_map2gl,
5032     /* WINED3DSIH_MIN           */ shader_glsl_map2gl,
5033     /* WINED3DSIH_MOV           */ shader_glsl_mov,
5034     /* WINED3DSIH_MOVA          */ shader_glsl_mov,
5035     /* WINED3DSIH_MOVC          */ NULL,
5036     /* WINED3DSIH_MUL           */ shader_glsl_arith,
5037     /* WINED3DSIH_NOP           */ NULL,
5038     /* WINED3DSIH_NRM           */ shader_glsl_nrm,
5039     /* WINED3DSIH_PHASE         */ NULL,
5040     /* WINED3DSIH_POW           */ shader_glsl_pow,
5041     /* WINED3DSIH_RCP           */ shader_glsl_rcp,
5042     /* WINED3DSIH_REP           */ shader_glsl_rep,
5043     /* WINED3DSIH_RET           */ shader_glsl_ret,
5044     /* WINED3DSIH_RSQ           */ shader_glsl_rsq,
5045     /* WINED3DSIH_SAMPLE        */ NULL,
5046     /* WINED3DSIH_SAMPLE_GRAD   */ NULL,
5047     /* WINED3DSIH_SAMPLE_LOD    */ NULL,
5048     /* WINED3DSIH_SETP          */ NULL,
5049     /* WINED3DSIH_SGE           */ shader_glsl_compare,
5050     /* WINED3DSIH_SGN           */ shader_glsl_sgn,
5051     /* WINED3DSIH_SINCOS        */ shader_glsl_sincos,
5052     /* WINED3DSIH_SLT           */ shader_glsl_compare,
5053     /* WINED3DSIH_SQRT          */ NULL,
5054     /* WINED3DSIH_SUB           */ shader_glsl_arith,
5055     /* WINED3DSIH_TEX           */ shader_glsl_tex,
5056     /* WINED3DSIH_TEXBEM        */ shader_glsl_texbem,
5057     /* WINED3DSIH_TEXBEML       */ shader_glsl_texbem,
5058     /* WINED3DSIH_TEXCOORD      */ shader_glsl_texcoord,
5059     /* WINED3DSIH_TEXDEPTH      */ shader_glsl_texdepth,
5060     /* WINED3DSIH_TEXDP3        */ shader_glsl_texdp3,
5061     /* WINED3DSIH_TEXDP3TEX     */ shader_glsl_texdp3tex,
5062     /* WINED3DSIH_TEXKILL       */ shader_glsl_texkill,
5063     /* WINED3DSIH_TEXLDD        */ shader_glsl_texldd,
5064     /* WINED3DSIH_TEXLDL        */ shader_glsl_texldl,
5065     /* WINED3DSIH_TEXM3x2DEPTH  */ shader_glsl_texm3x2depth,
5066     /* WINED3DSIH_TEXM3x2PAD    */ shader_glsl_texm3x2pad,
5067     /* WINED3DSIH_TEXM3x2TEX    */ shader_glsl_texm3x2tex,
5068     /* WINED3DSIH_TEXM3x3       */ shader_glsl_texm3x3,
5069     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
5070     /* WINED3DSIH_TEXM3x3PAD    */ shader_glsl_texm3x3pad,
5071     /* WINED3DSIH_TEXM3x3SPEC   */ shader_glsl_texm3x3spec,
5072     /* WINED3DSIH_TEXM3x3TEX    */ shader_glsl_texm3x3tex,
5073     /* WINED3DSIH_TEXM3x3VSPEC  */ shader_glsl_texm3x3vspec,
5074     /* WINED3DSIH_TEXREG2AR     */ shader_glsl_texreg2ar,
5075     /* WINED3DSIH_TEXREG2GB     */ shader_glsl_texreg2gb,
5076     /* WINED3DSIH_TEXREG2RGB    */ shader_glsl_texreg2rgb,
5077     /* WINED3DSIH_UTOF          */ NULL,
5078 };
5079
5080 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5081     SHADER_HANDLER hw_fct;
5082
5083     /* Select handler */
5084     hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5085
5086     /* Unhandled opcode */
5087     if (!hw_fct)
5088     {
5089         FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5090         return;
5091     }
5092     hw_fct(ins);
5093
5094     shader_glsl_add_instruction_modifiers(ins);
5095 }
5096
5097 const struct wined3d_shader_backend_ops glsl_shader_backend =
5098 {
5099     shader_glsl_handle_instruction,
5100     shader_glsl_select,
5101     shader_glsl_select_depth_blt,
5102     shader_glsl_deselect_depth_blt,
5103     shader_glsl_update_float_vertex_constants,
5104     shader_glsl_update_float_pixel_constants,
5105     shader_glsl_load_constants,
5106     shader_glsl_load_np2fixup_constants,
5107     shader_glsl_destroy,
5108     shader_glsl_alloc,
5109     shader_glsl_free,
5110     shader_glsl_context_destroyed,
5111     shader_glsl_get_caps,
5112     shader_glsl_color_fixup_supported,
5113 };