winealsa: Use "default" as the default card name instead of "default:0".
[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  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 /*
23  * D3D shader asm has swizzles on source parameters, and write masks for
24  * destination parameters. GLSL uses swizzles for both. The result of this is
25  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
26  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
27  * mask for the destination parameter into account.
28  */
29
30 #include "config.h"
31 #include <stdio.h>
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
36
37 #define GLINFO_LOCATION      (*gl_info)
38
39 typedef struct {
40     char reg_name[50];
41     char mask_str[6];
42 } glsl_dst_param_t;
43
44 typedef struct {
45     char reg_name[50];
46     char param_str[100];
47 } glsl_src_param_t;
48
49 typedef struct {
50     const char *name;
51     DWORD coord_mask;
52 } glsl_sample_function_t;
53
54 /** Prints the GLSL info log which will contain error messages if they exist */
55 void print_glsl_info_log(WineD3D_GL_Info *gl_info, GLhandleARB obj) {
56     
57     int infologLength = 0;
58     char *infoLog;
59     int i;
60     BOOL is_spam;
61
62     const char *spam[] = {
63         "Vertex shader was successfully compiled to run on hardware.\n",    /* fglrx        */
64         "Fragment shader was successfully compiled to run on hardware.\n",  /* fglrx        */
65         "Fragment shader(s) linked, vertex shader(s) linked.",              /* fglrx, no \n */
66         "Vertex shader(s) linked, no fragment shader(s) defined.",          /* fglrx, no \n */
67         "Fragment shader was successfully compiled to run on hardware.\nWARNING: 0:1: extension 'GL_ARB_draw_buffers' is not supported",
68         "Fragment shader(s) linked, no vertex shader(s) defined."           /* fglrx, no \n */
69     };
70
71     GL_EXTCALL(glGetObjectParameterivARB(obj,
72                GL_OBJECT_INFO_LOG_LENGTH_ARB,
73                &infologLength));
74
75     /* A size of 1 is just a null-terminated string, so the log should be bigger than
76      * that if there are errors. */
77     if (infologLength > 1)
78     {
79         /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
80          * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
81          */
82         infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
83         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
84         is_spam = FALSE;
85
86         for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
87             if(strcmp(infoLog, spam[i]) == 0) {
88                 is_spam = TRUE;
89                 break;
90             }
91         }
92         if(is_spam) {
93             TRACE("Spam received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
94         } else {
95             FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
96         }
97         HeapFree(GetProcessHeap(), 0, infoLog);
98     }
99 }
100
101 /**
102  * Loads (pixel shader) samplers
103  */
104 static void shader_glsl_load_psamplers(
105     WineD3D_GL_Info *gl_info,
106     IWineD3DStateBlock* iface,
107     GLhandleARB programId) {
108
109     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
110     GLhandleARB name_loc;
111     int i;
112     char sampler_name[20];
113
114     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
115         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
116         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
117         if (name_loc != -1) {
118             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
119             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
120                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
121                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
122                 checkGLcall("glUniform1iARB");
123             } else {
124                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
125             }
126         }
127     }
128 }
129
130 static void shader_glsl_load_vsamplers(WineD3D_GL_Info *gl_info, IWineD3DStateBlock* iface, GLhandleARB programId) {
131     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
132     GLhandleARB name_loc;
133     char sampler_name[20];
134     int i;
135
136     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
137         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
138         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
139         if (name_loc != -1) {
140             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
141             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
142                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
143                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
144                 checkGLcall("glUniform1iARB");
145             } else {
146                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
147             }
148         }
149     }
150 }
151
152 /** 
153  * Loads floating point constants (aka uniforms) into the currently set GLSL program.
154  * When constant_list == NULL, it will load all the constants.
155  */
156 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
157         unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
158         struct list *constant_list) {
159     constants_entry *constant;
160     local_constant* lconst;
161     GLhandleARB tmp_loc;
162     DWORD i, j, k;
163     DWORD *idx;
164
165     if (TRACE_ON(d3d_shader)) {
166         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
167             idx = constant->idx;
168             j = constant->count;
169             while (j--) {
170                 i = *idx++;
171                 tmp_loc = constant_locations[i];
172                 if (tmp_loc != -1) {
173                     TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
174                             constants[i * 4 + 0], constants[i * 4 + 1],
175                             constants[i * 4 + 2], constants[i * 4 + 3]);
176                 }
177             }
178         }
179     }
180
181     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
182     if(WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1 &&
183        shader_is_pshader_version(This->baseShader.hex_version)) {
184         float lcl_const[4];
185
186         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
187             idx = constant->idx;
188             j = constant->count;
189             while (j--) {
190                 i = *idx++;
191                 tmp_loc = constant_locations[i];
192                 if (tmp_loc != -1) {
193                     /* We found this uniform name in the program - go ahead and send the data */
194                     k = i * 4;
195                     if(constants[k + 0] < -1.0) lcl_const[0] = -1.0;
196                     else if(constants[k + 0] > 1.0) lcl_const[0] = 1.0;
197                     else lcl_const[0] = constants[k + 0];
198                     if(constants[k + 1] < -1.0) lcl_const[1] = -1.0;
199                     else if(constants[k + 1] > 1.0) lcl_const[1] = 1.0;
200                     else lcl_const[1] = constants[k + 1];
201                     if(constants[k + 2] < -1.0) lcl_const[2] = -1.0;
202                     else if(constants[k + 2] > 1.0) lcl_const[2] = 1.0;
203                     else lcl_const[2] = constants[k + 2];
204                     if(constants[k + 3] < -1.0) lcl_const[3] = -1.0;
205                     else if(constants[k + 3] > 1.0) lcl_const[3] = 1.0;
206                     else lcl_const[3] = constants[k + 3];
207
208                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, lcl_const));
209                 }
210             }
211         }
212     } else {
213         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
214             idx = constant->idx;
215             j = constant->count;
216             while (j--) {
217                 i = *idx++;
218                 tmp_loc = constant_locations[i];
219                 if (tmp_loc != -1) {
220                     /* We found this uniform name in the program - go ahead and send the data */
221                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
222                 }
223             }
224         }
225     }
226     checkGLcall("glUniform4fvARB()");
227
228     if(!This->baseShader.load_local_constsF) {
229         TRACE("No need to load local float constants for this shader\n");
230         return;
231     }
232
233     /* Load immediate constants */
234     if (TRACE_ON(d3d_shader)) {
235         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
236             tmp_loc = constant_locations[lconst->idx];
237             if (tmp_loc != -1) {
238                 GLfloat* values = (GLfloat*)lconst->value;
239                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
240                         values[0], values[1], values[2], values[3]);
241             }
242         }
243     }
244     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
245     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
246         tmp_loc = constant_locations[lconst->idx];
247         if (tmp_loc != -1) {
248             /* We found this uniform name in the program - go ahead and send the data */
249             GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
250         }
251     }
252     checkGLcall("glUniform4fvARB()");
253 }
254
255 /** 
256  * Loads integer constants (aka uniforms) into the currently set GLSL program.
257  * When @constants_set == NULL, it will load all the constants.
258  */
259 static void shader_glsl_load_constantsI(
260     IWineD3DBaseShaderImpl* This,
261     WineD3D_GL_Info *gl_info,
262     GLhandleARB programId,
263     GLhandleARB locations[MAX_CONST_I],
264     unsigned max_constants,
265     int* constants,
266     BOOL* constants_set) {
267     
268     int i;
269     struct list* ptr;
270
271     for (i=0; i<max_constants; ++i) {
272         if (NULL == constants_set || constants_set[i]) {
273
274             TRACE_(d3d_constants)("Loading constants %i: %i, %i, %i, %i\n",
275                   i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
276
277             /* We found this uniform name in the program - go ahead and send the data */
278             GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
279             checkGLcall("glUniform4ivARB");
280         }
281     }
282
283     /* Load immediate constants */
284     ptr = list_head(&This->baseShader.constantsI);
285     while (ptr) {
286         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
287         unsigned int idx = lconst->idx;
288         GLint* values = (GLint*) lconst->value;
289
290         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
291             values[0], values[1], values[2], values[3]);
292
293         /* We found this uniform name in the program - go ahead and send the data */
294         GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
295         checkGLcall("glUniform4ivARB");
296         ptr = list_next(&This->baseShader.constantsI, ptr);
297     }
298 }
299
300 /** 
301  * Loads boolean constants (aka uniforms) into the currently set GLSL program.
302  * When @constants_set == NULL, it will load all the constants.
303  */
304 static void shader_glsl_load_constantsB(
305     IWineD3DBaseShaderImpl* This,
306     WineD3D_GL_Info *gl_info,
307     GLhandleARB programId,
308     unsigned max_constants,
309     BOOL* constants,
310     BOOL* constants_set) {
311     
312     GLhandleARB tmp_loc;
313     int i;
314     char tmp_name[8];
315     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
316     const char* prefix = is_pshader? "PB":"VB";
317     struct list* ptr;
318
319     for (i=0; i<max_constants; ++i) {
320         if (NULL == constants_set || constants_set[i]) {
321
322             TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
323
324             /* TODO: Benchmark and see if it would be beneficial to store the 
325              * locations of the constants to avoid looking up each time */
326             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
327             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
328             if (tmp_loc != -1) {
329                 /* We found this uniform name in the program - go ahead and send the data */
330                 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
331                 checkGLcall("glUniform1ivARB");
332             }
333         }
334     }
335
336     /* Load immediate constants */
337     ptr = list_head(&This->baseShader.constantsB);
338     while (ptr) {
339         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
340         unsigned int idx = lconst->idx;
341         GLint* values = (GLint*) lconst->value;
342
343         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
344
345         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
346         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
347         if (tmp_loc != -1) {
348             /* We found this uniform name in the program - go ahead and send the data */
349             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
350             checkGLcall("glUniform1ivARB");
351         }
352         ptr = list_next(&This->baseShader.constantsB, ptr);
353     }
354 }
355
356
357
358 /**
359  * Loads the app-supplied constants into the currently set GLSL program.
360  */
361 void shader_glsl_load_constants(
362     IWineD3DDevice* device,
363     char usePixelShader,
364     char useVertexShader) {
365    
366     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
367     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
368     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
369
370     GLhandleARB *constant_locations;
371     struct list *constant_list;
372     GLhandleARB programId;
373     struct glsl_shader_prog_link *prog = stateBlock->glsl_program;
374
375     if (!prog) {
376         /* No GLSL program set - nothing to do. */
377         return;
378     }
379     programId = prog->programId;
380
381     if (useVertexShader) {
382         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
383
384         constant_locations = prog->vuniformF_locations;
385         constant_list = &stateBlock->set_vconstantsF;
386
387         /* Load DirectX 9 float constants/uniforms for vertex shader */
388         shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
389                 stateBlock->vertexShaderConstantF, constant_locations, constant_list);
390
391         /* Load DirectX 9 integer constants/uniforms for vertex shader */
392         shader_glsl_load_constantsI(vshader, gl_info, programId,
393                                     prog->vuniformI_locations, MAX_CONST_I,
394                                     stateBlock->vertexShaderConstantI,
395                                     stateBlock->changed.vertexShaderConstantsI);
396
397         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
398         shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
399                                     stateBlock->vertexShaderConstantB,
400                                     stateBlock->changed.vertexShaderConstantsB);
401
402         /* Upload the position fixup params */
403         GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
404         checkGLcall("glUniform4fvARB");
405     }
406
407     if (usePixelShader) {
408
409         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
410
411         constant_locations = prog->puniformF_locations;
412         constant_list = &stateBlock->set_pconstantsF;
413
414         /* Load DirectX 9 float constants/uniforms for pixel shader */
415         shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
416                 stateBlock->pixelShaderConstantF, constant_locations, constant_list);
417
418         /* Load DirectX 9 integer constants/uniforms for pixel shader */
419         shader_glsl_load_constantsI(pshader, gl_info, programId,
420                                     prog->puniformI_locations, MAX_CONST_I,
421                                     stateBlock->pixelShaderConstantI, 
422                                     stateBlock->changed.pixelShaderConstantsI);
423
424         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
425         shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
426                                     stateBlock->pixelShaderConstantB, 
427                                     stateBlock->changed.pixelShaderConstantsB);
428
429         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
430          * It can't be 0 for a valid texbem instruction.
431          */
432         if(((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat != -1) {
433             float *data = (float *) &stateBlock->textureState[(int) ((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat][WINED3DTSS_BUMPENVMAT00];
434             GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location, 1, 0, data));
435             checkGLcall("glUniformMatrix2fvARB");
436
437             /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
438              * is set too, so we can check that in the needsbumpmat check
439              */
440             if(((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams != -1) {
441                 int stage = ((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams;
442                 GLfloat *scale = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
443                 GLfloat *offset = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
444
445                 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location, 1, scale));
446                 checkGLcall("glUniform1fvARB");
447                 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location, 1, offset));
448                 checkGLcall("glUniform1fvARB");
449             }
450         } else if(((IWineD3DPixelShaderImpl *) pshader)->srgb_enabled &&
451                   !((IWineD3DPixelShaderImpl *) pshader)->srgb_mode_hardcoded) {
452             float comparison[4];
453             float mul_low[4];
454
455             if(stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
456                 comparison[0] = srgb_cmp; comparison[1] = srgb_cmp;
457                 comparison[2] = srgb_cmp; comparison[3] = srgb_cmp;
458
459                 mul_low[0] = srgb_mul_low; mul_low[1] = srgb_mul_low;
460                 mul_low[2] = srgb_mul_low; mul_low[3] = srgb_mul_low;
461             } else {
462                 comparison[0] = 1.0 / 0.0; comparison[1] = 1.0 / 0.0;
463                 comparison[2] = 1.0 / 0.0; comparison[3] = 1.0 / 0.0;
464
465                 mul_low[0] = 1.0; mul_low[1] = 1.0;
466                 mul_low[2] = 1.0; mul_low[3] = 1.0;
467             }
468
469             GL_EXTCALL(glUniform4fvARB(prog->srgb_comparison_location, 1, comparison));
470             GL_EXTCALL(glUniform4fvARB(prog->srgb_mul_low_location, 1, mul_low));
471         }
472         if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
473             float correction_params[4];
474             if(deviceImpl->render_offscreen) {
475                 correction_params[0] = 0.0;
476                 correction_params[1] = 1.0;
477             } else {
478                 /* position is window relative, not viewport relative */
479                 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
480                 correction_params[1] = -1.0;
481             }
482             GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
483         }
484     }
485 }
486
487 /** Generate the variable & register declarations for the GLSL output target */
488 void shader_generate_glsl_declarations(
489     IWineD3DBaseShader *iface,
490     shader_reg_maps* reg_maps,
491     SHADER_BUFFER* buffer,
492     WineD3D_GL_Info* gl_info) {
493
494     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
495     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
496     int i;
497     unsigned int extra_constants_needed = 0;
498     local_constant* lconst;
499
500     /* There are some minor differences between pixel and vertex shaders */
501     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
502     char prefix = pshader ? 'P' : 'V';
503
504     /* Prototype the subroutines */
505     for (i = 0; i < This->baseShader.limits.label; i++) {
506         if (reg_maps->labels[i])
507             shader_addline(buffer, "void subroutine%u();\n", i);
508     }
509
510     /* Declare the constants (aka uniforms) */
511     if (This->baseShader.limits.constant_float > 0) {
512         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
513                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
514         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
515     }
516
517     if (This->baseShader.limits.constant_int > 0)
518         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
519
520     if (This->baseShader.limits.constant_bool > 0)
521         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
522
523     if(!pshader) {
524         shader_addline(buffer, "uniform vec4 posFixup;\n");
525         /* Predeclaration; This function is added at link time based on the pixel shader.
526          * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
527          * that. We know the input to the reorder function at vertex shader compile time, so
528          * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
529          * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
530          * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
531          * it will write to the varying array. Here we depend on the shader optimizer on sorting that
532          * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
533          * inout.
534          */
535         if(This->baseShader.hex_version >= WINED3DVS_VERSION(3, 0)) {
536             shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
537         } else {
538             shader_addline(buffer, "void order_ps_input();\n");
539         }
540     } else {
541         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
542
543         if(reg_maps->bumpmat != -1) {
544             shader_addline(buffer, "uniform mat2 bumpenvmat;\n");
545             if(reg_maps->luminanceparams) {
546                 shader_addline(buffer, "uniform float luminancescale;\n");
547                 shader_addline(buffer, "uniform float luminanceoffset;\n");
548                 extra_constants_needed++;
549             }
550             extra_constants_needed++;
551         }
552
553         if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
554             ps_impl->srgb_enabled = 1;
555             if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
556                 shader_addline(buffer, "uniform vec4 srgb_mul_low;\n");
557                 shader_addline(buffer, "uniform vec4 srgb_comparison;\n");
558                 ps_impl->srgb_mode_hardcoded = 0;
559                 extra_constants_needed++;
560             } else {
561                 ps_impl->srgb_mode_hardcoded = 1;
562                 shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
563                                srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
564                 shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
565                                srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
566             }
567         } else {
568             IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
569
570             /* Do not write any srgb fixup into the shader to save shader size and processing time.
571              * As a consequence, we can't toggle srgb write on without recompilation
572              */
573             ps_impl->srgb_enabled = 0;
574             ps_impl->srgb_mode_hardcoded = 1;
575         }
576         if(reg_maps->vpos || reg_maps->usesdsy) {
577             if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
578                 shader_addline(buffer, "uniform vec4 ycorrection;\n");
579                 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
580                 extra_constants_needed++;
581             } else {
582                 /* This happens because we do not have proper tracking of the constant registers that are
583                  * actually used, only the max limit of the shader version
584                  */
585                 FIXME("Cannot find a free uniform for vpos correction params\n");
586                 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
587                                device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
588                                device->render_offscreen ? 1.0 : -1.0);
589             }
590             shader_addline(buffer, "vec4 vpos;\n");
591         }
592     }
593
594     /* Declare texture samplers */ 
595     for (i = 0; i < This->baseShader.limits.sampler; i++) {
596         if (reg_maps->samplers[i]) {
597
598             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
599             switch (stype) {
600
601                 case WINED3DSTT_1D:
602                     shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
603                     break;
604                 case WINED3DSTT_2D:
605                     if(device->stateBlock->textures[i] &&
606                        IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
607                         shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
608                     } else {
609                         shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
610                     }
611                     break;
612                 case WINED3DSTT_CUBE:
613                     shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
614                     break;
615                 case WINED3DSTT_VOLUME:
616                     shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
617                     break;
618                 default:
619                     shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
620                     FIXME("Unrecognized sampler type: %#x\n", stype);
621                     break;
622             }
623         }
624     }
625     
626     /* Declare address variables */
627     for (i = 0; i < This->baseShader.limits.address; i++) {
628         if (reg_maps->address[i])
629             shader_addline(buffer, "ivec4 A%d;\n", i);
630     }
631
632     /* Declare texture coordinate temporaries and initialize them */
633     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
634         if (reg_maps->texcoord[i]) 
635             shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
636     }
637
638     /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
639      * helper function shader that is linked in at link time
640      */
641     if(pshader && This->baseShader.hex_version >= WINED3DPS_VERSION(3, 0)) {
642         if(use_vs(device)) {
643             shader_addline(buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
644         } else {
645             /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
646              * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
647              * pixel shader that reads the fixed function color into the packed input registers.
648              */
649             shader_addline(buffer, "vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
650         }
651     }
652
653     /* Declare output register temporaries */
654     if(This->baseShader.limits.packed_output) {
655         shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
656     }
657
658     /* Declare temporary variables */
659     for(i = 0; i < This->baseShader.limits.temporary; i++) {
660         if (reg_maps->temporary[i])
661             shader_addline(buffer, "vec4 R%u;\n", i);
662     }
663
664     /* Declare attributes */
665     for (i = 0; i < This->baseShader.limits.attributes; i++) {
666         if (reg_maps->attributes[i])
667             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
668     }
669
670     /* Declare loop registers aLx */
671     for (i = 0; i < reg_maps->loop_depth; i++) {
672         shader_addline(buffer, "int aL%u;\n", i);
673         shader_addline(buffer, "int tmpInt%u;\n", i);
674     }
675
676     /* Temporary variables for matrix operations */
677     shader_addline(buffer, "vec4 tmp0;\n");
678     shader_addline(buffer, "vec4 tmp1;\n");
679
680     /* Hardcodable local constants */
681     if(!This->baseShader.load_local_constsF) {
682         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
683             float *value = (float *) lconst->value;
684             shader_addline(buffer, "const vec4 LC%u = vec4(%f, %f, %f, %f);\n", lconst->idx,
685                            value[0], value[1], value[2], value[3]);
686         }
687     }
688
689     /* Start the main program */
690     shader_addline(buffer, "void main() {\n");
691     if(pshader && reg_maps->vpos) {
692         shader_addline(buffer, "vpos = vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1) - 0.5;\n");
693     }
694 }
695
696 /*****************************************************************************
697  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
698  *
699  * For more information, see http://wiki.winehq.org/DirectX-Shaders
700  ****************************************************************************/
701
702 /* Prototypes */
703 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
704         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
705
706 /** Used for opcode modifiers - They multiply the result by the specified amount */
707 static const char * const shift_glsl_tab[] = {
708     "",           /*  0 (none) */ 
709     "2.0 * ",     /*  1 (x2)   */ 
710     "4.0 * ",     /*  2 (x4)   */ 
711     "8.0 * ",     /*  3 (x8)   */ 
712     "16.0 * ",    /*  4 (x16)  */ 
713     "32.0 * ",    /*  5 (x32)  */ 
714     "",           /*  6 (x64)  */ 
715     "",           /*  7 (x128) */ 
716     "",           /*  8 (d256) */ 
717     "",           /*  9 (d128) */ 
718     "",           /* 10 (d64)  */ 
719     "",           /* 11 (d32)  */ 
720     "0.0625 * ",  /* 12 (d16)  */ 
721     "0.125 * ",   /* 13 (d8)   */ 
722     "0.25 * ",    /* 14 (d4)   */ 
723     "0.5 * "      /* 15 (d2)   */ 
724 };
725
726 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
727 static void shader_glsl_gen_modifier (
728     const DWORD instr,
729     const char *in_reg,
730     const char *in_regswizzle,
731     char *out_str) {
732
733     out_str[0] = 0;
734     
735     if (instr == WINED3DSIO_TEXKILL)
736         return;
737
738     switch (instr & WINED3DSP_SRCMOD_MASK) {
739     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
740     case WINED3DSPSM_DW:
741     case WINED3DSPSM_NONE:
742         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
743         break;
744     case WINED3DSPSM_NEG:
745         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
746         break;
747     case WINED3DSPSM_NOT:
748         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
749         break;
750     case WINED3DSPSM_BIAS:
751         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
752         break;
753     case WINED3DSPSM_BIASNEG:
754         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
755         break;
756     case WINED3DSPSM_SIGN:
757         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
758         break;
759     case WINED3DSPSM_SIGNNEG:
760         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
761         break;
762     case WINED3DSPSM_COMP:
763         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
764         break;
765     case WINED3DSPSM_X2:
766         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
767         break;
768     case WINED3DSPSM_X2NEG:
769         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
770         break;
771     case WINED3DSPSM_ABS:
772         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
773         break;
774     case WINED3DSPSM_ABSNEG:
775         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
776         break;
777     default:
778         FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
779         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
780     }
781 }
782
783 /** Writes the GLSL variable name that corresponds to the register that the
784  * DX opcode parameter is trying to access */
785 static void shader_glsl_get_register_name(
786     const DWORD param,
787     const DWORD addr_token,
788     char* regstr,
789     BOOL* is_color,
790     SHADER_OPCODE_ARG* arg) {
791
792     /* oPos, oFog and oPts in D3D */
793     static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
794
795     DWORD reg = param & WINED3DSP_REGNUM_MASK;
796     DWORD regtype = shader_get_regtype(param);
797     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
798     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
799     WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
800
801     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
802     char tmpStr[50];
803
804     *is_color = FALSE;   
805  
806     switch (regtype) {
807     case WINED3DSPR_TEMP:
808         sprintf(tmpStr, "R%u", reg);
809     break;
810     case WINED3DSPR_INPUT:
811         if (pshader) {
812             /* Pixel shaders >= 3.0 */
813             if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3) {
814                 if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
815                     glsl_src_param_t rel_param;
816                     shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
817
818                     /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
819                      * operation there
820                      */
821                     if(((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]) {
822                         sprintf(tmpStr, "IN[%s + %u]", rel_param.param_str,
823                                 ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
824                     } else {
825                         sprintf(tmpStr, "IN[%s]", rel_param.param_str);
826                     }
827                 } else {
828                     sprintf(tmpStr, "IN[%u]",
829                             ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
830                 }
831             } else {
832                 if (reg==0)
833                     strcpy(tmpStr, "gl_Color");
834                 else
835                     strcpy(tmpStr, "gl_SecondaryColor");
836             }
837         } else {
838             if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
839                *is_color = TRUE;
840             sprintf(tmpStr, "attrib%u", reg);
841         } 
842         break;
843     case WINED3DSPR_CONST:
844     {
845         const char* prefix = pshader? "PC":"VC";
846
847         /* Relative addressing */
848         if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
849
850            /* Relative addressing on shaders 2.0+ have a relative address token, 
851             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
852            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
853                glsl_src_param_t rel_param;
854                shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
855                if(reg) {
856                    sprintf(tmpStr, "%s[%s + %u]", prefix, rel_param.param_str, reg);
857                } else {
858                    sprintf(tmpStr, "%s[%s]", prefix, rel_param.param_str);
859                }
860            } else {
861                if(reg) {
862                    sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
863                } else {
864                    sprintf(tmpStr, "%s[A0.x]", prefix);
865                }
866            }
867
868         } else {
869             if(shader_constant_is_local(This, reg)) {
870                 sprintf(tmpStr, "LC%u", reg);
871             } else {
872                 sprintf(tmpStr, "%s[%u]", prefix, reg);
873             }
874         }
875
876         break;
877     }
878     case WINED3DSPR_CONSTINT:
879         if (pshader)
880             sprintf(tmpStr, "PI[%u]", reg);
881         else
882             sprintf(tmpStr, "VI[%u]", reg);
883         break;
884     case WINED3DSPR_CONSTBOOL:
885         if (pshader)
886             sprintf(tmpStr, "PB[%u]", reg);
887         else
888             sprintf(tmpStr, "VB[%u]", reg);
889         break;
890     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
891         if (pshader) {
892             sprintf(tmpStr, "T%u", reg);
893         } else {
894             sprintf(tmpStr, "A%u", reg);
895         }
896     break;
897     case WINED3DSPR_LOOP:
898         sprintf(tmpStr, "aL%u", This->baseShader.cur_loop_regno - 1);
899     break;
900     case WINED3DSPR_SAMPLER:
901         if (pshader)
902             sprintf(tmpStr, "Psampler%u", reg);
903         else
904             sprintf(tmpStr, "Vsampler%u", reg);
905     break;
906     case WINED3DSPR_COLOROUT:
907         if (reg >= GL_LIMITS(buffers)) {
908             WARN("Write to render target %u, only %d supported\n", reg, 4);
909         }
910         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
911             sprintf(tmpStr, "gl_FragData[%u]", reg);
912         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
913             sprintf(tmpStr, "gl_FragColor");
914         }
915     break;
916     case WINED3DSPR_RASTOUT:
917         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
918     break;
919     case WINED3DSPR_DEPTHOUT:
920         sprintf(tmpStr, "gl_FragDepth");
921     break;
922     case WINED3DSPR_ATTROUT:
923         if (reg == 0) {
924             sprintf(tmpStr, "gl_FrontColor");
925         } else {
926             sprintf(tmpStr, "gl_FrontSecondaryColor");
927         }
928     break;
929     case WINED3DSPR_TEXCRDOUT:
930         /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
931         if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
932             sprintf(tmpStr, "OUT[%u]", reg);
933         else
934             sprintf(tmpStr, "gl_TexCoord[%u]", reg);
935     break;
936     case WINED3DSPR_MISCTYPE:
937         if (reg == 0) {
938             /* vPos */
939             sprintf(tmpStr, "vpos");
940         } else if (reg == 1){
941             /* Note that gl_FrontFacing is a bool, while vFace is
942              * a float for which the sign determines front/back
943              */
944             sprintf(tmpStr, "(gl_FrontFacing ? 1.0 : -1.0)");
945         } else {
946             FIXME("Unhandled misctype register %d\n", reg);
947             sprintf(tmpStr, "unrecognized_register");
948         }
949         break;
950     default:
951         FIXME("Unhandled register name Type(%d)\n", regtype);
952         sprintf(tmpStr, "unrecognized_register");
953     break;
954     }
955
956     strcat(regstr, tmpStr);
957 }
958
959 /* Get the GLSL write mask for the destination register */
960 static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
961     char *ptr = write_mask;
962     DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
963
964     if (shader_is_scalar(param)) {
965         mask = WINED3DSP_WRITEMASK_0;
966     } else {
967         *ptr++ = '.';
968         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
969         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
970         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
971         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
972     }
973
974     *ptr = '\0';
975
976     return mask;
977 }
978
979 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
980     unsigned int size = 0;
981
982     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
983     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
984     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
985     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
986
987     return size;
988 }
989
990 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
991     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
992      * but addressed as "rgba". To fix this we need to swap the register's x
993      * and z components. */
994     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
995     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
996     char *ptr = swizzle_str;
997
998     if (!shader_is_scalar(param)) {
999         *ptr++ = '.';
1000         /* swizzle bits fields: wwzzyyxx */
1001         if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
1002         if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
1003         if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
1004         if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
1005     }
1006
1007     *ptr = '\0';
1008 }
1009
1010 /* From a given parameter token, generate the corresponding GLSL string.
1011  * Also, return the actual register name and swizzle in case the
1012  * caller needs this information as well. */
1013 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
1014         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param) {
1015     BOOL is_color = FALSE;
1016     char swizzle_str[6];
1017
1018     src_param->reg_name[0] = '\0';
1019     src_param->param_str[0] = '\0';
1020     swizzle_str[0] = '\0';
1021
1022     shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
1023
1024     shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
1025     shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
1026 }
1027
1028 /* From a given parameter token, generate the corresponding GLSL string.
1029  * Also, return the actual register name and swizzle in case the
1030  * caller needs this information as well. */
1031 static DWORD shader_glsl_add_dst_param(SHADER_OPCODE_ARG* arg, const DWORD param,
1032         const DWORD addr_token, glsl_dst_param_t *dst_param) {
1033     BOOL is_color = FALSE;
1034
1035     dst_param->mask_str[0] = '\0';
1036     dst_param->reg_name[0] = '\0';
1037
1038     shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
1039     return shader_glsl_get_write_mask(param, dst_param->mask_str);
1040 }
1041
1042 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1043 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg, const DWORD param) {
1044     glsl_dst_param_t dst_param;
1045     DWORD mask;
1046     int shift;
1047
1048     mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);
1049
1050     if(mask) {
1051         shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1052         shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
1053     }
1054
1055     return mask;
1056 }
1057
1058 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1059 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg) {
1060     return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
1061 }
1062
1063 /** Process GLSL instruction modifiers */
1064 void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
1065     
1066     DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
1067  
1068     if (arg->opcode->dst_token && mask != 0) {
1069         glsl_dst_param_t dst_param;
1070
1071         shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1072
1073         if (mask & WINED3DSPDM_SATURATE) {
1074             /* _SAT means to clamp the value of the register to between 0 and 1 */
1075             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1076                     dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1077         }
1078         if (mask & WINED3DSPDM_MSAMPCENTROID) {
1079             FIXME("_centroid modifier not handled\n");
1080         }
1081         if (mask & WINED3DSPDM_PARTIALPRECISION) {
1082             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1083         }
1084     }
1085 }
1086
1087 static inline const char* shader_get_comp_op(
1088     const DWORD opcode) {
1089
1090     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
1091     switch (op) {
1092         case COMPARISON_GT: return ">";
1093         case COMPARISON_EQ: return "==";
1094         case COMPARISON_GE: return ">=";
1095         case COMPARISON_LT: return "<";
1096         case COMPARISON_NE: return "!=";
1097         case COMPARISON_LE: return "<=";
1098         default:
1099             FIXME("Unrecognized comparison value: %u\n", op);
1100             return "(\?\?)";
1101     }
1102 }
1103
1104 static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, BOOL texrect, glsl_sample_function_t *sample_function) {
1105     /* Note that there's no such thing as a projected cube texture. */
1106     switch(sampler_type) {
1107         case WINED3DSTT_1D:
1108             sample_function->name = projected ? "texture1DProj" : "texture1D";
1109             sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1110             break;
1111         case WINED3DSTT_2D:
1112             if(texrect) {
1113                 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1114             } else {
1115                 sample_function->name = projected ? "texture2DProj" : "texture2D";
1116             }
1117             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1118             break;
1119         case WINED3DSTT_CUBE:
1120             sample_function->name = "textureCube";
1121             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1122             break;
1123         case WINED3DSTT_VOLUME:
1124             sample_function->name = projected ? "texture3DProj" : "texture3D";
1125             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1126             break;
1127         default:
1128             sample_function->name = "";
1129             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1130             break;
1131     }
1132 }
1133
1134 static void shader_glsl_color_correction(SHADER_OPCODE_ARG* arg) {
1135     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1136     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) shader->baseShader.device;
1137     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
1138     glsl_dst_param_t dst_param;
1139     glsl_dst_param_t dst_param2;
1140     WINED3DFORMAT fmt;
1141     WINED3DFORMAT conversion_group;
1142     IWineD3DBaseTextureImpl *texture;
1143     DWORD mask, mask_size;
1144     UINT i;
1145     BOOL recorded = FALSE;
1146     DWORD sampler_idx;
1147     DWORD hex_version = shader->baseShader.hex_version;
1148
1149     switch(arg->opcode->opcode) {
1150         case WINED3DSIO_TEX:
1151             if (hex_version < WINED3DPS_VERSION(2,0)) {
1152                 sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1153             } else {
1154                 sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1155             }
1156             break;
1157
1158         case WINED3DSIO_TEXLDL:
1159             FIXME("Add color fixup for vertex texture WINED3DSIO_TEXLDL\n");
1160             return;
1161
1162         case WINED3DSIO_TEXDP3TEX:
1163         case WINED3DSIO_TEXM3x3TEX:
1164         case WINED3DSIO_TEXM3x3SPEC:
1165         case WINED3DSIO_TEXM3x3VSPEC:
1166         case WINED3DSIO_TEXBEM:
1167         case WINED3DSIO_TEXREG2AR:
1168         case WINED3DSIO_TEXREG2GB:
1169         case WINED3DSIO_TEXREG2RGB:
1170             sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1171             break;
1172
1173         default:
1174             /* Not a texture sampling instruction, nothing to do */
1175             return;
1176     };
1177
1178     texture = (IWineD3DBaseTextureImpl *) deviceImpl->stateBlock->textures[sampler_idx];
1179     if(texture) {
1180         fmt = texture->resource.format;
1181         conversion_group = texture->baseTexture.shader_conversion_group;
1182     } else {
1183         fmt = WINED3DFMT_UNKNOWN;
1184         conversion_group = WINED3DFMT_UNKNOWN;
1185     }
1186
1187     /* before doing anything, record the sampler with the format in the format conversion list,
1188      * but check if it's not there already
1189      */
1190     for(i = 0; i < shader->baseShader.num_sampled_samplers; i++) {
1191         if(shader->baseShader.sampled_samplers[i] == sampler_idx) {
1192             recorded = TRUE;
1193             break;
1194         }
1195     }
1196     if(!recorded) {
1197         shader->baseShader.sampled_samplers[shader->baseShader.num_sampled_samplers] = sampler_idx;
1198         shader->baseShader.num_sampled_samplers++;
1199         shader->baseShader.sampled_format[sampler_idx] = conversion_group;
1200     }
1201
1202     switch(fmt) {
1203         case WINED3DFMT_V8U8:
1204         case WINED3DFMT_V16U16:
1205             if(GL_SUPPORT(NV_TEXTURE_SHADER) ||
1206               (GL_SUPPORT(ATI_ENVMAP_BUMPMAP) && fmt == WINED3DFMT_V8U8)) {
1207                 /* The 3rd channel returns 1.0 in d3d, but 0.0 in gl. Fix this while we're at it :-) */
1208                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_2, &dst_param);
1209                 mask_size = shader_glsl_get_write_mask_size(mask);
1210                 if(mask_size >= 3) {
1211                     shader_addline(arg->buffer, "%s.%c = 1.0;\n", dst_param.reg_name, dst_param.mask_str[3]);
1212                 }
1213             } else {
1214                 /* Correct the sign, but leave the blue as it is - it was loaded correctly already */
1215                 mask = shader_glsl_add_dst_param(arg, arg->dst,
1216                                           WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1,
1217                                           &dst_param);
1218                 mask_size = shader_glsl_get_write_mask_size(mask);
1219                 if(mask_size >= 2) {
1220                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1221                     dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
1222                     dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
1223                 } else if(mask_size == 1) {
1224                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str[1],
1225                     dst_param.reg_name, dst_param.mask_str[1]);
1226                 }
1227             }
1228             break;
1229
1230         case WINED3DFMT_X8L8V8U8:
1231             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1232                 /* Red and blue are the signed channels, fix them up; Blue(=L) is correct already,
1233                  * and a(X) is always 1.0
1234                  */
1235                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
1236                 mask_size = shader_glsl_get_write_mask_size(mask);
1237                 if(mask_size >= 2) {
1238                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1239                                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
1240                                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
1241                 } else if(mask_size == 1) {
1242                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
1243                                    dst_param.reg_name, dst_param.mask_str[1],
1244                                    dst_param.reg_name, dst_param.mask_str[1]);
1245                 }
1246             }
1247             break;
1248
1249         case WINED3DFMT_L6V5U5:
1250             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1251                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
1252                 mask_size = shader_glsl_get_write_mask_size(mask);
1253                 shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_2, &dst_param2);
1254                 if(mask_size >= 3) {
1255                     /* Swap y and z (U and L), and do a sign conversion on x and the new y(V and U) */
1256                     shader_addline(arg->buffer, "tmp0.g = %s.%c;\n",
1257                                    dst_param.reg_name, dst_param.mask_str[2]);
1258                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1259                                    dst_param.reg_name, dst_param.mask_str[2], dst_param.mask_str[1],
1260                                    dst_param2.reg_name, dst_param.mask_str[1], dst_param.mask_str[3]);
1261                     shader_addline(arg->buffer, "%s.%c = tmp0.g;\n", dst_param.reg_name,
1262                                    dst_param.mask_str[3]);
1263                 } else if(mask_size == 2) {
1264                     /* This is bad: We have VL, but we need VU */
1265                     FIXME("2 components sampled from a converted L6V5U5 texture\n");
1266                 } else {
1267                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
1268                                    dst_param.reg_name, dst_param.mask_str[1],
1269                                    dst_param2.reg_name, dst_param.mask_str[1]);
1270                 }
1271             }
1272             break;
1273
1274         case WINED3DFMT_Q8W8V8U8:
1275             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1276                 /* Correct the sign in all channels. The writemask just applies as-is, no
1277                  * need for checking the mask size
1278                  */
1279                 shader_glsl_add_dst_param(arg, arg->dst,
1280                                           WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 |
1281                                           WINED3DSP_WRITEMASK_2 | WINED3DSP_WRITEMASK_3,
1282                                           &dst_param);
1283                 shader_addline(arg->buffer, "%s%s = %s%s * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str,
1284                                dst_param.reg_name, dst_param.mask_str);
1285             }
1286             break;
1287
1288             /* stupid compiler */
1289         default:
1290             break;
1291     }
1292 }
1293
1294 /*****************************************************************************
1295  * 
1296  * Begin processing individual instruction opcodes
1297  * 
1298  ****************************************************************************/
1299
1300 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1301 void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
1302     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1303     SHADER_BUFFER* buffer = arg->buffer;
1304     glsl_src_param_t src0_param;
1305     glsl_src_param_t src1_param;
1306     DWORD write_mask;
1307     char op;
1308
1309     /* Determine the GLSL operator to use based on the opcode */
1310     switch (curOpcode->opcode) {
1311         case WINED3DSIO_MUL: op = '*'; break;
1312         case WINED3DSIO_ADD: op = '+'; break;
1313         case WINED3DSIO_SUB: op = '-'; break;
1314         default:
1315             op = ' ';
1316             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1317             break;
1318     }
1319
1320     write_mask = shader_glsl_append_dst(buffer, arg);
1321     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1322     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1323     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1324 }
1325
1326 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1327 void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
1328     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1329     SHADER_BUFFER* buffer = arg->buffer;
1330     glsl_src_param_t src0_param;
1331     DWORD write_mask;
1332
1333     write_mask = shader_glsl_append_dst(buffer, arg);
1334     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1335
1336     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1337      * shader versions WINED3DSIO_MOVA is used for this. */
1338     if ((WINED3DSHADER_VERSION_MAJOR(shader->baseShader.hex_version) == 1 &&
1339             !shader_is_pshader_version(shader->baseShader.hex_version) &&
1340             shader_get_regtype(arg->dst) == WINED3DSPR_ADDR)) {
1341         /* This is a simple floor() */
1342         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1343         if (mask_size > 1) {
1344             shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1345         } else {
1346             shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1347         }
1348     } else if(arg->opcode->opcode == WINED3DSIO_MOVA) {
1349         /* We need to *round* to the nearest int here. */
1350         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1351         if (mask_size > 1) {
1352             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);
1353         } else {
1354             shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1355         }
1356     } else {
1357         shader_addline(buffer, "%s);\n", src0_param.param_str);
1358     }
1359 }
1360
1361 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1362 void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
1363     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1364     SHADER_BUFFER* buffer = arg->buffer;
1365     glsl_src_param_t src0_param;
1366     glsl_src_param_t src1_param;
1367     DWORD dst_write_mask, src_write_mask;
1368     unsigned int dst_size = 0;
1369
1370     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1371     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1372
1373     /* dp3 works on vec3, dp4 on vec4 */
1374     if (curOpcode->opcode == WINED3DSIO_DP4) {
1375         src_write_mask = WINED3DSP_WRITEMASK_ALL;
1376     } else {
1377         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1378     }
1379
1380     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
1381     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1382
1383     if (dst_size > 1) {
1384         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1385     } else {
1386         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1387     }
1388 }
1389
1390 /* Note that this instruction has some restrictions. The destination write mask
1391  * can't contain the w component, and the source swizzles have to be .xyzw */
1392 void shader_glsl_cross(SHADER_OPCODE_ARG *arg) {
1393     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1394     glsl_src_param_t src0_param;
1395     glsl_src_param_t src1_param;
1396     char dst_mask[6];
1397
1398     shader_glsl_get_write_mask(arg->dst, dst_mask);
1399     shader_glsl_append_dst(arg->buffer, arg);
1400     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1401     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1402     shader_addline(arg->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1403 }
1404
1405 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1406  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1407  * GLSL uses the value as-is. */
1408 void shader_glsl_pow(SHADER_OPCODE_ARG *arg) {
1409     SHADER_BUFFER *buffer = arg->buffer;
1410     glsl_src_param_t src0_param;
1411     glsl_src_param_t src1_param;
1412     DWORD dst_write_mask;
1413     unsigned int dst_size;
1414
1415     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1416     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1417
1418     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1419     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1420
1421     if (dst_size > 1) {
1422         shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1423     } else {
1424         shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1425     }
1426 }
1427
1428 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1429  * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1430  * GLSL uses the value as-is. */
1431 void shader_glsl_log(SHADER_OPCODE_ARG *arg) {
1432     SHADER_BUFFER *buffer = arg->buffer;
1433     glsl_src_param_t src0_param;
1434     DWORD dst_write_mask;
1435     unsigned int dst_size;
1436
1437     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1438     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1439
1440     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1441
1442     if (dst_size > 1) {
1443         shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1444     } else {
1445         shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1446     }
1447 }
1448
1449 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1450 void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
1451     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1452     SHADER_BUFFER* buffer = arg->buffer;
1453     glsl_src_param_t src_param;
1454     const char *instruction;
1455     char arguments[256];
1456     DWORD write_mask;
1457     unsigned i;
1458
1459     /* Determine the GLSL function to use based on the opcode */
1460     /* TODO: Possibly make this a table for faster lookups */
1461     switch (curOpcode->opcode) {
1462         case WINED3DSIO_MIN: instruction = "min"; break;
1463         case WINED3DSIO_MAX: instruction = "max"; break;
1464         case WINED3DSIO_ABS: instruction = "abs"; break;
1465         case WINED3DSIO_FRC: instruction = "fract"; break;
1466         case WINED3DSIO_NRM: instruction = "normalize"; break;
1467         case WINED3DSIO_LOGP:
1468         case WINED3DSIO_LOG: instruction = "log2"; break;
1469         case WINED3DSIO_EXP: instruction = "exp2"; break;
1470         case WINED3DSIO_SGN: instruction = "sign"; break;
1471         case WINED3DSIO_DSX: instruction = "dFdx"; break;
1472         case WINED3DSIO_DSY: instruction = "ycorrection.y * dFdy"; break;
1473         default: instruction = "";
1474             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1475             break;
1476     }
1477
1478     write_mask = shader_glsl_append_dst(buffer, arg);
1479
1480     arguments[0] = '\0';
1481     if (curOpcode->num_params > 0) {
1482         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
1483         strcat(arguments, src_param.param_str);
1484         for (i = 2; i < curOpcode->num_params; ++i) {
1485             strcat(arguments, ", ");
1486             shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
1487             strcat(arguments, src_param.param_str);
1488         }
1489     }
1490
1491     shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1492 }
1493
1494 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1495  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1496  *   dst.x = 2^(floor(src))
1497  *   dst.y = src - floor(src)
1498  *   dst.z = 2^src   (partial precision is allowed, but optional)
1499  *   dst.w = 1.0;
1500  * For 2.0 shaders, just do this (honoring writemask and swizzle):
1501  *   dst = 2^src;    (partial precision is allowed, but optional)
1502  */
1503 void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
1504     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1505     glsl_src_param_t src_param;
1506
1507     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1508
1509     if (shader->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
1510         char dst_mask[6];
1511
1512         shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1513         shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1514         shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1515         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1516
1517         shader_glsl_append_dst(arg->buffer, arg);
1518         shader_glsl_get_write_mask(arg->dst, dst_mask);
1519         shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1520     } else {
1521         DWORD write_mask;
1522         unsigned int mask_size;
1523
1524         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1525         mask_size = shader_glsl_get_write_mask_size(write_mask);
1526
1527         if (mask_size > 1) {
1528             shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1529         } else {
1530             shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1531         }
1532     }
1533 }
1534
1535 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1536 void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1537     glsl_src_param_t src_param;
1538     DWORD write_mask;
1539     unsigned int mask_size;
1540
1541     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1542     mask_size = shader_glsl_get_write_mask_size(write_mask);
1543     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1544
1545     if (mask_size > 1) {
1546         shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1547     } else {
1548         shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1549     }
1550 }
1551
1552 void shader_glsl_rsq(SHADER_OPCODE_ARG* arg) {
1553     SHADER_BUFFER* buffer = arg->buffer;
1554     glsl_src_param_t src_param;
1555     DWORD write_mask;
1556     unsigned int mask_size;
1557
1558     write_mask = shader_glsl_append_dst(buffer, arg);
1559     mask_size = shader_glsl_get_write_mask_size(write_mask);
1560
1561     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1562
1563     if (mask_size > 1) {
1564         shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1565     } else {
1566         shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1567     }
1568 }
1569
1570 /** Process signed comparison opcodes in GLSL. */
1571 void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1572     glsl_src_param_t src0_param;
1573     glsl_src_param_t src1_param;
1574     DWORD write_mask;
1575     unsigned int mask_size;
1576
1577     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1578     mask_size = shader_glsl_get_write_mask_size(write_mask);
1579     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1580     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1581
1582     if (mask_size > 1) {
1583         const char *compare;
1584
1585         switch(arg->opcode->opcode) {
1586             case WINED3DSIO_SLT: compare = "lessThan"; break;
1587             case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
1588             default: compare = "";
1589                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1590         }
1591
1592         shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1593                 src0_param.param_str, src1_param.param_str);
1594     } else {
1595         switch(arg->opcode->opcode) {
1596             case WINED3DSIO_SLT:
1597                 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
1598                  * to return 0.0 but step returns 1.0 because step is not < x
1599                  * An alternative is a bvec compare padded with an unused second component.
1600                  * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
1601                  * issue. Playing with not() is not possible either because not() does not accept
1602                  * a scalar.
1603                  */
1604                 shader_addline(arg->buffer, "(%s < %s) ? 1.0 : 0.0);\n", src0_param.param_str, src1_param.param_str);
1605                 break;
1606             case WINED3DSIO_SGE:
1607                 /* Here we can use the step() function and safe a conditional */
1608                 shader_addline(arg->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
1609                 break;
1610             default:
1611                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1612         }
1613
1614     }
1615 }
1616
1617 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1618 void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1619     glsl_src_param_t src0_param;
1620     glsl_src_param_t src1_param;
1621     glsl_src_param_t src2_param;
1622     DWORD write_mask, cmp_channel = 0;
1623     unsigned int i, j;
1624     char mask_char[6];
1625     BOOL temp_destination = FALSE;
1626
1627     if(shader_is_scalar(arg->src[0])) {
1628         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1629
1630         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
1631         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1632         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1633
1634         shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1635                        src0_param.param_str, src1_param.param_str, src2_param.param_str);
1636     } else {
1637         DWORD src0reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
1638         DWORD src1reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
1639         DWORD src2reg = arg->src[2] & WINED3DSP_REGNUM_MASK;
1640         DWORD src0regtype = shader_get_regtype(arg->src[0]);
1641         DWORD src1regtype = shader_get_regtype(arg->src[1]);
1642         DWORD src2regtype = shader_get_regtype(arg->src[2]);
1643         DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1644         DWORD dstregtype = shader_get_regtype(arg->dst);
1645
1646         /* Cycle through all source0 channels */
1647         for (i=0; i<4; i++) {
1648             write_mask = 0;
1649             /* Find the destination channels which use the current source0 channel */
1650             for (j=0; j<4; j++) {
1651                 if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1652                     write_mask |= WINED3DSP_WRITEMASK_0 << j;
1653                     cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1654                 }
1655             }
1656
1657             /* Splitting the cmp instruction up in multiple lines imposes a problem:
1658             * The first lines may overwrite source parameters of the following lines.
1659             * Deal with that by using a temporary destination register if needed
1660             */
1661             if((src0reg == dstreg && src0regtype == dstregtype) ||
1662             (src1reg == dstreg && src1regtype == dstregtype) ||
1663             (src2reg == dstreg && src2regtype == dstregtype)) {
1664
1665                 write_mask = shader_glsl_get_write_mask(arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask), mask_char);
1666                 if (!write_mask) continue;
1667                 shader_addline(arg->buffer, "tmp0%s = (", mask_char);
1668                 temp_destination = TRUE;
1669             } else {
1670                 write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1671                 if (!write_mask) continue;
1672             }
1673
1674             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1675             shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1676             shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1677
1678             shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1679                         src0_param.param_str, src1_param.param_str, src2_param.param_str);
1680         }
1681
1682         if(temp_destination) {
1683             shader_glsl_get_write_mask(arg->dst, mask_char);
1684             shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst);
1685             shader_addline(arg->buffer, "tmp0%s);\n", mask_char);
1686         }
1687     }
1688
1689 }
1690
1691 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1692 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
1693  * the compare is done per component of src0. */
1694 void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1695     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1696     glsl_src_param_t src0_param;
1697     glsl_src_param_t src1_param;
1698     glsl_src_param_t src2_param;
1699     DWORD write_mask, cmp_channel = 0;
1700     unsigned int i, j;
1701
1702     if (shader->baseShader.hex_version < WINED3DPS_VERSION(1, 4)) {
1703         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1704         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1705         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1706         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1707
1708         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
1709         if(arg->opcode_token & WINED3DSI_COISSUE) {
1710             shader_addline(arg->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
1711         } else {
1712             shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1713                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
1714         }
1715         return;
1716     }
1717     /* Cycle through all source0 channels */
1718     for (i=0; i<4; i++) {
1719         write_mask = 0;
1720         /* Find the destination channels which use the current source0 channel */
1721         for (j=0; j<4; j++) {
1722             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1723                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1724                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1725             }
1726         }
1727         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1728         if (!write_mask) continue;
1729
1730         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1731         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1732         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1733
1734         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1735                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1736     }
1737 }
1738
1739 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1740 void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1741     glsl_src_param_t src0_param;
1742     glsl_src_param_t src1_param;
1743     glsl_src_param_t src2_param;
1744     DWORD write_mask;
1745
1746     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1747     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1748     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1749     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1750     shader_addline(arg->buffer, "(%s * %s) + %s);\n",
1751             src0_param.param_str, src1_param.param_str, src2_param.param_str);
1752 }
1753
1754 /** Handles transforming all WINED3DSIO_M?x? opcodes for 
1755     Vertex shaders to GLSL codes */
1756 void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
1757     int i;
1758     int nComponents = 0;
1759     SHADER_OPCODE_ARG tmpArg;
1760    
1761     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1762
1763     /* Set constants for the temporary argument */
1764     tmpArg.shader      = arg->shader;
1765     tmpArg.buffer      = arg->buffer;
1766     tmpArg.src[0]      = arg->src[0];
1767     tmpArg.src_addr[0] = arg->src_addr[0];
1768     tmpArg.src_addr[1] = arg->src_addr[1];
1769     tmpArg.reg_maps = arg->reg_maps; 
1770     
1771     switch(arg->opcode->opcode) {
1772         case WINED3DSIO_M4x4:
1773             nComponents = 4;
1774             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1775             break;
1776         case WINED3DSIO_M4x3:
1777             nComponents = 3;
1778             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1779             break;
1780         case WINED3DSIO_M3x4:
1781             nComponents = 4;
1782             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1783             break;
1784         case WINED3DSIO_M3x3:
1785             nComponents = 3;
1786             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1787             break;
1788         case WINED3DSIO_M3x2:
1789             nComponents = 2;
1790             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1791             break;
1792         default:
1793             break;
1794     }
1795
1796     for (i = 0; i < nComponents; i++) {
1797         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1798         tmpArg.src[1]      = arg->src[1]+i;
1799         shader_glsl_dot(&tmpArg);
1800     }
1801 }
1802
1803 /**
1804     The LRP instruction performs a component-wise linear interpolation 
1805     between the second and third operands using the first operand as the
1806     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
1807     This is equivalent to mix(src2, src1, src0);
1808 */
1809 void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1810     glsl_src_param_t src0_param;
1811     glsl_src_param_t src1_param;
1812     glsl_src_param_t src2_param;
1813     DWORD write_mask;
1814
1815     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1816
1817     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1818     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1819     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1820
1821     shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
1822             src2_param.param_str, src1_param.param_str, src0_param.param_str);
1823 }
1824
1825 /** Process the WINED3DSIO_LIT instruction in GLSL:
1826  * dst.x = dst.w = 1.0
1827  * dst.y = (src0.x > 0) ? src0.x
1828  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
1829  *                                        where src.w is clamped at +- 128
1830  */
1831 void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1832     glsl_src_param_t src0_param;
1833     glsl_src_param_t src1_param;
1834     glsl_src_param_t src3_param;
1835     char dst_mask[6];
1836
1837     shader_glsl_append_dst(arg->buffer, arg);
1838     shader_glsl_get_write_mask(arg->dst, dst_mask);
1839
1840     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1841     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
1842     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
1843
1844     /* The sdk specifies the instruction like this
1845      * dst.x = 1.0;
1846      * if(src.x > 0.0) dst.y = src.x
1847      * else dst.y = 0.0.
1848      * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
1849      * else dst.z = 0.0;
1850      * dst.w = 1.0;
1851      *
1852      * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
1853      * dst.x = 1.0                                  ... No further explanation needed
1854      * dst.y = max(src.y, 0.0);                     ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
1855      * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0;   ... 0 ^ power is 0, and otherwise we use y anyway
1856      * dst.w = 1.0.                                 ... Nothing fancy.
1857      *
1858      * So we still have one conditional in there. So do this:
1859      * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
1860      *
1861      * 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),
1862      * 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.
1863      * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
1864      */
1865     shader_addline(arg->buffer, "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",
1866                    src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
1867 }
1868
1869 /** Process the WINED3DSIO_DST instruction in GLSL:
1870  * dst.x = 1.0
1871  * dst.y = src0.x * src0.y
1872  * dst.z = src0.z
1873  * dst.w = src1.w
1874  */
1875 void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1876     glsl_src_param_t src0y_param;
1877     glsl_src_param_t src0z_param;
1878     glsl_src_param_t src1y_param;
1879     glsl_src_param_t src1w_param;
1880     char dst_mask[6];
1881
1882     shader_glsl_append_dst(arg->buffer, arg);
1883     shader_glsl_get_write_mask(arg->dst, dst_mask);
1884
1885     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
1886     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
1887     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
1888     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
1889
1890     shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
1891             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
1892 }
1893
1894 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
1895  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
1896  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
1897  * 
1898  * dst.x = cos(src0.?)
1899  * dst.y = sin(src0.?)
1900  * dst.z = dst.z
1901  * dst.w = dst.w
1902  */
1903 void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1904     glsl_src_param_t src0_param;
1905     DWORD write_mask;
1906
1907     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1908     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1909
1910     switch (write_mask) {
1911         case WINED3DSP_WRITEMASK_0:
1912             shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
1913             break;
1914
1915         case WINED3DSP_WRITEMASK_1:
1916             shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
1917             break;
1918
1919         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
1920             shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
1921             break;
1922
1923         default:
1924             ERR("Write mask should be .x, .y or .xy\n");
1925             break;
1926     }
1927 }
1928
1929 /** Process the WINED3DSIO_LOOP instruction in GLSL:
1930  * Start a for() loop where src1.y is the initial value of aL,
1931  *  increment aL by src1.z for a total of src1.x iterations.
1932  *  Need to use a temporary variable for this operation.
1933  */
1934 /* FIXME: I don't think nested loops will work correctly this way. */
1935 void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1936     glsl_src_param_t src1_param;
1937     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1938     DWORD regtype = shader_get_regtype(arg->src[1]);
1939     DWORD reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
1940     const DWORD *control_values = NULL;
1941     local_constant *constant;
1942
1943     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
1944
1945     /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
1946      * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
1947      * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
1948      * addressing.
1949      */
1950     if(regtype == WINED3DSPR_CONSTINT) {
1951         LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
1952             if(constant->idx == reg) {
1953                 control_values = constant->value;
1954                 break;
1955             }
1956         }
1957     }
1958
1959     if(control_values) {
1960         if(control_values[2] > 0) {
1961             shader_addline(arg->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
1962                            shader->baseShader.cur_loop_depth, control_values[1],
1963                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
1964                            shader->baseShader.cur_loop_depth, control_values[2]);
1965         } else if(control_values[2] == 0) {
1966             shader_addline(arg->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
1967                            shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
1968                            shader->baseShader.cur_loop_depth, control_values[0],
1969                            shader->baseShader.cur_loop_depth);
1970         } else {
1971             shader_addline(arg->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
1972                            shader->baseShader.cur_loop_depth, control_values[1],
1973                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
1974                            shader->baseShader.cur_loop_depth, control_values[2]);
1975         }
1976     } else {
1977         shader_addline(arg->buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
1978                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
1979                        src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
1980                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
1981     }
1982
1983     shader->baseShader.cur_loop_depth++;
1984     shader->baseShader.cur_loop_regno++;
1985 }
1986
1987 void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1988     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1989
1990     shader_addline(arg->buffer, "}\n");
1991
1992     if(arg->opcode->opcode == WINED3DSIO_ENDLOOP) {
1993         shader->baseShader.cur_loop_depth--;
1994         shader->baseShader.cur_loop_regno--;
1995     }
1996     if(arg->opcode->opcode == WINED3DSIO_ENDREP) {
1997         shader->baseShader.cur_loop_depth--;
1998     }
1999 }
2000
2001 void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
2002     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
2003     glsl_src_param_t src0_param;
2004
2005     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2006     shader_addline(arg->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2007                    shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2008                    src0_param.param_str, shader->baseShader.cur_loop_depth);
2009     shader->baseShader.cur_loop_depth++;
2010 }
2011
2012 void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
2013     glsl_src_param_t src0_param;
2014
2015     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2016     shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
2017 }
2018
2019 void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
2020     glsl_src_param_t src0_param;
2021     glsl_src_param_t src1_param;
2022
2023     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2024     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2025
2026     shader_addline(arg->buffer, "if (%s %s %s) {\n",
2027             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2028 }
2029
2030 void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
2031     shader_addline(arg->buffer, "} else {\n");
2032 }
2033
2034 void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
2035     shader_addline(arg->buffer, "break;\n");
2036 }
2037
2038 /* FIXME: According to MSDN the compare is done per component. */
2039 void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
2040     glsl_src_param_t src0_param;
2041     glsl_src_param_t src1_param;
2042
2043     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2044     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2045
2046     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
2047             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2048 }
2049
2050 void shader_glsl_label(SHADER_OPCODE_ARG* arg) {
2051
2052     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2053     shader_addline(arg->buffer, "}\n");
2054     shader_addline(arg->buffer, "void subroutine%u () {\n",  snum);
2055 }
2056
2057 void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
2058     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2059     shader_addline(arg->buffer, "subroutine%u();\n", snum);
2060 }
2061
2062 void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
2063     glsl_src_param_t src1_param;
2064
2065     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2066     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2067     shader_addline(arg->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, snum);
2068 }
2069
2070 /*********************************************
2071  * Pixel Shader Specific Code begins here
2072  ********************************************/
2073 void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
2074     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2075     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2076     DWORD hex_version = This->baseShader.hex_version;
2077     char dst_swizzle[6];
2078     glsl_sample_function_t sample_function;
2079     DWORD sampler_type;
2080     DWORD sampler_idx;
2081     BOOL projected, texrect = FALSE;
2082     DWORD mask = 0;
2083
2084     /* All versions have a destination register */
2085     shader_glsl_append_dst(arg->buffer, arg);
2086
2087     /* 1.0-1.4: Use destination register as sampler source.
2088      * 2.0+: Use provided sampler source. */
2089     if (hex_version < WINED3DPS_VERSION(1,4)) {
2090         DWORD flags;
2091
2092         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2093         flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2094
2095         if (flags & WINED3DTTFF_PROJECTED) {
2096             projected = TRUE;
2097             switch (flags & ~WINED3DTTFF_PROJECTED) {
2098                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2099                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2100                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2101                 case WINED3DTTFF_COUNT4:
2102                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2103             }
2104         } else {
2105             projected = FALSE;
2106         }
2107     } else if (hex_version < WINED3DPS_VERSION(2,0)) {
2108         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2109         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2110
2111         if (src_mod == WINED3DSPSM_DZ) {
2112             projected = TRUE;
2113             mask = WINED3DSP_WRITEMASK_2;
2114         } else if (src_mod == WINED3DSPSM_DW) {
2115             projected = TRUE;
2116             mask = WINED3DSP_WRITEMASK_3;
2117         } else {
2118             projected = FALSE;
2119         }
2120     } else {
2121         sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2122         if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
2123                 /* ps 2.0 texldp instruction always divides by the fourth component. */
2124                 projected = TRUE;
2125                 mask = WINED3DSP_WRITEMASK_3;
2126         } else {
2127             projected = FALSE;
2128         }
2129     }
2130
2131     if(deviceImpl->stateBlock->textures[sampler_idx] &&
2132        IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2133         texrect = TRUE;
2134     }
2135
2136     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2137     shader_glsl_get_sample_function(sampler_type, projected, texrect, &sample_function);
2138     mask |= sample_function.coord_mask;
2139
2140     if (hex_version < WINED3DPS_VERSION(2,0)) {
2141         shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2142     } else {
2143         shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
2144     }
2145
2146     /* 1.0-1.3: Use destination register as coordinate source.
2147        1.4+: Use provided coordinate source register. */
2148     if (hex_version < WINED3DPS_VERSION(1,4)) {
2149         char coord_mask[6];
2150         shader_glsl_get_write_mask(mask, coord_mask);
2151         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s)%s);\n",
2152                 sample_function.name, sampler_idx, sampler_idx, coord_mask, dst_swizzle);
2153     } else {
2154         glsl_src_param_t coord_param;
2155         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
2156         if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
2157             glsl_src_param_t bias;
2158             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);
2159
2160             shader_addline(arg->buffer, "%s(Psampler%u, %s, %s)%s);\n",
2161                     sample_function.name, sampler_idx, coord_param.param_str,
2162                     bias.param_str, dst_swizzle);
2163         } else {
2164             shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n",
2165                     sample_function.name, sampler_idx, coord_param.param_str, dst_swizzle);
2166         }
2167     }
2168 }
2169
2170 void shader_glsl_texldl(SHADER_OPCODE_ARG* arg) {
2171     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
2172     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2173     glsl_sample_function_t sample_function;
2174     glsl_src_param_t coord_param, lod_param;
2175     char dst_swizzle[6];
2176     DWORD sampler_type;
2177     DWORD sampler_idx;
2178     BOOL texrect = FALSE;
2179
2180     shader_glsl_append_dst(arg->buffer, arg);
2181     shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
2182
2183     sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2184     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2185     if(deviceImpl->stateBlock->textures[sampler_idx] &&
2186        IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2187         texrect = TRUE;
2188     }
2189     shader_glsl_get_sample_function(sampler_type, FALSE, texrect, &sample_function);    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
2190
2191     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);
2192
2193     if (shader_is_pshader_version(This->baseShader.hex_version)) {
2194         /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2195          * However, they seem to work just fine in fragment shaders as well. */
2196         WARN("Using %sLod in fragment shader.\n", sample_function.name);
2197         shader_addline(arg->buffer, "%sLod(Psampler%u, %s, %s)%s);\n",
2198                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
2199     } else {
2200         shader_addline(arg->buffer, "%sLod(Vsampler%u, %s, %s)%s);\n",
2201                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
2202     }
2203 }
2204
2205 void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {
2206
2207     /* FIXME: Make this work for more than just 2D textures */
2208     
2209     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2210     SHADER_BUFFER* buffer = arg->buffer;
2211     DWORD hex_version = This->baseShader.hex_version;
2212     DWORD write_mask;
2213     char dst_mask[6];
2214
2215     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2216     shader_glsl_get_write_mask(write_mask, dst_mask);
2217
2218     if (hex_version != WINED3DPS_VERSION(1,4)) {
2219         DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2220         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
2221     } else {
2222         DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
2223         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2224         char dst_swizzle[6];
2225
2226         shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);
2227
2228         if (src_mod == WINED3DSPSM_DZ) {
2229             glsl_src_param_t div_param;
2230             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2231             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
2232
2233             if (mask_size > 1) {
2234                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2235             } else {
2236                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2237             }
2238         } else if (src_mod == WINED3DSPSM_DW) {
2239             glsl_src_param_t div_param;
2240             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2241             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
2242
2243             if (mask_size > 1) {
2244                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2245             } else {
2246                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2247             }
2248         } else {
2249             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2250         }
2251     }
2252 }
2253
2254 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2255  * Take a 3-component dot product of the TexCoord[dstreg] and src,
2256  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2257 void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
2258     glsl_src_param_t src0_param;
2259     char dst_mask[6];
2260     glsl_sample_function_t sample_function;
2261     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2262     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2263     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2264
2265     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2266
2267     shader_glsl_append_dst(arg->buffer, arg);
2268     shader_glsl_get_write_mask(arg->dst, dst_mask);
2269
2270     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2271      * scalar, and projected sampling would require 4.
2272      *
2273      * It is a dependent read - not valid with conditional NP2 textures
2274      */
2275     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2276
2277     switch(count_bits(sample_function.coord_mask)) {
2278         case 1:
2279             shader_addline(arg->buffer, "%s(Psampler%u, dot(gl_TexCoord[%u].xyz, %s))%s);\n",
2280                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2281             break;
2282
2283         case 2:
2284             shader_addline(arg->buffer, "%s(Psampler%u, vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0))%s);\n",
2285                           sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2286             break;
2287
2288         case 3:
2289             shader_addline(arg->buffer, "%s(Psampler%u, vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0))%s);\n",
2290                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2291             break;
2292         default:
2293             FIXME("Unexpected mask bitcount %d\n", count_bits(sample_function.coord_mask));
2294     }
2295 }
2296
2297 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2298  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2299 void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
2300     glsl_src_param_t src0_param;
2301     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2302     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2303     DWORD dst_mask;
2304     unsigned int mask_size;
2305
2306     dst_mask = shader_glsl_append_dst(arg->buffer, arg);
2307     mask_size = shader_glsl_get_write_mask_size(dst_mask);
2308     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2309
2310     if (mask_size > 1) {
2311         shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2312     } else {
2313         shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2314     }
2315 }
2316
2317 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2318  * Calculate the depth as dst.x / dst.y   */
2319 void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
2320     glsl_dst_param_t dst_param;
2321
2322     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2323
2324     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2325      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2326      * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2327      * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2328      * >= 1.0 or < 0.0
2329      */
2330     shader_addline(arg->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name);
2331 }
2332
2333 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2334  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2335  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
2336  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2337  */
2338 void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
2339     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2340     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2341     glsl_src_param_t src0_param;
2342
2343     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2344
2345     shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2346     shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2347 }
2348
2349 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2350  * Calculate the 1st of a 2-row matrix multiplication. */
2351 void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
2352     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2353     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2354     SHADER_BUFFER* buffer = arg->buffer;
2355     glsl_src_param_t src0_param;
2356
2357     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2358     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2359 }
2360
2361 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2362  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2363 void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {
2364
2365     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2366     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2367     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2368     SHADER_BUFFER* buffer = arg->buffer;
2369     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2370     glsl_src_param_t src0_param;
2371
2372     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2373     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2374     current_state->texcoord_w[current_state->current_row++] = reg;
2375 }
2376
2377 void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
2378     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2379     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2380     SHADER_BUFFER* buffer = arg->buffer;
2381     glsl_src_param_t src0_param;
2382     char dst_mask[6];
2383
2384     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2385     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2386
2387     shader_glsl_append_dst(buffer, arg);
2388     shader_glsl_get_write_mask(arg->dst, dst_mask);
2389
2390     /* Sample the texture using the calculated coordinates */
2391     shader_addline(buffer, "texture2D(Psampler%u, tmp0.xy)%s);\n", reg, dst_mask);
2392 }
2393
2394 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2395  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2396 void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
2397     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2398     glsl_src_param_t src0_param;
2399     char dst_mask[6];
2400     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2401     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2402     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2403     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2404     glsl_sample_function_t sample_function;
2405
2406     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2407     shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2408
2409     shader_glsl_append_dst(arg->buffer, arg);
2410     shader_glsl_get_write_mask(arg->dst, dst_mask);
2411     /* Dependent read, not valid with conditional NP2 */
2412     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2413
2414     /* Sample the texture using the calculated coordinates */
2415     shader_addline(arg->buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2416
2417     current_state->current_row = 0;
2418 }
2419
2420 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2421  * Perform the 3rd row of a 3x3 matrix multiply */
2422 void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
2423     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2424     glsl_src_param_t src0_param;
2425     char dst_mask[6];
2426     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2427     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2428     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2429
2430     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2431
2432     shader_glsl_append_dst(arg->buffer, arg);
2433     shader_glsl_get_write_mask(arg->dst, dst_mask);
2434     shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2435
2436     current_state->current_row = 0;
2437 }
2438
2439 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
2440  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2441 void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {
2442
2443     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2444     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2445     glsl_src_param_t src0_param;
2446     glsl_src_param_t src1_param;
2447     char dst_mask[6];
2448     SHADER_BUFFER* buffer = arg->buffer;
2449     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2450     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2451     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2452     glsl_sample_function_t sample_function;
2453
2454     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2455     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
2456
2457     /* Perform the last matrix multiply operation */
2458     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2459     /* Reflection calculation */
2460     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2461
2462     shader_glsl_append_dst(buffer, arg);
2463     shader_glsl_get_write_mask(arg->dst, dst_mask);
2464     /* Dependent read, not valid with conditional NP2 */
2465     shader_glsl_get_sample_function(stype, FALSE, FALSE, &sample_function);
2466
2467     /* Sample the texture */
2468     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2469
2470     current_state->current_row = 0;
2471 }
2472
2473 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
2474  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2475 void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
2476
2477     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2478     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2479     SHADER_BUFFER* buffer = arg->buffer;
2480     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2481     glsl_src_param_t src0_param;
2482     char dst_mask[6];
2483     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2484     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2485     glsl_sample_function_t sample_function;
2486
2487     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2488
2489     /* Perform the last matrix multiply operation */
2490     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2491
2492     /* Construct the eye-ray vector from w coordinates */
2493     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2494             current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2495     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2496
2497     shader_glsl_append_dst(buffer, arg);
2498     shader_glsl_get_write_mask(arg->dst, dst_mask);
2499     /* Dependent read, not valid with conditional NP2 */
2500     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2501
2502     /* Sample the texture using the calculated coordinates */
2503     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2504
2505     current_state->current_row = 0;
2506 }
2507
2508 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2509  * Apply a fake bump map transform.
2510  * texbem is pshader <= 1.3 only, this saves a few version checks
2511  */
2512 void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
2513     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2514     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2515     char dst_swizzle[6];
2516     glsl_sample_function_t sample_function;
2517     glsl_src_param_t coord_param;
2518     DWORD sampler_type;
2519     DWORD sampler_idx;
2520     DWORD mask;
2521     DWORD flags;
2522     char coord_mask[6];
2523
2524     sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2525     flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2526
2527     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2528     /* Dependent read, not valid with conditional NP2 */
2529     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2530     mask = sample_function.coord_mask;
2531
2532     shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2533
2534     shader_glsl_get_write_mask(mask, coord_mask);
2535
2536     /* with projective textures, texbem only divides the static texture coord, not the displacement,
2537          * so we can't let the GL handle this.
2538          */
2539     if (flags & WINED3DTTFF_PROJECTED) {
2540         DWORD div_mask=0;
2541         char coord_div_mask[3];
2542         switch (flags & ~WINED3DTTFF_PROJECTED) {
2543             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2544             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2545             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2546             case WINED3DTTFF_COUNT4:
2547             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2548         }
2549         shader_glsl_get_write_mask(div_mask, coord_div_mask);
2550         shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2551     }
2552
2553     shader_glsl_append_dst(arg->buffer, arg);
2554     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2555     if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
2556         glsl_src_param_t luminance_param;
2557         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2558         shader_addline(arg->buffer, "(%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )*(%s * luminancescale + luminanceoffset))%s);\n",
2559                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask,
2560                        luminance_param.param_str, dst_swizzle);
2561     } else {
2562         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )%s);\n",
2563                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask, dst_swizzle);
2564     }
2565 }
2566
2567 void pshader_glsl_bem(SHADER_OPCODE_ARG* arg) {
2568     glsl_src_param_t src0_param, src1_param;
2569
2570     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
2571     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);
2572
2573     shader_glsl_append_dst(arg->buffer, arg);
2574     shader_addline(arg->buffer, "%s + bumpenvmat * %s);\n",
2575                    src0_param.param_str, src1_param.param_str);
2576 }
2577
2578 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2579  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2580 void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
2581
2582     glsl_src_param_t src0_param;
2583     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2584     char dst_mask[6];
2585
2586     shader_glsl_append_dst(arg->buffer, arg);
2587     shader_glsl_get_write_mask(arg->dst, dst_mask);
2588     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2589
2590     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.wx)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2591 }
2592
2593 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2594  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2595 void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
2596     glsl_src_param_t src0_param;
2597     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2598     char dst_mask[6];
2599
2600     shader_glsl_append_dst(arg->buffer, arg);
2601     shader_glsl_get_write_mask(arg->dst, dst_mask);
2602     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2603
2604     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.yz)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2605 }
2606
2607 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2608  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2609 void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
2610     glsl_src_param_t src0_param;
2611     char dst_mask[6];
2612     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2613     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2614     glsl_sample_function_t sample_function;
2615
2616     shader_glsl_append_dst(arg->buffer, arg);
2617     shader_glsl_get_write_mask(arg->dst, dst_mask);
2618     /* Dependent read, not valid with conditional NP2 */
2619     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2620     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2621
2622     shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n", sample_function.name, sampler_idx, src0_param.param_str, dst_mask);
2623 }
2624
2625 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2626  * If any of the first 3 components are < 0, discard this pixel */
2627 void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
2628     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2629     DWORD hex_version = This->baseShader.hex_version;
2630     glsl_dst_param_t dst_param;
2631
2632     /* The argument is a destination parameter, and no writemasks are allowed */
2633     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2634     if((hex_version >= WINED3DPS_VERSION(2,0))) {
2635         /* 2.0 shaders compare all 4 components in texkill */
2636         shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2637     } else {
2638         /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
2639          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2640          * 4 components are defined, only the first 3 are used
2641          */
2642         shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2643     }
2644 }
2645
2646 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2647  * dst = dot2(src0, src1) + src2 */
2648 void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
2649     glsl_src_param_t src0_param;
2650     glsl_src_param_t src1_param;
2651     glsl_src_param_t src2_param;
2652     DWORD write_mask;
2653     unsigned int mask_size;
2654
2655     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2656     mask_size = shader_glsl_get_write_mask_size(write_mask);
2657
2658     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2659     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2660     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2661
2662     shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2663 }
2664
2665 void pshader_glsl_input_pack(
2666    SHADER_BUFFER* buffer,
2667    semantic* semantics_in,
2668    IWineD3DPixelShader *iface) {
2669
2670    unsigned int i;
2671    IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
2672
2673    for (i = 0; i < MAX_REG_INPUT; i++) {
2674
2675        DWORD usage_token = semantics_in[i].usage;
2676        DWORD register_token = semantics_in[i].reg;
2677        DWORD usage, usage_idx;
2678        char reg_mask[6];
2679
2680        /* Uninitialized */
2681        if (!usage_token) continue;
2682        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2683        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2684        shader_glsl_get_write_mask(register_token, reg_mask);
2685
2686        switch(usage) {
2687
2688            case WINED3DDECLUSAGE_TEXCOORD:
2689                if(usage_idx < 8 && This->vertexprocessing == pretransformed) {
2690                    shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2691                                   This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
2692                } else {
2693                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2694                                   This->input_reg_map[i], reg_mask, reg_mask);
2695                }
2696                break;
2697
2698            case WINED3DDECLUSAGE_COLOR:
2699                if (usage_idx == 0)
2700                    shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
2701                        This->input_reg_map[i], reg_mask, reg_mask);
2702                else if (usage_idx == 1)
2703                    shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
2704                        This->input_reg_map[i], reg_mask, reg_mask);
2705                else
2706                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2707                        This->input_reg_map[i], reg_mask, reg_mask);
2708                break;
2709
2710            default:
2711                shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2712                    This->input_reg_map[i], reg_mask, reg_mask);
2713         }
2714     }
2715 }
2716
2717 /*********************************************
2718  * Vertex Shader Specific Code begins here
2719  ********************************************/
2720
2721 static void add_glsl_program_entry(IWineD3DDeviceImpl *device, struct glsl_shader_prog_link *entry) {
2722     glsl_program_key_t *key;
2723
2724     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2725     key->vshader = entry->vshader;
2726     key->pshader = entry->pshader;
2727
2728     hash_table_put(device->glsl_program_lookup, key, entry);
2729 }
2730
2731 static struct glsl_shader_prog_link *get_glsl_program_entry(IWineD3DDeviceImpl *device,
2732         GLhandleARB vshader, GLhandleARB pshader) {
2733     glsl_program_key_t key;
2734
2735     key.vshader = vshader;
2736     key.pshader = pshader;
2737
2738     return (struct glsl_shader_prog_link *)hash_table_get(device->glsl_program_lookup, &key);
2739 }
2740
2741 void delete_glsl_program_entry(IWineD3DDevice *iface, struct glsl_shader_prog_link *entry) {
2742     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2743     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2744     glsl_program_key_t *key;
2745
2746     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2747     key->vshader = entry->vshader;
2748     key->pshader = entry->pshader;
2749     hash_table_remove(This->glsl_program_lookup, key);
2750
2751     GL_EXTCALL(glDeleteObjectARB(entry->programId));
2752     if (entry->vshader) list_remove(&entry->vshader_entry);
2753     if (entry->pshader) list_remove(&entry->pshader_entry);
2754     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
2755     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
2756     HeapFree(GetProcessHeap(), 0, entry);
2757 }
2758
2759 static void handle_ps3_input(SHADER_BUFFER *buffer, semantic *semantics_in, semantic *semantics_out, WineD3D_GL_Info *gl_info, DWORD *map) {
2760     unsigned int i, j;
2761     DWORD usage_token, usage_token_out;
2762     DWORD register_token, register_token_out;
2763     DWORD usage, usage_idx, usage_out, usage_idx_out;
2764     DWORD *set;
2765     char reg_mask[6], reg_mask_out[6];
2766
2767     set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (GL_LIMITS(glsl_varyings) / 4));
2768
2769     for(i = 0; i < MAX_REG_INPUT; i++) {
2770         usage_token = semantics_in[i].usage;
2771         if (!usage_token) continue;
2772         if(map[i] >= (GL_LIMITS(glsl_varyings) / 4)) {
2773             FIXME("More input varyings declared than supported, expect issues\n");
2774             continue;
2775         } else if(map[i] == -1) {
2776             /* Declared, but not read register */
2777             continue;
2778         }
2779         register_token = semantics_in[i].reg;
2780
2781         usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2782         usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2783         set[map[i]] = shader_glsl_get_write_mask(register_token, reg_mask);
2784
2785         if(!semantics_out) {
2786             switch(usage) {
2787                 case WINED3DDECLUSAGE_COLOR:
2788                     if (usage_idx == 0)
2789                         shader_addline(buffer, "IN[%u]%s = gl_FrontColor%s;\n",
2790                                        map[i], reg_mask, reg_mask);
2791                     else if (usage_idx == 1)
2792                         shader_addline(buffer, "IN[%u]%s = gl_FrontSecondaryColor%s;\n",
2793                                        map[i], reg_mask, reg_mask);
2794                     else
2795                         shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2796                                        map[i], reg_mask, reg_mask);
2797                     break;
2798
2799                 case WINED3DDECLUSAGE_TEXCOORD:
2800                     if (usage_idx < 8) {
2801                         shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2802                                        map[i], reg_mask, usage_idx, reg_mask);
2803                     } else {
2804                         shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2805                                        map[i], reg_mask, reg_mask);
2806                     }
2807                     break;
2808
2809                 case WINED3DDECLUSAGE_FOG:
2810                     shader_addline(buffer, "IN[%u]%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
2811                                    map[i], reg_mask, reg_mask);
2812                     break;
2813
2814                 default:
2815                     shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2816                                    map[i], reg_mask, reg_mask);
2817             }
2818         } else {
2819             BOOL found = FALSE;
2820             for(j = 0; j < MAX_REG_OUTPUT; j++) {
2821                 usage_token_out = semantics_out[j].usage;
2822                 if (!usage_token_out) continue;
2823                 register_token_out = semantics_out[j].reg;
2824
2825                 usage_out = (usage_token_out & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2826                 usage_idx_out = (usage_token_out & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2827                 shader_glsl_get_write_mask(register_token_out, reg_mask_out);
2828
2829                 if(usage == usage_out &&
2830                    usage_idx == usage_idx_out) {
2831                     shader_addline(buffer, "IN[%u]%s = OUT[%u]%s;\n",
2832                                    map[i], reg_mask, j, reg_mask);
2833                     found = TRUE;
2834                 }
2835             }
2836             if(!found) {
2837                 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2838                                map[i], reg_mask, reg_mask);
2839             }
2840         }
2841     }
2842
2843     /* This is solely to make the compiler / linker happy and avoid warning about undefined
2844      * varyings. It shouldn't result in any real code executed on the GPU, since all read
2845      * input varyings are assigned above, if the optimizer works properly.
2846      */
2847     for(i = 0; i < GL_LIMITS(glsl_varyings) / 4; i++) {
2848         if(set[i] != WINED3DSP_WRITEMASK_ALL) {
2849             unsigned int size = 0;
2850             memset(reg_mask, 0, sizeof(reg_mask));
2851             if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
2852                 reg_mask[size] = 'x';
2853                 size++;
2854             }
2855             if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
2856                 reg_mask[size] = 'y';
2857                 size++;
2858             }
2859             if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
2860                 reg_mask[size] = 'z';
2861                 size++;
2862             }
2863             if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
2864                 reg_mask[size] = 'w';
2865                 size++;
2866             }
2867             switch(size) {
2868                 case 1:
2869                     shader_addline(buffer, "IN[%u].%s = 0.0;\n", i, reg_mask);
2870                     break;
2871                 case 2:
2872                     shader_addline(buffer, "IN[%u].%s = vec2(0.0, 0.0);\n", i, reg_mask);
2873                     break;
2874                 case 3:
2875                     shader_addline(buffer, "IN[%u].%s = vec3(0.0, 0.0, 0.0);\n", i, reg_mask);
2876                     break;
2877                 case 4:
2878                     shader_addline(buffer, "IN[%u].%s = vec4(0.0, 0.0, 0.0, 0.0);\n", i, reg_mask);
2879                     break;
2880             }
2881         }
2882     }
2883
2884     HeapFree(GetProcessHeap(), 0, set);
2885 }
2886
2887 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
2888         IWineD3DPixelShader *pixelshader,
2889         WineD3D_GL_Info *gl_info) {
2890     GLhandleARB ret = 0;
2891     IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
2892     IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
2893     DWORD vs_major = vs ? WINED3DSHADER_VERSION_MAJOR(vs->baseShader.hex_version) : 0;
2894     DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.hex_version) : 0;
2895     unsigned int i;
2896     SHADER_BUFFER buffer;
2897     DWORD usage_token;
2898     DWORD register_token;
2899     DWORD usage, usage_idx, writemask;
2900     char reg_mask[6];
2901     semantic *semantics_out, *semantics_in;
2902
2903     buffer.buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SHADER_PGMSIZE);
2904     buffer.bsize = 0;
2905     buffer.lineNo = 0;
2906     buffer.newline = TRUE;
2907
2908     if(vs_major < 3 && ps_major < 3) {
2909         /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
2910          * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
2911          */
2912         if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0) {
2913             shader_addline(&buffer, "void order_ps_input() {\n");
2914             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
2915                 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
2916                    vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
2917                     shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
2918                 }
2919             }
2920             shader_addline(&buffer, "}\n");
2921         } else {
2922             shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
2923         }
2924     } else if(ps_major < 3 && vs_major >= 3) {
2925         /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
2926         semantics_out = vs->semantics_out;
2927
2928         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
2929         for(i = 0; i < MAX_REG_OUTPUT; i++) {
2930             usage_token = semantics_out[i].usage;
2931             if (!usage_token) continue;
2932             register_token = semantics_out[i].reg;
2933
2934             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2935             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2936             writemask = shader_glsl_get_write_mask(register_token, reg_mask);
2937
2938             switch(usage) {
2939                 case WINED3DDECLUSAGE_COLOR:
2940                     if (usage_idx == 0)
2941                         shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2942                     else if (usage_idx == 1)
2943                         shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2944                     break;
2945
2946                 case WINED3DDECLUSAGE_POSITION:
2947                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2948                     break;
2949
2950                 case WINED3DDECLUSAGE_TEXCOORD:
2951                     if (usage_idx < 8) {
2952                         if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;
2953
2954                         shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
2955                                         usage_idx, reg_mask, i, reg_mask);
2956                         if(!(writemask & WINED3DSP_WRITEMASK_3)) {
2957                             shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
2958                         }
2959                     }
2960                     break;
2961
2962                 case WINED3DDECLUSAGE_PSIZE:
2963                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
2964                     break;
2965
2966                 case WINED3DDECLUSAGE_FOG:
2967                     shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
2968                     break;
2969
2970                 default:
2971                     break;
2972             }
2973         }
2974         shader_addline(&buffer, "}\n");
2975
2976     } else if(ps_major >= 3 && vs_major >= 3) {
2977         semantics_out = vs->semantics_out;
2978         semantics_in = ps->semantics_in;
2979
2980         /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
2981         shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
2982         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
2983
2984         /* First, sort out position and point size. Those are not passed to the pixel shader */
2985         for(i = 0; i < MAX_REG_OUTPUT; i++) {
2986             usage_token = semantics_out[i].usage;
2987             if (!usage_token) continue;
2988             register_token = semantics_out[i].reg;
2989
2990             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2991             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2992             shader_glsl_get_write_mask(register_token, reg_mask);
2993
2994             switch(usage) {
2995                 case WINED3DDECLUSAGE_POSITION:
2996                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2997                     break;
2998
2999                 case WINED3DDECLUSAGE_PSIZE:
3000                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3001                     break;
3002
3003                 default:
3004                     break;
3005             }
3006         }
3007
3008         /* Then, fix the pixel shader input */
3009         handle_ps3_input(&buffer, semantics_in, semantics_out, gl_info, ps->input_reg_map);
3010
3011         shader_addline(&buffer, "}\n");
3012     } else if(ps_major >= 3 && vs_major < 3) {
3013         semantics_in = ps->semantics_in;
3014
3015         shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3016         shader_addline(&buffer, "void order_ps_input() {\n");
3017         /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3018          * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3019          * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3020          */
3021         handle_ps3_input(&buffer, semantics_in, NULL, gl_info, ps->input_reg_map);
3022         shader_addline(&buffer, "}\n");
3023     } else {
3024         ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3025     }
3026
3027     ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3028     checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3029     GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3030     checkGLcall("glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL)");
3031     GL_EXTCALL(glCompileShaderARB(ret));
3032     checkGLcall("glCompileShaderARB(ret)");
3033
3034     HeapFree(GetProcessHeap(), 0, buffer.buffer);
3035     return ret;
3036 }
3037
3038 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3039  * It sets the programId on the current StateBlock (because it should be called
3040  * inside of the DrawPrimitive() part of the render loop).
3041  *
3042  * If a program for the given combination does not exist, create one, and store
3043  * the program in the hash table.  If it creates a program, it will link the
3044  * given objects, too.
3045  */
3046 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3047     IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
3048     WineD3D_GL_Info *gl_info               = &This->adapter->gl_info;
3049     IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
3050     IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
3051     struct glsl_shader_prog_link *entry    = NULL;
3052     GLhandleARB programId                  = 0;
3053     GLhandleARB reorder_shader_id          = 0;
3054     int i;
3055     char glsl_name[8];
3056
3057     GLhandleARB vshader_id = use_vs ? ((IWineD3DBaseShaderImpl*)vshader)->baseShader.prgId : 0;
3058     GLhandleARB pshader_id = use_ps ? ((IWineD3DBaseShaderImpl*)pshader)->baseShader.prgId : 0;
3059     entry = get_glsl_program_entry(This, vshader_id, pshader_id);
3060     if (entry) {
3061         This->stateBlock->glsl_program = entry;
3062         return;
3063     }
3064
3065     /* If we get to this point, then no matching program exists, so we create one */
3066     programId = GL_EXTCALL(glCreateProgramObjectARB());
3067     TRACE("Created new GLSL shader program %u\n", programId);
3068
3069     /* Create the entry */
3070     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3071     entry->programId = programId;
3072     entry->vshader = vshader_id;
3073     entry->pshader = pshader_id;
3074     /* Add the hash table entry */
3075     add_glsl_program_entry(This, entry);
3076
3077     /* Set the current program */
3078     This->stateBlock->glsl_program = entry;
3079
3080     /* Attach GLSL vshader */
3081     if (vshader_id) {
3082         int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
3083         char tmp_name[10];
3084
3085         reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
3086         TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
3087         GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
3088         checkGLcall("glAttachObjectARB");
3089         /* Flag the reorder function for deletion, then it will be freed automatically when the program
3090          * is destroyed
3091          */
3092         GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
3093
3094         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
3095         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
3096         checkGLcall("glAttachObjectARB");
3097
3098         /* Bind vertex attributes to a corresponding index number to match
3099          * the same index numbers as ARB_vertex_programs (makes loading
3100          * vertex attributes simpler).  With this method, we can use the
3101          * exact same code to load the attributes later for both ARB and
3102          * GLSL shaders.
3103          *
3104          * We have to do this here because we need to know the Program ID
3105          * in order to make the bindings work, and it has to be done prior
3106          * to linking the GLSL program. */
3107         for (i = 0; i < max_attribs; ++i) {
3108             if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
3109                 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
3110                 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
3111             }
3112         }
3113         checkGLcall("glBindAttribLocationARB");
3114
3115         list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3116     }
3117
3118     /* Attach GLSL pshader */
3119     if (pshader_id) {
3120         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3121         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3122         checkGLcall("glAttachObjectARB");
3123
3124         list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3125     }
3126
3127     /* Link the program */
3128     TRACE("Linking GLSL shader program %u\n", programId);
3129     GL_EXTCALL(glLinkProgramARB(programId));
3130     print_glsl_info_log(&GLINFO_LOCATION, programId);
3131
3132     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3133     for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3134         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3135         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3136     }
3137     for (i = 0; i < MAX_CONST_I; ++i) {
3138         snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
3139         entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3140     }
3141     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3142     for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3143         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3144         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3145     }
3146     for (i = 0; i < MAX_CONST_I; ++i) {
3147         snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
3148         entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3149     }
3150
3151     entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
3152     entry->bumpenvmat_location = GL_EXTCALL(glGetUniformLocationARB(programId, "bumpenvmat"));
3153     entry->luminancescale_location = GL_EXTCALL(glGetUniformLocationARB(programId, "luminancescale"));
3154     entry->luminanceoffset_location = GL_EXTCALL(glGetUniformLocationARB(programId, "luminanceoffset"));
3155     entry->srgb_comparison_location = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_comparison"));
3156     entry->srgb_mul_low_location = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_mul_low"));
3157     entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3158     checkGLcall("Find glsl program uniform locations");
3159
3160     /* Set the shader to allow uniform loading on it */
3161     GL_EXTCALL(glUseProgramObjectARB(programId));
3162     checkGLcall("glUseProgramObjectARB(programId)");
3163
3164     /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
3165      * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
3166      * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
3167      * vertex shader with fixed function pixel processing is used we make sure that the card
3168      * supports enough samplers to allow the max number of vertex samplers with all possible
3169      * fixed function fragment processing setups. So once the program is linked these samplers
3170      * won't change.
3171      */
3172     if(vshader_id) {
3173         /* Load vertex shader samplers */
3174         shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
3175     }
3176     if(pshader_id) {
3177         /* Load pixel shader samplers */
3178         shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
3179     }
3180 }
3181
3182 static GLhandleARB create_glsl_blt_shader(WineD3D_GL_Info *gl_info) {
3183     GLhandleARB program_id;
3184     GLhandleARB vshader_id, pshader_id;
3185     const char *blt_vshader[] = {
3186         "void main(void)\n"
3187         "{\n"
3188         "    gl_Position = gl_Vertex;\n"
3189         "    gl_FrontColor = vec4(1.0);\n"
3190         "    gl_TexCoord[0].x = (gl_Vertex.x * 0.5) + 0.5;\n"
3191         "    gl_TexCoord[0].y = (-gl_Vertex.y * 0.5) + 0.5;\n"
3192         "}\n"
3193     };
3194
3195     const char *blt_pshader[] = {
3196         "uniform sampler2D sampler;\n"
3197         "void main(void)\n"
3198         "{\n"
3199         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3200         "}\n"
3201     };
3202
3203     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3204     GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3205     GL_EXTCALL(glCompileShaderARB(vshader_id));
3206
3207     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3208     GL_EXTCALL(glShaderSourceARB(pshader_id, 1, blt_pshader, NULL));
3209     GL_EXTCALL(glCompileShaderARB(pshader_id));
3210
3211     program_id = GL_EXTCALL(glCreateProgramObjectARB());
3212     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3213     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3214     GL_EXTCALL(glLinkProgramARB(program_id));
3215
3216     print_glsl_info_log(&GLINFO_LOCATION, program_id);
3217
3218     /* Once linked we can mark the shaders for deletion. They will be deleted once the program
3219      * is destroyed
3220      */
3221     GL_EXTCALL(glDeleteObjectARB(vshader_id));
3222     GL_EXTCALL(glDeleteObjectARB(pshader_id));
3223     return program_id;
3224 }
3225
3226 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3227     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3228     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3229     GLhandleARB program_id = 0;
3230
3231     if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3232     else This->stateBlock->glsl_program = NULL;
3233
3234     program_id = This->stateBlock->glsl_program ? This->stateBlock->glsl_program->programId : 0;
3235     if (program_id) TRACE("Using GLSL program %u\n", program_id);
3236     GL_EXTCALL(glUseProgramObjectARB(program_id));
3237     checkGLcall("glUseProgramObjectARB");
3238 }
3239
3240 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface) {
3241     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3242     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3243     struct shader_glsl_priv *priv = (struct shader_glsl_priv *) This->shader_priv;
3244     static GLhandleARB loc = -1;
3245
3246     if (!priv->depth_blt_glsl_program_id) {
3247         priv->depth_blt_glsl_program_id = create_glsl_blt_shader(gl_info);
3248         loc = GL_EXTCALL(glGetUniformLocationARB(priv->depth_blt_glsl_program_id, "sampler"));
3249     }
3250
3251     GL_EXTCALL(glUseProgramObjectARB(priv->depth_blt_glsl_program_id));
3252     GL_EXTCALL(glUniform1iARB(loc, 0));
3253 }
3254
3255 static void shader_glsl_destroy_depth_blt(IWineD3DDevice *iface) {
3256     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3257     struct shader_glsl_priv *priv = (struct shader_glsl_priv *) This->shader_priv;
3258     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3259
3260     if(priv->depth_blt_glsl_program_id) {
3261         GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_glsl_program_id));
3262         priv->depth_blt_glsl_program_id = 0;
3263     }
3264 }
3265
3266 static void shader_glsl_cleanup(IWineD3DDevice *iface) {
3267     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3268     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3269     GL_EXTCALL(glUseProgramObjectARB(0));
3270 }
3271
3272 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
3273     struct list *linked_programs;
3274     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
3275     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *) This->baseShader.device)->adapter->gl_info;
3276
3277     /* Note: Do not use QueryInterface here to find out which shader type this is because this code
3278      * can be called from IWineD3DBaseShader::Release
3279      */
3280     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
3281
3282     if(This->baseShader.prgId == 0) return;
3283     linked_programs = &This->baseShader.linked_programs;
3284
3285     TRACE("Deleting linked programs\n");
3286     if (linked_programs->next) {
3287         struct glsl_shader_prog_link *entry, *entry2;
3288
3289         if(pshader) {
3290             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
3291                 delete_glsl_program_entry(This->baseShader.device, entry);
3292             }
3293         } else {
3294             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
3295                 delete_glsl_program_entry(This->baseShader.device, entry);
3296             }
3297         }
3298     }
3299
3300     TRACE("Deleting shader object %u\n", This->baseShader.prgId);
3301     GL_EXTCALL(glDeleteObjectARB(This->baseShader.prgId));
3302     checkGLcall("glDeleteObjectARB");
3303     This->baseShader.prgId = 0;
3304     This->baseShader.is_compiled = FALSE;
3305 }
3306
3307 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
3308     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3309     This->shader_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
3310     return WINED3D_OK;
3311 }
3312
3313 static void shader_glsl_free(IWineD3DDevice *iface) {
3314     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3315     HeapFree(GetProcessHeap(), 0, This->shader_priv);
3316 }
3317
3318 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
3319     /* TODO: GL_EXT_bindable_uniform can be used to share constants accross shaders */
3320     return FALSE;
3321 }
3322
3323 const shader_backend_t glsl_shader_backend = {
3324     &shader_glsl_select,
3325     &shader_glsl_select_depth_blt,
3326     &shader_glsl_destroy_depth_blt,
3327     &shader_glsl_load_constants,
3328     &shader_glsl_cleanup,
3329     &shader_glsl_color_correction,
3330     &shader_glsl_destroy,
3331     &shader_glsl_alloc,
3332     &shader_glsl_free,
3333     &shader_glsl_dirty_const
3334 };