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