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