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