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