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