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