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