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