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