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