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