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