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