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