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