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