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