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