push 87b6981010d7405c33b14cddcceec21b47729eba
[wine/hacks.git] / dlls / wined3d / glsl_shader.c
blobca05ebf9388c88494f38c7caedfe36828bc59cd8
1 /*
2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
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.
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.
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
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.
32 #include "config.h"
33 #include <limits.h>
34 #include <stdio.h>
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
42 #define GLINFO_LOCATION (*gl_info)
44 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
45 #define WINED3D_GLSL_SAMPLE_RECT 0x2
46 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
49 typedef struct {
50 char reg_name[150];
51 char mask_str[6];
52 } glsl_dst_param_t;
54 typedef struct {
55 char reg_name[150];
56 char param_str[200];
57 } glsl_src_param_t;
59 typedef struct {
60 const char *name;
61 DWORD coord_mask;
62 } glsl_sample_function_t;
64 enum heap_node_op
66 HEAP_NODE_TRAVERSE_LEFT,
67 HEAP_NODE_TRAVERSE_RIGHT,
68 HEAP_NODE_POP,
71 struct constant_entry
73 unsigned int idx;
74 unsigned int version;
77 struct constant_heap
79 struct constant_entry *entries;
80 unsigned int *positions;
81 unsigned int size;
84 /* GLSL shader private data */
85 struct shader_glsl_priv {
86 struct wined3d_shader_buffer shader_buffer;
87 struct wine_rb_tree program_lookup;
88 struct glsl_shader_prog_link *glsl_program;
89 struct constant_heap vconst_heap;
90 struct constant_heap pconst_heap;
91 unsigned char *stack;
92 GLhandleARB depth_blt_program[tex_type_count];
93 UINT next_constant_version;
96 /* Struct to maintain data about a linked GLSL program */
97 struct glsl_shader_prog_link {
98 struct wine_rb_entry program_lookup_entry;
99 struct list vshader_entry;
100 struct list pshader_entry;
101 GLhandleARB programId;
102 GLint *vuniformF_locations;
103 GLint *puniformF_locations;
104 GLint vuniformI_locations[MAX_CONST_I];
105 GLint puniformI_locations[MAX_CONST_I];
106 GLint posFixup_location;
107 GLint np2Fixup_location;
108 GLint bumpenvmat_location[MAX_TEXTURES];
109 GLint luminancescale_location[MAX_TEXTURES];
110 GLint luminanceoffset_location[MAX_TEXTURES];
111 GLint ycorrection_location;
112 GLenum vertex_color_clamp;
113 IWineD3DVertexShader *vshader;
114 IWineD3DPixelShader *pshader;
115 struct vs_compile_args vs_args;
116 struct ps_compile_args ps_args;
117 UINT constant_version;
118 const struct ps_np2fixup_info *np2Fixup_info;
121 typedef struct {
122 IWineD3DVertexShader *vshader;
123 IWineD3DPixelShader *pshader;
124 struct ps_compile_args ps_args;
125 struct vs_compile_args vs_args;
126 } glsl_program_key_t;
128 struct shader_glsl_ctx_priv {
129 const struct vs_compile_args *cur_vs_args;
130 const struct ps_compile_args *cur_ps_args;
131 struct ps_np2fixup_info *cur_np2fixup_info;
134 struct glsl_ps_compiled_shader
136 struct ps_compile_args args;
137 struct ps_np2fixup_info np2fixup;
138 GLhandleARB prgId;
141 struct glsl_pshader_private
143 struct glsl_ps_compiled_shader *gl_shaders;
144 UINT num_gl_shaders, shader_array_size;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
150 GLhandleARB prgId;
153 struct glsl_vshader_private
155 struct glsl_vs_compiled_shader *gl_shaders;
156 UINT num_gl_shaders, shader_array_size;
159 static const char *debug_gl_shader_type(GLenum type)
161 switch (type)
163 #define WINED3D_TO_STR(u) case u: return #u
164 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
165 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
166 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
167 #undef WINED3D_TO_STR
168 default:
169 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
173 /* Extract a line from the info log.
174 * Note that this modifies the source string. */
175 static char *get_info_log_line(char **ptr)
177 char *p, *q;
179 p = *ptr;
180 if (!(q = strstr(p, "\n")))
182 if (!*p) return NULL;
183 *ptr += strlen(p);
184 return p;
186 *q = '\0';
187 *ptr = q + 1;
189 return p;
192 /** Prints the GLSL info log which will contain error messages if they exist */
193 /* GL locking is done by the caller */
194 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
196 int infologLength = 0;
197 char *infoLog;
198 unsigned int i;
199 BOOL is_spam;
201 static const char * const spam[] =
203 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
204 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
205 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
206 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
207 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
208 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
209 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
210 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
211 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
214 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
216 GL_EXTCALL(glGetObjectParameterivARB(obj,
217 GL_OBJECT_INFO_LOG_LENGTH_ARB,
218 &infologLength));
220 /* A size of 1 is just a null-terminated string, so the log should be bigger than
221 * that if there are errors. */
222 if (infologLength > 1)
224 char *ptr, *line;
226 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
227 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
229 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
230 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
231 is_spam = FALSE;
233 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
234 if(strcmp(infoLog, spam[i]) == 0) {
235 is_spam = TRUE;
236 break;
240 ptr = infoLog;
241 if (is_spam)
243 TRACE("Spam received from GLSL shader #%u:\n", obj);
244 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
246 else
248 FIXME("Error received from GLSL shader #%u:\n", obj);
249 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
251 HeapFree(GetProcessHeap(), 0, infoLog);
255 /* GL locking is done by the caller. */
256 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
258 GLint i, object_count, source_size;
259 GLhandleARB *objects;
260 char *source = NULL;
262 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
263 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
264 if (!objects)
266 ERR("Failed to allocate object array memory.\n");
267 return;
270 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
271 for (i = 0; i < object_count; ++i)
273 char *ptr, *line;
274 GLint tmp;
276 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
278 if (!source || source_size < tmp)
280 HeapFree(GetProcessHeap(), 0, source);
282 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
283 if (!source)
285 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
286 HeapFree(GetProcessHeap(), 0, objects);
287 return;
289 source_size = tmp;
292 FIXME("Object %u:\n", objects[i]);
293 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
294 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
295 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
296 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
297 FIXME("\n");
299 ptr = source;
300 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
301 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
302 FIXME("\n");
305 HeapFree(GetProcessHeap(), 0, source);
306 HeapFree(GetProcessHeap(), 0, objects);
309 /* GL locking is done by the caller. */
310 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
312 GLint tmp;
314 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
316 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
317 if (tmp == GL_PROGRAM_OBJECT_ARB)
319 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
320 if (!tmp)
322 FIXME("Program %u link status invalid.\n", program);
323 shader_glsl_dump_program_source(gl_info, program);
327 print_glsl_info_log(gl_info, program);
331 * Loads (pixel shader) samplers
333 /* GL locking is done by the caller */
334 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
335 DWORD *tex_unit_map, GLhandleARB programId)
337 GLint name_loc;
338 int i;
339 char sampler_name[20];
341 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
342 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
343 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
344 if (name_loc != -1) {
345 DWORD mapped_unit = tex_unit_map[i];
346 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
348 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
349 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
350 checkGLcall("glUniform1iARB");
351 } else {
352 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
358 /* GL locking is done by the caller */
359 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
360 DWORD *tex_unit_map, GLhandleARB programId)
362 GLint name_loc;
363 char sampler_name[20];
364 int i;
366 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
367 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
368 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
369 if (name_loc != -1) {
370 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
371 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
373 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
374 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
375 checkGLcall("glUniform1iARB");
376 } else {
377 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
383 /* GL locking is done by the caller */
384 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
385 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
387 int stack_idx = 0;
388 unsigned int heap_idx = 1;
389 unsigned int idx;
391 if (heap->entries[heap_idx].version <= version) return;
393 idx = heap->entries[heap_idx].idx;
394 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
395 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
397 while (stack_idx >= 0)
399 /* Note that we fall through to the next case statement. */
400 switch(stack[stack_idx])
402 case HEAP_NODE_TRAVERSE_LEFT:
404 unsigned int left_idx = heap_idx << 1;
405 if (left_idx < heap->size && heap->entries[left_idx].version > version)
407 heap_idx = left_idx;
408 idx = heap->entries[heap_idx].idx;
409 if (constant_locations[idx] != -1)
410 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
412 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
413 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
414 break;
418 case HEAP_NODE_TRAVERSE_RIGHT:
420 unsigned int right_idx = (heap_idx << 1) + 1;
421 if (right_idx < heap->size && heap->entries[right_idx].version > version)
423 heap_idx = right_idx;
424 idx = heap->entries[heap_idx].idx;
425 if (constant_locations[idx] != -1)
426 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
428 stack[stack_idx++] = HEAP_NODE_POP;
429 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
430 break;
434 case HEAP_NODE_POP:
436 heap_idx >>= 1;
437 --stack_idx;
438 break;
442 checkGLcall("walk_constant_heap()");
445 /* GL locking is done by the caller */
446 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
448 GLfloat clamped_constant[4];
450 if (location == -1) return;
452 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
453 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
454 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
455 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
457 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
460 /* GL locking is done by the caller */
461 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
462 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
464 int stack_idx = 0;
465 unsigned int heap_idx = 1;
466 unsigned int idx;
468 if (heap->entries[heap_idx].version <= version) return;
470 idx = heap->entries[heap_idx].idx;
471 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
472 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
474 while (stack_idx >= 0)
476 /* Note that we fall through to the next case statement. */
477 switch(stack[stack_idx])
479 case HEAP_NODE_TRAVERSE_LEFT:
481 unsigned int left_idx = heap_idx << 1;
482 if (left_idx < heap->size && heap->entries[left_idx].version > version)
484 heap_idx = left_idx;
485 idx = heap->entries[heap_idx].idx;
486 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
488 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
489 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
490 break;
494 case HEAP_NODE_TRAVERSE_RIGHT:
496 unsigned int right_idx = (heap_idx << 1) + 1;
497 if (right_idx < heap->size && heap->entries[right_idx].version > version)
499 heap_idx = right_idx;
500 idx = heap->entries[heap_idx].idx;
501 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
503 stack[stack_idx++] = HEAP_NODE_POP;
504 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
505 break;
509 case HEAP_NODE_POP:
511 heap_idx >>= 1;
512 --stack_idx;
513 break;
517 checkGLcall("walk_constant_heap_clamped()");
520 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
521 /* GL locking is done by the caller */
522 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
523 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
524 unsigned char *stack, UINT version)
526 const local_constant *lconst;
528 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
529 if (This->baseShader.reg_maps.shader_version.major == 1
530 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
531 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
532 else
533 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
535 if (!This->baseShader.load_local_constsF)
537 TRACE("No need to load local float constants for this shader\n");
538 return;
541 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
542 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
544 GLint location = constant_locations[lconst->idx];
545 /* We found this uniform name in the program - go ahead and send the data */
546 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
548 checkGLcall("glUniform4fvARB()");
551 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
552 /* GL locking is done by the caller */
553 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
554 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
556 unsigned int i;
557 struct list* ptr;
559 for (i = 0; constants_set; constants_set >>= 1, ++i)
561 if (!(constants_set & 1)) continue;
563 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
564 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
566 /* We found this uniform name in the program - go ahead and send the data */
567 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
568 checkGLcall("glUniform4ivARB");
571 /* Load immediate constants */
572 ptr = list_head(&This->baseShader.constantsI);
573 while (ptr) {
574 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
575 unsigned int idx = lconst->idx;
576 const GLint *values = (const GLint *)lconst->value;
578 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
579 values[0], values[1], values[2], values[3]);
581 /* We found this uniform name in the program - go ahead and send the data */
582 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
583 checkGLcall("glUniform4ivARB");
584 ptr = list_next(&This->baseShader.constantsI, ptr);
588 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
589 /* GL locking is done by the caller */
590 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
591 GLhandleARB programId, const BOOL *constants, WORD constants_set)
593 GLint tmp_loc;
594 unsigned int i;
595 char tmp_name[8];
596 const char *prefix;
597 struct list* ptr;
599 switch (This->baseShader.reg_maps.shader_version.type)
601 case WINED3D_SHADER_TYPE_VERTEX:
602 prefix = "VB";
603 break;
605 case WINED3D_SHADER_TYPE_GEOMETRY:
606 prefix = "GB";
607 break;
609 case WINED3D_SHADER_TYPE_PIXEL:
610 prefix = "PB";
611 break;
613 default:
614 FIXME("Unknown shader type %#x.\n",
615 This->baseShader.reg_maps.shader_version.type);
616 prefix = "UB";
617 break;
620 /* TODO: Benchmark and see if it would be beneficial to store the
621 * locations of the constants to avoid looking up each time */
622 for (i = 0; constants_set; constants_set >>= 1, ++i)
624 if (!(constants_set & 1)) continue;
626 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
628 /* TODO: Benchmark and see if it would be beneficial to store the
629 * locations of the constants to avoid looking up each time */
630 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
631 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
632 if (tmp_loc != -1)
634 /* We found this uniform name in the program - go ahead and send the data */
635 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
636 checkGLcall("glUniform1ivARB");
640 /* Load immediate constants */
641 ptr = list_head(&This->baseShader.constantsB);
642 while (ptr) {
643 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
644 unsigned int idx = lconst->idx;
645 const GLint *values = (const GLint *)lconst->value;
647 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
649 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
650 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
651 if (tmp_loc != -1) {
652 /* We found this uniform name in the program - go ahead and send the data */
653 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
654 checkGLcall("glUniform1ivARB");
656 ptr = list_next(&This->baseShader.constantsB, ptr);
660 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
662 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
666 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
668 /* GL locking is done by the caller (state handler) */
669 static void shader_glsl_load_np2fixup_constants(
670 IWineD3DDevice* device,
671 char usePixelShader,
672 char useVertexShader) {
674 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
675 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
677 if (!prog) {
678 /* No GLSL program set - nothing to do. */
679 return;
682 if (!usePixelShader) {
683 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
684 return;
687 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
688 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
689 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
690 UINT i;
691 UINT fixup = prog->ps_args.np2_fixup;
692 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
694 for (i = 0; fixup; fixup >>= 1, ++i) {
695 const unsigned char idx = prog->np2Fixup_info->idx[i];
696 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
697 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
699 if (!tex) {
700 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
701 continue;
704 if (idx % 2) {
705 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
706 } else {
707 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
711 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
716 * Loads the app-supplied constants into the currently set GLSL program.
718 /* GL locking is done by the caller (state handler) */
719 static void shader_glsl_load_constants(const struct wined3d_context *context,
720 char usePixelShader, char useVertexShader)
722 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
723 const struct wined3d_gl_info *gl_info = context->gl_info;
724 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
725 struct shader_glsl_priv *priv = device->shader_priv;
727 GLhandleARB programId;
728 struct glsl_shader_prog_link *prog = priv->glsl_program;
729 UINT constant_version;
730 int i;
732 if (!prog) {
733 /* No GLSL program set - nothing to do. */
734 return;
736 programId = prog->programId;
737 constant_version = prog->constant_version;
739 if (useVertexShader) {
740 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
742 /* Load DirectX 9 float constants/uniforms for vertex shader */
743 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
744 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
746 /* Load DirectX 9 integer constants/uniforms for vertex shader */
747 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
748 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
750 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
751 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
752 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
754 /* Upload the position fixup params */
755 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
756 checkGLcall("glUniform4fvARB");
759 if (usePixelShader) {
761 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
763 /* Load DirectX 9 float constants/uniforms for pixel shader */
764 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
765 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
767 /* Load DirectX 9 integer constants/uniforms for pixel shader */
768 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
769 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
771 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
772 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
773 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
775 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
776 * It can't be 0 for a valid texbem instruction.
778 for(i = 0; i < MAX_TEXTURES; i++) {
779 const float *data;
781 if(prog->bumpenvmat_location[i] == -1) continue;
783 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
784 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
785 checkGLcall("glUniformMatrix2fvARB");
787 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
788 * is set too, so we can check that in the needsbumpmat check
790 if(prog->luminancescale_location[i] != -1) {
791 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
792 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
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");
801 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
802 float correction_params[4];
804 if (context->render_offscreen)
806 correction_params[0] = 0.0f;
807 correction_params[1] = 1.0f;
808 } else {
809 /* position is window relative, not viewport relative */
810 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
811 correction_params[1] = -1.0f;
813 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
817 if (priv->next_constant_version == UINT_MAX)
819 TRACE("Max constant version reached, resetting to 0.\n");
820 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
821 priv->next_constant_version = 1;
823 else
825 prog->constant_version = priv->next_constant_version++;
829 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
830 unsigned int heap_idx, DWORD new_version)
832 struct constant_entry *entries = heap->entries;
833 unsigned int *positions = heap->positions;
834 unsigned int parent_idx;
836 while (heap_idx > 1)
838 parent_idx = heap_idx >> 1;
840 if (new_version <= entries[parent_idx].version) break;
842 entries[heap_idx] = entries[parent_idx];
843 positions[entries[parent_idx].idx] = heap_idx;
844 heap_idx = parent_idx;
847 entries[heap_idx].version = new_version;
848 entries[heap_idx].idx = idx;
849 positions[idx] = heap_idx;
852 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
854 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
855 struct shader_glsl_priv *priv = This->shader_priv;
856 struct constant_heap *heap = &priv->vconst_heap;
857 UINT i;
859 for (i = start; i < count + start; ++i)
861 if (!This->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);
868 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
870 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
871 struct shader_glsl_priv *priv = This->shader_priv;
872 struct constant_heap *heap = &priv->pconst_heap;
873 UINT i;
875 for (i = start; i < count + start; ++i)
877 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
878 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
879 else
880 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
884 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
886 unsigned int ret = gl_info->limits.glsl_varyings / 4;
887 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
888 if(shader_major > 3) return ret;
890 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
891 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
892 return ret;
895 /** Generate the variable & register declarations for the GLSL output target */
896 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
897 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
898 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
900 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
901 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
902 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
903 const struct wined3d_gl_info *gl_info = context->gl_info;
904 unsigned int i, extra_constants_needed = 0;
905 const local_constant *lconst;
906 DWORD map;
908 /* There are some minor differences between pixel and vertex shaders */
909 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
910 char prefix = pshader ? 'P' : 'V';
912 /* Prototype the subroutines */
913 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
915 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
918 /* Declare the constants (aka uniforms) */
919 if (This->baseShader.limits.constant_float > 0) {
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.
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.
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
934 if (pshader)
936 /* No indirect addressing here. */
937 max_constantsF = gl_info->limits.glsl_ps_float_constants;
939 else
941 if(This->baseShader.reg_maps.usesrelconstF) {
942 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
943 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
944 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
945 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
947 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
949 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
950 if(ctx_priv->cur_vs_args->clip_enabled)
952 max_constantsF -= gl_info->limits.clipplanes;
954 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
955 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
956 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
957 * for now take this into account when calculating the number of available constants
959 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
960 /* Set by driver quirks in directx.c */
961 max_constantsF -= gl_info->reserved_glsl_constants;
963 else
965 max_constantsF = gl_info->limits.glsl_vs_float_constants;
968 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
969 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
972 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
973 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
975 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
976 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
978 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
979 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
981 if(!pshader) {
982 shader_addline(buffer, "uniform vec4 posFixup;\n");
983 /* Predeclaration; This function is added at link time based on the pixel shader.
984 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
985 * that. We know the input to the reorder function at vertex shader compile time, so
986 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
987 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
988 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
989 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
990 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
991 * inout.
993 if (reg_maps->shader_version.major >= 3)
995 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
996 } else {
997 shader_addline(buffer, "void order_ps_input();\n");
999 } else {
1000 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1002 if (!(map & 1)) continue;
1004 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1006 if (reg_maps->luminanceparams & (1 << i))
1008 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1009 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1010 extra_constants_needed++;
1013 extra_constants_needed++;
1016 if (ps_args->srgb_correction)
1018 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1019 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1020 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1021 srgb_cmp);
1023 if (reg_maps->vpos || reg_maps->usesdsy)
1025 if (This->baseShader.limits.constant_float + extra_constants_needed
1026 + 1 < gl_info->limits.glsl_ps_float_constants)
1028 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1029 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1030 extra_constants_needed++;
1031 } else {
1032 /* This happens because we do not have proper tracking of the constant registers that are
1033 * actually used, only the max limit of the shader version
1035 FIXME("Cannot find a free uniform for vpos correction params\n");
1036 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1037 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
1038 context->render_offscreen ? 1.0f : -1.0f);
1040 shader_addline(buffer, "vec4 vpos;\n");
1044 /* Declare texture samplers */
1045 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1046 if (reg_maps->sampler_type[i])
1048 switch (reg_maps->sampler_type[i])
1050 case WINED3DSTT_1D:
1051 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1052 break;
1053 case WINED3DSTT_2D:
1054 if(device->stateBlock->textures[i] &&
1055 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
1056 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1057 } else {
1058 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1060 break;
1061 case WINED3DSTT_CUBE:
1062 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1063 break;
1064 case WINED3DSTT_VOLUME:
1065 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1066 break;
1067 default:
1068 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1069 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1070 break;
1075 /* Declare uniforms for NP2 texcoord fixup:
1076 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1077 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1078 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1079 if (pshader && ps_args->np2_fixup) {
1081 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1082 UINT cur = 0;
1084 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1085 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1086 * samplerNP2Fixup stores texture dimensions and is updated through
1087 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1089 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1090 if (reg_maps->sampler_type[i]) {
1091 if (!(ps_args->np2_fixup & (1 << i))) continue;
1093 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1094 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1095 continue;
1098 fixup->idx[i] = cur++;
1102 fixup->num_consts = (cur + 1) >> 1;
1103 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1106 /* Declare address variables */
1107 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1109 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1112 /* Declare texture coordinate temporaries and initialize them */
1113 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1115 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1118 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1119 * helper function shader that is linked in at link time
1121 if (pshader && reg_maps->shader_version.major >= 3)
1123 if (use_vs(device->stateBlock))
1125 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1126 } else {
1127 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1128 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1129 * pixel shader that reads the fixed function color into the packed input registers.
1131 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1135 /* Declare output register temporaries */
1136 if(This->baseShader.limits.packed_output) {
1137 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1140 /* Declare temporary variables */
1141 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1143 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1146 /* Declare attributes */
1147 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1149 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1151 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1155 /* Declare loop registers aLx */
1156 for (i = 0; i < reg_maps->loop_depth; i++) {
1157 shader_addline(buffer, "int aL%u;\n", i);
1158 shader_addline(buffer, "int tmpInt%u;\n", i);
1161 /* Temporary variables for matrix operations */
1162 shader_addline(buffer, "vec4 tmp0;\n");
1163 shader_addline(buffer, "vec4 tmp1;\n");
1165 /* Local constants use a different name so they can be loaded once at shader link time
1166 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1167 * float -> string conversion can cause precision loss.
1169 if(!This->baseShader.load_local_constsF) {
1170 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1171 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1175 shader_addline(buffer, "const float FLT_MAX = 1e38;\n");
1177 /* Start the main program */
1178 shader_addline(buffer, "void main() {\n");
1179 if(pshader && reg_maps->vpos) {
1180 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1181 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1182 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1183 * precision troubles when we just substract 0.5.
1185 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1187 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1189 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1190 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1191 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1192 * correctly on drivers that returns integer values.
1194 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1198 /*****************************************************************************
1199 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1201 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1202 ****************************************************************************/
1204 /* Prototypes */
1205 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1206 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1208 /** Used for opcode modifiers - They multiply the result by the specified amount */
1209 static const char * const shift_glsl_tab[] = {
1210 "", /* 0 (none) */
1211 "2.0 * ", /* 1 (x2) */
1212 "4.0 * ", /* 2 (x4) */
1213 "8.0 * ", /* 3 (x8) */
1214 "16.0 * ", /* 4 (x16) */
1215 "32.0 * ", /* 5 (x32) */
1216 "", /* 6 (x64) */
1217 "", /* 7 (x128) */
1218 "", /* 8 (d256) */
1219 "", /* 9 (d128) */
1220 "", /* 10 (d64) */
1221 "", /* 11 (d32) */
1222 "0.0625 * ", /* 12 (d16) */
1223 "0.125 * ", /* 13 (d8) */
1224 "0.25 * ", /* 14 (d4) */
1225 "0.5 * " /* 15 (d2) */
1228 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1229 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1231 out_str[0] = 0;
1233 switch (src_modifier)
1235 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1236 case WINED3DSPSM_DW:
1237 case WINED3DSPSM_NONE:
1238 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1239 break;
1240 case WINED3DSPSM_NEG:
1241 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1242 break;
1243 case WINED3DSPSM_NOT:
1244 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1245 break;
1246 case WINED3DSPSM_BIAS:
1247 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1248 break;
1249 case WINED3DSPSM_BIASNEG:
1250 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1251 break;
1252 case WINED3DSPSM_SIGN:
1253 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1254 break;
1255 case WINED3DSPSM_SIGNNEG:
1256 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1257 break;
1258 case WINED3DSPSM_COMP:
1259 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1260 break;
1261 case WINED3DSPSM_X2:
1262 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1263 break;
1264 case WINED3DSPSM_X2NEG:
1265 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1266 break;
1267 case WINED3DSPSM_ABS:
1268 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1269 break;
1270 case WINED3DSPSM_ABSNEG:
1271 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1272 break;
1273 default:
1274 FIXME("Unhandled modifier %u\n", src_modifier);
1275 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1279 /** Writes the GLSL variable name that corresponds to the register that the
1280 * DX opcode parameter is trying to access */
1281 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1282 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1284 /* oPos, oFog and oPts in D3D */
1285 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1287 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1288 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1289 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1291 *is_color = FALSE;
1293 switch (reg->type)
1295 case WINED3DSPR_TEMP:
1296 sprintf(register_name, "R%u", reg->idx);
1297 break;
1299 case WINED3DSPR_INPUT:
1300 /* vertex shaders */
1301 if (!pshader)
1303 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1304 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1305 sprintf(register_name, "attrib%u", reg->idx);
1306 break;
1309 /* pixel shaders >= 3.0 */
1310 if (This->baseShader.reg_maps.shader_version.major >= 3)
1312 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1313 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1315 if (reg->rel_addr)
1317 glsl_src_param_t rel_param;
1319 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1321 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1322 * operation there */
1323 if (idx)
1325 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1327 sprintf(register_name,
1328 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1329 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1330 rel_param.param_str, idx);
1332 else
1334 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1337 else
1339 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1341 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1342 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1343 rel_param.param_str);
1345 else
1347 sprintf(register_name, "IN[%s]", rel_param.param_str);
1351 else
1353 if (idx == in_count) sprintf(register_name, "gl_Color");
1354 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1355 else sprintf(register_name, "IN[%u]", idx);
1358 else
1360 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1361 else strcpy(register_name, "gl_SecondaryColor");
1362 break;
1364 break;
1366 case WINED3DSPR_CONST:
1368 const char prefix = pshader ? 'P' : 'V';
1370 /* Relative addressing */
1371 if (reg->rel_addr)
1373 glsl_src_param_t rel_param;
1374 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1375 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1376 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1378 else
1380 if (shader_constant_is_local(This, reg->idx))
1381 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1382 else
1383 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1386 break;
1388 case WINED3DSPR_CONSTINT:
1389 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1390 else sprintf(register_name, "VI[%u]", reg->idx);
1391 break;
1393 case WINED3DSPR_CONSTBOOL:
1394 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1395 else sprintf(register_name, "VB[%u]", reg->idx);
1396 break;
1398 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1399 if (pshader) sprintf(register_name, "T%u", reg->idx);
1400 else sprintf(register_name, "A%u", reg->idx);
1401 break;
1403 case WINED3DSPR_LOOP:
1404 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1405 break;
1407 case WINED3DSPR_SAMPLER:
1408 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1409 else sprintf(register_name, "Vsampler%u", reg->idx);
1410 break;
1412 case WINED3DSPR_COLOROUT:
1413 if (reg->idx >= gl_info->limits.buffers)
1414 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1416 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1417 break;
1419 case WINED3DSPR_RASTOUT:
1420 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1421 break;
1423 case WINED3DSPR_DEPTHOUT:
1424 sprintf(register_name, "gl_FragDepth");
1425 break;
1427 case WINED3DSPR_ATTROUT:
1428 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1429 else sprintf(register_name, "gl_FrontSecondaryColor");
1430 break;
1432 case WINED3DSPR_TEXCRDOUT:
1433 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1434 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1435 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1436 break;
1438 case WINED3DSPR_MISCTYPE:
1439 if (reg->idx == 0)
1441 /* vPos */
1442 sprintf(register_name, "vpos");
1444 else if (reg->idx == 1)
1446 /* Note that gl_FrontFacing is a bool, while vFace is
1447 * a float for which the sign determines front/back */
1448 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1450 else
1452 FIXME("Unhandled misctype register %d\n", reg->idx);
1453 sprintf(register_name, "unrecognized_register");
1455 break;
1457 case WINED3DSPR_IMMCONST:
1458 switch (reg->immconst_type)
1460 case WINED3D_IMMCONST_FLOAT:
1461 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1462 break;
1464 case WINED3D_IMMCONST_FLOAT4:
1465 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1466 *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1467 *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1468 break;
1470 default:
1471 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1472 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1474 break;
1476 default:
1477 FIXME("Unhandled register name Type(%d)\n", reg->type);
1478 sprintf(register_name, "unrecognized_register");
1479 break;
1483 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1485 *str++ = '.';
1486 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1487 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1488 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1489 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1490 *str = '\0';
1493 /* Get the GLSL write mask for the destination register */
1494 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1496 DWORD mask = param->write_mask;
1498 if (shader_is_scalar(&param->reg))
1500 mask = WINED3DSP_WRITEMASK_0;
1501 *write_mask = '\0';
1503 else
1505 shader_glsl_write_mask_to_str(mask, write_mask);
1508 return mask;
1511 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1512 unsigned int size = 0;
1514 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1515 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1516 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1517 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1519 return size;
1522 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1524 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1525 * but addressed as "rgba". To fix this we need to swap the register's x
1526 * and z components. */
1527 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1529 *str++ = '.';
1530 /* swizzle bits fields: wwzzyyxx */
1531 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1532 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1533 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1534 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1535 *str = '\0';
1538 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1539 BOOL fixup, DWORD mask, char *swizzle_str)
1541 if (shader_is_scalar(&param->reg))
1542 *swizzle_str = '\0';
1543 else
1544 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1547 /* From a given parameter token, generate the corresponding GLSL string.
1548 * Also, return the actual register name and swizzle in case the
1549 * caller needs this information as well. */
1550 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1551 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1553 BOOL is_color = FALSE;
1554 char swizzle_str[6];
1556 glsl_src->reg_name[0] = '\0';
1557 glsl_src->param_str[0] = '\0';
1558 swizzle_str[0] = '\0';
1560 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1561 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1562 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1565 /* From a given parameter token, generate the corresponding GLSL string.
1566 * Also, return the actual register name and swizzle in case the
1567 * caller needs this information as well. */
1568 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1569 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1571 BOOL is_color = FALSE;
1573 glsl_dst->mask_str[0] = '\0';
1574 glsl_dst->reg_name[0] = '\0';
1576 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1577 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1580 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1581 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1582 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1584 glsl_dst_param_t glsl_dst;
1585 DWORD mask;
1587 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1588 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1590 return mask;
1593 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1594 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1596 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1599 /** Process GLSL instruction modifiers */
1600 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1602 glsl_dst_param_t dst_param;
1603 DWORD modifiers;
1605 if (!ins->dst_count) return;
1607 modifiers = ins->dst[0].modifiers;
1608 if (!modifiers) return;
1610 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1612 if (modifiers & WINED3DSPDM_SATURATE)
1614 /* _SAT means to clamp the value of the register to between 0 and 1 */
1615 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1616 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1619 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1621 FIXME("_centroid modifier not handled\n");
1624 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1626 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1630 static inline const char *shader_get_comp_op(DWORD op)
1632 switch (op) {
1633 case COMPARISON_GT: return ">";
1634 case COMPARISON_EQ: return "==";
1635 case COMPARISON_GE: return ">=";
1636 case COMPARISON_LT: return "<";
1637 case COMPARISON_NE: return "!=";
1638 case COMPARISON_LE: return "<=";
1639 default:
1640 FIXME("Unrecognized comparison value: %u\n", op);
1641 return "(\?\?)";
1645 static void shader_glsl_get_sample_function(const struct wined3d_gl_info *gl_info,
1646 DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1648 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1649 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1650 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1651 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1653 /* Note that there's no such thing as a projected cube texture. */
1654 switch(sampler_type) {
1655 case WINED3DSTT_1D:
1656 if(lod) {
1657 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1659 else if (grad)
1661 if (gl_info->supported[EXT_GPU_SHADER4])
1662 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1663 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1664 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1665 else
1667 FIXME("Unsupported 1D grad function.\n");
1668 sample_function->name = "unsupported1DGrad";
1671 else
1673 sample_function->name = projected ? "texture1DProj" : "texture1D";
1675 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1676 break;
1677 case WINED3DSTT_2D:
1678 if(texrect) {
1679 if(lod) {
1680 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1682 else if (grad)
1684 if (gl_info->supported[EXT_GPU_SHADER4])
1685 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1686 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1687 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1688 else
1690 FIXME("Unsupported RECT grad function.\n");
1691 sample_function->name = "unsupported2DRectGrad";
1694 else
1696 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1698 } else {
1699 if(lod) {
1700 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1702 else if (grad)
1704 if (gl_info->supported[EXT_GPU_SHADER4])
1705 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1706 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1707 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1708 else
1710 FIXME("Unsupported 2D grad function.\n");
1711 sample_function->name = "unsupported2DGrad";
1714 else
1716 sample_function->name = projected ? "texture2DProj" : "texture2D";
1719 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1720 break;
1721 case WINED3DSTT_CUBE:
1722 if(lod) {
1723 sample_function->name = "textureCubeLod";
1725 else if (grad)
1727 if (gl_info->supported[EXT_GPU_SHADER4])
1728 sample_function->name = "textureCubeGrad";
1729 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1730 sample_function->name = "textureCubeGradARB";
1731 else
1733 FIXME("Unsupported Cube grad function.\n");
1734 sample_function->name = "unsupportedCubeGrad";
1737 else
1739 sample_function->name = "textureCube";
1741 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1742 break;
1743 case WINED3DSTT_VOLUME:
1744 if(lod) {
1745 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1747 else if (grad)
1749 if (gl_info->supported[EXT_GPU_SHADER4])
1750 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1751 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1752 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1753 else
1755 FIXME("Unsupported 3D grad function.\n");
1756 sample_function->name = "unsupported3DGrad";
1759 else
1761 sample_function->name = projected ? "texture3DProj" : "texture3D";
1763 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1764 break;
1765 default:
1766 sample_function->name = "";
1767 sample_function->coord_mask = 0;
1768 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1769 break;
1773 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1774 BOOL sign_fixup, enum fixup_channel_source channel_source)
1776 switch(channel_source)
1778 case CHANNEL_SOURCE_ZERO:
1779 strcat(arguments, "0.0");
1780 break;
1782 case CHANNEL_SOURCE_ONE:
1783 strcat(arguments, "1.0");
1784 break;
1786 case CHANNEL_SOURCE_X:
1787 strcat(arguments, reg_name);
1788 strcat(arguments, ".x");
1789 break;
1791 case CHANNEL_SOURCE_Y:
1792 strcat(arguments, reg_name);
1793 strcat(arguments, ".y");
1794 break;
1796 case CHANNEL_SOURCE_Z:
1797 strcat(arguments, reg_name);
1798 strcat(arguments, ".z");
1799 break;
1801 case CHANNEL_SOURCE_W:
1802 strcat(arguments, reg_name);
1803 strcat(arguments, ".w");
1804 break;
1806 default:
1807 FIXME("Unhandled channel source %#x\n", channel_source);
1808 strcat(arguments, "undefined");
1809 break;
1812 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1815 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1817 struct wined3d_shader_dst_param dst;
1818 unsigned int mask_size, remaining;
1819 glsl_dst_param_t dst_param;
1820 char arguments[256];
1821 DWORD mask;
1823 mask = 0;
1824 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1825 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1826 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1827 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1828 mask &= ins->dst[0].write_mask;
1830 if (!mask) return; /* Nothing to do */
1832 if (is_yuv_fixup(fixup))
1834 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1835 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1836 return;
1839 mask_size = shader_glsl_get_write_mask_size(mask);
1841 dst = ins->dst[0];
1842 dst.write_mask = mask;
1843 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1845 arguments[0] = '\0';
1846 remaining = mask_size;
1847 if (mask & WINED3DSP_WRITEMASK_0)
1849 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1850 if (--remaining) strcat(arguments, ", ");
1852 if (mask & WINED3DSP_WRITEMASK_1)
1854 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1855 if (--remaining) strcat(arguments, ", ");
1857 if (mask & WINED3DSP_WRITEMASK_2)
1859 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1860 if (--remaining) strcat(arguments, ", ");
1862 if (mask & WINED3DSP_WRITEMASK_3)
1864 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1865 if (--remaining) strcat(arguments, ", ");
1868 if (mask_size > 1)
1870 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1871 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1873 else
1875 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1879 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1880 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1881 const char *dx, const char *dy,
1882 const char *bias, const char *coord_reg_fmt, ...)
1884 const char *sampler_base;
1885 char dst_swizzle[6];
1886 struct color_fixup_desc fixup;
1887 BOOL np2_fixup = FALSE;
1888 va_list args;
1890 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1892 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1894 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1895 fixup = priv->cur_ps_args->color_fixup[sampler];
1896 sampler_base = "Psampler";
1898 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
1899 if(bias) {
1900 FIXME("Biased sampling from NP2 textures is unsupported\n");
1901 } else {
1902 np2_fixup = TRUE;
1905 } else {
1906 sampler_base = "Vsampler";
1907 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1910 shader_glsl_append_dst(ins->ctx->buffer, ins);
1912 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1914 va_start(args, coord_reg_fmt);
1915 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1916 va_end(args);
1918 if(bias) {
1919 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1920 } else {
1921 if (np2_fixup) {
1922 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1923 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
1925 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
1926 (idx % 2) ? "zw" : "xy", dst_swizzle);
1927 } else if(dx && dy) {
1928 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1929 } else {
1930 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1934 if(!is_identity_fixup(fixup)) {
1935 shader_glsl_color_correction(ins, fixup);
1939 /*****************************************************************************
1940 * Begin processing individual instruction opcodes
1941 ****************************************************************************/
1943 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1944 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1946 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1947 glsl_src_param_t src0_param;
1948 glsl_src_param_t src1_param;
1949 DWORD write_mask;
1950 char op;
1952 /* Determine the GLSL operator to use based on the opcode */
1953 switch (ins->handler_idx)
1955 case WINED3DSIH_MUL: op = '*'; break;
1956 case WINED3DSIH_ADD: op = '+'; break;
1957 case WINED3DSIH_SUB: op = '-'; break;
1958 default:
1959 op = ' ';
1960 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1961 break;
1964 write_mask = shader_glsl_append_dst(buffer, ins);
1965 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1966 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1967 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1970 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1971 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1973 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1974 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1975 glsl_src_param_t src0_param;
1976 DWORD write_mask;
1978 write_mask = shader_glsl_append_dst(buffer, ins);
1979 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1981 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1982 * shader versions WINED3DSIO_MOVA is used for this. */
1983 if (ins->ctx->reg_maps->shader_version.major == 1
1984 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1985 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1987 /* This is a simple floor() */
1988 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1989 if (mask_size > 1) {
1990 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1991 } else {
1992 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1995 else if(ins->handler_idx == WINED3DSIH_MOVA)
1997 /* We need to *round* to the nearest int here. */
1998 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2000 if (gl_info->supported[EXT_GPU_SHADER4])
2002 if (mask_size > 1)
2003 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2004 else
2005 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2007 else
2009 if (mask_size > 1)
2010 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2011 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2012 else
2013 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2014 src0_param.param_str, src0_param.param_str);
2017 else
2019 shader_addline(buffer, "%s);\n", src0_param.param_str);
2023 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2024 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2026 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2027 glsl_src_param_t src0_param;
2028 glsl_src_param_t src1_param;
2029 DWORD dst_write_mask, src_write_mask;
2030 unsigned int dst_size = 0;
2032 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2033 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2035 /* dp3 works on vec3, dp4 on vec4 */
2036 if (ins->handler_idx == WINED3DSIH_DP4)
2038 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2039 } else {
2040 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2043 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2044 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2046 if (dst_size > 1) {
2047 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2048 } else {
2049 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2053 /* Note that this instruction has some restrictions. The destination write mask
2054 * can't contain the w component, and the source swizzles have to be .xyzw */
2055 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2057 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2058 glsl_src_param_t src0_param;
2059 glsl_src_param_t src1_param;
2060 char dst_mask[6];
2062 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2063 shader_glsl_append_dst(ins->ctx->buffer, ins);
2064 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2065 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2066 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2069 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2070 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2071 * GLSL uses the value as-is. */
2072 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2074 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2075 glsl_src_param_t src0_param;
2076 glsl_src_param_t src1_param;
2077 DWORD dst_write_mask;
2078 unsigned int dst_size;
2080 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2081 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2083 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2084 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2086 if (dst_size > 1) {
2087 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2088 } else {
2089 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
2093 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2094 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2095 * GLSL uses the value as-is. */
2096 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2098 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2099 glsl_src_param_t src0_param;
2100 DWORD dst_write_mask;
2101 unsigned int dst_size;
2103 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2104 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2106 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2108 if (dst_size > 1)
2110 shader_addline(buffer, "vec%d(%s == 0.0 ? -FLT_MAX : log2(abs(%s))));\n",
2111 dst_size, src0_param.param_str, src0_param.param_str);
2113 else
2115 shader_addline(buffer, "%s == 0.0 ? -FLT_MAX : log2(abs(%s)));\n",
2116 src0_param.param_str, src0_param.param_str);
2120 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2121 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2123 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2124 glsl_src_param_t src_param;
2125 const char *instruction;
2126 DWORD write_mask;
2127 unsigned i;
2129 /* Determine the GLSL function to use based on the opcode */
2130 /* TODO: Possibly make this a table for faster lookups */
2131 switch (ins->handler_idx)
2133 case WINED3DSIH_MIN: instruction = "min"; break;
2134 case WINED3DSIH_MAX: instruction = "max"; break;
2135 case WINED3DSIH_ABS: instruction = "abs"; break;
2136 case WINED3DSIH_FRC: instruction = "fract"; break;
2137 case WINED3DSIH_EXP: instruction = "exp2"; break;
2138 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2139 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2140 default: instruction = "";
2141 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2142 break;
2145 write_mask = shader_glsl_append_dst(buffer, ins);
2147 shader_addline(buffer, "%s(", instruction);
2149 if (ins->src_count)
2151 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2152 shader_addline(buffer, "%s", src_param.param_str);
2153 for (i = 1; i < ins->src_count; ++i)
2155 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2156 shader_addline(buffer, ", %s", src_param.param_str);
2160 shader_addline(buffer, "));\n");
2163 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2165 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2166 glsl_src_param_t src_param;
2167 DWORD write_mask;
2168 char dst_mask[6];
2170 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2171 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2173 shader_addline(buffer, "tmp0.x = length(%s);\n", src_param.param_str);
2174 shader_glsl_append_dst(buffer, ins);
2175 shader_addline(buffer, "tmp0.x == 0.0 ? (%s * FLT_MAX) : (%s / tmp0.x));",
2176 src_param.param_str, src_param.param_str);
2179 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2180 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2181 * dst.x = 2^(floor(src))
2182 * dst.y = src - floor(src)
2183 * dst.z = 2^src (partial precision is allowed, but optional)
2184 * dst.w = 1.0;
2185 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2186 * dst = 2^src; (partial precision is allowed, but optional)
2188 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2190 glsl_src_param_t src_param;
2192 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2194 if (ins->ctx->reg_maps->shader_version.major < 2)
2196 char dst_mask[6];
2198 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2199 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2200 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2201 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2203 shader_glsl_append_dst(ins->ctx->buffer, ins);
2204 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2205 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2206 } else {
2207 DWORD write_mask;
2208 unsigned int mask_size;
2210 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2211 mask_size = shader_glsl_get_write_mask_size(write_mask);
2213 if (mask_size > 1) {
2214 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2215 } else {
2216 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2221 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2222 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2224 glsl_src_param_t src_param;
2225 DWORD write_mask;
2226 unsigned int mask_size;
2228 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2229 mask_size = shader_glsl_get_write_mask_size(write_mask);
2230 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2232 if (mask_size > 1)
2234 shader_addline(ins->ctx->buffer, "vec%d(%s == 0.0 ? FLT_MAX : 1.0 / %s));\n",
2235 mask_size, src_param.param_str, src_param.param_str);
2237 else
2239 shader_addline(ins->ctx->buffer, "%s == 0.0 ? FLT_MAX : 1.0 / %s);\n",
2240 src_param.param_str, src_param.param_str);
2244 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2246 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2247 glsl_src_param_t src_param;
2248 DWORD write_mask;
2249 unsigned int mask_size;
2251 write_mask = shader_glsl_append_dst(buffer, ins);
2252 mask_size = shader_glsl_get_write_mask_size(write_mask);
2254 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2256 if (mask_size > 1)
2258 shader_addline(buffer, "vec%d(%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s))));\n",
2259 mask_size, src_param.param_str, src_param.param_str);
2261 else
2263 shader_addline(buffer, "%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s)));\n",
2264 src_param.param_str, src_param.param_str);
2268 /** Process signed comparison opcodes in GLSL. */
2269 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2271 glsl_src_param_t src0_param;
2272 glsl_src_param_t src1_param;
2273 DWORD write_mask;
2274 unsigned int mask_size;
2276 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2277 mask_size = shader_glsl_get_write_mask_size(write_mask);
2278 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2279 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2281 if (mask_size > 1) {
2282 const char *compare;
2284 switch(ins->handler_idx)
2286 case WINED3DSIH_SLT: compare = "lessThan"; break;
2287 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2288 default: compare = "";
2289 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2292 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2293 src0_param.param_str, src1_param.param_str);
2294 } else {
2295 switch(ins->handler_idx)
2297 case WINED3DSIH_SLT:
2298 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2299 * to return 0.0 but step returns 1.0 because step is not < x
2300 * An alternative is a bvec compare padded with an unused second component.
2301 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2302 * issue. Playing with not() is not possible either because not() does not accept
2303 * a scalar.
2305 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2306 src0_param.param_str, src1_param.param_str);
2307 break;
2308 case WINED3DSIH_SGE:
2309 /* Here we can use the step() function and safe a conditional */
2310 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2311 break;
2312 default:
2313 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2319 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2320 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2322 glsl_src_param_t src0_param;
2323 glsl_src_param_t src1_param;
2324 glsl_src_param_t src2_param;
2325 DWORD write_mask, cmp_channel = 0;
2326 unsigned int i, j;
2327 char mask_char[6];
2328 BOOL temp_destination = FALSE;
2330 if (shader_is_scalar(&ins->src[0].reg))
2332 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2334 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2335 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2336 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2338 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2339 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2340 } else {
2341 DWORD dst_mask = ins->dst[0].write_mask;
2342 struct wined3d_shader_dst_param dst = ins->dst[0];
2344 /* Cycle through all source0 channels */
2345 for (i=0; i<4; i++) {
2346 write_mask = 0;
2347 /* Find the destination channels which use the current source0 channel */
2348 for (j=0; j<4; j++) {
2349 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2351 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2352 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2355 dst.write_mask = dst_mask & write_mask;
2357 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2358 * The first lines may overwrite source parameters of the following lines.
2359 * Deal with that by using a temporary destination register if needed
2361 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2362 && ins->src[0].reg.type == ins->dst[0].reg.type)
2363 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2364 && ins->src[1].reg.type == ins->dst[0].reg.type)
2365 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2366 && ins->src[2].reg.type == ins->dst[0].reg.type))
2368 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2369 if (!write_mask) continue;
2370 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2371 temp_destination = TRUE;
2372 } else {
2373 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2374 if (!write_mask) continue;
2377 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2378 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2379 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2381 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2382 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2385 if(temp_destination) {
2386 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2387 shader_glsl_append_dst(ins->ctx->buffer, ins);
2388 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2394 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2395 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2396 * the compare is done per component of src0. */
2397 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2399 struct wined3d_shader_dst_param dst;
2400 glsl_src_param_t src0_param;
2401 glsl_src_param_t src1_param;
2402 glsl_src_param_t src2_param;
2403 DWORD write_mask, cmp_channel = 0;
2404 unsigned int i, j;
2405 DWORD dst_mask;
2406 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2407 ins->ctx->reg_maps->shader_version.minor);
2409 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2411 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2412 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2413 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2414 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2416 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2417 if (ins->coissue)
2419 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2420 } else {
2421 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2422 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2424 return;
2426 /* Cycle through all source0 channels */
2427 dst_mask = ins->dst[0].write_mask;
2428 dst = ins->dst[0];
2429 for (i=0; i<4; i++) {
2430 write_mask = 0;
2431 /* Find the destination channels which use the current source0 channel */
2432 for (j=0; j<4; j++) {
2433 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2435 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2436 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2440 dst.write_mask = dst_mask & write_mask;
2441 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2442 if (!write_mask) continue;
2444 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2445 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2446 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2448 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2449 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2453 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2454 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2456 glsl_src_param_t src0_param;
2457 glsl_src_param_t src1_param;
2458 glsl_src_param_t src2_param;
2459 DWORD write_mask;
2461 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2462 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2463 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2464 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2465 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2466 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2469 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2470 Vertex shaders to GLSL codes */
2471 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2473 int i;
2474 int nComponents = 0;
2475 struct wined3d_shader_dst_param tmp_dst = {{0}};
2476 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2477 struct wined3d_shader_instruction tmp_ins;
2479 memset(&tmp_ins, 0, sizeof(tmp_ins));
2481 /* Set constants for the temporary argument */
2482 tmp_ins.ctx = ins->ctx;
2483 tmp_ins.dst_count = 1;
2484 tmp_ins.dst = &tmp_dst;
2485 tmp_ins.src_count = 2;
2486 tmp_ins.src = tmp_src;
2488 switch(ins->handler_idx)
2490 case WINED3DSIH_M4x4:
2491 nComponents = 4;
2492 tmp_ins.handler_idx = WINED3DSIH_DP4;
2493 break;
2494 case WINED3DSIH_M4x3:
2495 nComponents = 3;
2496 tmp_ins.handler_idx = WINED3DSIH_DP4;
2497 break;
2498 case WINED3DSIH_M3x4:
2499 nComponents = 4;
2500 tmp_ins.handler_idx = WINED3DSIH_DP3;
2501 break;
2502 case WINED3DSIH_M3x3:
2503 nComponents = 3;
2504 tmp_ins.handler_idx = WINED3DSIH_DP3;
2505 break;
2506 case WINED3DSIH_M3x2:
2507 nComponents = 2;
2508 tmp_ins.handler_idx = WINED3DSIH_DP3;
2509 break;
2510 default:
2511 break;
2514 tmp_dst = ins->dst[0];
2515 tmp_src[0] = ins->src[0];
2516 tmp_src[1] = ins->src[1];
2517 for (i = 0; i < nComponents; ++i)
2519 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2520 shader_glsl_dot(&tmp_ins);
2521 ++tmp_src[1].reg.idx;
2526 The LRP instruction performs a component-wise linear interpolation
2527 between the second and third operands using the first operand as the
2528 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2529 This is equivalent to mix(src2, src1, src0);
2531 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2533 glsl_src_param_t src0_param;
2534 glsl_src_param_t src1_param;
2535 glsl_src_param_t src2_param;
2536 DWORD write_mask;
2538 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2540 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2541 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2542 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2544 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2545 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2548 /** Process the WINED3DSIO_LIT instruction in GLSL:
2549 * dst.x = dst.w = 1.0
2550 * dst.y = (src0.x > 0) ? src0.x
2551 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2552 * where src.w is clamped at +- 128
2554 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2556 glsl_src_param_t src0_param;
2557 glsl_src_param_t src1_param;
2558 glsl_src_param_t src3_param;
2559 char dst_mask[6];
2561 shader_glsl_append_dst(ins->ctx->buffer, ins);
2562 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2564 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2565 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2566 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2568 /* The sdk specifies the instruction like this
2569 * dst.x = 1.0;
2570 * if(src.x > 0.0) dst.y = src.x
2571 * else dst.y = 0.0.
2572 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2573 * else dst.z = 0.0;
2574 * dst.w = 1.0;
2576 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2577 * dst.x = 1.0 ... No further explanation needed
2578 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2579 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2580 * dst.w = 1.0. ... Nothing fancy.
2582 * So we still have one conditional in there. So do this:
2583 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2585 * 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),
2586 * 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.
2587 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2589 shader_addline(ins->ctx->buffer,
2590 "vec4(1.0, max(%s, 0.0), pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2591 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2594 /** Process the WINED3DSIO_DST instruction in GLSL:
2595 * dst.x = 1.0
2596 * dst.y = src0.x * src0.y
2597 * dst.z = src0.z
2598 * dst.w = src1.w
2600 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2602 glsl_src_param_t src0y_param;
2603 glsl_src_param_t src0z_param;
2604 glsl_src_param_t src1y_param;
2605 glsl_src_param_t src1w_param;
2606 char dst_mask[6];
2608 shader_glsl_append_dst(ins->ctx->buffer, ins);
2609 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2611 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2612 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2613 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2614 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2616 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2617 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2620 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2621 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2622 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2624 * dst.x = cos(src0.?)
2625 * dst.y = sin(src0.?)
2626 * dst.z = dst.z
2627 * dst.w = dst.w
2629 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2631 glsl_src_param_t src0_param;
2632 DWORD write_mask;
2634 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2635 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2637 switch (write_mask) {
2638 case WINED3DSP_WRITEMASK_0:
2639 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2640 break;
2642 case WINED3DSP_WRITEMASK_1:
2643 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2644 break;
2646 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2647 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2648 break;
2650 default:
2651 ERR("Write mask should be .x, .y or .xy\n");
2652 break;
2656 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2657 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2658 * generate invalid code
2660 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2662 glsl_src_param_t src0_param;
2663 DWORD write_mask;
2665 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2666 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2668 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2671 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2672 * Start a for() loop where src1.y is the initial value of aL,
2673 * increment aL by src1.z for a total of src1.x iterations.
2674 * Need to use a temporary variable for this operation.
2676 /* FIXME: I don't think nested loops will work correctly this way. */
2677 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2679 glsl_src_param_t src1_param;
2680 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2681 const DWORD *control_values = NULL;
2682 const local_constant *constant;
2684 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2686 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2687 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2688 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2689 * addressing.
2691 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2693 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2694 if (constant->idx == ins->src[1].reg.idx)
2696 control_values = constant->value;
2697 break;
2702 if (control_values)
2704 struct wined3d_shader_loop_control loop_control;
2705 loop_control.count = control_values[0];
2706 loop_control.start = control_values[1];
2707 loop_control.step = (int)control_values[2];
2709 if (loop_control.step > 0)
2711 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2712 shader->baseShader.cur_loop_depth, loop_control.start,
2713 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2714 shader->baseShader.cur_loop_depth, loop_control.step);
2716 else if (loop_control.step < 0)
2718 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2719 shader->baseShader.cur_loop_depth, loop_control.start,
2720 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2721 shader->baseShader.cur_loop_depth, loop_control.step);
2723 else
2725 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2726 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2727 shader->baseShader.cur_loop_depth, loop_control.count,
2728 shader->baseShader.cur_loop_depth);
2730 } else {
2731 shader_addline(ins->ctx->buffer,
2732 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2733 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2734 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2735 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2738 shader->baseShader.cur_loop_depth++;
2739 shader->baseShader.cur_loop_regno++;
2742 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2744 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2746 shader_addline(ins->ctx->buffer, "}\n");
2748 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2750 shader->baseShader.cur_loop_depth--;
2751 shader->baseShader.cur_loop_regno--;
2754 if (ins->handler_idx == WINED3DSIH_ENDREP)
2756 shader->baseShader.cur_loop_depth--;
2760 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2762 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2763 glsl_src_param_t src0_param;
2764 const DWORD *control_values = NULL;
2765 const local_constant *constant;
2767 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2768 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2770 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2772 if (constant->idx == ins->src[0].reg.idx)
2774 control_values = constant->value;
2775 break;
2780 if(control_values) {
2781 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2782 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2783 control_values[0], shader->baseShader.cur_loop_depth);
2784 } else {
2785 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2786 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2787 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2788 src0_param.param_str, shader->baseShader.cur_loop_depth);
2790 shader->baseShader.cur_loop_depth++;
2793 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2795 glsl_src_param_t src0_param;
2797 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2798 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2801 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2803 glsl_src_param_t src0_param;
2804 glsl_src_param_t src1_param;
2806 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2807 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2809 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2810 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2813 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2815 shader_addline(ins->ctx->buffer, "} else {\n");
2818 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2820 shader_addline(ins->ctx->buffer, "break;\n");
2823 /* FIXME: According to MSDN the compare is done per component. */
2824 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2826 glsl_src_param_t src0_param;
2827 glsl_src_param_t src1_param;
2829 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2830 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2832 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2833 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2836 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2838 shader_addline(ins->ctx->buffer, "}\n");
2839 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2842 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2844 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2847 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2849 glsl_src_param_t src1_param;
2851 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2852 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2855 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
2857 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
2858 * function only suppresses the unhandled instruction warning
2862 /*********************************************
2863 * Pixel Shader Specific Code begins here
2864 ********************************************/
2865 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
2867 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2868 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
2869 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2870 ins->ctx->reg_maps->shader_version.minor);
2871 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2872 glsl_sample_function_t sample_function;
2873 DWORD sample_flags = 0;
2874 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2875 DWORD sampler_idx;
2876 DWORD mask = 0, swizzle;
2878 /* 1.0-1.4: Use destination register as sampler source.
2879 * 2.0+: Use provided sampler source. */
2880 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2881 else sampler_idx = ins->src[1].reg.idx;
2882 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2884 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2886 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2888 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2889 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2890 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2891 switch (flags & ~WINED3DTTFF_PROJECTED) {
2892 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2893 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2894 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2895 case WINED3DTTFF_COUNT4:
2896 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2900 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2902 DWORD src_mod = ins->src[0].modifiers;
2904 if (src_mod == WINED3DSPSM_DZ) {
2905 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2906 mask = WINED3DSP_WRITEMASK_2;
2907 } else if (src_mod == WINED3DSPSM_DW) {
2908 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2909 mask = WINED3DSP_WRITEMASK_3;
2911 } else {
2912 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2914 /* ps 2.0 texldp instruction always divides by the fourth component. */
2915 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2916 mask = WINED3DSP_WRITEMASK_3;
2920 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2921 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2922 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2925 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
2926 mask |= sample_function.coord_mask;
2928 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2929 else swizzle = ins->src[1].swizzle;
2931 /* 1.0-1.3: Use destination register as coordinate source.
2932 1.4+: Use provided coordinate source register. */
2933 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2935 char coord_mask[6];
2936 shader_glsl_write_mask_to_str(mask, coord_mask);
2937 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2938 "T%u%s", sampler_idx, coord_mask);
2939 } else {
2940 glsl_src_param_t coord_param;
2941 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2942 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2944 glsl_src_param_t bias;
2945 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2946 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2947 "%s", coord_param.param_str);
2948 } else {
2949 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2950 "%s", coord_param.param_str);
2955 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2957 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2958 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2959 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2960 glsl_sample_function_t sample_function;
2961 glsl_src_param_t coord_param, dx_param, dy_param;
2962 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2963 DWORD sampler_type;
2964 DWORD sampler_idx;
2965 DWORD swizzle = ins->src[1].swizzle;
2967 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
2969 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2970 return shader_glsl_tex(ins);
2973 sampler_idx = ins->src[1].reg.idx;
2974 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2975 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2976 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2977 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2980 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
2981 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2982 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2983 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2985 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2986 "%s", coord_param.param_str);
2989 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2991 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2992 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2993 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2994 glsl_sample_function_t sample_function;
2995 glsl_src_param_t coord_param, lod_param;
2996 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2997 DWORD sampler_type;
2998 DWORD sampler_idx;
2999 DWORD swizzle = ins->src[1].swizzle;
3001 sampler_idx = ins->src[1].reg.idx;
3002 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3003 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3004 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3005 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3007 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3008 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3010 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3012 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3013 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3015 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
3016 * However, they seem to work just fine in fragment shaders as well. */
3017 WARN("Using %s in fragment shader.\n", sample_function.name);
3019 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3020 "%s", coord_param.param_str);
3023 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3025 /* FIXME: Make this work for more than just 2D textures */
3026 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3027 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3029 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3031 char dst_mask[6];
3033 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3034 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3035 ins->dst[0].reg.idx, dst_mask);
3036 } else {
3037 DWORD reg = ins->src[0].reg.idx;
3038 DWORD src_mod = ins->src[0].modifiers;
3039 char dst_swizzle[6];
3041 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3043 if (src_mod == WINED3DSPSM_DZ) {
3044 glsl_src_param_t div_param;
3045 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3046 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3048 if (mask_size > 1) {
3049 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3050 } else {
3051 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3053 } else if (src_mod == WINED3DSPSM_DW) {
3054 glsl_src_param_t div_param;
3055 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3056 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3058 if (mask_size > 1) {
3059 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3060 } else {
3061 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3063 } else {
3064 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3069 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3070 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3071 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3072 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3074 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3075 glsl_src_param_t src0_param;
3076 glsl_sample_function_t sample_function;
3077 DWORD sampler_idx = ins->dst[0].reg.idx;
3078 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3079 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3080 UINT mask_size;
3082 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3084 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3085 * scalar, and projected sampling would require 4.
3087 * It is a dependent read - not valid with conditional NP2 textures
3089 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3090 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3092 switch(mask_size)
3094 case 1:
3095 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3096 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3097 break;
3099 case 2:
3100 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3101 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3102 break;
3104 case 3:
3105 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3106 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3107 break;
3109 default:
3110 FIXME("Unexpected mask size %u\n", mask_size);
3111 break;
3115 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3116 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3117 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3119 glsl_src_param_t src0_param;
3120 DWORD dstreg = ins->dst[0].reg.idx;
3121 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3122 DWORD dst_mask;
3123 unsigned int mask_size;
3125 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3126 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3127 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3129 if (mask_size > 1) {
3130 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3131 } else {
3132 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3136 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3137 * Calculate the depth as dst.x / dst.y */
3138 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3140 glsl_dst_param_t dst_param;
3142 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3144 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3145 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3146 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3147 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3148 * >= 1.0 or < 0.0
3150 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3151 dst_param.reg_name, dst_param.reg_name);
3154 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3155 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3156 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3157 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3159 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3161 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3162 DWORD dstreg = ins->dst[0].reg.idx;
3163 glsl_src_param_t src0_param;
3165 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3167 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3168 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3171 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3172 * Calculate the 1st of a 2-row matrix multiplication. */
3173 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3175 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3176 DWORD reg = ins->dst[0].reg.idx;
3177 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3178 glsl_src_param_t src0_param;
3180 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3181 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3184 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3185 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3186 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3188 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3189 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3190 DWORD reg = ins->dst[0].reg.idx;
3191 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3192 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3193 glsl_src_param_t src0_param;
3195 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3196 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3197 current_state->texcoord_w[current_state->current_row++] = reg;
3200 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3202 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3203 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3204 DWORD reg = ins->dst[0].reg.idx;
3205 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3206 glsl_src_param_t src0_param;
3207 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3208 glsl_sample_function_t sample_function;
3210 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3211 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3213 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3215 /* Sample the texture using the calculated coordinates */
3216 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3219 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3220 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3221 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3223 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3224 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3225 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3226 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3227 glsl_src_param_t src0_param;
3228 DWORD reg = ins->dst[0].reg.idx;
3229 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3230 glsl_sample_function_t sample_function;
3232 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3233 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3235 /* Dependent read, not valid with conditional NP2 */
3236 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3238 /* Sample the texture using the calculated coordinates */
3239 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3241 current_state->current_row = 0;
3244 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3245 * Perform the 3rd row of a 3x3 matrix multiply */
3246 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3248 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3249 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3250 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3251 glsl_src_param_t src0_param;
3252 char dst_mask[6];
3253 DWORD reg = ins->dst[0].reg.idx;
3255 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3257 shader_glsl_append_dst(ins->ctx->buffer, ins);
3258 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3259 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3261 current_state->current_row = 0;
3264 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3265 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3266 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3268 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3269 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3270 DWORD reg = ins->dst[0].reg.idx;
3271 glsl_src_param_t src0_param;
3272 glsl_src_param_t src1_param;
3273 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3274 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3275 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3276 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3277 glsl_sample_function_t sample_function;
3279 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3280 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3282 /* Perform the last matrix multiply operation */
3283 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3284 /* Reflection calculation */
3285 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3287 /* Dependent read, not valid with conditional NP2 */
3288 shader_glsl_get_sample_function(gl_info, stype, 0, &sample_function);
3290 /* Sample the texture */
3291 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3293 current_state->current_row = 0;
3296 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3297 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3298 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3300 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3301 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3302 DWORD reg = ins->dst[0].reg.idx;
3303 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3304 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3305 glsl_src_param_t src0_param;
3306 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3307 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3308 glsl_sample_function_t sample_function;
3310 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3312 /* Perform the last matrix multiply operation */
3313 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3315 /* Construct the eye-ray vector from w coordinates */
3316 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3317 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3318 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3320 /* Dependent read, not valid with conditional NP2 */
3321 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3323 /* Sample the texture using the calculated coordinates */
3324 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3326 current_state->current_row = 0;
3329 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3330 * Apply a fake bump map transform.
3331 * texbem is pshader <= 1.3 only, this saves a few version checks
3333 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3335 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3336 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3337 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3338 glsl_sample_function_t sample_function;
3339 glsl_src_param_t coord_param;
3340 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3341 DWORD sampler_idx;
3342 DWORD mask;
3343 DWORD flags;
3344 char coord_mask[6];
3346 sampler_idx = ins->dst[0].reg.idx;
3347 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3349 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3350 /* Dependent read, not valid with conditional NP2 */
3351 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3352 mask = sample_function.coord_mask;
3354 shader_glsl_write_mask_to_str(mask, coord_mask);
3356 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3357 * so we can't let the GL handle this.
3359 if (flags & WINED3DTTFF_PROJECTED) {
3360 DWORD div_mask=0;
3361 char coord_div_mask[3];
3362 switch (flags & ~WINED3DTTFF_PROJECTED) {
3363 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3364 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3365 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3366 case WINED3DTTFF_COUNT4:
3367 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3369 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3370 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3373 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3375 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3376 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3377 coord_param.param_str, coord_mask);
3379 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3381 glsl_src_param_t luminance_param;
3382 glsl_dst_param_t dst_param;
3384 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3385 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3387 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3388 dst_param.reg_name, dst_param.mask_str,
3389 luminance_param.param_str, sampler_idx, sampler_idx);
3393 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3395 glsl_src_param_t src0_param, src1_param;
3396 DWORD sampler_idx = ins->dst[0].reg.idx;
3398 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3399 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3401 shader_glsl_append_dst(ins->ctx->buffer, ins);
3402 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3403 src0_param.param_str, sampler_idx, src1_param.param_str);
3406 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3407 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3408 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3410 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3411 glsl_src_param_t src0_param;
3412 DWORD sampler_idx = ins->dst[0].reg.idx;
3413 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3414 glsl_sample_function_t sample_function;
3416 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3418 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3419 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3420 "%s.wx", src0_param.reg_name);
3423 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3424 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3425 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3427 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3428 glsl_src_param_t src0_param;
3429 DWORD sampler_idx = ins->dst[0].reg.idx;
3430 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3431 glsl_sample_function_t sample_function;
3433 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3435 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3436 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3437 "%s.yz", src0_param.reg_name);
3440 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3441 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3442 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3444 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3445 glsl_src_param_t src0_param;
3446 DWORD sampler_idx = ins->dst[0].reg.idx;
3447 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3448 glsl_sample_function_t sample_function;
3450 /* Dependent read, not valid with conditional NP2 */
3451 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3452 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3454 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3455 "%s", src0_param.param_str);
3458 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3459 * If any of the first 3 components are < 0, discard this pixel */
3460 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3462 glsl_dst_param_t dst_param;
3464 /* The argument is a destination parameter, and no writemasks are allowed */
3465 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3466 if (ins->ctx->reg_maps->shader_version.major >= 2)
3468 /* 2.0 shaders compare all 4 components in texkill */
3469 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3470 } else {
3471 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3472 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3473 * 4 components are defined, only the first 3 are used
3475 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3479 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3480 * dst = dot2(src0, src1) + src2 */
3481 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3483 glsl_src_param_t src0_param;
3484 glsl_src_param_t src1_param;
3485 glsl_src_param_t src2_param;
3486 DWORD write_mask;
3487 unsigned int mask_size;
3489 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3490 mask_size = shader_glsl_get_write_mask_size(write_mask);
3492 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3493 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3494 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3496 if (mask_size > 1) {
3497 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3498 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3499 } else {
3500 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3501 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3505 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3506 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3507 enum vertexprocessing_mode vertexprocessing)
3509 unsigned int i;
3510 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3511 WORD map = reg_maps->input_registers;
3513 for (i = 0; map; map >>= 1, ++i)
3515 const char *semantic_name;
3516 UINT semantic_idx;
3517 char reg_mask[6];
3519 /* Unused */
3520 if (!(map & 1)) continue;
3522 semantic_name = input_signature[i].semantic_name;
3523 semantic_idx = input_signature[i].semantic_idx;
3524 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3526 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3528 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3529 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3530 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3531 else
3532 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3533 This->input_reg_map[i], reg_mask, reg_mask);
3535 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3537 if (semantic_idx == 0)
3538 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3539 This->input_reg_map[i], reg_mask, reg_mask);
3540 else if (semantic_idx == 1)
3541 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3542 This->input_reg_map[i], reg_mask, reg_mask);
3543 else
3544 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3545 This->input_reg_map[i], reg_mask, reg_mask);
3547 else
3549 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3550 This->input_reg_map[i], reg_mask, reg_mask);
3555 /*********************************************
3556 * Vertex Shader Specific Code begins here
3557 ********************************************/
3559 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3560 glsl_program_key_t key;
3562 key.vshader = entry->vshader;
3563 key.pshader = entry->pshader;
3564 key.vs_args = entry->vs_args;
3565 key.ps_args = entry->ps_args;
3567 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3569 ERR("Failed to insert program entry.\n");
3573 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3574 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3575 struct ps_compile_args *ps_args) {
3576 struct wine_rb_entry *entry;
3577 glsl_program_key_t key;
3579 key.vshader = vshader;
3580 key.pshader = pshader;
3581 key.vs_args = *vs_args;
3582 key.ps_args = *ps_args;
3584 entry = wine_rb_get(&priv->program_lookup, &key);
3585 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3588 /* GL locking is done by the caller */
3589 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3590 struct glsl_shader_prog_link *entry)
3592 glsl_program_key_t key;
3594 key.vshader = entry->vshader;
3595 key.pshader = entry->pshader;
3596 key.vs_args = entry->vs_args;
3597 key.ps_args = entry->ps_args;
3598 wine_rb_remove(&priv->program_lookup, &key);
3600 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3601 if (entry->vshader) list_remove(&entry->vshader_entry);
3602 if (entry->pshader) list_remove(&entry->pshader_entry);
3603 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3604 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3605 HeapFree(GetProcessHeap(), 0, entry);
3608 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3609 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3610 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3612 unsigned int i, j;
3613 const char *semantic_name_in, *semantic_name_out;
3614 UINT semantic_idx_in, semantic_idx_out;
3615 DWORD *set;
3616 DWORD in_idx;
3617 unsigned int in_count = vec4_varyings(3, gl_info);
3618 char reg_mask[6], reg_mask_out[6];
3619 char destination[50];
3620 WORD input_map, output_map;
3622 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3624 if (!output_signature)
3626 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3627 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3628 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3631 input_map = reg_maps_in->input_registers;
3632 for (i = 0; input_map; input_map >>= 1, ++i)
3634 if (!(input_map & 1)) continue;
3636 in_idx = map[i];
3637 if (in_idx >= (in_count + 2)) {
3638 FIXME("More input varyings declared than supported, expect issues\n");
3639 continue;
3641 else if (map[i] == ~0U)
3643 /* Declared, but not read register */
3644 continue;
3647 if (in_idx == in_count) {
3648 sprintf(destination, "gl_FrontColor");
3649 } else if (in_idx == in_count + 1) {
3650 sprintf(destination, "gl_FrontSecondaryColor");
3651 } else {
3652 sprintf(destination, "IN[%u]", in_idx);
3655 semantic_name_in = input_signature[i].semantic_name;
3656 semantic_idx_in = input_signature[i].semantic_idx;
3657 set[map[i]] = input_signature[i].mask;
3658 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3660 if (!output_signature)
3662 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3664 if (semantic_idx_in == 0)
3665 shader_addline(buffer, "%s%s = front_color%s;\n",
3666 destination, reg_mask, reg_mask);
3667 else if (semantic_idx_in == 1)
3668 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3669 destination, reg_mask, reg_mask);
3670 else
3671 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3672 destination, reg_mask, reg_mask);
3674 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3676 if (semantic_idx_in < 8)
3678 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3679 destination, reg_mask, semantic_idx_in, reg_mask);
3681 else
3683 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3684 destination, reg_mask, reg_mask);
3687 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3689 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3690 destination, reg_mask, reg_mask);
3692 else
3694 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3695 destination, reg_mask, reg_mask);
3697 } else {
3698 BOOL found = FALSE;
3700 output_map = reg_maps_out->output_registers;
3701 for (j = 0; output_map; output_map >>= 1, ++j)
3703 if (!(output_map & 1)) continue;
3705 semantic_name_out = output_signature[j].semantic_name;
3706 semantic_idx_out = output_signature[j].semantic_idx;
3707 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3709 if (semantic_idx_in == semantic_idx_out
3710 && !strcmp(semantic_name_in, semantic_name_out))
3712 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3713 destination, reg_mask, j, reg_mask);
3714 found = TRUE;
3717 if(!found) {
3718 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3719 destination, reg_mask, reg_mask);
3724 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3725 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3726 * input varyings are assigned above, if the optimizer works properly.
3728 for(i = 0; i < in_count + 2; i++) {
3729 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
3731 unsigned int size = 0;
3732 memset(reg_mask, 0, sizeof(reg_mask));
3733 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3734 reg_mask[size] = 'x';
3735 size++;
3737 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3738 reg_mask[size] = 'y';
3739 size++;
3741 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3742 reg_mask[size] = 'z';
3743 size++;
3745 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3746 reg_mask[size] = 'w';
3747 size++;
3750 if (i == in_count) {
3751 sprintf(destination, "gl_FrontColor");
3752 } else if (i == in_count + 1) {
3753 sprintf(destination, "gl_FrontSecondaryColor");
3754 } else {
3755 sprintf(destination, "IN[%u]", i);
3758 if (size == 1) {
3759 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3760 } else {
3761 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3766 HeapFree(GetProcessHeap(), 0, set);
3769 /* GL locking is done by the caller */
3770 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3771 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3773 GLhandleARB ret = 0;
3774 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3775 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3776 IWineD3DDeviceImpl *device;
3777 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3778 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3779 unsigned int i;
3780 const char *semantic_name;
3781 UINT semantic_idx;
3782 char reg_mask[6];
3783 const struct wined3d_shader_signature_element *output_signature;
3785 shader_buffer_clear(buffer);
3787 shader_addline(buffer, "#version 120\n");
3789 if(vs_major < 3 && ps_major < 3) {
3790 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3791 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3793 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3794 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
3795 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
3797 shader_addline(buffer, "void order_ps_input() {\n");
3798 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3799 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3800 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3801 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3804 shader_addline(buffer, "}\n");
3805 } else {
3806 shader_addline(buffer, "void order_ps_input() { /* do nothing */ }\n");
3808 } else if(ps_major < 3 && vs_major >= 3) {
3809 WORD map = vs->baseShader.reg_maps.output_registers;
3811 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3812 output_signature = vs->baseShader.output_signature;
3814 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3815 for (i = 0; map; map >>= 1, ++i)
3817 DWORD write_mask;
3819 if (!(map & 1)) continue;
3821 semantic_name = output_signature[i].semantic_name;
3822 semantic_idx = output_signature[i].semantic_idx;
3823 write_mask = output_signature[i].mask;
3824 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3826 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3828 if (semantic_idx == 0)
3829 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3830 else if (semantic_idx == 1)
3831 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3833 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3835 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3837 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3839 if (semantic_idx < 8)
3841 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3842 write_mask |= WINED3DSP_WRITEMASK_3;
3844 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3845 semantic_idx, reg_mask, i, reg_mask);
3846 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3847 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3850 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3852 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3854 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3856 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3859 shader_addline(buffer, "}\n");
3861 } else if(ps_major >= 3 && vs_major >= 3) {
3862 WORD map = vs->baseShader.reg_maps.output_registers;
3864 output_signature = vs->baseShader.output_signature;
3866 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3867 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3868 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3870 /* First, sort out position and point size. Those are not passed to the pixel shader */
3871 for (i = 0; map; map >>= 1, ++i)
3873 if (!(map & 1)) continue;
3875 semantic_name = output_signature[i].semantic_name;
3876 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3878 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3880 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3882 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3884 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3888 /* Then, fix the pixel shader input */
3889 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3890 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3892 shader_addline(buffer, "}\n");
3893 } else if(ps_major >= 3 && vs_major < 3) {
3894 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3895 shader_addline(buffer, "void order_ps_input() {\n");
3896 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3897 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3898 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3900 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3901 &ps->baseShader.reg_maps, NULL, NULL);
3902 shader_addline(buffer, "}\n");
3903 } else {
3904 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3907 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3908 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3909 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
3910 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
3911 GL_EXTCALL(glCompileShaderARB(ret));
3912 checkGLcall("glCompileShaderARB(ret)");
3914 return ret;
3917 /* GL locking is done by the caller */
3918 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3919 GLhandleARB programId, char prefix)
3921 const local_constant *lconst;
3922 GLint tmp_loc;
3923 const float *value;
3924 char glsl_name[8];
3926 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3927 value = (const float *)lconst->value;
3928 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3929 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3930 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3932 checkGLcall("Hardcoding local constants");
3935 /* GL locking is done by the caller */
3936 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3937 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3938 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3940 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3941 const struct wined3d_gl_info *gl_info = context->gl_info;
3942 CONST DWORD *function = This->baseShader.function;
3943 struct shader_glsl_ctx_priv priv_ctx;
3945 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3946 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3948 memset(&priv_ctx, 0, sizeof(priv_ctx));
3949 priv_ctx.cur_ps_args = args;
3950 priv_ctx.cur_np2fixup_info = np2fixup_info;
3952 shader_addline(buffer, "#version 120\n");
3954 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
3956 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3958 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3960 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3961 * drivers write a warning if we don't do so
3963 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3965 if (gl_info->supported[EXT_GPU_SHADER4])
3967 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3970 /* Base Declarations */
3971 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3973 /* Pack 3.0 inputs */
3974 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3976 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
3977 This->baseShader.input_signature, reg_maps, args->vp_mode);
3980 /* Base Shader Body */
3981 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3983 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3984 if (reg_maps->shader_version.major < 2)
3986 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3987 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3990 if (args->srgb_correction)
3992 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
3993 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
3994 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
3995 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
3996 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
3997 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
3999 /* Pixel shader < 3.0 do not replace the fog stage.
4000 * This implements linear fog computation and blending.
4001 * TODO: non linear fog
4002 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4003 * -1/(e-s) and e/(e-s) respectively.
4005 if (reg_maps->shader_version.major < 3)
4007 switch(args->fog) {
4008 case FOG_OFF: break;
4009 case FOG_LINEAR:
4010 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4011 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4012 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4013 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4014 break;
4015 case FOG_EXP:
4016 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4017 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4018 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4019 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4020 break;
4021 case FOG_EXP2:
4022 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4023 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4024 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4025 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4026 break;
4030 shader_addline(buffer, "}\n");
4032 TRACE("Compiling shader object %u\n", shader_obj);
4033 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4034 GL_EXTCALL(glCompileShaderARB(shader_obj));
4035 print_glsl_info_log(gl_info, shader_obj);
4037 /* Store the shader object */
4038 return shader_obj;
4041 /* GL locking is done by the caller */
4042 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4043 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4044 const struct vs_compile_args *args)
4046 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4047 const struct wined3d_gl_info *gl_info = context->gl_info;
4048 CONST DWORD *function = This->baseShader.function;
4049 struct shader_glsl_ctx_priv priv_ctx;
4051 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4052 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4054 shader_addline(buffer, "#version 120\n");
4056 if (gl_info->supported[EXT_GPU_SHADER4])
4058 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4061 memset(&priv_ctx, 0, sizeof(priv_ctx));
4062 priv_ctx.cur_vs_args = args;
4064 /* Base Declarations */
4065 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4067 /* Base Shader Body */
4068 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4070 /* Unpack 3.0 outputs */
4071 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
4072 else shader_addline(buffer, "order_ps_input();\n");
4074 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4075 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4076 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4077 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4079 if(args->fog_src == VS_FOG_Z) {
4080 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4081 } else if (!reg_maps->fog) {
4082 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4085 /* Write the final position.
4087 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4088 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4089 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4090 * contains 1.0 to allow a mad.
4092 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4093 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4094 if(args->clip_enabled) {
4095 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4098 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4100 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4101 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4102 * which is the same as z = z * 2 - w.
4104 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4106 shader_addline(buffer, "}\n");
4108 TRACE("Compiling shader object %u\n", shader_obj);
4109 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4110 GL_EXTCALL(glCompileShaderARB(shader_obj));
4111 print_glsl_info_log(gl_info, shader_obj);
4113 return shader_obj;
4116 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4117 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4118 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4120 UINT i;
4121 DWORD new_size;
4122 struct glsl_ps_compiled_shader *new_array;
4123 struct glsl_pshader_private *shader_data;
4124 struct ps_np2fixup_info *np2fixup = NULL;
4125 GLhandleARB ret;
4127 if (!shader->baseShader.backend_data)
4129 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4130 if (!shader->baseShader.backend_data)
4132 ERR("Failed to allocate backend data.\n");
4133 return 0;
4136 shader_data = shader->baseShader.backend_data;
4138 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4139 * so a linear search is more performant than a hashmap or a binary search
4140 * (cache coherency etc)
4142 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4143 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4144 if(args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4145 return shader_data->gl_shaders[i].prgId;
4149 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4150 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4151 if (shader_data->num_gl_shaders)
4153 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4154 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4155 new_size * sizeof(*shader_data->gl_shaders));
4156 } else {
4157 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4158 new_size = 1;
4161 if(!new_array) {
4162 ERR("Out of memory\n");
4163 return 0;
4165 shader_data->gl_shaders = new_array;
4166 shader_data->shader_array_size = new_size;
4169 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4171 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4172 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4174 pixelshader_update_samplers(&shader->baseShader.reg_maps,
4175 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4177 shader_buffer_clear(buffer);
4178 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4179 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4180 *np2fixup_info = np2fixup;
4182 return ret;
4185 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4186 const DWORD use_map) {
4187 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4188 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4189 return stored->fog_src == new->fog_src;
4192 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4193 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4194 const struct vs_compile_args *args)
4196 UINT i;
4197 DWORD new_size;
4198 struct glsl_vs_compiled_shader *new_array;
4199 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4200 struct glsl_vshader_private *shader_data;
4201 GLhandleARB ret;
4203 if (!shader->baseShader.backend_data)
4205 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4206 if (!shader->baseShader.backend_data)
4208 ERR("Failed to allocate backend data.\n");
4209 return 0;
4212 shader_data = shader->baseShader.backend_data;
4214 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4215 * so a linear search is more performant than a hashmap or a binary search
4216 * (cache coherency etc)
4218 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4219 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4220 return shader_data->gl_shaders[i].prgId;
4224 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4226 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4227 if (shader_data->num_gl_shaders)
4229 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4230 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4231 new_size * sizeof(*shader_data->gl_shaders));
4232 } else {
4233 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4234 new_size = 1;
4237 if(!new_array) {
4238 ERR("Out of memory\n");
4239 return 0;
4241 shader_data->gl_shaders = new_array;
4242 shader_data->shader_array_size = new_size;
4245 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4247 shader_buffer_clear(buffer);
4248 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4249 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4251 return ret;
4254 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4255 * It sets the programId on the current StateBlock (because it should be called
4256 * inside of the DrawPrimitive() part of the render loop).
4258 * If a program for the given combination does not exist, create one, and store
4259 * the program in the hash table. If it creates a program, it will link the
4260 * given objects, too.
4263 /* GL locking is done by the caller */
4264 static void set_glsl_shader_program(const struct wined3d_context *context,
4265 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4267 IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
4268 IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
4269 const struct wined3d_gl_info *gl_info = context->gl_info;
4270 struct shader_glsl_priv *priv = device->shader_priv;
4271 struct glsl_shader_prog_link *entry = NULL;
4272 GLhandleARB programId = 0;
4273 GLhandleARB reorder_shader_id = 0;
4274 unsigned int i;
4275 char glsl_name[8];
4276 struct ps_compile_args ps_compile_args;
4277 struct vs_compile_args vs_compile_args;
4279 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4280 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4282 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4283 if (entry) {
4284 priv->glsl_program = entry;
4285 return;
4288 /* If we get to this point, then no matching program exists, so we create one */
4289 programId = GL_EXTCALL(glCreateProgramObjectARB());
4290 TRACE("Created new GLSL shader program %u\n", programId);
4292 /* Create the entry */
4293 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4294 entry->programId = programId;
4295 entry->vshader = vshader;
4296 entry->pshader = pshader;
4297 entry->vs_args = vs_compile_args;
4298 entry->ps_args = ps_compile_args;
4299 entry->constant_version = 0;
4300 entry->np2Fixup_info = NULL;
4301 /* Add the hash table entry */
4302 add_glsl_program_entry(priv, entry);
4304 /* Set the current program */
4305 priv->glsl_program = entry;
4307 /* Attach GLSL vshader */
4308 if (vshader)
4310 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4311 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4312 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4313 char tmp_name[10];
4315 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4316 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4317 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4318 checkGLcall("glAttachObjectARB");
4319 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4320 * is destroyed
4322 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4324 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4325 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4326 checkGLcall("glAttachObjectARB");
4328 /* Bind vertex attributes to a corresponding index number to match
4329 * the same index numbers as ARB_vertex_programs (makes loading
4330 * vertex attributes simpler). With this method, we can use the
4331 * exact same code to load the attributes later for both ARB and
4332 * GLSL shaders.
4334 * We have to do this here because we need to know the Program ID
4335 * in order to make the bindings work, and it has to be done prior
4336 * to linking the GLSL program. */
4337 for (i = 0; map; map >>= 1, ++i)
4339 if (!(map & 1)) continue;
4341 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4342 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4344 checkGLcall("glBindAttribLocationARB");
4346 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4349 /* Attach GLSL pshader */
4350 if (pshader)
4352 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4353 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4354 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4355 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4356 checkGLcall("glAttachObjectARB");
4358 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4361 /* Link the program */
4362 TRACE("Linking GLSL shader program %u\n", programId);
4363 GL_EXTCALL(glLinkProgramARB(programId));
4364 shader_glsl_validate_link(gl_info, programId);
4366 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4367 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4368 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4370 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4371 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4373 for (i = 0; i < MAX_CONST_I; ++i)
4375 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4376 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4378 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4379 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4380 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4382 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4383 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4385 for (i = 0; i < MAX_CONST_I; ++i)
4387 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4388 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4391 if(pshader) {
4392 char name[32];
4394 for(i = 0; i < MAX_TEXTURES; i++) {
4395 sprintf(name, "bumpenvmat%u", i);
4396 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4397 sprintf(name, "luminancescale%u", i);
4398 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4399 sprintf(name, "luminanceoffset%u", i);
4400 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4403 if (ps_compile_args.np2_fixup) {
4404 if (entry->np2Fixup_info) {
4405 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4406 } else {
4407 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4412 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4413 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4414 checkGLcall("Find glsl program uniform locations");
4416 if (pshader
4417 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4418 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4420 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4421 entry->vertex_color_clamp = GL_FALSE;
4422 } else {
4423 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4426 /* Set the shader to allow uniform loading on it */
4427 GL_EXTCALL(glUseProgramObjectARB(programId));
4428 checkGLcall("glUseProgramObjectARB(programId)");
4430 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4431 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4432 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4433 * vertex shader with fixed function pixel processing is used we make sure that the card
4434 * supports enough samplers to allow the max number of vertex samplers with all possible
4435 * fixed function fragment processing setups. So once the program is linked these samplers
4436 * won't change.
4438 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4439 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4441 /* If the local constants do not have to be loaded with the environment constants,
4442 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4443 * later
4445 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4447 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4449 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4451 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4455 /* GL locking is done by the caller */
4456 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4458 GLhandleARB program_id;
4459 GLhandleARB vshader_id, pshader_id;
4460 static const char *blt_vshader[] =
4462 "#version 120\n"
4463 "void main(void)\n"
4464 "{\n"
4465 " gl_Position = gl_Vertex;\n"
4466 " gl_FrontColor = vec4(1.0);\n"
4467 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4468 "}\n"
4471 static const char *blt_pshaders[tex_type_count] =
4473 /* tex_1d */
4474 NULL,
4475 /* tex_2d */
4476 "#version 120\n"
4477 "uniform sampler2D sampler;\n"
4478 "void main(void)\n"
4479 "{\n"
4480 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4481 "}\n",
4482 /* tex_3d */
4483 NULL,
4484 /* tex_cube */
4485 "#version 120\n"
4486 "uniform samplerCube sampler;\n"
4487 "void main(void)\n"
4488 "{\n"
4489 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4490 "}\n",
4491 /* tex_rect */
4492 "#version 120\n"
4493 "#extension GL_ARB_texture_rectangle : enable\n"
4494 "uniform sampler2DRect sampler;\n"
4495 "void main(void)\n"
4496 "{\n"
4497 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4498 "}\n",
4501 if (!blt_pshaders[tex_type])
4503 FIXME("tex_type %#x not supported\n", tex_type);
4504 tex_type = tex_2d;
4507 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4508 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4509 GL_EXTCALL(glCompileShaderARB(vshader_id));
4511 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4512 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4513 GL_EXTCALL(glCompileShaderARB(pshader_id));
4515 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4516 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4517 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4518 GL_EXTCALL(glLinkProgramARB(program_id));
4520 shader_glsl_validate_link(gl_info, program_id);
4522 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4523 * is destroyed
4525 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4526 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4527 return program_id;
4530 /* GL locking is done by the caller */
4531 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4533 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
4534 const struct wined3d_gl_info *gl_info = context->gl_info;
4535 struct shader_glsl_priv *priv = device->shader_priv;
4536 GLhandleARB program_id = 0;
4537 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4539 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4541 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4542 else priv->glsl_program = NULL;
4544 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4546 if (old_vertex_color_clamp != current_vertex_color_clamp)
4548 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4550 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4551 checkGLcall("glClampColorARB");
4553 else
4555 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4559 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4560 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4561 GL_EXTCALL(glUseProgramObjectARB(program_id));
4562 checkGLcall("glUseProgramObjectARB");
4564 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4565 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4566 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4567 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4569 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4573 /* GL locking is done by the caller */
4574 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4575 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4576 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4577 struct shader_glsl_priv *priv = This->shader_priv;
4578 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4580 if (!*blt_program) {
4581 GLint loc;
4582 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4583 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4584 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4585 GL_EXTCALL(glUniform1iARB(loc, 0));
4586 } else {
4587 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4591 /* GL locking is done by the caller */
4592 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4593 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4594 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4595 struct shader_glsl_priv *priv = This->shader_priv;
4596 GLhandleARB program_id;
4598 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4599 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4601 GL_EXTCALL(glUseProgramObjectARB(program_id));
4602 checkGLcall("glUseProgramObjectARB");
4605 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4606 const struct list *linked_programs;
4607 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4608 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4609 struct shader_glsl_priv *priv = device->shader_priv;
4610 const struct wined3d_gl_info *gl_info;
4611 struct wined3d_context *context;
4613 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4614 * can be called from IWineD3DBaseShader::Release
4616 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4618 if(pshader) {
4619 struct glsl_pshader_private *shader_data;
4620 shader_data = This->baseShader.backend_data;
4621 if(!shader_data || shader_data->num_gl_shaders == 0)
4623 HeapFree(GetProcessHeap(), 0, shader_data);
4624 This->baseShader.backend_data = NULL;
4625 return;
4628 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4629 gl_info = context->gl_info;
4631 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4633 ENTER_GL();
4634 shader_glsl_select(context, FALSE, FALSE);
4635 LEAVE_GL();
4637 } else {
4638 struct glsl_vshader_private *shader_data;
4639 shader_data = This->baseShader.backend_data;
4640 if(!shader_data || shader_data->num_gl_shaders == 0)
4642 HeapFree(GetProcessHeap(), 0, shader_data);
4643 This->baseShader.backend_data = NULL;
4644 return;
4647 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4648 gl_info = context->gl_info;
4650 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4652 ENTER_GL();
4653 shader_glsl_select(context, FALSE, FALSE);
4654 LEAVE_GL();
4658 linked_programs = &This->baseShader.linked_programs;
4660 TRACE("Deleting linked programs\n");
4661 if (linked_programs->next) {
4662 struct glsl_shader_prog_link *entry, *entry2;
4664 ENTER_GL();
4665 if(pshader) {
4666 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4667 delete_glsl_program_entry(priv, gl_info, entry);
4669 } else {
4670 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4671 delete_glsl_program_entry(priv, gl_info, entry);
4674 LEAVE_GL();
4677 if(pshader) {
4678 UINT i;
4679 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
4681 ENTER_GL();
4682 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4683 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4684 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4685 checkGLcall("glDeleteObjectARB");
4687 LEAVE_GL();
4688 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4690 else
4692 UINT i;
4693 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
4695 ENTER_GL();
4696 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4697 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4698 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4699 checkGLcall("glDeleteObjectARB");
4701 LEAVE_GL();
4702 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4705 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
4706 This->baseShader.backend_data = NULL;
4708 context_release(context);
4711 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4713 const glsl_program_key_t *k = key;
4714 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4715 const struct glsl_shader_prog_link, program_lookup_entry);
4716 int cmp;
4718 if (k->vshader > prog->vshader) return 1;
4719 else if (k->vshader < prog->vshader) return -1;
4721 if (k->pshader > prog->pshader) return 1;
4722 else if (k->pshader < prog->pshader) return -1;
4724 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4725 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4727 return 0;
4730 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4732 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4733 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4735 if (!mem)
4737 ERR("Failed to allocate memory\n");
4738 return FALSE;
4741 heap->entries = mem;
4742 heap->entries[1].version = 0;
4743 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4744 heap->size = 1;
4746 return TRUE;
4749 static void constant_heap_free(struct constant_heap *heap)
4751 HeapFree(GetProcessHeap(), 0, heap->entries);
4754 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4756 wined3d_rb_alloc,
4757 wined3d_rb_realloc,
4758 wined3d_rb_free,
4759 glsl_program_key_compare,
4762 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4763 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4764 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4765 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4766 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4767 gl_info->limits.glsl_ps_float_constants)) + 1;
4769 if (!shader_buffer_init(&priv->shader_buffer))
4771 ERR("Failed to initialize shader buffer.\n");
4772 goto fail;
4775 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4776 if (!priv->stack)
4778 ERR("Failed to allocate memory.\n");
4779 goto fail;
4782 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4784 ERR("Failed to initialize vertex shader constant heap\n");
4785 goto fail;
4788 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4790 ERR("Failed to initialize pixel shader constant heap\n");
4791 goto fail;
4794 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4796 ERR("Failed to initialize rbtree.\n");
4797 goto fail;
4800 priv->next_constant_version = 1;
4802 This->shader_priv = priv;
4803 return WINED3D_OK;
4805 fail:
4806 constant_heap_free(&priv->pconst_heap);
4807 constant_heap_free(&priv->vconst_heap);
4808 HeapFree(GetProcessHeap(), 0, priv->stack);
4809 shader_buffer_free(&priv->shader_buffer);
4810 HeapFree(GetProcessHeap(), 0, priv);
4811 return E_OUTOFMEMORY;
4814 /* Context activation is done by the caller. */
4815 static void shader_glsl_free(IWineD3DDevice *iface) {
4816 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4817 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4818 struct shader_glsl_priv *priv = This->shader_priv;
4819 int i;
4821 ENTER_GL();
4822 for (i = 0; i < tex_type_count; ++i)
4824 if (priv->depth_blt_program[i])
4826 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4829 LEAVE_GL();
4831 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4832 constant_heap_free(&priv->pconst_heap);
4833 constant_heap_free(&priv->vconst_heap);
4834 HeapFree(GetProcessHeap(), 0, priv->stack);
4835 shader_buffer_free(&priv->shader_buffer);
4837 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4838 This->shader_priv = NULL;
4841 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4842 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4843 return FALSE;
4846 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4848 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4849 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4850 * on the version of NV_vertex_program.
4851 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4852 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4853 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4854 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4856 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4857 || gl_info->limits.arb_ps_instructions <= 512)
4858 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4859 else
4860 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4861 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4862 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4864 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4865 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4866 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4867 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4868 * in max native instructions. Intel and others also offer the info in this extension but they
4869 * don't support GLSL (at least on Windows).
4871 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4872 * of instructions is 512 or less we have to do with ps2.0 hardware.
4873 * NOTE: ps3.0 hardware requires 512 or more instructions but ati and nvidia offer 'enough' (1024 vs 4096) on their most basic ps3.0 hardware.
4875 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4876 || gl_info->limits.arb_ps_instructions <= 512)
4877 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4878 else
4879 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4881 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4883 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4884 * Direct3D minimum requirement.
4886 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4887 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4889 * The problem is that the refrast clamps temporary results in the shader to
4890 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4891 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4892 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4893 * offer a way to query this.
4895 pCaps->PixelShader1xMaxValue = 8.0;
4896 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4898 pCaps->VSClipping = TRUE;
4901 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4903 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4905 TRACE("Checking support for fixup:\n");
4906 dump_color_fixup_desc(fixup);
4909 /* We support everything except YUV conversions. */
4910 if (!is_yuv_fixup(fixup))
4912 TRACE("[OK]\n");
4913 return TRUE;
4916 TRACE("[FAILED]\n");
4917 return FALSE;
4920 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4922 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4923 /* WINED3DSIH_ADD */ shader_glsl_arith,
4924 /* WINED3DSIH_BEM */ shader_glsl_bem,
4925 /* WINED3DSIH_BREAK */ shader_glsl_break,
4926 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4927 /* WINED3DSIH_BREAKP */ NULL,
4928 /* WINED3DSIH_CALL */ shader_glsl_call,
4929 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4930 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4931 /* WINED3DSIH_CND */ shader_glsl_cnd,
4932 /* WINED3DSIH_CRS */ shader_glsl_cross,
4933 /* WINED3DSIH_CUT */ NULL,
4934 /* WINED3DSIH_DCL */ NULL,
4935 /* WINED3DSIH_DEF */ NULL,
4936 /* WINED3DSIH_DEFB */ NULL,
4937 /* WINED3DSIH_DEFI */ NULL,
4938 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4939 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4940 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4941 /* WINED3DSIH_DST */ shader_glsl_dst,
4942 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4943 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4944 /* WINED3DSIH_ELSE */ shader_glsl_else,
4945 /* WINED3DSIH_EMIT */ NULL,
4946 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4947 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4948 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4949 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4950 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4951 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4952 /* WINED3DSIH_IADD */ NULL,
4953 /* WINED3DSIH_IF */ shader_glsl_if,
4954 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4955 /* WINED3DSIH_IGE */ NULL,
4956 /* WINED3DSIH_LABEL */ shader_glsl_label,
4957 /* WINED3DSIH_LIT */ shader_glsl_lit,
4958 /* WINED3DSIH_LOG */ shader_glsl_log,
4959 /* WINED3DSIH_LOGP */ shader_glsl_log,
4960 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4961 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4962 /* WINED3DSIH_LT */ NULL,
4963 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4964 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4965 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4966 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4967 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4968 /* WINED3DSIH_MAD */ shader_glsl_mad,
4969 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4970 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4971 /* WINED3DSIH_MOV */ shader_glsl_mov,
4972 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4973 /* WINED3DSIH_MUL */ shader_glsl_arith,
4974 /* WINED3DSIH_NOP */ NULL,
4975 /* WINED3DSIH_NRM */ shader_glsl_nrm,
4976 /* WINED3DSIH_PHASE */ NULL,
4977 /* WINED3DSIH_POW */ shader_glsl_pow,
4978 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4979 /* WINED3DSIH_REP */ shader_glsl_rep,
4980 /* WINED3DSIH_RET */ shader_glsl_ret,
4981 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4982 /* WINED3DSIH_SETP */ NULL,
4983 /* WINED3DSIH_SGE */ shader_glsl_compare,
4984 /* WINED3DSIH_SGN */ shader_glsl_sgn,
4985 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4986 /* WINED3DSIH_SLT */ shader_glsl_compare,
4987 /* WINED3DSIH_SUB */ shader_glsl_arith,
4988 /* WINED3DSIH_TEX */ shader_glsl_tex,
4989 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
4990 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
4991 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
4992 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
4993 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
4994 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
4995 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
4996 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4997 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4998 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
4999 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5000 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5001 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5002 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5003 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5004 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5005 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5006 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5007 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5008 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5009 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5012 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5013 SHADER_HANDLER hw_fct;
5015 /* Select handler */
5016 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5018 /* Unhandled opcode */
5019 if (!hw_fct)
5021 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5022 return;
5024 hw_fct(ins);
5026 shader_glsl_add_instruction_modifiers(ins);
5029 const shader_backend_t glsl_shader_backend = {
5030 shader_glsl_handle_instruction,
5031 shader_glsl_select,
5032 shader_glsl_select_depth_blt,
5033 shader_glsl_deselect_depth_blt,
5034 shader_glsl_update_float_vertex_constants,
5035 shader_glsl_update_float_pixel_constants,
5036 shader_glsl_load_constants,
5037 shader_glsl_load_np2fixup_constants,
5038 shader_glsl_destroy,
5039 shader_glsl_alloc,
5040 shader_glsl_free,
5041 shader_glsl_dirty_const,
5042 shader_glsl_get_caps,
5043 shader_glsl_color_fixup_supported,