comctl32: We can now store binary files in the repository.
[wine] / dlls / wined3d / glsl_shader.c
1 /*
2  * GLSL pixel and vertex shader implementation
3  *
4  * Copyright 2006 Jason Green 
5  * Copyright 2006-2007 Henri Verbeet
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 /*
23  * D3D shader asm has swizzles on source parameters, and write masks for
24  * destination parameters. GLSL uses swizzles for both. The result of this is
25  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
26  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
27  * mask for the destination parameter into account.
28  */
29
30 #include "config.h"
31 #include <stdio.h>
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
36
37 #define GLINFO_LOCATION      (*gl_info)
38
39 typedef struct {
40     char reg_name[50];
41     char mask_str[6];
42 } glsl_dst_param_t;
43
44 typedef struct {
45     char reg_name[50];
46     char param_str[100];
47 } glsl_src_param_t;
48
49 typedef struct {
50     const char *name;
51     DWORD coord_mask;
52 } glsl_sample_function_t;
53
54 /** Prints the GLSL info log which will contain error messages if they exist */
55 void print_glsl_info_log(WineD3D_GL_Info *gl_info, GLhandleARB obj) {
56     
57     int infologLength = 0;
58     char *infoLog;
59
60     GL_EXTCALL(glGetObjectParameterivARB(obj,
61                GL_OBJECT_INFO_LOG_LENGTH_ARB,
62                &infologLength));
63
64     /* A size of 1 is just a null-terminated string, so the log should be bigger than
65      * that if there are errors. */
66     if (infologLength > 1)
67     {
68         infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
69         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
70         FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
71         HeapFree(GetProcessHeap(), 0, infoLog);
72     }
73 }
74
75 /**
76  * Loads (pixel shader) samplers
77  */
78 static void shader_glsl_load_psamplers(
79     WineD3D_GL_Info *gl_info,
80     IWineD3DStateBlock* iface) {
81
82     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
83     GLhandleARB programId = stateBlock->glsl_program->programId;
84     GLhandleARB name_loc;
85     int i;
86     char sampler_name[20];
87
88     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
89         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
90         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
91         if (name_loc != -1) {
92             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
93             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
94                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
95                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
96                 checkGLcall("glUniform1iARB");
97             } else {
98                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
99             }
100         }
101     }
102 }
103
104 static void shader_glsl_load_vsamplers(WineD3D_GL_Info *gl_info, IWineD3DStateBlock* iface) {
105     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
106     GLhandleARB programId = stateBlock->glsl_program->programId;
107     GLhandleARB name_loc;
108     char sampler_name[20];
109     int i;
110
111     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
112         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
113         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
114         if (name_loc != -1) {
115             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
116             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
117                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
118                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
119                 checkGLcall("glUniform1iARB");
120             } else {
121                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
122             }
123         }
124     }
125 }
126
127 /** 
128  * Loads floating point constants (aka uniforms) into the currently set GLSL program.
129  * When constant_list == NULL, it will load all the constants.
130  */
131 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
132         unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
133         struct list *constant_list) {
134     constants_entry *constant;
135     local_constant* lconst;
136     GLhandleARB tmp_loc;
137     DWORD i, j, k;
138     DWORD *idx;
139
140     if (TRACE_ON(d3d_shader)) {
141         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
142             idx = constant->idx;
143             j = constant->count;
144             while (j--) {
145                 i = *idx++;
146                 tmp_loc = constant_locations[i];
147                 if (tmp_loc != -1) {
148                     TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
149                             constants[i * 4 + 0], constants[i * 4 + 1],
150                             constants[i * 4 + 2], constants[i * 4 + 3]);
151                 }
152             }
153         }
154     }
155
156     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
157     if(WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1 &&
158        shader_is_pshader_version(This->baseShader.hex_version)) {
159         float lcl_const[4];
160
161         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
162             idx = constant->idx;
163             j = constant->count;
164             while (j--) {
165                 i = *idx++;
166                 tmp_loc = constant_locations[i];
167                 if (tmp_loc != -1) {
168                     /* We found this uniform name in the program - go ahead and send the data */
169                     k = i * 4;
170                     if(constants[k + 0] < -1.0) lcl_const[0] = -1.0;
171                     else if(constants[k + 0] > 1.0) lcl_const[0] = 1.0;
172                     else lcl_const[0] = constants[k + 0];
173                     if(constants[k + 1] < -1.0) lcl_const[1] = -1.0;
174                     else if(constants[k + 1] > 1.0) lcl_const[1] = 1.0;
175                     else lcl_const[1] = constants[k + 1];
176                     if(constants[k + 2] < -1.0) lcl_const[2] = -1.0;
177                     else if(constants[k + 2] > 1.0) lcl_const[2] = 1.0;
178                     else lcl_const[2] = constants[k + 2];
179                     if(constants[k + 3] < -1.0) lcl_const[3] = -1.0;
180                     else if(constants[k + 3] > 1.0) lcl_const[3] = 1.0;
181                     else lcl_const[3] = constants[k + 3];
182
183                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, lcl_const));
184                 }
185             }
186         }
187     } else {
188         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
189             idx = constant->idx;
190             j = constant->count;
191             while (j--) {
192                 i = *idx++;
193                 tmp_loc = constant_locations[i];
194                 if (tmp_loc != -1) {
195                     /* We found this uniform name in the program - go ahead and send the data */
196                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
197                 }
198             }
199         }
200     }
201     checkGLcall("glUniform4fvARB()");
202
203     /* Load immediate constants */
204     if (TRACE_ON(d3d_shader)) {
205         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
206             tmp_loc = constant_locations[lconst->idx];
207             if (tmp_loc != -1) {
208                 GLfloat* values = (GLfloat*)lconst->value;
209                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
210                         values[0], values[1], values[2], values[3]);
211             }
212         }
213     }
214     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
215     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
216         tmp_loc = constant_locations[lconst->idx];
217         if (tmp_loc != -1) {
218             /* We found this uniform name in the program - go ahead and send the data */
219             GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
220         }
221     }
222     checkGLcall("glUniform4fvARB()");
223 }
224
225 /** 
226  * Loads integer constants (aka uniforms) into the currently set GLSL program.
227  * When @constants_set == NULL, it will load all the constants.
228  */
229 static void shader_glsl_load_constantsI(
230     IWineD3DBaseShaderImpl* This,
231     WineD3D_GL_Info *gl_info,
232     GLhandleARB programId,
233     unsigned max_constants,
234     int* constants,
235     BOOL* constants_set) {
236     
237     GLhandleARB tmp_loc;
238     int i;
239     char tmp_name[8];
240     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
241     const char* prefix = is_pshader? "PI":"VI";
242     struct list* ptr;
243
244     for (i=0; i<max_constants; ++i) {
245         if (NULL == constants_set || constants_set[i]) {
246
247             TRACE_(d3d_constants)("Loading constants %i: %i, %i, %i, %i\n",
248                   i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
249
250             /* TODO: Benchmark and see if it would be beneficial to store the 
251              * locations of the constants to avoid looking up each time */
252             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
253             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
254             if (tmp_loc != -1) {
255                 /* We found this uniform name in the program - go ahead and send the data */
256                 GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, &constants[i*4]));
257                 checkGLcall("glUniform4ivARB");
258             }
259         }
260     }
261
262     /* Load immediate constants */
263     ptr = list_head(&This->baseShader.constantsI);
264     while (ptr) {
265         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
266         unsigned int idx = lconst->idx;
267         GLint* values = (GLint*) lconst->value;
268
269         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
270             values[0], values[1], values[2], values[3]);
271
272         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
273         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
274         if (tmp_loc != -1) {
275             /* We found this uniform name in the program - go ahead and send the data */
276             GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, values));
277             checkGLcall("glUniform4ivARB");
278         }
279         ptr = list_next(&This->baseShader.constantsI, ptr);
280     }
281 }
282
283 /** 
284  * Loads boolean constants (aka uniforms) into the currently set GLSL program.
285  * When @constants_set == NULL, it will load all the constants.
286  */
287 static void shader_glsl_load_constantsB(
288     IWineD3DBaseShaderImpl* This,
289     WineD3D_GL_Info *gl_info,
290     GLhandleARB programId,
291     unsigned max_constants,
292     BOOL* constants,
293     BOOL* constants_set) {
294     
295     GLhandleARB tmp_loc;
296     int i;
297     char tmp_name[8];
298     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
299     const char* prefix = is_pshader? "PB":"VB";
300     struct list* ptr;
301
302     for (i=0; i<max_constants; ++i) {
303         if (NULL == constants_set || constants_set[i]) {
304
305             TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i*4]);
306
307             /* TODO: Benchmark and see if it would be beneficial to store the 
308              * locations of the constants to avoid looking up each time */
309             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
310             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
311             if (tmp_loc != -1) {
312                 /* We found this uniform name in the program - go ahead and send the data */
313                 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i*4]));
314                 checkGLcall("glUniform1ivARB");
315             }
316         }
317     }
318
319     /* Load immediate constants */
320     ptr = list_head(&This->baseShader.constantsB);
321     while (ptr) {
322         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
323         unsigned int idx = lconst->idx;
324         GLint* values = (GLint*) lconst->value;
325
326         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
327
328         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
329         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
330         if (tmp_loc != -1) {
331             /* We found this uniform name in the program - go ahead and send the data */
332             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
333             checkGLcall("glUniform1ivARB");
334         }
335         ptr = list_next(&This->baseShader.constantsB, ptr);
336     }
337 }
338
339
340
341 /**
342  * Loads the app-supplied constants into the currently set GLSL program.
343  */
344 void shader_glsl_load_constants(
345     IWineD3DDevice* device,
346     char usePixelShader,
347     char useVertexShader) {
348    
349     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
350     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
351     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
352
353     GLhandleARB *constant_locations;
354     struct list *constant_list;
355     GLhandleARB programId;
356     GLint pos;
357
358     if (!stateBlock->glsl_program) {
359         /* No GLSL program set - nothing to do. */
360         return;
361     }
362     programId = stateBlock->glsl_program->programId;
363
364     if (useVertexShader) {
365         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
366         GLint pos;
367
368         constant_locations = stateBlock->glsl_program->vuniformF_locations;
369         constant_list = &stateBlock->set_vconstantsF;
370
371         /* Load vertex shader samplers */
372         shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)stateBlock);
373
374         /* Load DirectX 9 float constants/uniforms for vertex shader */
375         shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
376                 stateBlock->vertexShaderConstantF, constant_locations, constant_list);
377
378         /* Load DirectX 9 integer constants/uniforms for vertex shader */
379         shader_glsl_load_constantsI(vshader, gl_info, programId, MAX_CONST_I,
380                                     stateBlock->vertexShaderConstantI,
381                                     stateBlock->changed.vertexShaderConstantsI);
382
383         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
384         shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
385                                     stateBlock->vertexShaderConstantB,
386                                     stateBlock->changed.vertexShaderConstantsB);
387
388         /* Upload the position fixup params */
389         pos = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
390         checkGLcall("glGetUniformLocationARB");
391         GL_EXTCALL(glUniform4fvARB(pos, 1, &deviceImpl->posFixup[0]));
392         checkGLcall("glUniform4fvARB");
393     }
394
395     if (usePixelShader) {
396
397         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
398
399         constant_locations = stateBlock->glsl_program->puniformF_locations;
400         constant_list = &stateBlock->set_pconstantsF;
401
402         /* Load pixel shader samplers */
403         shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*) stateBlock);
404
405         /* Load DirectX 9 float constants/uniforms for pixel shader */
406         shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
407                 stateBlock->pixelShaderConstantF, constant_locations, constant_list);
408
409         /* Load DirectX 9 integer constants/uniforms for pixel shader */
410         shader_glsl_load_constantsI(pshader, gl_info, programId, MAX_CONST_I,
411                                     stateBlock->pixelShaderConstantI, 
412                                     stateBlock->changed.pixelShaderConstantsI);
413
414         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
415         shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
416                                     stateBlock->pixelShaderConstantB, 
417                                     stateBlock->changed.pixelShaderConstantsB);
418
419         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
420          * It can't be 0 for a valid texbem instruction.
421          */
422         if(((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat != -1) {
423             float *data = (float *) &stateBlock->textureState[(int) ((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat][WINED3DTSS_BUMPENVMAT00];
424             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "bumpenvmat"));
425             checkGLcall("glGetUniformLocationARB");
426             GL_EXTCALL(glUniformMatrix2fvARB(pos, 1, 0, data));
427             checkGLcall("glUniformMatrix2fvARB");
428
429             /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
430              * is set too, so we can check that in the needsbumpmat check
431              */
432             if(((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams != -1) {
433                 int stage = ((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams;
434                 GLfloat *scale = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
435                 GLfloat *offset = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
436
437                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminancescale"));
438                 checkGLcall("glGetUniformLocationARB");
439                 GL_EXTCALL(glUniform1fvARB(pos, 1, scale));
440                 checkGLcall("glUniform1fvARB");
441                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminanceoffset"));
442                 checkGLcall("glGetUniformLocationARB");
443                 GL_EXTCALL(glUniform1fvARB(pos, 1, offset));
444                 checkGLcall("glUniform1fvARB");
445             }
446         }
447     }
448 }
449
450 /** Generate the variable & register declarations for the GLSL output target */
451 void shader_generate_glsl_declarations(
452     IWineD3DBaseShader *iface,
453     shader_reg_maps* reg_maps,
454     SHADER_BUFFER* buffer,
455     WineD3D_GL_Info* gl_info) {
456
457     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
458     int i;
459
460     /* There are some minor differences between pixel and vertex shaders */
461     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
462     char prefix = pshader ? 'P' : 'V';
463
464     /* Prototype the subroutines */
465     for (i = 0; i < This->baseShader.limits.label; i++) {
466         if (reg_maps->labels[i])
467             shader_addline(buffer, "void subroutine%lu();\n", i);
468     }
469
470     /* Declare the constants (aka uniforms) */
471     if (This->baseShader.limits.constant_float > 0) {
472         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
473                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
474         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
475     }
476
477     if (This->baseShader.limits.constant_int > 0)
478         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
479
480     if (This->baseShader.limits.constant_bool > 0)
481         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
482
483     if(!pshader)
484         shader_addline(buffer, "uniform vec4 posFixup;\n");
485     else if(reg_maps->bumpmat != -1) {
486         shader_addline(buffer, "uniform mat2 bumpenvmat;\n");
487         if(reg_maps->luminanceparams) {
488             shader_addline(buffer, "uniform float luminancescale;\n");
489             shader_addline(buffer, "uniform float luminanceoffset;\n");
490         }
491     }
492
493     /* Declare texture samplers */ 
494     for (i = 0; i < This->baseShader.limits.sampler; i++) {
495         if (reg_maps->samplers[i]) {
496
497             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
498             switch (stype) {
499
500                 case WINED3DSTT_1D:
501                     shader_addline(buffer, "uniform sampler1D %csampler%lu;\n", prefix, i);
502                     break;
503                 case WINED3DSTT_2D:
504                     shader_addline(buffer, "uniform sampler2D %csampler%lu;\n", prefix, i);
505                     break;
506                 case WINED3DSTT_CUBE:
507                     shader_addline(buffer, "uniform samplerCube %csampler%lu;\n", prefix, i);
508                     break;
509                 case WINED3DSTT_VOLUME:
510                     shader_addline(buffer, "uniform sampler3D %csampler%lu;\n", prefix, i);
511                     break;
512                 default:
513                     shader_addline(buffer, "uniform unsupported_sampler %csampler%lu;\n", prefix, i);
514                     FIXME("Unrecognized sampler type: %#x\n", stype);
515                     break;
516             }
517         }
518     }
519     
520     /* Declare address variables */
521     for (i = 0; i < This->baseShader.limits.address; i++) {
522         if (reg_maps->address[i])
523             shader_addline(buffer, "ivec4 A%d;\n", i);
524     }
525
526     /* Declare texture coordinate temporaries and initialize them */
527     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
528         if (reg_maps->texcoord[i]) 
529             shader_addline(buffer, "vec4 T%lu = gl_TexCoord[%lu];\n", i, i);
530     }
531
532     /* Declare input register temporaries */
533     for (i=0; i < This->baseShader.limits.packed_input; i++) {
534         if (reg_maps->packed_input[i])
535             shader_addline(buffer, "vec4 IN%lu;\n", i);
536     }
537
538     /* Declare output register temporaries */
539     for (i = 0; i < This->baseShader.limits.packed_output; i++) {
540         if (reg_maps->packed_output[i])
541             shader_addline(buffer, "vec4 OUT%lu;\n", i);
542     }
543
544     /* Declare temporary variables */
545     for(i = 0; i < This->baseShader.limits.temporary; i++) {
546         if (reg_maps->temporary[i])
547             shader_addline(buffer, "vec4 R%lu;\n", i);
548     }
549
550     /* Declare attributes */
551     for (i = 0; i < This->baseShader.limits.attributes; i++) {
552         if (reg_maps->attributes[i])
553             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
554     }
555
556     /* Declare loop register aL */
557     if (reg_maps->loop) {
558         shader_addline(buffer, "int aL;\n");
559         shader_addline(buffer, "int tmpInt;\n");
560     }
561     
562     /* Temporary variables for matrix operations */
563     shader_addline(buffer, "vec4 tmp0;\n");
564     shader_addline(buffer, "vec4 tmp1;\n");
565
566     /* Start the main program */
567     shader_addline(buffer, "void main() {\n");
568 }
569
570 /*****************************************************************************
571  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
572  *
573  * For more information, see http://wiki.winehq.org/DirectX-Shaders
574  ****************************************************************************/
575
576 /* Prototypes */
577 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
578         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
579
580 /** Used for opcode modifiers - They multiply the result by the specified amount */
581 static const char * const shift_glsl_tab[] = {
582     "",           /*  0 (none) */ 
583     "2.0 * ",     /*  1 (x2)   */ 
584     "4.0 * ",     /*  2 (x4)   */ 
585     "8.0 * ",     /*  3 (x8)   */ 
586     "16.0 * ",    /*  4 (x16)  */ 
587     "32.0 * ",    /*  5 (x32)  */ 
588     "",           /*  6 (x64)  */ 
589     "",           /*  7 (x128) */ 
590     "",           /*  8 (d256) */ 
591     "",           /*  9 (d128) */ 
592     "",           /* 10 (d64)  */ 
593     "",           /* 11 (d32)  */ 
594     "0.0625 * ",  /* 12 (d16)  */ 
595     "0.125 * ",   /* 13 (d8)   */ 
596     "0.25 * ",    /* 14 (d4)   */ 
597     "0.5 * "      /* 15 (d2)   */ 
598 };
599
600 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
601 static void shader_glsl_gen_modifier (
602     const DWORD instr,
603     const char *in_reg,
604     const char *in_regswizzle,
605     char *out_str) {
606
607     out_str[0] = 0;
608     
609     if (instr == WINED3DSIO_TEXKILL)
610         return;
611
612     switch (instr & WINED3DSP_SRCMOD_MASK) {
613     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
614     case WINED3DSPSM_DW:
615     case WINED3DSPSM_NONE:
616         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
617         break;
618     case WINED3DSPSM_NEG:
619         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
620         break;
621     case WINED3DSPSM_NOT:
622         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
623         break;
624     case WINED3DSPSM_BIAS:
625         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
626         break;
627     case WINED3DSPSM_BIASNEG:
628         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
629         break;
630     case WINED3DSPSM_SIGN:
631         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
632         break;
633     case WINED3DSPSM_SIGNNEG:
634         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
635         break;
636     case WINED3DSPSM_COMP:
637         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
638         break;
639     case WINED3DSPSM_X2:
640         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
641         break;
642     case WINED3DSPSM_X2NEG:
643         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
644         break;
645     case WINED3DSPSM_ABS:
646         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
647         break;
648     case WINED3DSPSM_ABSNEG:
649         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
650         break;
651     default:
652         FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
653         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
654     }
655 }
656
657 /** Writes the GLSL variable name that corresponds to the register that the
658  * DX opcode parameter is trying to access */
659 static void shader_glsl_get_register_name(
660     const DWORD param,
661     const DWORD addr_token,
662     char* regstr,
663     BOOL* is_color,
664     SHADER_OPCODE_ARG* arg) {
665
666     /* oPos, oFog and oPts in D3D */
667     static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
668
669     DWORD reg = param & WINED3DSP_REGNUM_MASK;
670     DWORD regtype = shader_get_regtype(param);
671     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
672     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
673     WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
674
675     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
676     char tmpStr[50];
677
678     *is_color = FALSE;   
679  
680     switch (regtype) {
681     case WINED3DSPR_TEMP:
682         sprintf(tmpStr, "R%u", reg);
683     break;
684     case WINED3DSPR_INPUT:
685         if (pshader) {
686             /* Pixel shaders >= 3.0 */
687             if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
688                 sprintf(tmpStr, "IN%u", reg);
689              else {
690                 if (reg==0)
691                     strcpy(tmpStr, "gl_Color");
692                 else
693                     strcpy(tmpStr, "gl_SecondaryColor");
694             }
695         } else {
696             if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
697                *is_color = TRUE;
698             sprintf(tmpStr, "attrib%u", reg);
699         } 
700         break;
701     case WINED3DSPR_CONST:
702     {
703         const char* prefix = pshader? "PC":"VC";
704
705         /* Relative addressing */
706         if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
707
708            /* Relative addressing on shaders 2.0+ have a relative address token, 
709             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
710            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
711                glsl_src_param_t rel_param;
712                shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
713                sprintf(tmpStr, "%s[%s + %u]", prefix, rel_param.param_str, reg);
714            } else
715                sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
716
717         } else
718              sprintf(tmpStr, "%s[%u]", prefix, reg);
719
720         break;
721     }
722     case WINED3DSPR_CONSTINT:
723         if (pshader)
724             sprintf(tmpStr, "PI[%u]", reg);
725         else
726             sprintf(tmpStr, "VI[%u]", reg);
727         break;
728     case WINED3DSPR_CONSTBOOL:
729         if (pshader)
730             sprintf(tmpStr, "PB[%u]", reg);
731         else
732             sprintf(tmpStr, "VB[%u]", reg);
733         break;
734     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
735         if (pshader) {
736             sprintf(tmpStr, "T%u", reg);
737         } else {
738             sprintf(tmpStr, "A%u", reg);
739         }
740     break;
741     case WINED3DSPR_LOOP:
742         sprintf(tmpStr, "aL");
743     break;
744     case WINED3DSPR_SAMPLER:
745         if (pshader)
746             sprintf(tmpStr, "Psampler%u", reg);
747         else
748             sprintf(tmpStr, "Vsampler%u", reg);
749     break;
750     case WINED3DSPR_COLOROUT:
751         if (reg >= GL_LIMITS(buffers)) {
752             WARN("Write to render target %u, only %d supported\n", reg, 4);
753         }
754         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
755             sprintf(tmpStr, "gl_FragData[%u]", reg);
756         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
757             sprintf(tmpStr, "gl_FragColor");
758         }
759     break;
760     case WINED3DSPR_RASTOUT:
761         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
762     break;
763     case WINED3DSPR_DEPTHOUT:
764         sprintf(tmpStr, "gl_FragDepth");
765     break;
766     case WINED3DSPR_ATTROUT:
767         if (reg == 0) {
768             sprintf(tmpStr, "gl_FrontColor");
769         } else {
770             sprintf(tmpStr, "gl_FrontSecondaryColor");
771         }
772     break;
773     case WINED3DSPR_TEXCRDOUT:
774         /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
775         if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
776             sprintf(tmpStr, "OUT%u", reg);
777         else
778             sprintf(tmpStr, "gl_TexCoord[%u]", reg);
779     break;
780     case WINED3DSPR_MISCTYPE:
781         if (reg == 0) {
782             /* vPos */
783             sprintf(tmpStr, "gl_FragCoord");
784         } else {
785             /* gl_FrontFacing could be used for vFace, but note that
786              * gl_FrontFacing is a bool, while vFace is a float for
787              * which the sign determines front/back */
788             FIXME("Unhandled misctype register %d\n", reg);
789             sprintf(tmpStr, "unrecognized_register");
790         }
791         break;
792     default:
793         FIXME("Unhandled register name Type(%d)\n", regtype);
794         sprintf(tmpStr, "unrecognized_register");
795     break;
796     }
797
798     strcat(regstr, tmpStr);
799 }
800
801 /* Get the GLSL write mask for the destination register */
802 static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
803     char *ptr = write_mask;
804     DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
805
806     if (shader_is_scalar(param)) {
807         mask = WINED3DSP_WRITEMASK_0;
808     } else {
809         *ptr++ = '.';
810         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
811         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
812         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
813         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
814     }
815
816     *ptr = '\0';
817
818     return mask;
819 }
820
821 static size_t shader_glsl_get_write_mask_size(DWORD write_mask) {
822     size_t size = 0;
823
824     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
825     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
826     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
827     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
828
829     return size;
830 }
831
832 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
833     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
834      * but addressed as "rgba". To fix this we need to swap the register's x
835      * and z components. */
836     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
837     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
838     char *ptr = swizzle_str;
839
840     if (!shader_is_scalar(param)) {
841         *ptr++ = '.';
842         /* swizzle bits fields: wwzzyyxx */
843         if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
844         if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
845         if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
846         if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
847     }
848
849     *ptr = '\0';
850 }
851
852 /* From a given parameter token, generate the corresponding GLSL string.
853  * Also, return the actual register name and swizzle in case the
854  * caller needs this information as well. */
855 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
856         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param) {
857     BOOL is_color = FALSE;
858     char swizzle_str[6];
859
860     src_param->reg_name[0] = '\0';
861     src_param->param_str[0] = '\0';
862     swizzle_str[0] = '\0';
863
864     shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
865
866     shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
867     shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
868 }
869
870 /* From a given parameter token, generate the corresponding GLSL string.
871  * Also, return the actual register name and swizzle in case the
872  * caller needs this information as well. */
873 static DWORD shader_glsl_add_dst_param(SHADER_OPCODE_ARG* arg, const DWORD param,
874         const DWORD addr_token, glsl_dst_param_t *dst_param) {
875     BOOL is_color = FALSE;
876
877     dst_param->mask_str[0] = '\0';
878     dst_param->reg_name[0] = '\0';
879
880     shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
881     return shader_glsl_get_write_mask(param, dst_param->mask_str);
882 }
883
884 /* Append the destination part of the instruction to the buffer, return the effective write mask */
885 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg, const DWORD param) {
886     glsl_dst_param_t dst_param;
887     DWORD mask;
888     int shift;
889
890     mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);
891
892     if(mask) {
893         shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
894         shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
895     }
896
897     return mask;
898 }
899
900 /* Append the destination part of the instruction to the buffer, return the effective write mask */
901 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg) {
902     return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
903 }
904
905 /** Process GLSL instruction modifiers */
906 void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
907     
908     DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
909  
910     if (arg->opcode->dst_token && mask != 0) {
911         glsl_dst_param_t dst_param;
912
913         shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
914
915         if (mask & WINED3DSPDM_SATURATE) {
916             /* _SAT means to clamp the value of the register to between 0 and 1 */
917             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
918                     dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
919         }
920         if (mask & WINED3DSPDM_MSAMPCENTROID) {
921             FIXME("_centroid modifier not handled\n");
922         }
923         if (mask & WINED3DSPDM_PARTIALPRECISION) {
924             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
925         }
926     }
927 }
928
929 static inline const char* shader_get_comp_op(
930     const DWORD opcode) {
931
932     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
933     switch (op) {
934         case COMPARISON_GT: return ">";
935         case COMPARISON_EQ: return "==";
936         case COMPARISON_GE: return ">=";
937         case COMPARISON_LT: return "<";
938         case COMPARISON_NE: return "!=";
939         case COMPARISON_LE: return "<=";
940         default:
941             FIXME("Unrecognized comparison value: %u\n", op);
942             return "(\?\?)";
943     }
944 }
945
946 static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, glsl_sample_function_t *sample_function) {
947     /* Note that there's no such thing as a projected cube texture. */
948     switch(sampler_type) {
949         case WINED3DSTT_1D:
950             sample_function->name = projected ? "texture1DProj" : "texture1D";
951             sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
952             break;
953         case WINED3DSTT_2D:
954             sample_function->name = projected ? "texture2DProj" : "texture2D";
955             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
956             break;
957         case WINED3DSTT_CUBE:
958             sample_function->name = "textureCube";
959             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
960             break;
961         case WINED3DSTT_VOLUME:
962             sample_function->name = projected ? "texture3DProj" : "texture3D";
963             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
964             break;
965         default:
966             sample_function->name = "";
967             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
968             break;
969     }
970 }
971
972
973 /*****************************************************************************
974  * 
975  * Begin processing individual instruction opcodes
976  * 
977  ****************************************************************************/
978
979 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
980 void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
981     CONST SHADER_OPCODE* curOpcode = arg->opcode;
982     SHADER_BUFFER* buffer = arg->buffer;
983     glsl_src_param_t src0_param;
984     glsl_src_param_t src1_param;
985     DWORD write_mask;
986     char op;
987
988     /* Determine the GLSL operator to use based on the opcode */
989     switch (curOpcode->opcode) {
990         case WINED3DSIO_MUL: op = '*'; break;
991         case WINED3DSIO_ADD: op = '+'; break;
992         case WINED3DSIO_SUB: op = '-'; break;
993         default:
994             op = ' ';
995             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
996             break;
997     }
998
999     write_mask = shader_glsl_append_dst(buffer, arg);
1000     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1001     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1002     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1003 }
1004
1005 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1006 void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
1007     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1008     SHADER_BUFFER* buffer = arg->buffer;
1009     glsl_src_param_t src0_param;
1010     DWORD write_mask;
1011
1012     write_mask = shader_glsl_append_dst(buffer, arg);
1013     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1014
1015     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1016      * shader versions WINED3DSIO_MOVA is used for this. */
1017     if ((WINED3DSHADER_VERSION_MAJOR(shader->baseShader.hex_version) == 1 &&
1018             !shader_is_pshader_version(shader->baseShader.hex_version) &&
1019             shader_get_regtype(arg->dst) == WINED3DSPR_ADDR) ||
1020             arg->opcode->opcode == WINED3DSIO_MOVA) {
1021         /* We need to *round* to the nearest int here. */
1022         size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1023         if (mask_size > 1) {
1024             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);
1025         } else {
1026             shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1027         }
1028     } else {
1029         shader_addline(buffer, "%s);\n", src0_param.param_str);
1030     }
1031 }
1032
1033 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1034 void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
1035     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1036     SHADER_BUFFER* buffer = arg->buffer;
1037     glsl_src_param_t src0_param;
1038     glsl_src_param_t src1_param;
1039     DWORD dst_write_mask, src_write_mask;
1040     size_t dst_size = 0;
1041
1042     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1043     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1044
1045     /* dp3 works on vec3, dp4 on vec4 */
1046     if (curOpcode->opcode == WINED3DSIO_DP4) {
1047         src_write_mask = WINED3DSP_WRITEMASK_ALL;
1048     } else {
1049         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1050     }
1051
1052     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
1053     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1054
1055     if (dst_size > 1) {
1056         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1057     } else {
1058         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1059     }
1060 }
1061
1062 /* Note that this instruction has some restrictions. The destination write mask
1063  * can't contain the w component, and the source swizzles have to be .xyzw */
1064 void shader_glsl_cross(SHADER_OPCODE_ARG *arg) {
1065     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1066     glsl_src_param_t src0_param;
1067     glsl_src_param_t src1_param;
1068     char dst_mask[6];
1069
1070     shader_glsl_get_write_mask(arg->dst, dst_mask);
1071     shader_glsl_append_dst(arg->buffer, arg);
1072     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1073     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1074     shader_addline(arg->buffer, "cross(%s, %s).%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1075 }
1076
1077 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1078  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1079  * GLSL uses the value as-is. */
1080 void shader_glsl_pow(SHADER_OPCODE_ARG *arg) {
1081     SHADER_BUFFER *buffer = arg->buffer;
1082     glsl_src_param_t src0_param;
1083     glsl_src_param_t src1_param;
1084     DWORD dst_write_mask;
1085     size_t dst_size;
1086
1087     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1088     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1089
1090     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1091     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1092
1093     if (dst_size > 1) {
1094         shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1095     } else {
1096         shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1097     }
1098 }
1099
1100 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1101 void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
1102     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1103     SHADER_BUFFER* buffer = arg->buffer;
1104     glsl_src_param_t src_param;
1105     const char *instruction;
1106     char arguments[256];
1107     DWORD write_mask;
1108     unsigned i;
1109
1110     /* Determine the GLSL function to use based on the opcode */
1111     /* TODO: Possibly make this a table for faster lookups */
1112     switch (curOpcode->opcode) {
1113         case WINED3DSIO_MIN: instruction = "min"; break;
1114         case WINED3DSIO_MAX: instruction = "max"; break;
1115         case WINED3DSIO_ABS: instruction = "abs"; break;
1116         case WINED3DSIO_FRC: instruction = "fract"; break;
1117         case WINED3DSIO_NRM: instruction = "normalize"; break;
1118         case WINED3DSIO_LOGP:
1119         case WINED3DSIO_LOG: instruction = "log2"; break;
1120         case WINED3DSIO_EXP: instruction = "exp2"; break;
1121         case WINED3DSIO_SGN: instruction = "sign"; break;
1122         case WINED3DSIO_DSX: instruction = "dFdx"; break;
1123         case WINED3DSIO_DSY: instruction = "dFdy"; break;
1124         default: instruction = "";
1125             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1126             break;
1127     }
1128
1129     write_mask = shader_glsl_append_dst(buffer, arg);
1130
1131     arguments[0] = '\0';
1132     if (curOpcode->num_params > 0) {
1133         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
1134         strcat(arguments, src_param.param_str);
1135         for (i = 2; i < curOpcode->num_params; ++i) {
1136             strcat(arguments, ", ");
1137             shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
1138             strcat(arguments, src_param.param_str);
1139         }
1140     }
1141
1142     shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1143 }
1144
1145 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1146  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1147  *   dst.x = 2^(floor(src))
1148  *   dst.y = src - floor(src)
1149  *   dst.z = 2^src   (partial precision is allowed, but optional)
1150  *   dst.w = 1.0;
1151  * For 2.0 shaders, just do this (honoring writemask and swizzle):
1152  *   dst = 2^src;    (partial precision is allowed, but optional)
1153  */
1154 void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
1155     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1156     glsl_src_param_t src_param;
1157
1158     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1159
1160     if (shader->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
1161         char dst_mask[6];
1162
1163         shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1164         shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1165         shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1166         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1167
1168         shader_glsl_append_dst(arg->buffer, arg);
1169         shader_glsl_get_write_mask(arg->dst, dst_mask);
1170         shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1171     } else {
1172         DWORD write_mask;
1173         size_t mask_size;
1174
1175         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1176         mask_size = shader_glsl_get_write_mask_size(write_mask);
1177
1178         if (mask_size > 1) {
1179             shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1180         } else {
1181             shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1182         }
1183     }
1184 }
1185
1186 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1187 void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1188     glsl_src_param_t src_param;
1189     DWORD write_mask;
1190     size_t mask_size;
1191
1192     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1193     mask_size = shader_glsl_get_write_mask_size(write_mask);
1194     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1195
1196     if (mask_size > 1) {
1197         shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1198     } else {
1199         shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1200     }
1201 }
1202
1203 void shader_glsl_rsq(SHADER_OPCODE_ARG* arg) {
1204     SHADER_BUFFER* buffer = arg->buffer;
1205     glsl_src_param_t src_param;
1206     DWORD write_mask;
1207     size_t mask_size;
1208
1209     write_mask = shader_glsl_append_dst(buffer, arg);
1210     mask_size = shader_glsl_get_write_mask_size(write_mask);
1211
1212     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1213
1214     if (mask_size > 1) {
1215         shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1216     } else {
1217         shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1218     }
1219 }
1220
1221 /** Process signed comparison opcodes in GLSL. */
1222 void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1223     glsl_src_param_t src0_param;
1224     glsl_src_param_t src1_param;
1225     DWORD write_mask;
1226     size_t mask_size;
1227
1228     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1229     mask_size = shader_glsl_get_write_mask_size(write_mask);
1230     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1231     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1232
1233     if (mask_size > 1) {
1234         const char *compare;
1235
1236         switch(arg->opcode->opcode) {
1237             case WINED3DSIO_SLT: compare = "lessThan"; break;
1238             case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
1239             default: compare = "";
1240                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1241         }
1242
1243         shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1244                 src0_param.param_str, src1_param.param_str);
1245     } else {
1246         const char *compare;
1247
1248         switch(arg->opcode->opcode) {
1249             case WINED3DSIO_SLT: compare = "<"; break;
1250             case WINED3DSIO_SGE: compare = ">="; break;
1251             default: compare = "";
1252                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1253         }
1254
1255         shader_addline(arg->buffer, "(%s %s %s) ? 1.0 : 0.0);\n",
1256                 src0_param.param_str, compare, src1_param.param_str);
1257     }
1258 }
1259
1260 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1261 void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1262     glsl_src_param_t src0_param;
1263     glsl_src_param_t src1_param;
1264     glsl_src_param_t src2_param;
1265     DWORD write_mask, cmp_channel = 0;
1266     unsigned int i, j;
1267
1268     /* Cycle through all source0 channels */
1269     for (i=0; i<4; i++) {
1270         write_mask = 0;
1271         /* Find the destination channels which use the current source0 channel */
1272         for (j=0; j<4; j++) {
1273             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1274                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1275                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1276             }
1277         }
1278         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1279         if (!write_mask) continue;
1280
1281         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1282         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1283         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1284
1285         shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1286                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1287     }
1288 }
1289
1290 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1291 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
1292  * the compare is done per component of src0. */
1293 void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1294     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1295     glsl_src_param_t src0_param;
1296     glsl_src_param_t src1_param;
1297     glsl_src_param_t src2_param;
1298     DWORD write_mask, cmp_channel = 0;
1299     unsigned int i, j;
1300
1301     if (shader->baseShader.hex_version < WINED3DPS_VERSION(1, 4)) {
1302         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1303         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1304         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1305         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1306
1307         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
1308         if(arg->opcode_token & WINED3DSI_COISSUE) {
1309             shader_addline(arg->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
1310         } else {
1311             shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1312                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
1313         }
1314         return;
1315     }
1316     /* Cycle through all source0 channels */
1317     for (i=0; i<4; i++) {
1318         write_mask = 0;
1319         /* Find the destination channels which use the current source0 channel */
1320         for (j=0; j<4; j++) {
1321             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1322                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1323                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1324             }
1325         }
1326         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1327         if (!write_mask) continue;
1328
1329         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1330         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1331         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1332
1333         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1334                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1335     }
1336 }
1337
1338 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1339 void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1340     glsl_src_param_t src0_param;
1341     glsl_src_param_t src1_param;
1342     glsl_src_param_t src2_param;
1343     DWORD write_mask;
1344
1345     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1346     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1347     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1348     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1349     shader_addline(arg->buffer, "(%s * %s) + %s);\n",
1350             src0_param.param_str, src1_param.param_str, src2_param.param_str);
1351 }
1352
1353 /** Handles transforming all WINED3DSIO_M?x? opcodes for 
1354     Vertex shaders to GLSL codes */
1355 void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
1356     int i;
1357     int nComponents = 0;
1358     SHADER_OPCODE_ARG tmpArg;
1359    
1360     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1361
1362     /* Set constants for the temporary argument */
1363     tmpArg.shader      = arg->shader;
1364     tmpArg.buffer      = arg->buffer;
1365     tmpArg.src[0]      = arg->src[0];
1366     tmpArg.src_addr[0] = arg->src_addr[0];
1367     tmpArg.src_addr[1] = arg->src_addr[1];
1368     tmpArg.reg_maps = arg->reg_maps; 
1369     
1370     switch(arg->opcode->opcode) {
1371         case WINED3DSIO_M4x4:
1372             nComponents = 4;
1373             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1374             break;
1375         case WINED3DSIO_M4x3:
1376             nComponents = 3;
1377             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1378             break;
1379         case WINED3DSIO_M3x4:
1380             nComponents = 4;
1381             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1382             break;
1383         case WINED3DSIO_M3x3:
1384             nComponents = 3;
1385             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1386             break;
1387         case WINED3DSIO_M3x2:
1388             nComponents = 2;
1389             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1390             break;
1391         default:
1392             break;
1393     }
1394
1395     for (i = 0; i < nComponents; i++) {
1396         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1397         tmpArg.src[1]      = arg->src[1]+i;
1398         shader_glsl_dot(&tmpArg);
1399     }
1400 }
1401
1402 /**
1403     The LRP instruction performs a component-wise linear interpolation 
1404     between the second and third operands using the first operand as the
1405     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
1406     This is equivalent to mix(src2, src1, src0);
1407 */
1408 void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1409     glsl_src_param_t src0_param;
1410     glsl_src_param_t src1_param;
1411     glsl_src_param_t src2_param;
1412     DWORD write_mask;
1413
1414     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1415
1416     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1417     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1418     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1419
1420     shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
1421             src2_param.param_str, src1_param.param_str, src0_param.param_str);
1422 }
1423
1424 /** Process the WINED3DSIO_LIT instruction in GLSL:
1425  * dst.x = dst.w = 1.0
1426  * dst.y = (src0.x > 0) ? src0.x
1427  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
1428  *                                        where src.w is clamped at +- 128
1429  */
1430 void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1431     glsl_src_param_t src0_param;
1432     glsl_src_param_t src1_param;
1433     glsl_src_param_t src3_param;
1434     char dst_mask[6];
1435
1436     shader_glsl_append_dst(arg->buffer, arg);
1437     shader_glsl_get_write_mask(arg->dst, dst_mask);
1438
1439     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1440     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
1441     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
1442
1443     shader_addline(arg->buffer, "vec4(1.0, (%s > 0.0 ? %s : 0.0), (%s > 0.0 ? ((%s > 0.0) ? pow(%s, clamp(%s, -128.0, 128.0)) : 0.0) : 0.0), 1.0)%s);\n",
1444         src0_param.param_str, src0_param.param_str, src0_param.param_str, src1_param.param_str, src1_param.param_str, src3_param.param_str, dst_mask);
1445 }
1446
1447 /** Process the WINED3DSIO_DST instruction in GLSL:
1448  * dst.x = 1.0
1449  * dst.y = src0.x * src0.y
1450  * dst.z = src0.z
1451  * dst.w = src1.w
1452  */
1453 void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1454     glsl_src_param_t src0y_param;
1455     glsl_src_param_t src0z_param;
1456     glsl_src_param_t src1y_param;
1457     glsl_src_param_t src1w_param;
1458     char dst_mask[6];
1459
1460     shader_glsl_append_dst(arg->buffer, arg);
1461     shader_glsl_get_write_mask(arg->dst, dst_mask);
1462
1463     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
1464     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
1465     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
1466     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
1467
1468     shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
1469             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
1470 }
1471
1472 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
1473  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
1474  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
1475  * 
1476  * dst.x = cos(src0.?)
1477  * dst.y = sin(src0.?)
1478  * dst.z = dst.z
1479  * dst.w = dst.w
1480  */
1481 void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1482     glsl_src_param_t src0_param;
1483     DWORD write_mask;
1484
1485     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1486     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1487
1488     switch (write_mask) {
1489         case WINED3DSP_WRITEMASK_0:
1490             shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
1491             break;
1492
1493         case WINED3DSP_WRITEMASK_1:
1494             shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
1495             break;
1496
1497         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
1498             shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
1499             break;
1500
1501         default:
1502             ERR("Write mask should be .x, .y or .xy\n");
1503             break;
1504     }
1505 }
1506
1507 /** Process the WINED3DSIO_LOOP instruction in GLSL:
1508  * Start a for() loop where src1.y is the initial value of aL,
1509  *  increment aL by src1.z for a total of src1.x iterations.
1510  *  Need to use a temporary variable for this operation.
1511  */
1512 /* FIXME: I don't think nested loops will work correctly this way. */
1513 void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1514     glsl_src_param_t src1_param;
1515
1516     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
1517   
1518     shader_addline(arg->buffer, "for (tmpInt = 0, aL = %s.y; tmpInt < %s.x; tmpInt++, aL += %s.z) {\n",
1519             src1_param.reg_name, src1_param.reg_name, src1_param.reg_name);
1520 }
1521
1522 void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1523     shader_addline(arg->buffer, "}\n");
1524 }
1525
1526 void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
1527     glsl_src_param_t src0_param;
1528
1529     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1530     shader_addline(arg->buffer, "for (tmpInt = 0; tmpInt < %s; tmpInt++) {\n", src0_param.param_str);
1531 }
1532
1533 void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1534     glsl_src_param_t src0_param;
1535
1536     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1537     shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
1538 }
1539
1540 void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
1541     glsl_src_param_t src0_param;
1542     glsl_src_param_t src1_param;
1543
1544     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1545     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1546
1547     shader_addline(arg->buffer, "if (%s %s %s) {\n",
1548             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1549 }
1550
1551 void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
1552     shader_addline(arg->buffer, "} else {\n");
1553 }
1554
1555 void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
1556     shader_addline(arg->buffer, "break;\n");
1557 }
1558
1559 /* FIXME: According to MSDN the compare is done per component. */
1560 void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
1561     glsl_src_param_t src0_param;
1562     glsl_src_param_t src1_param;
1563
1564     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1565     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1566
1567     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
1568             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1569 }
1570
1571 void shader_glsl_label(SHADER_OPCODE_ARG* arg) {
1572
1573     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1574     shader_addline(arg->buffer, "}\n");
1575     shader_addline(arg->buffer, "void subroutine%lu () {\n",  snum);
1576 }
1577
1578 void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
1579     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1580     shader_addline(arg->buffer, "subroutine%lu();\n", snum);
1581 }
1582
1583 void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
1584     glsl_src_param_t src1_param;
1585
1586     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1587     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1588     shader_addline(arg->buffer, "if (%s) subroutine%lu();\n", src1_param.param_str, snum);
1589 }
1590
1591 /*********************************************
1592  * Pixel Shader Specific Code begins here
1593  ********************************************/
1594 void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
1595     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1596     DWORD hex_version = This->baseShader.hex_version;
1597     char dst_swizzle[6];
1598     glsl_sample_function_t sample_function;
1599     DWORD sampler_type;
1600     DWORD sampler_idx;
1601     BOOL projected;
1602     DWORD mask = 0;
1603
1604     /* All versions have a destination register */
1605     shader_glsl_append_dst(arg->buffer, arg);
1606
1607     /* 1.0-1.4: Use destination register as sampler source.
1608      * 2.0+: Use provided sampler source. */
1609     if (hex_version < WINED3DPS_VERSION(1,4)) {
1610         IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1611         DWORD flags;
1612
1613         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1614         flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1615
1616         if (flags & WINED3DTTFF_PROJECTED) {
1617             projected = TRUE;
1618             switch (flags & ~WINED3DTTFF_PROJECTED) {
1619                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
1620                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
1621                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
1622                 case WINED3DTTFF_COUNT4:
1623                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
1624             }
1625         } else {
1626             projected = FALSE;
1627         }
1628     } else if (hex_version < WINED3DPS_VERSION(2,0)) {
1629         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1630         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1631
1632         if (src_mod == WINED3DSPSM_DZ) {
1633             projected = TRUE;
1634             mask = WINED3DSP_WRITEMASK_2;
1635         } else if (src_mod == WINED3DSPSM_DW) {
1636             projected = TRUE;
1637             mask = WINED3DSP_WRITEMASK_3;
1638         } else {
1639             projected = FALSE;
1640         }
1641     } else {
1642         sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1643         if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
1644                 /* ps 2.0 texldp instruction always divides by the fourth component. */
1645                 projected = TRUE;
1646                 mask = WINED3DSP_WRITEMASK_3;
1647         } else {
1648             projected = FALSE;
1649         }
1650     }
1651
1652     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1653     shader_glsl_get_sample_function(sampler_type, projected, &sample_function);
1654     mask |= sample_function.coord_mask;
1655
1656     if (hex_version < WINED3DPS_VERSION(2,0)) {
1657         shader_glsl_get_write_mask(arg->dst, dst_swizzle);
1658     } else {
1659         shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
1660     }
1661
1662     /* 1.0-1.3: Use destination register as coordinate source.
1663        1.4+: Use provided coordinate source register. */
1664     if (hex_version < WINED3DPS_VERSION(1,4)) {
1665         char coord_mask[6];
1666         shader_glsl_get_write_mask(mask, coord_mask);
1667         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s)%s);\n",
1668                 sample_function.name, sampler_idx, sampler_idx, coord_mask, dst_swizzle);
1669     } else {
1670         glsl_src_param_t coord_param;
1671         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
1672         if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
1673             glsl_src_param_t bias;
1674             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);
1675
1676             shader_addline(arg->buffer, "%s(Psampler%u, %s, %s)%s);\n",
1677                     sample_function.name, sampler_idx, coord_param.param_str,
1678                     bias.param_str, dst_swizzle);
1679         } else {
1680             shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n",
1681                     sample_function.name, sampler_idx, coord_param.param_str, dst_swizzle);
1682         }
1683     }
1684 }
1685
1686 void shader_glsl_texldl(SHADER_OPCODE_ARG* arg) {
1687     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
1688     glsl_sample_function_t sample_function;
1689     glsl_src_param_t coord_param, lod_param;
1690     char dst_swizzle[6];
1691     DWORD sampler_type;
1692     DWORD sampler_idx;
1693
1694     shader_glsl_append_dst(arg->buffer, arg);
1695     shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
1696
1697     sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1698     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1699     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1700     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
1701
1702     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);
1703
1704     if (shader_is_pshader_version(This->baseShader.hex_version)) {
1705         /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
1706          * However, they seem to work just fine in fragment shaders as well. */
1707         WARN("Using %sLod in fragment shader.\n", sample_function.name);
1708         shader_addline(arg->buffer, "%sLod(Psampler%u, %s, %s)%s);\n",
1709                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
1710     } else {
1711         shader_addline(arg->buffer, "%sLod(Vsampler%u, %s, %s)%s);\n",
1712                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
1713     }
1714 }
1715
1716 void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {
1717
1718     /* FIXME: Make this work for more than just 2D textures */
1719     
1720     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1721     SHADER_BUFFER* buffer = arg->buffer;
1722     DWORD hex_version = This->baseShader.hex_version;
1723     DWORD write_mask;
1724     char dst_mask[6];
1725
1726     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1727     shader_glsl_get_write_mask(write_mask, dst_mask);
1728
1729     if (hex_version != WINED3DPS_VERSION(1,4)) {
1730         DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1731         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
1732     } else {
1733         DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
1734         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1735         char dst_swizzle[6];
1736
1737         shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);
1738
1739         if (src_mod == WINED3DSPSM_DZ) {
1740             glsl_src_param_t div_param;
1741             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1742             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
1743
1744             if (mask_size > 1) {
1745                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
1746             } else {
1747                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
1748             }
1749         } else if (src_mod == WINED3DSPSM_DW) {
1750             glsl_src_param_t div_param;
1751             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1752             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
1753
1754             if (mask_size > 1) {
1755                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
1756             } else {
1757                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
1758             }
1759         } else {
1760             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
1761         }
1762     }
1763 }
1764
1765 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
1766  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1767  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1768 void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
1769     glsl_src_param_t src0_param;
1770     char dst_mask[6];
1771     glsl_sample_function_t sample_function;
1772     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1773     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1774     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1775
1776     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1777
1778     shader_glsl_append_dst(arg->buffer, arg);
1779     shader_glsl_get_write_mask(arg->dst, dst_mask);
1780
1781     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
1782      * scalar, and projected sampling would require 4
1783      */
1784     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1785
1786     switch(count_bits(sample_function.coord_mask)) {
1787         case 1:
1788             shader_addline(arg->buffer, "%s(Psampler%u, dot(gl_TexCoord[%u].xyz, %s))%s);\n",
1789                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
1790             break;
1791
1792         case 2:
1793             shader_addline(arg->buffer, "%s(Psampler%u, vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0))%s);\n",
1794                           sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
1795             break;
1796
1797         case 3:
1798             shader_addline(arg->buffer, "%s(Psampler%u, vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0))%s);\n",
1799                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
1800             break;
1801         default:
1802             FIXME("Unexpected mask bitcount %d\n", count_bits(sample_function.coord_mask));
1803     }
1804 }
1805
1806 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
1807  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1808 void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
1809     glsl_src_param_t src0_param;
1810     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1811     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1812     DWORD dst_mask;
1813     size_t mask_size;
1814
1815     dst_mask = shader_glsl_append_dst(arg->buffer, arg);
1816     mask_size = shader_glsl_get_write_mask_size(dst_mask);
1817     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1818
1819     if (mask_size > 1) {
1820         shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
1821     } else {
1822         shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
1823     }
1824 }
1825
1826 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
1827  * Calculate the depth as dst.x / dst.y   */
1828 void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
1829     glsl_dst_param_t dst_param;
1830
1831     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1832
1833     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
1834      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
1835      * this doesn't always work, so clamp the results manually. Wether or not the x value is clamped at 1
1836      * too is irrelevant, since if x = 0, any y value < 1.0(and > 1.0 is not allowed) results in a result
1837      * >= 1.0 or < 0.0
1838      */
1839     shader_addline(arg->buffer, "gl_FragDepth = (%s.y == 0.0) ? 1.0 : clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name, dst_param.reg_name);
1840 }
1841
1842 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
1843  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1844  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1845  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1846  */
1847 void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
1848     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1849     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1850     glsl_src_param_t src0_param;
1851
1852     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1853
1854     shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
1855     shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
1856 }
1857
1858 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
1859  * Calculate the 1st of a 2-row matrix multiplication. */
1860 void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
1861     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1862     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1863     SHADER_BUFFER* buffer = arg->buffer;
1864     glsl_src_param_t src0_param;
1865
1866     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1867     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1868 }
1869
1870 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
1871  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
1872 void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {
1873
1874     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1875     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1876     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1877     SHADER_BUFFER* buffer = arg->buffer;
1878     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1879     glsl_src_param_t src0_param;
1880
1881     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1882     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
1883     current_state->texcoord_w[current_state->current_row++] = reg;
1884 }
1885
1886 void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1887     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1888     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1889     SHADER_BUFFER* buffer = arg->buffer;
1890     glsl_src_param_t src0_param;
1891     char dst_mask[6];
1892
1893     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1894     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1895
1896     shader_glsl_append_dst(buffer, arg);
1897     shader_glsl_get_write_mask(arg->dst, dst_mask);
1898
1899     /* Sample the texture using the calculated coordinates */
1900     shader_addline(buffer, "texture2D(Psampler%u, tmp0.xy)%s);\n", reg, dst_mask);
1901 }
1902
1903 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
1904  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
1905 void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1906     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1907     glsl_src_param_t src0_param;
1908     char dst_mask[6];
1909     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1910     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1911     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1912     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1913     glsl_sample_function_t sample_function;
1914
1915     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1916     shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1917
1918     shader_glsl_append_dst(arg->buffer, arg);
1919     shader_glsl_get_write_mask(arg->dst, dst_mask);
1920     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1921
1922     /* Sample the texture using the calculated coordinates */
1923     shader_addline(arg->buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
1924
1925     current_state->current_row = 0;
1926 }
1927
1928 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
1929  * Perform the 3rd row of a 3x3 matrix multiply */
1930 void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
1931     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1932     glsl_src_param_t src0_param;
1933     char dst_mask[6];
1934     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1935     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1936     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1937
1938     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1939
1940     shader_glsl_append_dst(arg->buffer, arg);
1941     shader_glsl_get_write_mask(arg->dst, dst_mask);
1942     shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
1943
1944     current_state->current_row = 0;
1945 }
1946
1947 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
1948  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1949 void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {
1950
1951     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1952     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1953     glsl_src_param_t src0_param;
1954     glsl_src_param_t src1_param;
1955     char dst_mask[6];
1956     SHADER_BUFFER* buffer = arg->buffer;
1957     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1958     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1959     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1960     glsl_sample_function_t sample_function;
1961
1962     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1963     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1964
1965     /* Perform the last matrix multiply operation */
1966     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1967     /* Reflection calculation */
1968     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
1969
1970     shader_glsl_append_dst(buffer, arg);
1971     shader_glsl_get_write_mask(arg->dst, dst_mask);
1972     shader_glsl_get_sample_function(stype, FALSE, &sample_function);
1973
1974     /* Sample the texture */
1975     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
1976
1977     current_state->current_row = 0;
1978 }
1979
1980 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
1981  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1982 void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
1983
1984     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1985     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1986     SHADER_BUFFER* buffer = arg->buffer;
1987     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1988     glsl_src_param_t src0_param;
1989     char dst_mask[6];
1990     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1991     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1992     glsl_sample_function_t sample_function;
1993
1994     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1995
1996     /* Perform the last matrix multiply operation */
1997     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
1998
1999     /* Construct the eye-ray vector from w coordinates */
2000     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2001             current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2002     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2003
2004     shader_glsl_append_dst(buffer, arg);
2005     shader_glsl_get_write_mask(arg->dst, dst_mask);
2006     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2007
2008     /* Sample the texture using the calculated coordinates */
2009     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2010
2011     current_state->current_row = 0;
2012 }
2013
2014 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2015  * Apply a fake bump map transform.
2016  * texbem is pshader <= 1.3 only, this saves a few version checks
2017  */
2018 void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
2019     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2020     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2021     char dst_swizzle[6];
2022     glsl_sample_function_t sample_function;
2023     glsl_src_param_t coord_param;
2024     DWORD sampler_type;
2025     DWORD sampler_idx;
2026     DWORD mask;
2027     DWORD flags;
2028     char coord_mask[6];
2029
2030     sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2031     flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2032
2033     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2034     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2035     mask = sample_function.coord_mask;
2036
2037     shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2038
2039     shader_glsl_get_write_mask(mask, coord_mask);
2040
2041     /* with projective textures, texbem only divides the static texture coord, not the displacement,
2042          * so we can't let the GL handle this.
2043          */
2044     if (flags & WINED3DTTFF_PROJECTED) {
2045         DWORD div_mask=0;
2046         char coord_div_mask[3];
2047         switch (flags & ~WINED3DTTFF_PROJECTED) {
2048             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2049             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2050             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2051             case WINED3DTTFF_COUNT4:
2052             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2053         }
2054         shader_glsl_get_write_mask(div_mask, coord_div_mask);
2055         shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2056     }
2057
2058     shader_glsl_append_dst(arg->buffer, arg);
2059     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2060     if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
2061         glsl_src_param_t luminance_param;
2062         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2063         shader_addline(arg->buffer, "(%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )*(%s * luminancescale + luminanceoffset))%s);\n",
2064                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask,
2065                        luminance_param.param_str, dst_swizzle);
2066     } else {
2067         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )%s);\n",
2068                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask, dst_swizzle);
2069     }
2070 }
2071
2072 void pshader_glsl_bem(SHADER_OPCODE_ARG* arg) {
2073     glsl_src_param_t src0_param, src1_param;
2074
2075     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
2076     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);
2077
2078     shader_glsl_append_dst(arg->buffer, arg);
2079     shader_addline(arg->buffer, "%s + bumpenvmat * %s);\n",
2080                    src0_param.param_str, src1_param.param_str);
2081 }
2082
2083 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2084  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2085 void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
2086     glsl_src_param_t src0_param;
2087     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2088     char dst_mask[6];
2089
2090     shader_glsl_append_dst(arg->buffer, arg);
2091     shader_glsl_get_write_mask(arg->dst, dst_mask);
2092     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2093
2094     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.wx)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2095 }
2096
2097 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2098  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2099 void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
2100     glsl_src_param_t src0_param;
2101     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2102     char dst_mask[6];
2103
2104     shader_glsl_append_dst(arg->buffer, arg);
2105     shader_glsl_get_write_mask(arg->dst, dst_mask);
2106     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2107
2108     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.yz)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2109 }
2110
2111 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2112  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2113 void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
2114     glsl_src_param_t src0_param;
2115     char dst_mask[6];
2116     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2117     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2118     glsl_sample_function_t sample_function;
2119
2120     shader_glsl_append_dst(arg->buffer, arg);
2121     shader_glsl_get_write_mask(arg->dst, dst_mask);
2122     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2123     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2124
2125     shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n", sample_function.name, sampler_idx, src0_param.param_str, dst_mask);
2126 }
2127
2128 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2129  * If any of the first 3 components are < 0, discard this pixel */
2130 void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
2131     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2132     DWORD hex_version = This->baseShader.hex_version;
2133     glsl_dst_param_t dst_param;
2134
2135     /* The argument is a destination parameter, and no writemasks are allowed */
2136     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2137     if((hex_version >= WINED3DPS_VERSION(2,0))) {
2138         /* 2.0 shaders compare all 4 components in texkill */
2139         shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2140     } else {
2141         /* 1.X shaders only compare the first 3 components, propably due to the nature of the texkill
2142          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2143          * 4 components are defined, only the first 3 are used
2144          */
2145         shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2146     }
2147 }
2148
2149 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2150  * dst = dot2(src0, src1) + src2 */
2151 void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
2152     glsl_src_param_t src0_param;
2153     glsl_src_param_t src1_param;
2154     glsl_src_param_t src2_param;
2155     DWORD write_mask;
2156     size_t mask_size;
2157
2158     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2159     mask_size = shader_glsl_get_write_mask_size(write_mask);
2160
2161     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2162     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2163     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2164
2165     shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2166 }
2167
2168 void pshader_glsl_input_pack(
2169    SHADER_BUFFER* buffer,
2170    semantic* semantics_in) {
2171
2172    unsigned int i;
2173
2174    for (i = 0; i < MAX_REG_INPUT; i++) {
2175
2176        DWORD usage_token = semantics_in[i].usage;
2177        DWORD register_token = semantics_in[i].reg;
2178        DWORD usage, usage_idx;
2179        char reg_mask[6];
2180
2181        /* Uninitialized */
2182        if (!usage_token) continue;
2183        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2184        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2185        shader_glsl_get_write_mask(register_token, reg_mask);
2186
2187        switch(usage) {
2188
2189            case WINED3DDECLUSAGE_COLOR:
2190                if (usage_idx == 0)
2191                    shader_addline(buffer, "IN%u%s = vec4(gl_Color)%s;\n",
2192                        i, reg_mask, reg_mask);
2193                else if (usage_idx == 1)
2194                    shader_addline(buffer, "IN%u%s = vec4(gl_SecondaryColor)%s;\n",
2195                        i, reg_mask, reg_mask);
2196                else
2197                    shader_addline(buffer, "IN%u%s = vec4(unsupported_color_input)%s;\n",
2198                        i, reg_mask, reg_mask);
2199                break;
2200
2201            case WINED3DDECLUSAGE_TEXCOORD:
2202                shader_addline(buffer, "IN%u%s = vec4(gl_TexCoord[%u])%s;\n",
2203                    i, reg_mask, usage_idx, reg_mask );
2204                break;
2205
2206            case WINED3DDECLUSAGE_FOG:
2207                shader_addline(buffer, "IN%u%s = vec4(gl_FogFragCoord)%s;\n",
2208                    i, reg_mask, reg_mask);
2209                break;
2210
2211            default:
2212                shader_addline(buffer, "IN%u%s = vec4(unsupported_input)%s;\n",
2213                    i, reg_mask, reg_mask);
2214         }
2215     }
2216 }
2217
2218 /*********************************************
2219  * Vertex Shader Specific Code begins here
2220  ********************************************/
2221
2222 void vshader_glsl_output_unpack(
2223    SHADER_BUFFER* buffer,
2224    semantic* semantics_out) {
2225
2226    unsigned int i;
2227
2228    for (i = 0; i < MAX_REG_OUTPUT; i++) {
2229
2230        DWORD usage_token = semantics_out[i].usage;
2231        DWORD register_token = semantics_out[i].reg;
2232        DWORD usage, usage_idx;
2233        char reg_mask[6];
2234
2235        /* Uninitialized */
2236        if (!usage_token) continue;
2237
2238        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2239        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2240        shader_glsl_get_write_mask(register_token, reg_mask);
2241
2242        switch(usage) {
2243
2244            case WINED3DDECLUSAGE_COLOR:
2245                if (usage_idx == 0)
2246                    shader_addline(buffer, "gl_FrontColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2247                else if (usage_idx == 1)
2248                    shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2249                else
2250                    shader_addline(buffer, "unsupported_color_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2251                break;
2252
2253            case WINED3DDECLUSAGE_POSITION:
2254                shader_addline(buffer, "gl_Position%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2255                break;
2256
2257            case WINED3DDECLUSAGE_TEXCOORD:
2258                shader_addline(buffer, "gl_TexCoord[%u]%s = OUT%u%s;\n",
2259                    usage_idx, reg_mask, i, reg_mask);
2260                break;
2261
2262            case WINED3DDECLUSAGE_PSIZE:
2263                shader_addline(buffer, "gl_PointSize = OUT%u.x;\n", i);
2264                break;
2265
2266            case WINED3DDECLUSAGE_FOG:
2267                shader_addline(buffer, "gl_FogFragCoord = OUT%u%s;\n", i, reg_mask);
2268                break;
2269
2270            default:
2271                shader_addline(buffer, "unsupported_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2272        }
2273     }
2274 }
2275
2276 static void add_glsl_program_entry(IWineD3DDeviceImpl *device, struct glsl_shader_prog_link *entry) {
2277     glsl_program_key_t *key;
2278
2279     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2280     key->vshader = entry->vshader;
2281     key->pshader = entry->pshader;
2282
2283     hash_table_put(device->glsl_program_lookup, key, entry);
2284 }
2285
2286 static struct glsl_shader_prog_link *get_glsl_program_entry(IWineD3DDeviceImpl *device,
2287         GLhandleARB vshader, GLhandleARB pshader) {
2288     glsl_program_key_t key;
2289
2290     key.vshader = vshader;
2291     key.pshader = pshader;
2292
2293     return (struct glsl_shader_prog_link *)hash_table_get(device->glsl_program_lookup, &key);
2294 }
2295
2296 void delete_glsl_program_entry(IWineD3DDevice *iface, struct glsl_shader_prog_link *entry) {
2297     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2298     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2299     glsl_program_key_t *key;
2300
2301     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2302     key->vshader = entry->vshader;
2303     key->pshader = entry->pshader;
2304     hash_table_remove(This->glsl_program_lookup, key);
2305
2306     GL_EXTCALL(glDeleteObjectARB(entry->programId));
2307     if (entry->vshader) list_remove(&entry->vshader_entry);
2308     if (entry->pshader) list_remove(&entry->pshader_entry);
2309     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
2310     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
2311     HeapFree(GetProcessHeap(), 0, entry);
2312 }
2313
2314 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
2315  * It sets the programId on the current StateBlock (because it should be called
2316  * inside of the DrawPrimitive() part of the render loop).
2317  *
2318  * If a program for the given combination does not exist, create one, and store
2319  * the program in the hash table.  If it creates a program, it will link the
2320  * given objects, too.
2321  */
2322 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
2323     IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
2324     WineD3D_GL_Info *gl_info               = &This->adapter->gl_info;
2325     IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
2326     IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
2327     struct glsl_shader_prog_link *entry    = NULL;
2328     GLhandleARB programId                  = 0;
2329     int i;
2330     char glsl_name[8];
2331
2332     GLhandleARB vshader_id = use_vs ? ((IWineD3DBaseShaderImpl*)vshader)->baseShader.prgId : 0;
2333     GLhandleARB pshader_id = use_ps ? ((IWineD3DBaseShaderImpl*)pshader)->baseShader.prgId : 0;
2334     entry = get_glsl_program_entry(This, vshader_id, pshader_id);
2335     if (entry) {
2336         This->stateBlock->glsl_program = entry;
2337         return;
2338     }
2339
2340     /* If we get to this point, then no matching program exists, so we create one */
2341     programId = GL_EXTCALL(glCreateProgramObjectARB());
2342     TRACE("Created new GLSL shader program %u\n", programId);
2343
2344     /* Create the entry */
2345     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
2346     entry->programId = programId;
2347     entry->vshader = vshader_id;
2348     entry->pshader = pshader_id;
2349     /* Add the hash table entry */
2350     add_glsl_program_entry(This, entry);
2351
2352     /* Set the current program */
2353     This->stateBlock->glsl_program = entry;
2354
2355     /* Attach GLSL vshader */
2356     if (vshader_id) {
2357         int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
2358         char tmp_name[10];
2359
2360         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
2361         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
2362         checkGLcall("glAttachObjectARB");
2363
2364         /* Bind vertex attributes to a corresponding index number to match
2365          * the same index numbers as ARB_vertex_programs (makes loading
2366          * vertex attributes simpler).  With this method, we can use the
2367          * exact same code to load the attributes later for both ARB and
2368          * GLSL shaders.
2369          *
2370          * We have to do this here because we need to know the Program ID
2371          * in order to make the bindings work, and it has to be done prior
2372          * to linking the GLSL program. */
2373         for (i = 0; i < max_attribs; ++i) {
2374              snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
2375              GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
2376         }
2377         checkGLcall("glBindAttribLocationARB");
2378
2379         list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
2380     }
2381
2382     /* Attach GLSL pshader */
2383     if (pshader_id) {
2384         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
2385         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
2386         checkGLcall("glAttachObjectARB");
2387
2388         list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
2389     }
2390
2391     /* Link the program */
2392     TRACE("Linking GLSL shader program %u\n", programId);
2393     GL_EXTCALL(glLinkProgramARB(programId));
2394     print_glsl_info_log(&GLINFO_LOCATION, programId);
2395
2396     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
2397     for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
2398         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
2399         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
2400     }
2401     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
2402     for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
2403         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
2404         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
2405     }
2406 }
2407
2408 static GLhandleARB create_glsl_blt_shader(WineD3D_GL_Info *gl_info) {
2409     GLhandleARB program_id;
2410     GLhandleARB vshader_id, pshader_id;
2411     const char *blt_vshader[] = {
2412         "void main(void)\n"
2413         "{\n"
2414         "    gl_Position = gl_Vertex;\n"
2415         "    gl_FrontColor = vec4(1.0);\n"
2416         "    gl_TexCoord[0].x = (gl_Vertex.x * 0.5) + 0.5;\n"
2417         "    gl_TexCoord[0].y = (-gl_Vertex.y * 0.5) + 0.5;\n"
2418         "}\n"
2419     };
2420
2421     const char *blt_pshader[] = {
2422         "uniform sampler2D sampler;\n"
2423         "void main(void)\n"
2424         "{\n"
2425         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
2426         "}\n"
2427     };
2428
2429     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
2430     GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
2431     GL_EXTCALL(glCompileShaderARB(vshader_id));
2432
2433     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
2434     GL_EXTCALL(glShaderSourceARB(pshader_id, 1, blt_pshader, NULL));
2435     GL_EXTCALL(glCompileShaderARB(pshader_id));
2436
2437     program_id = GL_EXTCALL(glCreateProgramObjectARB());
2438     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
2439     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
2440     GL_EXTCALL(glLinkProgramARB(program_id));
2441
2442     print_glsl_info_log(&GLINFO_LOCATION, program_id);
2443
2444     return program_id;
2445 }
2446
2447 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
2448     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2449     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2450     GLhandleARB program_id = 0;
2451
2452     if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
2453     else This->stateBlock->glsl_program = NULL;
2454
2455     program_id = This->stateBlock->glsl_program ? This->stateBlock->glsl_program->programId : 0;
2456     if (program_id) TRACE("Using GLSL program %u\n", program_id);
2457     GL_EXTCALL(glUseProgramObjectARB(program_id));
2458     checkGLcall("glUseProgramObjectARB");
2459 }
2460
2461 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface) {
2462     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2463     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2464     static GLhandleARB program_id = 0;
2465     static GLhandleARB loc = -1;
2466
2467     if (!program_id) {
2468         program_id = create_glsl_blt_shader(gl_info);
2469         loc = GL_EXTCALL(glGetUniformLocationARB(program_id, "sampler"));
2470     }
2471
2472     GL_EXTCALL(glUseProgramObjectARB(program_id));
2473     GL_EXTCALL(glUniform1iARB(loc, 0));
2474 }
2475
2476 static void shader_glsl_cleanup(IWineD3DDevice *iface) {
2477     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2478     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2479     GL_EXTCALL(glUseProgramObjectARB(0));
2480 }
2481
2482 const shader_backend_t glsl_shader_backend = {
2483     &shader_glsl_select,
2484     &shader_glsl_select_depth_blt,
2485     &shader_glsl_load_constants,
2486     &shader_glsl_cleanup
2487 };