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