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