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