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